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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
125986_8 | import java.util.ArrayList;
public class Cell {
/**
* The status of the Cell.
*/
private boolean alive;
/**
* Constructs a dead cell.
*/
public Cell() {
alive = false;
}
/**
* Constructs a cell with the specified status.
*
* @param status a boolean to specify if the Cell is initially alive
*/
public Cell(boolean status) {
alive = status;
}
/**
* Returns whether the cell is currently alive.
*
* @return whether the cell is currently alive
*/
public boolean getAlive() {
return alive;
}
/**
* Sets the current status of the cell to the specified status.
*
* @param status a boolean to specify if the Cell is alive or dead
*/
public void setAlive(boolean status) {
alive = status;
}
/**
* Updates the state of the Cell.
*
* If this Cell is alive and if there are 2 or 3 alive neighbors,
* this Cell stays alive. Otherwise, it dies.
*
* If this Cell is dead and there are 3 alive neighbors,
* this Cell comes back to life. Otherwise, it stays dead.
*
* @param neighbors An ArrayList of Cells
*/
public void updateState(ArrayList<Cell> neighbors) {
//boolean cellCondition = Cell.getAlive();
int aliveNeighbors = 0;
if (alive == false) {
for (int i=0; i< neighbors.size(); i++) {
if (neighbors.get(i).getAlive() == true) {
aliveNeighbors +=1;
}
}
if (aliveNeighbors == 3) {
alive = true;
}
}
else if (alive == true) {
for (int i=0; i< neighbors.size(); i++) {
if (neighbors.get(i).getAlive() == true) {
aliveNeighbors +=1;
}
}
if (aliveNeighbors == 3 || aliveNeighbors == 2) {
alive = true;
}
else {
alive = false;
}
}
}
/**
* This method is a part of our extension. It also updates the state of the Cell.
*
* If this Cell is alive and if there are 3 or 4 alive neighbors,
* this Cell stays alive. Otherwise, it dies.
*
* If this Cell is dead and there are 3 alive neighbors,
* this Cell comes back to life. Otherwise, it stays dead.
*
* @param neighbors An ArrayList of Cells
*/
public void modifiedUpdateState(ArrayList<Cell> neighbors) {
int aliveNeighbors = 0;
if (alive == false) {
for (int i=0; i< neighbors.size(); i++) {
if (neighbors.get(i).getAlive() == true) {
aliveNeighbors +=1;
}
}
if (aliveNeighbors == 3) {
alive = true;
}
}
else if (alive == true) {
for (int i=0; i< neighbors.size(); i++) {
if (neighbors.get(i).getAlive() == true) {
aliveNeighbors +=1;
}
}
if (aliveNeighbors == 3 || aliveNeighbors == 4) {
alive = true;
}
else {
alive = false;
}
}
}
/**
* Returns a String representation of this Cell.
*
* @return 1 if this Cell is alive, otherwise 0.
*/
public String toString() {
if (alive == true) {
return "" + 1;
}
else {
return "" + 0;
}
}
}
| saadiqnafis/Conway-s-game-of-Life | Cell.java | 832 | /**
* Returns a String representation of this Cell.
*
* @return 1 if this Cell is alive, otherwise 0.
*/ | block_comment | en | false | 822 | 32 | 832 | 31 | 1,022 | 36 | 832 | 31 | 1,119 | 37 | false | false | false | false | false | true |
126203_2 | /**
* MTClient.java
*
* This program implements a simple multithreaded chat client. It connects to the
* server (assumed to be localhost on port 7654) and starts two threads:
* one for listening for data sent from the server, and another that waits
* for the user to type something in that will be sent to the server.
* Anything sent to the server is broadcast to all clients.
*
* The MTClient uses a ClientListener whose code is in a separate file.
* The ClientListener runs in a separate thread, recieves messages form the server,
* and displays them on the screen.
*
* Data received is sent to the output screen, so it is possible that as
* a user is typing in information a message from the server will be
* inserted.
*
*/
import java.net.Socket;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Scanner;
public class MTClient
{
public static void main(String[] args)
{
try
{
String hostname = "localhost";
int port = 7654;
System.out.println("Connecting to server on port " + port);
Socket connectionSock = new Socket(hostname, port);
DataOutputStream serverOutput = new DataOutputStream(connectionSock.getOutputStream());
System.out.println("Connection made.");
// Start a thread to listen and display data sent by the server
ClientListener listener = new ClientListener(connectionSock);
Thread theThread = new Thread(listener);
theThread.start();
//Prompt for the user's nme and send it to the server
Scanner keyboard = new Scanner(System.in);
String name = keyboard.nextLine();
serverOutput.writeBytes(name + "\n");
// Read input from the keyboard and send it to everyone else.
// The only way to quit is to hit control-c, but a quit command
// could easily be added
while (true)
{
String data = keyboard.nextLine();
serverOutput.writeBytes(data + "\n");
}
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
} // MTClient
| michaelfahy/game | MTClient.java | 549 | //Prompt for the user's nme and send it to the server | line_comment | en | false | 472 | 14 | 549 | 14 | 543 | 15 | 549 | 14 | 634 | 16 | false | false | false | false | false | true |
126477_4 | /*************************************************************************
* Compilation: javac Graph.java
* Dependencies: ST.java SET.java In.java
*
* Undirected graph data type implemented using a symbol table
* whose keys are vertices (String) and whose values are sets
* of neighbors (SET of Strings).
*
* Remarks
* -------
* - Parallel edges are not allowed
* - Self-loop are allowed
* - Adjacency lists store many different copies of the same
* String. You can use less memory by interning the strings.
*
*************************************************************************/
/**
* The <tt>Graph</tt> class represents an undirected graph of vertices
* with string names.
* It supports the following operations: add an edge, add a vertex,
* get all of the vertices, iterate over all of the neighbors adjacent
* to a vertex, is there a vertex, is there an edge between two vertices.
* Self-loops are permitted; parallel edges are discarded.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/45graph">Section 4.5</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public class Graph {
// symbol table: key = string vertex, value = set of neighboring vertices
private ST<String, SET<String>> st;
// number of edges
private int E;
/**
* Create an empty graph with no vertices or edges.
*/
public Graph() {
st = new ST<String, SET<String>>();
}
/**
* Create an graph from given input stream using given delimiter.
*/
public Graph(In in, String delimiter) {
st = new ST<String, SET<String>>();
while (in.hasNextLine()) {
String line = in.readLine();
String[] names = line.split(delimiter);
for (int i = 1; i < names.length; i++) {
addEdge(names[0], names[i]);
}
}
}
/**
* Number of vertices.
*/
public int V() {
return st.size();
}
/**
* Number of edges.
*/
public int E() {
return E;
}
/**
* Degree of this vertex.
*/
public int degree(String v) {
if (!st.contains(v)) throw new RuntimeException(v + " is not a vertex");
else return st.get(v).size();
}
/**
* Add edge v-w to this graph (if it is not already an edge)
*/
public void addEdge(String v, String w) {
if (!hasEdge(v, w)) E++;
if (!hasVertex(v)) addVertex(v);
if (!hasVertex(w)) addVertex(w);
st.get(v).add(w);
st.get(w).add(v);
}
/**
* Add vertex v to this graph (if it is not already a vertex)
*/
public void addVertex(String v) {
if (!hasVertex(v)) st.put(v, new SET<String>());
}
/**
* Return the set of vertices as an Iterable.
*/
public Iterable<String> vertices() {
return st;
}
/**
* Return the set of neighbors of vertex v as in Iterable.
*/
public Iterable<String> adjacentTo(String v) {
// return empty set if vertex isn't in graph
if (!hasVertex(v)) return new SET<String>();
else return st.get(v);
}
/**
* Is v a vertex in this graph?
*/
public boolean hasVertex(String v) {
return st.contains(v);
}
/**
* Is v-w an edge in this graph?
*/
public boolean hasEdge(String v, String w) {
if (!hasVertex(v)) return false;
return st.get(v).contains(w);
}
/**
* Return a string representation of the graph.
*/
public String toString() {
String s = "";
for (String v : st) {
s += v + ": ";
for (String w : st.get(v)) {
s += w + " ";
}
s += "\n";
}
return s;
}
public static void main(String[] args) {
Graph G = new Graph();
G.addEdge("A", "B");
G.addEdge("A", "C");
G.addEdge("C", "D");
G.addEdge("D", "E");
G.addEdge("D", "G");
G.addEdge("E", "G");
G.addVertex("H");
// print out graph
StdOut.println(G);
// print out graph again by iterating over vertices and edges
for (String v : G.vertices()) {
StdOut.print(v + ": ");
for (String w : G.adjacentTo(v)) {
StdOut.print(w + " ");
}
StdOut.println();
}
}
}
| rayning0/Princeton-Algorithms-Java | introcs/Graph.java | 1,185 | /**
* Create an empty graph with no vertices or edges.
*/ | block_comment | en | false | 1,071 | 15 | 1,185 | 15 | 1,288 | 17 | 1,185 | 15 | 1,364 | 17 | false | false | false | false | false | true |
126544_5 | import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* @author Arezoo Vejdanparast <vejdanpa@aston.ac.uk> & Ali Karami <ali.karami@alumni.york.ac.uk>
*/
public class Optimal {
private ArrayList<Camera> cameras;
private ArrayList<Object> objects;
private Double[] zooms;
private int steps;
private Double threshold;
private String outputPath;
private int[] step0CamConfig;
private int tempMinK; //for internal use with recursive function
private int[] tempCamConfig; //for internal use with recursive function
/**
* Constructor
* @param settings An instance of Settings class that contains all scenario settings.
* @param steps Number of time steps the simulation will run for.
* @param threshold The selected confidence threshold to determine whether an object
* is detectable or not.
* @param outputPath The path to output folder.
*/
public Optimal(Settings settings, int steps, Double threshold, String outputPath) {
System.out.println("Running Optimal algorithm ....\n");
this.cameras = settings.cameras;
this.objects = settings.objects;
this.zooms = this.cameras.get(0).zooms;
this.steps = steps;
this.threshold = threshold;
this.outputPath = outputPath;
this.step0CamConfig = new int[cameras.size()];
Arrays.fill(step0CamConfig, 0);
run();
}
/**
* Runs the optimal algorithm simulation
*/
private void run() {
int[] minKCover = new int[steps];
for (int step=0 ; step<steps ; step++) {
tempMinK = 0;
tempCamConfig = new int[cameras.size()];
System.out.print("step "+step+" .... ");
computeMinKCover(cameras.size(), new int[cameras.size()], step);
minKCover[step] = tempMinK;
if (step==0)
step0CamConfig = tempCamConfig.clone();
updateObjects();
System.out.println("COMPLETE");
}
long tableCount = (long)Math.pow(zooms.length, cameras.size());
System.out.println("Table Count = "+tableCount+"\n");
exportResult(minKCover);
}
/**
* Computes the minimum k-covers for a given step by finding the table with maximum min k and
* saves the value in a global variable (tempMinK) to be used in run().
* @param size The number of cameras in each (recursive) run.
* @param zoomList An (initially empty) auxiliary list for keeping the configuration indexes.
* @param step The current time step.
*/
private void computeMinKCover(int size, int[] zoomList, int step) {
if (size==0) {
int tableResult = getMinK(zoomList);
if (tableResult > tempMinK) {
tempMinK = tableResult;
tempCamConfig = zoomList.clone();
}
// System.out.print("Step "+step+": [");
// for (int i=0 ; i<zoomList.length ; i++) {
// System.out.print(zoomList[i]);
// if (i<zoomList.length-1)
// System.out.print(",");
// }
// System.out.println("] ::: "+tableResult);
}
else {
for (int z=0 ; z<zooms.length ; z++) {
zoomList[size-1] = z;
computeMinKCover(size-1, zoomList, step);
}
}
}
/**
* Returns the minimum number of cameras that detect each object.
* @param zoomList List of selected cameras' zoom indexes.
* @return the k value of k-cover with a specific (given) camera configuration.
*/
private int getMinK(int[] zoomList) {
int[] objCover = new int[objects.size()];
for (int n=0 ; n<cameras.size() ; n++) {
int z = zoomList[n];
for (int m=0 ; m<objects.size() ; m++) {
if (isDetectable(m, n, z))
objCover[m]++;
}
}
return minimum(objCover);
}
/**
* Checked whether an object is detectable by a camera with a specified zoom (FOV).
* @param m The index of the object in the list of objects
* @param n The index of the camera in the list of cameras
* @param z The index of the zoom level in the list of zoom values
* @return True if the object is within FOV (zoom range) AND the camera can see it
* with a confidence above threshold. False otherwise.
*/
private boolean isDetectable(int m, int n, int z) {
Double distance = Math.sqrt(Math.pow((cameras.get(n).x-objects.get(m).x), 2) + Math.pow((cameras.get(n).y-objects.get(m).y), 2));
if (distance > cameras.get(n).zooms[z])
return false;
else {
double b = 15;
Double conf = 0.95 * (b / (cameras.get(n).zooms[z] * distance)) - 0.15;
return (conf >= threshold);
}
}
/**
* Returns the minimum value of a list of integers < 10000.
* @param list The list of integer
* @return The minimum integer value in the list
*/
private static int minimum(int[] list) {
int min = 10000;
for (int i : list){
if (i < min)
min = i;
}
return min;
}
/**
* Updates all objects one time step.
*/
private void updateObjects() {
for (Object obj : objects)
obj.update();
}
/**
* Writes the result to '*-egreedy.csv' file.
* @param minKCover The array of minimum k-cover values
*/
private void exportResult(int[] minKCover) {
FileWriter outFile;
try {
outFile = new FileWriter(outputPath+"-optimal.csv");
PrintWriter out = new PrintWriter(outFile);
out.println("optimal");
for (int k : minKCover)
out.println(k);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Gives read access to the camera configurations that is selected in step 0 of the runtime
* @return A list camera configurations that is optimised for step 0
*/
public int[] getStep0CamConfig() {
return step0CamConfig;
}
}
| alijy/CamSimLite | src/Optimal.java | 1,716 | /**
* Computes the minimum k-covers for a given step by finding the table with maximum min k and
* saves the value in a global variable (tempMinK) to be used in run().
* @param size The number of cameras in each (recursive) run.
* @param zoomList An (initially empty) auxiliary list for keeping the configuration indexes.
* @param step The current time step.
*/ | block_comment | en | false | 1,512 | 91 | 1,716 | 90 | 1,771 | 97 | 1,716 | 90 | 2,014 | 101 | false | false | false | false | false | true |
126580_3 | /*
Summary:
The Simulator class extends the JComponent class and is responsible for rendering the simulation of a network of cameras.
It contains an ArrayList of Camera objects and various properties related to rendering, such as line styles and colors.
The class provides the following methods:
1. setSender(Camera src, int destx, int desty): Sets the source camera and destination coordinates for rendering.
2. Simulator(): Constructor for the Simulator class, which sets the background color.
3. getList(): Returns the list of cameras in the simulator.
4. removeAll(): Removes all cameras from the simulator and repaints the component.
5. paintComponent(Graphics g1): Overrides the paintComponent method to render the simulator. It draws rectangles representing different cloud levels and renders the cameras based on the option value. If the option is 1, it also draws a dashed line from the source camera to the destination coordinates.
The purpose of this class is to provide a visual representation of the camera network simulation, allowing for rendering of cameras and their connections based on the specified options.
*/
package com;
import java.awt.Dimension;
import javax.swing.JComponent;
import java.awt.geom.Rectangle2D;
import java.awt.BasicStroke;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.util.ArrayList;
import java.awt.Color;
public class Simulator extends JComponent {
public int option = 0; // Variable to control the rendering option
public ArrayList<Camera> cameras = new ArrayList<Camera>(); // List of cameras to be simulated
float dash1[] = {10.0f}; // Dash pattern for dashed line
BasicStroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f); // Dashed line style
BasicStroke rect = new BasicStroke(1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1f, new float[]{2f}, 0f); // Rectangle line style
Dimension dim; // Dimension of the component
Camera src; // Source camera for rendering
int destx, desty; // Destination coordinates for rendering
/**
* Sets the source camera and destination coordinates for rendering.
*
* @param src the source camera
* @param destx the x-coordinate of the destination
* @param desty the y-coordinate of the destination
*/
public void setSender(Camera src, int destx, int desty) {
this.src = src;
this.destx = destx;
this.desty = desty;
}
/**
* Constructor for the Simulator class.
*/
public Simulator() {
super.setBackground(new Color(255, 0, 255));
this.setBackground(new Color(255, 0, 255));
}
/**
* Returns the list of cameras in the simulator.
*
* @return the list of cameras
*/
public ArrayList<Camera> getList() {
return cameras;
}
/**
* Removes all cameras from the simulator and repaints the component.
*/
public void removeAll() {
option = 0;
cameras.clear();
repaint();
}
/**
* Overrides the paintComponent method to render the simulator.
*
* @param g1 the Graphics object to render on
*/
public void paintComponent(Graphics g1) {
super.paintComponent(g1);
GradientPaint gradient = new GradientPaint(0, 0, Color.green, 175, 175, Color.yellow, true); // Gradient paint for background
Graphics2D g = (Graphics2D) g1;
g.setPaint(gradient);
g.setStroke(rect); // Set the stroke for drawing rectangles
// Draw and label the rectangles representing different cloud levels
Rectangle2D rectangle = new Rectangle2D.Double(10, 30, 200, 40);
g.setStroke(rect);
g.draw(rectangle);
g.drawString("High Cloud", 60, 60);
rectangle = new Rectangle2D.Double(310, 30, 200, 40);
g.setStroke(rect);
g.draw(rectangle);
g.drawString("Medium Cloud", 380, 60);
rectangle = new Rectangle2D.Double(610, 30, 200, 40);
g.setStroke(rect);
g.draw(rectangle);
g.drawString("Low Cloud", 670, 60);
if (option == 0) {
// Render the cameras when option is 0
for (int i = 0; i < cameras.size(); i++) {
Camera c = cameras.get(i);
c.draw(g, "fill"); // Draw the camera shape
g.drawString(c.getCamera(), c.x + 10, c.y + 50); // Draw the camera label
}
}
if (option == 1) {
// Render the cameras and a dashed line from the source camera to the destination when option is 1
for (int i = 0; i < cameras.size(); i++) {
Camera c = cameras.get(i);
c.draw(g, "fill"); // Draw the camera shape
g.drawString(c.getCamera(), c.x + 10, c.y + 50); // Draw the camera label
}
g.setStroke(dashed); // Set the stroke for drawing dashed line
g.drawLine(src.x + 10, src.y + 10, destx + 20, desty); // Draw the dashed line
}
}
} | HarshaLakkaraju/Adaptive_Resource_Management_with_google_drive_support-public- | Simulator.java | 1,335 | // Dash pattern for dashed line | line_comment | en | false | 1,225 | 6 | 1,335 | 7 | 1,391 | 6 | 1,335 | 7 | 1,516 | 7 | false | false | false | false | false | true |
126848_2 | import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main {
private JFrame frame;
private JTextField txtPhoneOperatingSystem;
private JTextField txtBatteryLife;
private JTextField txtCarrier;
private JTextField txtPersonToCall;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnCreatePhone = new JButton("Create Phone");
btnCreatePhone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double battery = Double.parseDouble(txtBatteryLife.getText());
Phone newPhone = new Phone(battery, txtPhoneOperatingSystem.getText(), txtCarrier.getText(), txtPersonToCall.getText());
newPhone.draw();
}
});
btnCreatePhone.setBounds(245, 473, 117, 29);
frame.getContentPane().add(btnCreatePhone);
txtPhoneOperatingSystem = new JTextField();
txtPhoneOperatingSystem.setText("Phone Operating System");
txtPhoneOperatingSystem.setBounds(53, 37, 192, 26);
frame.getContentPane().add(txtPhoneOperatingSystem);
txtPhoneOperatingSystem.setColumns(10);
txtBatteryLife = new JTextField();
txtBatteryLife.setText("100");
txtBatteryLife.setBounds(53, 75, 192, 26);
frame.getContentPane().add(txtBatteryLife);
txtBatteryLife.setColumns(10);
txtCarrier = new JTextField();
txtCarrier.setText("Carrier");
txtCarrier.setBounds(53, 113, 192, 26);
frame.getContentPane().add(txtCarrier);
txtCarrier.setColumns(10);
txtPersonToCall = new JTextField();
txtPersonToCall.setText("Person to Call");
txtPersonToCall.setBounds(53, 169, 192, 26);
frame.getContentPane().add(txtPersonToCall);
txtPersonToCall.setColumns(10);
}
}
| SanDiegoCode/phonecreator | src/Main.java | 719 | /**
* Initialize the contents of the frame.
*/ | block_comment | en | false | 576 | 12 | 719 | 12 | 717 | 14 | 719 | 12 | 891 | 14 | false | false | false | false | false | true |
126902_1 | import play.Application;
import play.GlobalSettings;
import play.Logger;
/**
* Implements a Global object for the Play Framework.
* @author eduardgamiao
*
*/
public class Global extends GlobalSettings {
/**
* Initialization method for this Play Framework web application.
* @param app A Play Framework application.
*/
public void onStart(Application app) {
Logger.info("TextBookMania has started");
}
}
| eduardgamiao/textbookmania | app/Global.java | 104 | /**
* Initialization method for this Play Framework web application.
* @param app A Play Framework application.
*/ | block_comment | en | false | 89 | 24 | 104 | 24 | 111 | 27 | 104 | 24 | 119 | 28 | false | false | false | false | false | true |
127127_0 | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Medicine {
private String name;
private String manufacturer;
private double price;
private int quantity;
public Medicine(String name, String manufacturer, double price, int quantity) {
this.name = name;
this.manufacturer = manufacturer;
this.price = price;
this.quantity = quantity;
}
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return "Medicine{" +
"name='" + name + '\'' +
", manufacturer='" + manufacturer + '\'' +
", price=" + price +
", quantity=" + quantity +
'}';
}
}
public class MedicineManager {
private List<Medicine> medicines;
public MedicineManager() {
medicines = new ArrayList<>();
}
public void addMedicine(Medicine medicine) {
medicines.add(medicine);
System.out.println("Medicine added successfully.");
}
public void viewMedicines() {
if (medicines.isEmpty()) {
System.out.println("No medicines available.");
} else {
for (Medicine medicine : medicines) {
System.out.println(medicine);
}
}
}
public Medicine searchMedicine(String name) {
for (Medicine medicine : medicines) {
if (medicine.getName().equalsIgnoreCase(name)) {
return medicine;
}
}
return null;
}
public void removeMedicine(String name) {
Medicine medicine = searchMedicine(name);
if (medicine != null) {
medicines.remove(medicine);
System.out.println("Medicine removed successfully.");
} else {
System.out.println("Medicine not found.");
}
}
public static void main(String[] args) {
MedicineManager manager = new MedicineManager();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\nMedicine Management System");
System.out.println("1. Add Medicine");
System.out.println("2. View Medicines");
System.out.println("3. Search Medicine");
System.out.println("4. Remove Medicine");
System.out.println("5. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (choice) {
case 1:
System.out.print("Enter name: ");
String name = scanner.nextLine();
System.out.print("Enter manufacturer: ");
String manufacturer = scanner.nextLine();
System.out.print("Enter price: ");
double price = scanner.nextDouble();
System.out.print("Enter quantity: ");
int quantity = scanner.nextInt();
scanner.nextLine(); // Consume newline
Medicine medicine = new Medicine(name, manufacturer, price, quantity);
manager.addMedicine(medicine);
break;
case 2:
manager.viewMedicines();
break;
case 3:
System.out.print("Enter name to search: ");
String searchName = scanner.nextLine();
Medicine foundMedicine = manager.searchMedicine(searchName);
if (foundMedicine != null) {
System.out.println("Medicine found: " + foundMedicine);
} else {
System.out.println("Medicine not found.");
}
break;
case 4:
System.out.print("Enter name to remove: ");
String removeName = scanner.nextLine();
manager.removeMedicine(removeName);
break;
case 5:
System.out.println("Exiting...");
scanner.close();
System.exit(0);
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
| Bilalasghar1111/Java | MedicineProject.java | 1,015 | // Getters and setters | line_comment | en | false | 881 | 5 | 1,015 | 6 | 1,082 | 5 | 1,015 | 6 | 1,257 | 6 | false | false | false | false | false | true |
127574_0 | import org.chicago.cases.AbstractExchangeArbCase;
import org.chicago.cases.arb.Quote;
import com.optionscity.freeway.api.IDB;
import com.optionscity.freeway.api.IJobSetup;
import java.util.ArrayList;
public class MIT2ArbCase extends AbstractExchangeArbCase {
class MyArbImplementation implements ArbCase {
double reversionCoeff;
double spreadConst;
double biasThreshold;
int roundThreshold;
boolean tradeThisRound;
double w5, w4, w3, w2, w1;
int position = 0;
double balance = 0;
ArrayList<Double> snowBids = new ArrayList<Double>();
ArrayList<Double> snowAsks = new ArrayList<Double>();
ArrayList<Double> robotBids = new ArrayList<Double>();
ArrayList<Double> robotAsks = new ArrayList<Double>();
ArrayList<Double> truePrice = new ArrayList<Double>();
ArrayList<Double> snow = new ArrayList<Double>();
ArrayList<Double> robot = new ArrayList<Double>();
public void addVariables(IJobSetup setup) {
// Registers a variable with the system.
setup.addVariable("reversionCoeff", "Coefficient for the (true - exch) term", "double", "0");
setup.addVariable("spreadConst", "Term added or subtracted from the bids", "double", "0");
setup.addVariable("biasThreshold", "Threshold for keeping position in check", "int", "150");
setup.addVariable("roundThreshold", "Threshold for starting to liquidate assets", "int", "950");
setup.addVariable("tradeThisRound", "Whether we trade this round", "boolean", "true");
setup.addVariable("w5", "Factor * {t-3}", "double", "0");
setup.addVariable("w4", "Factor * {t-3}", "double", "0");
setup.addVariable("w3", "Factor * {t-3}", "double", ".1");
setup.addVariable("w2", "Factor * {t-2}", "double", ".3");
setup.addVariable("w1", "Factor * {t-1}", "double", ".6");
}
public void initializeAlgo(IDB database) {
reversionCoeff = getDoubleVar("reversionCoeff");
spreadConst = getDoubleVar("spreadConst");
biasThreshold = getIntVar("biasThreshold");
roundThreshold = getIntVar("roundThreshold");
tradeThisRound = getBooleanVar("tradeThisRound");
w5 = getDoubleVar("w5");
w4 = getDoubleVar("w4");
w3 = getDoubleVar("w3");
w2 = getDoubleVar("w2");
w1 = getDoubleVar("w1");
}
@Override
public void fillNotice(Exchange exchange, double price, AlgoSide algoside) {
log("My quote was filled with at a price of " + price + " on " + exchange + " as a " + algoside);
if(algoside == AlgoSide.ALGOBUY){
position += 1;
balance -= price;
}else{
position -= 1;
balance += price;
}
}
@Override
public void positionPenalty(int clearedQuantity, double price) {
log("I received a position penalty with " + clearedQuantity + " positions cleared at " + price);
position -= clearedQuantity;
balance += clearedQuantity * price;
}
@Override
public void newTopOfBook(Quote[] quotes) {
log("my balance is " + balance + "; my position is " + position);
for (Quote quote : quotes) {
log("I received a new bid of " + quote.bidPrice + ", and ask of " + quote.askPrice + " from " + quote.exchange);
}
robotBids.add(quotes[0].bidPrice);
robotAsks.add(quotes[0].askPrice);
snowBids.add(quotes[1].bidPrice);
snowAsks.add(quotes[1].askPrice);
truePrice.add((quotes[0].bidPrice + quotes[0].askPrice + quotes[1].bidPrice + quotes[1].askPrice) / 4);
robot.add((quotes[0].bidPrice + quotes[0].askPrice) / 2 );
snow.add((quotes[1].bidPrice + quotes[1].askPrice) / 2);
}
@Override
public Quote[] refreshQuotes() {
double robotBid, robotAsk, snowBid, snowAsk;
double bias;
if (tradeThisRound){
if (Math.abs(position) > biasThreshold){
bias = -position / 25.0;
} else if (truePrice.size() + Math.abs(position) > roundThreshold){
bias = -position / 25.0;
} else {
bias = 0;
}
if (truePrice.size() <= 5){
robotBid = 99.;
robotAsk = 101.;
snowBid = 99.;
snowAsk = 101.;
}
else {
robotBid = estimate(robotBids);
robotAsk = estimate(robotAsks);
snowBid = estimate(snowBids);
snowAsk = estimate(snowAsks);
robotBid += reversionCoeff * (estimate(truePrice) - estimate(robot)) + spreadConst + bias;
robotAsk += reversionCoeff * (estimate(truePrice) - estimate(robot)) + spreadConst + bias;
snowBid += reversionCoeff * (estimate(truePrice) - estimate(snow)) + spreadConst + bias;
snowAsk += reversionCoeff * (estimate(truePrice) - estimate(snow)) - spreadConst + bias;
}
} else {
snowBid = 0.;
snowAsk = 200.;
robotBid = 0.;
robotAsk = 200.;
}
Quote[] quotes = new Quote[2];
quotes[0] = new Quote(Exchange.ROBOT, robotBid, robotAsk);
quotes[1] = new Quote(Exchange.SNOW, snowBid, snowAsk);
return quotes;
}
private double estimate(ArrayList<Double> data){
double result = 0;
int length = data.size();
result += w1 * data.get(length - 1);
result += w2 * data.get(length - 2);
result += w3 * data.get(length - 3);
result += w4 * data.get(length - 4);
result += w5 * data.get(length - 5);
return result;
}
}
@Override
public ArbCase getArbCaseImplementation() {
return new MyArbImplementation();
}
}
| rnyang/MidwestTradingCompetition | cases/MIT2ArbCase.java | 1,677 | // Registers a variable with the system. | line_comment | en | false | 1,518 | 8 | 1,677 | 8 | 1,671 | 8 | 1,677 | 8 | 2,145 | 9 | false | false | false | false | false | true |
127734_2 | public class GlassLine implements Runnable{
Component glass;
public GlassLine(Component component){
this.glass = component;
}
@Override
public void run() {
while(true){
//acquire the lock
glass.productLock.lock();
try{
// enough produced
while(glass.currenCount == glass.requiredAmount){
glass.produceCondition.await();
}
// not started yet
if(glass.currenCount == 0){
Actions.startGlassProductionLine();
}
Actions.produceGlass();
glass.currenCount++;
//now if its enough wake assembly if no wake other produce threads
if(glass.currenCount == glass.requiredAmount){
glass.enoughCondition.signalAll();
Actions.stopGlassProductionLine();
}else{
glass.produceCondition.signalAll();
}
}catch (InterruptedException ex){
ex.printStackTrace();
}finally {
//release the lock
glass.productLock.unlock();
}
}
}
}
| CemMeric26/oop-thread | GlassLine.java | 241 | // not started yet | line_comment | en | false | 217 | 4 | 241 | 4 | 263 | 4 | 241 | 4 | 295 | 4 | false | false | false | false | false | true |
127742_5 |
/**
* Glass Falling
*/
public class GlassFalling {
// Do not change the parameters!
/**
*
* @param floors
* @param sheets
* @return int
*/
public int glassFallingRecur(int floors, int sheets) {
// Fill in here and change the return
/**
* If floors have reached its limit, then return the floor Used as fail safe if
* sheet does not break
*/
if (floors == 1 || floors == 0)
return floors;
/**
* If sheets are broken, return the floor it is broken at s
*/
if (sheets == 1)
return floors;
/**
* Variable used to compare against the result returned from recursion
*/
int minCheck = Integer.MAX_VALUE;
/**
* Store the result of the recurstion
*/
int result;
/**
* loop through each floor, recursively checking for the value if the sheet
* breaks and if the sheet does not break
*/
for (int x = 1; x <= floors; x++) {
// Increase by 1 because recursion will return the value 1 level below
// First option is if the sheet breaks, second parameter is if the sheet does not break, check the lower floors
result = 1 + Math.max(glassFallingRecur(x - 1, sheets - 1), glassFallingRecur(floors - x, sheets));
minCheck = Math.min(minCheck, result);
}
return minCheck;
}
// Optional:
// Pick whatever parameters you want to, just make sure to return an int.
/**
*
* @param floors
* @param sheets
* @param arr
* @return int
*/
public int glassFallingMemoized(int floors, int sheets, int[][] arr) {
// Fill in here and change the return
/**
* Store results of each recursion
*/
int result;
// Set the default for the first and zero floors
for (int i = 1; i <= floors; i++) {
arr[i][1] = 1;
arr[i][0] = 0;
}
// Set the floor value for first sheet to each floor
for (int j = 1; j <= floors; j++)
arr[1][j] = j;
/**
* Fill remaining substructures using
* 2 foro loops
*/
for (int i = 2; i <= floors; i++) {
for (int j = 2; j <= sheets; j++) {
arr[i][j] = Integer.MAX_VALUE;
for (int x = 1; x <= j; x++) {
// Check the value of the previous substructures and select the max
result = 1 + Math.max(arr[i - 1][x - 1], arr[i][j - x]);
// If the resulting arrays are less, set current
// iteration to result
if (result < arr[i][j])
arr[i][j] = result;
}
}
}
// eggFloor[n][k] holds the result
return arr[floors][sheets];
}
// Do not change the parameters!
public int glassFallingBottomUp(int floors, int sheets) {
/**
* If floors have reached its limit, then return the floor Used as fail safe if
* sheet does not break
*/
if (floors == 1 || floors == 0)
return floors;
/**
* If sheets are broken, return the floor it is broken at s
*/
if (sheets == 1)
return floors;
/**
* Variable used to compare against the result returned from recursion
*/
int minCheck = Integer.MAX_VALUE;
/**
* Store the result of the recurstion
*/
int result;
/**
* loop through each floor, recursively checking for the value if the sheet
* breaks and if the sheet does not break
*/
for (int x = floors; x >= 1; x--) {
try {
// Increase by 1 because recursion will return the value 1 level below
// First option is if the sheet breaks, second parameter is if the sheet does not break, check the lower floors
result = 1 + Math.max(glassFallingBottomUp(x - 1, sheets - 1), glassFallingBottomUp(floors - x, sheets));
minCheck = Math.min(minCheck, result);
} catch (Exception e) {
e.printStackTrace();
}
}
return minCheck;
}
public static void main(String args[]) {
GlassFalling gf = new GlassFalling();
// Do not touch the below lines of code, and make sure
// in your final turned-in copy, these are the only things printed
int minTrials1Recur = gf.glassFallingRecur(27, 2);
int minTrials1Bottom = gf.glassFallingBottomUp(27, 2);
int minTrials2Mem = gf.glassFallingMemoized(100, 3, new int[101][4]);
int minTrials2Bottom = gf.glassFallingBottomUp(100, 3);
System.out.println(minTrials1Recur + " " + minTrials1Bottom);
System.out.println(minTrials2Mem + " " + minTrials2Bottom);
}
} | dave325/algos-assignment-DP | GlassFalling.java | 1,246 | /**
* If sheets are broken, return the floor it is broken at s
*/ | block_comment | en | false | 1,218 | 19 | 1,246 | 18 | 1,398 | 21 | 1,246 | 18 | 1,511 | 22 | false | false | false | false | false | true |
128986_3 | public class Sedan extends MidSizeCars {
private boolean sportsCar;
private String trunkSize;
public Sedan(String make, String vinNumber, String model, double price,
int year, double mileage, boolean coupe, boolean convertible, int doorNum, boolean sportsCar, String trunkSize) {
super(make, vinNumber, model, price, year, mileage, coupe, convertible, doorNum);
this.trunkSize = trunkSize;
this.sportsCar = sportsCar;
}
// Getter for sportsCar
public boolean isSportsCar() {
return sportsCar;
}
// Setter for sportsCar
public void setSportsCar(boolean sportsCar) {
this.sportsCar = sportsCar;
}
// Getter for trunkSize
public String getTrunkSize() {
return trunkSize;
}
// Setter for trunkSize
public void setTrunkSize(String trunkSize) {
this.trunkSize = trunkSize;
}
public String toString(){
return super.toString() + ", Sports Car: " + isSportsCar() +
", Trunk size: " + getTrunkSize();
}
}
| slabaniego/Java2Project | Sedan.java | 277 | // Setter for trunkSize
| line_comment | en | false | 249 | 6 | 277 | 6 | 294 | 6 | 277 | 6 | 328 | 8 | false | false | false | false | false | true |
129072_0 | package com.lethalflame.bot;
import com.lethalflame.bot.Utlis.ClassUtlis;
import com.lethalflame.bot.Utlis.CommandExecutor;
import com.lethalflame.bot.listeners.messageListener;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.utils.Compression;
import net.dv8tion.jda.api.utils.cache.CacheFlag;
import org.jetbrains.annotations.NotNull;
import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.util.HashMap;
public class bot {
public static JDABuilder builder;
public static HashMap<String, CommandExecutor> COMMANDS = new HashMap<>();
public static HashMap<String, CommandExecutor> ALIASES = new HashMap<>();
public static String b_Prefix = "!";
public static void main(String[] args) throws LoginException, IOException {
String token = ""; // Please insert bot token here
builder = JDABuilder.createDefault(token);
builder.disableCache(CacheFlag.MEMBER_OVERRIDES, CacheFlag.VOICE_STATE);
builder.setBulkDeleteSplittingEnabled(false);
builder.setCompression(Compression.NONE);
builder.enableIntents(GatewayIntent.GUILD_MEMBERS);
builder.setActivity(Activity.watching("Bot made by: Flame"));
builder.addEventListeners(new messageListener());
builder.addEventListeners(new ListenerAdapter() {
@Override
public void onReady(@NotNull ReadyEvent event) {
System.out.println("Blacklist Bot Loaded.");
}
});
ClassUtlis.registerAllCommands();
for(CommandExecutor commandExecutor : COMMANDS.values()) {
if (commandExecutor.aliases() != null) {
for(String alias : commandExecutor.aliases()) {
ALIASES.put(alias.toLowerCase(), commandExecutor);
}
}
}
builder.build();
}
public static void executeCommand(String prefix, MessageReceivedEvent event) throws IOException {
String chatMessage = event.getMessage().getContentRaw();
String[] splitCommand = chatMessage.split(" ");
String command = splitCommand[0].replaceFirst("[" + prefix + "]", "");
String commandArgs = event.getMessage().getContentRaw().replace(prefix + command, "");
commandArgs = commandArgs.replaceFirst(" ", "");
String[] args = commandArgs.split(" ");
if (args.length == 1) {
if (args[0].isEmpty() || args[0].equals(" ") || args[0].equals(prefix + command) || args[0].equals(prefix)) {
args = new String[0];
}
}
if (COMMANDS.get(command.toLowerCase()) != null) {
if(!COMMANDS.get(command.toLowerCase()).exectue(args, event)) {
event.getChannel().sendMessage("This command is disabled").queue();
}
} else if (ALIASES.get(command.toLowerCase()) != null) {
if (!ALIASES.get(command.toLowerCase()).exectue(args, event)) {
event.getChannel().sendMessage("This command is disabled").queue();
}
}
}
} | JustinPrograms/BlacklistDiscordBot | bot.java | 854 | // Please insert bot token here
| line_comment | en | false | 711 | 7 | 854 | 7 | 903 | 7 | 854 | 7 | 1,018 | 7 | false | false | false | false | false | true |
130215_4 | /*
* GPS calculates the satellites coordinates with respect to its position above
* Earth
*
* Inclination of 20 degrees would mean that the satellite would never reach
* ISAE Therefore, the inclination is set to 43.5 degrees
*
* We have a 90 min period
*
* ISAE coordinates : long = 1.4742547702385902 / lat = 43.56569930662392
*
* Satellite is assumed to begin over ISAE where the ground station is also
* located. Coordinates rounded to one decimal point
*/
public class GPS {
private double longitude;
private double latitude;
public final static double INCLINATION = 43.5;
/*
* Default GPS constructor
*/
public GPS() {
this.longitude = 1.5;
this.latitude = 43.5;
}
/*
* @returns GPS longitude
*/
public double getLongitude() {
return this.longitude;
}
/*
* @returns GPS latitude
*/
public double getLatitude() {
return this.latitude;
}
/*
* Latitude is a cosine function with a period of 90 minutes
*/
public void setLatitude(double time) {
double num = (Math.round(10 * (INCLINATION * Math.cos(2 * Math.PI * time / 90))));
this.latitude = num / 10;
}
/*
* Longitude is a linear function with a period of 90 minutes
*/
public void setLongitude(double time) {
double num = (Math.round(10 * ((((180 + 1.5) + (time * 4)) % 360) - 180)));
this.longitude = num / 10;
}
}
| rokeane/OOP-Satellite | src/GPS.java | 433 | /*
* Latitude is a cosine function with a period of 90 minutes
*/ | block_comment | en | false | 409 | 19 | 433 | 20 | 459 | 20 | 433 | 20 | 502 | 22 | false | false | false | false | false | true |
130441_8 | import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class Variable {
// Fields:
// ArrayList from type of Variables that keeps the parents of this Variable.
private final ArrayList<Variable> parents;
// ArrayList from type of Variables that keeps the children of this Variable.
private final ArrayList<Variable> children;
// String of the Variable name.
private final String Var_name;
// Array from type of String that keeps all the outcomes of this Variable (T/F, v1/v2/v3...).
private final String[] outcomes;
// HashMap that the key is a String and the value is a double.
// CPT = Conditional Probability Table, this HashMap keeps all the probabilities
// of this Variables given his parents (if there are parents).
private final HashMap<String, Double> CPT;
// Boolean which used only in the BayesBall Algorithm,
// while running the BayesBall Algorithm @evidence is true only if this
// Variable is an evidence in the question.
private boolean evidence = false;
// Constructor.
public Variable(String var_name, String[] outcomes) {
Var_name = var_name;
parents = new ArrayList<>();
children = new ArrayList<>();
this.outcomes = outcomes;
CPT = new HashMap<>();
}
/**
*
* @return - String of the Variable name.
*/
public String getVar_name() {
return this.Var_name;
}
/**
*
* @return - ArrayList from type of Variables with all the parents of this Variable.
*/
public ArrayList<Variable> getParents() {
return this.parents;
}
/**
*
* @return - ArrayList from type of Variables with all the children of this Variable.
*/
public ArrayList<Variable> getChildren() {
return this.children;
}
/**
*
* @return - Array from type of String with all the outcomes of this Variable.
*/
public String[] getOutcomes() {
return this.outcomes;
}
/**
*
* @return - HashMap that the key is a String and the value is a double.
*/
public HashMap<String, Double> getCPT() {
return this.CPT;
}
/**
*
* @return - true if this Variable is an evidence(given) in the BayesBall question.
*/
public boolean isEvidence() {
return this.evidence;
}
/**
* This method resets this Variable field evidence to be false.
* used at the end of the question.
*/
public void resetEvidence() {
this.evidence = false;
}
/**
* In the BayesBall Algorithm if this Variable is given set @evidence to be true.
*/
public void setEvidence(){ this.evidence = true;}
/**
*
* @param parent - Variable of a parent of this Variable.
*/
public void add_parent(Variable parent){this.parents.add(parent);}
/**
*
* @param child - Variable of a child of this Variable.
*/
public void add_children(Variable child){this.children.add(child);}
/**
*
* @return - true if this Variable has parents, false otherwise.
*/
public boolean hasParent(){
return parents.size() > 0;
}
/**
*
* @return - String that keeps all this Variable data: Var_name, Outcomes, Parents, Children, CPT.
*/
@Override
public String toString(){
String result = "\nVar_name- " + this.Var_name + "\nOutcomes- ";
result += Arrays.toString(this.outcomes) + "\nParents- [";
for(Variable parent: this.parents){
result += parent.getVar_name() + ",";
}
result = this.parents.size() > 0 ? result.substring(0, result.length() -1) + "]," : result + "],";
result += "\nChildren- [";
for(Variable child: this.children){
result += child.getVar_name() + ",";
}
result = this.children.size() > 0 ? result.substring(0, result.length() -1) + "]," : result + "],";
result += "\nCPT- " + CPT;
return result + "\n";
}
}
| netanellevine/Bayesian_Network | src/Variable.java | 980 | // Boolean which used only in the BayesBall Algorithm, | line_comment | en | false | 920 | 12 | 980 | 12 | 1,069 | 11 | 980 | 12 | 1,164 | 13 | false | false | false | false | false | true |
130848_10 | package oop_bookmart;
public abstract class Member {
private int memberID;
private String memberFName;
private String memberMidIni;
private String memberLName;
private String memberEmail;
private String memberPasswd;
private double memberFee;
private boolean isAdmin;
private boolean isStudent;
private boolean isFaculty;
private String memberPaypalID;
/*
public Member()
{
memberID = 500;
memberFName = "Member1";
memberMidIni = "n";
memberLName = "None";
memberEmail = "member1@bookmart.com";
memberPasswd = "memPass1";
memberFee = 0.0;
}
*/
public Member(int memberID, String memberFName, String memberMidIni,
String memberLName, String memberEmail, String memberPasswd,
boolean isStudent, boolean isFaculty, String memberPaypalID)
{
this.memberID = memberID;
this.memberFName = memberFName;
this.memberMidIni = memberMidIni;
this.memberLName = memberLName;
this.memberEmail = memberEmail;
this.memberPasswd = memberPasswd;
this.isAdmin = false;
this.isStudent = isStudent;
this.isFaculty = isFaculty;
this.memberPaypalID = memberPaypalID;
}
//Set member ID
public void setMemberID(int memberID) { this.memberID = memberID; }
//Set member first name
public void setMemberFName(String memberFName) { this.memberFName = memberFName; }
//Set member middle initial
public void setMemberMidIni(String memberMidIni) { this.memberMidIni = memberMidIni; }
//Set member last name
public void setMemberLName(String memberLName) { this.memberLName = memberLName; }
//Set member email address
public void setMemberEmail(String memberEmail) { this.memberEmail = memberEmail; }
//Set member password
public void setMemberPasswd(String memberPasswd) { this.memberPasswd = memberPasswd; }
//Set member's monthly fee
public void setMemberFee(double memberFee) { this.memberFee = memberFee; }
//Set member's status of student
public void setIsStudent(boolean isStudent) { this.isStudent = isStudent; }
//Set member's status of faculty
public void setIsFaculty(boolean isFaculty) { this.isStudent = isFaculty; }
//Set paypal ID
public void setPaypalID(String memberPaypalID) { this.memberPaypalID = memberPaypalID; }
//Get member ID
public int getMemberID() { return memberID; }
//Get member first name
public String getMemberFName() { return memberFName; }
//Get member middle initial
public String getMemberMidIni() { return memberMidIni; }
//Get member last name
public String getMemberLName() { return memberLName; }
//Get member email address
public String getMemberEmail() { return memberEmail; }
//Get member password
public String getMemberPasswd() { return memberPasswd; }
//Get member fee
public double getMemberFee() { return memberFee; }
//Get isAdmin value
public boolean getIsAdmin() { return isAdmin; }
//Get member status
public boolean getIsStudent() { return isStudent; }
public boolean getIsFaculty() { return isFaculty; }
//Get paypal ID
public String getPaypalID() { return memberPaypalID; }
//Override toString
@Override
public String toString()
{
return "User Information\n" +
"Member ID: " + memberID + "\n" +
"First name: " + memberFName + "\n" +
"Middle Initial : " + memberMidIni + "\n" +
"Last Name: " + memberLName + "\n" +
"Email address: " + memberEmail + "\n" +
"Monthly fee: " + memberFee + "\n" +
"Member is student: " + isStudent + "\n" +
"Member is faculty: " + isFaculty;
}
}
| jlcastaneda/oop-project1 | Member.java | 1,066 | //Set paypal ID | line_comment | en | false | 947 | 4 | 1,066 | 5 | 1,094 | 4 | 1,066 | 5 | 1,224 | 5 | false | false | false | false | false | true |
131102_0 | // basic code to understand about operators such like that arithmetic ,assignment,addition ,subtraction,division nd many more...
public class third {
public static void main(String args[]) {
int a = 2;
int b = 3;
//add of 2 numbers
int c = a + b;
//multipication of 2 numbers
int d = a * b;
//division of 2 numbers
int n = a / b;
System.out.println("The addition of a and b is:" + c);
System.out.println("The mmulti " + d);
System.out.println("The mmulti " + n);
}
}
| Ayush-Singodia/All-about-JAVA | Third.java | 150 | // basic code to understand about operators such like that arithmetic ,assignment,addition ,subtraction,division nd many more... | line_comment | en | false | 147 | 25 | 150 | 24 | 170 | 24 | 150 | 24 | 178 | 29 | false | false | false | false | false | true |
131756_12 | package ProgAssignment4;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Student extends User{
private String idType = "Student";
ArrayList<String> rentals = new ArrayList<String>();
ArrayList<String> rentalDates = new ArrayList<String>();
Student(String id, String pin) {
super(id, pin);
}
Student(String id, String pin, boolean access){
super(id, pin, access);
}
//adds a book in an array of checkedoutBooks from UI
public void addRental(String rentBook) throws ParseException{
Date date = new Date();
LibrarySystem y = new LibrarySystem();
Database x = LibrarySystem.database;
this.checkAccess();
if(access == true && x.getBookAvail(rentBook)){
String stime = y.getCurrentDate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
System.out.println("here");
Calendar cal = GregorianCalendar.getInstance(); //set calendar date to loginDate
date = sdf.parse(stime);
cal.setTime(date); //cal time for login date used to compareTo rentalDate
cal.add(GregorianCalendar.DAY_OF_MONTH, 10); //add 10 days of rent
String tempRentalDate = sdf.format(cal.getTime());
String tempRental = rentBook;
System.out.println(tempRentalDate);
x.changeAvail(rentBook);
rentalDates.add(tempRentalDate);
rentals.add(tempRental);
System.out.println("rented");
}
else{
System.out.println("can't rent");
}
}
public void removeRental(String rentedBook){
//compare titles and remove title
for(int i = 0; i < rentals.size(); i++){
if((rentals.get(i)).compareTo(rentedBook) == 0){
rentalDates.remove(i);
rentals.remove(i);
break;
}
}
}
public String getidType(){ return idType;}
//adds into an arrayList of Strings from text files
@Override
public void setRental(String rental) {
String[] tempString = rental.split(":|,");
String temp;
for(int i = 0; i < tempString.length; i++){
temp = tempString[i];
if((i+1)%2 == 0){
rentals.add(temp);
}
else{
rentalDates.add(temp);
}
}
}
//merges an array of rental books into a single string
@Override
public String getRental(){
String tempString = "";
for(int i = 0; i < rentals.size(); i++){
if(i == rentals.size()-1)
tempString = tempString.concat(rentalDates.get(i) + ":" + rentals.get(i));
else
tempString = tempString.concat(rentalDates.get(i) + ":" + rentals.get(i));
}
return tempString;
}
public boolean returnBook(String magicCode) throws ParseException{
String code = magicCode;
for(int i = 0; i < rentals.size(); i++){
if(code.compareTo(rentals.get(i)) == 0){
rentals.remove(i);
rentalDates.remove(i);
this.checkAccess();
return true;
}
}
return false;
}
public void checkAccess() throws ParseException{
//checks student rentals for any overdue
LibrarySystem x = new LibrarySystem();
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy/MM/dd" );
boolean verified = true; //if verification is true the user did not have an overdue book
Date loginDate = dateFormat.parse(x.getCurrentDate()); // conversion from String to Date
Date rentalDate;
Calendar cal = GregorianCalendar.getInstance(); //set calendar date to loginDate
Calendar rentCal = GregorianCalendar.getInstance();
cal.add(GregorianCalendar.DAY_OF_MONTH, 10); //add 10 days of rent
cal.setTime(loginDate); //cal time for login date used to compareTo rentalDate
//String dates = dateFormat.format(cal.getTime()); //String conversion
//System.out.println(dates);
for(int i = 0; i < rentalDates.size(); i++){
rentalDate = dateFormat.parse(rentalDates.get(i));
rentCal.setTime(rentalDate);
if(cal.compareTo(rentCal) > 0) { //compare two dates if today's date is before the due date it is greater than zero
verified = false; //overdue book; notifies method not to setAccess to true
this.setAccess(false); //student has overdue books
}
}
if(verified){
this.setAccess(true);
}
}
//returns the rental arrayList
public ArrayList<String> getRentalArray() {
return rentals;
}
public ArrayList<String> getrentalDueDates(){
return rentalDates;
}
public String getBlock(){
String isBlock = "Blocked";
if(isAccess()){
isBlock = "Unblocked";
}
return isBlock;
}
@Override
public String toString(){
String isBlock = "Blocked";
if(isAccess()){
isBlock = "Unblocked";
}
return idType + " " + isBlock + ": " + " " + getId() + " \nName:" + getName() + " \nAddress:" + getAddress() + " \nPhone #:" + getPhoneNum() + " \n" + getRental();
}
}
| Melvine/School-Library-GUI | Student.java | 1,483 | //cal time for login date used to compareTo rentalDate | line_comment | en | false | 1,253 | 11 | 1,483 | 13 | 1,516 | 11 | 1,483 | 13 | 1,826 | 13 | false | false | false | false | false | true |
132478_0 | package winterbreak;
import battlecode.common.*;
import java.util.Random;
public class viper extends Inform {
/*
* Priority: enemy is not infected:
* Infect enemies with most health first - avoid turning into zombies
* AVOID scouts + archons with low health [no big or fast zombies]
*If about to die & more enemies close
* attack self
* when nearest robot is enemy
* disintegrate [suicide]
*If infected
* commonFunc
*/
private static MapLocation attackTarget = null;
private static RobotType type = RobotType.VIPER;
private static int lastKnownArchonId = -1;
private static MapLocation lastKnownArchonLocation = null;
public static RobotController me;
public static MapLocation here;
static void run(RobotController rc) throws Exception
{
me = rc;
here = rc.getLocation();
Direction[] directions = {Direction.NORTH, Direction.NORTH_EAST, Direction.EAST, Direction.SOUTH_EAST,
Direction.SOUTH, Direction.SOUTH_WEST, Direction.WEST, Direction.NORTH_WEST};
Random rand = new Random(rc.getID());
while (true)
{
try
{
attack();
}
catch (Exception e)
{
e.printStackTrace();
}
Clock.yield();
}
}
private static void attack() throws Exception
{
if (me.isWeaponReady() && me.getCoreDelay() >= type.cooldownDelay)
{
RobotInfo[] enemies = me.senseNearbyRobots(here, type.attackRadiusSquared, them);
if (enemies.length > 0)
{
RobotInfo best = null;
for( RobotInfo pos : enemies )
{
if( pickTarget(pos, best) )
best = pos;
}
me.attackLocation(best.location);
}
}
}
//update overall goal based on new info
private static void updateTarget()
{
}
//If a is betterTarget than b return true
//Improve
private static boolean pickTarget(RobotInfo a, RobotInfo b) {
if (a.type == RobotType.SCOUT)
return false; //never infect scouts
if (a.type == RobotType.ARCHON && a.health < 500)
return false; // big zombies are too dangerous
if (b == null)
return true;
if (b.type.isZombie)
{
if (a.type.isZombie)
return a.health < b.health;
return true;
}
// b is not a zombie
if (a.type.isZombie)
return false;
// neither a nor b are zombies
if (a.viperInfectedTurns != b.viperInfectedTurns)
{
return a.viperInfectedTurns < b.viperInfectedTurns;
//add conditions based on health
}
// a and b are infected for the same number of turns
return score(a.type, a.health) > score(b.type, b.health);
}
private static double score(RobotType type, double health) //arbitrary values right now
{
switch(type)
{
case ARCHON:
return -1;
case ZOMBIEDEN:
return -2;
case TTM:
return RobotType.TURRET.attackPower / (health * RobotType.TURRET.attackDelay);
case TURRET:
return type.attackPower / (health * type.attackDelay);
case VIPER:
return 10 / (health);
default:
return type.attackPower / (health * type.attackDelay);
}
}
} | DWiz24/winterbreak | viper.java | 953 | /*
* Priority: enemy is not infected:
* Infect enemies with most health first - avoid turning into zombies
* AVOID scouts + archons with low health [no big or fast zombies]
*If about to die & more enemies close
* attack self
* when nearest robot is enemy
* disintegrate [suicide]
*If infected
* commonFunc
*/ | block_comment | en | false | 831 | 90 | 953 | 97 | 942 | 96 | 953 | 97 | 1,203 | 110 | false | false | false | false | false | true |
132481_2 | import java.util.*;
/*
* JOBTABLE - created to hold all job objects
* arrived into the system. Used to retrieve and
* update job information in OS class
*
*/
public class jobTable
{
public static Map<Integer, PCB> JobTable;
public static int maxSize = 50;
public static int JobTableSize;
/*
* initialization of JobTable
* creates Map data structure,
* save Job Number in key
* and Job Object itself in value
*/
public jobTable()
{
JobTable = new HashMap<Integer,PCB>();
JobTableSize = 0;
}
/*
* Adding new Job in Jobtable by placing
* JobNumber in key, JobObject in value
*/
public static void addNewJob(PCB job)
{
if(JobTable.size()<maxSize) {
JobTable.put(job.getJobNum(), job);
JobTableSize++;
} else System.out.println("No More Space to Place Job in Table, Improve Swapping");
}
/*
* Remove Job from JobTable when Job finished
* done by OS
*/
public static void removeJob(PCB job)
{
JobTable.remove(job.getJobNum());
JobTableSize--;
}
/*
* methods 'put', 'get', 'size' needed
* to use Map commands in other class
* Since JobTable created in OS class
* we have to set own getters and setters to use Map
*/
public static void put(int JobNum, PCB job)
{
JobTable.put(JobNum, job);
}
public static PCB get(int JobNum)
{
return JobTable.get(JobNum);
}
public static int size()
{
return JobTable.size();
}
}
| zyam007/OS- | jobTable.java | 448 | /*
* Adding new Job in Jobtable by placing
* JobNumber in key, JobObject in value
*/ | block_comment | en | false | 401 | 26 | 448 | 25 | 473 | 27 | 448 | 25 | 508 | 27 | false | false | false | false | false | true |
133022_9 | import java.util.*;
/**
*
* @author Angelica Davis, James Beck, Shane Bauerman
*/
public class ES {
private int mu; // number of individuals in parent pool (size of B)
private int p; // mixing number (size of mixing set)
private int lambda; // number of offspring
private int k; // size of x-vector (weights)
private Individual[] B; // current population
private Individual[] P; // mixing set
private static float tao;
private static float tao_prime;
private float alpha;
private Network[] networks;
public ES(Network[] networks, int mu, int p, int lambda, float alhpa) {
this.mu = mu;
this.p = p;
this.lambda = lambda;
B = initializeB(networks);
this.networks = networks;
P = new Individual[p];
this.alpha = alpha;
tao_prime = (float) (1 / Math.sqrt(2) * N(1)); // N?????
}
/*
* Extracts weights from each input network to be used as a population starting point
* returns a set of individuals
*/
public Individual[] initializeB(Network[] nets) {
// create an array for the initial population of individuals
Individual[] B = new Individual[nets.length];
for (int i = 0; i < nets.length; i++) {
// initialize strategy params to random value
Random rand = new Random();
float s = rand.nextFloat();
// extract weights from the current network
float[][] w_I = new float[nets[i].getINodes().length][];
float[][] w_H = new float[nets[i].getL1HNodes().length][];
for (int j = 0; j < nets[i].getINodes().length; j++) {
w_I[j] = nets[i].getINodes()[j].getWeight();
}
for (int j = 0; j < nets[i].getL1HNodes().length; j++) {
w_H[j] = nets[i].getINodes()[j].getWeight();
}
float[] weights_from_network = convertTo1DArray(w_I, w_H);
// create new indivdual based on extracted weights and add to population
Individual x = new Individual(weights_from_network, s);
B[i] = x;
}
return B;
}
/*
* Combines a pair of weight matrices extracted from networks
* and returns a single 1-D array of all network weights
*/
public float[] convertTo1DArray(float[][] w_I, float[][] w_H) {
int h1 = w_I.length; // "height" of first array
int w1 = w_I[0].length; // "width" of first array
int h2 = w_H.length; // "" of second
int w2 = w_H[0].length; // ""
int dimension = h1 * w1 + h2 * w2;
float[] w = new float[dimension];
for (int i = 0; i < w_I.length; i++) {
for (int j = 0; j < w_I[0].length; j++) {
w[i * w1 + j] = w_I[i][j];
}
}
for (int i = 0; i < w_H.length; i++) {
for (int j = 0; j < w_H[0].length; j++) {
w[h1 * w1 + i * w2 + j] = w_H[i][j];
}
}
return w;
}
// Not sure yet how to return weights to network, return type void for now
public void Evolve() {
int g = 0;
Individual[] B_prime = new Individual[lambda];
for (int i = 0; i < lambda; i++) {
float s = recombine_Ps();
float x[] = recombine_Px();
float s_prime = mutate_s(s);
Individual x_prime = mutate_x(x, s_prime);
// fitness
B_prime[i] = x_prime;
}
Individual[] BnextGen = nextGen(B_prime);
B = BnextGen;
g++;
}
/*
* Returns a set of networks given the current population
*/
public Network[] getNetworks(Individual[] Population) {
Network[] nets = networks;
int w1 = networks[0].getINodes().length; // "width" of input nodes' weight matrix
int h1 = networks[0].getINodes()[0].getWeight().length; // "height""
int w2 = networks[0].getL1HNodes().length; // "width" of hidden layer weights
int h2 = networks[0].getL1HNodes()[0].getWeight().length; // "height" of hidden layer weights matrix
for (int i = 0; i < Population.length; i++) {
float[][] w_I = new float[w1][h1];
float[][] w_H = new float[w2][h2];
float[] x = Population[i].get_x();
for (int j = 0; j < w1; j++) {
for (int k = 0; k < h1; k++) {
w_I[i][j] = x[i * w1 + j];
}
}
for (int j = 0; j < w2; j++) {
for (int k = 0; k < h2; k++) {
w_I[i][j] = x[w1*h1 + i * w2 + j];
}
}
nets[i].updateNetworkWeights(w_I, w_H);
}
return nets;
}
public float[] recombine_Px() {
float[] x = new float[k]; // x-vector derived from recombination
Random random = new Random();
for (int i = 0; i < k; k++) {
int r = random.nextInt(p); // randomly select a parent from the mixing set
x[i] = P[r].get_x()[i]; // select the ith "gene" from the selected parent
}
return x;
}
public float recombine_Ps() {
Random random = new Random();
int r = random.nextInt(mu);
return P[r].get_s(); // randomly select the s "gene" from parent pool
}
public Individual mutate_x(float[] x, float s_prime) {
float[] x_prime = new float[k];
for (int i = 0; i < k; i++) {
x_prime[i] = x[i] + s_prime * N(x[i]);
}
return new Individual(x_prime, s_prime);
}
public float mutate_s(float s) {
float rho_prime = (float) 0.0;
rho_prime = (float) (s * Math.pow(Math.E, tao * N(1))); // Math????
return rho_prime;
}
/*
* Computes and returns the Gaussian distribution
* N(0,1)
*/
public float N(float x) {
return (float) (1 / Math.sqrt(2 * Math.PI) * Math.pow(Math.E, -x * x));
}
public Individual[] nextGen(Individual[] B_prime) {
Individual[] nextGen = new Individual[p + lambda];
for (int i = 0; i < p; i++) {
nextGen[i] = B[i];
}
for (int i = p; i < lambda; i++) {
nextGen[i] = B_prime[i];
}
return nextGen;
}
}
| MLGroup13/Project-3 | project3/ES.java | 1,825 | // create an array for the initial population of individuals | line_comment | en | false | 1,692 | 10 | 1,825 | 10 | 1,949 | 10 | 1,825 | 10 | 2,058 | 10 | false | false | false | false | false | true |
133061_2 | // Polymorphism using interfaces
interface MyCamera1{
void takeSnap();
void recordVideo();
default void record4kVideo(){
System.out.println("Recording in 4k...");
}
}
interface MyWifi1{
String [] getNetworks();
void connectToNetwork(String Network);
}
class MyCellPhone1 {
void callNumber(int phoneNumber) {
System.out.println("Calling" + phoneNumber);
}
void pickCall() {
System.out.println("Connecting....");
}
}
class MySmartPhone1 extends MyCellPhone1 implements MyCamera1,MyWifi1{
public void takeSnap(){
System.out.println("Take snap");
}
public void recordVideo(){
System.out.println("Record a video");
}
public void record4kVideo(){ // Override due to overridden method this will only work
System.out.println("Record a video in 4k");
}
public String[] getNetworks() {
System.out.println("Getting list of networks");
String[] networkList = {"Harry","Ayush","Buli"};
return networkList;
}
public void connectToNetwork(String Network) {
System.out.println("Connecting to " + Network);
}
}
public class Lecture59{
public static void main(String[] args) {
MyCamera1 cam1 = new MySmartPhone1(); //This is a smartphone but use it only as a camera...
// cam1.getNetworks(); not allowed...
cam1.record4kVideo();
cam1.recordVideo();
cam1.takeSnap();
MySmartPhone1 s = new MySmartPhone1();
s.getNetworks();
s.recordVideo();
s.record4kVideo();
s.callNumber(123);
s.pickCall();
}
}
| dynoayush/Java-Full-Course | src/Lecture59.java | 434 | //This is a smartphone but use it only as a camera...
| line_comment | en | false | 383 | 14 | 434 | 17 | 466 | 13 | 434 | 17 | 500 | 15 | false | false | false | false | false | true |
133110_9 | /*
* TO DO
*
* Add bias saves
*/
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileReader;
import java.util.ArrayList;
public class NetSave {
String str = "";
File file;
FileWriter writer;
FileReader reader;
static ArrayList<ArrayList<double[][]>> netList = new ArrayList<>();
static ArrayList<int[]> networkShapes = new ArrayList<>();
static ArrayList<ArrayList<double[]>> biasList = new ArrayList<>();
static ArrayList<String> commentList = new ArrayList<>();
static int numNetworks = 0;
//Defined characters
char dimensionCharacter = '@';
char networkCharacter = ':';
char biasCharacter = '~';
char commentCharacter = '#';
char closeCharacter = '$';
public NetSave(File file) throws IOException {
this.file = file;
writer = new FileWriter(file, true);
reader = new FileReader(file);
if(!file.exists()) {
file.createNewFile();
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists");
}
}
public void writeFile(int[] size, String net, String bias, String comment) throws IOException {
//append size
writer.append(dimensionCharacter);
for(int i = 0; i < size.length; i++) {
writer.append(size[i] + " ");
}
writer.append(networkCharacter);
//append network
writer.append(net + biasCharacter);
//append bias
writer.append(bias + commentCharacter);
//append comment
writer.append(comment + closeCharacter);
}
public void closeWriter() throws IOException {
writer.close();
}
public void loadStr() throws IOException {
int data = reader.read();
numNetworks = 0;
int currentIndex = 0;
//load data into one big string
while(data != -1) {
String phold = "";
String[] pholdArr;
//@ - dimensions character
if((char)data == dimensionCharacter) {
//System.out.println("size");
data = reader.read();
numNetworks++;
System.out.println("added");
while((char)data != ':') {
phold += (char)data;
data = reader.read();
}
pholdArr = phold.split(" ");
networkShapes.add(new int[pholdArr.length]);
for(int i = 0; i < pholdArr.length; i++) {
networkShapes.get(currentIndex)[i] = Integer.parseInt(pholdArr[i]);
}
phold = "";
}
//: - closing dimension character, opening network character
if((char)data == networkCharacter) {
//System.out.println("net");
data = reader.read();
while((char)data != biasCharacter) {
if((char)data != '\n') {
phold += (char)data;
}
data = reader.read();
}
pholdArr = phold.split(" ");
netList.add(new ArrayList<double[][]>());
int pholdArrInd = 0;
for(int numArr = 0; numArr < networkShapes.get(currentIndex).length - 1; numArr++) {
int numRows = networkShapes.get(currentIndex)[numArr + 1];
int numCol = networkShapes.get(currentIndex)[numArr];
netList.get(currentIndex).add(new double[numRows][numCol]);
for(int rows = 0; rows < numRows; rows++) {
for(int columns = 0; columns < numCol; columns++) {
netList.get(currentIndex).get(numArr)[rows][columns] = Double.parseDouble(pholdArr[pholdArrInd]);
pholdArrInd++;
}
}
}
phold = "";
}
//~ - closing network character, opening bias character
if((char)data == biasCharacter) {
//System.out.println("bias");
data = reader.read();
while((char)data != commentCharacter) {
if((char)data != '\n') {
phold += (char)data;
}
data = reader.read();
}
pholdArr = phold.split(" ");
int pholdArrInd = 0;
int numRows = networkShapes.get(currentIndex).length - 1;
ArrayList<double[]> pholdArrBias = new ArrayList<>();
for(int row = 0; row < numRows; row++) {
int numCol = networkShapes.get(currentIndex)[row + 1];
pholdArrBias.add(new double[numCol]);
for(int col = 0; col < numCol; col++) {
pholdArrBias.get(row)[col] = Double.parseDouble(pholdArr[pholdArrInd]);
pholdArrInd++;
}
}
biasList.add(pholdArrBias);
pholdArrBias.clear();
phold = "";
}
//# - closing bias character, opening comment character
if((char)data == commentCharacter) {
//System.out.println("comment");
data = reader.read();
while((char)data != closeCharacter) {
if((char)data != '\n') {
phold += (char)data;
}
data = reader.read();
}
commentList.add(phold);
phold = "";
currentIndex++;
}
data = reader.read();
}
}
}
| MilianDIngco/pong | NetSave.java | 1,268 | //: - closing dimension character, opening network character | line_comment | en | false | 1,145 | 9 | 1,268 | 10 | 1,413 | 9 | 1,268 | 10 | 1,527 | 10 | false | false | false | false | false | true |
133286_10 |
/*
Kareem Masalma.
1220535.
Project phase1.
*/
import java.util.*;
public class Family {
private String familyName;
ArrayList<Person> members = new ArrayList<>();
ArrayList<Person> parents = new ArrayList<>();
// No argument constructor.
public Family() {
}
// constructor with argument.
public Family(String familyName) {
this.familyName = familyName;
}
// A method to add a new member to a family.
public boolean addMember(Person member, String role) {
for (int i = 0; i < members.size(); i++) { // To check if the entered ID is already exist.
if (members.get(i).getID().equals(member.getID())) {
System.out.println("ID already exists.");
return false;
}
}
// To check if the person is a mother or a father to add to members ArrayList and parents ArrayList.
if (role.equalsIgnoreCase("Mom") || role.equalsIgnoreCase("Dad") || role.equalsIgnoreCase("Mother")
|| role.equalsIgnoreCase("Father")) {
parents.add(member);
members.add(member);
return true;
// To check if the person is a son or a daughter to add to members ArrayList only.
} else if (role.equalsIgnoreCase("Son") || role.equalsIgnoreCase("Daughter")) {
members.add(member);
return true;
} else {
return false;
}
}
// A method to remove a member.
public boolean removeMember(Person member) {
if (member == null)
return false;
// A loop to search for the member.
for (int i = 0; i < members.size(); i++) {
// If the ID exists the member will be removed from the ArrayList members.
if (members.get(i).getID().equals(member.getID())) {
members.remove(i);
return true; // return true if the member is successfully removed
}
}
return false; // If the member was not found it will return false.
}
// return all the members in the ArrayList.
public ArrayList<Person> getMembers() {
return members;
}
// A method to add a parent to the parents ArrayList.
public void addParent(Person parent) {
// A loop to check if the parent already added to parents ArrayList.
for (int i = 0; i < parents.size(); i++) {
if (parents.get(i).getID().equals(parent.getID())) {
System.out.println("The parent with this ID already exists.");
return;
}
}
parents.add(parent);
members.add(parent);
System.out.println("Parent added successfully.");
}
// A method to remove a parent.
public boolean removeParent(Person parent) {
boolean flag = false;
if (parent == null)
return false;
// Remove the parent from parents ArrayList.
for (int i = 0; i < parents.size(); i++) {
if (parents.get(i).getID().equals(parent.getID())) {
parents.remove(i);
flag = true;
}
}
// Remove the parent from parents ArrayList.
for (int i = 0; i < members.size(); i++) {
if (members.get(i).getID().equals(parent.getID())) {
members.remove(i);
flag = true;
}
}
return flag;
}
// Setters and getters:
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public ArrayList<Person> getParents() {
return parents;
}
// toString method to get the info about the family and its members.
@Override
public String toString() {
return "Family [Family Name=" + familyName + ", members=" + members + "]";
}
// Overridden method to check if 2 families are equal by the number of the
// martyrs.
@Override
public boolean equals(Object obj) {
int mar = 0;
int marFam = 0;
// To check the number of the martyrs in the family.
for (int i = 0; i < members.size(); i++) {
if (members.get(i) instanceof Martyr) {
mar++;
}
}
// check the number of the martyrs in the sent family.
if (obj instanceof Family) { // To check if the obj is a Family.
int size = ((Family) obj).members.size();
for (int i = 0; i < size; i++) {
if (((Family) obj).members.get(i) instanceof Martyr) {
marFam++;
}
}
}
if (mar == marFam)
return true;
else
return false;
}
} | Kareem-Masalma/OOP-phase-1 | Family.java | 1,237 | // return true if the member is successfully removed
| line_comment | en | false | 1,048 | 10 | 1,237 | 10 | 1,253 | 10 | 1,237 | 10 | 1,462 | 10 | false | false | false | false | false | true |
133319_12 | package gitlet;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Formatter;
/** Commit class for gitlet.
* @author Philipp
*/
public class Commit implements Serializable {
/** Message of commit. */
private String _message;
/** Timestamp oof commit. */
private Date _timestamp;
/** List of commit's parents commits. */
private List<String> _parents;
/** List of files that are tracked by this commit. */
private List<FileToShaMapping> _trackedFiles;
/** Creates new commit with commit message MESSAGE. */
public Commit(String message) {
_message = message;
_timestamp = new Date();
_trackedFiles = new ArrayList<FileToShaMapping>();
}
/** Creates new commit with commit message MESSAGE and
* timestamp TIMESTAMPMS.
*/
public Commit(String message, long timestampMS) {
_message = message;
_timestamp = new Date(timestampMS);
}
/** Returns new initial commit.
*/
public static Commit newInitialCommit() {
return new Commit("initial commit", 0);
}
/** Returns list of files that are tracked in this commit.
*/
public List<FileToShaMapping> getTrackedFiles() {
if (_trackedFiles == null) {
_trackedFiles = new ArrayList<FileToShaMapping>();
}
return _trackedFiles;
}
/** Sets list of tracked files to list PREVIOUS.
*/
public void setTrackedFiles(List<FileToShaMapping> previous) {
_trackedFiles = previous;
}
/** Update tracked file FILENAME in this commit with commit hash HASH.
*/
public void updateTrackedFile(String filename, String hash) {
boolean existing = false;
if (_trackedFiles == null) {
_trackedFiles = new ArrayList<FileToShaMapping>();
} else {
for (FileToShaMapping mapping : _trackedFiles) {
if (mapping.getFilename().equals(filename)) {
mapping.setHash(hash);
existing = true;
break;
}
}
}
if (!existing) {
_trackedFiles.add(new FileToShaMapping(filename, hash));
}
}
/** Adds parent COMMITHASH to this commit.
*/
public void addParent(String commitHash) {
if (_parents == null) {
_parents = new LinkedList<String>();
}
_parents.add(commitHash);
}
/** Remove file FILENAME from this commit's tracking.
*/
public void removeTracking(String filename) {
int index = -1;
for (int i = 0; i < _trackedFiles.size(); i++) {
if (_trackedFiles.get(i).getFilename().equals(filename)) {
index = i;
break;
}
}
if (index > -1) {
_trackedFiles.remove(index);
}
}
/** Returns date string from this commit's timestamp.
*/
public String getDateString() {
StringBuilder sbuf = new StringBuilder();
Formatter fmt = new Formatter(sbuf);
fmt.format("%ta %tb %td %tH:%tM:%tS %tY %tz", _timestamp, _timestamp,
_timestamp, _timestamp, _timestamp, _timestamp, _timestamp,
_timestamp);
return sbuf.toString();
}
/** Return this commit's commit message.
*/
public String getMessage() {
return _message;
}
/** Return this commit's first parent.
*/
public String getParent() {
if (_parents == null || _parents.size() == 0) {
return null;
}
return _parents.get(0);
}
/** Returns this commit's parent with index IND.
*/
public String getParent(int ind) {
if (_parents == null || _parents.size() <= ind) {
return null;
}
return _parents.get(ind);
}
/** Returns FileToShaMapping for file FILENAME from this commit.
*/
public FileToShaMapping getMapping(String filename) {
FileToShaMapping res = null;
for (FileToShaMapping map : _trackedFiles) {
if (map.getFilename().equals(filename)) {
res = map;
break;
}
}
return res;
}
/** Returns true iff this commit is a merge commit.
*/
public boolean isMergeCommit() {
return _parents != null && _parents.size() > 1;
}
}
| philipp-kurz/Gitlet | Commit.java | 1,037 | /** Remove file FILENAME from this commit's tracking.
*/ | block_comment | en | false | 966 | 13 | 1,037 | 13 | 1,204 | 15 | 1,037 | 13 | 1,301 | 15 | false | false | false | false | false | true |
133578_1 | import java.util.LinkedList;
public class Bank {
AccountHolder ah = new AccountHolder();
String f_name, l_name;
String mobile_no;
LinkedList<String> transactions_list;
private int userid, pin, age;
private int balance;
public Bank(){}
public Bank(String f_name, String l_name, int age, int userid, int pin, String mobile_no, int balance){
this.f_name = f_name;
this.l_name = l_name;
this.age = age;
this.userid = userid;
this.pin = pin;
this.mobile_no = mobile_no;
this.balance = balance;
this.transactions_list = new LinkedList<>();
}
public String getName(){
return this.f_name + " " + this.l_name;
}
public String getFirstName(){
return this.f_name;
}
public String getLastName(){
return this.l_name;
}
public int getAge(){
return this.age;
}
public int getUserId(){
return this.userid;
}
public int getPin(){
return this.pin;
}
public int getBalance(){
return this.balance;
}
public String getPhoneNumber(){
return this.mobile_no;
}
public void addBalance(double amount){
this.balance += amount;
//generate transaction message
this.generateTransaction(userid, amount, "Deposit", userid, "Successfull");
}
public boolean reduceBalance(double amount){
if (this.balance> amount){
this.balance -= amount;
this.generateTransaction(userid, amount, "Withdraw", userid, "Successfull");
return true;
}
else{
this.generateTransaction(userid, amount, "Withdraw", userid, "Failed");
//generate transaction failed message
return false;
}
}
public boolean transfer(double amount, Bank account){
if(this.balance > amount){
this.balance -= amount;
account.addBalance(amount);
this.generateTransaction(this.userid, amount, "Transfer", account.userid, "Successfull");
return true;
}
else{
//generate transaction failed
this.generateTransaction(this.userid, amount, "Transfer", account.userid, "Failed");
account.generateTransaction(account.userid, amount, "Transfer", this.userid, "Failed");
return false;
}
}
public void generateTransaction(int userid, double amount, String type, int target, String Status){
long ref_no =(long) (Math.random() * Math.pow(10, 10));
String message = "Ref.no: " + ref_no + " user id : " + userid + " target : " + target + " amount: " + amount + " type : " + type + " Status : " + Status;
this.updateTransaction(message);
}
public void updateTransaction(String transaction){
transactions_list.add(transaction);
}
public void showTransaction(){
for(String transaction: this.transactions_list){
System.out.println(transaction);
}
}
}
| ganpat-university/industry-project-submission-2020-batch-stuti-1610 | Bank.java | 709 | //generate transaction failed message | line_comment | en | false | 624 | 5 | 709 | 5 | 797 | 5 | 709 | 5 | 865 | 5 | false | false | false | false | false | true |
133726_0 | import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
enum PantryType {
PANTRY,
SHOPPING_CART
}
public class Kitchen
{
public static ArrayList<Pantry> inventory = new ArrayList<Pantry>();
public Pantry createPantry(PantryType type, String name){
Pantry newPantry = PantryService.createPantry(type, name);
inventory.add(newPantry);
return newPantry;
}
public Pantry retrievePantry(int pantryID){
//checks each item in the items array list
int index = getPantryIndex(pantryID);
if (index == -1) {
return null;
} else {
return inventory.get(index);
}
}
public Pantry deletePantry(int pantryID) {
Pantry deletedPantry = null;
Iterator<Pantry> iterator = inventory.iterator();
while (iterator.hasNext()) {
Pantry pantry = iterator.next();
if (pantry.getPantryID() == pantryID) {
deletedPantry = pantry;
iterator.remove();
}
}
return deletedPantry;
}
public Pantry addItem(int pantryID, String name, Calendar dateAdded, int quantity){
int index = getPantryIndex(pantryID);
if (index != -1) {
inventory.get(index).addItem(name, dateAdded, quantity);
}
return inventory.get(index);
}
public Pantry addItem(int pantryID, String name, Calendar dateAdded, int quantity, Calendar expirDate, int lowQuantityNotifThreshold) {
int index = getPantryIndex(pantryID);
if (index != -1) {
inventory.get(index).addItem(name, dateAdded, quantity, expirDate, lowQuantityNotifThreshold);
}
return inventory.get(index);
}
public Pantry editItem(int pantryID, int itemID, String name, Calendar dateAdded, int quantity, Calendar expirDate, int lowQuantityNotifThreshold) {
int index = getPantryIndex(pantryID);
if (index != -1) {
inventory.get(index).editItem(itemID, name, dateAdded, quantity, expirDate, lowQuantityNotifThreshold);
}
return inventory.get(index);
}
public Pantry editItem(int pantryID, int itemID, String name, Calendar dateAdded, int quantity){
int index = getPantryIndex(pantryID);
if (index != -1) {
inventory.get(index).editItem(itemID, name, dateAdded, quantity);
}
return inventory.get(index);
}
public void saveRecipe(Recipe recipe){
CookbookService.saveRecipe(recipe);
}
private int getPantryIndex(int pantryID) {
Iterator<Pantry> iterator = inventory.iterator();
Pantry foundPantry = null;
int count = 0;
while(iterator.hasNext()) {
Pantry list = iterator.next();
if (list.getPantryID() == pantryID) {
foundPantry = list;
break;
}
count++;
}
if (foundPantry == null) {
System.out.println("Pantry with ID: " + pantryID + " cannot be found");
return -1;
} else {
return count;
}
}
public ArrayList<Recipe> sortRecipeNames() {
return CookbookService.sortRecipeNames();
}
} | Gsheley/MyKitchen | src/Kitchen.java | 818 | //checks each item in the items array list | line_comment | en | false | 725 | 9 | 818 | 9 | 862 | 9 | 818 | 9 | 958 | 10 | false | false | false | false | false | true |
134998_15 | import io.ScannerUtils;
import java.util.Scanner;
import java.util.Set;
import common.Util;
import common.types.Tuple;
import common.types.Tuple5;
/** An instance represents a disease spreading and ultimately dying out among
* a limited population (or killing everyone).
* <br>
* Each Disease is created on a Network of people and with a chosen first patient.
* Disease is runnable, but for the purposes of this project, it does not need
* to be run on a separate thread.
* @author MPatashnik
*/
public class Disease implements Runnable {
private Network network; // The graph on which this Disease is running. */
private DiseaseTree tree; // The tree representing this disease.
private int steps; // Number of time steps this disease took to create dt.
private Statistics statistics; // The disease model:
// Statistics that determine the spread of the disease.
/** How many chars to print per line in the running section. */
private static final int RUNNING_CHAR_COUNT_MAX= 50;
/** Used in printing the run progress. */
private int runningCharCount= 7;
/** Constructor: a new Disease on network nw with first patient fp
* and disease model s. */
public Disease(Network nw, Person fp, Statistics s){
steps= 0;
network= nw;
fp.becomeSick(0);
tree= new DiseaseTree(fp);
statistics= s;
}
/** Run the disease until no sick people remain.
* Print out info about running.*/
public @Override void run(){
System.out.print("Running");
while (network.getPeopleOfType(Person.State.SICK).size() > 0) {
step();
}
System.out.println("Done.\n");
}
/** Perform a single step on the disease, using disease model statistics.
* First, sick people may become immune with a certain probability.
* Second, sick people become less healthy by 1, and if their health reaches 0, they die.
* Third, sick people may spread the disease to one neighbor, with a certain probability.
*/
private void step() {
Set<Person> people= network.vertexSet();
System.out.print(".");
runningCharCount++;
if (runningCharCount > RUNNING_CHAR_COUNT_MAX) {
System.out.print("\n");
}
// For each sick person, make them immune with a certain probability
for (Person p : people) {
if (p.isSick() && statistics.personBecomesImmune()){
p.becomeImmune(steps);
}
}
// For each sick person, deduct 1 from health and make death if health becomes 0
for (Person p : people) {
if (p.isSick()) {
p.reduceHealth(steps);
}
}
// For each sick person, spread the disease to one random neighbor with a
// certain probability.
for (Person p : people) {
if (p.isSick()) {
Person n= p.getRandomNeighbor();
if (n != null && n.isHealthy() && statistics.diseaseSpreadsToPerson()) {
n.becomeSick(steps);
tree.add(p, n);
}
}
}
steps= steps + 1;
}
/** Read in the five statistic arguments from the console.
* Return a Tuple5, with the following components:
* <br> - size: the number of people in the network
* <br> - maxHealth: how much health each person starts with
* <br> - connectionProbability: probability that two people are connected in the network
* <br> - sicknessProbability: probability that a sick person spreads the sickness to a neighbor in one time step
* <br> - immunizationProbability: probability that a sick person becomes immune in one time step
*/
private static Tuple5<Integer, Integer, Double, Double, Double> readArgs() {
Scanner scanner= ScannerUtils.defaultScanner();
int size = ScannerUtils.get(Integer.class, scanner, "Enter the size of the population: ",
"Please enter a positive non-zero integer", (i) -> i > 0);
int maxHealth= ScannerUtils.get(Integer.class, scanner,
"Enter the amount of health for each person: ",
"Please enter a positive non-zero integer", (i) -> i > 0);
double connectionProb= ScannerUtils.get(Double.class, scanner,
"Enter the probability of a connection: ",
"Please enter a double in the range [0,1]", (d) -> d >= 0 && d <= 1);
double sicknessProb= ScannerUtils.get(Double.class, scanner,
"Enter the probability of becoming sick: ",
"Please enter a double in the range [0,1]", (d) -> d >= 0 && d <= 1);
double immunizationProb= ScannerUtils.get(Double.class, scanner,
"Enter the probability of becoming immune: ",
"Please enter a double in the range [0,1]", (d) -> d >= 0 && d <= 1);
scanner.close();
return Tuple.of(size, maxHealth, connectionProb, sicknessProb, immunizationProb);
}
/** Run Disease on the arguments listed in args.
* If args does not match the pattern below, read in arguments via the console
* by using readArgs().
*
* Then, call disease.run() and create a DiseaseFrame showing the created DiseaseTree.
*
* args should be an array of [size, maxHealth, connection probability,
* sickness probability, immunization probability],
* or unused (any value). If not used, the user is prompted for input in the console.
*/
public static void main(String[] args) {
//Get arguments
int size= 10;
int maxHealth= 5;
double connectionProbability= 0.7;
double sicknessProbability= 0.5;
double immunizationProbability= 0.1;
try {
//Attempt to read from args array passed in
size= Integer.parseInt(args[0]);
maxHealth= Integer.parseInt(args[1]);
connectionProbability= Double.parseDouble(args[2]);
sicknessProbability= Double.parseDouble(args[3]);
immunizationProbability= Double.parseDouble(args[4]);
} catch (Exception e) {
//If too few or wrong type, read from scanner
Tuple5<Integer, Integer, Double, Double, Double> args2= readArgs();
size= args2._1;
maxHealth= args2._2;
connectionProbability= args2._3;
sicknessProbability= args2._4;
immunizationProbability= args2._5;
}
//Set defaults and create the Network, Statistics, and Disease objects
System.out.print("\nSetting up ");
System.out.print(".");
Network n= new Network(size, connectionProbability, maxHealth);
System.out.print(".");
Statistics s= new Statistics(sicknessProbability, immunizationProbability);
System.out.print(".");
Disease d= new Disease(n, Util.randomElement(n.vertexSet()), s);
System.out.println("Done.");
d.run();
System.out.println(d.tree.toStringVerbose() + "\n");
for (Person p : d.network.getPeopleOfType(Person.State.HEALTHY)) {
System.out.println(p);
}
DiseaseFrame.show(d.tree, d.steps);
}
}
| wushirong/Workspace | A4/src/Disease.java | 1,778 | /** Read in the five statistic arguments from the console.
* Return a Tuple5, with the following components:
* <br> - size: the number of people in the network
* <br> - maxHealth: how much health each person starts with
* <br> - connectionProbability: probability that two people are connected in the network
* <br> - sicknessProbability: probability that a sick person spreads the sickness to a neighbor in one time step
* <br> - immunizationProbability: probability that a sick person becomes immune in one time step
*/ | block_comment | en | false | 1,603 | 130 | 1,778 | 137 | 1,847 | 136 | 1,778 | 137 | 2,065 | 156 | false | false | false | false | false | true |
135002_13 | package realdata;
import graph.Graph;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import statistics.Probability;
import statistics.Sample;
import statistics.SampleSet;
import statistics.Utils;
public class App {
public static final String TYPE_FLOWER = "files/iris.csv";
public static final String TYPE_WINE = "files/wine.csv";
public static final String TYPE_DISEASE = "files/heartDisease.csv";
public static ArrayList<Data> readFile(String fileToParse) {
ArrayList<Data> data = new ArrayList<Data>();
//Input file which needs to be parsed
BufferedReader fileReader = null;
//Delimiter used in CSV file
final String DELIMITER = ",";
try {
String line = "";
//Create the file reader
fileReader = new BufferedReader(new FileReader(fileToParse));
//Read the file line by line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(DELIMITER);
switch (fileToParse) {
case TYPE_FLOWER:
data.add(new Flower(tokens));
break;
case TYPE_WINE:
data.add(new Wine(tokens));
break;
case TYPE_DISEASE:
data.add(new HeartDisease(tokens));
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
public static SampleSet dataToSampleSet(ArrayList<Data> data) {
SampleSet set = new SampleSet(data.size(), data.get(0).getDimensions());
int i = 0;
for (Data d: data) {
set.setSample(i++, d.toSample());
}
return set;
}
public static void classify(int c, int d, SampleSet samples) {
int fold = 8; //8-fold cross validation
float independentCorrectClassifications = 0;
float dependentCorrectClassifications = 0;
ArrayList<ArrayList<Sample>> testingSets = new ArrayList<ArrayList<Sample>>();
double[][] estimatedProbabilities = new double[c][d];
for (int i = 0; i < c; ++i) {
estimatedProbabilities[i] = samples.getProbabilities(i);
}
for (int i = 0; i < c; ++i) {
for (int j = 0; j < d; ++j) {
System.out.print(estimatedProbabilities[i][j] + " ");
}
System.out.println();
}
System.out.println();
//cross-validation
System.out.println("INDEPENDENT CLASSIFICATION");
for (int f = 0; f < fold; ++f) {
//testing
//get testing sets
for (int i = 0; i < c; ++i) {
testingSets.add(samples.getTestingSet(f, fold));
}
//for each sample in each classes test set
int testingSetIndex = 0;
for (ArrayList<Sample> list: testingSets) {
int[] counts = new int[c];
for (Sample sample: list) {
//classify
double probs[] = new double[c];
for (int i = 0; i < c; ++i) {
probs[i] = Probability.getSampleProbability(sample, estimatedProbabilities[i], d);
}
double max = Utils.findMax(probs);
for (int i = 0; i < c; ++i) {
if (max == probs[i]) {
counts[i]++;
sample.set_class(i+1);
if (testingSetIndex == i) {
independentCorrectClassifications++;
}
break;
}
}
}
for (int i = 0; i < c; ++i) {
System.out.println("Class" + (i+1) + ": " + counts[i] + "/" + samples.getSize()/fold);
}
System.out.println("");
testingSetIndex++;
}
testingSets.clear();
}
double percentage = (independentCorrectClassifications/samples.getSize());
System.out.println("Independent Accuracy: " + Utils.roundToDecimals(percentage, 2) + "%\n");
System.out.println("DEPENDENT CLASSIFICATION");
for (int f = 0; f < fold; ++f) {
//testing
//get testing sets
for (int i = 0; i < c; ++i) {
testingSets.add(samples.getTestingSet(f, fold));
}
//for each sample in each classes test set
int testingSetIndex = 0;
for (ArrayList<Sample> list: testingSets) {
int[] counts = new int[c];
for (Sample sample: list) {
//classify
double probs[] = new double[c];
for (int i = 0; i < c; ++i) {
probs[i] = Probability.getSampleProbability(sample, estimatedProbabilities[i], d);
}
double max = Utils.findMax(probs);
for (int i = 0; i < c; ++i) {
if (max == probs[i]) {
counts[i]++;
sample.set_class(i+1);
if (testingSetIndex == i) {
dependentCorrectClassifications++;
}
break;
}
}
}
for (int i = 0; i < c; ++i) {
System.out.println("Class" + (i+1) + ": " + counts[i] + "/" + samples.getSize()/fold);
}
System.out.println("");
testingSetIndex++;
}
testingSets.clear();
}
double percentage2 = (dependentCorrectClassifications/samples.getSize());
System.out.println("Dependent Accuracy: " + Utils.roundToDecimals(percentage2, 2) + "%\n");
Graph g1 = Graph.assignWeights(samples, d);
Graph mst1 = g1.maximumSpanningTree();
System.out.println(g1.toString());
System.out.println(mst1.toString());
}
public static void main(String[] args) {
String type = TYPE_DISEASE;
ArrayList<Data> data = readFile(type);
ArrayList<Double> thresh = null;
switch (type) {
case TYPE_FLOWER:
thresh = Flower.getThresholds(data);
break;
case TYPE_WINE:
thresh = Wine.getThresholds(data);
break;
case TYPE_DISEASE:
thresh = HeartDisease.getThresholds(data);
break;
}
for (Data d: data) {
d.convertToBinary(thresh);
}
for (Data d: data) {
System.out.println(d.toString());
}
switch (type) {
case TYPE_FLOWER:
classify(3, 4, dataToSampleSet(data));
break;
case TYPE_WINE:
classify(3, 13, dataToSampleSet(data));
break;
case TYPE_DISEASE:
classify(5, 13, dataToSampleSet(data));
break;
}
}
}
| Cloudxtreme/AIClassification | src/realdata/App.java | 1,885 | //for each sample in each classes test set
| line_comment | en | false | 1,642 | 10 | 1,885 | 10 | 2,054 | 10 | 1,885 | 10 | 2,590 | 10 | false | false | false | false | false | true |
135252_0 |
package school.management.system;
import java.io.Serializable;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Teacher extends Person implements Information, Serializable {
private int grade;
private double salary;
private int absentDays;
private String isSalaryPaid;
private Date hiringDate;
transient Scanner input = new Scanner(System.in);
// no argument Constructor.
public Teacher() {
super();
absentDays = 0;
isSalaryPaid = "unpaid";
getInformation();
}
// Function to assign salary to Teacher
private int assignSalary(int g) {
return (g * 10_000);
}
// Function to calculation salary after deducting absent days
public double calculateSalary() {
if (absentDays > 5) {
double deduction = ((2.0 / 100) * absentDays) * salary;
salary -= deduction;
}
return salary;
}
// Function to get Teacher Information
@Override
public void getInformation() {
try {
System.out.print("Enter the Grade of Teacher from 1 to 6:");
grade = input.nextInt();
if (grade < 1 || grade > 6) {
System.out.println("Wrong input! Enter grade again ");
grade = input.nextInt();
}
salary = assignSalary(grade);
System.out.println("Enter exact date of Hiring");
System.out.print("Enter date from 1 to 31 :");
int day = input.nextInt();
System.out.print("\nEnter month from 1 to 12");
int month = input.nextInt();
System.out.print("\nEnter year in 20xx:");
int year = input.nextInt();
hiringDate = new Date(day, month, year);
} catch (InputMismatchException ex) {
System.out.println("Wrong Input!!!!!!");
}
}
// toString for Teacher
@Override
public String toString() {
return (super.toString() + "\nSalary=" + salary + "\nAbsentent Days=" + absentDays + "\nSalary paid?"
+ isSalaryPaid + "\nDate of Hiring=" + hiringDate.toString());
}
// Getter Setter for all datafeilds
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getAbsentDays() {
return absentDays;
}
public void setAbsentDays(int absentDays) {
this.absentDays = absentDays;
}
public String getSalaryPaidStatus() {
return isSalaryPaid;
}
public void setSalaryPaidStatus(String isSalaryPaid) {
this.isSalaryPaid = isSalaryPaid;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
// Function to change and set Teacher's Hiring date
public void changeHiringDate(Date d) {
hiringDate.setDay(d.getDay());
hiringDate.setMonth(d.getMonth());
hiringDate.setYear(d.getYear());
System.out.println("Now the hiring date is " + hiringDate.toString());
}
}
| ayeshakamran543/School-Management-System-Project | Teacher.java | 856 | // no argument Constructor.
| line_comment | en | false | 681 | 6 | 856 | 6 | 899 | 5 | 856 | 6 | 1,064 | 6 | false | false | false | false | false | true |
135383_14 | package org.kodejava.example.text;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class LocaleDateTime {
public static void main(String[] args) {
Locale[] locales = {
Locale.CANADA,
Locale.FRANCE,
Locale.GERMANY,
Locale.US,
Locale.JAPAN
};
Date today = new Date();
for (Locale locale : locales) {
StringBuilder sb = new StringBuilder();
sb.append(locale.getDisplayCountry());
sb.append("n--------------------------------");
//
// Gets a DateFormat instance for the specified locale
// and format a date object by calling the format
// method.
//
DateFormat df = DateFormat.getDateInstance(
DateFormat.DEFAULT, locale);
String date = df.format(today);
sb.append("n Default date format: ").append(date);
//
// Gets a DateFormat instance for the specified locale
// and format a time information by calling the format
// method.
//
DateFormat tf = DateFormat.getTimeInstance(
DateFormat.DEFAULT, locale);
String time = tf.format(today.getTime());
sb.append("n Default time format: ").append(time)
.append("n");
System.out.println(sb.toString());
}
//
// Gets date and time formatted value for Italy locale using
// To display a date and time in the same String, create the
// formatter with the getDateTimeInstance method.
// The first parameter is the date style, and the second is
// the time style. The third parameter is the Locale
//
DateFormat dtf = DateFormat.getDateTimeInstance(
DateFormat.DEFAULT, DateFormat.DEFAULT,
Locale.ITALY);
String datetime = dtf.format(today);
System.out.println("date time format in " +
Locale.ITALY.getDisplayCountry() + ": " + datetime);
}
}
| masud-technope/NLP2API-Replication-Package | oracle-310-code/182.java | 444 | // The first parameter is the date style, and the second is | line_comment | en | false | 390 | 13 | 444 | 13 | 469 | 13 | 444 | 13 | 530 | 13 | false | false | false | false | false | true |
135663_1 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.servlet;
import java.io.IOException;
/**
* A filter is an object that performs filtering tasks on either the request to
* a resource (a servlet or static content), or on the response from a resource,
* or both. <br>
* <br>
* Filters perform filtering in the <code>doFilter</code> method. Every Filter
* has access to a FilterConfig object from which it can obtain its
* initialization parameters, a reference to the ServletContext which it can
* use, for example, to load resources needed for filtering tasks.
* <p>
* Filters are configured in the deployment descriptor of a web application
* <p>
* Examples that have been identified for this design are<br>
* 1) Authentication Filters <br>
* 2) Logging and Auditing Filters <br>
* 3) Image conversion Filters <br>
* 4) Data compression Filters <br>
* 5) Encryption Filters <br>
* 6) Tokenizing Filters <br>
* 7) Filters that trigger resource access events <br>
* 8) XSL/T filters <br>
* 9) Mime-type chain Filter <br>
*
* @since Servlet 2.3
*/
public interface Filter {
/**
* Called by the web container to indicate to a filter that it is being
* placed into service. The servlet container calls the init method exactly
* once after instantiating the filter. The init method must complete
* successfully before the filter is asked to do any filtering work. <br>
* <br>
* The web container cannot place the filter into service if the init method
* either<br>
* 1.Throws a ServletException <br>
* 2.Does not return within a time period defined by the web container
*/
public void init(FilterConfig filterConfig) throws ServletException;
/**
* The <code>doFilter</code> method of the Filter is called by the container
* each time a request/response pair is passed through the chain due to a
* client request for a resource at the end of the chain. The FilterChain
* passed in to this method allows the Filter to pass on the request and
* response to the next entity in the chain.
* <p>
* A typical implementation of this method would follow the following
* pattern:- <br>
* 1. Examine the request<br>
* 2. Optionally wrap the request object with a custom implementation to
* filter content or headers for input filtering <br>
* 3. Optionally wrap the response object with a custom implementation to
* filter content or headers for output filtering <br>
* 4. a) <strong>Either</strong> invoke the next entity in the chain using
* the FilterChain object (<code>chain.doFilter()</code>), <br>
* 4. b) <strong>or</strong> not pass on the request/response pair to the
* next entity in the filter chain to block the request processing<br>
* 5. Directly set headers on the response after invocation of the next
* entity in the filter chain.
**/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;
/**
* Called by the web container to indicate to a filter that it is being
* taken out of service. This method is only called once all threads within
* the filter's doFilter method have exited or after a timeout period has
* passed. After the web container calls this method, it will not call the
* doFilter method again on this instance of the filter. <br>
* <br>
*
* This method gives the filter an opportunity to clean up any resources
* that are being held (for example, memory, file handles, threads) and make
* sure that any persistent state is synchronized with the filter's current
* state in memory.
*/
public void destroy();
}
| masud-technope/BLIZZARD-Replication-Package-ESEC-FSE2018 | Corpus/tomcat70/663.java | 1,058 | /**
* A filter is an object that performs filtering tasks on either the request to
* a resource (a servlet or static content), or on the response from a resource,
* or both. <br>
* <br>
* Filters perform filtering in the <code>doFilter</code> method. Every Filter
* has access to a FilterConfig object from which it can obtain its
* initialization parameters, a reference to the ServletContext which it can
* use, for example, to load resources needed for filtering tasks.
* <p>
* Filters are configured in the deployment descriptor of a web application
* <p>
* Examples that have been identified for this design are<br>
* 1) Authentication Filters <br>
* 2) Logging and Auditing Filters <br>
* 3) Image conversion Filters <br>
* 4) Data compression Filters <br>
* 5) Encryption Filters <br>
* 6) Tokenizing Filters <br>
* 7) Filters that trigger resource access events <br>
* 8) XSL/T filters <br>
* 9) Mime-type chain Filter <br>
*
* @since Servlet 2.3
*/ | block_comment | en | false | 1,031 | 248 | 1,058 | 268 | 1,096 | 265 | 1,058 | 268 | 1,177 | 284 | true | true | true | true | true | false |
136262_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 CyvasseGame;
/**
*
* @author William
*/
//bunch of ways pieces can move, for checking if the piece move is valid
public enum WayItMoves {
square,pawn,rangedpawn,spearpawn,stationary,square2x2,square3x3,flyingcastle,queen,rook,nothing
}
| MrGSHS/apcs-final-project-cyvasse | WayItMoves.java | 128 | //bunch of ways pieces can move, for checking if the piece move is valid
| line_comment | en | false | 111 | 18 | 128 | 18 | 125 | 17 | 128 | 18 | 140 | 18 | false | false | false | false | false | true |
136666_1 | /* Name: Baron Ping-Yeh Hsieh
* PennKey: bpyhsieh
* Execution: N/A, this class is meant to be used by other classes
*
* A class that represents the fish projectile in
* Furious Flying Fish. Can update its own position based
* on velocity and time, and can compute whether
* it overlaps a given Target.
*
*/
public class Fish {
// The position, velocity, and radius members of the fish.
private double xPos, yPos, xVel, yVel, radius;
/**
* How many more times the player can throw the fish
* before losing the game.
*/
private int numThrowsRemaining;
/**
* Initialize the fish's member variables
* with the same names as the inputs to those values.
* Initializes the fish's velocity components to 0.
*/
public Fish(double xPos, double yPos, double radius, int numThrowsRemaining) {
// TODO
this.xPos = xPos;
this.yPos = yPos;
this.radius = radius;
this.numThrowsRemaining = numThrowsRemaining;
xVel = 0;
yVel = 0;
}
/**
* Draws a Circle centered at the fish's position
* with a radius equal to the fish's radius.
* Additionally, draws a triangular fin and a
* circular eye somewhere on the circle to make
* the fish look more like a fish. Additional details
* are up to your discretion.
* Also draws the fish's remaining throws 0.1 units
* above its circular body.
*/
public void draw() {
PennDraw.setPenColor(PennDraw.BLUE);
PennDraw.filledCircle(xPos, yPos, radius);
PennDraw.filledPolygon(xPos, yPos, xPos - 0.3, yPos + 0.3, xPos - 0.3,
yPos - 0.3);
PennDraw.setPenColor(PennDraw.BLACK);
PennDraw.filledCircle(xPos + 0.1, yPos + 0.1, 0.03);
PennDraw.text(xPos, yPos + 0.35 , "" + numThrowsRemaining);
}
/**
* Draw the line representing the fish's initial velocity
* when the player is clicking and dragging the mouse.
*/
public void drawVelocity() {
PennDraw.line(xPos, yPos, xPos + xVel, yPos + yVel);
}
/**
* Set xPos and yPos to 1.0,
* set xVel and yVel to 0.0.
*/
public void reset() {
xPos = 1.0;
yPos = 1.0;
xVel = 0.0;
yVel = 0.0;
}
/**
* Compute the fish's initial velocity as the
* vector from the mouse's current position to
* the fish's current position. This will be used
* in mouse listening mode to update the launch
* velocity.
*/
public void setVelocityFromMousePos() {
xVel = xPos - PennDraw.mouseX();
yVel = yPos - PennDraw.mouseY();
}
/**
* Given the change in time, compute the fish's
* new position and new velocity.
*/
public void update(double timeStep) {
xPos = xPos + (xVel * timeStep);
yPos = yPos + (yVel * timeStep);
yVel = yVel - (0.25 * timeStep);
System.out.println(xPos + " " + yPos);
}
/**
* A helper function used to find the distance
* between two 2D points. Remember to use the
* Pythagorean Theorem.
*/
private static double distance(double x1, double y1, double x2, double y2) {
double pointDistance = Math.sqrt((x2 - x1) * (x2 - x1) +
(y2 - y1) * (y2 - y1));
return pointDistance;
}
/**
* Given a Target, determine if the fish should
* test for collision against it. If the fish
* *should* see if it collides with the target,
* then perform that test. If the fish collides,
* then decrease the target's HP by 1 set its
* hitThisShot field to be true.
*/
public void testAndHandleCollision(Target t) {
if (t.getHitPoints() > 0) {
if (distance(xPos, yPos, t.getXPos(), t.getYPos()) < (radius +
t.getRadius())) {
t.setHitThisShot(true);
}
}
}
// Reduce numThrowsRemaining by 1.
public void decrementThrows() {
numThrowsRemaining--;
}
/**
* Getter functions that return a copy
* of the indicated member variable.
*/
public double getXpos() {
return xPos;
}
public double getYpos() {
return yPos;
}
public double getRadius() {
return radius;
}
public int getNumThrowsRemaining() {
return numThrowsRemaining;
}
}
| baronhsieh2005/FuriousFish | Fish.java | 1,219 | // The position, velocity, and radius members of the fish. | line_comment | en | false | 1,140 | 13 | 1,219 | 13 | 1,280 | 13 | 1,219 | 13 | 1,433 | 13 | false | false | false | false | false | true |
138874_2 | public class Role implements Comparable<Role>{
public final String name;
public final int rank;
public final String catchPhrase;
public final int roleType; //1 is on 2 is off
private Player player;
private int x;
private int y;
public Role(String name, int rank, String catchPhrase, int roleType, int x, int y) {
this.name = name;
this.rank = rank;
this.roleType = roleType;
this.catchPhrase = catchPhrase;
this.x = x;
this.y = y;
player = null;
}
//public getters and setters
public boolean isOccupied() {
if (player == null) return false;
return true;
}
public void giveRole(Player p) {
this.player = p;
}
//Role type of true = on the card, false = off the card
public int getroleType() {
return roleType;
}
public Player getPlayer() {
return this.player;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
//resets so that no player is on role
public void reset() {
this.player = null;
}
/*This method is called only for on card roles.
* When the card is placed on a set, the position of the role
* must set relative to the set coordinates. This method adds the origin to the pre existing coordinates.
*/
public void overridePosition(int xbase, int ybase) {
this.x += xbase;
this.y += ybase;
}
//Allows implementation of comparable and Collections utility usage
@Override public int compareTo(Role r) {
return r.rank-this.rank;
}
}
| Noah-Stull/deadwoodCSCI345 | Role.java | 407 | //Role type of true = on the card, false = off the card | line_comment | en | false | 388 | 15 | 407 | 15 | 455 | 15 | 407 | 15 | 482 | 15 | false | false | false | false | false | true |
139312_5 | // 2022.06.22
// Problem Statement:
// https://leetcode.com/problems/gas-station/
// idea: https://leetcode.com/problems/gas-station/discuss/1706142/JavaC%2B%2BPython-An-explanation-that-ever-EXISTS-till-now!!!!
// if starts at x1 and out of gas at x2, all stations between x1 and x2 (inclusive)
// are not good start points, should search to x2+1
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int answer = 0; // possible start point move from beginning to end
while (answer<gas.length) {
int curr_gas = 0;
boolean should_continue = true;
for (int i=answer; i<gas.length; i++) {
curr_gas += gas[i]-cost[i];
if (curr_gas<0) {
answer = i+1; // move possible start point to x2+1
should_continue = false;
break;
}
}
if (should_continue) {
for (int i=0; i<answer; i++) {
curr_gas += gas[i]-cost[i];
if (curr_gas<0) { // 0 to start point doesn't work, then no solution,
// as the start point will only move forward,
// the journey between 0 to start point can not be avoided
return -1;
}
}
return answer;
}
}
return -1;
}
} | ljn1999/LeetCode-problems | Amazon/q134.java | 371 | // are not good start points, should search to x2+1 | line_comment | en | false | 345 | 14 | 371 | 14 | 397 | 14 | 371 | 14 | 425 | 14 | false | false | false | false | false | true |
139376_1 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.company.dao;
import com.company.model.Patient;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
*
* @author Sahan Dharmarathna
*/
public class PatientDAO extends PersonDAO{
//Defining logger
private static final Logger LOGGER = Logger.getLogger(PatientDAO.class.getName());
//Initializing the arraylist
private static List<Patient> patients = new ArrayList<>();
//Defining the details static block
static{
patients.add(new Patient(1, "Kamal", "0716521830", "258/A Dope,Bentota", "Having Sugar", "Normal"));
patients.add(new Patient(2, "Piyal", "0718989890", "238/A Colombo,Fort", "Having Pressure", "Good"));
patients.add(new Patient(3, "Namal", "0775505500", "248/A Galle,Fort", "Having Fever", "Low"));
}
//Create Operation
public void createPatient(Patient patient){
patients.add(patient);
super.createPerson(patient);
}
//Read Operation for all patients.
public List<Patient> getAllPatients(){
//return new ArrayList<>(patients);
return patients;
}
//Read Operation for each patients.
public Patient getPatientById(int id){
for(Patient patient : patients){
if(patient.getId() == id){
return patient;
}
}
return null;
}
//Update Operation
public void updatePetient(Patient updatedPatient){
for(int i = 0; i < patients.size(); i++){
Patient patient =patients.get(i);
if(patient.getId() == updatedPatient.getId()){
patients.set(i, updatedPatient);
System.out.println("Person is updated: " + updatedPatient);
LOGGER.info("Patient is updated.");
return;
}
}
LOGGER.severe("There is no patient with this id to update: " + updatedPatient.getId());
throw new RuntimeException("There is no patient with this id to update: " + updatedPatient.getId());
}
//Delete Operation
public void deletePatient(int id){
patients.removeIf(patient -> patient.getId() == id);
LOGGER.info("Patient is deleted.");
}
}
| SahanVimukthiDharmarathne/Healthcare-ManagerAPI | dao/PatientDAO.java | 617 | /**
*
* @author Sahan Dharmarathna
*/ | block_comment | en | false | 552 | 14 | 617 | 16 | 668 | 15 | 617 | 16 | 751 | 16 | false | false | false | false | false | true |
139430_2 | package diet;
import java.util.*;
/**
* Represents a takeaway restaurant chain.
* It allows managing restaurants, customers, and orders.
*/
public class Takeaway {
Food f;
SortedMap<String,Restaurant> dizRes = new TreeMap<>();
List<Customer> listaClienti = new ArrayList<>();
List<Order> listaOrdini = new ArrayList<>();
public Takeaway(Food food){
f = food;
}
/**
* Creates a new restaurant with a given name
*
* @param restaurantName name of the restaurant
* @return the new restaurant
*/
public Restaurant addRestaurant(String restaurantName) {
Restaurant r = new Restaurant(restaurantName,listaOrdini);
dizRes.put(restaurantName, r);
return r;
}
public Collection<String> restaurants() {
return dizRes.keySet();
}
public Customer registerCustomer(String firstName, String lastName, String email, String phoneNumber) {
Customer c = new Customer(firstName,lastName);
c.SetEmail(email);
c.setPhone(phoneNumber);
listaClienti.add(c);
return c;
}
public Collection<Customer> customers(){
Comparator<Customer> bySurname = Comparator.comparing(Customer::getLastName);
Comparator<Customer> byName = Comparator.comparing(Customer::getFirstName);
Collections.sort(listaClienti, bySurname.thenComparing(byName));
return listaClienti;
}
public Order createOrder(Customer customer, String restaurantName, String time) {
Order o = new Order(customer,restaurantName,time,dizRes.get(restaurantName).orari);
listaOrdini.add(o);
return o;
}
/**
* Find all restaurants that are open at a given time.
*
* @param time the time with format {@code "HH:MM"}
* @return the sorted collection of restaurants
*/
public Collection<Restaurant> openRestaurants(String time){
int i=0;
String ricorda="";
List<Restaurant> listaAperti= new ArrayList<>();
for (String key : dizRes.keySet()) {
for (String orario : dizRes.get(key).orari) {
if(i%2!=0) {
if(ricorda.compareTo(time)<=0 && orario.compareTo(time)>=0) {
listaAperti.add(dizRes.get(key));
}
i+=1;
}
else {
ricorda=orario;
i+=1;
}
}
}
return listaAperti;
}
}
| ciccioconf01/LAB_Programmazione_Oggetti | lab3/diet/Takeaway.java | 660 | /**
* Find all restaurants that are open at a given time.
*
* @param time the time with format {@code "HH:MM"}
* @return the sorted collection of restaurants
*/ | block_comment | en | false | 544 | 44 | 660 | 45 | 646 | 48 | 660 | 45 | 809 | 50 | false | false | false | false | false | true |
139816_8 | import java.io.Serializable;
/**
* Abstraction of a determined Wine. Every wine has a name, a producer, the year
* of production, some notes that may be useful for the customers, a string
* containing all the grapes used in each wine, the quantity in stock of each
* wine.
*/
public class Wine implements Serializable {
private static final long serialVersionUID = 1727284212719259730L;
private String name;
private int productId;
private String producer;
private int year;
private String notes;
private int quantity;
private String grapes;
/**
* {@code Wine} class constructor.
*/
public Wine() {
this.name = "";
this.producer = "";
this.productId = -1;
this.year = -1;
this.notes = "";
this.grapes = "";
this.quantity = -1;
}
/**
* {@code Wine} class constructor.
*
* @param id product id of the {@code Wine}.[int]
* @param name name of the {@code Wine}. [String]
* @param producer producer of the {@code Wine}. [String]
* @param year year of production of the {@code Wine}. [int]
* @param notes notes for the {@code Wine}. [String]
* @param quantity quantity of the {@code Wine}. [int]
* @param grapes list of the grapes of the {@code Wine}. [String]
*/
public Wine(final int id, final String name, final String producer, final int year, final String notes,
final int quantity, final String grapes) {
this.name = name;
this.producer = producer;
this.year = year;
this.notes = notes;
this.productId = id;
this.quantity = quantity;
this.grapes = grapes;
}
/**
* Gets the name of the {@code Wine}.
*
* @return the name of the {@code Wine}. [String]
*/
public String getName() {
return this.name;
}
/**
* Gets the producer of the {@code Wine}.
*
* @return the producer of the {@code Wine}. [String]
*/
public String getProducer() {
return this.producer;
}
/**
* Gets the name of the {@code Wine}.
*
* @return the name of the {@code Wine}. [String]
*/
public int getYear() {
return this.year;
}
/**
* Gets the notes of the {@code Wine}.
*
* @return the notes of the {@code Wine}. [String]
*/
public String getNotes() {
return this.notes;
}
/**
* Gets the quantity of the {@code Wine}.
*
* @return the quantity of the {@code Wine}. [int]
*/
public int getQuantity() {
return this.quantity;
}
/**
* Gets the grapes of the {@code Wine}.
*
* @return the grapes of the {@code Wine}. [String]
*/
public String getGrapewines() {
return this.grapes;
}
/**
* Gets the product id of the {@code Wine}.
*
* @return the product id of the {@code Wine}. [int]
*/
public int getProductId() {
return this.productId;
}
} | Sclafus/Ecommerce-GUI | src/Wine.java | 865 | /**
* Gets the grapes of the {@code Wine}.
*
* @return the grapes of the {@code Wine}. [String]
*/ | block_comment | en | false | 729 | 32 | 865 | 37 | 868 | 36 | 865 | 37 | 975 | 43 | false | false | false | false | false | true |
140053_8 | /**
* User node class that could receive message sent from server and make voting
* decisions
*/
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
public class UserNode implements ProjectLib.MessageHandling {
public final String myId;
private static ProjectLib PL = null;
private static List<String> dirty = new ArrayList<String>();
private static final Object checkFile = new Object();
private static final Object writeLog = new Object();
public static File log;
private static FileWriter fWriter;
private static BufferedWriter writer;
private static FileReader fReader;
private static BufferedReader reader;
private static Map<String, String>logMap = new ConcurrentHashMap<String, String>();
public UserNode( String id ) {
myId = id;
}
/**
* callback function that delivers the message from the message queue
* @param ProjectLib.Message msg
* @return boolean
*/
public boolean deliverMessage( ProjectLib.Message msg ) {
try{
CommitMessage commitMsg = CommitMessage.parseMessage(msg);
if (commitMsg.type.equals("vote")){
boolean result = vote(commitMsg);
voteResponse(result, commitMsg.filename);
} else if (commitMsg.type.equals("commit") || commitMsg.type.equals("abort")){
commit(commitMsg);
}
} catch (Exception e) {
System.err.println("Exception " + e.getMessage());
return false;
}
return true;
}
/**
* make vote decisions. If a source could be used to construct the collage,
* it should be marked as dirty and write it to log.
* @param CommitMessage msg
* @return boolean
*/
public synchronized boolean vote(CommitMessage msg) throws IOException{
List<String> srcFilename = msg.srcFilename;
String[] sources = srcFilename.toArray(new String[srcFilename.size()]);
if (!PL.askUser(msg.img, sources)) return false;
for (int i = 0; i < sources.length; i++) {
String curFile = sources[i];
File f = new File(curFile);
if (dirty.contains(curFile) || !f.exists()) {
return false;
}
}
for (int i = 0; i < sources.length; i++) {
dirty.add(sources[i]); // add sources to dirty if vote reply is true
fWriter = new FileWriter(log, true);
writer = new BufferedWriter(fWriter);
fWriter.write(sources[i] +":yes\n");
writer.close();
fWriter.close();
PL.fsync();
}
return true;
}
/**
* send back the vote decision to server
* @param boolean result
* @param String filename
*/
public void voteResponse(boolean result, String filename) throws IOException{
String res;
List<String> tmpList = new ArrayList<String>();
byte[] tmpImg = new byte[0];
if (result) res = "yes";
else res = "no";
CommitMessage response = new CommitMessage(res, myId, tmpList, tmpImg, filename);
byte[] msgBytes = CommitMessage.makeMessage(response);
ProjectLib.Message msgToSend = new ProjectLib.Message("Server", msgBytes);
PL.sendMessage(msgToSend);
}
/**
* receive commit decision from the server. If server commits, the source
* files should be deleted from the directory; if server aborts, should
* unmark the dirty sources. Write the commit decision to log. Send an ACK
* message back to server.
* @param CommitMessage msg
*/
public synchronized void commit(CommitMessage msg) {
String[] sources = msg.srcFilename.toArray(new String[msg.srcFilename.size()]);
try {
String type;
for (int i = 0; i < sources.length; i++) {
if (msg.type.equals("commit")) { // delete the dirty files if commmit
type = "commit";
Path source = Paths.get(sources[i]);
Files.deleteIfExists(source);
} else type = "abort";
if (dirty.contains(sources[i])) {
dirty.remove(sources[i]);
}
fWriter = new FileWriter(log, true);
writer = new BufferedWriter(fWriter);
fWriter.write(sources[i] + ":" + type + "\n");
writer.close();
fWriter.close();
PL.fsync();
}
List<String> tmpList = new ArrayList<String>();
byte[] tmpImg = new byte[0];
CommitMessage response = new CommitMessage("ACK", myId, tmpList, tmpImg, msg.filename);
byte[] msgBytes = CommitMessage.makeMessage(response);
ProjectLib.Message msgToSend = new ProjectLib.Message("Server", msgBytes);
PL.sendMessage(msgToSend);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
/**
* read the log text and recover the previous procedures based on the log
* file.
* @param String id
*/
public static void recover(String id) throws IOException{
log = new File("LOG.txt");
if (log.exists()) {
fReader = new FileReader(log);
reader = new BufferedReader(fReader);
String line = reader.readLine();
while (line != null) {
String[] parts = line.split(":");
if (parts[1].equals("yes")) logMap.put(parts[0], "voted");
else logMap.put(parts[0], parts[-1]);
line = reader.readLine();
}
for (Map.Entry<String, String> entry : logMap.entrySet()) {
String srcFilename = entry.getKey();
String type = entry.getValue();
if (type.equals("voted")) dirty.add(srcFilename);
}
}
}
/**
* main function that runs each usernode
* @param String args[]
*/
public static void main ( String args[] ) throws Exception {
if (args.length != 2) throw new Exception("Need 2 args: <port> <id>");
recover(args[1]);
UserNode UN = new UserNode(args[1]);
PL = new ProjectLib( Integer.parseInt(args[0]), args[1], UN );
log = new File("LOG.txt");
if (!log.exists()) log.createNewFile();
}
}
| Lynn-Sun0814/15440-p4 | UserNode.java | 1,599 | /**
* main function that runs each usernode
* @param String args[]
*/ | block_comment | en | false | 1,362 | 20 | 1,599 | 19 | 1,624 | 22 | 1,599 | 19 | 1,893 | 23 | false | false | false | false | false | true |
140408_3 | package Draw;
import java.awt.*;
import java.util.Random;
/**
* Draws a sky, including (when applicable:
* Sun
* Moon
* Stars
* Sky with colors
*
* @author Ricardo Prins
*/
public class Sky extends LandscapeObject implements SceneryCFG {
private TIME time;
private GradientPaint skyColors;
private static Random randomizer = new Random();
private boolean hasStars = false;
private boolean hasSun = false;
private boolean hasMoon = false;
/**
* Just to spare code.
*/
public class SkyGradient extends GradientPaint {
public SkyGradient(Color color1, Color color2) {
super(ORIGIN, color1, DESTINY, color2);
}
}
/**
* Primary Constructor.
* Sets all class attributes.
*
* @param g2 The Graphics2D interface.
* @return void
*/
public Sky(Graphics2D g2) {
super(g2, 0, 0, SCALE);
this.time = time;
switch (time) {
case SUNRISE -> {
skyColors = new SkyGradient(SUNRISE_BLUE, SUNRISE_YELLOW);
hasSun = true;
}
case MORNING -> {
skyColors = new SkyGradient(MORNING_BLUE_1, MORNING_BLUE_2);
hasSun = true;
}
case MIDDAY -> {
skyColors = new SkyGradient(MIDDAY_BLUE_1, MIDDAY_BLUE_2);
hasSun = true;
}
case AFTERNOON -> {
skyColors = new SkyGradient(AFTERNOON_BLUE_1, AFTERNOON_BLUE_2);
hasSun = true;
}
case SUNSET -> {
skyColors = new SkyGradient(SUNSET_YELLOW, SUNSET_ORANGE);
hasSun = true;
hasMoon = true;
}
case EVENING -> {
skyColors = new SkyGradient(EVENING_RED, EVENING_ORANGE);
hasStars = true;
hasMoon = true;
}
case NIGHT -> {
skyColors = new SkyGradient(Color.BLACK, NIGHT_BLUE);
hasStars = true;
hasMoon = true;
}
}
}
private void drawSky() {
g2.setPaint(skyColors);
g2.fillRect(0, 0, WIDTH, HEIGHT);
}
private void drawSun() {
Shape sun = null;
if (hasSun) {
g2.setColor(Color.YELLOW);
switch(time) {
case SUNRISE -> sun = new RegularPolygon((int)((WIDTH/3)*2.5),HEIGHT/3,100,99);
case MORNING -> sun = new RegularPolygon((WIDTH/3)*2,HEIGHT/5,100,99);
case MIDDAY -> sun = new RegularPolygon(WIDTH/2,HEIGHT/7,100,99);
case AFTERNOON -> sun = new RegularPolygon(WIDTH/4,HEIGHT/5,100,99);
case SUNSET -> sun = new RegularPolygon(WIDTH/5,HEIGHT/3,100,99);
}
g2.fill(sun);
}
}
private void drawMoon() {
Shape moon = null;
if (hasMoon) {
g2.setColor(Color.WHITE);
switch(time){
case SUNSET -> moon = new RegularPolygon((WIDTH/3)*2,HEIGHT/5,45,99);
case EVENING -> moon = new RegularPolygon(WIDTH/2,HEIGHT/7,60,99);
case NIGHT -> moon = new RegularPolygon(WIDTH/4,HEIGHT/3,80,99);
}
g2.fill(moon);
}
}
private void drawStars() {
if (hasStars) {
g2.setColor(Color.WHITE);
for (int i = 0; i <= 100; i++) {
Shape star = new StarPolygon(randomizer.nextInt(WIDTH), randomizer.nextInt(HEIGHT / 5), 1, 1, 5);
g2.draw(star);
}
}
}
/**
* Must be implemented in all subclasses
* Calls applyScale to apply the scale multiplier to all shape dimensions for the object.
* Draws the object
*
* @return void.
*/
@Override
public void draw() {
drawSky();
drawSun();
drawMoon();
drawStars();
}
/**
* Must be implemented in all subclasses
* Applies the scale multiplier to all shape dimensions for the object.
* Called by draw()
*/
@Override
public void applyScale() {
//Foo!
}
} | Lourievc/CS115 | Draw/Sky.java | 1,097 | /**
* Must be implemented in all subclasses
* Calls applyScale to apply the scale multiplier to all shape dimensions for the object.
* Draws the object
*
* @return void.
*/ | block_comment | en | false | 1,022 | 44 | 1,097 | 43 | 1,164 | 48 | 1,097 | 43 | 1,355 | 52 | false | false | false | false | false | true |
140654_18 |
//////////////////////////////////////////////////////////////////////
// //
// JCSP ("CSP for Java") Libraries //
// Copyright (C) 1996-2018 Peter Welch, Paul Austin and Neil Brown //
// 2001-2004 Quickstone Technologies Limited //
// 2005-2018 Kevin Chalmers //
// //
// You may use this work under the terms of either //
// 1. The Apache License, Version 2.0 //
// 2. or (at your option), the GNU Lesser General Public License, //
// version 2.1 or greater. //
// //
// Full licence texts are included in the LICENCE file with //
// this library. //
// //
// Author contacts: P.H.Welch@kent.ac.uk K.Chalmers@napier.ac.uk //
// //
//////////////////////////////////////////////////////////////////////
package jcsp.net;
import java.io.*;
/**
* <p>
* A Class whose instances represent the global domain.
* There is only ever a need to have one instance of this class
* per JVM so a static instance is supplied.
* </p>
* <p>
* The <CODE>GlobalID</CODE> object is the parent
* <CODE>AbstractID</CODE> to all top level <CODE>DomainID</CODE> objects.
* </p>
* <p>
* See <code>{@link AbstractID}</code> for a fully explanation of
* this class.
* </p>
*
*
* @author Quickstone Technologies Limited
*/
public final class GlobalID extends AbstractID implements Serializable
{
/**
* <p>
* Returns <code>null</code> as there is no parent
* <code>AbstractID</code> of instances of this class.
* </p>
* @return <code>null</code>.
*/
public AbstractID getParentID()
{
return null;
}
/**
* <p>
* Compares another object with this <CODE>GlobalID</CODE> object.
* </p>
* @param o an object to compare with object.
* @return <CODE>true</CODE> iff the other object is a <CODE>GlobalID</CODE>.
*/
public boolean equals(Object o)
{
if (o == null || !(o instanceof GlobalID))
return false;
//o is an instance of GlobalID, therefore equal
return true;
}
/**
* <p>
* Returns an <CODE>int</CODE> hash code for this object.
* </p>
* @return an <CODE>int</CODE> hash code.
*/
public int hashCode()
{
return ("GlobalID").hashCode();
}
/**
* <p>
* Returns a human readable string representation of a
* <CODE>GlobalID</CODE>.
* </p>
*
* @return The human readable <CODE>String</CODE> - currently "Global".
*/
public String toString()
{
return "Global";
}
boolean onSameBranch(AbstractID abstractID)
{
if (abstractID != null && abstractID instanceof GlobalID)
return true;
return false;
}
/**
* <p>
* A static instance of <CODE>GlobalID</CODE>.
* Instead of creating <CODE>GlobalID</CODE> objects, it
* is better to use this instance as only once instance is
* ever required.
* </p>
*
*/
public static final GlobalID instance = new GlobalID();
} | CSPforJAVA/jcsp | src/main/java/jcsp/net/GlobalID.java | 840 | /**
* <p>
* A Class whose instances represent the global domain.
* There is only ever a need to have one instance of this class
* per JVM so a static instance is supplied.
* </p>
* <p>
* The <CODE>GlobalID</CODE> object is the parent
* <CODE>AbstractID</CODE> to all top level <CODE>DomainID</CODE> objects.
* </p>
* <p>
* See <code>{@link AbstractID}</code> for a fully explanation of
* this class.
* </p>
*
*
* @author Quickstone Technologies Limited
*/ | block_comment | en | false | 791 | 130 | 838 | 143 | 903 | 142 | 840 | 143 | 959 | 145 | false | false | false | false | false | true |
141659_0 | package com.huagu.vcoin.main.dao;
import static org.hibernate.criterion.Example.create;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import com.huagu.vcoin.main.dao.comm.HibernateDaoSupport;
import com.huagu.vcoin.main.model.Ffees;
/**
* A data access object (DAO) providing persistence and search support for Ffees
* entities. Transaction control of the save(), update() and delete() operations
* can directly support Spring container-managed transactions or they can be
* augmented to handle user-managed Spring transactions. Each of these methods
* provides additional information for how to configure it for the desired type
* of transaction control.
*
* @see ztmp.Ffees
* @author MyEclipse Persistence Tools
*/
@Repository
public class FfeesDAO extends HibernateDaoSupport {
private static final Logger log = LoggerFactory.getLogger(FfeesDAO.class);
// property constants
public static final String FFEE = "ffee";
public void save(Ffees transientInstance) {
log.debug("saving Ffees instance");
try {
getSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(Ffees persistentInstance) {
log.debug("deleting Ffees instance");
try {
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Ffees findById(java.lang.Integer id) {
log.debug("getting Ffees instance with id: " + id);
try {
Ffees instance = (Ffees) getSession().get("com.huagu.vcoin.main.model.Ffees", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List<Ffees> findByExample(Ffees instance) {
log.debug("finding Ffees instance by example");
try {
List<Ffees> results = getSession().createCriteria("com.huagu.vcoin.main.model.Ffees").add(create(instance))
.list();
log.debug("find by example successful, result size: " + results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding Ffees instance with property: " + propertyName + ", value: " + value);
try {
String queryString = "from Ffees as model where model." + propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List<Ffees> findByFfee(Object ffee) {
return findByProperty(FFEE, ffee);
}
public List findAll() {
log.debug("finding all Ffees instances");
try {
String queryString = "from Ffees";
Query queryObject = getSession().createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public Ffees merge(Ffees detachedInstance) {
log.debug("merging Ffees instance");
try {
Ffees result = (Ffees) getSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(Ffees instance) {
log.debug("attaching dirty Ffees instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(Ffees instance) {
log.debug("attaching clean Ffees instance");
try {
getSession().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public List<Ffees> list(int firstResult, int maxResults, String filter, boolean isFY) {
List<Ffees> list = null;
log.debug("finding Ffees instance with filter");
try {
String queryString = "from Ffees " + filter;
Query queryObject = getSession().createQuery(queryString);
queryObject.setCacheable(true);
if (isFY) {
queryObject.setFirstResult(firstResult);
queryObject.setMaxResults(maxResults);
}
list = queryObject.list();
} catch (RuntimeException re) {
log.error("find Ffees by filter name failed", re);
throw re;
}
return list;
}
public Ffees findFfee(int tradeMappingID, int level) {
log.debug("findFfee all Ffees instances");
try {
String queryString = "from Ffees where ftrademapping.fid=? and flevel=?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, tradeMappingID);
queryObject.setParameter(1, level);
return (Ffees) queryObject.list().get(0);
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
} | biecology/dpom | FfeesDAO.java | 1,372 | /**
* A data access object (DAO) providing persistence and search support for Ffees
* entities. Transaction control of the save(), update() and delete() operations
* can directly support Spring container-managed transactions or they can be
* augmented to handle user-managed Spring transactions. Each of these methods
* provides additional information for how to configure it for the desired type
* of transaction control.
*
* @see ztmp.Ffees
* @author MyEclipse Persistence Tools
*/ | block_comment | en | false | 1,260 | 104 | 1,372 | 106 | 1,516 | 112 | 1,372 | 106 | 1,668 | 121 | false | false | false | false | false | true |
141833_6 | import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Scanner;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class MAC {
public static void main(String[] args)
throws NoSuchAlgorithmException, InvalidKeyException {
// Message to be authenticated
Scanner sc = new Scanner(System.in);
System.out.print("Enter Message: ");
String message = sc.nextLine();
// Generate a random key
byte[] key = generateKey();
// Create SecretKeySpec object
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "HmacSHA256");
// Create Mac object
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(secretKeySpec);
// Calculate MAC and convert to hex string
byte[] macBytes = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
String macString = bytesToHex(macBytes);
System.out.println("Original message: " + message);
System.out.println("Generated MAC (hex): " + macString);
// Simulate tampering with the message
System.out.print(
"Enter the tampering you want to add to the code (Enter if none): "
);
message = message + sc.nextLine();
sc.close();
// Recalculate MAC and verify
mac.update(message.getBytes(StandardCharsets.UTF_8));
byte[] newMacBytes = mac.doFinal();
String newMacString = bytesToHex(newMacBytes);
if (macString.equals(newMacString)) {
System.out.println("Message verified as authentic.");
} else {
System.out.println("Message has been tampered with!");
}
}
private static byte[] generateKey() {
byte[] keyBytes = new byte[32];
SecureRandom random = new SecureRandom();
random.nextBytes(keyBytes);
return keyBytes;
}
private static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b & 0xFF));
}
return sb.toString();
}
}
| nithinramkalava/CryptographyNetworkSecurity | MAC.java | 498 | // Recalculate MAC and verify | line_comment | en | false | 445 | 6 | 498 | 6 | 538 | 7 | 498 | 6 | 591 | 8 | false | false | false | false | false | true |
142198_9 | public class Main {
public static void main(String[] args) {
// NOTE: This code has errors in it and WILL NOT COMPILE
// Setting variables for examples
int a = 5;
double b = 3.14;
String x = "3.95";
String y = "185";
// I: Numbers in string concatenation
String text = "The value of a is " + a;
System.out.println(text);
// II: Error in direct type conversion
String val = b; // Can't convert types
// III: Convert using the base value type's toString() method
String rate = Double.toString(b);
System.out.println(rate);
// IV: Parse (Convert) a string to a number
double piValue = Double.parseDouble(x);
int qty = Integer.parseInt(y);
double price = Double.parseDouble("$2.50"); // Generates an error
// V: Casting values
double foo = 3.00;
int bar = foo; // No cast, generates an error
int baz = (int) foo; // With cast
// VI: Casting issues
int value1 = 2, value2 = 5;
float quotient;
//// without casting:
quotient = value2 / value1;
System.out.println(quotient); // 2.0
//// with improper casting:
quotient = (float)(value2 / value1);
System.out.println(quotient); // 2.0
//// with proper casting:
quotient = (float)value2 / (float)value1;
System.out.println(quotient); // 2.5
}
} | sfdesigner/APCompSci-Sprint20 | Main.java | 385 | // No cast, generates an error
| line_comment | en | false | 369 | 8 | 385 | 8 | 457 | 8 | 385 | 8 | 478 | 8 | false | false | false | false | false | true |
142390_11 | import java.util.*;
import java.awt.*;
import javax.swing.*;
/* creates and manages tower production and upgrades */
class Player{
private int money = 500;
private int MX,MY,MB, mapMX, mapMY, tx, ty, tb, mapTX, mapTY;
private GUI gui;
private boolean selecting; // is the player currently selecting anything
private boolean alive = true; // is the player alive
public Player( GUI gui ){
this.gui = gui;
}
public void updateMouse(int[] mP, int b, int [] convertedMP){
tb = MB; // previous mouse click
MX = mP[0]; // new mouse position
MY = mP[1];
mapMX = convertedMP[0]; // where on the map was it clicked
mapMY = convertedMP[1];
MB = b; // new mouse click
}
public void addMoney( int n){
money += n;
if (money < 0){
alive = false;
}
}
public boolean getAlive(){return alive;}
public void build(Cell[][] grid,HashMap<String,Tower> buildSet,String name,LinkedList<Tower>towers){
// build a tower on the map based on specific conditions
// the mouse has to be pressed and the tower has to be affordable
if ( MB == 1 && tb == 0 && MX > 128 && gui.getVisible("main") && name != null && money >= Global.towerCost ){
double locX = (int)(mapMX/Global.MAX_SIZE)*Global.MAX_SIZE;
double locY = (int)(mapMY/Global.MAX_SIZE)*Global.MAX_SIZE;
int tileX = mapMX/Global.MAX_SIZE;
int tileY = mapMY/Global.MAX_SIZE;
locX += Global.MAX_SIZE/2;
locY += Global.MAX_SIZE/2;
if(tileX >= 0 && tileX < Global.TILE_AMOUNT && tileY >= 0 && tileY < Global.TILE_AMOUNT){
if (checkAroundCell(grid,tileX,tileY)){
money -= Global.towerCost;
buildSet.get(name).produce((double)locX,(double)locY);
}
}
}
}
public boolean checkAroundCell(Cell[][] grid, int cellX, int cellY ){
/* before a tower can be built, the area around the tower must be almost clear.
* Only one tower can be around the new tower*/
int numberOfBlockedCells = 0;
int[][] checks = {{0,0},{0,1},{0,-1},{1,0},{-1,0},{1,1},{-1,-1},{-1,1},{1,-1}};
if(grid[cellX][cellY].getBlock() == true){
return false;
}
for(int i = 0; i < checks.length;i++){
int newCellX = cellX+checks[i][0];
int newCellY = cellY+checks[i][1];
if ( newCellX >= 0 && newCellX < Global.TILE_AMOUNT && newCellY >= 0 && newCellY < Global.TILE_AMOUNT ){
if(grid[newCellX][newCellY].getBlock() == true || grid[newCellX][newCellY].getSize() != 0){
numberOfBlockedCells++;
}
}
}
if(numberOfBlockedCells < 2){return true;}
else{return false;}
}
LinkedList<Tower> selected = new LinkedList<Tower>();
public void selection(LinkedList<Tower> choices){
double [] tmp = { mapTX,mapTY,mapMX-mapTX,mapMY-mapTY }; // create a rectangle
normalize(tmp); // fix the rectangle if it has negative width or height
tmp[2] += tmp[0]; // change the width and height to coordintes
tmp[3] += tmp[1];
for(Tower i: choices){
if(i.check_if_in_Box(tmp)){
i.highlight();
selected.add(i);
}
}
if(selected.size() > 0){ // if some units are selected, bring up the upgrade menu
gui.setVisible("upgrades",true);
gui.setVisible("main",false);
gui.deactivate("main");
}
}
public void upgradeSelection(){ // upgrade the units based on what the user clicked in the "upgrade" menu
if(selected.size() > 0 && MB == 1 && tb == 0 && gui.getVisible("upgrades") && money >= Global.upgradeCost*selected.size()){
String name = gui.getActiveButtonName("upgrades"); // get the current active button
if(name != null){
if( name.equals("+10% attack") ){
for( Unit i: selected){
i.multiplyAP(1.1);
}
}
else if( name.equals("+10% range") ){
for( Unit i: selected){
i.multiplyRange(1.1);
}
}
else if( name.equals("+1 weapon") ){
for(Unit i: selected ){
i.nextLevel();
}
}
else if( name.equals("+10% damage radius") ){
for( Unit i: selected ){
i.multiplyDamageRadius(1.1);
}
}
money -= Global.upgradeCost*selected.size();
}
}
}
public void highlight(LinkedList<Tower>choices){
if ( MB == 2){
gui.reset();
}
if ( MB == 0 && selecting == false ){
tx = MX;
ty = MY;
mapTX = mapMX;
mapTY = mapMY;
}
else if(MB == 0 && selecting == true){
this.selecting = false;
selection(choices);
}
else if(MB == 1 && gui.getActiveButton("main") == null ){
this.selecting = true;
if(selected.size() != 0){
for(Unit i: selected){
i.dehighlight();
}
selected.clear();
gui.setVisible("main",true);
gui.setVisible("upgrades",false);
}
}
}
public void draw(Graphics g, JFrame canvas){
g.setColor(Color.white);
int[] box = {tx,ty,MX-tx,MY-ty};
normalize(box);
if (this.selecting == true){
g.drawRect(box[0],box[1],box[2], box[3]);
}
g.setColor(Color.black);
BattleMap.statList.add(" money: "+money);
if(selected.size() != 0){
double range = 0.0;
double attack = 0.0;
double level = 0.0;
double upgradeCost = 0.0;
for(Unit i : selected){
range += i.getRange();
attack += i.getAttack();
level += i.getLevel();
}
range /= selected.size();
attack /= selected.size();
level /= selected.size();
BattleMap.statList.add(" average level: "+(int)level ) ;
BattleMap.statList.add(" average range: "+(int)range ) ;
BattleMap.statList.add(" average attack: "+(int)attack ) ;
BattleMap.statList.add(" upgrade cost: "+ Global.upgradeCost*selected.size() ) ;
}
}
public void normalize(int[] box){
if (box[2] < 0){
box[0] += box[2];
box[2]*=-1;
}
if (box[3] < 0){
box[1] += box[3];
box[3]*= -1;
}
}
public void normalize(double[] box){
if (box[2] < 0){
box[0] += box[2];
box[2]*=-1;
}
if (box[3] < 0){
box[1] += box[3];
box[3]*= -1;
}
}
public void normalizeCords (double [] box){
double temp;
if (box[2] < box[0]){
temp = box[0];
box[0] = box[2];
box[2] = temp;
}
if (box[3] < box[1]){
temp = box[1];
box[1] = box[3];
box[3] = box[1];
}
}
}
| shaon0000/Tower-Defense | Player.java | 2,145 | // fix the rectangle if it has negative width or height
| line_comment | en | false | 1,859 | 12 | 2,145 | 12 | 2,153 | 12 | 2,145 | 12 | 2,688 | 12 | false | false | false | false | false | true |
142849_0 | /*Make a function with the same return type, name of the function, number and type of
arguments in the Child class as they are in the Mother class. Change the string to be
displayed on the screen. For example, if Mother class version of show ( ) was displaying
βHello Worldβ then the child class version of show ( ) will display βHello JUETβ.*/
class Mother
{
public void show()
{
System.out.println("Hello World");
}
}
class Child extends Mother
{
public void show()
{
System.out.println("Hello JUET");
}
}
public class Main
{
public static void main(String[] args)
{
Child obj = new Child();
obj.show();
}
}
| 047pegasus/SEM-6 | AP/LAB1/2.java | 179 | /*Make a function with the same return type, name of the function, number and type of
arguments in the Child class as they are in the Mother class. Change the string to be
displayed on the screen. For example, if Mother class version of show ( ) was displaying
βHello Worldβ then the child class version of show ( ) will display βHello JUETβ.*/ | block_comment | en | false | 159 | 81 | 179 | 83 | 182 | 79 | 179 | 83 | 189 | 81 | false | false | false | false | false | true |
143345_1 | import javafx.scene.Node;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
//This class allows traffic lights on the map to be created and their colors to change.
public class TrafficLight {
private Line line;
private Circle circle;
private Pane pane;
private double startX;
private double startY;
// The traffic light consists of a circle and a line that change color when
// pressed.
public TrafficLight(double startX, double startY, double endX, double endY) {
this.startX = startX;
this.startY = startY;
line = new Line(0, 0, endX - startX, endY - startY);
line.setStrokeWidth(1);
double centerX = (startX + endX) / 2;
double centerY = (startY + endY) / 2;
circle = new Circle(centerX - startX, centerY - startY, 6);
circle.setFill(Color.LIGHTGREEN);
circle.setStroke(Color.BLACK);
circle.setOnMouseClicked(e -> {
if (circle.getFill() == Color.LIGHTGREEN) {
circle.setFill(Color.RED);
} else {
circle.setFill(Color.LIGHTGREEN);
}
});
pane = new Pane();
pane.getChildren().addAll(line, circle);
pane.setLayoutX(startX);
pane.setLayoutY(startY);
}
public Node getPane() {
return pane;
}
public Color getLightColor() {
if (circle.getFill() == Color.LIGHTGREEN) {
return Color.LIGHTGREEN;
} else {
return Color.RED;
}
}
public double getStartX() {
return startX;
}
public double getStartY() {
return startY;
}
public double getWidth() {
return circle.getRadius() * 2;
}
public double getHeight() {
return circle.getRadius() * 2;
}
} | beyzacoban/RoadRush | TrafficLight.java | 536 | // The traffic light consists of a circle and a line that change color when | line_comment | en | false | 418 | 15 | 536 | 15 | 507 | 15 | 536 | 15 | 627 | 15 | false | false | false | false | false | true |
144347_2 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Seniors class
*
* One type of human(seniors).
*
* @author (your name)
* @version (a version number or a date)
*/
public class Seniors extends Human
{
// Declare instance variable of Image.
private GreenfootImage Seniors;
/**
* Constructor for Seniors that create seniors and set initial stats.
*
* @param age Seniors' age.
* @param Health Seniors' health situation.
* @param pathway Seniors' pathway in simulation.
* @param houseX House's x-coordinate.
* @param houseY House's y-coordinate.
*/
public Seniors(int age, String Health,int[][] pathway,int houseX,int houseY){
movingSpeed=11;
setAgeRange();
setAge(age);
setHealthSituation(Health);
inFacility=false;
this.pathwayGo=Human.deepCopyPathway(pathway);
this.pathwayBack=backPathway(pathway, houseX, houseY);
}
/**
* Set the age for seniors.
*/
protected void setAge(int age){
super.age=age;
if(age>=lower_Edge_Of_Young&&age<=higher_Edge_Of_Young){
Immune_System_Strength=5;
}
else if(age>=lower_Edge_Of_Old&&age<=higher_Edge_Of_Old){
Immune_System_Strength=3;
}
}
/**
* Draw the image for seniors.
*/
public void drawImage(){
Seniors=new GreenfootImage(side_Length+1, side_Length+1);
Color Situation= ColorConversion(Health);
Seniors.setColor(Situation);
Seniors.fillOval(0,0,side_Length,side_Length);
Seniors.setColor(Color.BLACK);
Seniors.drawOval(0,0,side_Length,side_Length);
this.setImage(Seniors);
}
/**
* Set the age range for seniors.
*/
private void setAgeRange(){
super.lower_Edge_Of_Young = 65;
super.higher_Edge_Of_Young = 72;
super.lower_Edge_Of_Old = 73;
super.higher_Edge_Of_Old = 100;
}
/**
* Set seniors' schedule randomly.
*
* @param SW The world that seniors belong to.
*/
protected void scheduleDecision(SimulationWorld SW){
int random = Greenfoot.getRandomNumber(10+50+80+30);
if(random<10) {
f=SW.facility("school");
}
else if(random<10+50) {
f=SW.facility("supermarket");
}
else if(random<10+50+80) {
f=SW.facility("restaurant");
}
else if(random<10+50+80+30) {
f=SW.facility("trainStation");
}
if(f.getFacilityStatus()) stayAtHome=true;
else{
stayAtHome=false;
pathwayGo[0][pathwayGo[0].length-1]=f.getX();
pathwayGo[1][pathwayGo[1].length-1]=f.getY();
}
}
}
| Xiao215/Covid-Simulation | Seniors.java | 853 | // Declare instance variable of Image. | line_comment | en | false | 760 | 7 | 853 | 7 | 891 | 7 | 853 | 7 | 970 | 8 | false | false | false | false | false | true |
145143_4 | /**
* Class Beamer - An Beamer in an adventure game
*
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game.
*
* A "Beamer" is a type of Item that can be charged and fired.
* When the beamer is fired, it should take the player to the
* location where the beamer was charged.
*
* @Fiona Cheng (Student Number 101234672)
* @version February 21, 2023
*/
public class Beamer extends Item
{
private Room chargedRoom;
/**
* Creates a Beamer.
*/
public Beamer()
{
super("wonderful beamer", 20.1, "beamer", 250.0);
chargedRoom = null;
}
/**
* Return whether or not the beamer is charged.
*
* @return Whether or not the beamer is charged
*/
public boolean isCharged()
{
return chargedRoom != null;
}
/**
* Return the room to move to after the beamer is fired.
*
* @return location The room to move to
*/
public Room fire()
{
Room location = chargedRoom;
chargedRoom = null;
return location;
}
/**
* Charges the beamer.
* Sets the room in which the beamer was charged to "currentRoom".
*
* @param currentRoom The room in which the beamer was charged
*/
public void charge(Room currentRoom)
{
chargedRoom = currentRoom;
}
}
| Indecisive613/World-of-Zuul | Beamer.java | 391 | /**
* Charges the beamer.
* Sets the room in which the beamer was charged to "currentRoom".
*
* @param currentRoom The room in which the beamer was charged
*/ | block_comment | en | false | 371 | 46 | 391 | 47 | 418 | 50 | 391 | 47 | 443 | 55 | false | false | false | false | false | true |
145428_6 | // This file contains material supporting section 2.8 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com
package postalcode;
/**
* This class is a subclass of PostalCode used to deal with Canadian
* postal codes.
*
* @author Dr Timothy C. Lethbridge
* @author François Bélanger
* @author Paul Holden
* @version July 2014
*/
public class CanadianPostalCode extends PostalCode
{
//Constructors ****************************************************
/**
* Constructs a Canadian postal code object.
*
* @param code The code to be analysed.
*/
public CanadianPostalCode(String code) throws PostalCodeException
{
super(code);
}
//Instance methods ************************************************
/**
* Returns the country of origin of the code.
*
* @return A String containing the country of origin of the code.
*/
public String getCountry()
{
return "Canadian";
}
/**
* This method will verifiy the validity of the postal code.
*
* @throws PostalCodeException If the code is found to be invalid.
*/
protected void validate() throws PostalCodeException
{
String postCode = getCode();
// Check code format, throw an exception if it is invalid.
if ((postCode.length()== 0)
|| (!Character.isLetter(postCode.charAt(0)))
|| (!Character.isDigit(postCode.charAt(1)))
|| (!Character.isLetter(postCode.charAt(2)))
|| (!Character.isWhitespace(postCode.charAt(3)))
|| (!Character.isDigit(postCode.charAt(4)))
|| (!Character.isLetter(postCode.charAt(5)))
|| (!Character.isDigit(postCode.charAt(6)))
|| (!Character.isUpperCase(postCode.charAt(0)))
|| (!Character.isUpperCase(postCode.charAt(2)))
|| (!Character.isUpperCase(postCode.charAt(5)))
|| (postCode.length() > 7))
{
throwException("Sequence of characters not like A9A 9A9");
}
else
{
setDestination(computeDestination());
}
}
/**
* This method will return the destination of the postal code.
*
* @throws PostalCodeException If the code has an invalid letter
* to indicate a destination.
*/
private String computeDestination() throws PostalCodeException
{
char firstLetter; // first letter designates the destination
//If the postal code is valid, get its first letter
firstLetter = (char)getCode().charAt(0);
// Determine the area the postal code refers to
switch (firstLetter)
{
case 'A':
return "in Newfoundland";
case 'B':
return "in Nova Scotia";
case 'C':
return "in PEI";
case 'E':
return "in New Brunswick";
case 'G':
return "in Quebec";
case 'H':
return "in Metropolitan Montreal";
case 'J':
return "in Western Quebec";
case 'K':
return "in Eastern Ontario";
case 'L':
return "in Central Ontario";
case 'M':
return "in Metropolitan Toronto";
case 'N':
return "in Southwestern Ontario";
case 'P':
return "in Northern Ontario";
case 'R':
return "in Manitoba";
case 'S':
return "in Saskatchewan";
case 'T':
return "in Alberta";
case 'V':
return "in British Columbia";
case 'X':
return "in the Northwest Territories or Nunavut";
case 'Y':
return "in the Yukon Territories";
default:
throwException("Invalid first letter");
}
return "";
}
}
| rafi-haque/postal | postalcode/CanadianPostalCode.java | 961 | //Instance methods ************************************************ | line_comment | en | false | 851 | 4 | 961 | 6 | 992 | 7 | 961 | 6 | 1,087 | 9 | false | false | false | false | false | true |
145800_4 | /**
*
*/
package edu.wlu.cs.staufferl;
/**
* @author staufferl
* This class describes the Book On Tape child class which inherits from Media Item.
* Has unique fields author and narrator.
*
*/
public class BookOnTape extends MediaItem {
private String author;
private String narrator;
/**
* @param title
* @param isPresent
* @param playingTime
* @param copyrightYear
* @param author
* @param narrator
* Constructor for BookOnTape
*/
public BookOnTape(String title, boolean isPresent, double playingTime, int copyrightYear, String author, String narrator) {
super(title, isPresent, playingTime, copyrightYear);
this.author = author;
this.narrator = narrator;
}
/**
* @return the author
* Person who wrote the original book
*/
public String getAuthor() {
return author;
}
/**
* @return the narrator
* Person who reads the book out loud
*/
public String getNarrator() {
return narrator;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
* String representation of BookOnTape, includes all relevant fields
*/
@Override
public String toString() {
return "BookOnTape[author=" + getAuthor() + ", narrator=" + getNarrator() + ", title=" + getTitle() + ", isPresent="
+ isPresent() + ", playingTime=" + getPlayingTime() + ", copyrightYear=" + getCopyrightYear() + "]";
}
/**
* @param args
* Tester program for BookOnTape.
*/
public static void main(String[] args) {
BookOnTape myBook = new BookOnTape("The Art Forger", false, 600.00, 2012, "B.A. Shapiro", "Xe Sands");
System.out.println("Getting title: " + myBook.getTitle());
System.out.println("Getting rating: " + myBook.getAuthor());
System.out.println("Getting narrator: " + myBook.getNarrator());
System.out.println("Expect false: " + myBook.isPresent());
myBook.setStatus(true);
System.out.println("Expect true: " + myBook.isPresent());
System.out.println("Getting playing time: " + myBook.getPlayingTime());
System.out.println("Getting copyright year: " + myBook.getCopyrightYear());
System.out.println("String representation of DVD: " + myBook.toString());
}
}
| staufferl16/CompSci209 | BookOnTape.java | 651 | /**
* @return the narrator
* Person who reads the book out loud
*/ | block_comment | en | false | 555 | 20 | 651 | 21 | 639 | 21 | 651 | 21 | 734 | 22 | false | false | false | false | false | true |
145858_1 | // Zusammenarbeit: Janik Teege, Nele HΓΌsemann
import java.util.Collection;
import java.util.LinkedList;
class User {
private static int ID = 0;
protected String _username;
protected String _email;
protected final int _id;
public User(String username, String email) {
assert(username != null);
assert(email != null);
this._username = username;
this._email = email;
this._id = ID++;
}
/**
* Get the username of this user. This will never be null!
*/
public String getUsername() {
return this._username;
}
/**
* Get the email of this user. This will never be null!
*/
public String getEmail() {
return this._email;
}
/**
* returns generated ID of this user
*/
public int getID(){
return this._id;
}
}
class NotRegisteredUser extends User {
public NotRegisteredUser() {
super("Unknown", "Unknown");
}
}
class EnterpriseUser extends User {
private String _personalAssistant;
public EnterpriseUser(String username, String personalAssistant) {
super(username, "Unknown");
this._personalAssistant = personalAssistant;
}
public String getPersonalAssistant() {
return this._personalAssistant;
}
}
public class Liskov {
public static void main(String[] args) {
final Collection<User> users = new LinkedList<>();
users.add(new EnterpriseUser("enterprise-customer", "CEO"));
users.add(new User("max", "max.mustermann@mail.io"));
users.add(new NotRegisteredUser());
for (final User user : users) {
System.out.println(user.getUsername() + " (" + user.getID() + ")");
}
}
} | janikteege/Programmierparadigmen | 03_Γbung/Liskov.java | 422 | /**
* Get the username of this user. This will never be null!
*/ | block_comment | en | false | 377 | 18 | 422 | 18 | 457 | 20 | 422 | 18 | 501 | 20 | false | false | false | false | false | true |
146110_5 | package hackerrank;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class P1 {
public static void main(String[] args) {
int i = 4;
double d = 4.0;
String s = "HackerRank ";
Scanner scan = new Scanner(System.in);
int j;
double e;
String t;
/* Declare second integer, double, and String variables. */
j=scan.nextInt();
e=scan.nextDouble();
t=scan.next();
/* Read and save an integer, double, and String to your variables.*/
// Note: If you have trouble reading the entire String, please go back and review the Tutorial closely.
System.out.println(i+j);
/* Print the sum of both integer variables on a new line. */
System.out.println(d+e);
/* Print the sum of the double variables on a new line. */
System.out.println(s +
t);
/* Concatenate and print the String variables on a new line;
the 's' variable above should be printed first. */
scan.close();
}
}
| RamkiGanesh007/HashCode_HackerRank | Day3.java | 280 | /* Concatenate and print the String variables on a new line;
the 's' variable above should be printed first. */ | block_comment | en | false | 249 | 27 | 280 | 27 | 306 | 30 | 280 | 27 | 318 | 30 | false | false | false | false | false | true |
148542_12 | /*
* %Z%%W% %I%
*
* =========================================================================
* Licensed Materials - Property of IBM
* "Restricted Materials of IBM"
* (C) Copyright IBM Corp. 2011. All Rights Reserved
*
* DISCLAIMER:
* The following [enclosed] code is sample code created by IBM
* Corporation. This sample code is not part of any standard IBM product
* and is provided to you solely for the purpose of assisting you in the
* development of your applications. The code is provided 'AS IS',
* without warranty of any kind. IBM shall not be liable for any damages
* arising out of your use of the sample code, even if they have been
* advised of the possibility of such damages.
* =========================================================================
*/
package com.ibm.jzos.sample;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import com.ibm.jzos.Exec;
import com.ibm.jzos.RcException;
import com.ibm.jzos.ZUtil;
/**
* Sample program which reads all sysout data for a MvsJob (jobname and jobid),
* and writes the output to a specified Writer.
*
* The class relies on the sample REXX script "jobOutput", spawned as a child process
* via the {@link com.ibm.jzos.Exec} class.
*
* @since 2.1.0
*/
public class MvsJobOutput {
public static final String JOB_STATUS_CMD = "jobStatus";
public static final String JOB_OUTPUT_CMD = "jobOutput";
/**
* A sample main method that writes sysout output for
* a job to System.out (STDOUT).
*
* The first argument is the jobname, and the second argument
* is the jobid (JOBnnnnn).
*/
public static void main(String[] args) throws IOException {
if (args.length < 2 ) {
throw new IllegalArgumentException("Missing arguments: jobname jobid");
}
MvsJob mvsJob = new MvsJob(args[0], args[1]);
// print out the status of the job
// this will throw an exception if there is no such job
System.out.println("JOB " + mvsJob + " " + getStatus(mvsJob));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
writeJobOutput(mvsJob, writer);
writer.close();
}
/**
* Returns the job status using the TSO "status" command, which
* is invoked via the "jobStatus" REXX USS script.
*
* @return String the TSO "STATUS" command status
* @throws IOException if there was an error communicating with the child REXX script process
*/
public static String getStatus(MvsJob job) throws IOException {
Exec exec = new Exec(getStatusCommand(job), getEnvironment());
exec.run();
String line = exec.readLine();
if (line == null) throw new IOException("No output from jobStatus child process");
// close the stream which is connected
// to the stdin input of the external process
BufferedWriter wdr = exec.getStdinWriter();
wdr.close();
// slurp other output
while (exec.readLine() != null) {};
int rc = exec.getReturnCode();
if (rc != 0) {
throw new RcException("REXX 'jobStatus' process failed: " + line, rc);
}
StringTokenizer tok = new StringTokenizer(line);
if (tok.countTokens() < 3 ) {
throw new IOException("Invalid output from jobStatus child process: " + line);
}
String next = tok.nextToken();
// skip over message id
if (next.startsWith("IKJ")) {
next = tok.nextToken();
}
if (!next.equalsIgnoreCase("JOB")) {
throw new IOException("Invalid output from jobStatus child process: " + line);
}
// skip jobname(jobid)
tok.nextToken();
String answer = "";
// concat remaining words
while (tok.hasMoreTokens()) {
answer += tok.nextToken();
if (tok.hasMoreTokens()) {
answer += " ";
}
}
return answer;
}
/**
* Returns the command to be executed via Runtime.exec().
* This is the REXX script 'jobStatus' followed by the jobname and jobid.
* By default, this script needs to be present in the current PATH.
* However, if the System variable jzos.script.path is defined, it will
* be used to prefix 'jobStatus'.
*/
protected static String getStatusCommand(MvsJob job) {
String cmdPath = System.getProperty("jzos.script.path", "");
if (cmdPath.length() > 0 && !cmdPath.endsWith("/")) {
cmdPath = cmdPath + "/";
}
cmdPath = cmdPath + JOB_STATUS_CMD
+ " "
+ job.getJobname()
+ " ";
if (job.getJobid() != null) {
cmdPath = cmdPath + job.getJobid();
}
return cmdPath;
}
/**
* Writes all of the output for a given job to a writer.
* Note: this method flushes the writer, but does not close it.
* It is the caller's responsibility to close the writer.
*/
public static void writeJobOutput(MvsJob mvsJob, Writer writer) throws IOException {
Exec exec = new Exec(getJobOutputCommand(mvsJob), getEnvironment());
exec.run();
try {
String line;
while ((line = exec.readLine()) != null) {
writer.write(line);
writer.write('\n');
};
writer.flush();
}
finally {
int rc = exec.getReturnCode();
if (rc != 0) {
throw new RcException("REXX 'jobOutput' process failed", rc);
}
}
}
/**
* Returns the command to be executed via Runtime.exec().
* This is the REXX script 'jobOutput'.
* By default, this script needs to be present in the current PATH.
* However, if the System variable jzos.script.path is defined, it will be
* used to prefix 'jobOutput'.
*/
protected static String getJobOutputCommand(MvsJob mvsJob) {
String cmdPath = System.getProperty("jzos.script.path", "");
if (cmdPath.length() > 0 && !cmdPath.endsWith("/")) {
cmdPath = cmdPath + "/";
}
return cmdPath + JOB_OUTPUT_CMD
+ " "
+ mvsJob.getJobname()
+ " "
+ mvsJob.getJobid();
}
/**
* Returns the environment to use for the child process.
* This is the current environment with _BPX_SHAREAS and _BPX_SPAWN_SCRIPT
* set to "YES", so that the child process will execute in the same
* address space.
*/
protected static String[] getEnvironment() {
Properties p = ZUtil.getEnvironment();
p.put("_BPX_SHAREAS", "YES");
p.put("_BPX_SPAWN_SCRIPT", "YES");
String[] environ = new String[p.size()];
int i = 0;
for (Iterator<Object> iter = p.keySet().iterator(); iter.hasNext();) {
String key = (String)iter.next();
environ[i++] = key + "=" + p.getProperty(key);
}
return environ;
}
}
| zsystems/java-samples | MvsJobOutput.java | 1,829 | /**
* Returns the command to be executed via Runtime.exec().
* This is the REXX script 'jobStatus' followed by the jobname and jobid.
* By default, this script needs to be present in the current PATH.
* However, if the System variable jzos.script.path is defined, it will
* be used to prefix 'jobStatus'.
*/ | block_comment | en | false | 1,661 | 81 | 1,829 | 83 | 1,967 | 88 | 1,829 | 83 | 2,177 | 88 | false | false | false | false | false | true |
148907_3 |
/** This is the base class for computer player/bots.
*
*/
public abstract class Bot
{
public String playerName;
public String guestName;
public int numStartingGems;
public String gemLocations;
public String[] playerNames;
public String[] guestNames;
/**
* The game calls this method when it is your turn to get the actions you want to perform
* @param d1 the face value of dice 1
* @param d2 the face value of dice 2
* @param card1 a string that represents the actions possible for card1
* @param card2 a string that represents the actions possible for card2
* @param board a string representation of the state of the board
* @return a string with the set of actions the player chooses to take
*
* The return string should have 5 actions in it. One move action for each
* dice, the card played, and one action for each action on the played card.
* The first action in the action string should be the move corresponding to dice 1.
* The second action should be the move corresponding to dice 2.
* The third action should the the card you are going to play.
* The 4th and 5th action should be actions from the card, in any order.
* Each action should be separated by a colon :.
* Move action syntax: move,player_name,x,y
* Play card syntax: play,card1|card2
* Card action syntax:
* * move,guest_name,x,y
* * viewDeck
* * ask,guest,player (can player see guest)
* * get,red|green|yellow
*
* Example getPlayerActions("Earl of Volesworthy", "?", "get,:viewDeck", "get,yellow:ask,Remy La Rocque", "Stefano Laconi,Trudie Mudge::Lily Nesbitt::Remy La Rocque:Dr. Ashraf Najem,Buford Barnswallow:::::Viola Chung:Nadia Bwalya,Mildred Wellington,Earl of Volesworthy")
* return value of action: "move,Earl of Volesworthy,1,3:move,Buford Barnswallow,1,2:play,card1:viewDeck:get,yellow"
*/
public abstract String getPlayerActions(String d1, String d2, String card1, String card2, String board) throws Suspicion.BadActionException;
/**
* The game calls this method to inform you about the actions that each player takes
*
* @param player name of the player who did the actions
* @param d1 value of dice1
* @param d2 value of dice 2
* @param cardPlayed the face value of the card the player played
* @param board the state of the board before they performed the actions
* @param actions the action string the player sent to the game engine
*/
public abstract void reportPlayerActions(String player, String d1, String d2, String cardPlayed, String board, String actions);
public void reportPlayerActions(String player, String d1, String d2, String cardPlayed, String[] board, String actions)
{
reportPlayerActions(player, d1, d2, cardPlayed, board[4], actions);
}
/**
* The game calls this method to answer the question can player see guest?
* @param guest the name of the guest
* @param player the name of the player
* @param board the state of the board when the question was asked
* @param canSee true if player can see the guest, false otherwise
*/
public abstract void answerAsk(String guest, String player, String board, boolean canSee);
/**
* The game calls this method to inform you who is the named player on the top of the deck of NPC cards
* @param player
*/
public abstract void answerViewDeck(String player);
/**
*
* @return a string with your best guesses for each player. Format of string is player1Name,guest1Name:player2Name,guest2Name...
*/
public abstract String reportGuesses();
public String getPlayerName()
{
return playerName;
}
public String getGuestName()
{
return guestName;
}
public Bot(String playerName, String guestName, int numStartingGems, String gemLocations, String[] playerNames, String[] guestNames)
{
this.playerName= playerName;
this.guestName = guestName;
this.numStartingGems = numStartingGems;
this.gemLocations = gemLocations;
this.playerNames = playerNames;
this.guestNames = guestNames;
}
}
| juanbecerra0/cs457-suspicion | 457.deliver/Bot.java | 1,088 | /**
* The game calls this method to answer the question can player see guest?
* @param guest the name of the guest
* @param player the name of the player
* @param board the state of the board when the question was asked
* @param canSee true if player can see the guest, false otherwise
*/ | block_comment | en | false | 1,055 | 74 | 1,088 | 70 | 1,129 | 77 | 1,088 | 70 | 1,206 | 77 | false | false | false | false | false | true |
148968_7 | package taojava.labs.sorting;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
/**
* A variety of utilities to support experiments with sorting
* algorithms.
*
* @author Samuel A. Rebelsky
*/
public class ExptUtils
{
// +-----------+-------------------------------------------------------
// | Utilities |
// +-----------+
/**
* Check the result of sorting. Given an array, a known sorted version
* of the array, and a candidate sorted version of the array, determines
* if the candidate is correct. Also prints other useful log info.
*/
public static <T> void checkSorting(PrintWriter pen, T[] values, T[] sorted,
T[] candidate)
{
// Print a quick prefix so that we can see whether or not the
// sort worked.
if (Arrays.equals(sorted, candidate))
{
pen.print("OK: ");
}
else
{
pen.print("BAD: ");
} // if the sorted array does not equal the original array.
// Print the transformation for folks who like to look.
pen.println("sort(" + Arrays.toString(values) + ") => ");
pen.println(" " + Arrays.toString(candidate));
} // checkSorting
// +--------------------+----------------------------------------------
// | Simple Experiments |
// +--------------------+
/**
* A simple experiment in permutations.
*/
public static <T> void
permutationExperiment(PrintWriter pen, Sorter<T> sorter,
Comparator<T> compare, T[] sorted)
{
T[] values = sorted.clone();
Utils.permute(values);
checkSorting(pen, values, sorted, sorter.sort(values, compare));
} // permutationExperiment(PrintWriter, Sorter<T>, Comparator<T>
// +-----------------------+-------------------------------------------
// | Groups of Experiments |
// +-----------------------+
/**
* Run some experiments using an integer sorter.
*/
public static void iExperiments(Sorter<Integer> sorter)
{
PrintWriter pen = new PrintWriter(System.out, true);
Integer[] vals1 = new Integer[] { 1, 2, 2, 2, 4, 5, 7, 7, 11, 13 };
// A case that's proven problematic. (Why is it problematic? Because
// people sometimes screw up double values and an element at the end of
// the array.)
Integer[] vals2 = new Integer[] { 1, 1, 2, 3, 4, 5, 7, 9, 11, 13, 13, 0 };
checkSorting(pen, vals2, new Integer[] { 0, 1, 1, 2, 3, 4, 5, 7, 9, 11, 13,
13 },
sorter.sort(vals2, StandardIntegerComparator.COMPARATOR));
// Five random permutation experiments seems like enough.
for (int i = 0; i < 5; i++)
{
permutationExperiment(pen, sorter,
StandardIntegerComparator.COMPARATOR, vals1);
} // for
// A permutation experiment with different sizes
for (int i = 1; i < 5; i++)
{
permutationExperiment(pen, sorter,
StandardIntegerComparator.COMPARATOR,
Utils.randomSortedInts(i * 10));
} // for
} // experiments(Sorter<Integer>)
/**
* Run some experiments using a string sorter.
*/
public static void sExperiments(Sorter<String> sorter)
{
PrintWriter pen = new PrintWriter(System.out, true);
String[] vals1 =
new String[] { "a", "b", "b", "f", "g", "g", "w", "x", "y", "z", "z",
"z" };
// Five random permutation experiments seems like enough
for (int i = 0; i < 5; i++)
{
permutationExperiment(pen, sorter, StandardStringComparator.COMPARATOR,
vals1);
} // for
} // experiments(Sorter<String>)
} // class ExptUtils
| joshluisaac/javasorting | ExptUtils.java | 961 | // if the sorted array does not equal the original array. | line_comment | en | false | 914 | 12 | 961 | 12 | 1,030 | 12 | 961 | 12 | 1,146 | 12 | false | false | false | false | false | true |
150267_5 | //**********************************************************************
// ITC 115 - Assignment 11 - ch9 Ex2&3 - Janitor and HarvardLawyer
//
// Add Janitor and HarvardLawyer classes to law firm employees, that
// interact with the superclass. Recreated from previous exercises to
// have Employee class be abstract, and to include more superclass
// interaction.
//
// By: Mike Gilson
// Date: 3/16/2020
//**********************************************************************
import java.text.*; // for using the NumberFormat Class
public abstract class Employee {
// Getters-Accessors for base employee information: Hours, Salary, Vacation Days, and Form Type
public double getHours() {
return 40.00;
} // end getHours
public double getSalary() {
return 40000.00;
} // end getSalary
public int getVacation() {
return 10;
} // end getVacation
public String getVacationForm() {
return "yellow";
} // end getVacationForm
// Generic information for displaying all employee information, with new lines
// for each category and tabs for display readability
public String info() {
return "\n\tSalary: " +getPriceFormatted() + "\n\tHours per week: " + getHours() + "\n\tVacation days: " + getVacation()
+ " (Use " + getVacationForm() + " form)\n";
} // end info
// Borrowing the PriceFormatted method for displaying Salary info properly
public String getPriceFormatted() {
String formattedPrice = NumberFormat.getCurrencyInstance().format(this.getSalary());
return formattedPrice;
}
} // end Employee class
| ZenSorcere/ITC115-Java-EmployeeAbstract | EmpAbst/src/Employee.java | 448 | // have Employee class be abstract, and to include more superclass
| line_comment | en | false | 391 | 14 | 448 | 14 | 465 | 15 | 448 | 14 | 524 | 15 | false | false | false | false | false | true |
150515_7 | import java.util.List;
/** A principal class which extends the Staff class, that creates a new principal, and also contains a list
* of teachers and the nonAcademic staff, thereby allowing the principal to add
* and remove both teachers and non-academic staff
*/
public class Principal extends Staff{
List<Teacher> teachers;
List<NonAcademic> nonAcademics;
public Principal(String name, String idColour, boolean hasParkingSpace, List<Teacher> teachers, List<NonAcademic> nonAcademics) {
super(name, idColour, hasParkingSpace);
this.teachers = teachers;
this.nonAcademics = nonAcademics;
}
/**
* A constructor for the principal object
* @param name name of the principal
* @param teachers contains the list of the teachers
* @param nonAcademics list of all non-academic staff in the school
*/
public Principal(String name, List<Teacher> teachers, List<NonAcademic> nonAcademics) {
this(name,"Green",true,teachers,nonAcademics);
super.setName(name);
// super.setIdColour("Green");
// super.setHasParkingSpace(true);
// this.teachers = teachers;
// this.nonAcademics = nonAcademics;
}
/**
*
* @return returns the list of the all the teachers
*/
public List<Teacher> getTeacher() {
return teachers;
}
/**
* This is an add new teacher method that takes in a new object of teacher in form of teacher
* as the param and adds it to the existing list of teachers
* @param teacher teacher object -> new Teacher
*/
public void addNewTeacher(Teacher teacher) {
this.teachers.add(teacher);
}
/**
*
* @return returns the list of nonAcademics staff
*/
public List<NonAcademic> getNonAcademics() {
return nonAcademics;
}
/**
* This is an add new non-academic staff method that takes in a new object of a nonacademic in form of nonacademic
* as the param and adds it to the existing list of non-academic staff
* @param nonAcademic teacher object -> new Teacher
*/
public void addNewNonAcademic(NonAcademic nonAcademic){
this.nonAcademics.add(nonAcademic);
}
/**
*This sack method takes in a parameter of the teachers name to be sacked and removes it
* from the list
* @param name name of the teacher to be sacked
*/
public void sackTeacher(String name) {
for (int i = 0; i < teachers.size(); i++) {
if (teachers.get(i).getName().equals(name)) {
this.teachers.remove(i);
System.out.println(name + " successfully sacked");
}
}
}
/**
*This sack method takes in a parameter of the non academic staff name to be sacked and removes it
* from the list
* @param name name of the non-academic staff to be sacked
*/
public void sackNonAcademics (String name){
for (int i = 0; i < nonAcademics.size(); i++) {
if (nonAcademics.get(i).getName().equals(name)) {
this.nonAcademics.remove(i);
System.out.println(name + " successfully sacked");
}
}
}
/**
*
* @return returns a string representation of the principal
*/
@Override
public String toString() {
return "The principal of the school is: "+ super.getName() + "\n\t" +
"IdColour: " + super.getIdColour() +
"\t\thasParkingSpace=" + super.getHasParkingSpace();
}
/**
* This method is called ny the principal to print all the staff present in the school including the principal
*/
public void printAllStaff(){
System.out.println(toString());
System.out.println("\nTeachers in the school are:");
for (int i = 0; i<teachers.size();i++){
System.out.println(teachers.get(i));
}
System.out.println("\nNon-Academic Staffs in the school are:");
for (int i = 0; i< nonAcademics.size(); i++){
System.out.println(nonAcademics.get(i));
}
}
}
| tolulonge/School-Project | src/Principal.java | 1,077 | /**
* This is an add new teacher method that takes in a new object of teacher in form of teacher
* as the param and adds it to the existing list of teachers
* @param teacher teacher object -> new Teacher
*/ | block_comment | en | false | 964 | 51 | 1,077 | 50 | 1,053 | 52 | 1,077 | 50 | 1,234 | 53 | false | false | false | false | false | true |
150550_5 | /**
* $Revision$
* $Date$
*
* Copyright 2003-2007 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.workgroup.packet;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* Represents the conversation transcript that occured in a group chat room between an Agent
* and a user that requested assistance. The transcript contains all the Messages that were sent
* to the room as well as the sent presences.
*
* @author Gaston Dombiak
*/
public class Transcript extends IQ {
private String sessionID;
private List<Packet> packets;
/**
* Creates a transcript request for the given sessionID.
*
* @param sessionID the id of the session to get the conversation transcript.
*/
public Transcript(String sessionID) {
this.sessionID = sessionID;
this.packets = new ArrayList<Packet>();
}
/**
* Creates a new transcript for the given sessionID and list of packets. The list of packets
* may include Messages and/or Presences.
*
* @param sessionID the id of the session that generated this conversation transcript.
* @param packets the list of messages and presences send to the room.
*/
public Transcript(String sessionID, List<Packet> packets) {
this.sessionID = sessionID;
this.packets = packets;
}
/**
* Returns id of the session that generated this conversation transcript. The sessionID is a
* value generated by the server when a new request is received.
*
* @return id of the session that generated this conversation transcript.
*/
public String getSessionID() {
return sessionID;
}
/**
* Returns the list of Messages and Presences that were sent to the room.
*
* @return the list of Messages and Presences that were sent to the room.
*/
public List<Packet> getPackets() {
return Collections.unmodifiableList(packets);
}
public String getChildElementXML() {
StringBuilder buf = new StringBuilder();
buf.append("<transcript xmlns=\"http://jivesoftware.com/protocol/workgroup\" sessionID=\"").append(sessionID).append("\">");
for (Iterator<Packet> it = packets.iterator(); it.hasNext(); ) {
Packet packet = it.next();
buf.append(packet.toXML());
}
buf.append("</transcript>");
return buf.toString();
}
}
| masud-technope/BLIZZARD-Replication-Package-ESEC-FSE2018 | Corpus/ecf/759.java | 747 | /**
* Returns the list of Messages and Presences that were sent to the room.
*
* @return the list of Messages and Presences that were sent to the room.
*/ | block_comment | en | false | 674 | 40 | 747 | 40 | 784 | 44 | 747 | 40 | 870 | 46 | false | false | false | false | false | true |
150609_3 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
package jsjava.util;
import java.util.Collection;
/**
* A collection designed for holding elements prior to processing.
* Besides basic {@link java.util.Collection Collection} operations,
* queues provide additional insertion, extraction, and inspection
* operations. Each of these methods exists in two forms: one throws
* an exception if the operation fails, the other returns a special
* value (either <tt>null</tt> or <tt>false</tt>, depending on the
* operation). The latter form of the insert operation is designed
* specifically for use with capacity-restricted <tt>Queue</tt>
* implementations; in most implementations, insert operations cannot
* fail.
*
* <p>
* <table BORDER CELLPADDING=3 CELLSPACING=1>
* <tr>
* <td></td>
* <td ALIGN=CENTER><em>Throws exception</em></td>
* <td ALIGN=CENTER><em>Returns special value</em></td>
* </tr>
* <tr>
* <td><b>Insert</b></td>
* <td>{@link #add add(e)}</td>
* <td>{@link #offer offer(e)}</td>
* </tr>
* <tr>
* <td><b>Remove</b></td>
* <td>{@link #remove remove()}</td>
* <td>{@link #poll poll()}</td>
* </tr>
* <tr>
* <td><b>Examine</b></td>
* <td>{@link #element element()}</td>
* <td>{@link #peek peek()}</td>
* </tr>
* </table>
*
* <p>Queues typically, but do not necessarily, order elements in a
* FIFO (first-in-first-out) manner. Among the exceptions are
* priority queues, which order elements according to a supplied
* comparator, or the elements' natural ordering, and LIFO queues (or
* stacks) which order the elements LIFO (last-in-first-out).
* Whatever the ordering used, the <em>head</em> of the queue is that
* element which would be removed by a call to {@link #remove() } or
* {@link #poll()}. In a FIFO queue, all new elements are inserted at
* the <em> tail</em> of the queue. Other kinds of queues may use
* different placement rules. Every <tt>Queue</tt> implementation
* must specify its ordering properties.
*
* <p>The {@link #offer offer} method inserts an element if possible,
* otherwise returning <tt>false</tt>. This differs from the {@link
* java.util.Collection#add Collection.add} method, which can fail to
* add an element only by throwing an unchecked exception. The
* <tt>offer</tt> method is designed for use when failure is a normal,
* rather than exceptional occurrence, for example, in fixed-capacity
* (or "bounded") queues.
*
* <p>The {@link #remove()} and {@link #poll()} methods remove and
* return the head of the queue.
* Exactly which element is removed from the queue is a
* function of the queue's ordering policy, which differs from
* implementation to implementation. The <tt>remove()</tt> and
* <tt>poll()</tt> methods differ only in their behavior when the
* queue is empty: the <tt>remove()</tt> method throws an exception,
* while the <tt>poll()</tt> method returns <tt>null</tt>.
*
* <p>The {@link #element()} and {@link #peek()} methods return, but do
* not remove, the head of the queue.
*
* <p>The <tt>Queue</tt> interface does not define the <i>blocking queue
* methods</i>, which are common in concurrent programming. These methods,
* which wait for elements to appear or for space to become available, are
* defined in the {@link java.util.concurrent.BlockingQueue} interface, which
* extends this interface.
*
* <p><tt>Queue</tt> implementations generally do not allow insertion
* of <tt>null</tt> elements, although some implementations, such as
* {@link LinkedList}, do not prohibit insertion of <tt>null</tt>.
* Even in the implementations that permit it, <tt>null</tt> should
* not be inserted into a <tt>Queue</tt>, as <tt>null</tt> is also
* used as a special return value by the <tt>poll</tt> method to
* indicate that the queue contains no elements.
*
* <p><tt>Queue</tt> implementations generally do not define
* element-based versions of methods <tt>equals</tt> and
* <tt>hashCode</tt> but instead inherit the identity based versions
* from class <tt>Object</tt>, because element-based equality is not
* always well-defined for queues with the same elements but different
* ordering properties.
*
*
* <p>This interface is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @see java.util.Collection
* @see LinkedList
* @see PriorityQueue
* @see java.util.concurrent.LinkedBlockingQueue
* @see java.util.concurrent.BlockingQueue
* @see java.util.concurrent.ArrayBlockingQueue
* @see java.util.concurrent.LinkedBlockingQueue
* @see java.util.concurrent.PriorityBlockingQueue
* @since 1.5
* @author Doug Lea
* @param <E> the type of elements held in this collection
*/
public interface Queue<E> extends Collection<E> {
/**
* Inserts the specified element into this queue if it is possible to do so
* immediately without violating capacity restrictions, returning
* <tt>true</tt> upon success and throwing an <tt>IllegalStateException</tt>
* if no space is currently available.
*
* @param e the element to add
* @return <tt>true</tt> (as specified by {@link Collection#add})
* @throws IllegalStateException if the element cannot be added at this
* time due to capacity restrictions
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null and
* this queue does not permit null elements
* @throws IllegalArgumentException if some property of this element
* prevents it from being added to this queue
*/
@Override
boolean add(E e);
/**
* Inserts the specified element into this queue if it is possible to do
* so immediately without violating capacity restrictions.
* When using a capacity-restricted queue, this method is generally
* preferable to {@link #add}, which can fail to insert an element only
* by throwing an exception.
*
* @param e the element to add
* @return <tt>true</tt> if the element was added to this queue, else
* <tt>false</tt>
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null and
* this queue does not permit null elements
* @throws IllegalArgumentException if some property of this element
* prevents it from being added to this queue
*/
boolean offer(E e);
/**
* Retrieves and removes the head of this queue. This method differs
* from {@link #poll poll} only in that it throws an exception if this
* queue is empty.
*
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*/
E remove();
/**
* Retrieves and removes the head of this queue,
* or returns <tt>null</tt> if this queue is empty.
*
* @return the head of this queue, or <tt>null</tt> if this queue is empty
*/
E poll();
/**
* Retrieves, but does not remove, the head of this queue. This method
* differs from {@link #peek peek} only in that it throws an exception
* if this queue is empty.
*
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*/
E element();
/**
* Retrieves, but does not remove, the head of this queue,
* or returns <tt>null</tt> if this queue is empty.
*
* @return the head of this queue, or <tt>null</tt> if this queue is empty
*/
E peek();
}
| SwingJS/SwingJS | src/jsjava/util/Queue.java | 2,385 | /**
* Inserts the specified element into this queue if it is possible to do so
* immediately without violating capacity restrictions, returning
* <tt>true</tt> upon success and throwing an <tt>IllegalStateException</tt>
* if no space is currently available.
*
* @param e the element to add
* @return <tt>true</tt> (as specified by {@link Collection#add})
* @throws IllegalStateException if the element cannot be added at this
* time due to capacity restrictions
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null and
* this queue does not permit null elements
* @throws IllegalArgumentException if some property of this element
* prevents it from being added to this queue
*/ | block_comment | en | false | 2,248 | 189 | 2,385 | 181 | 2,369 | 201 | 2,385 | 181 | 2,642 | 214 | true | true | true | true | true | false |
150631_1 | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
class Task {
String description;
boolean completed;
Task(String description) {
this.description = description;
this.completed = false;
}
}
class TaskManager {
private ArrayList<Task> tasks;
TaskManager() {
this.tasks = new ArrayList<>();
}
void addTask(String description) {
Task task = new Task(description);
tasks.add(task);
System.out.println("Task added: " + description);
}
ArrayList<Task> getTasks() {
return tasks;
}
void markTaskAsComplete(int index) {
if (index >= 1 && index <= tasks.size()) {
Task task = tasks.get(index - 1);
task.completed = true;
System.out.println("Task marked as complete: " + task.description);
} else {
System.out.println("Invalid task index.");
}
}
}
public class oops {
public static void main(String[] args) {
TaskManager taskManager = new TaskManager();
// Set look and feel to Nimbus for a modern appearance
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
// Create and set up the main frame
JFrame frame = new JFrame("Task Manager");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH); // Make it full screen
frame.setLayout(new BorderLayout());
// Set font to Times New Roman
Font timesNewRomanFont = new Font("Times New Roman", Font.PLAIN, 16);
// Create components
JTextArea taskTextArea = new JTextArea();
taskTextArea.setEditable(false);
taskTextArea.setFont(timesNewRomanFont);
JTextField inputField = new JTextField();
inputField.setFont(timesNewRomanFont);
JButton addButton = new JButton("Add Task");
addButton.setFont(timesNewRomanFont);
JButton listButton = new JButton("List Tasks");
listButton.setFont(timesNewRomanFont);
JButton markCompleteButton = new JButton("Mark as Complete");
markCompleteButton.setFont(timesNewRomanFont);
JButton exitButton = new JButton("Exit");
exitButton.setFont(timesNewRomanFont);
// Create a panel to hold the components
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBackground(Color.BLACK);
// Project information text box
JTextArea projectInfo = new JTextArea(
"## TaskSwing - Task Manager Application π\n" +
"\n" +
"**Overview**\n" +
"\n" +
"TaskSwing is a dynamic Java Swing-based task manager application designed to simplify task management through an intuitive graphical user interface. Users can efficiently organize and track their tasks, enhancing productivity and workflow management.\n" +
"\n" +
"### Key Features\n" +
"\n" +
"- **Add Task π:** Seamlessly add new tasks with a user-friendly interface.\n" +
"- **List Tasks π:** View the task list with descriptions and status indicators.\n" +
"- **Mark as Complete βοΈ:** Easily mark tasks as complete by entering the task index.\n" +
"- **Project Information βΉοΈ:** A dedicated section provides insights into the project.\n" +
"- **Team Information π₯:** Display team members' names who contributed to TaskSwing.\n" +
"- **Exit Button πͺ:** Gracefully exit the application for a smooth user experience.\n"
);
projectInfo.setEditable(false);
projectInfo.setLineWrap(true);
projectInfo.setWrapStyleWord(true);
projectInfo.setFont(timesNewRomanFont);
projectInfo.setBackground(Color.BLACK);
projectInfo.setForeground(Color.GREEN);
JScrollPane projectInfoScrollPane = new JScrollPane(projectInfo);
panel.add(projectInfoScrollPane, BorderLayout.NORTH);
// Create a panel for task-related components
JPanel taskPanel = new JPanel();
taskPanel.setLayout(new GridLayout(3, 1));
taskPanel.setBackground(Color.BLACK);
// Task Description components
JPanel taskDescriptionPanel = new JPanel();
taskDescriptionPanel.setLayout(new GridLayout(1, 2));
taskDescriptionPanel.add(new JLabel("Task Description:"));
taskDescriptionPanel.add(inputField);
taskPanel.add(taskDescriptionPanel);
// Button components
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 4));
buttonPanel.add(addButton);
buttonPanel.add(listButton);
buttonPanel.add(markCompleteButton);
buttonPanel.add(exitButton);
taskPanel.add(buttonPanel);
panel.add(taskPanel, BorderLayout.WEST);
// Add action listeners
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String description = inputField.getText();
taskManager.addTask(description);
inputField.setText("");
// Automatically list tasks after adding a task
listButton.doClick();
}
});
listButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
taskTextArea.setText(""); // Clear previous content
for (int i = 0; i < taskManager.getTasks().size(); i++) {
Task task = taskManager.getTasks().get(i);
taskTextArea.append((i + 1) + ". " + task.description + " - " +
(task.completed ? "Completed" : "Incomplete") + "\n");
}
}
});
markCompleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int index = Integer.parseInt(JOptionPane.showInputDialog("Enter the index of the task to mark as complete:"));
taskManager.markTaskAsComplete(index);
// Automatically list tasks after marking as complete
listButton.doClick();
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Invalid input. Please enter a valid index.");
}
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Exiting the program. Goodbye!");
System.exit(0);
}
});
// Create a panel for displaying tasks
JScrollPane taskDisplayScrollPane = new JScrollPane(taskTextArea);
panel.add(taskDisplayScrollPane, BorderLayout.CENTER);
// Add components to the frame
frame.getContentPane().add(panel);
frame.getContentPane().add(BorderLayout.NORTH, createTeamPanel());
frame.setVisible(true);
}
private static JPanel createTeamPanel() {
JPanel teamPanel = new JPanel();
teamPanel.setLayout(new GridLayout(1, 2));
teamPanel.setBackground(Color.BLACK);
JLabel teamLabel = new JLabel("Team Members:");
teamLabel.setForeground(Color.GREEN);
teamPanel.add(teamLabel);
JButton teamLinkButton = new JButton("<html><a href='https://example.com'>John, Jane, Alex</a></html>");
teamLinkButton.setBorderPainted(false);
teamLinkButton.setOpaque(false);
teamLinkButton.setBackground(Color.BLACK);
teamLinkButton.setForeground(Color.GREEN);
teamPanel.add(teamLinkButton);
return teamPanel;
}
}
| ANUJDWIVDI/java_task_manager | oops.java | 1,737 | // Create and set up the main frame | line_comment | en | false | 1,505 | 8 | 1,737 | 8 | 1,843 | 8 | 1,737 | 8 | 2,145 | 8 | false | false | false | false | false | true |
150717_2 | package puzzleSolver;
/**
* Queen.java
*
* File:
* $Id: Queen.java,v 1.1 2013/05/03 22:27:18 cas5420 Exp $
*
* Revisions:
* $Log: Queen.java,v $
* Revision 1.1 2013/05/03 22:27:18 cas5420
* Finished Puzzle solver, just need to comment.
*
* Revision 1.3 2013/05/03 13:52:10 cas5420
* Completed chess solver, debugging
*
*/
import java.util.HashSet;
/**
* Defines Queen piece.
* @author Chris Sleys
*
*/
public class Queen extends Piece{
/**
* Initializes inherited values.
* @param name Name of Queen
* @param X Length of the board on x-axis
* @param Y Length of the board on y-axis
*/
public Queen(String name, int X, int Y) {
super(name, X, Y);
}
/**
* Returns the union of the diagonal moves and the cardinal moves.
*/
@Override
public HashSet<Point> getMoves(Point init) {
HashSet<Point> moves = super.diagonalMoves(init);
moves.addAll(super.cardinalMoves(init));
return moves;
}
}
| Galaran28/PuzzleSolver | Queen.java | 371 | /**
* Initializes inherited values.
* @param name Name of Queen
* @param X Length of the board on x-axis
* @param Y Length of the board on y-axis
*/ | block_comment | en | false | 313 | 44 | 371 | 44 | 363 | 48 | 371 | 44 | 404 | 51 | false | false | false | false | false | true |
151839_12 | import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class PacificAtlantic {
private static final int[][] DIRECTIONS = new int[][]{{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
private int numRows;
private int numCols;
private int[][] landHeights;
public List<List<Integer>> pacificAtlantic(int[][] matrix) {
// Check if input is empty
if (matrix.length == 0 || matrix[0].length == 0) {
return new ArrayList<>();
}
// Save initial values to parameters
numRows = matrix.length;
numCols = matrix[0].length;
landHeights = matrix;
// Setup each queue with cells adjacent to their respective ocean
Queue<int[]> pacificQueue = new LinkedList<>();
Queue<int[]> atlanticQueue = new LinkedList<>();
for (int i = 0; i < numRows; i++) {
pacificQueue.offer(new int[]{i, 0});
atlanticQueue.offer(new int[]{i, numCols - 1});
}
for (int i = 0; i < numCols; i++) {
pacificQueue.offer(new int[]{0, i});
atlanticQueue.offer(new int[]{numRows - 1, i});
}
// Perform a BFS for each ocean to find all cells accessible by each ocean
boolean[][] pacificReachable = bfs(pacificQueue);
boolean[][] atlanticReachable = bfs(atlanticQueue);
// Find all cells that can reach both oceans
List<List<Integer>> commonCells = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (pacificReachable[i][j] && atlanticReachable[i][j]) {
commonCells.add(List.of(i, j));
}
}
}
return commonCells;
}
private boolean[][] bfs(Queue<int[]> queue) {
boolean[][] reachable = new boolean[numRows][numCols];
while (!queue.isEmpty()) {
int[] cell = queue.poll();
// This cell is reachable, so mark it
reachable[cell[0]][cell[1]] = true;
for (int[] dir : DIRECTIONS) { // Check all 4 directions
int newRow = cell[0] + dir[0];
int newCol = cell[1] + dir[1];
// Check if new cell is within bounds
if (newRow < 0 || newRow >= numRows || newCol < 0 || newCol >= numCols) {
continue;
}
// Check that the new cell hasn't already been visited
if (reachable[newRow][newCol]) {
continue;
}
// Check that the new cell has a higher or equal height,
// So that water can flow from the new cell to the old cell
if (landHeights[newRow][newCol] < landHeights[cell[0]][cell[1]]) {
continue;
}
// If we've gotten this far, that means the new cell is reachable
queue.offer(new int[]{newRow, newCol});
}
}
return reachable;
}
public List<List<Integer>> pacificAtlanticDFS(int[][] matrix) {
// Check if input is empty
if (matrix.length == 0 || matrix[0].length == 0) {
return new ArrayList<>();
}
// Save initial values to parameters
numRows = matrix.length;
numCols = matrix[0].length;
landHeights = matrix;
boolean[][] pacificReachable = new boolean[numRows][numCols];
boolean[][] atlanticReachable = new boolean[numRows][numCols];
// Loop through each cell adjacent to the oceans and start a DFS
for (int i = 0; i < numRows; i++) {
dfs(i, 0, pacificReachable);
dfs(i, numCols - 1, atlanticReachable);
}
for (int i = 0; i < numCols; i++) {
dfs(0, i, pacificReachable);
dfs(numRows - 1, i, atlanticReachable);
}
// Find all cells that can reach both oceans
List<List<Integer>> commonCells = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (pacificReachable[i][j] && atlanticReachable[i][j]) {
commonCells.add(List.of(i, j));
}
}
}
return commonCells;
}
private void dfs(int row, int col, boolean[][] reachable) {
// This cell is reachable, so mark it
reachable[row][col] = true;
for (int[] dir : DIRECTIONS) { // Check all 4 directions
int newRow = row + dir[0];
int newCol = col + dir[1];
// Check if new cell is within bounds
if (newRow < 0 || newRow >= numRows || newCol < 0 || newCol >= numCols) {
continue;
}
// Check that the new cell hasn't already been visited
if (reachable[newRow][newCol]) {
continue;
}
// Check that the new cell has a higher or equal height,
// So that water can flow from the new cell to the old cell
if (landHeights[newRow][newCol] < landHeights[row][col]) {
continue;
}
// If we've gotten this far, that means the new cell is reachable
dfs(newRow, newCol, reachable);
}
}
public static void main(String[] args) {
PacificAtlantic sol = new PacificAtlantic();
int[][] heights;
List<List<Integer>> res;
heights = new int[][]{{1,2,2,3,5},{3,2,3,4,4},{2,4,5,3,1},{6,7,1,4,5},{5,1,1,2,4}};
res = sol.pacificAtlantic(heights);
System.out.println("Heights : " + Arrays.deepToString(heights));
System.out.println("Results : " + Arrays.deepToString(res.toArray()));
}
}
/*abstract
https://leetcode.com/problems/pacific-atlantic-water-flow/
*/ | zt5rice/LeetcodeHighFreq | BFS/PacificAtlantic.java | 1,543 | // Check if input is empty | line_comment | en | false | 1,426 | 6 | 1,543 | 6 | 1,600 | 6 | 1,543 | 6 | 1,798 | 6 | false | false | false | false | false | true |
152688_4 | import java.util.*;
/*
44. Wildcard Matching
Hard
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "*"
Output: true
Explanation: '*' matches any sequence.
Example 3:
Input: s = "cb", p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
Constraints:
0 <= s.length, p.length <= 2000
s contains only lowercase English letters.
p contains only lowercase English letters, '?' or '*'.
*/
class Solution {
public:
bool f(int i,int j, string &s,string &p)
{
if(i<0 && j<0) return true;
if(j<0 && i>=0) return false;
if(i<0 && j>=0)
{
while(j>=0)
{
if(p[j]=='*') j--;
else return false;
}
return true;
}
if(s[i]==p[j] || p[j]=='?') return f(i-1,j-1,s,p);
if(p[j]=='*')
{
return f(i-1,j,s,p) || f(i,j-1,s,p);
//Two cases
//Consider * as len=0
//Give one charcter to * and remain at *
//at next step it will again be decided from both these cases
}
return false;
}
bool isMatch(string s, string p) {
int n=s.length(),m=p.length();
return f(n-1,m-1,s,p);
}
}; | UVid489/hacktoberfest-LeetCode-2022 | Java/f.java | 508 | //at next step it will again be decided from both these cases | line_comment | en | false | 446 | 13 | 508 | 13 | 535 | 13 | 508 | 13 | 589 | 13 | false | false | false | false | false | true |
152902_4 | package org.saleen.rs2.pf;
/**
* An individual tile on a <code>TileMap</code>. Immutable.
*
* @author Graham Edgecombe
*
*/
public class Tile {
/**
* Constant values used by the bitmask.
*/
public static final int NORTH_TRAVERSAL_PERMITTED = 1,
EAST_TRAVERSAL_PERMITTED = 2, SOUTH_TRAVERSAL_PERMITTED = 4,
WEST_TRAVERSAL_PERMITTED = 8;
/**
* A bitmask which determines which directions can be traversed.
*/
private final int traversalMask;
/**
* Creates the tile.
*
* @param traversalMask
* The traversal bitmask.
*/
public Tile(int traversalMask) {
this.traversalMask = traversalMask;
}
/**
* Gets the traversal bitmask.
*
* @return The traversal bitmask.
*/
public int getTraversalMask() {
return traversalMask;
}
/**
* Checks if northern traversal is permitted.
*
* @return True if so, false if not.
*/
public boolean isNorthernTraversalPermitted() {
return (traversalMask & NORTH_TRAVERSAL_PERMITTED) > 0;
}
/**
* Checks if eastern traversal is permitted.
*
* @return True if so, false if not.
*/
public boolean isEasternTraversalPermitted() {
return (traversalMask & EAST_TRAVERSAL_PERMITTED) > 0;
}
/**
* Checks if southern traversal is permitted.
*
* @return True if so, false if not.
*/
public boolean isSouthernTraversalPermitted() {
return (traversalMask & SOUTH_TRAVERSAL_PERMITTED) > 0;
}
/**
* Checks if western traversal is permitted.
*
* @return True if so, false if not.
*/
public boolean isWesternTraversalPermitted() {
return (traversalMask & WEST_TRAVERSAL_PERMITTED) > 0;
}
} | nikkiii/saleenrs | src/org/saleen/rs2/pf/Tile.java | 510 | /**
* Gets the traversal bitmask.
*
* @return The traversal bitmask.
*/ | block_comment | en | false | 436 | 21 | 510 | 22 | 532 | 27 | 510 | 22 | 643 | 30 | false | false | false | false | false | true |
153309_6 | public class Dog {
private String name;
private String breed;
// Constructor
public Dog(String name, String breed) {
this.name = name;
this.breed = breed;
}
// Setter for name attribute
public void setName(String name) {
this.name = name;
}
// Setter for breed attribute
public void setBreed(String breed) {
this.breed = breed;
}
// Getter for name attribute
public String getName() {
return name;
}
// Getter for breed attribute
public String getBreed() {
return breed;
}
public static void main(String[] args) {
// Create two instances of Dog class
Dog dog1 = new Dog("Max", "Labrador");
Dog dog2 = new Dog("Buddy", "Golden Retriever");
// Print initial values
System.out.println("Initial values:");
System.out.println("Dog 1 - Name: " + dog1.getName() + ", Breed: " + dog1.getBreed());
System.out.println("Dog 2 - Name: " + dog2.getName() + ", Breed: " + dog2.getBreed());
// Modify attributes using setter methods
dog1.setName("Charlie");
dog2.setBreed("German Shepherd");
// Print updated values
System.out.println("\nUpdated values:");
System.out.println("Dog 1 - Name: " + dog1.getName() + ", Breed: " + dog1.getBreed());
System.out.println("Dog 2 - Name: " + dog2.getName() + ", Breed: " + dog2.getBreed());
}
} | quiesscent/AllStar-Java | Dog.java | 390 | // Print initial values | line_comment | en | false | 351 | 4 | 390 | 4 | 404 | 4 | 390 | 4 | 460 | 4 | false | false | false | false | false | true |
154464_1 | /**
* Space represents a space on a game board. It keeps track of any pieces on the space
* and allows users to add and remove pieces from the space.
* @author Tanner Braun
*
*/
import java.util.ArrayList;
public class Space {
private ArrayList<Piece> currentPieces;
private int spaceSize;
// Creates a space that can hold spaceSize pieces at once
public Space(int spaceSize) {
currentPieces = new ArrayList<Piece>();
this.spaceSize = spaceSize;
}
// Creates a space that can hold unlimited pieces
public Space() {
currentPieces = new ArrayList<Piece>();
this.spaceSize = Integer.MAX_VALUE;
}
/**
* Puts a given piece on this space
* @param piece - the piece to be placed on this space
* @return returns 1 on successful placement, and 0 on illegal move
*/
public int addPiece(Piece piece) {
if(currentPieces.size() < spaceSize) {
currentPieces.add(piece);
return 1;
} else {
return 0;
}
}
/**
* Removes all instances of the given piece from this space
* @param removePiece - the piece to be removed
* @return whether or not the piece was successfully removed
*/
public boolean removePiece(Piece removePiece) {
return currentPieces.remove(removePiece);
}
public ArrayList<Piece> getCurrentPieces() {
return currentPieces;
}
public int getSpaceSize() {
return spaceSize;
}
public boolean isEmpty() {
return this.currentPieces.isEmpty();
}
public String toString() {
return currentPieces.toString();
}
}
| tsbraun1891/LegendsOfValor | Space.java | 421 | // Creates a space that can hold spaceSize pieces at once | line_comment | en | false | 362 | 12 | 421 | 12 | 436 | 12 | 421 | 12 | 513 | 13 | false | false | false | false | false | true |
154885_0 | package net.minecraft.src;
public class Timer
{
/** The number of timer ticks per second of real time */
float ticksPerSecond;
/**
* The time reported by the high-resolution clock at the last call of updateTimer(), in seconds
*/
private double lastHRTime;
/**
* How many full ticks have turned over since the last call to updateTimer(), capped at 10.
*/
public int elapsedTicks;
/**
* How much time has elapsed since the last tick, in ticks, for use by display rendering routines (range: 0.0 -
* 1.0). This field is frozen if the display is paused to eliminate jitter.
*/
public float renderPartialTicks;
/**
* A multiplier to make the timer (and therefore the game) go faster or slower. 0.5 makes the game run at half-
* speed.
*/
public float timerSpeed;
/**
* How much time has elapsed since the last tick, in ticks (range: 0.0 - 1.0).
*/
public float elapsedPartialTicks;
/**
* The time reported by the system clock at the last sync, in milliseconds
*/
private long lastSyncSysClock;
/**
* The time reported by the high-resolution clock at the last sync, in milliseconds
*/
private long lastSyncHRClock;
private long field_28132_i;
/**
* A ratio used to sync the high-resolution clock to the system clock, updated once per second
*/
private double timeSyncAdjustment;
public Timer(float par1)
{
timerSpeed = 1.0F;
elapsedPartialTicks = 0.0F;
timeSyncAdjustment = 1.0D;
ticksPerSecond = par1;
lastSyncSysClock = System.currentTimeMillis();
lastSyncHRClock = System.nanoTime() / 0xf4240L;
}
/**
* Updates all fields of the Timer using the current time
*/
public void updateTimer()
{
long l = System.currentTimeMillis();
long l1 = l - lastSyncSysClock;
long l2 = System.nanoTime() / 0xf4240L;
double d = (double)l2 / 1000D;
if (l1 > 1000L)
{
lastHRTime = d;
}
else if (l1 < 0L)
{
lastHRTime = d;
}
else
{
field_28132_i += l1;
if (field_28132_i > 1000L)
{
long l3 = l2 - lastSyncHRClock;
double d2 = (double)field_28132_i / (double)l3;
timeSyncAdjustment += (d2 - timeSyncAdjustment) * 0.20000000298023224D;
lastSyncHRClock = l2;
field_28132_i = 0L;
}
if (field_28132_i < 0L)
{
lastSyncHRClock = l2;
}
}
lastSyncSysClock = l;
double d1 = (d - lastHRTime) * timeSyncAdjustment;
lastHRTime = d;
if (d1 < 0.0D)
{
d1 = 0.0D;
}
if (d1 > 1.0D)
{
d1 = 1.0D;
}
elapsedPartialTicks += d1 * (double)timerSpeed * (double)ticksPerSecond;
elapsedTicks = (int)elapsedPartialTicks;
elapsedPartialTicks -= elapsedTicks;
if (elapsedTicks > 10)
{
elapsedTicks = 10;
}
renderPartialTicks = elapsedPartialTicks;
}
}
| DND91/mod_Discord | Timer.java | 889 | /** The number of timer ticks per second of real time */ | block_comment | en | false | 880 | 12 | 889 | 12 | 980 | 12 | 889 | 12 | 1,087 | 13 | false | false | false | false | false | true |
155651_6 | /*
Copyright (c) 2011, Tom Van Cutsem, Vrije Universiteit Brussel
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Vrije Universiteit Brussel nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Vrije Universiteit Brussel BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/
import java.awt.Canvas;
import java.awt.Frame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.DirectColorModel;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
/**
* Demo of using Fork/Join parallelism to speed up the rendering of the
* Mandelbrot fractal. The fractal is shown centered around the origin
* of the Complex plane with x and y coordinates in the interval [-2, 2].
*
* @author tvcutsem
*/
public class Mandelbrot extends Canvas {
// size of fractal in pixels (HEIGHT X HEIGHT)
private static final int HEIGHT = 1024;
// how long to test for orbit divergence
private static final int NUM_ITERATIONS = 50;
// maximum grid size to process sequentially
private static final int SEQ_CUTOFF = 64;
private int colorscheme[];
// 2-dimensional array of colors stored in packed ARGB format
private int[] fractal;
private int height;
private boolean optDrawGrid;
private Image img;
private String msg;
private ForkJoinPool fjPool = new ForkJoinPool();
/**
* Construct a new Mandelbrot canvas.
* The constructor will calculate the fractal (either sequentially
* or in parallel), then store the result in an {@link java.awt.Image}
* for faster drawing in its {@link #paint(Graphics)} method.
*
* @param height the size of the fractal (height x height pixels).
* @param optParallel if true, render in parallel
* @param optDrawGrid if true, render the grid of leaf task pixel areas
*/
public Mandelbrot(int height, boolean optParallel, boolean optDrawGrid) {
this.optDrawGrid = optDrawGrid;
this.colorscheme = new int[NUM_ITERATIONS+1];
// fill array with color palette going from Red over Green to Blue
int scale = (255 * 2) / NUM_ITERATIONS;
// going from Red to Green
for (int i = 0; i < (NUM_ITERATIONS/2); i++)
// Alpha=255 | Red | Green | Blue=0
colorscheme[i] = 0xFF << 24 | (255 - i*scale) << 16 | i*scale << 8;
// going from Green to Blue
for (int i = 0; i < (NUM_ITERATIONS/2); i++)
// Alpha=255 | Red=0 | Green | Blue
colorscheme[i+NUM_ITERATIONS/2] = 0xFF000000 | (255-i*scale) << 8 | i*scale;
// convergence color
colorscheme[NUM_ITERATIONS] = 0xFF0000FF; // Blue
this.height = height;
// fractal[x][y] = fractal[x + height*y]
this.fractal = new int[height*height];
long start = System.currentTimeMillis();
if (optParallel) {
// parallel calculation through Fork/Join
fjPool.invoke(new FractalTask(0, 0, height));
} else {
// sequential calculation by the main Thread
calcMandelBrot(0, 0, height, height);
}
long end = System.currentTimeMillis();
msg = (optParallel ? "parallel" : "sequential") +
" done in " + (end - start) + "ms.";
this.img = getImageFromArray(fractal, height, height);
}
/**
* Draws part of the mandelbrot fractal.
*
* This method calculates the colors of pixels in the square:
*
* (srcx, srcy) (srcx+size, srcy)
* +--------------------------+
* | |
* | |
* | |
* +--------------------------+
* (srcx, srcy+size) (srcx+size, srcy + size)
*/
private void calcMandelBrot(int srcx, int srcy, int size, int height) {
double x, y, t, cx, cy;
int k;
// loop over specified rectangle grid
for (int px = srcx; px < srcx + size; px++) {
for (int py = srcy; py < srcy + size; py++) {
x=0; y=0;
// convert pixels into complex coordinates between (-2, 2)
cx = (px * 4.0) / height - 2;
cy = 2 - (py * 4.0) / height;
// test for divergence
for (k = 0; k < NUM_ITERATIONS; k++) {
t = x*x-y*y+cx;
y = 2*x*y+cy;
x = t;
if (x*x+y*y > 4) break;
}
fractal[px + height * py] = colorscheme[k];
}
}
// paint grid boundaries
if (optDrawGrid) {
drawGrid(srcx, srcy, size, Color.BLACK.getRGB());
}
}
/**
* Draw the rectangular outline of the grid to show the
* subdivision of the canvas into grids processed in parallel.
*/
private void drawGrid(int x, int y, int size, int color) {
for (int i = 0; i < size; i++) {
fractal[x+i + height * (y )] = color;
fractal[x+i + height * (y+size-1)] = color;
}
for (int j = 0; j < size; j++) {
fractal[x + height * (y+j)] = color;
fractal[x + size-1 + height * (y+j)] = color;
}
}
/**
* Divide the grid into four equally-sized subgrids until they
* are small enough to be drawn sequentially.
*/
private class FractalTask extends RecursiveAction {
final int srcx;
final int srcy;
final int size;
public FractalTask(int sx, int sy, int siz) {
srcx = sx; srcy = sy; size = siz;
}
@Override
protected void compute() {
if (size < SEQ_CUTOFF) {
calcMandelBrot(srcx, srcy, size, height);
} else {
FractalTask ul = new FractalTask(srcx, srcy, size/2);
FractalTask ur = new FractalTask(srcx+size/2, srcy, size/2);
FractalTask ll = new FractalTask(srcx, srcy+size/2, size/2);
FractalTask lr = new FractalTask(srcx+size/2, srcy+size/2, size/2);
// forks and immediately joins the four subtasks
invokeAll(ul, ur, ll, lr);
}
}
}
@Override
public void paint(Graphics g) {
// draw the fractal from the stored image
g.drawImage(this.img, 0, 0, null);
// draw the message text in the lower-right-hand corner
byte[] data = this.msg.getBytes();
g.drawBytes(
data,
0,
data.length,
getWidth() - (data.length)*8,
getHeight() - 20);
}
/**
* Auxiliary function that converts an array of pixels into a BufferedImage.
* This is used to be able to quickly draw the fractal onto the canvas using
* native code, instead of us having to manually plot each pixel to the canvas.
*/
private static Image getImageFromArray(int[] pixels, int width, int height) {
// RGBdefault expects 0x__RRGGBB packed pixels
ColorModel cm = DirectColorModel.getRGBdefault();
SampleModel sampleModel = cm.createCompatibleSampleModel(width, height);
DataBuffer db = new DataBufferInt(pixels, height, 0);
WritableRaster raster = Raster.createWritableRaster(sampleModel, db, null);
BufferedImage image = new BufferedImage(cm, raster, false, null);
return image;
}
/**
* Supported command-line options:
* -p : render in parallel (default: sequential)
* -g : draw grid of pixels drawn by leaf tasks (default: off)
*/
public static void main(String args[]) {
boolean optParallel = false;
boolean optDrawGrid = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-p")) {
optParallel = true;
} else if (args[i].equals("-g")) {
optDrawGrid = true;
} else {
System.err.println("unknown option: " + args[i]);
}
}
Frame f = new Frame();
Mandelbrot canvas = new Mandelbrot(HEIGHT, optParallel, optDrawGrid);
f.setSize(HEIGHT, HEIGHT);
f.add(canvas);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setVisible(true);
}
}
| tvcutsem/mandelbrot | Mandelbrot.java | 2,627 | /**
* Construct a new Mandelbrot canvas.
* The constructor will calculate the fractal (either sequentially
* or in parallel), then store the result in an {@link java.awt.Image}
* for faster drawing in its {@link #paint(Graphics)} method.
*
* @param height the size of the fractal (height x height pixels).
* @param optParallel if true, render in parallel
* @param optDrawGrid if true, render the grid of leaf task pixel areas
*/ | block_comment | en | false | 2,456 | 112 | 2,627 | 115 | 2,776 | 117 | 2,627 | 115 | 3,170 | 128 | false | false | false | false | false | true |
155698_30 | // Copyright (c) 2021, C. P. Mah
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -----------------------------------------------------------------------------
// Stopat.java : 27May00 CPM
// extended stop pattern matching
package stem;
import aw.*;
import java.io.*;
class PatternQualify {
boolean lAnchor; // must be at start of line if true
boolean rAnchor; // must be at end of line if true
short cur; // state for applicability of match
short nxt; // next state after a match
char lContext; // left context for match
char rContext; // right context for match
}
public class Stopat {
private static final int MXPT = 72; // how many patterns
private TokenPattern [] pa = new TokenPattern [MXPT]; // stop patterns
private PatternQualify[] qu = new PatternQualify[MXPT]; // pattern qualifiers
private int npq = 0;
// constructor
public Stopat (
BufferedReader in // definitions
) throws AWException {
if (in == null)
return;
// load stop patterns from text input
try {
for (String line; (line = in.readLine()) != null; ) {
line = line.trim();
if (line.length() == 0)
continue;
// take care of any qualifier first
PatternQualify q = new PatternQualify();
line = parse(line,q);
if (npq == qu.length)
throw new AWException("pattern overflow");
qu[npq] = q;
// encode actual pattern
pa[npq++] = new TokenPattern(line);
}
} catch (IOException e) {
throw new AWException("cannot get stop patterns");
}
}
// extract qualifiers from pattern
private String parse (
String s, // pattern definition
PatternQualify q // record to be filled
) {
// get state definitions
int k = s.indexOf(' ');
if (k < 0)
q.cur = q.nxt = -1;
else {
String t = s.substring(k).trim();
s = s.substring(0,k);
char c0 = (t.length() < 1) ? '0' : t.charAt(0);
char c1 = (t.length() < 2) ? '0' : t.charAt(1);
if (!Character.isDigit(c0))
q.cur = q.nxt = 0;
else {
q.cur = (short)(c0 - '0');
q.nxt = (!Character.isDigit(c1)) ? q.cur : (short)(c1 - '0');
}
}
// get left and right contexts
if (s.length() > 1) {
if (s.charAt(0) == ']') {
q.lAnchor = true;
s = s.substring(1);
}
else if (s.charAt(1) == ']') {
q.lContext = s.charAt(0);
s = s.substring(2);
}
k = s.indexOf('[');
if (k >= 0) {
if (k + 1 < s.length())
q.rContext = s.charAt(k+1);
else
q.rAnchor = true;
s = s.substring(0,k);
}
}
return s;
}
// compare token sequentially against
// currently defined stop-patterns
private static int state = 0; // for finite-state automaton (FSA)
public final boolean stopat (
Token token, // to match against
char left, // context char
char right // context char
) {
for (int p = 0; p < npq; p++) {
// check for match
if (pa[p].match(token)) {
// now check pattern qualifiers
PatternQualify q = qu[p];
if ((q.cur < 0 || q.cur == state) &&
(!q.lAnchor || left == '\n' || left == '\r') &&
(!q.rAnchor || right == '\n' || right == '\r') &&
(q.lContext == 0 || q.lContext == left) &&
(q.rContext == 0 || q.rContext == right)) {
if (q.nxt >= 0)
state = q.nxt;
return true;
}
}
}
return false;
}
// reinitialize FSA for qualifiers
public final void reset ( ) {
state = 0;
}
}
| prohippo/ActiveWatch | stem/Stopat.java | 1,426 | // left context for match | line_comment | en | false | 1,296 | 6 | 1,426 | 6 | 1,525 | 6 | 1,426 | 6 | 1,988 | 6 | false | false | false | false | false | true |
155702_13 | /* ----------------------------------------------------------------------
*
* coNCePTuaL GUI: task
*
* By Nick Moss <nickm@lanl.gov>
*
* This class contains methods for drawing a task within a task row
* and event-handling for mouse events within its bounds.
*
* ----------------------------------------------------------------------
*
*
* Copyright (C) 2015, Los Alamos National Security, LLC
* All rights reserved.
*
* Copyright (2015). Los Alamos National Security, LLC. This software
* was produced under U.S. Government contract DE-AC52-06NA25396
* for Los Alamos National Laboratory (LANL), which is operated by
* Los Alamos National Security, LLC (LANS) for the U.S. Department
* of Energy. The U.S. Government has rights to use, reproduce,
* and distribute this software. NEITHER THE GOVERNMENT NOR LANS
* MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY
* FOR THE USE OF THIS SOFTWARE. If software is modified to produce
* derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* Additionally, redistribution and use in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Los Alamos National Security, LLC, Los Alamos
* National Laboratory, the U.S. Government, nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY LANS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LANS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* ----------------------------------------------------------------------
*/
package gov.lanl.c3.ncptl;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
public class Task extends AbstractComponent {
// default diameter of tasks
public static final int TASK_SIZE = 25;
// coordinates of the task relative to its task row
private int x;
private int y;
private Program program;
public Task( Program program, int id, int x, int y ){
setID( id );
this.program = program;
setBounds( x, y, TASK_SIZE+1, TASK_SIZE+1 );
addMouseMotionListener( program.getScrollPane() );
addMouseListener( program.getScrollPane() );
}
public void paintComponent( Graphics graphics ){
String idString = Integer.toString( getID() );
if( isSelected() ){
graphics.setColor( GraphicsUtility.getSelectedColor() );
graphics.fillOval( 0, 0, TASK_SIZE, TASK_SIZE );
graphics.setColor( Color.black );
graphics.drawOval( 0, 0, TASK_SIZE, TASK_SIZE );
}
else{
graphics.setColor( Color.white );
graphics.fillOval( 0, 0, TASK_SIZE, TASK_SIZE );
graphics.setColor( Color.black );
graphics.drawOval( 0, 0, TASK_SIZE, TASK_SIZE );
}
float x = TASK_SIZE/2.0f - idString.length()*3.50f;
float y = TASK_SIZE/2.0f + 5.0f;
graphics.drawString( idString, (int)x, (int)y );
}
// get the ID of the task row that this task belongs to
public int getRowID(){
TaskRow taskRow = (TaskRow)getParent();
return taskRow.getID();
}
public void mouseDragged( MouseEvent mouseEvent ){
// sourceTask is the source task if a drag to
// create a communication stmt is already in progress
Task sourceTask = program.getSourceTask();
if( sourceTask == null ){
TaskRow taskRow = (TaskRow)getParent();
// can only create communication stmt if there are no
// collectives in the row
if( !taskRow.hasSynchronize() &&
!taskRow.hasReduce() &&
!taskRow.hasMulticast() &&
!taskRow.hasOther() &&
!taskRow.hasWait() ){
program.setSourceTask( this );
}
setSelectedMouseDown( true );
repaint();
}
if( program.getSourceTask() != null )
program.dragArrow( toGlobalPoint( mouseEvent.getX(),
mouseEvent.getY() ) );
}
public void mouseClicked( MouseEvent mouseEvent ){
if( !isSelected() ){
if( mouseEvent.isShiftDown() || mouseEvent.isControlDown() )
deselectNonTasks();
else
// deselect all other components
program.setAllSelected( false );
}
// toggle the selection state
setSelected( !isSelected() );
// set the source task for any drag in progress to null
program.setSourceTask( null );
program.clearDialogPane();
program.updateState();
repaint();
}
public void mouseEntered( MouseEvent mouseEvent ){
Task sourceTask = program.getSourceTask();
// if there is a drag in progress and it is from a
// task in a task row to another task row after it
if( sourceTask != null && program.appearsAfter( sourceTask, this ) ){
setSelectedMouseDown( true );
program.setTargetTask( this );
repaint();
}
}
public void mouseExited( MouseEvent mouseEvent ){
Task sourceTask = program.getSourceTask();
// if there is a drag in progress and the mouse
// has left the target task then unset target task
if( sourceTask != null && this != sourceTask ){
program.setTargetTask( null );
setSelectedMouseDown( false );
repaint();
}
}
public void mouseReleased( MouseEvent mouseEvent ){
Task sourceTask = program.getSourceTask();
Task targetTask = program.getTargetTask();
// if the mouse has been released and there is a drag
// in progress and the target task is valid then
// create the communication edge
if( sourceTask != null && targetTask != null ){
program.createEdge( sourceTask, targetTask );
program.setSourceTask( null );
program.setTargetTask( null );
sourceTask.setSelected( false );
targetTask.setSelected( false );
program.dragArrow( null );
program.repaint();
}
// else release the sourceTask
else if( sourceTask != null && targetTask == null ){
sourceTask.setSelected( false );
program.setSourceTask( null );
program.dragArrow( null );
program.repaint();
}
}
public void setProgram( Program program ){
this.program = program;
}
public void setSelected( boolean flag ){
super.setSelected( flag );
program.updateState();
}
public void setSelectedMouseDown( boolean flag ){
super.setSelected( flag );
}
public void deselectNonTasks(){
Vector selectedComponents = program.getAllSelected( new Vector() );
for( int i = 0; i < selectedComponents.size(); i++ ){
AbstractComponent component =
(AbstractComponent)selectedComponents.elementAt( i );
if( !(component instanceof Task) )
component.setSelected( false );
}
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| sstsimulator/coNCePTuaL | gui/Task.java | 1,893 | // if there is a drag in progress and the mouse | line_comment | en | false | 1,775 | 11 | 1,893 | 11 | 2,054 | 11 | 1,893 | 11 | 2,405 | 11 | false | false | false | false | false | true |
157294_1 | import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class Shop {
private Map<SportEquipment, Integer> goods;
private Map<SportEquipment, Integer> rentedGoods;
public Shop(){
goods = new HashMap<>();
rentedGoods = new HashMap<>();
}
void readGoods (String filename) throws FileNotFoundException, IOException, EmptyException{
File file = new File(filename);
if (!file.exists()) {
throw new FileNotFoundException();
}
BufferedReader in = new BufferedReader(new FileReader(file.getAbsoluteFile()));
String s;
in.readLine();//the first line is expected to be the csv table header and is skipped
while ((s = in.readLine()) != null) {
String[] data = s.split(";");
try {
if (data.length != 3) {
System.out.println("Incorrectly formatted line");
}
if (Integer.parseInt(data[1]) <= 0 || Integer.parseInt(data[2]) <=0 ){
System.out.println("Incorrectly formatted line. Price or quantity can't be negative or zero");
}
goods.put(new SportEquipment(data[0], Integer.parseInt(data[1])), Integer.parseInt(data[2]));
} catch (NumberFormatException e) {
System.out.println("Incorrectly formatted number");
}
} //display an error for every incorrectly formatted line but continue reading and adding to the map every correct one
if (goods.isEmpty()) { throw new EmptyException(); }
in.close();
}
void printGoods (Map<SportEquipment, Integer> map){
if (rentedGoods.isEmpty()) {System.out.println("No goods");}
else{
for (HashMap.Entry<SportEquipment, Integer> entry : map.entrySet()){
System.out.println(entry.getKey().toString() + " " + entry.getValue().toString());
}
}
}
void printAvailableGoods(){
System.out.println("Available:");
printGoods(goods);
}
void printRentedGoods(){
System.out.println("Rented:");
printGoods(rentedGoods);
}
void rentGoodsToCustomer(RentUnit customer, String name){
boolean isFound = false;
for (HashMap.Entry<SportEquipment, Integer> entry : goods.entrySet()){
if (entry.getKey().getTitle().equalsIgnoreCase(name)) {
isFound = true;
if (customer.rentGoods(entry.getKey())) {
if (entry.getValue() == 1) {
goods.remove(entry.getKey());
} else {
goods.put(entry.getKey(), (entry.getValue()) - 1);
}
boolean isFoundRented = false;
for (HashMap.Entry<SportEquipment, Integer> rentedEntry : rentedGoods.entrySet()) {
if (rentedEntry.getKey().getTitle().equalsIgnoreCase(name)) {
rentedGoods.put(rentedEntry.getKey(), (rentedEntry.getValue() + 1));
isFoundRented = true;
}
}
if (!isFoundRented){
rentedGoods.put(entry.getKey(), 1);
}
}
break;
}
}
if (!isFound){
System.out.println("There are no such goods in store");
}
}
void getBackGoods (RentUnit customer, int number){
SportEquipment returnedGoods = customer.returnGoods(number-1);
if (returnedGoods != null){
Integer qty = goods.get(returnedGoods);
if (qty == null) {
qty = 0;
}
goods.put(returnedGoods, qty+1);
qty = rentedGoods.get(returnedGoods);
if (qty == 1) {
rentedGoods.remove(returnedGoods);
}
else {
rentedGoods.put(returnedGoods, qty-1);
}
}
}
}
| Riliane/EPAM-task | src/Shop.java | 875 | //display an error for every incorrectly formatted line but continue reading and adding to the map every correct one | line_comment | en | false | 778 | 20 | 875 | 20 | 964 | 20 | 875 | 20 | 1,094 | 20 | false | false | false | false | false | true |
158893_5 | import static java.nio.file.StandardOpenOption.APPEND;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
public class Logger{
private Path mLogPath;
private int mEventClock;
// Initialises the directories for logging and creates the path
// to the log file
public Logger(String clientName, String testName, String dir){
String path = "./" + dir + "/" + testName + "/";
try{ maybeCreateFolder(path); }
catch(Exception e) { e.printStackTrace(); }
mLogPath = Paths.get(path + clientName + ".log");
mEventClock = 0;
}
// Creates a folder for storing logs if on doesn't already exist
private void maybeCreateFolder(String dir) throws IOException{
if (!Files.exists(Paths.get(dir)))
{ Files.createDirectories(Paths.get(dir)); }
}
// Appends a string to the log file
private void writeToLog(String event) throws IOException{
if (Files.exists(mLogPath))
{ Files.write(mLogPath, event.getBytes(), APPEND); }
else{ Files.write(mLogPath, event.getBytes()); }
}
// Increments the logical time on the clock
public synchronized void incrementEvents(){ mEventClock++; }
// Writes a message sent or received by the client to the log
public void logMessage(boolean sent, String message) throws IOException{
String header = "Event " + mEventClock + " ";
if (sent) { header += "Message Sent by Client: \r\n \r\n"; }
else { header += "Message Received by Client: \r\n \r\n"; }
header += message + "\r\n \r\n";
writeToLog(header);
incrementEvents();
}
// Adds an event to the client log
public void logEvent(String event, String details) throws IOException{
String header = "Event " + mEventClock + " ";
header += event + " occurred on Client: \r\n \r\n";
header += details + "\r\n \r\n";
writeToLog(header);
incrementEvents();
}
} | XDynames/Distributed_News_Aggregator | Logger.java | 566 | // Writes a message sent or received by the client to the log | line_comment | en | false | 470 | 13 | 566 | 13 | 567 | 13 | 566 | 13 | 629 | 14 | false | false | false | false | false | true |
159333_13 | // Mission Marcus
// mmarcu6 Project 2
import java.util.Vector;
import java.util.Scanner;
public class Game { // remember the name and the current place and list of places of the game
private String name;
private static Place currentPlace;
private Vector<Place> places;
private Vector<Artifact> artifacts; // possessions of the player.
@SuppressWarnings("unused") // this is to suppress the fact that artifact and direction are both unused.
public Game(Scanner scan)
{
places = new Vector<Place>(); // places and artifact lists
artifacts = new Vector<Artifact>();
String [] line;
String environment = LineParser.getCleanLine(scan); // get the clean line without comments
this.name = environment;
System.out.println(name);
int numberOfPlaces = 0; // find the number of places, directions, and artifacts.
int numberOfDirections = 0;
int numberOfArtifacts = 0;
while (scan.hasNextLine()) // while we still have lines.
{
String txt = LineParser.findNextLine(scan); // find the next line
line = txt.split("\\s+"); // split at space
if (line[0].equals("PLACES")) // if we are reading places
{
line = line[1].split("\\s+"); // split at the space
numberOfPlaces = Integer.parseInt(line[0]); // find the integer value
LineParser.findNextLine(scan);
for (int x = 0; x < numberOfPlaces; x++) // for the number of spaces..
{
Place newPlace = new Place(scan);
places.add(newPlace);
}
currentPlace = places.get(0); // set the current place to the first one read.
}
else if (line[0].equals("DIRECTIONS")) // if we are reading directions
{
line = line[1].split("\\s+");
numberOfDirections = Integer.parseInt(line[0]);
LineParser.findNextLine(scan);
for (int x = 0; x < numberOfDirections; x++)
{
Direction newDirection = new Direction(scan);
}
}
else if (line[0].equals("ARTIFACTS")) // if its artifacts..
{
line = line[1].split("\\s+");
numberOfArtifacts = Integer.parseInt(line[0]);
LineParser.findNextLine(scan);
for (int x = 0; x < numberOfArtifacts; x++)
{
Artifact art = new Artifact(scan);
}
}
}
}
public void print() // printing the current place and the name of the game.
{
System.out.println("The name of the game is " + name);
System.out.println("The Current Place is " + currentPlace.name());
System.out.println("Player artifacts are: ");
for (Artifact b: artifacts)
{
System.out.println(b.name() + ": " + b.description());
}
}
public static Place getCurrentPlace() // return the current place
{
return currentPlace;
}
public boolean get(String aName) // get the item
{
for (Artifact a : getCurrentPlace().getA()) // for all the artifacts in the place
{
if (a.name().toLowerCase().trim().equals(aName.toLowerCase().trim())) // if the name matches what is typed
{
artifacts.add(a); // add the artifacts
getCurrentPlace().getA().remove(a); // remove it from the place artifacts
System.out.println("You obtained the " + aName + "!");
return true;
}
}
System.out.print("That artifact doesn't exist!"); // if its not found,
return false;
}
public boolean drop(String aName) // drop the item
{
for (Artifact a : artifacts) // for all the artifacts in the place
{
if (a.name().toLowerCase().equals(aName.toLowerCase())) // if it equals the name
{
getCurrentPlace().getA().addElement(a); // add the inventory element back to the place
artifacts.remove(a); // remove it from player artifacts
System.out.println("You dropped the " + aName + "!");
return true;
}
}
System.out.print("That artifact doesn't exist!"); // if it doesnt exist.
return false;
}
public boolean use(String aName) // using a key
{
for (Artifact a: artifacts)
{
if (a.name().toLowerCase().equals(aName.toLowerCase()) && a.keyPattern() != 0) // if the item exists and is a key.
{
a.use();
return true;
}
}
System.out.print("You cant use that!"); // if its not a key
return false;
}
public void look()
{
System.out.println("Artifacts: \n");
for (Artifact b : currentPlace.getA())
{
System.out.println(b.name() + ": " + b.description());
}
}
public void inventory() //
{
System.out.println("Inventory: \n");
for (Artifact a : artifacts)
{
System.out.println("Name: " + a.name() + "\nValue: " + a.value() + "\nMobility: " + a.size() + " lb(s)\n");
}
}
public boolean addPlace(Place p1) // add a place to the places..
{
places.add(p1);
return true;
}
public boolean go(Place pl, String dir) // go to a place
{
for (Direction direct: pl.directions())
{
if (direct.match(dir.toUpperCase()) && !direct.isLocked()) // if the strings match and its not locked..
{
currentPlace = pl.followDirection(dir); // follow the direction
return true;
}
else if (direct.match(dir.toUpperCase()) && direct.isLocked()) // if they match but is locked..
{
System.out.println("That door is locked!");
}
}
return false;
}
public void play()
{
Scanner scanny = new Scanner(System.in);
String input = "";
while ((currentPlace.getID() != 1) && (!input.toLowerCase().equals("quit")) && (!input.toLowerCase().equals("exit")))
{
System.out.println("\n"); // while we arent at id 1 or quit or exit
currentPlace.display(); // display info
input = scanny.nextLine();
//checkFormat(input, currentPlace);
String []arr = input.toLowerCase().split("\\s+");
switch(arr[0])
{
case "get": // run the get command on the item typed
if (arr.length > 1)
{
get(input.substring(4, input.length()));
}
else
{
System.out.println("Invalid Command.");
}
break;
case "inve": // call inventory
inventory();
break;
case "inventory": // call inverntory
inventory();
break;
case "use": // use an item
if (arr.length > 1)
{
use(input.substring(4, input.length()));
}
else
{
System.out.println("Invalid Command.");
}
break;
case "drop": // drop signalled item
if (arr.length > 1)
{
drop(input.substring(5, input.length()));
}
else
{
System.out.println("Invalid Command.");
}
break;
case "go": // go to the direction noted.
if (arr.length > 1)
{
go(currentPlace, arr[1]);
}
else
{
System.out.println("Invalid Command.");
}
break;
case "exit": // exit
input = "exit";
break;
case "quit":
input = "quit";
break;
case "q":
input = "quit";
break;
case "look": // edit this one later?
look();
break;
default:
System.out.println("Invalid Command.");
break;
}
if (currentPlace == null) // if we are at a null area,
{
break; // break it and end.
}
}
scanny.close(); // closing out the scanner.
System.out.println("Thanks for playing!");
}
}
| Miszion/MysticCity | Game.java | 2,157 | // find the integer value | line_comment | en | false | 1,926 | 5 | 2,157 | 5 | 2,269 | 5 | 2,157 | 5 | 2,941 | 5 | false | false | false | false | false | true |
160054_9 | class RecAccess{
int a; //default access, public within its own package
public int b; //public access, it can be accessed from anywhere, from outside also
private int c; //private access, it can be acessed by the methods within this class only
//methods to access c
void setc(int i){
c=i; //set value of c
}
//methods to get c
int getc(){
return c;
}
}
class AccessTest{
public static void main(String args[]){
RecAccess obj= new RecAccess();
//a and b may be accessed directly
obj.a=10;
obj.b=20;
//c cannot be accessed directly
//obj.c=30;
//c can be accessed through its methods
obj.setc(100);
System.out.println("values of a,b,c are:" + obj.a+ " "+obj.b+" "+obj.getc());
}
} | Ankurac7/Java-Programs | q7.java | 222 | //c can be accessed through its methods | line_comment | en | false | 214 | 8 | 222 | 8 | 245 | 8 | 222 | 8 | 253 | 8 | false | false | false | false | false | true |
160436_7 | /*
* Copyright 2011 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*
* Modified by Rodney Tholanah, 2021
*/
package routing;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import core.DTNHost;
import core.Message;
import core.Settings;
import routing.util.EnergyModel;
import util.Tuple;
import core.Connection;
/**
* Router module mimicking the game-of-life behavior
*/
public class E_LifeRouter extends ActiveRouter {
/**
* Neighboring message count -setting id ({@value}). Two comma
* separated values: min and max. Only if the amount of connected nodes
* with the given message is between the min and max value, the message
* is accepted for transfer and kept in the buffer.
*/
public Map<String, Integer> delivered;
private void initDelivered()
{
this.delivered = new HashMap<>(200);
}
private static double battery_level_threshold;
public static final String NM_COUNT_S = "nmcount";
private int countRange[];
/**
* Constructor. Creates a new message router based on the settings in
* the given Settings object.
* @param s The settings object
*/
public E_LifeRouter(Settings s) {
super(s);
countRange = s.getCsvInts(NM_COUNT_S, 2);
battery_level_threshold = s.getInt("E_LifeRouter.battery_level_threshold");
}
/**
* Copy constructor.
* @param r The router prototype where setting values are copied from
*/
protected E_LifeRouter(E_LifeRouter r) {
super(r);
this.countRange = r.countRange;
initDelivered(); ///
}
/**
* Counts how many of the connected peers have the given message
* @param m The message to check
* @return Amount of connected peers with the message
*/
private int getPeerMessageCount(Message m) {
DTNHost me = getHost();
String id = m.getId();
int peerMsgCount = 0;
for (Connection c : getConnections()) {
if (c.getOtherNode(me).getRouter().hasMessage(id)) {
peerMsgCount++;
}
}
return peerMsgCount;
}
@Override
protected int checkReceiving(Message m, DTNHost from) {
int peerMsgCount = getPeerMessageCount(m);
if (peerMsgCount < this.countRange[0] ||
peerMsgCount > this.countRange[1]) {
return DENIED_POLICY;
}
/* peer message count check OK; receive based on other checks */
return super.checkReceiving(m, from);
}
@Override
public void update() {
int peerMsgCount;
Vector<String> messagesToDelete = new Vector<String>();
super.update();
if (isTransferring() || !canStartTransfer()) {
return; /* transferring, don't try other connections yet */
}
/* Try first the messages that can be delivered to final recipient */
if (exchangeDeliverableMessages() != null) {
return;
}
this.tryOtherMessages();
/* see if need to drop some messages... */
for (Message m : getMessageCollection()) {
peerMsgCount = getPeerMessageCount(m);
if (peerMsgCount < this.countRange[0] ||
peerMsgCount > this.countRange[1]) {
messagesToDelete.add(m.getId());
}
}
for (String id : messagesToDelete) { /* ...and drop them */
this.deleteMessage(id, true);
}
}
private Tuple<Message, Connection> tryOtherMessages(){
List<Tuple<Message, Connection>> messages = new ArrayList<Tuple<Message, Connection>>();
Collection<Message> msgCollection = getMessageCollection();
Collection<Message> msg_to_be_deleted = new HashSet<Message>();
for (Connection con : getConnections())
{
DTNHost other = con.getOtherNode(getHost());
E_LifeRouter othRouter = (E_LifeRouter) other.getRouter();
if (othRouter.isTransferring())
{
continue;
}
// obtain neighbour node's energy value
double nn_energy = (double) othRouter.getHost().getComBus().getProperty(EnergyModel.ENERGY_VALUE_ID);
// go through all messages in current node's buffer
for (Message m : msgCollection)
{
if(othRouter.hasMessage(m.getId()))
{
continue;
}
DTNHost dest = m.getTo();
//check if neighbour node's energy value is less than
//minimum energy threshold and not the destination node
String key = m.getId ()+"<β>"+m. getFrom().toString()+"<β>"+dest.toString();
if(othRouter.delivered.containsKey(key))
{
int cnt = (int)othRouter.delivered.get(key);
this.delivered.put(key, ++cnt);
msg_to_be_deleted.add(m);
continue;
}
if (nn_energy < this.battery_level_threshold && !dest.equals(other))
{
continue;
}
if(dest.equals(other))
{
messages.add(new Tuple<Message, Connection>(m, con));
}
else
{
messages.add(new Tuple<Message, Connection>(m, con));
}
}
}
return tryMessagesForConnected(messages);
}
@Override
public int receiveMessage(Message m, DTNHost from)
{
//-1 means the message is an acknowledgement message
if (m.getSize() == -1)
{
String ack_m = m.getId();
this.delivered.put(ack_m,1);
String[] parts = ack_m.split("<β>");
String m_Id = parts[0];
//delete the delivered message from the buffer
this.deleteMessage(m_Id,false);
return 0;
}
int i = super.receiveMessage (m, from ) ;
if(m.getTo().equals(this.getHost()) && i ==RCV_OK)
{
String ack_m = m.getId()+"<β>"+m.getFrom().toString()+"<β>"+m.getTo().toString();
//message with with size -1 is created indicating that it is an
//acknowledgement message
Message ack_mes = new Message ( this.getHost(),from,ack_m,-1);
//last sending node is is send the acknowledgement message
from.receiveMessage(ack_mes,this.getHost());
this.delivered.put(ack_m,1);
}
return i;
}
@Override
public E_LifeRouter replicate() {
return new E_LifeRouter(this);
}
} | Rody10/Implementation-of-energy-efficient-routing-protocols-for-infrastructure-less-Opportunistic-networks | E_LifeRouter.java | 1,807 | /* peer message count check OK; receive based on other checks */ | block_comment | en | false | 1,551 | 13 | 1,807 | 13 | 1,943 | 13 | 1,807 | 13 | 2,375 | 13 | false | false | false | false | false | true |
160498_4 | package net.fe.unit;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import static java.util.Collections.emptyList;
import net.fe.fightStage.*;
import net.fe.overworldStage.FieldSkill;
import net.fe.overworldStage.fieldskill.*;
// TODO: Auto-generated Javadoc
/**
* The Class Class.
*/
public final class Class implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 9144407404798873761L;
/** The crit. */
public final int crit;
/** The master skill. */
public final CombatTrigger masterSkill;
public final List<FieldSkill> fieldSkills;
/** The usable weapon. */
public final List<Weapon.Type> usableWeapon;
/** The name. */
public final String name;
/** The description. */
public final String description;
/**
* Instantiates a new class.
*
* @param name the name
* @param desc the desc
* @param c the class's innate crit rate
* @param m the class's combat abilities
* @param fs the class's field abilities
* @param types the types
*/
private Class(String name, String desc, int c, CombatTrigger m, List<? extends FieldSkill> fs, Weapon.Type... types){
this.crit = c;
this.masterSkill = m;
this.usableWeapon = java.util.Collections.unmodifiableList(Arrays.asList(types));
this.name = name;
this.description = desc;
this.fieldSkills = java.util.Collections.unmodifiableList(new java.util.ArrayList<FieldSkill>(fs));
}
@Override
public String toString() {
return "Class [" + name + ", " + description + ", ...]";
}
@Override
public int hashCode() {
return (((this.crit * 31 +
this.masterSkill.hashCode()) * 31 +
this.name.hashCode()) * 31 +
this.description.hashCode()) * 31 +
this.usableWeapon.stream().mapToInt((x) -> 1 << x.ordinal()).sum();
}
@Override
public boolean equals(Object other) {
if (other != null && other instanceof Class) {
Class o2 = (Class) other;
return this.crit == o2.crit &&
this.masterSkill.equals(o2.masterSkill) &&
this.usableWeapon.equals(o2.usableWeapon) &&
this.name.equals(o2.name) &&
this.description.equals(o2.description);
} else {
return false;
}
}
/**
* Creates the class.
*
* @param name the name
* @return the class
*/
public static Class createClass(String name){
List<FieldSkill> emptyFieldSkillList = emptyList();
//Lords
if(name.equals("Roy"))
return new Class("Lord",
"A noble youth who commands armies.",
0, new Aether(), Arrays.asList(new Shove()),
Weapon.Type.SWORD);
if(name.equals("Eliwood"))
return new Class("Lord",
"A courageous royal who commands armies.",
0, new Sol(false), emptyFieldSkillList,
Weapon.Type.SWORD, Weapon.Type.LANCE);
if(name.equals("Lyn"))
return new Class("Lord",
"A serene youth who commands armies.",
0, new Astra(), Arrays.asList(new Shove()),
Weapon.Type.SWORD, Weapon.Type.BOW);
if(name.equals("Hector"))
return new Class("Lord",
"A mighty noble who commands armies.",
0, new Luna(false), Arrays.asList(new Shove(), new Smite()),
Weapon.Type.AXE, Weapon.Type.SWORD);
if(name.equals("Eirika"))
return new Class("Lord",
"A brave princess who commands armies.",
0, new Luna(false), emptyFieldSkillList,
Weapon.Type.SWORD);
if(name.equals("Ephraim"))
return new Class("Lord",
"A skilled prince who commands armies.",
0, new Sol(false), emptyFieldSkillList,
Weapon.Type.LANCE);
if(name.equals("Marth"))
return new Class("Lord",
"A legendary prince who commands armies.",
0, new Aether(), Arrays.asList(new Shove()),
Weapon.Type.SWORD);
if(name.equals("Ike"))
return new Class("Lord",
"A radiant hero who commands armies.",
0, new Aether(), Arrays.asList(new Shove(), new Smite()),
Weapon.Type.SWORD, Weapon.Type.AXE);
//Other
if(name.equals("Sniper"))
return new Class("Sniper",
"An expert archer who has mastered the bow.",
10, new Deadeye(), Arrays.asList(new Shove()),
Weapon.Type.BOW, Weapon.Type.CROSSBOW);
if(name.equals("Hero"))
return new Class("Hero",
"Battle-hardened warriors who possess exceptional skill.",
0, new Luna(false), Arrays.asList(new Shove()),
Weapon.Type.SWORD, Weapon.Type.AXE);
if(name.equals("Berserker"))
return new Class("Berserker",
"A master pirate who deals devastating attacks.",
10, new Colossus(), Arrays.asList(new Shove(), new Smite()),
Weapon.Type.AXE);
if(name.equals("Warrior"))
return new Class("Warrior",
"An experienced fighter whose might is second to none.",
0, new Colossus(), Arrays.asList(new Shove(), new Smite()),
Weapon.Type.AXE, Weapon.Type.CROSSBOW);
if(name.equals("Assassin"))
return new Class("Assassin",
"A deadly killer who lives in the shadows.",
10, new Lethality(), Arrays.asList(new Shove()),
Weapon.Type.SWORD);
if(name.equals("Paladin"))
return new Class("Paladin",
"An experienced and dignified knight, possessing high mobility.",
0, new Sol(false), emptyFieldSkillList,
Weapon.Type.LANCE, Weapon.Type.SWORD, Weapon.Type.AXE);
if(name.equals("Sage"))
return new Class("Sage",
"A powerful magic user who wields mighty tomes.",
0, new Sol(true), Arrays.asList(new Shove()),
Weapon.Type.ANIMA, Weapon.Type.LIGHT, Weapon.Type.STAFF);
if(name.equals("General"))
return new Class("General",
"Armoured knights who possess overpowering strength and defense.",
0, new Pavise(), Arrays.asList(new Shove(), new Smite()),
Weapon.Type.AXE, Weapon.Type.LANCE);
if(name.equals("Valkyrie"))
return new Class("Valkyrie",
"A cleric who rides a horse into combat.",
0, new Miracle(), emptyFieldSkillList,
Weapon.Type.STAFF, Weapon.Type.LIGHT);
if(name.equals("Swordmaster"))
return new Class("Swordmaster",
"A seasoned myrmidon who has reached the pinnacle of swordsmanship.",
20, new Astra(), Arrays.asList(new Shove()),
Weapon.Type.SWORD);
if(name.equals("Sorcerer"))
return new Class("Sorcerer",
"A sinister warlock who wields potent dark magic.",
0, new Luna(true), Arrays.asList(new Shove()),
Weapon.Type.DARK, Weapon.Type.ANIMA);
if(name.equals("Falconknight"))
return new Class("Falconknight",
"Knights who control pegasi with great mastery.",
0, new Crisis(), emptyFieldSkillList,
Weapon.Type.LANCE, Weapon.Type.SWORD);
if(name.equals("Phantom"))
return new Class("Phantom",
"A phantom that fights for its summoner.",
0, new Miracle(), Arrays.asList(),
Weapon.Type.AXE);
throw new IllegalArgumentException("Unknown Class Name: " + name);
}
}
| HamaIndustries/FEMultiPlayer-V2 | src/net/fe/unit/Class.java | 2,143 | /** The master skill. */ | block_comment | en | false | 1,767 | 6 | 2,143 | 6 | 2,092 | 6 | 2,143 | 6 | 2,772 | 6 | false | false | false | false | false | true |
160933_4 | package homework04;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* This class is going to help organize a map that maps upc codes to another
* map the maps dates with quantites
* @author James Yeates
*
*/
public class HelperMap {
protected Map<String,TreeMap<GregorianCalendar,Integer>> quickSearch;
protected int daysSinceStartDate;
public HelperMap()
{
quickSearch = new TreeMap<String,TreeMap<GregorianCalendar,Integer>>();
daysSinceStartDate =0;
}
/**
* Adds a food item to the map, creates a new date map if needed. if date maps exists then the quantity is added.
* @param upcCode a String
*
* @param criticalDate GregorianCalendar
* @param quantity an integer
*/
public void addItem(String upcCode, GregorianCalendar criticalDate, int quantity)
{
if (upcCode == null || criticalDate == null || quantity < 1)
return;
if(quickSearch.containsKey(upcCode)){
if(quickSearch.get(upcCode).containsKey(criticalDate)){
int temp = quickSearch.get(upcCode).get(criticalDate).intValue()+ quantity;
quickSearch.get(upcCode).put(criticalDate, temp);
}
else
quickSearch.get(upcCode).put(criticalDate, quantity);
}
else
{
quickSearch.put(upcCode,new TreeMap<GregorianCalendar,Integer> ());
quickSearch.get(upcCode).put(criticalDate, quantity);
}
}
public void removeItem(String upcCode, GregorianCalendar criticalDate, int quantity)
{
if (upcCode == null || criticalDate == null || quantity < 1)
return;
//get the value for tha item
int amount = quickSearch.get(upcCode).get(criticalDate).intValue();
//remove all more has been asked for than that is available
if (amount < quantity)
quickSearch.get(upcCode).remove(criticalDate);
else
{
int newAmount = amount-quantity;
quickSearch.get(upcCode).put(criticalDate, newAmount);
}
}
public void removeExpiredItems(GregorianCalendar date)
{
Set<String> set = quickSearch.keySet();
Set<GregorianCalendar> datesToRemove = new TreeSet<GregorianCalendar>();
//loop throught each upcCode
for(String s : set){
Set<GregorianCalendar> dateSet = quickSearch.get(s).keySet();
//loop through dates
for(GregorianCalendar dates : dateSet){
if(dates.equals(date)){
quickSearch.get(s).remove(dates);
break;
}
}
}
}
public void itemRequested(String upcCode, int requestedQuantity,Set<GregorianCalendar> datesSet){
for(GregorianCalendar date : datesSet)
{
if(requestedQuantity<1)
break;
if(quickSearch.get(upcCode)==null)
continue;
if(quickSearch.get(upcCode).get(date)==null)
continue;
int tempAmount =quickSearch.get(upcCode).get(date).intValue();
if(tempAmount>requestedQuantity){
tempAmount -= requestedQuantity;
requestedQuantity=0;
quickSearch.get(upcCode).put(date, tempAmount);
}
else{
requestedQuantity -=tempAmount;
quickSearch.get(upcCode).remove(date);
}
}
}
}
| jimibue/cs2420 | homework04/HelperMap.java | 919 | //loop throught each upcCode | line_comment | en | false | 806 | 8 | 919 | 9 | 972 | 8 | 919 | 9 | 1,195 | 8 | false | false | false | false | false | true |
161352_6 | package stuytorrent.peer;
import java.net.Socket;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.charset.Charset;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import stuytorrent.Bitfield;
//import stuytorrent.Torrent;
//import stuytorrent.TorrentList;
import stuytorrent.peer.message.*;
/**
* represents another torrent Client to which we are connected
*/
public class Peer {
private final ExecutorService exec = Executors.newSingleThreadExecutor();
public Socket socket;
private Receiver receiver;
private Sender sender;
//private Downloader downloader;
//public Torrent torrent = null;
private String id; private byte[] info_hash;
//private Death death;
/** if HE is chocking ME */
public final AtomicBoolean peer_choking = new AtomicBoolean(true);
/** if HE is interested in ME */
public final AtomicBoolean peer_interested = new AtomicBoolean(false);
/** if I am chocking HIM */
public final AtomicBoolean am_choking = new AtomicBoolean(true);
/** if I am chocking HIM */
public final AtomicBoolean am_interested = new AtomicBoolean(false);
public Bitfield bitfield;
private AtomicBoolean closed = new AtomicBoolean(false);
/**
* called when we are initiating the connection
* @param socket the {@link java.net.Socket} to the Peer
* @param torrent the {@link Torrent} for which we want to download make a connection
*/
public Peer(Socket socket) throws IOException {
//startDeath();
this.socket = socket;
setStreams();
//this.torrent = torrent;
sendHandshake();
System.out.println("sent handshake");
//receiveHandshake();
System.out.println("received handshake");
if (!verify()) {
System.out.println("closed because unverified");
//close();
return;
}
System.out.println("verified");
setBitfield();
//setDownloader();
//torrent.addPeer(this);
System.out.println("starting");
startThreads();
System.out.println("started");
}
/**
* called when the Peer is intitiating the connection
* @param socket the {@link java.net.Socket} to the other client
* @param torrents the {@link Client#torrents} so we can determine if we are serving the torrent the Peer has requested
*/
public Peer(Socket socket, int poop) throws IOException {
this.socket = socket;
setStreams();
//receiveHandshake();
//torrent = torrents.getTorrent(info_hash);
//if (torrent == null) {
//System.out.println("Couldn't find torrent so closed");
//close();
//return;
//}
sendHandshake();
setBitfield();
//setDownloader();
//torrent.addPeer(this);
startThreads();
}
public Peer(String hostname, int port) throws IOException {
this(new Socket(hostname, port));
}
private void setStreams() throws IOException {
receiver = new Receiver(this, new DataInputStream(socket.getInputStream()), getKillPeer());
sender = new Sender(socket.getOutputStream(), getKillPeer());
}
/** sends a handshake
* <b>{@link torrent}</b> must be set
*/
public void sendHandshake() throws IOException {
//send(torrent.handshake);
}
/**
* receives a handshake and sets {@link id} and {@link info_hash}
* @return the info_hash from the handshake
*/
// TODO move to Receiver
/*public void receiveHandshake() throws IOException {
byte[] pstrlen, pstr, reserved, peer_id_bytes;
pstrlen = new byte[1];
in.read(pstrlen);
pstr = new byte[pstrlen[0]];
in.read(pstr);
reserved = new byte[8];
in.read(reserved);
info_hash = new byte[20];
System.out.println("read " + in.read(info_hash));
peer_id_bytes = new byte[20];
in.read(peer_id_bytes);
id = new String(peer_id_bytes, stuytorrent.Globals.CHARSET);
}*/
private boolean verify() {
return false;
//return Arrays.equals(torrent.info_hash, info_hash);
}
private void setBitfield() {
//bitfield = new Bitfield(torrent.pieces.length);
}
private void setDownloader() {
//downloader = new Downloader(this, torrent.pieces);
}
private void startThreads() {
//receiver.start();
//responder.start();
//downloader.start();
}
public byte[] getChunk(int index, int begin, int length) {
return new byte[0];
//return torrent.getChunk(index, begin, length);
}
public void submitChunk(int index, int begin, byte[] block) {
//torrent.addChunk(index, begin, block);
}
public Runnable getKillPeer() {
return new KillPeerTask(this);
}
public void choke() {
am_choking.set(true);
//send(new Choke());
}
public void unchoke() {
am_choking.set(false);
//send(new Unchoke());
}
public void interested() {
am_interested.set(true);
//send(new Interested());
}
public void notInterested() {
am_interested.set(false);
send(new NotInterested());
}
public void send(Message m) {}
// CHOKED/INTERESTED GETTERS
public boolean peer_choking() {
return peer_choking.get();
}
public boolean peer_interested() {
return peer_interested.get();
}
public boolean am_choking() {
return am_choking.get();
}
public boolean am_interested() {
return am_interested.get();
}
public void shutdownSender() {
sender.shutdown();
}
public void shutdownReceiver() {
//receiver.shutdown();
}
public void removeFromPeerList() {
}
public void takeAction(Message m) {
exec.submit(m.action(this));
}
public Sender getSender() {
return sender;
}
public synchronized void shutdown() {
try {
socket.close();
} catch (IOException e) {
System.out.println("Error on closing socket");
}
}
public String toString() {
return id;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if ( !(other instanceof Peer)) return false;
Peer otherPeer = (Peer) other;
return this.id.equals(otherPeer.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}
enum PeerStatus { NOOB, READY, CONNECTED }
| jbaum98/stuytorrent | peer/Peer.java | 1,661 | /** if HE is chocking ME */ | block_comment | en | false | 1,470 | 8 | 1,661 | 9 | 1,802 | 8 | 1,661 | 9 | 2,067 | 9 | false | false | false | false | false | true |
161689_4 | /**
* Copyright (c) 2017, Carnegie Mellon University. All Rights Reserved.
*/
import java.io.*;
/**
* The root class of all query operators that use a retrieval model
* to determine whether a query matches a document and to calculate a
* score for the document. This class has two main purposes. First, it
* allows query operators to easily recognize any nested query
* operator that returns a document scores (e.g., #AND (a #OR(b c)).
* Second, it is a place to store data structures and methods that are
* common to all query operators that calculate document scores.
*/
public abstract class QrySop extends Qry {
/**
* Get a score for the document that docIteratorHasMatch matched.
*
* @param r The retrieval model that determines how scores are calculated.
* @return The document score.
* @throws IOException Error accessing the Lucene index
*/
public abstract double getScore(RetrievalModel r)
throws IOException;
/**
* Get a score for the document if this document does not match the current term.
*
* @param r The retrieval model that determines how scores are calculated.
* @param docid The document ID.
* @return The document score.
* @throws IOException
*/
public abstract double getDefaultScore(RetrievalModel r, long docid)
throws IOException;
/**
* Initialize the query operator (and its arguments), including any
* internal iterators. If the query operator is of type QryIop, it
* is fully evaluated, and the results are stored in an internal
* inverted list that may be accessed via the internal iterator.
*
* @param r A retrieval model that guides initialization
* @throws IOException Error accessing the Lucene index.
*/
public void initialize(RetrievalModel r) throws IOException {
for (Qry q_i : this.args) {
q_i.initialize(r);
}
}
}
| MelonTennis/SearchEngine | QrySop.java | 446 | /**
* Initialize the query operator (and its arguments), including any
* internal iterators. If the query operator is of type QryIop, it
* is fully evaluated, and the results are stored in an internal
* inverted list that may be accessed via the internal iterator.
*
* @param r A retrieval model that guides initialization
* @throws IOException Error accessing the Lucene index.
*/ | block_comment | en | false | 431 | 91 | 446 | 87 | 469 | 96 | 446 | 87 | 501 | 100 | false | false | false | false | false | true |
161758_23 | /*
Copyright 2018-19 Mark P Jones, Portland State University
This file is part of mil-tools.
mil-tools is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
mil-tools 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 mil-tools. If not, see <https://www.gnu.org/licenses/>.
*/
package llvm;
/** Base class for representing LLVM types. */
public abstract class Type {
/** A class for representing primitive LLVM types. */
private static class Basic extends Type {
/** Name of the type. */
private String name;
/** Default value. */
private Value def;
/** Default constructor. */
private Basic(String name, Value def) {
this.name = name;
this.def = def;
}
/** Get the name of this type as a String. */
public String toString() {
return name;
}
/** Calculate a default value of this type, suitable for use as an initial value. */
public Value defaultValue() {
return def;
}
}
/** Represents the void type. TODO: eliminate this! */
public static final Type vd = new Basic("void", Word.ONES);
/** Represents the type of Boolean values. */
public static final Type i1 = new Basic("i1", Bool.FALSE);
/** Represents the type of 8 bit signed integer values. */
public static final Type i8 = new Basic("i8", Word.ZERO);
/** Represents the type of 16 bit signed integer values. */
public static final Type i16 = new Basic("i16", Word.ZERO);
/** Represents the type of 32 bit signed integer values. */
public static final Type i32 = new Basic("i32", Word.ZERO);
/** Represents the type of 64 bit signed integer values. */
public static final Type i64 = new Basic("i64", Word.ZERO);
/**
* Holds the LLVM type corresponding to the MIL Word type. Should obviously be set to a non-null
* value before use, and should be fixed throughout any given LLVM program.
*/
private static Type word;
/** Return the LLVM type corresponding to the MIL Word type. */
public static Type word() {
return word;
}
/** Set the LLVM type for Word using the given size value (which must be either 32 or 64). */
public static void setWord(int size) {
if (size == 32) {
word = i32;
} else if (size == 64) {
word = i64;
} else {
debug.Internal.error("Invalid LLVM wordsize " + size);
}
}
/** Get the type of the ith component in this (assumed) structure type. */
public Type at(int i) {
debug.Internal.error("invalid at() on type: " + this);
return null;
}
/** Represents a pointer type. */
private static class PtrType extends Type {
/** The type of value that is pointed to. */
private Type ty;
/** Default constructor. */
private PtrType(Type ty) {
this.ty = ty;
}
/** Get the type of value that this (assumed) pointer type points to. */
public Type ptsTo() {
return ty;
}
/** Append the name of this type to the specified buffer. */
public void append(StringBuilder buf) {
ty.append(buf);
buf.append('*');
}
/** Calculate a default value of this type, suitable for use as an initial value. */
public Value defaultValue() {
return new Null(this);
}
}
/** Get the type of value that this (assumed) pointer type points to. */
public Type ptsTo() {
debug.Internal.error("invalid ptsTo() on a type: " + this);
return null;
}
/**
* Identifies the type of pointers to this type, or null if there has not been any previous
* reference to this pointer type.
*/
private Type ptrType = null;
/**
* Return the type of pointers to values of this type. Initializes the ptrType field if necessary
* to cache the pointer type for future uses.
*/
public Type ptr() {
return (ptrType == null) ? ptrType = new PtrType(this) : ptrType;
}
/** Get the type of the ith component in this (assumed) structure type. */
public Type definition() {
debug.Internal.error("invalid definition() on type: " + this);
return null;
}
/** Get the name of this type as a String. */
public String toString() {
StringBuilder buf = new StringBuilder();
this.append(buf);
return buf.toString();
}
/** Append the name of this type to the specified buffer. */
public void append(StringBuilder buf) {
buf.append(toString());
}
/** Append the types in the given array to the specified buffer as a comma separated list. */
static void append(StringBuilder buf, Type[] tys) {
for (int i = 0; i < tys.length; i++) {
if (i > 0) {
buf.append(", ");
}
tys[i].append(buf);
}
}
/** Calculate a default value of this type, suitable for use as an initial value. */
public abstract Value defaultValue();
public Type codePtrType() {
return ptsTo().definition().at(0);
}
}
| habit-lang/mil-tools | src/llvm/Type.java | 1,321 | /** Calculate a default value of this type, suitable for use as an initial value. */ | block_comment | en | false | 1,275 | 18 | 1,321 | 18 | 1,450 | 18 | 1,321 | 18 | 1,578 | 19 | false | false | false | false | false | true |
162311_6 | /*=============================================
class Rogue -- protagonist of Ye Olde RPG
=============================================*/
public class Rogue extends Character {
// ~~~~~~~~~~~ INSTANCE VARIABLES ~~~~~~~~~~~
// inherited from superclass
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*=============================================
default constructor
pre: instance vars are declared
post: initializes instance vars.
=============================================*/
public Rogue() {
super();
_hitPts = 50;
_strength = 100;
_defense = 30;
_attack = 0.9;
}
/*=============================================
overloaded constructor
pre: instance vars are declared
post: initializes instance vars. _name is set to input String.
=============================================*/
public Rogue( String name ) {
this();
if (!name.equals("")) {
_name = name;
}
}
/*=============================================
void specialize() -- prepares character for special attack
pre:
post: Attack of character is increased, defense is decreased
=============================================*/
public void specialize() {
_attack = 1;
_defense = 25;
}
/*=============================================
void normalize() -- revert stats back to normal
pre:
post: Attack and defense of character is de-specialized
=============================================*/
public void normalize() {
_attack = .9;
_defense = 30;
}
/*=============================================
String about() -- returns descriptions character type
pre:
post: Info is returned
=============================================*/
public String about() {
return "Rogues are sneaky, fast, and elusive, but aren't very sturdy.";
}
/*==========================
String heroSpecial()
pre:
post: executes a character's special move, for example, a priest would heal itself, and
returns a string summarizing what happened.
========================*/
public String heroSpecial(){
if (((int) (Math.random()*99)) >= 50){
this._hitPts -=5;
this._defense -=5;
this._strength +=20;
return "your rogue sacrifices HP and Defence for its strength to increase to " + this._strength + "but it now has " + this._hitPts + " HP " + this._defense + " defence";
}
else {
this._hitPts-=-15;
return "your rogue messes up the sacrifice, lowering HP by 15";
}
}
}//end class Rogue
| siuryan-cs-stuy/YoRPG_FileNotFound | Rogue.java | 593 | /*=============================================
void specialize() -- prepares character for special attack
pre:
post: Attack of character is increased, defense is decreased
=============================================*/ | block_comment | en | false | 541 | 36 | 593 | 38 | 679 | 43 | 593 | 38 | 783 | 51 | false | false | false | false | false | true |
162488_11 | /**
* The Graduate class contains information about a graduate student at Chapman University
* @author Evelyn Lawrie
* Student ID: 2364909
* lawrie@chapman.edu
* CPSC 231-04
* MP4: Inheritance, Interfaces, & Abstract Classes - Oh My!
* @version 1.0
* @see Printable
* @see Affiliate
* @see Faculty
* @see Student
* @see Staff
* @see Assistant
* @see Associate
* @see Full
* @see Graduate
* @see Undergrad
* @see FullTime
* @see PartTime
* @see AffiliatesDriver
*/
import java.util.Scanner;
public class Graduate extends Student {
/** An int representing the number of papers the graduate student has published */
private int m_numPapers;
/** An int representing the graduate student's thesis advisor */
private int m_advisor;
/** The default constructor for the Graduate class */
public Graduate() {
super();
m_numPapers = 0;
m_advisor = 0;
}
/**
* Creates a graduate student based their name, age, address, phone number, ID, starting year at Chapman, major, minor, class standing, number of papers published, and thesis advisor
* @param name The graduate students's name
* @param age The graduate student's age
* @param address The graduate student's address
* @param phoneNumber The graduate student's phone number
* @param id The graduate student's ID
* @param startingYear The graduate student's starting year at Chapman
* @param major The graduate student's major
* @param minor The graduate student's minor
* @param classStanding The graduate student's class standing
* @param numPapers The number of papers that the graduate student has published
* @param advisor The graduate student's thesis advisor
*/
public Graduate(String name, int age, String address, long phoneNumber, int id, int startingYear, String major, String minor, String classStanding, int numPapers, int advisor) {
super(name, age, address, phoneNumber, id, startingYear, major, minor, classStanding);
m_numPapers = numPapers;
m_advisor = advisor;
}
/**
* Mutator for number of papers published attribute
* @param numPapers The number of papers that the graduate student has published
*/
public void setNumPapers(int numPapers) {
m_numPapers = numPapers;
}
/**
* Mutator for advisor attribute
* @param advisor The graduate student's thesis advisor
*/
public void setAdvisor(int advisor) {
m_advisor = advisor;
}
/**
* Accessor for number of papers published attribute
* @return An int representing the number of papers that the graduate student has published
*/
public int getNumPapers() {
return m_numPapers;
}
/**
* Accessor for advisor attribute
* @return An int representing the graduate student's thesis advisor
*/
public int getAdvisor() {
return m_advisor;
}
/**
* The print method prints all information associated with an instance of the Graduate class
*/
public void print() {
super.print();
System.out.println("Number of Papers Published: " + m_numPapers);
System.out.println("Advisor: " + m_advisor);
}
/**
* The getInput method prompts the user for data to store as class attributes
* @param sin A Scanner used to retrieve user input
*/
public void getInput(Scanner sin) {
super.getInput(sin);
System.out.println("Enter the number of papers published:");
this.setNumPapers(sin.nextInt());
sin.nextLine();
System.out.println("Enter the ID of the thesis advisor:");
this.setAdvisor(sin.nextInt());
sin.nextLine();
}
/**
* The toString method allows for pretty printing of an instance of the Graduate class
* @return a String representing all the information held by an instance of the Graduate class
*/
public String toString() {
String s = "Graduate,";
s += super.toString();
s += m_advisor + ",";
s += m_numPapers + "\n";
return s;
}
}
| elawrie/JavaMP_CPSC231 | Graduate.java | 1,063 | /**
* The toString method allows for pretty printing of an instance of the Graduate class
* @return a String representing all the information held by an instance of the Graduate class
*/ | block_comment | en | false | 943 | 39 | 1,063 | 39 | 1,083 | 42 | 1,063 | 39 | 1,225 | 48 | false | false | false | false | false | true |
164388_6 | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* This is the Menu class. It extends JPanel.
* It contains the basic elements of the start screen at the beginning of the game.
*
* @author Yemin Shou
*/
public class Menu extends JPanel implements ActionListener
{
//private buttons
private JButton start, instructions, leaderboard;
/**
* Constructor method builds Menu panel
*/
public Menu()
{
super();
setLayout(null);
setBounds(0, 0, 880,700);
setBackground(new Color(88,60,100));
//title is set
JLabel title = new JLabel();
title.setBounds((getWidth()-600)/2, 20, 600, 250);
title.setIcon(new ImageIcon("logo.gif"));
add(title);
//buttons are set
start = new JButton();
start.setBounds((getWidth()-350)/2,280, 350, 300);
start.setIcon(new ImageIcon("play.gif"));
start.setBorder(null);
start.addActionListener(this);
add(start);
instructions = new JButton();
instructions.setBounds(50,380,200,160);
instructions.setIcon(new ImageIcon("instructionstart.gif"));
instructions.setBorder(null);
instructions.addActionListener(this);
add(instructions);
leaderboard = new JButton();
leaderboard.setBounds(630,380,200,160);
leaderboard.setIcon(new ImageIcon("leaderboard.gif"));
leaderboard.setBorder(null);
leaderboard.addActionListener(this);
add(leaderboard);
}//end constructor
/**
* Implemented from ActionListener
* This method will wait for an event to occur (ex.button being pressed) and will react to that action occurring
*/
public void actionPerformed(ActionEvent e)
{
//functions that will occur when the buttons are pressed
if(e.getSource() == start)
Game.start();
if(e.getSource() == instructions)
new Instructions();
if(e.getSource() == leaderboard)
new Leaderboard();
}//end actionPerformed
}//end class
| yeminlemon/Jewels | src/Menu.java | 558 | /**
* Implemented from ActionListener
* This method will wait for an event to occur (ex.button being pressed) and will react to that action occurring
*/ | block_comment | en | false | 479 | 34 | 558 | 34 | 571 | 37 | 558 | 34 | 694 | 41 | false | false | false | false | false | true |
165756_18 | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
/**
* This is where the main program is run. Honestly, never ran it outside of an IDE, but it worked there.
* @author James
*
*/
public class Client {
/**This program is not networked. It is a blockchain,
* but it runs locally. These accounts can send and
* recieve transactions, and be logged in to, but
* are all hardcoded and local.
*/
Account Ahmed = new Account("Ahmed", 500);
Account Iddo = new Account("Iddo", 499); //get wrecked
Account Ben = new Account("Ben", 500);
Account Rishi = new Account("Rishi", 500);
Account Roshan = new Account("Roshan", 500);
Account Pimmy = new Account("Pimmy", 500);
Account Shannon = new Account("Shannon", 500);
Account Casey = new Account("Casey", 500);
Account Nick = new Account("Nick", 500);
Account Gabe = new Account("Gabe", 500);
Account Tristan = new Account("Tristan", 500);
Account Martinez = new Account("Martinez", 500);
/**
* When a user mines a block, they get paid from here.
*
* In a more robust version, the miner payout would be a method in block, but
* this is simpler (while less secure, but it's local, come on) and cooperates
* with other methods better, because it's just a transaction
*
*/
Account Odin = new Account("Mining Rewarder", 2147483647);
public Block currentBlock = new Block();
public Account signedInUser = Tristan;
//This is where the blockchain is
public Stack<Block> blockchain = new Stack<Block>();
//probably a better way to do this
public ArrayList<Account> allAccounts = new ArrayList<Account>(Arrays.asList(
Ahmed, Iddo, Ben, Rishi, Roshan, Pimmy,
Shannon, Casey, Nick, Gabe, Tristan, Martinez
));
//Constructs a transaction from user inputs
public Transaction buildTransaction() {
Transaction r = new Transaction();
r.setFrom(signedInUser);
r.setTo(chooseUserFromList());
StdOut.print("How many coins would you like to send?\n> ");
int amount = StdIn.readInt();
r.setAmount(amount);
StdOut.println("Transaction built. That transaction will be in Block #"
+ currentBlock.placement + ".");
this.currentBlock.addTransaction(r);
return r;
}
//Builds the special transaction for Mining a block
public Transaction minerReward(Account a) {
return new Transaction(Odin, 5, a);
}
//All user input is ints, to simplify things
public Account chooseUserFromList() {
StdOut.println("Choose a user from the list! Enter number below.");
int tick = 0;
for (Account a : allAccounts) {
StdOut.println(tick + " " + a.getName());
tick++;
}
StdOut.print("> ");
int name = StdIn.readInt();
while (name >= allAccounts.size() || name < 0) {
StdOut.println("That didn't work. Try again?");
StdOut.print("> ");
name = StdIn.readInt();
}
return allAccounts.get(name);
}
public void signInUser(Account a) {
this.signedInUser = a;
}
public void addBlockToChain(Block b) {
blockchain.add(b);
}
/**
* Reads every transaction in a block and updates balances. Here's why that Odin solution to miner
* payouts is used, it fits in to this cleanly
* @param b
*/
public void updateAccountBalancesByBlock(Block b) {
for (Transaction t : b.getBlockData()) {
t.getFrom().deductCoins(t.getAmount());
t.getTo().gainCoins(t.getAmount());
}
}
//main loop
public int centralAsk() {
StdOut.println("\nWhat do you want to do?"
+ "\n[0] View your transaction history"
+ "\n[1] Send some coins to a friend"
+ "\n[2] Read the Blockchain"
+ "\n[3] Read another user's TX history"
+ "\n[4] Read the contents of the current block"
+ "\n[5] Mine the current block"
+ "\n[6] Sign in as a differnt user"
+ "\n[7] Help Menu"
);
StdOut.print("> ");
return StdIn.readInt();
}
//Shows every transaction an account is a part of
public void showTransactionHistory(Account a) {
StdOut.println("The account " + a.getName() + " currently hodls " + a.balance + " coins.");
StdOut.println("The genesis balance was " + a.genesisBalance + " Coins."
+ " Transactions made to or from " + a.getName() + ":");
boolean found = false;
for (Block b : blockchain) {
for (Transaction t : b.getBlockData()) {
if ((t.getFrom() == a) || t.getTo() == a) {
found = true;
if (t.getFrom() == Odin) {
StdOut.println("At " + t.getTimeStamp() + " " + a.getName()
+ " mined block #" + b.placement
+ " and earned " + t.getAmount() + " coins");
} else {
StdOut.println(t.readable());
}
}
}
}
if (!found) {
StdOut.println(a.getName() + " has never made a transaction on the network.");
}
}
/**
* Shows contents of the current, unmined block.
* Not actually very useful, but a good way to show of the datastructure of
* what a blockchain is. This is for a class, after all
*/
public void currentBlockStatus() {
StdOut.println(currentBlock.polishedPrintEntireBlock());
}
/**
* Adds the current block to chain and creates new current.
* Assumes the current block has been mined/solved.
*/
public void generateNewCurrentBlock() {
this.blockchain.add(currentBlock);
String passTheHashBro = currentBlock.hashBlockData();
currentBlock = new Block();
currentBlock.setPlacement(this.blockchain.size());
currentBlock.setPriorBlockHash(passTheHashBro);
}
public void signInAsOtherUser() {
this.signedInUser = chooseUserFromList();
}
//Prints all data from all blocks
public void readBlockchain() {
if (blockchain.size() == 0) {
StdOut.println("There's no blocks yet! Mine one to get things rolling.");
} else {
for (Block b : this.blockchain) {
StdOut.println(b.polishedPrintEntireBlock());
}
}
}
//Adds miner reward transaction and does POW. genereates new current block.
public void mineCurrentBlock(int difficulty, boolean loud) {
currentBlock.addTransaction(minerReward(signedInUser));
this.currentBlock.mine(difficulty, loud);
updateAccountBalancesByBlock(currentBlock);
generateNewCurrentBlock();
}
public void printHelpMenu(int difficulty) {
StdOut.println(
"Vertex Network Version 2.4.1"
+ "\nNetwork Hashing Difficulty: " + difficulty
+ "\nVertex Network* has an asterisk because"
+ "\nnothing about this program is networked."
+ "\n"
+ "\nVertex Coins are not legal tender."
+ "\nAs few animals as possible were harmed in the"
+ "\nmaking of this program. Any references to actual"
+ "\npersons, events, establishments, or"
+ "\nlocations are purely coincidental.");
}
public void printLogo() {
StdOut.println(
" __ __ _______ ______ _______ _______ __ __ \r\n" +
"| | | || || _ | | || || |_| | \r\n" +
"| |_| || ___|| | || |_ _|| ___|| | \r\n" +
"| || |___ | |_||_ | | | |___ | | \r\n" +
"| || ___|| __ | | | | ___| | | \r\n" +
" | | | |___ | | | | | | | |___ | _ | \r\n" +
" |___| |_______||___| |_| |___| |_______||__| |__| \r\n" +
" __ _ _______ _______ _ _ _______ ______ ___ _ * \r\n" +
"| | | || || || | _ | || || _ | | | | | \r\n" +
"| |_| || ___||_ _|| || || || _ || | || | |_| | \r\n" +
"| || |___ | | | || | | || |_||_ | _| \r\n" +
"| _ || ___| | | | || |_| || __ || |_ \r\n" +
"| | | || |___ | | | _ || || | | || _ | \r\n" +
"|_| |__||_______| |___| |__| |__||_______||___| |_||___| |_| \n"
);
}
//RUNS THE PROGRAM
public void run() {
printLogo();
StdOut.println("Welcome to the Vertex Network*!");
StdOut.println("You're logged in as " + signedInUser.name);
int difficulty = 5; //4 is instant, 5 is ~10 secs, 6 is ~2 minutes
while (true) {
int process = centralAsk();
StdOut.println();
if (process == 0) {
showTransactionHistory(this.signedInUser);
}
if (process == 1) {
buildTransaction();
}
if (process == 2) {
readBlockchain();
}
if (process == 3) {
showTransactionHistory(chooseUserFromList());
}
if (process == 4) {
currentBlockStatus();
}
if (process == 5) {
mineCurrentBlock(difficulty, true);
}
if (process == 6) {
signInAsOtherUser();
StdOut.println("\nWelcome to the Vertex Network*!");
StdOut.println("You're logged in as " + signedInUser.name);
}
if (process == 7) {
printHelpMenu(difficulty);
}
}
}
public static void main(String[] args) {
/**
* honestly, this run() way of doing things seems like a bit of a redundant step,
* but that's how the prof does all of her programs so whatevs
*/
new Client().run();
}
}
| kh3dron/Vertex-Network | src/Client.java | 2,972 | /**
* honestly, this run() way of doing things seems like a bit of a redundant step,
* but that's how the prof does all of her programs so whatevs
*/ | block_comment | en | false | 2,719 | 42 | 2,972 | 41 | 3,001 | 45 | 2,972 | 41 | 3,629 | 49 | false | false | false | false | false | true |
165823_20 | //
// Copyright Martin Cenek <drcenek@gmail.com> 2016-2019
//
// All source code is released under the terms of the MIT License.
// See LICENSE for more information.
// Contributions from:
// Eric Pak, Levi Oyster, Boyd Ching, Rowan Bulkow, Neal Logan, Mackenzie Bartlett
//
//package netgen;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
/**
*
* @author Neal
*/
public class IO {
//Reads a file & returns each line in the file as a string
public static String readFileAsString(String fileName)
{
return concatenateAll(readFileAsLines(fileName));
}
//Reads a file and returns its lines in an arraylist
public static ArrayList<String> readFileAsLines(String fileName) {
ArrayList<String> lines = new ArrayList<>();
Scanner inFile = null;
try {
//Debugging print statements
// System.out.println(new File("").getAbsolutePath());
// System.out.println(fileName);
inFile = new Scanner(new FileReader(fileName));
} catch (Exception e) {
e.printStackTrace();
//System.out.println("Failed to open input file. Exiting.");
System.exit(-1);
}
while (inFile.hasNextLine()) {
lines.add(inFile.nextLine());
}
return lines;
}
public static String importDirectory(String dirName)
{
File[] files = new File("../"+dirName).listFiles();
System.out.println(dirName);
//System.out.println(files.length);
String returnString = "";
for(int i=0;i<files.length-1; i++)
{
if(files[i].toString().endsWith(".txt")){
try {
//importGraph(files[i].getName());
returnString.concat(concatenateAll(readFileAsLines(files[i].getName())));
} catch (Exception e) {
System.out.println(files[i].toString() + " is not a graph file");
}
}
}
return returnString;
}
//Combines the lines of the lines of the arraylist into a single String, separated by newline characters
//TODO: throw exception if too many chars in strings?
//Must have a total of less than about 2^30 characters
public static String concatenateAll(ArrayList<String> lines) {
String condensed = "";
for (String line : lines) {
condensed += ("\n" + line);
}
return condensed;
}
//Takes the lines of a .dl file and returns a weighted edgelist
public static HashMap<SemanticPair, Double> importWeightedEdgelist(ArrayList<String> input) {
HashMap<SemanticPair, Double> edges = new HashMap<>();
for(int i = 4; i < input.size(); i++) {
String[] line = input.get(i).split("\\s");
edges.put(new SemanticPair(line[0], line[1]), Double.parseDouble(line[2]));
}
return edges;
}
}
| mcenek/SNAP | NetGen/IO.java | 764 | //Must have a total of less than about 2^30 characters
| line_comment | en | false | 664 | 16 | 764 | 16 | 830 | 16 | 764 | 16 | 914 | 17 | false | false | false | false | false | true |
165864_14 | package jump61;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.io.FileReader;
import java.io.IOException;
/** The GUI for jump61 game.
* @author Derrick Mar
*/
public class GameGui {
/** holds game. */
private Game game;
/** entire Window. */
private JFrame frame;
/** totalPanel holds all panels. */
private JPanel totalPanel;
/** panel for board of game. */
private JPanel gamePanel;
/** panel for options of game. */
private JPanel optionPanel;
/** help button. */
private JButton help;
/** size button that changes the size of the board. */
private JButton size;
/** start button. */
private JButton start;
/** set button. */
private JButton set;
/** move button. */
private JButton move;
/** restart button. */
private JButton restart;
/** manual button. */
private JButton manual;
/** auto button. */
private JButton auto;
/** constraints to design totalPanel layout. */
private GridBagConstraints c;
/** pixels for width of window. */
public static final int WINDOW_W = 600;
/** pixels for height of window. */
public static final int WINDOW_H = 800;
/** pixels of size of game board. */
public static final int GAMEPANEL_PIXEL = 450;
/** pixels for width of option panel. */
public static final int OPTION_W = 200;
/** pixels for height of option panel. */
public static final int OPTION_H = 500;
/** pixels for width of help text area. */
public static final int TA_W = 20;
/** pixels for height of help text area. */
public static final int TA_H = 60;
/** GameGui constructor. Take in the current game CURRGAME. */
public GameGui(Game currgame) {
game = currgame;
frame = new JFrame("Jump-61 by Derrick Mar");
frame.setSize(WINDOW_H, WINDOW_W);
frame.setDefaultCloseOperation(javax.swing.WindowConstants.
EXIT_ON_CLOSE);
totalPanel = new JPanel(new GridBagLayout());
frame.getContentPane().add(totalPanel, BorderLayout.NORTH);
c = new GridBagConstraints();
gamePanel = new JPanel();
gamePanel = setBoard(gamePanel);
gamePanel.setPreferredSize(new Dimension(GAMEPANEL_PIXEL,
GAMEPANEL_PIXEL));
c.insets = new Insets(10, 10, 10, 10);
c.gridx = 0; c.gridy = 0;
totalPanel.add(gamePanel, c);
optionPanel = new JPanel(new GridLayout(8, 1));
optionPanel.setPreferredSize(new Dimension(OPTION_W, OPTION_H));
optionPanel = initializeComp(optionPanel);
c.gridx = 1; c.gridy = 0;
totalPanel.add(optionPanel, c);
frame.setVisible(true);
}
/** takes in a PANEL and initializes its components and finally
* returns the new Jpanel. */
public JPanel initializeComp(JPanel panel) {
start = new JButton("start");
panel.add(start);
start.addActionListener(new StartAction());
restart = new JButton("restart");
panel.add(restart);
restart.addActionListener(new RestartAction());
size = new JButton("size");
panel.add(size);
size.addActionListener(new SizeAction());
manual = new JButton("manual");
panel.add(manual);
manual.addActionListener(new ManualAction());
auto = new JButton("auto");
panel.add(auto);
auto.addActionListener(new AutoAction());
set = new JButton("set");
panel.add(set);
set.addActionListener(new SetAction());
move = new JButton("move");
panel.add(move);
move.addActionListener(new MoveAction());
help = new JButton("help");
panel.add(help);
help.addActionListener(new HelpAction());
return panel;
}
/** Inner class that controls size button. */
class HelpAction implements ActionListener {
/** HelpAction constructor that takes in R and C for row
* and column for Makemove. */
/** action performed with mouseclick event E. */
public void actionPerformed(ActionEvent e) {
try {
JTextArea ta = new JTextArea(TA_W, TA_H);
ta.read(new FileReader("jump61/Help.txt"), null);
ta.setEditable(false);
JOptionPane.showMessageDialog(help, new JScrollPane(ta));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
/** Inner class that controls size button. */
class AutoAction implements ActionListener {
/** AutoAction constructor that takes in R and C for row
* and column for Makemove. */
/** action performed with mouseclick event E. */
public void actionPerformed(ActionEvent e) {
String setmanualInput = JOptionPane.
showInputDialog(null,
"What player would you like to change to a"
+ "computer player?\n(Type either red for Red "
+ "player blue for Blue player).");
game.executeCommand("auto " + setmanualInput);
}
}
/** Inner class that controls size button. */
class ManualAction implements ActionListener {
/** ManualAction constructor that takes in R and C for row
* and column for Makemove. */
/** action performed with mouseclick event E. */
public void actionPerformed(ActionEvent e) {
String setmanualInput = JOptionPane.
showInputDialog(null,
"What player would you like to change to "
+ "manual?\n (Type either red for Red player "
+ "or blue for Blue player).");
game.executeCommand("manual " + setmanualInput);
}
}
/** Inner class that controls size button. */
class RestartAction implements ActionListener {
/** RestartAction constructor that takes in R and C for row
* and column for Makemove. */
/** action performed with mouseclick event E. */
public void actionPerformed(ActionEvent e) {
game.restartGame();
gamePanel = setBoard(gamePanel);
gamePanel.revalidate();
}
}
/** Inner class that controls move button. */
class MoveAction implements ActionListener {
/** MoveAction constructor that takes in R and C for row
* and column for Makemove. */
/** action performed with mouseclick event E. */
public void actionPerformed(ActionEvent e) {
String moveInput = JOptionPane.
showInputDialog(null,
"What would you like the move number to be?\n"
+ "(Odd number means red will move next and "
+ "even number means blue will move next).");
game.executeCommand("move " + moveInput);
}
}
/** Inner class that controls size button. */
class SetAction implements ActionListener {
/** SetAction constructor that takes in R and C for row
* and column for Makemove. */
/** action performed with mouseclick event E. */
public void actionPerformed(ActionEvent e) {
String setInput = JOptionPane.
showInputDialog(null,
"Set the move of the player by using this "
+ "format below: \nR C N P where R is row, "
+ "C is column, N is number of spots, "
+ "and P is player (either βbβ "
+ "or βrβ for blue or red).");
game.executeCommand("set " + setInput);
gamePanel = setBoard(gamePanel);
gamePanel.revalidate();
}
}
/** Inner class that controls size button. */
class StartAction implements ActionListener {
/** StartAction constructor that takes in R and C for row
* and column for Makemove. */
/** action performed with mouseclick event E. */
public void actionPerformed(ActionEvent e) {
game.start();
game.aiMove();
gamePanel = setBoard(gamePanel);
gamePanel.revalidate();
}
}
/** Inner class that controls size button. */
class SizeAction implements ActionListener {
/** ButtonAction constructor that takes in R and C for row
* and column for Makemove. */
/** action performed with mouseclick event E. */
public void actionPerformed(ActionEvent e) {
String sizeInput = JOptionPane.
showInputDialog(null,
"Input the new size of the board");
game.executeCommand("size " + sizeInput);
gamePanel = setBoard(gamePanel);
gamePanel.revalidate();
}
}
/** set the Board after ever move. Transforms PANEL, by returning
* edited JPanel */
public JPanel setBoard(JPanel panel) {
panel.removeAll();
Square[][] currBoard = game.getMutableBoard().getcurrBoard();
int N = currBoard.length;
panel.setLayout(new GridLayout(N, N));
for (int i = 0; i < N; i += 1) {
for (int j = 0; j < N; j += 1) {
Square square = currBoard[i][j];
JButton btn = new JButton(square.getStringRep());
if (square.getColor() == Color.WHITE) {
btn.setBackground(java.awt.Color.white);
} else if (square.getColor() == Color.RED) {
btn.setBackground(java.awt.Color.red);
} else {
btn.setBackground(java.awt.Color.blue);
}
panel.add(btn);
btn.addActionListener(new ButtonAction(i + 1, j + 1));
}
}
return panel;
}
/** Inner class that controls actions to button. */
class ButtonAction implements ActionListener {
/** ButtonAction constructor that takes in R and CL for row
* and column for Makemove. */
ButtonAction(int r, int cl) {
row = r;
col = cl;
}
/** action performed with mouseclick event E. */
public void actionPerformed(ActionEvent e) {
game.start();
game.aiMove();
game.makeMove(row, col);
GameGui.this.gamePanel = setBoard(GameGui.this.gamePanel);
GameGui.this.gamePanel.revalidate();
game.aiMove();
GameGui.this.gamePanel = setBoard(GameGui.this.gamePanel);
GameGui.this.gamePanel.revalidate();
}
/** Instance variable Row. */
private int row;
/** Instance variable Col. */
private int col;
}
}
| derrickmar/jump-61 | GameGui.java | 2,502 | /** constraints to design totalPanel layout. */ | block_comment | en | false | 2,257 | 9 | 2,502 | 9 | 2,725 | 9 | 2,502 | 9 | 3,001 | 9 | false | false | false | false | false | true |
166796_22 | import java.awt.*;
import javax.swing.*;
import org.fife.ui.autocomplete.*;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextScrollPane;
public class AutoCompleteDemo extends JFrame {
public AutoCompleteDemo() {
JPanel contentPane = new JPanel(new BorderLayout());
RSyntaxTextArea textArea = new RSyntaxTextArea(20, 60);
textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
textArea.setCodeFoldingEnabled(true);
contentPane.add(new RTextScrollPane(textArea));
// A CompletionProvider is what knows of all possible completions, and
// analyzes the contents of the text area at the caret position to
// determine what completion choices should be presented. Most instances
// of CompletionProvider (such as DefaultCompletionProvider) are designed
// so that they can be shared among multiple text components.
CompletionProvider provider = createCompletionProvider();
// An AutoCompletion acts as a "middle-man" between a text component
// and a CompletionProvider. It manages any options associated with
// the auto-completion (the popup trigger key, whether to display a
// documentation window along with completion choices, etc.). Unlike
// CompletionProviders, instances of AutoCompletion cannot be shared
// among multiple text components.
AutoCompletion ac = new AutoCompletion(provider);
ac.install(textArea);
setContentPane(contentPane);
setTitle("AutoComplete Demo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
/**
* Create a simple provider that adds some Java-related completions.
*/
private CompletionProvider createCompletionProvider() {
// A DefaultCompletionProvider is the simplest concrete implementation
// of CompletionProvider. This provider has no understanding of
// language semantics. It simply checks the text entered up to the
// caret position for a match against known completions. This is all
// that is needed in the majority of cases.
DefaultCompletionProvider provider = new DefaultCompletionProvider();
// Add completions for all Java keywords. A BasicCompletion is just
// a straightforward word completion.
provider.addCompletion(new BasicCompletion(provider, "abstract"));
provider.addCompletion(new BasicCompletion(provider, "assert"));
provider.addCompletion(new BasicCompletion(provider, "break"));
provider.addCompletion(new BasicCompletion(provider, "case"));
// ... etc ...
provider.addCompletion(new BasicCompletion(provider, "transient"));
provider.addCompletion(new BasicCompletion(provider, "try"));
provider.addCompletion(new BasicCompletion(provider, "void"));
provider.addCompletion(new BasicCompletion(provider, "volatile"));
provider.addCompletion(new BasicCompletion(provider, "while"));
// Add a couple of "shorthand" completions. These completions don't
// require the input text to be the same thing as the replacement text.
provider.addCompletion(new ShorthandCompletion(provider, "sysout",
"System.out.println(", "System.out.println("));
provider.addCompletion(new ShorthandCompletion(provider, "syserr",
"System.err.println(", "System.err.println("));
return provider;
}
public static void main(String[] args) {
// Instantiate GUI on the EDT.
SwingUtilities.invokeLater(() -> {
try {
String laf = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(laf);
} catch (Exception e) { /* Never happens */ }
new AutoCompleteDemo().setVisible(true);
});
}
} | nimishbongale/code-editor | AutoCompleteDemo.java | 836 | // Instantiate GUI on the EDT. | line_comment | en | false | 744 | 7 | 836 | 8 | 877 | 7 | 836 | 8 | 965 | 10 | false | false | false | false | false | true |
167291_2 | package blackjack;
import java.util.ArrayList;
public class Dealer
{
private String name;
private ArrayList<Card> dealerCards;
private int total;
private boolean bust;
private boolean hasAce;
//Constructor
public Dealer()
{
name = "Dealer";
dealerCards = new ArrayList<Card>();
total = 0;
bust = false;
hasAce = false;
}
//Returns dealerCard of position x
public Card getDealerCard(int x)
{
return dealerCards.get(x);
}
//Adds Card c to dealerCards
public void addCard(Card c)
{
dealerCards.add(c);
}
//Returns total
public int getTotal()
{
total = 0;
for(Card i : dealerCards)
total += i.getValue();
return total;
}
//Checks to see if an ace is held
public boolean hasAce()
{
for(int i=0; i < dealerCards.size(); i++)
{
if(dealerCards.get(i).getValue() == 1)
hasAce = true;
}
return hasAce;
}
//Returns "Dealer"
public String getName()
{
return name;
}
//Returns size of dealerCards
public int handSize()
{
return dealerCards.size();
}
//Returns bust value
public boolean isBusted()
{
if(getTotal() > 21)
bust = true;
return bust;
}
//Resets relevant variables between hands
public void reset()
{
dealerCards.clear();
bust = false;
hasAce = false;
}
//The logic for the dealer's turn
public void playTurn(Deck deck)
{
//Checks initial cards to see if there's an ace
hasAce();
//Logic loop
while(true)
{
//Dealer is hard-stopped at 17+
if(getTotal() >= 17)
return;
/*If dealer has an ace AND if counting the ace as 11
* brings the total to 17-21, kick out. Otherwise,
* play will continue.
*/
if(hasAce)
if(getTotal() + 10 >= 17 && getTotal() + 10 <= 21)
return;
//Picks up next card
dealerCards.add(deck.getNextCard());
//Checks if the picked up card was an ace
if(dealerCards.get(dealerCards.size()-1).getValue() == 1)
hasAce = true;
//Checking to see if dealer busts
if(getTotal() > 21)
{
bust = true;
return;
}
}
}
} | lexdura/Group6 | Dealer.java | 740 | //Adds Card c to dealerCards
| line_comment | en | false | 619 | 8 | 736 | 9 | 774 | 8 | 740 | 9 | 955 | 11 | false | false | false | false | false | true |
167433_1 | // Screen.java
// Represents the screen of the ATM
public class Screen
{
// displays a message without a carriage return
public void displayMessage( String message )
{
System.out.print( message );
} // end method displayMessage
// display a message with a carriage return
public void displayMessageLine( String message )
{
System.out.println( message );
} // end method displayMessageLine
// display a dollar amount
public void displayDollarAmount( double amount )
{
System.out.printf( "$%,.2f", amount );
} // end method displayDollarAmount
} // end class Screen
/**************************************************************************
* (C) Copyright 1992-2012 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/ | MikeMMattinson/deitel_java | src/ch13/Screen.java | 350 | // Represents the screen of the ATM | line_comment | en | false | 321 | 7 | 350 | 8 | 360 | 7 | 350 | 8 | 398 | 10 | false | false | false | false | false | true |
169649_6 |
package com.pronetbeans.examples;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* Entity class Businesses
*
* @author Adam Myatt
*/
@Entity
@Table(name = "Businesses")
@NamedQueries( {
@NamedQuery(name = "Businesses.findByBusinessId", query = "SELECT b FROM Businesses b WHERE b.businessId = :businessId"),
@NamedQuery(name = "Businesses.findByBusinessName", query = "SELECT b FROM Businesses b WHERE b.businessName = :businessName")
})
public class Businesses implements Serializable {
@Id
@Column(name = "BUSINESS_ID", nullable = false)
private BigDecimal businessId;
@Column(name = "BUSINESS_NAME")
private String businessName;
/** Creates a new instance of Businesses */
public Businesses() {
}
/**
* Creates a new instance of Businesses with the specified values.
* @param businessId the businessId of the Businesses
*/
public Businesses(BigDecimal businessId) {
this.businessId = businessId;
}
/**
* Gets the businessId of this Businesses.
* @return the businessId
*/
public BigDecimal getBusinessId() {
return this.businessId;
}
/**
* Sets the businessId of this Businesses to the specified value.
* @param businessId the new businessId
*/
public void setBusinessId(BigDecimal businessId) {
this.businessId = businessId;
}
/**
* Gets the businessName of this Businesses.
* @return the businessName
*/
public String getBusinessName() {
return this.businessName;
}
/**
* Sets the businessName of this Businesses to the specified value.
* @param businessName the new businessName
*/
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
/**
* Returns a hash code value for the object. This implementation computes
* a hash code value based on the id fields in this object.
* @return a hash code value for this object.
*/
@Override
public int hashCode() {
int hash = 0;
hash += (this.businessId != null ? this.businessId.hashCode() : 0);
return hash;
}
/**
* Determines whether another object is equal to this Businesses. The result is
* <code>true</code> if and only if the argument is not null and is a Businesses object that
* has the same id field values as this object.
* @param object the reference object with which to compare
* @return <code>true</code> if this object is the same as the argument;
* <code>false</code> otherwise.
*/
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Businesses)) {
return false;
}
Businesses other = (Businesses)object;
if (this.businessId != other.businessId && (this.businessId == null || !this.businessId.equals(other.businessId))) return false;
return true;
}
/**
* Returns a string representation of the object. This implementation constructs
* that representation based on the id fields.
* @return a string representation of the object.
*/
@Override
public String toString() {
return "com.pronetbeans.examples.Businesses[businessId=" + businessId + "]";
}
}
| Apress/pro-netbeans-ide-5.5-enterprise-edition | Chapter06/Businesses.java | 858 | /**
* Sets the businessName of this Businesses to the specified value.
* @param businessName the new businessName
*/ | block_comment | en | false | 780 | 28 | 858 | 28 | 902 | 30 | 858 | 28 | 1,017 | 32 | false | false | false | false | false | true |
169736_8 | package com.company.GUI;
import com.company.TFIDF.SortByTFIDF;
import com.company.TFIDF.TFIDF;
import com.company.TFIDF.Term;
import com.company.dataStructures.MyHashMap;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.*;
public class app extends JFrame implements ActionListener {
//JFame setup variables
JFrame jFrame = this;
JPanel panelMain;
JPanel[] panels;
JLabel[] labels;
private JComboBox<String> jComboBox;
final private DefaultComboBoxModel<String> comboBoxModel = new DefaultComboBoxModel<>();
private JButton submit;
//File location variables
final private String jsonFileLocation = "/10k_business_dataset.txt";
final private String cleanedFileLocation = "/10k_business_dataset(cleaned).txt";
//limit
int numOfBusinessesToDisplay = 10;
//myHashmaps is a Hashmap contain all the individual business hashTables
//allHashmaps is explained in the comment for allToOneHashMap function
//sortedBusiness is used to list the x most similar businesses (where x is numOfBusinessesToDisplay)
HashMap<String, MyHashMap> myHashMaps = new HashMap<>();
MyHashMap allHashmaps = new MyHashMap();
List<MyHashMap> sortedBusinesses;
//Business used to find other similar business
String comparatorBusiness;
//constructor that enables comboBox and button functionality
//& Takes care of the autocomplete box via the imported library swingx-all-1.6.4
public app() {
super("Compare Businesses");
panelMain.setVisible(false);
setHashMaps();
allToOneHashmap();
fillJComboBoxModel();
AutoCompleteDecorator.decorate(jComboBox);
submit.setText("Submit");
submit.addActionListener(e -> {});
jFrame.getRootPane().setDefaultButton(submit);
labels = new JLabel[numOfBusinessesToDisplay];
createLabels();
createPanels();
setUpPage();
}
/**Basic page setUp.
* This will enable the program to halt when the application is closed.
* Adds functionality to the button, designs the text field, adds everything to the JFrame.
* Sets the JFrame to visible so that it actually displays.
*/
public void setUpPage(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
submit.addActionListener(this);
jComboBox.setPreferredSize(new Dimension(250, 28));
jComboBox.setFont(new Font("Consolas", Font.PLAIN, 18));
jComboBox.setForeground(Color.blue);
jComboBox.setBackground(Color.white);
jComboBox.setToolTipText("Choose a business");//setText("Choose a business");
this.add(submit);
this.add(jComboBox);
this.pack();
this.setSize(500,500);
this.setVisible(true);
}
/**Changes the suggested element in text field based on what is currently typed*/
public void fillJComboBoxModel(){
String[] keys = myHashMaps.keySet().toArray(new String[0]);
for(String elements: keys) {
comboBoxModel.addElement(elements);
}
jComboBox.setModel(comboBoxModel);
jComboBox.setMaximumRowCount(5);
}
/**Runs TF-IDF calculation on every key in the comparator hashmap (the document you want to compare against)*/
private void makeTfIdf(){
//Layer 1
for(MyHashMap maps: myHashMaps.values()) {
maps.setTfidf(0);
//Layer 2
for (LinkedList<Term> ll : myHashMaps.get(comparatorBusiness).map) {
if (ll == null)
continue;
for (Term key : ll) {
maps.addToTfidf(TFIDF.CalculateTFIDF(allHashmaps, maps, key.key, myHashMaps.size()));
}
}
}
}
/**Puts all of the hashmaps terms into one hashmap,
* in turn it records the number of documents that each word appears in due to how the myHashmaps put method works
*/
public void allToOneHashmap(){
//Layer 1
for(MyHashMap maps: myHashMaps.values()) {
//Layer 2
for (LinkedList<Term> ll : maps.map) {
if (ll == null)
continue;
for (Term key : ll) {
allHashmaps.put(key.key);
}
}
}
}
//Needed for the implements actionListener
@Override
public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent.getSource() == submit){
comparatorBusiness = Objects.requireNonNull(jComboBox.getSelectedItem()).toString();
makeTfIdf();
setSortedBusinesses();
populateLabels();
populatePanels();
this.setSize(500,500);
}
}
private void createLabels(){
for(int i = 0; i < labels.length; i++) {
labels[i] = new JLabel();
}
}
//add text to the label
private void populateLabels(){
for(int i = 0; i < labels.length; i++) {
labels[i].setText(sortedBusinesses.get(i).getBusinessName());
}
}
private void createPanels() {
panels = new JPanel[numOfBusinessesToDisplay];
int height = 25;
int width = 500;
for (int i = 0; i < panels.length; i++) {
panels[i] = new JPanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
};
panels[i].setBounds(0, height * i, width, height);
}
}
//add labels to the panels
private void populatePanels(){
int rgb = 200;
for (int i = 0; i < panels.length; i++) {
panels[i].setBackground(new Color(rgb, rgb, rgb));
panels[i].add(labels[i]);
labels[i].setVerticalAlignment(JLabel.CENTER);
jFrame.add(panels[i]);
}
jFrame.pack();
}
/**
* Reads a json file and puts the different objects into their own hashmap.
* Stores the information inside an arrayList for sorting later.
* */
private void setHashMaps(){
try {
//checks if a cleaned database file exist. If not, it creates one. (cleaned file == removed non-alphanumerics)
File file;
file = new File(System.getProperty("user.dir") + cleanedFileLocation);
if(!file.isFile()) {
cleanJsonFile();
file = new File(System.getProperty("user.dir") + cleanedFileLocation);
}
Scanner getBusiness = new Scanner(file);
Scanner getContentKeys;
String business;
//each business is on its own line in the file and this reads it as such
//this will only work if the json file is in newLine-delimited format
while (getBusiness.hasNextLine()) {
business = getBusiness.nextLine();
getContentKeys = new Scanner(business);
MyHashMap myHashMap = new MyHashMap();
for(int j = 0; getContentKeys.hasNext(); j++){
if (j == 3){
//each business is the 4th word and followed by an address for this dataset
//as such we make those checks to find the business names
//THIS IS HACKY, USE Dynamic Json mapping (https://www.baeldung.com/jackson-mapping-dynamic-object)
StringBuilder concatBusinessName = new StringBuilder();
for (String temp = getContentKeys.next(); !temp.equalsIgnoreCase("address");){
concatBusinessName.append(temp).append(" ");
myHashMap.put(temp);
temp = getContentKeys.next();
if (temp.equalsIgnoreCase("address"))
myHashMap.put(temp);
}
myHashMap.setBusinessName(String.valueOf(concatBusinessName).trim());
continue;
}
myHashMap.put(getContentKeys.next());
if (!getContentKeys.hasNext()){
myHashMaps.put(myHashMap.getBusinessName(),myHashMap);
}
}
getContentKeys.close();
}
getBusiness.close();
sortedBusinesses = new ArrayList<>(myHashMaps.values());
} catch (IOException e) {
e.printStackTrace();
}
}
public void setSortedBusinesses(){
SortByTFIDF sortByTFIDF = new SortByTFIDF();
sortedBusinesses.sort(sortByTFIDF);
}
// Removes non-alphanumerics from the whole database file and adds spaces where there should be
public void cleanJsonFile() throws IOException {
File file = new File(System.getProperty("user.dir") + jsonFileLocation);
FileReader fileReader = new FileReader(file);
FileWriter fileWriter = new FileWriter(System.getProperty("user.dir") + cleanedFileLocation, false);
Scanner scanner = new Scanner(fileReader);
String newDoc;
while (scanner.hasNext()){
newDoc = scanner.nextLine().replaceAll("[: ,]", " ");
newDoc = newDoc.replaceAll("[^a-zA-Z0-9 ]", "");
fileWriter.write(newDoc + "\n");
}
fileReader.close();
fileWriter.flush();
fileWriter.close();
scanner.close();
}
}
| DavisNicholas04/CSC365-DL | src/com/company/GUI/app.java | 2,199 | //& Takes care of the autocomplete box via the imported library swingx-all-1.6.4 | line_comment | en | false | 1,991 | 21 | 2,199 | 23 | 2,354 | 22 | 2,199 | 23 | 2,688 | 24 | false | false | false | false | false | true |
170137_25 | package Fundamentals;
/*************************************************************************
* Compilation: javac Out.java
* Execution: java Out
*
* Writes data of various types to: stdout, file, or socket.
*
*************************************************************************/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Locale;
import java.util.Scanner;
/**
* This class provides methods for writing strings and numbers to
* various output streams, including standard output, file, and sockets.
* <p>
* For additional documentation, see
* <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>
* by Robert Sedgewick and Kevin Wayne.
*/
public class Out {
// force Unicode UTF-8 encoding; otherwise it's system dependent
private static final String UTF8 = "UTF-8";
// assume language = English, country = US for consistency with StdIn
private static final Locale US_LOCALE = new Locale("en", "US");
private PrintWriter out;
/**
* Create an Out object using an OutputStream.
*/
public Out(OutputStream os) {
try {
OutputStreamWriter osw = new OutputStreamWriter(os, UTF8);
out = new PrintWriter(osw, true);
}
catch (IOException e) { e.printStackTrace(); }
}
/**
* Create an Out object using standard output.
*/
public Out() { this(System.out); }
/**
* Create an Out object using a Socket.
*/
public Out(Socket socket) {
try {
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, UTF8);
out = new PrintWriter(osw, true);
}
catch (IOException e) { e.printStackTrace(); }
}
/**
* Create an Out object using a file specified by the given name.
*/
public Out(String s) {
try {
OutputStream os = new FileOutputStream(s);
OutputStreamWriter osw = new OutputStreamWriter(os, UTF8);
out = new PrintWriter(osw, true);
}
catch (IOException e) { e.printStackTrace(); }
}
/*
* Added 3/30/2013
*/
public Out(String dirname, String filename) {
Path inputPath= Paths.get(dirname, filename);
String inputPathString = dirname + File.separator + filename;
// if (! Files.isReadable(inputPath)) {
// System.out.printf("File %s does not exist.", inputPathString);
// return;
// }
File file = inputPath.toFile();
try {
OutputStream os = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(os, UTF8);
out = new PrintWriter(osw, true);
}
catch (IOException ioe) {
System.err.println("Could not open " + file);
}
}
/**
* Close the output stream.
*/
public void close() { out.close(); }
/**
* Terminate the line.
*/
public void println() {
out.println();
}
/**
* Print an object and then terminate the line.
*/
public void println(Object x) {
out.println(x);
}
/**
* Print a boolean and then terminate the line.
*/
public void println(boolean x) {
out.println(x);
}
/**
* Print a char and then terminate the line.
*/
public void println(char x) {
out.println(x);
}
/**
* Print an double and then terminate the line.
*/
public void println(double x) {
out.println(x);
}
/**
* Print a float and then terminate the line.
*/
public void println(float x) {
out.println(x);
}
/**
* Print an int and then terminate the line.
*/
public void println(int x) {
out.println(x);
}
/**
* Print a long and then terminate the line.
*/
public void println(long x) {
out.println(x);
}
/**
* Print a byte and then terminate the line.
*/
public void println(byte x) {
out.println(x);
}
/**
* Flush the output stream.
*/
public void print() {
out.flush();
}
/**
* Print an object and then flush the output stream.
*/
public void print(Object x) {
out.print(x);
out.flush();
}
/**
* Print an boolean and then flush the output stream.
*/
public void print(boolean x) {
out.print(x);
out.flush();
}
/**
* Print an char and then flush the output stream.
*/
public void print(char x) {
out.print(x);
out.flush();
}
/**
* Print an double and then flush the output stream.
*/
public void print(double x) {
out.print(x);
out.flush();
}
/**
* Print a float and then flush the output stream.
*/
public void print(float x) {
out.print(x);
out.flush();
}
/**
* Print an int and then flush the output stream.
*/
public void print(int x) {
out.print(x);
out.flush();
}
/**
* Print a long and then flush the output stream.
*/
public void print(long x) {
out.print(x);
out.flush();
}
/**
* Print a byte and then flush the output stream.
*/
public void print(byte x) {
out.print(x);
out.flush();
}
/**
* Print a formatted string using the specified format string and arguments,
* and then flush the output stream.
*/
public void printf(String format, Object... args) {
out.printf(US_LOCALE, format, args);
out.flush();
}
/**
* Print a formatted string using the specified locale, format string and arguments,
* and then flush the output stream.
*/
public void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
}
/**
* A test client.
*/
public static void main(String[] args) {
Out out;
String s;
// write to stdout
out = new Out();
out.println("Test 1");
out.close();
// write to a file
out = new Out("test.txt");
out.println("Test 2");
out.close();
}
}
| stefanzero/JavaFundamentals | Out.java | 1,630 | /**
* Print an boolean and then flush the output stream.
*/ | block_comment | en | false | 1,462 | 15 | 1,630 | 15 | 1,834 | 17 | 1,630 | 15 | 1,933 | 17 | false | false | false | false | false | true |
170422_2 | import java.io.IOException;
import java.util.List;
import com.gurobi.gurobi.GRB;
import com.gurobi.gurobi.GRBEnv;
import com.gurobi.gurobi.GRBException;
import com.gurobi.gurobi.GRBLinExpr;
import com.gurobi.gurobi.GRBModel;
import com.gurobi.gurobi.GRBVar;
/**
* Class containing the ZDWCD model
*
* @author 562606ad
*/
public class ZDWCD {
public GRBModel model;
public GRBEnv env;
public GRBVar[] excessDemand;
public GRBVar[] accumulatedDemand;
public GRBVar[] demand;
public GRBVar[] thereIsExcessDemand;
public GRBVar[][] isClosestPickUp;
public GRBVar[][] demandRealised;
public GRBVar[][] typeDemandRealised;
public int numDP;
public int numDV;
public int numSh;
public int numTypes;
public int[] numOfEachType;
public int[][] typeAssignment;
public double[] isPickUpLocationValues;
public double[][] isClosestPickUpValues;
public double[][][] tripsValues;
/**
* Constructor for the ZDWCD model
* @param isPickUpLocation Array of binary variables indicating whether a demand point is a pick-up location
* @param isClosestPickUp Array of binary variables indicating whether a demand point is the closest pick-up location to another demand point
* @param trips Array of binary variables indicating whether a bus travels from a demand point to a shelter
* @param busCap Capacity of the buses
* @param numBus Number of buses
* @param demandVectors List of the possible vectors of demand for each demand point
* @param longestWalk Maximum allowed walking time
* @param maxT Maximum allowed driving time for the buses
* @param times Matrix containing the driving times from each demand point to each shelter
* @param walkingTimes Matrix containing the walking times between each pair of nodes
* @param selectedDemandVectors List of selected demand vectors
* @param shelterCap Array containing the capacities of the shelters
* @param types Array containing the types of the demand points
* @param assignment Matrix containing the assignments of the demand points, 1 if the demand point is of that type, 0 otherwise
* @param parameter Correlation parameter
* @throws IOException
*/
public ZDWCD(GRBVar[] isPickUpLocation, GRBVar[][] isClosestPickUp, GRBVar[][][] trips,
int busCap, int numBus, List<Integer[]> demandVectors, int longestWalk,
int maxT, int[][] times, int[][] walkingTimes, List<Integer[]> selectedDemandVectors,
int[] shelterCap, int[] types, int[] assignment, double parameter) throws IOException {
this.numDP = isPickUpLocation.length;
this.numDV = demandVectors.size(); // possible values for a demand point
this.numSh = shelterCap.length;
this.numTypes = types.length;
this.numOfEachType = helper.getNumOfEachType(types, assignment);
this.typeAssignment = helper.assignTypes(types, assignment);
this.excessDemand = new GRBVar[numDP];
this.accumulatedDemand = new GRBVar[numDP];
this.demand = new GRBVar[numDP];
this.thereIsExcessDemand = new GRBVar[numDP];
this.demandRealised = new GRBVar[numDP][numDV];
this.typeDemandRealised = new GRBVar[numTypes][numDV];
this.isPickUpLocationValues = new double[numDP];
this.isClosestPickUpValues = new double[numDP][numDP];
this.tripsValues = new double[numBus][numDP][numSh];
try {
this.env = new GRBEnv();
this.model = new GRBModel(env);
for (int i = 0; i < numDP; i++) {
isPickUpLocationValues[i] = isPickUpLocation[i].get(GRB.DoubleAttr.X);
for (int p = 0; p < numDP; p++) {
isClosestPickUpValues[i][p] = isClosestPickUp[i][p].get(GRB.DoubleAttr.X);
}
for (int b = 0; b < numBus; b++) {
for (int j = 0; j < numSh; j++) {
tripsValues[b][i][j] = trips[b][i][j].get(GRB.DoubleAttr.X);
}
}
}
for (int i = 0; i < numDP; i++) {
excessDemand[i] = model.addVar(- GRB.INFINITY, GRB.INFINITY, 0, GRB.CONTINUOUS, "excessDemand" + i);
accumulatedDemand[i] = model.addVar(0, GRB.INFINITY, 0, GRB.CONTINUOUS, "accumulatedDemand" + i);
demand[i] = model.addVar(0, GRB.INFINITY, 0, GRB.CONTINUOUS, "demand" + i);
thereIsExcessDemand[i] = model.addVar(0, 1, 0, GRB.BINARY, "thereIsExcessDemand" + i);
}
for (int s = 0; s < numDV; s++) {
for (int i = 0; i < numDP; i++) {
demandRealised[i][s] = model.addVar(0, 1, 0, GRB.BINARY, "demandRealised" + "_" + i + "_" + s);
}
for (int t = 0; t < numTypes; t++) {
typeDemandRealised[t][s] = model.addVar(0, 1, 0, GRB.BINARY, "typeDemandRealised" + "_" + t + "_" + s);
}
}
// Define objective function
GRBLinExpr objExpr = new GRBLinExpr();
for (int i = 0; i < numDP; i++) {
objExpr.addTerm(1, excessDemand[i]);
}
model.setObjective(objExpr, GRB.MAXIMIZE);
// Add constraints ---------------------------------------------------
// 1. Bound excess demand of all demand points that are not pick-up locations to 0
for (int i = 0; i < numDP; i++) {
GRBLinExpr rhs = new GRBLinExpr();
rhs.addTerm(10000, thereIsExcessDemand[i]);
model.addConstr(excessDemand[i], GRB.LESS_EQUAL, rhs, "constraint1_" + i);
}
// 2. Excess demand of a demand point is the difference between the capacity of the buses in the current solution and the new accumulated demand
for (int i = 0; i < numDP; i++) {
GRBLinExpr lhs = new GRBLinExpr();
GRBLinExpr rhs = new GRBLinExpr();
lhs.addTerm(1, excessDemand[i]);
lhs.addTerm(- 1, accumulatedDemand[i]);
for (int b = 0; b < numBus; b++) {
for (int j = 0; j < numSh; j++) {
lhs.addConstant(busCap * tripsValues[b][i][j]);
}
}
rhs.addConstant((10000));
rhs.addTerm(- 10000, thereIsExcessDemand[i]);
model.addConstr(lhs, GRB.LESS_EQUAL, rhs, "constraint2_" + i);
}
// 3.
for (int i = 0; i < numDP; i++) {
model.addConstr(excessDemand[i], GRB.GREATER_EQUAL, 0, "excessDemandNonNegative_" + i);
}
// 4.
for (int p = 0; p < numDP; p++) {
GRBLinExpr rhs = new GRBLinExpr();
for (int i = 0; i < numDP; i++) {
rhs.addTerm(isClosestPickUpValues[p][i], demand[i]);
}
model.addConstr(accumulatedDemand[p], GRB.EQUAL, rhs, "accDemandDef_" + p);
}
// 5.
for (int t = 0; t < numTypes; t++) {
GRBLinExpr lhs = new GRBLinExpr();
for (int s = 1; s < numDV; s++) {
lhs.addTerm(1, typeDemandRealised[t][s]);
}
model.addConstr(lhs, GRB.EQUAL, 1, "oneTypeDemandRealised_" + t);
}
// 6.
for (int i = 0; i < numDP; i++) {
GRBLinExpr rhs = new GRBLinExpr();
for (int s = 0; s < numDV; s++) {
rhs.addTerm(demandVectors.get(s)[i], demandRealised[i][s]);
}
model.addConstr(demand[i], GRB.LESS_EQUAL, rhs, "demandRealised_" + i);
}
// 7.
GRBLinExpr lhs7 = new GRBLinExpr();
for (int t = 0; t < numTypes; t++) {
lhs7.addTerm(1, typeDemandRealised[t][2]);
}
model.addConstr(lhs7, GRB.LESS_EQUAL, 1, "OnlyOneHighTypeDemandRealised");
// 8.
for (int t = 0; t < numTypes; t++) {
GRBLinExpr lhs = new GRBLinExpr();
GRBLinExpr rhs = new GRBLinExpr();
for (int i = 0; i < numDP; i++) {
lhs.addTerm(typeAssignment[i][t], demandRealised[i][1]);
}
rhs.addTerm(Math.ceil(numOfEachType[t] * parameter), typeDemandRealised[t][1]);
model.addConstr(lhs, GRB.GREATER_EQUAL, rhs, "lowDemandRealised" + t);
}
// 9.
for (int t = 0; t < numTypes; t++) {
GRBLinExpr lhs = new GRBLinExpr();
GRBLinExpr rhs = new GRBLinExpr();
for (int i = 0; i < numDP; i++) {
lhs.addTerm(typeAssignment[i][t], demandRealised[i][2]);
}
rhs.addTerm((int) Math.ceil(numOfEachType[t]), typeDemandRealised[t][2]);
model.addConstr(lhs, GRB.EQUAL, rhs, "highDemandRealised_" + t);
}
// 10.
for (int i = 0; i < numDP; i++) {
GRBLinExpr lhs = new GRBLinExpr();
for (int s = 0; s < numDV; s++) {
lhs.addTerm(1, demandRealised[i][s]);
}
model.addConstr(lhs, GRB.EQUAL, 1, "demandRealised_" + i);
}
} catch (GRBException e) {
e.printStackTrace();
}
}
/**
* Solve the ZDWCD model
* @throws IOException
* @throws GRBException
*/
public void solve() throws IOException, GRBException {
model.optimize();
}
/**
* Dispose of the ZDWCD model
* @throws GRBException
*/
public void dispose() throws GRBException {
model.dispose();
env.dispose();
}
/**
* Get the objective value of the ZDWCD model
* @return Objective value
* @throws GRBException
*/
public double getObjective() throws GRBException {
model.optimize();
return model.get(GRB.DoubleAttr.ObjVal);
}
/**
* Write the ZDWCD model to a file
* @throws IOException
* @throws GRBException
*/
public void write() throws IOException, GRBException {
model.write("ZDWCD.lp");
}
}
| Uanra14/RTPL_Evac | ZDWCD.java | 2,864 | // possible values for a demand point
| line_comment | en | false | 2,692 | 8 | 2,867 | 8 | 3,141 | 8 | 2,864 | 8 | 3,496 | 8 | false | false | false | false | false | true |
170830_2 | /**
*
* Represents a lexical token for 254 exercise.
*
* This class has been provided to students
*
* @Author: Roger Garside
*
*
**/
public class Token
{
public static final int becomesSymbol = 1 ;
public static final int beginSymbol = 2 ;
public static final int callSymbol = 3 ;
public static final int colonSymbol = 4 ;
public static final int commaSymbol = 5 ;
public static final int divideSymbol = 6 ;
public static final int doSymbol = 7 ;
public static final int endSymbol = 8 ;
public static final int elseSymbol = 9 ;
public static final int eofSymbol = 10 ;
public static final int equalSymbol = 11 ;
public static final int errorSymbol = 12 ;
public static final int floatSymbol = 13 ;
public static final int greaterEqualSymbol = 14 ;
public static final int greaterThanSymbol = 15 ;
public static final int identifier = 16 ;
public static final int ifSymbol = 17 ;
public static final int integerSymbol = 18 ;
public static final int isSymbol = 19 ;
public static final int leftParenthesis = 20 ;
public static final int lessEqualSymbol = 21 ;
public static final int lessThanSymbol = 22 ;
public static final int loopSymbol = 23 ;
public static final int minusSymbol = 24 ;
public static final int notEqualSymbol = 25 ;
public static final int numberConstant = 26 ;
public static final int plusSymbol = 27 ;
public static final int procedureSymbol = 28 ;
public static final int rightParenthesis = 29 ;
public static final int semicolonSymbol = 30 ;
public static final int stringConstant = 31 ;
public static final int stringSymbol = 32 ;
public static final int timesSymbol = 33 ;
public static final int thenSymbol = 34 ;
public static final int untilSymbol = 35 ;
public static final int whileSymbol = 36 ;
public static final int forSymbol = 37 ;
private static final String[] names = {
":=", "begin", "call", ":", ",",
"/", "do", "end", "else", "EOF",
"=", "ERROR", "float", ">=", ">",
"IDENTIFIER", "if", "integer", "is", "(",
"<=", "<", "loop", "-", "/=",
"NUMBER", "+", "procedure", ")", ";",
"STRING", "string", "*", "then", "until",
"while", "for"
} ;
/** The symbol this token instance represents */
public int symbol ;
/** The original text. */
public String text ;
/** The line number of the original text in the source file. */
public int lineNumber ;
/** Constructs a new token with a given token type and line number.
@param s The type of symbol, typically as a class constant from Token.
@param t The original string recognised from the source file.
@param l The line number of the original string.
*/
public Token(int s, String t, int l)
{
symbol = s ;
text = t ;
lineNumber = l ;
} // end of constructor method
/** Constructs a new token from a StringBuffer, given type and line number.
@param s The type of symbol, typically as a class constant from Token.
@param t The original string recognised from the source file.
@param l The line number of the original string.
*/
public Token(int s, StringBuffer t, int l)
{
symbol = s ;
text = new String(t) ;
lineNumber = l ;
} // end of constructor method
/** Returns a string representation of a symbol type.
@param i The value of a symbol, typically as a class constant from Token.
@return The name of this symbol.
*/
public static String getName(int i)
{
if ((i < 1) || (i > names.length))
return "UNKNOWN" ;
else
return names[i - 1] ;
} // end of method getName
/** @see Object.toString */
public String toString()
{
String tt = "token " + getName(symbol) ;
if ((symbol == identifier) ||
(symbol == numberConstant) ||
(symbol == stringConstant))
tt += ": " + text ;
tt += " (line " + lineNumber + ")" ;
return tt ;
} // end of method toString
} // end of class Token
| Bikash3110/SCC312-Languages-and-Compilation--Recursive-Desecent-Recogniser | Token.java | 1,148 | /** The original text. */ | block_comment | en | false | 1,018 | 6 | 1,148 | 6 | 1,165 | 6 | 1,148 | 6 | 1,260 | 6 | false | false | false | false | false | true |
170929_17 | /**
* Sugarscape
* Copyright 2009-2010 Denis M., Stefan H., Waldemar S.
*
* Author: Denis M., Stefan H., Waldemar S.
* Website: http://github.com/CallToPower/Sugarscape
* AG: Lecture "Regelbasierte Modelle" at the University of Osnabrueck (Germany)
*
* The Sugarscape is free Software:
* You can redistribute it and/or modify it under the Terms of the
* GNU General Public License
* as published by the Free Software Foundation, either version 3 of the
* License,
* or (at your Option) any later Version.
*
* The Sugarscape Application is distributed WITHOUT ANY WARRANTY;
* without even the implied Warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE.
* See the GNU General Public License for more Details.
*
* You should have received a copy of the GNU General Public License
* along with the Sugarscape Application.
* If not, see <http://www.gnu.org/licenses/>.
*
* File: scr/SCGrid.java
*/
package scr;
import eawag.grid.Bug;
import eawag.grid.Grid;
/**
* Grid
*
* @author Denis Meyer
*/
public class SCGrid extends Grid {
private static final SCHelper helper = new SCHelper();
/************************************************/
// Private Variables
/************************************************/
private boolean init = true;
private int avarageWealth = 0;
private int _avarageWealth = 0;
private int bugCount = 0;
private int _bugCount = 0;
private int deathCount = 0;
private int deathAge = 0;
private int d_poor = 0;
private int d_AgePoor = 0;
private int d_rich = 0;
private int d_AgeRich = 0;
/************************************************/
// Other Functions
/************************************************/
public void condition() {
avarageWealth = _avarageWealth;
bugCount = _bugCount;
_avarageWealth = _bugCount = 0;
d_poor = 0;
d_AgePoor = 0;
d_rich = 0;
d_AgeRich = 0;
super.condition();
}
/**
* Action-Function 1. Put SCSugarAgents on every Cell
*/
public void action() {
if (init) {
Bug b;
for (int x = 0; x < this.getXSize(); x++) {
for (int y = 0; y < this.getYSize(); y++) {
// assume only one level
b = this.getBug(x, y, 0);
// amount of sugar
int r = -1;
if (b != null) {
// Bug has been initialized
if (b instanceof SCSugarBug) {
// get amount of sugar was set
r = ((SCSugarBug) b).getCurrentAmountOfSugar();
}
b.leave();
}
b = newSCSugarBug(r);
b.moveBug(x, y, 0);
b.join(this);
((SCSugarBug) b).updateDepiction();
}
}
init = false;
}
}
/**
* Adds
* @param currentBugWealth
*/
public void addAvarageWealth(int currentBugWealth) {
_avarageWealth += currentBugWealth;
_bugCount++;
}
/**
* Returns the Average Wealth
* @return the Average Wealth
*/
public int getAvarageWealth() {
return (int) (bugCount > 0 ? avarageWealth / bugCount : 0);
}
/**
* Returns the number of died Agents
*
* @return number of died Agents
*/
public int getDeadAgents() {
return deathCount;
}
/**
* Returns the Age of Death
*
* @return the Age of Death
*/
public int getAgeOfDeath() {
return deathAge;
}
/**
* Returns number of poor dead Agents
*
* @return d_poor
*/
public int getD_Poor() {
return d_poor;
}
/**
* Returns Age of death from poor agents
*
* @return d_AgePoor
*/
public int getD_AgePoor() {
return d_AgePoor;
}
/**
* Returns number of rich dead Agents
*
* @return d_rich
*/
public int getD_Rich() {
return d_rich;
}
/**
* Returns Age of death from rich agents
*
* @return d_AgeRich
*/
public int getD_AgeRich() {
return d_AgeRich;
}
public void incDeathAgents() {
this.deathCount++;
}
public void incAgeOfDeath(int deathAge) {
this.deathAge += deathAge;
}
public void incD_Poor() {
d_poor++;
}
public void incD_Rich() {
d_rich++;
}
public void incD_AgePoor(int dAgePoor) {
d_AgePoor += dAgePoor;
}
public void incD_AgeRich(int dAgeRich) {
d_AgeRich += dAgeRich;
}
/************************************************/
// Internal Helper-Functions
/************************************************/
/**
* Returns a new SCBug
*
* @return SCBug a new SCBug
*/
private SCSugarBug newSCSugarBug(int amountSugar) {
if (amountSugar < 0)
amountSugar = helper.getRandomIntWithinLimits(0, helper
.getMaxAmountOfSugarInSugarAgent());
return new SCSugarBug(amountSugar);
}
}
| wsmirnow/Sugarscape | src/scr/SCGrid.java | 1,501 | /**
* Returns number of poor dead Agents
*
* @return d_poor
*/ | block_comment | en | false | 1,296 | 23 | 1,501 | 22 | 1,492 | 25 | 1,501 | 22 | 1,804 | 27 | false | false | false | false | false | true |
171095_6 | /*
Given a string, count the number of words ending in 'y' or 'z' -- so the 'y' in "heavy" and the 'z' in "fez" count,
but not the 'y' in "yellow" (not case sensitive). We'll say that a y or z is at the end of a word if there is not an
alphabetic letter immediately following it. (Note: Character.isLetter(char) tests if a char is an alphabetic letter.)
countYZ("fez day") β 2
countYZ("day fez") β 2
countYZ("day fyyyz") β 2
*/
public int countYZ(String str) {
int count = 0;
str = str.toLowerCase() + " ";
for (int i = 0; i < str.length() - 1; i++)
if ((str.charAt(i) == 'y' || str.charAt(i) == 'z') && !Character.isLetter(str.charAt(i + 1)))
count++;
return count;
}
----------------------------------------------------------------------------------------------------------------------------
/*
Given two strings, base and remove, return a version of the base string where all instances of the remove string have
been removed (not case sensitive). You may assume that the remove string is length 1 or more.
Remove only non-overlapping instances, so with "xxx" removing "xx" leaves "x".
withoutString("Hello there", "llo") β "He there"
withoutString("Hello there", "e") β "Hllo thr"
withoutString("Hello there", "x") β "Hello there"
*/
public String withoutString(String base, String remove) {
if(base.length() < remove.length())
return base;
if(base.substring(0, remove.length()).toLowerCase().equals(remove.toLowerCase()))
return withoutString(base.substring(remove.length()), remove);
return base.charAt(0) + withoutString(base.substring(1), remove);
}
----------------------------------------------------------------------------------------------------------------------------
/*
Given a string, return true if the number of appearances of "is" anywhere in the string is equal to the number of
appearances of "not" anywhere in the string (case sensitive).
equalIsNot("This is not") β false
equalIsNot("This is notnot") β true
equalIsNot("noisxxnotyynotxisi") β true
*/
public boolean equalIsNot(String str) {
int isCount = 0;
int notCount = 0;
str += "x";
for(int i = 0; i < str.length() - 2; i++) {
if(str.length() >= 2 && str.substring(i, i + 2).equals("is"))
isCount++;
if(str.length() >= 3 && str.substring(i, i + 3).equals("not"))
notCount++;
}
return (isCount == notCount);
}
----------------------------------------------------------------------------------------------------------------------------
/*
We'll say that a lowercase 'g' in a string is "happy" if there is another 'g' immediately to its left or right.
Return true if all the g's in the given string are happy.
gHappy("xxggxx") β true
gHappy("xxgxx") β false
gHappy("xxggyygxx") β false
*/
public boolean gHappy(String str) {
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == 'g'){
if((i-1 < 0 || str.charAt(i-1) != 'g')){
if((i+1 >= str.length() || str.charAt(i+1) != 'g'))
return false;
}
}
}
return true;
}
----------------------------------------------------------------------------------------------------------------------------
/*
We'll say that a "triple" in a string is a char appearing three times in a row. Return the number of triples in the given
string. The triples may overlap.
countTriple("abcXXXabc") β 1
countTriple("xxxabyyyycd") β 3
countTriple("a") β 0
*/
public int countTriple(String str) {
int count = 0;
for(int i = 0; i < str.length() - 2; i++) {
if(str.charAt(i) == str.charAt(i + 1) && str.charAt(i) == str.charAt(i + 2))
count++;
}
return count;
}
----------------------------------------------------------------------------------------------------------------------------
/*
Given a string, return the sum of the digits 0-9 that appear in the string, ignoring all other characters.
Return 0 if there are no digits in the string. (Note: Character.isDigit(char) tests if a char is one of the chars
'0', '1', .. '9'. Integer.parseInt(string) converts a string to an int.)
sumDigits("aa1bc2d3") β 6
sumDigits("aa11b33") β 8
sumDigits("Chocolate") β 0
*/
public int sumDigits(String str) {
int sum = 0;
for(int i = 0; i < str.length(); i++) {
if(Character.isDigit(str.charAt(i)) == true)
sum += Integer.parseInt(str.substring(i, i+1));
}
return sum;
}
----------------------------------------------------------------------------------------------------------------------------
/*
Given a string, return the longest substring that appears at both the beginning and end of the string without overlapping.
For example, sameEnds("abXab") is "ab".
sameEnds("abXYab") β "ab"
sameEnds("xx") β "x"
sameEnds("xxx") β "x"
*/
public String sameEnds(String string) {
int count;
int length = string.length();
String str = "";
for(count = length / 2; count > 0; count--){
if(string.substring(0,count).equals(string.substring(length - count, length))) {
str += string.substring(0, count);
break;
}
}
return str;
}
----------------------------------------------------------------------------------------------------------------------------
/*
Given a string, look for a mirror image (backwards) string at both the beginning and end of the given string.
In other words, zero or more characters at the very begining of the given string, and at the very end of the string in
reverse order (possibly overlapping). For example, the string "abXYZba" has the mirror end "ab".
mirrorEnds("abXYZba") β "ab"
mirrorEnds("abca") β "a"
mirrorEnds("aba") β "aba"
*/
public String mirrorEnds(String string) {
String result = "";
for (int i = 0, j = string.length() - 1; i < string.length(); i++, j--) {
if (string.charAt(i) == string.charAt(j))
result += string.charAt(i);
else break;
}
return result;
}
----------------------------------------------------------------------------------------------------------------------------
/*
Given a string, return the length of the largest "block" in the string. A block is a run of adjacent chars that are the same.
maxBlock("hoopla") β 2
maxBlock("abbCCCddBBBxx") β 3
maxBlock("") β 0
*/
public int maxBlock(String str) {
int count = 0;
int max = 0;
for(int i = 0; i < str.length(); i++) {
count = 0;
for(int j = i; j < str.length(); j++) {
if(str.charAt(i) == str.charAt(j))
count++;
else
break;
}
if(count > max)
max = count;
}
return max;
}
----------------------------------------------------------------------------------------------------------------------------
/*
Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the
chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an int.)
sumNumbers("abc123xyz") β 123
sumNumbers("aa11b33") β 44
sumNumbers("7 11") β 18
*/
public int sumNumbers(String str) {
String temp = "";
int sum = 0;
int ctr = 0;
int i = 0;
while(i < str.length()) {
char letter = str.charAt(i);
while(Character.isDigit(letter)) {
temp += letter + "";
i++;
if(i >= str.length()) break;
letter = str.charAt(i);
}
if(!temp.equals(""))
sum += Integer.parseInt(temp);
temp = "";
i++;
}
return sum;
}
----------------------------------------------------------------------------------------------------------------------------
/*
Given a string, return a string where every appearance of the lowercase word "is" has been replaced with "is not".
The word "is" should not be immediately preceeded or followed by a letter -- so for example the "is" in "this" does not
count. (Note: Character.isLetter(char) tests if a char is a letter.)
notReplace("is test") β "is not test"
notReplace("is-is") β "is not-is not"
notReplace("This is right") β "This is not right"
*/
public String notReplace(String str) {
String result = "";
str = " " + str + " ";
for (int i = 0; i < str.length() - 2; i++) {
if (str.charAt(i) == 'i') {
if (str.charAt(i + 1) == 's'
&& !Character.isLetter(str.charAt(i + 2))
&& !Character.isLetter(str.charAt(i - 1))) {
result += "is not";
i += 1;
} else result += "i";
} else result += str.charAt(i);
}
return result.substring(1);
}
----------------------------------------------------------------------------------------------------------------------------
| lifeofmatsu/Java_CodingBats | String-3.java | 2,397 | /*
Given a string, return the longest substring that appears at both the beginning and end of the string without overlapping.
For example, sameEnds("abXab") is "ab".
sameEnds("abXYab") β "ab"
sameEnds("xx") β "x"
sameEnds("xxx") β "x"
*/ | block_comment | en | false | 2,133 | 72 | 2,397 | 79 | 2,533 | 74 | 2,397 | 79 | 2,684 | 82 | false | false | false | false | false | true |
171365_9 | import java.util.concurrent.ThreadLocalRandom;
abstract public class Workers implements Runnable {
private int id;
public void DoANote(Note CurrNote, QueuesList queuesList, int seconds,String doctorType) { // the treatment process for the senior and junior doctors
if (CurrNote.getSeverity() == -1) { //error registering for note
queuesList.InsertToNurseQ(new Note(CurrNote.getPatient())); // insert to Unbounded Queue for Nurses to re-measurement
return;
}
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
CurrNote.setDoctorid(getId()); // the doctor id in the note of the patient
CurrNote.setJunior(doctorType); // the doctor type in the note of the patient
CurrNote.setTreatment(ThreadLocalRandom.current().nextInt(1, 6) + CurrNote.getSeverity()); // the treatment for the patient
int r1 = (int) (Math.random() * 100);
if (r1 < 50) { // 50%, if the patient required to prescription or not
Prescription pre = new Prescription(CurrNote.getTreatment() + ThreadLocalRandom.current().nextInt(1, 6));
CurrNote.setPer(pre);
queuesList.getPharmacyQ().insert(CurrNote); // insert to Unbounded Queue for Pharmacist
DebugPrinter.PrintDebug("The doctor" + " " + this.getId() + " has sent the patient" +CurrNote.getPatient().getFirst_name() + " " + CurrNote.getPatient().getLast_name() + " to " + " the pharmacy");
} // else the patient is already extracted from the queue which means he is already sent home.
queuesList.getM().addNote(CurrNote); // Send to manger list the Note
DebugPrinter.PrintDebug("The doctor" + " " + this.getId() + " has sent the patient" +CurrNote.getPatient().getFirst_name() + " " + CurrNote.getPatient().getLast_name() + " to " + " the Manager");
}
public Workers(int id) { // setter method
this.id = id;
}
public int getId() { // getter method
return id;
}
}
| Dan1k99/multithreading | Workers.java | 574 | // Send to manger list the Note
| line_comment | en | false | 502 | 9 | 574 | 9 | 575 | 8 | 574 | 9 | 683 | 9 | false | false | false | false | false | true |
171483_9 | /**
* This class is used to store the data of the different types of farmers
* which are farmer (default), registered farmer, distinguished farmer, and
* legendary farmer. These different types of farmers have different values for
* their bonuses, minimum level, and registration fees.
*/
public class FarmerType {
private int bonusEarning; // The bonus earning of the farmer per harvest
private int costReduction; // The cost reduction of the farmer per seed
private int bonusWaterLimit; // The bonus water limit of the farmer per seed
private int bonusFertilizerLimit; // The bonus fertilizer limit of the farmer per seed
private int regFee; // registration fee of the type of farmer
private int minLevel; // minimum level to register
private String type; // type of farmer (farmer, registered farmer, distinguished farmer, legendary farmer)
/**
* This constructor assigns the values of each attribute.
* @param bonusEarning The bonus earning of the farmer per harvest
* @param costReduction The cost reduction of the farmer per seed
* @param bonusWaterLimit The bonus water limit of the farmer per seed
* @param bonusFertilizerLimit The bonus fertilizer limit of the farmer per seed
* @param regFee registration fee of the type of farmer
* @param minLevel minimum level to register
* @param type type of farmer (farmer, registered farmer, distinguished farmer, legendary farmer)
*/
public FarmerType(int bonusEarning, int costReduction, int bonusWaterLimit, int bonusFertilizerLimit, int regFee, int minLevel, String type) {
this.bonusEarning = bonusEarning;
this.costReduction = costReduction;
this.bonusWaterLimit = bonusWaterLimit;
this.bonusFertilizerLimit = bonusFertilizerLimit;
this.regFee = regFee;
this.minLevel = minLevel;
this.type = type;
}
/**
* This function returns the Bonus Earnings per Produce of the farmer type.
*
* @return The bonus earnings per produce.
*/
public int getBonusEarning() {
return this.bonusEarning;
}
/**
* This function returns the seed cost reduction of the farmer type.
*
* @return The amount reduced per seed.
*/
public int getCostReduction() {
return this.costReduction;
}
/**
* This function returns the Water Bonus Limit Increase of the farmer type.
*
* @return The water bonus limit increase.
*/
public int getBonusWaterLimit() {
return this.bonusWaterLimit;
}
/**
* This function returns the Fertilizer Bonus Limit Increase of the farmer type.
*
* @return The fertilizer bonus limit increase.
*/
public int getBonusFertilizerLimit() {
return this.bonusFertilizerLimit;
}
/**
* This function returns the cost it takes to register as this farmer type.
*
* @return The cost of registration.
*/
public int getRegFee() {
return this.regFee;
}
/**
* This function returns the minimum level it takes to register as this farmer type.
*
* @return The minimum level.
*/
public int getMinLevel() {
return this.minLevel;
}
/**
* This function returns the name of the farmer type in String.
*
* @return The name of the farmer type
*/
public String getType() {
return this.type;
}
}
| JsRphlMrtnz/Magpapakasal-sa-A-farm | FarmerType.java | 844 | /**
* This function returns the Bonus Earnings per Produce of the farmer type.
*
* @return The bonus earnings per produce.
*/ | block_comment | en | false | 752 | 28 | 844 | 37 | 816 | 31 | 844 | 37 | 953 | 37 | false | false | false | false | false | true |