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
217249_6
package gh2; import deque.Deque; import deque.LinkedListDeque; //Note: This file will not compile until you complete the Deque implementations public class GuitarString { /** Constants. Do not change. In case you're curious, the keyword final * means the values cannot be changed at runtime. We'll discuss this and * other topics in lecture on Friday. */ private static final int SR = 44100; // Sampling Rate private static final double DECAY = .996; // energy decay factor /* Buffer for storing sound data. */ private Deque<Double> buffer; /* Create a guitar string of the given frequency. */ public GuitarString(double frequency) { int capacity = (int) Math.round((double) SR / frequency); buffer = new LinkedListDeque(); for (int i = 0; i < capacity; i++) { buffer.addFirst(0.0); } } /* Pluck the guitar string by replacing the buffer with white noise. */ public void pluck() { Deque<Double> buffer2 = new LinkedListDeque(); for (int i = 0; i < buffer.size(); i++) { double numbers = Math.random() - 0.5; buffer2.addFirst(numbers); } buffer = buffer2; } /* Advance the simulation one time step by performing one iteration of * the Karplus-Strong algorithm. */ public void tic() { double first = buffer.removeFirst(); double getter = buffer.get(0); double enqueue = DECAY * ((first + getter) / 2); buffer.addLast(enqueue); } /* Return the double at the front of the buffer. */ public double sample() { return buffer.get(0); } }
angela-rodriguezz/Double-Ended-Deques
gh2/GuitarString.java
421
/* Pluck the guitar string by replacing the buffer with white noise. */
block_comment
en
false
391
15
421
16
451
15
421
16
478
15
false
false
false
false
false
true
218369_3
/* * Copyright (c) 2008-2009, Motorola, Inc. * * 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 Motorola, Inc. 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 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. */ package javax.obex; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * The <code>Operation</code> interface provides ways to manipulate a single * OBEX PUT or GET operation. The implementation of this interface sends OBEX * packets as they are built. If during the operation the peer in the operation * ends the operation, an <code>IOException</code> is thrown on the next read * from the input stream, write to the output stream, or call to * <code>sendHeaders()</code>. * <P> * <STRONG>Definition of methods inherited from <code>ContentConnection</code> * </STRONG> * <P> * <code>getEncoding()</code> will always return <code>null</code>. <BR> * <code>getLength()</code> will return the length specified by the OBEX Length * header or -1 if the OBEX Length header was not included. <BR> * <code>getType()</code> will return the value specified in the OBEX Type * header or <code>null</code> if the OBEX Type header was not included.<BR> * <P> * <STRONG>How Headers are Handled</STRONG> * <P> * As headers are received, they may be retrieved through the * <code>getReceivedHeaders()</code> method. If new headers are set during the * operation, the new headers will be sent during the next packet exchange. * <P> * <STRONG>PUT example</STRONG> * <P> * <PRE> * void putObjectViaOBEX(ClientSession conn, HeaderSet head, byte[] obj) throws IOException { * // Include the length header * head.setHeader(head.LENGTH, new Long(obj.length)); * // Initiate the PUT request * Operation op = conn.put(head); * // Open the output stream to put the object to it * DataOutputStream out = op.openDataOutputStream(); * // Send the object to the server * out.write(obj); * // End the transaction * out.close(); * op.close(); * } * </PRE> * <P> * <STRONG>GET example</STRONG> * <P> * <PRE> * byte[] getObjectViaOBEX(ClientSession conn, HeaderSet head) throws IOException { * // Send the initial GET request to the server * Operation op = conn.get(head); * // Retrieve the length of the object being sent back * int length = op.getLength(); * // Create space for the object * byte[] obj = new byte[length]; * // Get the object from the input stream * DataInputStream in = trans.openDataInputStream(); * in.read(obj); * // End the transaction * in.close(); * op.close(); * return obj; * } * </PRE> * * <H3>Client PUT Operation Flow</H3> For PUT operations, a call to * <code>close()</code> the <code>OutputStream</code> returned from * <code>openOutputStream()</code> or <code>openDataOutputStream()</code> will * signal that the request is done. (In OBEX terms, the End-Of-Body header * should be sent and the final bit in the request will be set.) At this point, * the reply from the server may begin to be processed. A call to * <code>getResponseCode()</code> will do an implicit close on the * <code>OutputStream</code> and therefore signal that the request is done. * <H3>Client GET Operation Flow</H3> For GET operation, a call to * <code>openInputStream()</code> or <code>openDataInputStream()</code> will * signal that the request is done. (In OBEX terms, the final bit in the request * will be set.) A call to <code>getResponseCode()</code> will cause an implicit * close on the <code>InputStream</code>. No further data may be read at this * point. * @hide */ public interface Operation { /** * Sends an ABORT message to the server. By calling this method, the * corresponding input and output streams will be closed along with this * object. No headers are sent in the abort request. This will end the * operation since <code>close()</code> will be called by this method. * @throws IOException if the transaction has already ended or if an OBEX * server calls this method */ void abort() throws IOException; /** * Returns the headers that have been received during the operation. * Modifying the object returned has no effect on the headers that are sent * or retrieved. * @return the headers received during this <code>Operation</code> * @throws IOException if this <code>Operation</code> has been closed */ HeaderSet getReceivedHeader() throws IOException; /** * Specifies the headers that should be sent in the next OBEX message that * is sent. * @param headers the headers to send in the next message * @throws IOException if this <code>Operation</code> has been closed or the * transaction has ended and no further messages will be exchanged * @throws IllegalArgumentException if <code>headers</code> was not created * by a call to <code>ServerRequestHandler.createHeaderSet()</code> * or <code>ClientSession.createHeaderSet()</code> * @throws NullPointerException if <code>headers</code> if <code>null</code> */ void sendHeaders(HeaderSet headers) throws IOException; /** * Returns the response code received from the server. Response codes are * defined in the <code>ResponseCodes</code> class. * @see ResponseCodes * @return the response code retrieved from the server * @throws IOException if an error occurred in the transport layer during * the transaction; if this object was created by an OBEX server */ int getResponseCode() throws IOException; String getEncoding(); long getLength(); int getHeaderLength(); String getType(); InputStream openInputStream() throws IOException; DataInputStream openDataInputStream() throws IOException; OutputStream openOutputStream() throws IOException; DataOutputStream openDataOutputStream() throws IOException; void close() throws IOException; void noEndofBody(); int getMaxPacketSize(); }
gp-b2g/frameworks_base
obex/javax/obex/Operation.java
1,829
/** * Returns the headers that have been received during the operation. * Modifying the object returned has no effect on the headers that are sent * or retrieved. * @return the headers received during this <code>Operation</code> * @throws IOException if this <code>Operation</code> has been closed */
block_comment
en
false
1,737
72
1,829
70
1,813
70
1,829
70
2,163
77
false
false
false
false
false
true
219069_0
/** * This program is intended to calculate the value of pi by simulating throwing darts at a dart *board. * */ import java.util.Scanner; import java.util.Random; import java.lang.Math; class PiValueMC { public static double[] calcPi(int d, int t) { int hit = 0; int miss = 0; double [] posX = new double[d]; double [] posY = new double[d]; double[] pi = new double[t]; for(int i = 0; i < t; i++) { hit = 0; for(int index = 0; index < d; index++) { posX[index] = 2 * Math.random() + - 1; posY[index] = 2 * Math.random() + - 1; if((Math.pow(posX[index], 2) + Math.pow(posY[index], 2)) <= 1) { hit++; } } pi[i] = (4 * ((double)hit / d)); } return pi; } public static double calcPiAverage(double[] p, double t) { double average = 0; double sum = 0; for(int i = 0; i < t; i++) { sum += p[i]; } average = sum / t; return average; } public static void printOutput(double [] p, double ave, int t) { for(int i = 0; i < t; i++) { System.out.print("Trial [" + i + "]: pi = "); System.out.printf("%5.5f%n", p[i]); } System.out.println("After " + t + " trials, Estimate of pi = " + ave); } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("How many darts per trial? "); int darts = in.nextInt(); System.out.println("How many trials? "); int trials = in.nextInt(); double [] pi = new double[trials]; pi = calcPi(darts, trials); double piAverage = calcPiAverage(pi, trials); printOutput(pi, piAverage, trials); } }
sreetamdas/Java
PiValueMC.java
555
/** * This program is intended to calculate the value of pi by simulating throwing darts at a dart *board. * */
block_comment
en
false
491
28
561
30
594
29
555
30
641
33
false
false
false
false
false
true
219082_0
/** * Validate if a given string is numeric. * * Some examples: * * "0" => true * " 0.1 " => true * "abc" => false * "1 a" => false * "2e10" => true * * Note: It is intended for the problem statement to be ambiguous. * You should gather all requirements up front before implementing one. * */ public class ValidNumber { public boolean isNumber(String s) { StringBuffer sb = new StringBuffer(s.trim()); int i = sb.length() - 1; while (i >= 0 && sb.charAt(i) == ' ') { i--; } sb.delete(i + 1, sb.length()); s = sb.toString(); int length = s.length(); if (length == 0) return false; i = 0; int start = 0; if (s.charAt(i) == '-' || s.charAt(i) == '+') { i++; start++; } for (; i < length; i++) { char c = s.charAt(i); if (c == 'e' || c == 'E') { return isDouble(s.substring(start, i)) && isDigitals(s.substring(i + 1, s.length())); } else if (c != '.' && (c < '0' || c > '9')) { return false; } } return isDouble(s.substring(start)); } private boolean isDouble(String s) { int length = s.length(); if (length == 0 || ((s.charAt(0) == '-' || s.charAt(0) == '+') && length == 1)) return false; int i = 0, start = 0; if (s.charAt(i) == '-' || s.charAt(i) == '+') { i++; start++; } for (; i < length; i++) { char c = s.charAt(i); if (c == '.') { if (i == start && s.length() - i - 1 == 0) return false; boolean left = i == start ? true : isDigitals(s.substring(0, i)); boolean right = s.length() - i - 1 == 0 ? true : isDigitals(s.substring(i + 1, s.length())); return left && right; } else if (c < '0' || c > '9') { return false; } } return true; } private boolean isDigitals(String s) { int length = s.length(); if (length == 0 || ((s.charAt(0) == '-' || s.charAt(0) == '+') && length == 1)) return false; int i = 0; if (s.charAt(i) == '-' || s.charAt(i) == '+') { i++; } for (; i < length; i++) { char c = s.charAt(i); if (c < '0' || c > '9') { return false; } } return true; } }
mikezhouhan/leetcode-3
ValidNumber.java
801
/** * Validate if a given string is numeric. * * Some examples: * * "0" => true * " 0.1 " => true * "abc" => false * "1 a" => false * "2e10" => true * * Note: It is intended for the problem statement to be ambiguous. * You should gather all requirements up front before implementing one. * */
block_comment
en
false
682
91
801
96
805
100
801
96
944
102
false
false
false
false
false
true
220125_4
/* * Copyright (c) OSGi Alliance (2009, 2014). 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.osgi.service.remoteserviceadmin; import org.osgi.annotation.versioning.ProviderType; /** * An Import Registration associates an active proxy service to a remote * endpoint. * * The Import Registration can be used to delete the proxy associated with an * endpoint. It is created with the * {@link RemoteServiceAdmin#importService(EndpointDescription)} method. * * When this Import Registration has been closed, all methods must return * {@code null}. * * @ThreadSafe * @author $Id: 4dfea3f10524d18ba3b46176b9df33e7de0e7176 $ */ @ProviderType public interface ImportRegistration { /** * Return the Import Reference for the imported service. * * @return The Import Reference for this registration, or <code>null</code> * if this Import Registration is closed. * @throws IllegalStateException When this registration was not properly * initialized. See {@link #getException()}. */ ImportReference getImportReference(); /** * Update the local service represented by this {@link ImportRegistration}. * After this method returns the {@link EndpointDescription} returned via * {@link #getImportReference()} must have been updated. * * @param endpoint The updated endpoint * * @return <code>true</code> if the endpoint was successfully updated, * <code>false</code> otherwise. If the update fails then the * failure can be retrieved from {@link #getException()}. * * @throws IllegalStateException When this registration is closed, or if it * was not properly initialized. See {@link #getException()}. * @throws IllegalArgumentException When the supplied * {@link EndpointDescription} does not represent the same endpoint * as this {@link ImportRegistration}. * * @since 1.1 */ boolean update(EndpointDescription endpoint); /** * Close this Import Registration. This must close the connection to the * endpoint and unregister the proxy. After this method returns, all other * methods must return {@code null}. * * This method has no effect when this registration has already been closed * or is being closed. */ void close(); /** * Return the exception for any error during the import process. * * If the Remote Service Admin for some reasons is unable to properly * initialize this registration, then it must return an exception from this * method. If no error occurred, this method must return {@code null}. * * The error must be set before this Import Registration is returned. * Asynchronously occurring errors must be reported to the log. * * @return The exception that occurred during the initialization of this * registration or {@code null} if no exception occurred. */ Throwable getException(); }
masud-technope/BLIZZARD-Replication-Package-ESEC-FSE2018
Corpus/ecf/468.java
802
/** * Close this Import Registration. This must close the connection to the * endpoint and unregister the proxy. After this method returns, all other * methods must return {@code null}. * * This method has no effect when this registration has already been closed * or is being closed. */
block_comment
en
false
788
68
802
64
859
72
802
64
931
74
false
false
false
false
false
true
221523_0
import java.awt.Color; import java.util.Arrays; public class poly { //TODO: only show if the poly if it is facing towards you double [] rotationPoint = new double[3]; public Corner [] corners; public Color color; public double [] centerXYZ; public poly(Corner[] corners, double [] centerXYZ, Color color) { this.color = color; this.corners = corners; this.centerXYZ = centerXYZ; } // rotates around given center public void rotate(double [] angles, double [] center) { for (int i = 0; i < corners.length; i ++) { corners[i].rotateCornerSet(angles[0], angles[1], angles[2], center); } } // rotates around given center public poly getRotated(double [] angles, double [] center) { poly pTemp = new poly(this.corners, this.centerXYZ, this.color); for (int i = 0; i < pTemp.corners.length; i ++) { pTemp.corners[i].rotateCornerSet(angles[0], angles[1], angles[2], center); } return pTemp; } public Corner getFurthestCorner() { Corner furthest = corners[0]; for(int i = 0; i < corners.length; i ++) { if(corners[i].locationIJK[Corner.K] > furthest.locationIJK[Corner.K]) { furthest = corners[i]; } } return furthest; } }
AndrewCaylor/3DRender
poly.java
422
//TODO: only show if the poly if it is facing towards you
line_comment
en
false
361
15
422
15
442
15
422
15
519
16
false
false
false
false
false
true
221636_3
import java.util.Comparator; /** * This class is implemented to store the rank list information * each rank consists of two data fields * 1. name : the user's name * 2. score: the score achieved while playing the game */ public class Rank implements Comparable<Rank>{ private int score; private String name; public Rank(String name, int score){ this.name = name; this.score = score; } @Override public String toString() { return this.name + " " + this.score; } @Override /** * when compare two Rank, actually compares their scores */ public int compareTo(Rank o) { if(this.score < o.score) return -1; if(this.score == o.score) return 0; else return 1; } public int getScore() { return score; } } /** * this sort class is used when calling the function of * Standard Sort and pass as a argument */ class SortRank implements Comparator<Rank>{ @Override public int compare(Rank o1, Rank o2) { return -o1.compareTo(o2); } } /** * this class contains two different properties * line eliminator and block transfer * it is randomly awarded after each successful elimination */ class Propoty{ private int numberOfLineEliminater = 1; private int numberOfBlockTransfer = 1; /** * after elimination, this function is automatically called * to award the player using this random algorithm * @param num the line successfully eliminated */ public void update(int num){ if(num * Math.random() > 1.2){ System.out.println("Congratulations: you get a Line Eliminator"); numberOfLineEliminater++; System.out.println(this); } else if(num * Math.random() > 1 ){ System.out.println("Congratulations: you get a block Transfer"); numberOfBlockTransfer++; System.out.println(this); } } /** * to display to the user how many properties are available * @return */ @Override public String toString() { return "\n\neliminator:"+numberOfLineEliminater + " |transfer : "+ numberOfBlockTransfer; } /** * use a line eliminator to eliminate a line * @param lineNum the specified line waiting to be eliminated */ public void eliminateALine(int lineNum){ if(numberOfLineEliminater == 0){ System.out.println("\nSorry, you have no eliminators right now\n"); return; } for(int i = 1; i < TetrisGame.map.length-1; i++){ TetrisGame.map[i][lineNum] = '\u2588'; } numberOfLineEliminater--; } /** * use a block transfer to change the nextBlock's type */ public Block ChangeNextBlock() throws IndexOutOfBoundsException{ if(numberOfBlockTransfer == 0){ System.out.println("\nSorry, you have no block transfers right now\n"); throw new IndexOutOfBoundsException("Block"); } numberOfBlockTransfer--; return TetrisGame.randomGenerateBlock(); } }
SzyWilliam/TetrisGame
Rank.java
753
/** * this class contains two different properties * line eliminator and block transfer * it is randomly awarded after each successful elimination */
block_comment
en
false
700
28
753
31
821
29
753
31
902
30
false
false
false
false
false
true
224830_0
package main.model; import com.google.gson.annotations.SerializedName; import main.constants.TimeConstants; import java.time.LocalTime; /** * Movie DAO derived straight from TMDB API * Is a specialized MotionPicture for movies */ @SuppressWarnings({"unused", "InstanceVariableMayNotBeInitialized"}) public class Movie extends MotionPicture implements TmdbObject { @SerializedName("id") private String id; @SerializedName("title") private String title; @SerializedName("runtime") private int runtime; @SerializedName("adult") private boolean adult; @SerializedName("release_date") private String releaseDate; @SerializedName("budget") private double budget; @SerializedName("revenue") private double revenue; @SerializedName("reviews") private ResultsPager<MovieReview> reviews; @SerializedName("recommendations") private MovieRecommendationResults recommendations; public Movie() { } public String getTitle() { return title; } public String getId() { return id; } public boolean isAdult() { return adult; } public String getReleaseDate() { return releaseDate; } public LocalTime getRuntime() { int hours = runtime / TimeConstants.MINUTES_IN_HOUR; int minutes = runtime % TimeConstants.MINUTES_IN_HOUR; return LocalTime.of(hours, minutes); } @Override public MediaType getMediaType() { return MediaType.MOVIE; } public double getBudget() { return budget; } public double getRevenue() { return revenue; } public ResultsPager<MovieReview> getReviews() { return reviews; } public MovieRecommendationResults getRecommendationResults() { return recommendations; } }
ZinoKader/CineMate
src/main/model/Movie.java
399
/** * Movie DAO derived straight from TMDB API * Is a specialized MotionPicture for movies */
block_comment
en
false
361
21
399
22
433
22
399
22
539
27
false
false
false
false
false
true
226831_17
import java.text.*; public class HMM { /** number of states */ public int numStates; /** size of output vocabulary */ public int sigmaSize; /** initial state probabilities */ public double pi[]; /** transition probabilities */ public double a[][]; /** emission probabilities */ public double b[][]; /** * initializes an HMM. * * @param numStates * number of states * @param sigmaSize * size of output vocabulary */ public HMM(int numStates, int sigmaSize) { this.numStates = numStates; this.sigmaSize = sigmaSize; pi = new double[numStates]; a = new double[numStates][numStates]; b = new double[numStates][sigmaSize]; } /** * implementation of the Baum-Welch Algorithm for HMMs. * * @param o * the training set * @param steps * the number of steps */ public void train(int[] o, int steps) { int T = o.length; double[][] fwd; double[][] bwd; double pi1[] = new double[numStates]; double a1[][] = new double[numStates][numStates]; double b1[][] = new double[numStates][sigmaSize]; for (int s = 0; s < steps; s++) { /* * calculation of Forward- und Backward Variables from the current * model */ fwd = forwardProc(o); bwd = backwardProc(o); /* re-estimation of initial state probabilities */ for (int i = 0; i < numStates; i++) pi1[i] = gamma(i, 0, o, fwd, bwd); /* re-estimation of transition probabilities */ for (int i = 0; i < numStates; i++) { for (int j = 0; j < numStates; j++) { double num = 0; double denom = 0; for (int t = 0; t <= T - 1; t++) { num += p(t, i, j, o, fwd, bwd); denom += gamma(i, t, o, fwd, bwd); } a1[i][j] = divide(num, denom); } } /* re-estimation of emission probabilities */ for (int i = 0; i < numStates; i++) { for (int k = 0; k < sigmaSize; k++) { double num = 0; double denom = 0; for (int t = 0; t <= T - 1; t++) { double g = gamma(i, t, o, fwd, bwd); num += g * (k == o[t] ? 1 : 0); denom += g; } b1[i][k] = divide(num, denom); } } pi = pi1; a = a1; b = b1; } } /** * calculation of Forward-Variables f(i,t) for state i at time t for output * sequence O with the current HMM parameters * * @param o * the output sequence O * @return an array f(i,t) over states and times, containing the * Forward-variables. */ public double[][] forwardProc(int[] o) { int T = o.length; double[][] fwd = new double[numStates][T]; /* initialization (time 0) */ for (int i = 0; i < numStates; i++) fwd[i][0] = pi[i] * b[i][o[0]]; /* induction */ for (int t = 0; t <= T - 2; t++) { for (int j = 0; j < numStates; j++) { fwd[j][t + 1] = 0; for (int i = 0; i < numStates; i++) fwd[j][t + 1] += (fwd[i][t] * a[i][j]); fwd[j][t + 1] *= b[j][o[t + 1]]; } } return fwd; } /** * calculation of Backward-Variables b(i,t) for state i at time t for output * sequence O with the current HMM parameters * * @param o * the output sequence O * @return an array b(i,t) over states and times, containing the * Backward-Variables. */ public double[][] backwardProc(int[] o) { int T = o.length; double[][] bwd = new double[numStates][T]; /* initialization (time 0) */ for (int i = 0; i < numStates; i++) bwd[i][T - 1] = 1; /* induction */ for (int t = T - 2; t >= 0; t--) { for (int i = 0; i < numStates; i++) { bwd[i][t] = 0; for (int j = 0; j < numStates; j++) bwd[i][t] += (bwd[j][t + 1] * a[i][j] * b[j][o[t + 1]]); } } return bwd; } /** * calculation of probability P(X_t = s_i, X_t+1 = s_j | O, m). * * @param t * time t * @param i * the number of state s_i * @param j * the number of state s_j * @param o * an output sequence o * @param fwd * the Forward-Variables for o * @param bwd * the Backward-Variables for o * @return P */ public double p(int t, int i, int j, int[] o, double[][] fwd, double[][] bwd) { double num; if (t == o.length - 1) num = fwd[i][t] * a[i][j]; else num = fwd[i][t] * a[i][j] * b[j][o[t + 1]] * bwd[j][t + 1]; double denom = 0; for (int k = 0; k < numStates; k++) denom += (fwd[k][t] * bwd[k][t]); return divide(num, denom); } /** computes gamma(i, t) */ public double gamma(int i, int t, int[] o, double[][] fwd, double[][] bwd) { double num = fwd[i][t] * bwd[i][t]; double denom = 0; for (int j = 0; j < numStates; j++) denom += fwd[j][t] * bwd[j][t]; return divide(num, denom); } /** prints all the parameters of an HMM */ public void print() { DecimalFormat fmt = new DecimalFormat(); fmt.setMinimumFractionDigits(5); fmt.setMaximumFractionDigits(5); for (int i = 0; i < numStates; i++) System.out.println("pi(" + i + ") = " + fmt.format(pi[i])); System.out.println(); for (int i = 0; i < numStates; i++) { for (int j = 0; j < numStates; j++) System.out.print("a(" + i + "," + j + ") = " + fmt.format(a[i][j]) + " "); System.out.println(); } System.out.println(); for (int i = 0; i < numStates; i++) { for (int k = 0; k < sigmaSize; k++) System.out.print("b(" + i + "," + k + ") = " + fmt.format(b[i][k]) + " "); System.out.println(); } } /** divides two doubles. 0 / 0 = 0! */ public double divide(double n, double d) { if (n == 0) return 0; else return n / d; } }
yutarochan/HMM
src/HMM.java
2,074
/** * calculation of probability P(X_t = s_i, X_t+1 = s_j | O, m). * * @param t * time t * @param i * the number of state s_i * @param j * the number of state s_j * @param o * an output sequence o * @param fwd * the Forward-Variables for o * @param bwd * the Backward-Variables for o * @return P */
block_comment
en
false
1,879
128
2,074
121
2,106
137
2,074
121
2,524
142
false
false
false
false
false
true
228581_5
package model; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.swing.JOptionPane; import edu.princeton.cs.introcs.StdOut; import utils.FilmRatingCompare; import utils.Sort; /** * @author colum foskin * This class is the Member model where all functions relating to the Member are performed. */ public class Member { private String firstName; private String lastName; private String accountName; private String passWord; private Map <Film, Rating> ratedFilms; private ArrayList<Film> myFilms;//used this as it was more suitable then the map for displaying films in a list form. public Member(String name, String lastName , String accountName, String passWord){ this.firstName = name; this.lastName = lastName; this.accountName = accountName; this.passWord = passWord; ratedFilms = new HashMap<>(); myFilms = new ArrayList<Film>(); } /** * @param film * @param rating * @return this method takes in the film and rating from the recommenderController class * and adds these to the member object. */ public boolean addFilmRating(Film film, Rating rating) { if(rating == null || ratedFilms.containsKey(film))//not allowing the user to rate the same film twice. { return false; } else { ratedFilms.put(film, rating); myFilms.add(film); } return true; } /** * @param memberTwo * @return this method checks the films that this member and another member * have seen and returns an array of these films. this array can then be used to * calculate the dot product of two members to see how similar they are, this avoids * checking irrelevant data. */ public ArrayList<Film> checkFilmsInCommon (Member memberTwo) { ArrayList<Film> commonFilms = new ArrayList<Film>(); ArrayList<Film> m1Films = getMyFilms(); ArrayList<Film> m2Films = memberTwo.getMyFilms(); for(int i=0; i< m1Films.size(); i++) { for(int j = 0; j< m2Films.size();j++) { if(m1Films.get(i).equals(m2Films.get(j))) { Film film = m1Films.get(i); if(!(commonFilms.contains(film))) { commonFilms.add(film); } } } } return commonFilms; } /** * @param memberOneKeys * @param memberTwoKeys * @return this method takes in the two arrays of ratings used in the findMostSimilarMember() * method and calculates the similarity of the two members. * */ private int dotProduct(ArrayList<Integer> memberOneKeys,ArrayList<Integer> memberTwoKeys) { int dotProduct =0; for(int i =0; i< memberOneKeys.size(); i++) { dotProduct += (memberOneKeys.get(i) * memberTwoKeys.get(i)); } return dotProduct; } /** * @param members * @return this method takes in the array of members passed in from the * RecommenderController.getReccomendedFilms() method. */ public Member findMostSimilarMember(ArrayList<Member> members) { int mostSimilar =0 ; Member tempMember = null; Member mostSimilarMember = null; for(Member m : members) { ArrayList<Integer> memberOneRatings = new ArrayList<Integer>(); ArrayList<Integer> tempMemberRatings = new ArrayList<Integer>(); int similarity = 0; if(!this.equals(m))// don't check against this.member. { tempMember = m; ArrayList<Film> commonFilms = this.checkFilmsInCommon(tempMember);//getting the array of films they have both rated for(int i =0; i< commonFilms.size(); i++) {//this loop retrieves the ratings that each member has given every film in the common films arraylist. Film film = commonFilms.get(i); int memberOneRating = this.getRatedFilms().get(film).getRatingValue(); memberOneRatings.add(memberOneRating); int tempMemberRating = tempMember.getRatingForfilm(film).getRatingValue(); tempMemberRatings.add(tempMemberRating); } try { similarity = dotProduct(memberOneRatings, tempMemberRatings);//this is then used to calculate the similarity of two members. } catch (Exception e) { } } if(similarity > mostSimilar) { mostSimilar = similarity; mostSimilarMember = tempMember; } } return mostSimilarMember; } /** * @param film * @return I had to implement this method which is called in the findMostSimilarMember() above * as I was using a film object as a key and this was causing mapping problems when trying to retrieve the * tempMembers rating for the film. */ private Rating getRatingForfilm(Film film) { Object[] arrayOfRatedFilms = this.ratedFilms.keySet().toArray(); Rating ratingOfFilm = null; for(Object aFilm : arrayOfRatedFilms){ int indexOfFilm = this.myFilms.indexOf(aFilm); ratingOfFilm = this.ratedFilms.get(this.myFilms.get(indexOfFilm)); } return ratingOfFilm; } /** * @param mostSimilarMember * @return this method returns the arraylist of films that are recommended by only the * most similar member to this.member. this function is called in the getReccomendedFilms() method * in the RecommenderController class. */ public ArrayList<Film> findRecommendedFilms(Member mostSimilarMember) { ArrayList<Film> recommendedFilms = new ArrayList<Film>(); try { for(int i=0;i < mostSimilarMember.getMyFilms().size();i++) { Film film = mostSimilarMember.getMyFilms().get(i); if(!(this.getMyFilms().contains(film)))//check to see if i have already rated and seen this film. { recommendedFilms.add(film);//if not add it to the list of recommended films for this.member } } } catch (Exception e) { JOptionPane.showMessageDialog(null, "You have seen all the films that member most similar to you has seen!"); } return recommendedFilms; } /** * @return * returns the map of rated films */ public Map<Film, Rating> getRatedFilms() { return ratedFilms; } /** * @return * returns a sorted array of films that ive rated */ public ArrayList<Film> getMyFilms() { Sort sort = new Sort(new FilmRatingCompare()); sort.selectionSort(myFilms); Collections.reverse(myFilms); return myFilms; } /** * @return returns the members firstname */ public String getFirstName() { return firstName; } /** * @return returns the members last name */ public String getLastName() { return lastName; } /** * @return returns the members account name */ public String getAccountName() { return accountName; } /** * @return returns the users password */ public String getPassWord() { return passWord; } @Override public String toString() { return firstName + " " + lastName + " "+accountName + " number of fims rated: " + this.getMyFilms().size(); } }
cfoskin/recommenderAssignment
src/model/Member.java
1,980
/** * @param memberOneKeys * @param memberTwoKeys * @return this method takes in the two arrays of ratings used in the findMostSimilarMember() * method and calculates the similarity of the two members. * */
block_comment
en
false
1,746
55
1,980
52
1,948
59
1,980
52
2,357
62
false
false
false
false
false
true
231928_0
package psl.discus.javasrc.p2p; import psl.discus.javasrc.shared.*; import psl.discus.javasrc.security.ServiceSpace; import psl.discus.javasrc.security.ServiceSpaceDAO; import javax.sql.DataSource; import net.jxta.protocol.PipeAdvertisement; import net.jxta.document.*; import java.sql.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Vector; import org.apache.log4j.Logger; /** * Handles database access for the Client class * @author matias */ public class ClientDAO { private static final MimeMediaType xmlMimeMediaType = new MimeMediaType("text/xml"); private static final Logger logger = Logger.getLogger(ClientDAO.class); private DataSource ds; public ClientDAO(DataSource ds) { this.ds = ds; } public ServiceSpaceEndpoint addPipeAdvertisement(ServiceSpace serviceSpace, PipeAdvertisement pipeAd) throws DAOException { Connection con = null; PreparedStatement stmt = null; try { con = ds.getConnection(); String sql = "INSERT INTO ServiceSpaceEndpoints(serviceSpaceId,pipeAd) VALUES(?,?)"; stmt = con.prepareStatement(sql); ByteArrayOutputStream out = new ByteArrayOutputStream(); pipeAd.getDocument(xmlMimeMediaType).sendToStream(out); stmt.setInt(1,serviceSpace.getServiceSpaceId()); stmt.setString(2,out.toString()); stmt.executeUpdate(); return new ServiceSpaceEndpointImpl(serviceSpace, pipeAd); } catch (Exception e) { throw new DAOException("Could not store pipe advertisement: " + e.getMessage()); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException e) { } try { if (con != null) con.close(); } catch (SQLException e) { } } } public void removePipeAdvertisement(PipeAdvertisement pipeAd) throws DAOException { Connection con = null; PreparedStatement stmt = null; try { con = ds.getConnection(); String sql = "DELETE FROM ServiceSpaceEndpoints WHERE pipeAd=?"; stmt = con.prepareStatement(sql); ByteArrayOutputStream out = new ByteArrayOutputStream(); pipeAd.getDocument(xmlMimeMediaType).sendToStream(out); stmt.setString(1,out.toString()); stmt.executeUpdate(); } catch (Exception e) { throw new DAOException("Could not remove pipe advertisement: " + e.getMessage()); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException e) { } try { if (con != null) con.close(); } catch (SQLException e) { } } } public Vector getServiceSpaceEndpoints() throws DAOException { Vector ads = new Vector(); Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; try { con = ds.getConnection(); String sql = "SELECT sse.pipeAd, ss.* FROM ServiceSpaceEndpoints sse, ServiceSpaces ss " + "WHERE sse.serviceSpaceId = ss.serviceSpaceId"; stmt = con.prepareStatement(sql); rs = stmt.executeQuery(); while (rs.next()) { int serviceSpaceId = rs.getInt("ss.serviceSpaceId"); String serviceSpaceName = rs.getString("serviceSpaceName"); int trustLevel = rs.getInt("trustLevel"); String pipeAdString = rs.getString("pipeAd"); PipeAdvertisement pipeAd = null; // instantiate pipead from the string try { ByteArrayInputStream in = new ByteArrayInputStream(pipeAdString.getBytes()); pipeAd = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(xmlMimeMediaType, in); in.close(); } catch (Exception e) { logger.warn("failed to read/parse pipe advertisement: " + pipeAdString); continue; } ServiceSpace serviceSpace = new ServiceSpaceDAO.ServiceSpaceImpl(serviceSpaceId,serviceSpaceName,trustLevel); ads.add(new ServiceSpaceEndpointImpl(serviceSpace,pipeAd)); } return ads; } catch (SQLException e) { throw new DAOException("Could not load advertisements: " + e.getMessage()); } finally { try { if (rs != null) rs.close(); } catch (SQLException e) { } try { if (stmt != null) stmt.close(); } catch (SQLException e) { } try { if (con != null) con.close(); } catch (SQLException e) { } } } private class ServiceSpaceEndpointImpl implements ServiceSpaceEndpoint { private ServiceSpace serviceSpace; private PipeAdvertisement pipeAd; public ServiceSpaceEndpointImpl(ServiceSpace serviceSpace, PipeAdvertisement pipeAd) { this.serviceSpace = serviceSpace; this.pipeAd = pipeAd; } public ServiceSpace getServiceSpace() { return serviceSpace; } public PipeAdvertisement getPipeAdvertisement() { return pipeAd; } public String toString() { return "Service Space id " + serviceSpace.getServiceSpaceId() + ", trust=" + serviceSpace.getTrustLevel(); } } }
Programming-Systems-Lab/archived-discus
javasrc/p2p/ClientDAO.java
1,187
/** * Handles database access for the Client class * @author matias */
block_comment
en
false
1,052
17
1,187
18
1,267
18
1,187
18
1,486
19
false
false
false
false
false
true
232298_0
package BackEnd; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class TaskDate implements Comparable<TaskDate>{ private LocalDate date; private static final String DATE_FORMAT = "dd/LL/yyyy"; private DateTimeFormatter pattern = DateTimeFormatter.ofPattern(DATE_FORMAT); public TaskDate(LocalDate date) throws IllegalArgumentException{ if (date == null) { this.date = noDate(); } else if(date.compareTo(LocalDate.of(1,1,1)) >= 0) { this.date = date; } else { throw new IllegalArgumentException(); } } public TaskDate(String str) throws IllegalArgumentException{ if (str.equals("null")) date = noDate(); else { LocalDate aux = LocalDate.parse(str, pattern); if (aux.compareTo(LocalDate.of(1,1,1)) >= 0) date = aux; else throw new IllegalArgumentException(); } } private static LocalDate noDate() { return LocalDate.of(0,1,1); //There is no year 0, so we use it for noDate } private static LocalDate today(){ return LocalDate.now(); } private static LocalDate yesterday(){ return today().minusDays(1); } private static LocalDate tomorrow(){ return today().plusDays(1); } public LocalDate getLocalDate() { if (date.equals(noDate())) { return null; } return date; } boolean isOverdue(){ if (date.equals(noDate())) return false; return date.compareTo(today())<0; } boolean forToday() { return date.compareTo(today())==0; } @Override public int compareTo(TaskDate o){ return date.compareTo(o.date); } @Override public boolean equals(Object o){ if (this == o) return true; if (!(o instanceof TaskDate)) return false; TaskDate aux = (TaskDate) o; return this.date.equals(aux.date); } @Override public int hashCode(){ if (date == null) return 0; return date.hashCode(); } @Override public String toString(){ if(date.equals(noDate())) return ""; if(date.equals(yesterday())) return "Yesterday"; if(date.equals(today())) return "Today"; if(date.equals(tomorrow())) return "Tomorrow"; return date.format(pattern); } String saveFormat(){ if(date.equals(noDate())) return "null"; return date.format(pattern); } }
fpetrikovich/java-agenda
src/BackEnd/TaskDate.java
610
//There is no year 0, so we use it for noDate
line_comment
en
false
547
15
610
15
692
15
610
15
755
15
false
false
false
false
false
true
234753_7
/** * Project 5 -- Maze * This is the Maze class for project 5. It is passed a string obtained by MapCreator.readMapCreator() * at initialization and parses the string to create a maze. The maze consists of a 2-D array * of MazeRoom objects. The MazeRoom class a public class defined within the Maze class (simply * because only Maze.java and Rat.java can be turned in: otherwise it would be in its own file) which * contains a constructor, accessors, and mutators. It allows each element of the 2-D array to know * about its own status with regard to wall presence and whether it is the start or end room. * The maze class itself contains its constructor, and accessors for width, height, and individual * elements of the array. (MazeRoom is public so that this last may return a MazeRoom that Rat can look at). * * @author Bess L. Walker * * @recitation 01 01 (H) Markova * * @date October 6, 2002 */ public class Maze { public static final char NORTH = '0'; public static final char EAST = '1'; public static final char SOUTH = '2'; public static final char WEST = '3'; public static final char START = 'S'; public static final char END = 'E'; /** * MazeRoom * Normally this would be in a separate file, but turn-in constraints force my hand. */ public class MazeRoom { private boolean northWall; private boolean eastWall; private boolean southWall; private boolean westWall; private boolean start; private boolean end; /** * default constructor */ public MazeRoom() { northWall = false; eastWall = false; southWall = false; westWall = false; start = false; end = false; } /** * north wall accessor * * @return the value of northWall */ public boolean northWall() { return northWall; } /** * east wall acessor * * @return the value of eastWall */ public boolean eastWall() { return eastWall; } /** * south wall acessor * * @return the value of southWall */ public boolean southWall() { return southWall; } /** * west wall acessor * * @return the value of westWall */ public boolean westWall() { return westWall; } /** * start acessor * * @return the value of start */ public boolean start() { return start; } /** * end acessor * * @return the value of end */ public boolean end() { return end; } /** * north wall mutator * * @param boolean value of the north wall */ public void setNorth(boolean inValue) { northWall = inValue; } /** * east wall mutator * * @param boolean value of the east wall */ public void setEast(boolean inValue) { eastWall = inValue; } /** * south wall mutator * * @param boolean value of the south wall */ public void setSouth(boolean inValue) { southWall = inValue; } /** * west wall mutator * * @param boolean value of the west wall */ public void setWest(boolean inValue) { westWall = inValue; } /** * start mutator * * @param boolean value of start (is this room the starting room?) */ public void setStart(boolean inValue) { start = inValue; } /** * end mutator * * @param boolean value of end (is this room the ending room?) */ public void setEnd(boolean inValue) { end = inValue; } } private MazeRoom[][] room; //size and elements given in Maze constructor /** * constructor which takes a string of maze data found by MapCreator.readMapFile() and turns it into a maze * * @param string of maze data found by MapCreator.readMapFile() */ public Maze(String mazeData) { final int END_OF_HEIGHT = 6; //"HEIGHT=" ends at mazeData[6] int position; int height; int width; int numRow = 0; int numCol = 0; int i; int j; mazeData = mazeData.toUpperCase(); //just in case it is not in upper case as the specs show for(position = END_OF_HEIGHT + 1; position <= mazeData.length() - 1; position++) //it should never reach mazeData.length() -1, but you can't be too careful { if(mazeData.charAt(position) == ' ') {break;} } height = Integer.parseInt(mazeData.substring(END_OF_HEIGHT + 1, position)); //parse the part of the string which represents the height integer into an integer final int END_OF_WIDTH = position + 6; //same idea as END_OF_HEIGHT above, but it can't be defined until you know where the height definition ends; normally I would never declare things in the middle of a function for(position = END_OF_WIDTH + 1; position <= mazeData.length() - 1; position++) { if(mazeData.charAt(position) == ' ') {break;} } width = Integer.parseInt(mazeData.substring(END_OF_WIDTH + 1, position)); //as above room = new MazeRoom[height][width]; for(i = 0; i <= room.length - 1; i++) { for(j = 0; j <= room[i].length - 1; j++) { room[i][j] = new MazeRoom(); } } for(position = position + 1; position <= mazeData.length() - 1; position++) { switch(mazeData.charAt(position)) { case ' ': numCol++; if(numCol % (room[numRow].length) == 0) { numCol = 0; numRow++; } break; case '0': room[numRow][numCol].setNorth(true); break; case '1': room[numRow][numCol].setEast(true); break; case '2': room[numRow][numCol].setSouth(true); break; case '3': room[numRow][numCol].setWest(true); break; case 'S': room[numRow][numCol].setStart(true); break; case 'E': room[numRow][numCol].setEnd(true); break; case 'X': break; default: System.out.println("uh-oh" + mazeData.charAt(position)); break; } } } /** * accessor for height * * @return height of maze */ public int getHeight() { return room.length; } /** * accessor for width * * @return width of maze */ public int getWidth() { return room[0].length; } /** * accessor for an element of the maze * * @param height-index, width-index * @return room at that position */ public MazeRoom element(int h, int w) { return room[h][w]; } }
besslwalker/astar-maze
Maze.java
1,987
/** * start acessor * * @return the value of start */
block_comment
en
false
1,772
20
1,987
19
2,099
24
1,987
19
2,609
31
false
false
false
false
false
true
238582_13
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2012 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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 HOLDERS 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.tool; import imagej.Contextual; import imagej.Prioritized; import imagej.display.event.input.KyPressedEvent; import imagej.display.event.input.KyReleasedEvent; import imagej.display.event.input.MsClickedEvent; import imagej.display.event.input.MsDraggedEvent; import imagej.display.event.input.MsMovedEvent; import imagej.display.event.input.MsPressedEvent; import imagej.display.event.input.MsReleasedEvent; import imagej.display.event.input.MsWheelEvent; import imagej.input.MouseCursor; import imagej.plugin.ImageJPlugin; import imagej.plugin.Plugin; import imagej.plugin.PluginInfo; /** * Interface for ImageJ tools. A tool is a collection of rules binding user * input (e.g., keyboard and mouse events) to display and data manipulation in a * coherent way. * <p> * For example, a {@code PanTool} might pan a display when the mouse is dragged * or arrow key is pressed, while a {@code PencilTool} could draw hard lines on * the data within a display. * </p> * <p> * Tools discoverable at runtime must implement this interface and be annotated * with @{@link Plugin} with {@link Plugin#type()} = {@link Tool}.class. While * it possible to create a tool merely by implementing this interface, it is * encouraged to instead extend {@link AbstractTool}, for convenience. * </p> * * @author Rick Lentz * @author Grant Harris * @author Curtis Rueden * @see Plugin * @see ToolService */ public interface Tool extends ImageJPlugin, Contextual, Prioritized { /** Gets the info describing the tool. */ PluginInfo<? extends Tool> getInfo(); /** Sets the info describing the tool. */ void setInfo(PluginInfo<? extends Tool> info); /** The tool's mouse pointer. */ MouseCursor getCursor(); /** Informs the tool that it is now active. */ void activate(); /** Informs the tool that it is no longer active. */ void deactivate(); /** Occurs when a key on the keyboard is pressed while the tool is active. */ void onKeyDown(KyPressedEvent event); /** Occurs when a key on the keyboard is released while the tool is active. */ void onKeyUp(KyReleasedEvent event); /** Occurs when a mouse button is pressed while the tool is active. */ void onMouseDown(MsPressedEvent event); /** Occurs when a mouse button is released while the tool is active. */ void onMouseUp(MsReleasedEvent event); /** Occurs when a mouse button is double clicked while the tool is active. */ void onMouseClick(MsClickedEvent event); /** Occurs when the mouse is moved while the tool is active. */ void onMouseMove(MsMovedEvent event); /** Occurs when the mouse is dragged while the tool is active. */ void onMouseDrag(MsDraggedEvent event); /** Occurs when the mouse wheel is moved while the tool is active. */ void onMouseWheel(MsWheelEvent event); /** Occurs when the user right clicks this tool's icon. */ void configure(); /** Returns the text the tool provides when mouse hovers over tool */ String getDescription(); }
msteptoe/FURI_Code
ijExtract/imagej/tool/Tool.java
1,217
/** Occurs when the mouse is dragged while the tool is active. */
block_comment
en
false
1,068
15
1,217
16
1,218
15
1,217
16
1,480
16
false
false
false
false
false
true
241873_2
package Chow7; import battlecode.common.*; public class DesignSchool extends RobotPlayer { static Direction buildDir = Direction.NORTH; static int landscapersBuilt = 0; static int vaporatorsBuilt = 0; static boolean needLandscaper = false; static boolean dontBuild = false; static boolean terraformingTime = false; public static void run() throws GameActionException { RobotInfo[] nearbyEnemyRobots = rc.senseNearbyRobots(-1, enemyTeam); for (int i = nearbyEnemyRobots.length; --i >= 0; ) { RobotInfo info = nearbyEnemyRobots[i]; } Transaction[] lastRoundsBlocks = rc.getBlock(rc.getRoundNum() - 1); boolean willBuild = false; if (rc.getTeamSoup() >= RobotType.LANDSCAPER.cost && landscapersBuilt < 2) { willBuild = true; } checkMessages(lastRoundsBlocks); if (needLandscaper) { willBuild = true; needLandscaper = false; if (debug) System.out.println("Building landscaper as asked by HQ "); } if (vaporatorsBuilt * 2 + 2 > landscapersBuilt && rc.getTeamSoup() >= RobotType.LANDSCAPER.cost + 250) { willBuild = true; if (debug) System.out.println("Building landscaper matching vaporators"); } if (rc.getTeamSoup() > 1000) { willBuild = true; } if (dontBuild) { willBuild = false; dontBuild = false; } if (terraformingTime && rc.getTeamSoup() >= RobotType.LANDSCAPER.cost && rc.getLocation().distanceSquaredTo(HQLocation) <= 48) { if (vaporatorsBuilt > 8) { if (vaporatorsBuilt * 5+ 5 > landscapersBuilt) { willBuild = true; } } else { if (vaporatorsBuilt * 1 > landscapersBuilt) { willBuild = true; } } } if (debug) System.out.println("Trying to build: " + willBuild); if (willBuild) { // should rely on some signal boolean builtUnit = false; buildDir = rc.getLocation().directionTo(HQLocation); for (int i = 9; --i >= 1; ) { if (tryBuild(RobotType.LANDSCAPER, buildDir) && !isDigLocation(rc.adjacentLocation(buildDir))) { builtUnit = true; break; } else { buildDir = buildDir.rotateRight(); } } if (builtUnit) { landscapersBuilt++; } buildDir = buildDir.rotateRight(); } } static void checkMessages(Transaction[] transactions) throws GameActionException { for (int i = transactions.length; --i >= 0;) { int[] msg = transactions[i].getMessage(); decodeMsg(msg); if (isOurMessage((msg))) { // FIXME: Buggy, better way? if ((msg[1] ^ NEED_LANDSCAPERS_FOR_DEFENCE) == 0) { int origSoup = msg[2]; int soupSpent = origSoup - rc.getTeamSoup(); // if soup spent / number of landscapers needed is greater than cost if (soupSpent / msg[3] < RobotType.LANDSCAPER.cost) { needLandscaper = true; } } else if ((msg[1] ^ BUILD_DRONE_NOW) == 0) { dontBuild = true; } else if (msg[1] == RobotType.VAPORATOR.ordinal()) { vaporatorsBuilt++; } else if ((msg[1] ^ NO_MORE_LANDSCAPERS_NEEDED) == 0) { terraformingTime = true; } } } } public static void setup() throws GameActionException { storeHQLocation(); announceSelfLocation(1); } }
StoneT2000/Battlecode2020
src/Chow7/DesignSchool.java
958
// if soup spent / number of landscapers needed is greater than cost
line_comment
en
false
894
14
958
15
1,019
15
958
15
1,158
15
false
false
false
false
false
true
242350_0
package nachos.ag; import nachos.threads.Boat; import nachos.threads.KThread; import nachos.machine.Lib; /** * Boat Grader * * @author crowwork */ public class BoatGrader extends BasicTestGrader { /** * BoatGrader consists of functions to be called to show that your solution * is properly synchronized. This version simply prints messages to standard * out, so that you can watch it. You cannot submit this file, as we will be * using our own version of it during grading. * * Note that this file includes all possible variants of how someone can get * from one island to another. Inclusion in this class does not imply that * any of the indicated actions are a good idea or even allowed. */ void run() { final int adults = getIntegerArgument("adults"); final int children = getIntegerArgument("children"); Lib.assertTrue(adults >= 0 && children >= 0, "number can not be negative"); this.startTest(adults, children); done(); } public void startTest(int adults, int children) { this.adultsOahu = adults; this.childrenOahu = children; this.adultsMolokai = this.childrenMolokai = 0; Boat.begin(this.adultsOahu, childrenOahu, this); } protected int adultsOahu, childrenOahu; protected int adultsMolokai, childrenMolokai; /** */ protected void check(boolean value, String msg) { Lib.assertTrue(value, msg); } /** * all the passenger has been crossed */ private void AllCrossed() { check(adultsOahu == 0, "there are still " + adultsOahu + " adults in Oahu"); check(childrenOahu == 0, "there are still " + childrenOahu + " children in Oahu"); } private void doYield() { while (random.nextBoolean()) KThread.yield(); } /* * ChildRowToMolokai should be called when a child pilots the boat from Oahu * to Molokai */ public void ChildRowToMolokai() { doYield(); check(childrenOahu > 0, "no children in Oahu,invalid operation ChildRowToMolokai"); childrenOahu--; childrenMolokai++; // System.out.println("**Child rowing to Molokai."); } /* * ChildRowToOahu should be called when a child pilots the boat from Molokai * to Oahu */ public void ChildRowToOahu() { doYield(); check(childrenMolokai > 0, "no children in Oahu , invalid operation ChildRowToOahu"); childrenOahu++; childrenMolokai--; // System.out.println("**Child rowing to Oahu."); } /* * ChildRideToMolokai should be called when a child not piloting the boat * disembarks on Molokai */ public void ChildRideToMolokai() { doYield(); check(childrenOahu > 0, "no children in Molokai , invalid operation ChildRideToMolokai"); childrenOahu--; childrenMolokai++; // System.out.println("**Child arrived on Molokai as a passenger."); } /* * ChildRideToOahu should be called when a child not piloting the boat * disembarks on Oahu */ public void ChildRideToOahu() { doYield(); check(childrenMolokai > 0, "no children in Molokai, invalid operation ChildRideToOahu"); childrenOahu++; childrenMolokai--; // System.out.println("**Child arrived on Oahu as a passenger."); } /* * AdultRowToMolokai should be called when a adult pilots the boat from Oahu * to Molokai */ public void AdultRowToMolokai() { doYield(); check(adultsOahu > 0, " no adult in Oahu , invalid operation AdultRowToMolokai"); adultsOahu--; adultsMolokai++; // System.out.println("**Adult rowing to Molokai."); } /* * AdultRowToOahu should be called when a adult pilots the boat from Molokai * to Oahu */ public void AdultRowToOahu() { doYield(); check(adultsMolokai > 0, "no adult in Molokai , invalid operation AdultRowToOahu"); adultsOahu++; adultsMolokai--; // System.out.println("**Adult rowing to Oahu."); } /* * AdultRideToMolokai should be called when an adult not piloting the boat * disembarks on Molokai */ public void AdultRideToMolokai() { Lib.assertNotReached("invalid operation AdultRideToMolokai"); // System.out.println("**Adult arrived on Molokai as a passenger."); } @Override public void readyThread(KThread thread) { if (thread==idleThread) { ++idleReadyCount; if (idleReadyCount > 1000) AllCrossed(); } else idleReadyCount=0; } /* * AdultRideToOahu should be called when an adult not piloting the boat * disembarks on Oahu */ public void AdultRideToOahu() { Lib.assertNotReached("invalid operation AdultRideToOahu"); // System.out.println("**Adult arrived on Oahu as a passenger."); } @Override public void setIdleThread(KThread thread){ thread=idleThread; } KThread idleThread; java.util.Random random = new java.util.Random(); private static int idleReadyCount = 0; }
lqhl/lqhl-acm-nachos
src/nachos/ag/BoatGrader.java
1,618
/** * Boat Grader * * @author crowwork */
block_comment
en
false
1,374
15
1,618
18
1,453
17
1,618
18
1,730
18
false
false
false
false
false
true
243093_7
package omr; import java.util.Observable; import java.util.Observer; import omr.gui.StatusBar; abstract public class Task extends Observable implements Runnable { //private LinkedList<ProgressListener> listeners; private StatusBar statusBar; private int estimatedOperationsCount; private int completedOperationsCount; public Task() { //this.listeners = new LinkedList<ProgressListener>(); this.estimatedOperationsCount = 1; this.completedOperationsCount = 0; } /** * Constructor * @param observer Observer to be notified when task is finished */ public Task(Observer observer) { super(); if (observer != null) { this.addObserver(observer); } } /** * Sets the statusbar for showing progress to the user. */ public void setStatusBar(StatusBar statusBar) { this.statusBar = statusBar; } /* public void addProgressListener(ProgressListener listener) { this.listeners.add(listener); } */ /** * Updates the statusbar text. */ protected void setStatusText(String text) { if (statusBar != null) { statusBar.setStatusText(text); } } /** * Sets the number of operations needed to complete the task. Progress bar will show completedOperationsCount / estimatedOperationsCount. */ protected void setEstimatedOperationsCount(int n) { this.estimatedOperationsCount = n; if (statusBar != null) { statusBar.setProgressTarget(n); } } /** * Returns the total number of operations needed to complete the task. */ public int getEstimatedOperationsCount() { return estimatedOperationsCount; } /** * Sets the number of completed operation. */ protected void setCompletedOperationsCount(int n) { this.completedOperationsCount = n; this.updateProgressBar(); } /** * Increases the number of completed operations by one. */ synchronized protected void increaseCompletedOperationsCount() { this.completedOperationsCount++; this.updateProgressBar(); } private void updateProgressBar() { if (statusBar == null) { return; } statusBar.setProgress(completedOperationsCount); } /** * Called when the task is finished. */ protected void finished() { if (statusBar != null) { statusBar.setStatusText(null); statusBar.setProgress(0); } // Notify observers setChanged(); notifyObservers(); } abstract public void run(); }
tsauvine/omr
src/omr/Task.java
574
/** * Returns the total number of operations needed to complete the task. */
block_comment
en
false
540
18
574
17
675
20
574
17
752
20
false
false
false
false
false
true
246869_4
/* * TEALsim - MIT TEAL Project * Copyright (c) 2004 The Massachusetts Institute of Technology. All rights reserved. * Please see license.txt in top level directory for full license. * * http://icampus.mit.edu/teal/TEALsim * * $Id: Field.java,v 1.22 2010/07/21 21:54:28 stefan Exp $ * */ package teal.field; import java.io.Serializable; import javax.vecmath.*; /** * A generic wrapper class for a Vector3dField which gets the potential of the field. * * @author Andrew McKinney * @author Phil Bailey * @author Michael Danziger * @version $Revision: 1.22 $ */ public abstract class Field implements Vector3dField, Serializable { /** * */ private static final long serialVersionUID = 5849538359071491882L; public static final double epsilon = 0.001; public final static int UNDEFINED = 0; public final static int B_FIELD = 1; public final static int E_FIELD = 2; public final static int P_FIELD = 3; public final static int D_FIELD = 4; public final static int G_FIELD = 5; public final static int EP_FIELD = 6; public abstract int getType(); public abstract Vector3d get(Vector3d x, Vector3d data); /** * Deprecated, calls get(Vector3d x, Vector3d data). * * @param x * @param data * @param t * @return abstract Vector3d */ public abstract Vector3d get(Vector3d x, Vector3d data, double t); public abstract Vector3d get(Vector3d x); /** * Deprecated, calls get(Vector3d x). * * @param x * @param t * @return theFieldValue */ public abstract Vector3d get(Vector3d x, double t); /** * This method should return the scalar flux at the supplied position. Flux type is determined by specific Field * implementation (EField, BField, etc.). * * @param x location to calculate flux. * @return scalar flux at this point. */ public abstract double getFlux(Vector3d x); /** * This method should return the scalar potential at the supplied position. Potential type is determined by the * specific Field implemtation (EField, BField, etc.). * * @param x position at which to calculate potential. * @return scalar potential at this point. */ public abstract double getPotential(Vector3d x); /** * Convenience function, calls get(Vector3d x) with a new Vector3d based on the supplied component values. * * @param x * @param y * @param z * @return theFieldValue */ public Vector3d get(double x, double y, double z) { return get(new Vector3d(x, y, z)); } /** * Calculates the gradient of the field at the given position. * * @param x position at which to calculate gradient. * @return Matrix3d getGradient */ public Matrix3d getGradient(Vector3d x) { Vector3d[] F = new Vector3d[] { get(new Vector3d(x.x + epsilon, x.y, x.z)), get(new Vector3d(x.x - epsilon, x.y, x.z)), get(new Vector3d(x.x, x.y + epsilon, x.z)), get(new Vector3d(x.x, x.y - epsilon, x.z)), get(new Vector3d(x.x, x.y, x.z + epsilon)), get(new Vector3d(x.x, x.y, x.z - epsilon)) }; return computeGradient(F); } /** * Deprecated, same as getGradient(Vector3d x). * * @param x * @param t * @return Matrix3d getGradient */ public Matrix3d getGradient(Vector3d x, double t) { Vector3d[] F = new Vector3d[] { get(new Vector3d(x.x + epsilon, x.y, x.z), t), get(new Vector3d(x.x - epsilon, x.y, x.z), t), get(new Vector3d(x.x, x.y + epsilon, x.z), t), get(new Vector3d(x.x, x.y - epsilon, x.z), t), get(new Vector3d(x.x, x.y, x.z + epsilon), t), get(new Vector3d(x.x, x.y, x.z - epsilon), t) }; return computeGradient(F); } /** * Internal method that actually computes gradient. * @param F * @return gradient */ protected Matrix3d computeGradient(Vector3d[] F) { Matrix3d grad = new Matrix3d(); double scale = 1.0 / (2.0 * epsilon); if (F.length > 5) { Vector3d dFdx = new Vector3d(); Vector3d dFdy = new Vector3d(); Vector3d dFdz = new Vector3d(); dFdx.sub(F[0], F[1]); dFdy.sub(F[2], F[3]); dFdz.sub(F[4], F[5]); dFdx.scale(scale); dFdy.scale(scale); dFdz.scale(scale); grad.setColumn(0, dFdx); grad.setColumn(1, dFdy); grad.setColumn(2, dFdz); } return grad; } /** * This method returns a normalized vector pointing in the direction of the field at the supplied position. * * @param pos position at which to calculate field. * @param stepArc not used. * @return normalized vector tangent to field. */ public Vector3d deltaField(Vector3d pos, double stepArc) { Vector3d tangent = new Vector3d(); Vector3d delta = new Vector3d(); //delta = get(pos,stepArc); delta = get(pos); double leng = delta.length(); if (leng != 0) tangent.scale(1 / leng, delta); return tangent; } /** * Same as deltaField(Vector3d pos, double stepArc), except returns a non-normalized vector. * @param pos * @param stepArc * @param bool */ public Vector3d deltaField(Vector3d pos, double stepArc, boolean bool) { Vector3d tangent = new Vector3d(); Vector3d delta = new Vector3d(); delta = get(pos); tangent.set(delta); return tangent; } }
JoeyPrink/TEALsim
src/teal/field/Field.java
1,663
/** * Deprecated, calls get(Vector3d x). * * @param x * @param t * @return theFieldValue */
block_comment
en
false
1,546
36
1,663
33
1,797
40
1,663
33
1,909
43
false
false
false
false
false
true
247659_8
package RPNCalculator; import java.util.*; import RPNCalculator.Stack; /** * ArrayStack class. * @author Max, Harry, Tom. */ public class ArrayStack<T> implements Stack<T> { /** final data field for default stack size. */ final static int DEFAULT=10; /** data field for generic stack. */ T[]stack; /** data field for stack size. */ public int size=0; /** Default Constructor for ArrayStack class. */ public ArrayStack(){ stack= (T[]) new Object[DEFAULT]; } /** Constructor for ArrayStack that creates a stack of a given size. * @param n desired size of stack. */ public ArrayStack(int n){ stack= (T[]) new Object[n]; } /** * Push method. * @param element - object to be added to the stack. */ public void push (T element) { if (size >= stack.length) { enlarge(); } stack[size] = element; size++; } /** * Enlarge method - copies the array into a new array double the size. */ public void enlarge(){ stack=Arrays.copyOf(stack, 2*stack.length); } /** * Peek method. * @return the top element in the stack. */ public T peek() { if (this.isEmpty()) { try { throw new Exception("Peek on empty stack"); } catch (Exception e) { e.printStackTrace(); } } return stack[size-1]; } /** * Pop method. * Removes and returns the top element in the stack. * @return the top element in the stack. */ public T pop() { if (this.isEmpty()) { try { throw new Exception("Pop from empty stack"); } catch (Exception e) { e.printStackTrace(); } } size--; return stack[size]; } /** * isEmpty method. * checks if the stack is empty. * @return boolean True if the stack is empty. */ public boolean isEmpty() { return size == 0; } /** * Size method. * @return number of items in the stack. */ public int size() { return size; } }
maxvds/RPNCalculator
java/ArrayStack.java
531
/** * Peek method. * @return the top element in the stack. */
block_comment
en
false
512
19
531
20
620
22
531
20
645
23
false
false
false
false
false
true
248218_0
/** * This class stores 2020 presidential election results by state. */ public class VotesByState { private String state; private int trumpVotes; private int bidenVotes; /** * Initializes the member variables to the respective arguments. * * @param state 2-letter code for the state * @param trumpVotes number of electoral votes won by Trump * @param bidenVotes number of electoral votes won by Biden */ public VotesByState(String state, int trumpVotes, int bidenVotes) { this.state = state; this.trumpVotes = trumpVotes; this.bidenVotes = bidenVotes; } /** * Returns the name of the state. * * @return a 2-letter state code */ public String getState() { return state; } /** * Returns the number of electoral votes won by Trump. * * @return number of electoral votes won by Trump */ public int getTrumpVotes() { return trumpVotes; } /** * Returns the number of electoral votes won by Biden. * * @return number of electoral votes won by Biden */ public int getBidenVotes(){ return bidenVotes; } /** * Constructs a string representation of the object * * @return A string representing the state, votes won by Trump, and votes won by Biden */ public String toString(){ return "(" + state + ", " + trumpVotes + ", " + bidenVotes + ")"; } public int getTotalVotes() { return trumpVotes + bidenVotes; } }
akwaed/laeti
VotesByState.java
387
/** * This class stores 2020 presidential election results by state. */
block_comment
en
false
366
17
387
20
439
19
387
20
497
21
false
false
false
false
false
true
248407_0
package gbemu.core; /** * This class contains all Flags that are used in the Emulator */ public class Flags { //CPU Flags public static final int Z = 0x80; public static final int N = 0x40; public static final int H = 0x20; public static final int C = 0x10; public static final int TAC_ENABLED = 0x04; public static final int TAC_CLOCK = 0x03; public static final int SC_TRANSFER_START = 0x80; public static final int SC_CLK_SPEED = 0x02; public static final int SC_SHIFT_CLK = 0x01; public static final int IE_JOYPAD_IRQ = 0x10; public static final int IE_LCD_STAT_IRQ = 0x02; public static final int IE_TIMER_IRQ = 0x04; public static final int IE_SERIAL_IRQ = 0x08; public static final int IE_VBLANK_IRQ = 0x01; public static final int IF_JOYPAD_IRQ = 0x10; public static final int IF_LCD_STAT_IRQ = 0x02; public static final int IF_TIMER_IRQ = 0x04; public static final int IF_SERIAL_IRQ = 0x08; public static final int IF_VBLANK_IRQ = 0x01; public static final int LCDC_LCD_ON = 0x80; public static final int LCDC_WINDOW_MAP = 0x40; public static final int LCDC_WINDOW_ON = 0x20; public static final int LCDC_BG_TILE_DATA = 0x10; public static final int LCDC_BG_TILE_MAP = 0x08; public static final int LCDC_OBJ_SIZE = 0x04; public static final int LCDC_OBJ_ON = 0x02; public static final int LCDC_BG_ON = 0x01; public static final int STAT_COINCIDENCE_IRQ = 0x40; public static final int STAT_OAM_IRQ_ON = 0x20; public static final int STAT_VBLANK_IRQ_ON = 0x10; public static final int STAT_HBLANK_IRQ_ON = 0x08; public static final int STAT_COINCIDENCE_STATUS = 0x04; public static final int STAT_MODE = 0x03; public static final int NR10_SWEEP_TIME = 0x70; public static final int NR10_SWEEP_MODE = 0x08; public static final int NR10_SWEEP_SHIFT_NB = 0x07; public static final int NR11_PATTERN_DUTY = 0xC0; public static final int NR11_SOUND_LENGTH = 0x3F; public static final int NR12_ENVELOPE_VOLUME = 0xF0; public static final int NR12_ENVELOPE_DIR = 0x08; public static final int NR12_ENVELOPE_SWEEP_NB = 0x07; public static final int NR14_RESTART = 0x80; public static final int NR14_LOOP_CHANNEL = 0x40; public static final int NR14_FREQ_HIGH = 0x07; public static final int NR21_PATTERN_DUTY = 0xC0; public static final int NR21_SOUND_LENGTH = 0x3F; public static final int NR22_ENVELOPE_VOLUME = 0xF0; public static final int NR22_ENVELOPE_DIR = 0x08; public static final int NR22_ENVELOPE_SWEEP_NB = 0x07; public static final int NR24_RESTART = 0x80; public static final int NR24_LOOP_CHANNEL = 0x40; public static final int NR24_FREQ_HIGH = 0x07; public static final int NR30_CHANNEL_ON = 0x80; public static final int NR32_OUTPUT_LEVEL = 0x60; public static final int NR34_RESTART = 0x80; public static final int NR34_LOOP_CHANNEL = 0x40; public static final int NR34_FREQ_HIGH = 0x07; public static final int NR41_SOUND_LENGTH = 0x3F; public static final int NR42_ENVELOPE_VOLUME = 0xF0; public static final int NR42_ENVELOPE_DIR = 0x08; public static final int NR42_ENVELOPE_SWEEP_NB = 0x07; public static final int NR43_SHIFT_CLK_FREQ = 0xF0; public static final int NR43_COUNTER_WIDTH = 0x08; public static final int NR43_DIV_RATIO = 0x07; public static final int NR44_RESTART = 0x80; public static final int NR44_LOOP_CHANNEL = 0x40; public static final int NR50_LEFT_SPEAKER_ON = 0x80; public static final int NR50_LEFT_VOLUME = 0x70; public static final int NR50_RIGHT_SPEAKER_ON = 0x08; public static final int NR50_RIGHT_VOLUME = 0x07; public static final int NR51_CHANNEL_4_LEFT = 0x80; public static final int NR51_CHANNEL_3_LEFT = 0x40; public static final int NR51_CHANNEL_2_LEFT = 0x20; public static final int NR51_CHANNEL_1_LEFT = 0x10; public static final int NR51_CHANNEL_4_RIGHT = 0x08; public static final int NR51_CHANNEL_3_RIGHT = 0x04; public static final int NR51_CHANNEL_2_RIGHT = 0x02; public static final int NR51_CHANNEL_1_RIGHT = 0x01; public static final int NR52_SOUND_ENABLED = 0x80; public static final int NR52_CHANNEL_4_ON = 0x08; public static final int NR52_CHANNEL_3_ON = 0x04; public static final int NR52_CHANNEL_2_ON = 0x02; public static final int NR52_CHANNEL_1_ON = 0x01; public static final int SPRITE_ATTRIB_UNDER_BG = 0x80; public static final int SPRITE_ATTRIB_Y_FLIP = 0x40; public static final int SPRITE_ATTRIB_X_FLIP = 0x20; public static final int SPRITE_ATTRIB_PAL = 0x10; public static final int P1_BUTTON = 0x20; public static final int P1_DPAD = 0x10; public static final int CGB_BCPS_AUTO_INC = 0x80; public static final int CGB_BCPS_ADDR = 0x3F; public static final int CGB_TILE_VRAM_BANK = 0x08; public static final int CGB_TILE_PALETTE = 0x07; public static final int CGB_TILE_HFLIP = 0x20; public static final int CGB_TILE_VFLIP = 0x40; public static final int CGB_TILE_PRIORITY = 0x80; public static final int SPRITE_ATTRIB_CGB_VRAM_BANK = 0x08; public static final int SPRITE_ATTRIB_CGB_PAL = 0x07; public static final int CGB_KEY_1_SPEED = 0x80; public static final int CGB_KEY_1_SWITCH = 0x01; }
Alban098/GBemu
src/gbemu/core/Flags.java
2,025
/** * This class contains all Flags that are used in the Emulator */
block_comment
en
false
1,809
16
2,025
17
2,106
16
2,025
17
2,416
18
false
false
false
false
false
true
953_4
import java.io.*; import java_cup.runtime.*; /** * Main program to test the parser. * * There should be 2 command-line arguments: * 1. the file to be parsed * 2. the output file into which the AST built by the parser should be * unparsed * The program opens the two files, creates a scanner and a parser, and * calls the parser. If the parse is successful, the AST is unparsed. */ public class P5 { FileReader inFile; private PrintWriter outFile; private static PrintStream outStream = System.err; public static final int RESULT_CORRECT = 0; public static final int RESULT_SYNTAX_ERROR = 1; public static final int RESULT_TYPE_ERROR = 2; public static final int RESULT_OTHER_ERROR = -1; /** * P5 constructor for client programs and testers. Note that * users MUST invoke {@link setInfile} and {@link setOutfile} */ public P5(){ } /** * If we are directly invoking P5 from the command line, this * is the command line to use. It shouldn't be invoked from * outside the class (hence the private constructor) because * it * @param args command line args array for [<infile> <outfile>] */ private P5(String[] args){ //Parse arguments if (args.length < 2) { String msg = "please supply name of file to be parsed" + "and name of file for unparsed version."; pukeAndDie(msg); } try{ setInfile(args[0]); setOutfile(args[1]); } catch(BadInfileException e){ pukeAndDie(e.getMessage()); } catch(BadOutfileException e){ pukeAndDie(e.getMessage()); } } /** * Source code file path * @param filename path to source file */ public void setInfile(String filename) throws BadInfileException{ try { inFile = new FileReader(filename); } catch (FileNotFoundException ex) { throw new BadInfileException(ex, filename); } } /** * Text file output * @param filename path to destination file */ public void setOutfile(String filename) throws BadOutfileException{ try { outFile = new PrintWriter(filename); } catch (FileNotFoundException ex) { throw new BadOutfileException(ex, filename); } } /** * Perform cleanup at the end of parsing. This should be called * after both good and bad input so that the files are all in a * consistent state */ public void cleanup(){ if (inFile != null){ try { inFile.close(); } catch (IOException e) { //At this point, users already know they screwed // up. No need to rub it in. } } if (outFile != null){ //If there is any output that needs to be // written to the stream, force it out. outFile.flush(); outFile.close(); } } /** * Private error handling method. Convenience method for * @link pukeAndDie(String, int) with a default error code * @param error message to print on exit */ private void pukeAndDie(String error){ pukeAndDie(error, -1); } /** * Private error handling method. Prints an error message * @link pukeAndDie(String, int) with a default error code * @param error message to print on exit */ private void pukeAndDie(String error, int retCode){ outStream.println(error); cleanup(); System.exit(-1); } /** the parser will return a Symbol whose value * field is the translation of the root nonterminal * (i.e., of the nonterminal "program") * @return root of the CFG */ private Symbol parseCFG(){ try { parser P = new parser(new Yylex(inFile)); return P.parse(); } catch (Exception e){ return null; } } public int process(){ Symbol cfgRoot = parseCFG(); ProgramNode astRoot = (ProgramNode)cfgRoot.value; if (ErrMsg.getErr()) { return P5.RESULT_SYNTAX_ERROR; } astRoot.nameAnalysis(); // perform name analysis if(ErrMsg.getErr()) { return P5.RESULT_SYNTAX_ERROR; } astRoot.typeCheck(); if(ErrMsg.getErr()) { return P5.RESULT_TYPE_ERROR; } astRoot.unparse(outFile, 0); return P5.RESULT_CORRECT; } public void run(){ int resultCode = process(); if (resultCode == RESULT_CORRECT){ cleanup(); return; } switch(resultCode){ case RESULT_SYNTAX_ERROR: pukeAndDie("Syntax error", resultCode); case RESULT_TYPE_ERROR: pukeAndDie("Type checking error", resultCode); default: pukeAndDie("Type checking error", RESULT_OTHER_ERROR); } } private class BadInfileException extends Exception{ private static final long serialVersionUID = 1L; private String message; public BadInfileException(Exception cause, String filename) { super(cause); this.message = "Could not open " + filename + " for reading"; } @Override public String getMessage(){ return message; } } private class BadOutfileException extends Exception{ private static final long serialVersionUID = 1L; private String message; public BadOutfileException(Exception cause, String filename) { super(cause); this.message = "Could not open " + filename + " for reading"; } @Override public String getMessage(){ return message; } } public static void main(String[] args){ P5 instance = new P5(args); instance.run(); } }
jkoritzinsky/Moo-Type-Analysis
P5.java
1,503
/** * Source code file path * @param filename path to source file */
block_comment
en
false
1,349
20
1,503
18
1,600
22
1,503
18
1,825
22
false
false
false
false
false
true
2735_0
/* In a group of N people (labelled 0, 1, 2, ..., N-1), each person has different amounts of money, and different levels of quietness. For convenience, we'll call the person with label x, simply "person x". We'll say that richer[i] = [x, y] if person x definitely has more money than person y. Note that richer may only be a subset of valid observations. Also, we'll say quiet[x] = q if person x has quietness q. Now, return answer, where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]), among all people who definitely have equal to or more money than person x. Example 1: Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0] Output: [5,5,2,5,4,5,6,7] Explanation: answer[0] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet[x]) is person 7, but it isn't clear if they have more money than person 0. answer[7] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7. The other answers can be filled out with similar reasoning. */ class Solution { public int[] loudAndRich(int[][] richer, int[] quiet) { int n = quiet.length; int[] ans = new int[n]; List<List<Integer>> graph = new ArrayList<>(); for (int i = 0; i < n; i++) { ans[i] = -1; graph.add(new ArrayList<Integer>()); } for (int[] v : richer) graph.get(v[1]).add(v[0]); for (int i = 0; i < n; i++) { ans[i] = dfs(i, ans, quiet, graph); } return ans; } // cached dfs private int dfs(int s, int[] ans, int[] quiet, List<List<Integer>> graph) { if (ans[s] >= 0) return ans[s]; int min = s; for (int v : graph.get(s)) { int r = dfs(v, ans, quiet, graph); if (quiet[r] < quiet[min]) min = r; } System.out.println(s + "," + min); ans[s] = min; return ans[s]; } }
wxping715/LeetCode
851.java
699
/* In a group of N people (labelled 0, 1, 2, ..., N-1), each person has different amounts of money, and different levels of quietness. For convenience, we'll call the person with label x, simply "person x". We'll say that richer[i] = [x, y] if person x definitely has more money than person y. Note that richer may only be a subset of valid observations. Also, we'll say quiet[x] = q if person x has quietness q. Now, return answer, where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]), among all people who definitely have equal to or more money than person x. Example 1: Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0] Output: [5,5,2,5,4,5,6,7] Explanation: answer[0] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet[x]) is person 7, but it isn't clear if they have more money than person 0. answer[7] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7. The other answers can be filled out with similar reasoning. */
block_comment
en
false
630
379
699
416
718
407
699
416
747
426
true
true
true
true
true
false
8398_0
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(nums[i], i); } // In case there is no solution, we'll just return null return null; } }
raunakbhupal/CodingPractice
AmazonQuestions/2Sum.java
120
// In case there is no solution, we'll just return null
line_comment
en
false
110
13
120
13
133
14
120
13
140
14
false
false
false
false
false
true
9231_27
package src.org.qcri.pipeline; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Random; public class Data { public static void main(String[] args) throws IOException { Configuration config = new Configuration(); initConfig(config); // Sets the maximum number of sources to be 10. int maxSrc = 10; for (int src = 1; src <= maxSrc; src += 1) { // Sets the source number in the config file. config.setNumSources(src); // Sets the min change duration in the experiment. for (int ch = 8; ch < 20; ch += 2) { long ms = System.currentTimeMillis(); config.setMinChange(ch); // Sets the maximum hold duration in the experiment. config.setMaxHold(ch + 5); System.out.println("\nSources:" + config.getNumSources() + "\t" + config.getMinChange() + "\t" + config.getMaxHold()); cases(config); long ms2 = System.currentTimeMillis(); System.out.print(" " + (ms2 - ms) / 1000.0); } } } /** * Creates the initial configuration, i.e., initial paramaters to be fed into the system. * @param config a holder for the input parameters. */ private static void initConfig(Configuration config) { // set number of reference values. These are the left hand side values. config.setNumLhs(1000); // stable values are the default states for the experiments. // We use these values to revert back to the default state // after an experiment before another experiment starts. config.setStableChange(200); config.setStableValueError(-1); config.setStableTimeError(-1); // Set the probability of reporting to be 100%. config.setStableProbReport(1000); config.setProbChange(config.getStableChange()); config.setProbValueError(config.getStableValueError()); config.setProbTimeError(config.getStableTimeError()); config.setProbReport(config.getStableProbReport()); config.setMaxHold(9); } /** * Takes a configuration and runs experiments according to it. * @param config input parameters for the experiment. * @throws IOException */ private static void cases(Configuration config) throws IOException { // case 1 // Runs the reporting probability experiment. config.updateConfig(1000, -1, -1, false, true, false, false); runCase(config); // case2 // Runs the value error probability experiment. config.updateConfig(1000, -1, -1, false, false, false, true); runCase(config); // case3 // Runs the time error probability experiment with probability of reporting set to 100%. config.updateConfig(1000, -1, -1, false, false, true, false); runCase(config); // case4 // Runs the time error probability experiment with probability of reporting set to 40%. config.updateConfig(40, -1, -1, false, false, true, false); runCase(config); // case5 // Runs the value error probability experiment with probability of reporting set to 40%. config.updateConfig(40, -1, -1, false, false, false, true); runCase(config); // case 6 int prReport = 900; config.setProbChange(200); int probValue = 100; int probTime = 100; config.updateConfig(prReport, probTime, probValue, true, false, false, false); runCase(config); } /** * Takes a configuration and runs an experiment with that configuration. * * @param config input params for the experiment. * @throws IOException */ private static void runCase(Configuration config) throws IOException { // Changes the probability of change in the experiment if (config.runChangeExp()) { for (int ch = 0; ch <= 1000; ch += 100) { config.setProbChange(ch); start(config); } config.setProbChange(config.getStableChange()); } // Changes the probability of time error in the experiment. if (config.runValueExp()) { for (int val = 0; val < 800; val += 100) { config.setProbValueError(val); start(config); } config.setProbValueError(config.getStableValueError()); } // Changes the probability of time error in the experiment. if (config.runTimeExp()) { for (int ti = 0; ti < 800; ti += 100) { config.setProbTimeError(ti); start(config); } config.setProbTimeError(config.getStableTimeError()); } // Changes the probability of reporting in the experiment. if (config.runReportExp()) { for (int re = 1000; re >= 200; re -= 100) { config.setProbReport(re); start(config); } config.setProbReport(config.getStableProbReport()); } // Used to run the last, composite experiment. if (config.runGeneralExp()) { start(config); } } /** * Runs a configuration. */ private static void start(Configuration config) throws IOException { Map<Integer, Long> errors = new HashMap<Integer, Long>(); long probValueError = config.getProbValueError(); // If it is not the last experiment. if(!config.generalExp){ run(config,errors,probValueError); } else{ // it is the last experiment. // ls holds the errors that we will add to each source. long [] ls = new long[] { 0, 100, 200 }; for (long d : ls) { add(errors, d); run(config,errors,probValueError); } } } private static void run(Configuration config, Map<Integer,Long> errors, long probValueError){ // Holds the last time a reference value has changed its value. Map<Integer, Long> lastChangeTime = new HashMap<Integer, Long>(); // Holds the last attribute value of a reference value. Map<Integer, Long> lastValue = new HashMap<Integer, Long>(); int maxProb = 1000; // Sets the length of each stripe. // Creates a stripe 30 times the length of the minimum change duration. long stepCount = 30 * config.getMinChange(); StringBuffer dataContent = new StringBuffer(); // For each reference value for (int lhs = 0; lhs < config.getNumLhs(); lhs++) { for (long window = 1; window < stepCount; window++) { // prob of change is independent of sources. // is it allowed to change? lastValue = changeAspect(config, lastChangeTime, lastValue, maxProb, lhs, window); // we have a specific value that is reported by a source // now. for (int src = 0; src < config.getNumSources(); src += 1) { // but will the source report it? if (actionIsOK(config.getProbReport(), maxProb)) { long val = lastValue.get(lhs); // And we are going to change it with errors. // should we add value error? if(config.generalExp){ probValueError = errors.get(src); } if (actionIsOK(probValueError, maxProb)) { // we add value error val = genRand(val); } long misstep = window; if (actionIsOK(config.getProbTimeError(), maxProb)) { // we add time error double ran = Math.random(); int c = 1; if (ran > 0.5) { // negative c = -1; } misstep = window + c * new Random().nextInt(5); } dataContent.append(src + "\t" + lhs + "\t" + misstep + "\t" + val + "\r\n"); } } } } //This commented out code is the entry point for running the temporal experiments. // We are sending the file content that holds the synthetically generated input data. // SyntheticTimeConstraintEntrance.syn(dataContent); } private static void add(Map<Integer, Long> errors, long x) { errors.put(0, 100 + x); errors.put(1, 100 + x); errors.put(2, 300 + x); errors.put(3, 500 + x); errors.put(4, 100 + x); errors.put(5, 300 + x); errors.put(6, 500 + x); errors.put(7, 100 + x); errors.put(8, 300 + x); errors.put(9, 500 + x); } private static Map<Integer, Long> changeAspect(Configuration config, Map<Integer, Long> lastChangeTime, Map<Integer, Long> lastValue, int maxProb, int lhs, long step) { long val = -1; // case 1: No previous value if (!lastChangeTime.containsKey(lhs)) { val = genRand(-1); lastValue.put(lhs, val); lastChangeTime.put(lhs, step); return lastValue; } // case 2: It has to change because of the maxHold long l = lastChangeTime.get(lhs); if ((step - l) >= config.getMaxHold()) { val = genRand(lastValue.get(lhs)); lastValue.put(lhs, val); lastChangeTime.put(lhs, step); return lastValue; } // case 3: It is still not past the min change. No change! if ((step - l) < config.getMinChange()) { return lastValue; } // case 4: It is allowed to change. But will it? if (actionIsOK(config.getProbChange(), maxProb)) { val = lastValue.get(lhs); val = genRand(val); lastValue.put(lhs, val); lastChangeTime.put(lhs, step); } return lastValue; } private static boolean actionIsOK(long prob, int maxProb) { long g = new Random().nextInt(maxProb); if (g <= prob) { return true; } return false; } /** * Returns a random value. * * @param val * value that is guaranteed to be different from the returned * value. * @return random value between 0 to 1000. */ private static int genRand(long val) { int i; Random generator = new Random(); i = generator.nextInt(1000); while (i == val) { i = genRand(val); } return i; } }
daqcri/AETAS_Dataset
Data.java
2,886
// Used to run the last, composite experiment.
line_comment
en
false
2,555
11
2,886
11
3,013
10
2,886
11
3,598
11
false
false
false
false
false
true
10175_15
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.BitSet; // A drawing of a CA, with stages of progression being drawn line-by-line // Default size is 63 columns of 31 rows, but will adapt to window resizes class Ca extends JPanel { // Each stage of progression is stored alternately in row // The current row to draw is held in rowIndex private BitSet row[] = {new BitSet(63), new BitSet(63)}; private int rowIndex = 0, y = 0, width = 63, height = 31, newWidth = 63; private boolean clear = true, update = false, dummyPaint = true; int rule = 0; // Create the CA with default size Ca() { // Set middle column row[0].set(width/2); setPreferredSize(new Dimension(630, 310)); } // Respond to request to move the animation on by one step void update() { // Set by graphics thread (so frames aren't skipped) if (update) { // Painted all of window, reset, set new width (if any), next rule if (y++ == height) { rule = (rule+1) % 256; width = newWidth; row[0].clear(); row[0].set(width/2); row[1].clear(); rowIndex = 0; y = 0; clear = true; } // Reflected binary code int rule_g = rule>>1 ^ rule; // First and last columns are special cases where only 2 bits of information can be retrieved from the row, // the sides of the window are treated as 0's // get returns a zero-length BitSet when no bits are set (unfortunately) try { row[1-rowIndex].set(0, (rule_g >> (row[rowIndex].get(0, 2).toByteArray()[0] & 3) & 1) == 1 ? true : false); } catch (ArrayIndexOutOfBoundsException e) { row[1-rowIndex].set(0, (rule_g & 1) == 1 ? true : false); } for (int i = 1; i < width-1; ++i) { try { row[1-rowIndex].set(i, (rule_g >> (row[rowIndex].get(i-1, i+2).toByteArray()[0] & 7) & 1) == 1 ? true : false); } catch (ArrayIndexOutOfBoundsException e) { row[1-rowIndex].set(i, (rule_g & 1) == 1 ? true : false); } } try { row[1-rowIndex].set(width-1, (rule_g >> (row[rowIndex].get(61, 63).toByteArray()[0] & 3) & 1) == 1 ? true : false); } catch (ArrayIndexOutOfBoundsException e) { row[1-rowIndex].set(width-1, (rule_g & 1) == 1 ? true : false); } row[rowIndex].clear(); rowIndex = 1 - rowIndex; update = false; } } // Draw the CA (called by the graphics thread, whenever it needs to, in // response to a repaint() request). public void paintComponent(Graphics g) { // The first time this function is called, nothing is drawn (for whatever reason) if (dummyPaint) { dummyPaint = false; return; } // Set when the last row has been drawn if (clear) { super.paintComponent(g); clear = false; } // Each bit in the row will represent a 10x10 square where: // 0 is the background (black) and // 1 is the foreground (red) // The motivation for not using a transparent background is rules such as 0 and 32 for (int x = 0; x < width; ++x) { if (row[rowIndex].get(x)) g.setColor(Color.RED); else g.setColor(Color.BLACK); g.fillRect(x * 10, y * 10, 10, 10); } update = true; } public void resize(ComponentEvent e) { newWidth = e.getComponent().getWidth()/10; height = e.getComponent().getHeight()/10; } }
PJBoy/cellular-automata-play
Ca.java
1,061
// The first time this function is called, nothing is drawn (for whatever reason)
line_comment
en
false
1,024
18
1,061
18
1,179
17
1,061
18
1,256
17
false
false
false
false
false
true
10355_5
import java.io.File; import java.io.FileNotFoundException; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; /* *@author: Aastha Dixit * * This class computes the shortest path for DAG's for the given graph. * Pre condition : Graph is acyclic. Otherwise output is arbitary */ public class DAG { /* This method computes the shortest paths of all the vertices and prints them. */ public static void DAG_graph(Vertex s, Graph g) { reset(g); topological_Sort(g); //performs topological sort to get the order to process the vertices reset(g); g.verts.get(1).distance = 0; for (Vertex m : g.topological) { for (Edge e : m.Adj) { Vertex end = e.otherEnd(m); //relaxing the edges if (end.distance > m.distance + e.Weight) { end.distance = m.distance + e.Weight; end.parent = m; } } } printGraph(g); } /* This method prints the given graph input in the format specified as below. Example. DAG <summation of the weight of the shortest paths> Vertex shortestPathDistance parent @param g: Graph that has to be printed in the format as above. */ static void printGraph(Graph g) { int total = 0; for (Vertex u : g) { Vertex current = u; while (current.parent != null) { current = current.parent; } if (current.name != g.topological.getFirst().name) { u.distance = Integer.MIN_VALUE; } else { total += u.distance; } } System.out.print("DAG " + " " + total); System.out.println(); if (g.verts.size() <= 101) { for (Vertex u : g) { String shortPath = u.distance != Integer.MIN_VALUE ? String.valueOf(u.distance) : "INF"; String parent = u.parent == null ? "-" : u.parent.toString(); System.out.print(u + " " + shortPath + " " + parent); System.out.println(); } } } /* * This method takes the graph and resets all the vertices * * */ public static void reset(Graph g) { for (Vertex u : g) { u.seen = false; u.parent = null; u.distance = Integer.MAX_VALUE; } } /* * This method computes the topological sort of the given graph and adds the sorted order * to the List (which stores topological order) in the graph class. * */ public static void topological_Sort(Graph g) { setIndegree(g); Queue<Vertex> top = new LinkedList<>(); for (Vertex initial : g) { if (initial.inDegree == 0) top.add(initial); } int find = 0; while (!top.isEmpty()) { Vertex u = top.poll(); if (u == g.verts.get(1)) { find = 1; } if (find == 1) g.topological.addLast(u); for (Edge e : u.Adj) { Vertex v = e.otherEnd(u); v.inDegree--; if (v.inDegree == 0) top.add(v); } } } /* *This method sets the indegree of the graph based on the edges of the directed graph * */ public static void setIndegree(Graph g) { for (Vertex v : g) { for (Edge e : v.revAdj) { v.inDegree++; } } } }
keerthibs/Shortest-Path-Algorithms
DAG.java
1,020
/* * This method takes the graph and resets all the vertices * * */
block_comment
en
false
815
17
1,020
25
1,027
23
1,020
25
1,221
26
false
false
false
false
false
true
10385_1
//Fred Dolan //The cars travel from stop to stop in a random order until they have been to them all, at which point they win import java.util.ArrayList; import java.awt.Graphics; import java.util.Random; import java.awt.Color; public class Car extends Movable { //the stops this car has been to private ArrayList<Stop> visited; //all the stops private ArrayList<Stop> stops; //the stop this care is currently travelling to private Stop destination; //has this car won private boolean winner; //textArea to post info private String infoText; //colors int red; int green; int blue; public Car(double x, double y, String n, int nspeed, ArrayList<Stop> nStops) { super(x,y,n,nspeed); stops = nStops; visited = new ArrayList<Stop>(); destination = findStop(); //colors Random gen = new Random(); red = gen.nextInt(256); green = gen.nextInt(256); blue = gen.nextInt(256); infoText=""; } public void draw(Graphics g) { int x = (int)Math.round(super.getXPos()); int y = (int)Math.round(super.getYPos()); g.setColor(Color.black); g.fillOval(0+x, 5+y, 5, 5); g.fillOval(10+x, 5+y, 5, 5); g.setColor(new Color(red, green, blue)); g.fillRect(2+x, 0+y, 10, 5); g.setColor(Color.black); } //moves the car towards the destination public void go() { moveTo(destination); } //adds the current stop to the visited array and finds a new destination public void atStop(Stop stop) { visited.add(stop); destination=findStop(); } //finds an unvisited stop and returns it; sets the car to winner if all stops are visited public Stop findStop() { Random gen = new Random(); boolean done = false; if(stops.size()==visited.size()){ winner=true; } else{ while(!done) { int index = gen.nextInt(stops.size()); if(!visited.contains(stops.get(index))) { done=true; return stops.get(index); } else { done=false; } } } int index = gen.nextInt(stops.size()); return stops.get(index); } public boolean getWinner() { return winner; } public Stop getDestination() { return destination; } public ArrayList<Stop> getVisited() { return visited; } }
dewskii/AmazingCarRaceRedo
Car.java
678
//The cars travel from stop to stop in a random order until they have been to them all, at which point they win
line_comment
en
false
613
26
677
26
799
26
678
26
847
26
false
false
false
false
false
true
10873_1
import java.util.Scanner; public class BMI { public static void main(String[] args) { Scanner sc=new Scanner(System.in); float w,h = 0; int k; System.out.println("Enter your Wight (1 for kg and 2 for pound)"); k=sc.nextInt(); System.out.print("Enter:"); /*If user Enter 1 than direct kg value scan * other wise as we know that 1pound=0.453592Kg*/ if(k==1)w=sc.nextFloat(); else { float e=sc.nextFloat(); w=e*0.453592f; } System.out.println("Enter your hight( 1 for feet and 2 for inch and 3 for feet+inch)"); k=sc.nextInt(); System.out.print("Enter:"); /*If Enter 1 than direct scan in feet and 1feet=.3048f meter * if User Enter 2 than scan value as inches only than /12 and than convert in to meter* * and at last if 3 than just converts inch into feet and than add with first input and than to meter*/ if(k==1) h=sc.nextFloat()*0.3048f; else if(k==2)h=(sc.nextFloat()/12)*0.3048f; else { float h1,h2; System.out.println("Feet inch"); h1=sc.nextFloat(); h2=sc.nextFloat(); h=(h1+h2/12)*0.3048f; } sc.close(); float BMI=w/(h*h); /*if BMI is <18.5 print "Person is Under-weight", * if BMI is >18.5 & < 24.9 print "Person is having Normal * BMI" & if BMI is >25 & <29.9 print "Person is Over-weight", * if BMI>30 print "Person Is Obese".*/ if(BMI<18.5) System.out.print("Person is Under-weight:"); else if(BMI>18.5 && BMI<24.9) System.out.print("Person is having Normal BMI:"); else if(BMI>25 && BMI<29.9) System.out.print("Person is Over-weight:"); else System.out.print("Person Is Obese:"); System.out.printf("%.2f",BMI); } }
aj1511/Problems
BMI.java
662
/*If Enter 1 than direct scan in feet and 1feet=.3048f meter * if User Enter 2 than scan value as inches only than /12 and than convert in to meter* * and at last if 3 than just converts inch into feet and than add with first input and than to meter*/
block_comment
en
false
539
72
662
73
674
72
662
73
724
74
false
false
false
false
false
true
10883_9
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); long highestCalc = 1; long[] cache = new long[10001]; for(int a0 = 0; a0 < t; a0++){ int n = in.nextInt(); long sum = 0; // If we've already calculated/cached answer, just serve it up if (highestCalc > n) { sum = cache[n]; } else { // If we have calculated before, get highest calculation // to avoid repeating our work if (highestCalc > 1) { sum = cache[(int)highestCalc]; } // Formula is (1 + 2 + ... + n)^2 - (1^2 + 2^2 + ... + n^2) // Works out to (1^2 + 2^2 + ... + n^2 + 2(1 * 2) + 2(1 * 3) + 2(2 * 3) // + ... + 2((n-2) * n) + 2((n-1) * n)) - (1^2 + 2^2 + ... + n^2) // This way because of binomial expansions, just cut out squares // for func(n), answer is 2*(func(n-1) + sum ([i up to n-1] * n)) for (long i = highestCalc + 1; i <= n; i++) { for (long j = 1; j < i; j++) { sum += j*i; } } } // cache prev answers to avoid repeating work, multiply sum by 2 // as in binomial expansions, and update our highest calc before printing out cache[n] = sum; sum *= 2; highestCalc = (long)n; System.out.println(sum); } } }
ThomasSeaver/ProjectEulerSolutions
006.java
488
// as in binomial expansions, and update our highest calc before printing out
line_comment
en
false
459
15
488
17
516
14
488
17
542
17
false
false
false
false
false
true
13667_8
package com.exchange; import java.io.*; import java.net.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.InputStream; import java.net.*; import com.google.gson.*; /** * * @author pakallis */ class Recv { private String lhs; private String rhs; private String error; private String icc; public Recv( { } public String getLhs() { return lhs; } public String getRhs() { return rhs; } } public class Convert extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String query = ""; String amount = ""; String curTo = ""; String curFrom = ""; String submit = ""; String res = ""; HttpSession session; resp.setContentType("text/html;charset=UTF-8"); PrintWriter out = resp.getWriter(); /*Read request parameters*/ amount = req.getParameter("amount"); curTo = req.getParameter("to"); curFrom = req.getParameter("from"); /*Open a connection to google and read the result*/ try { query = "http://www.google.com/ig/calculator?hl=en&q=" + amount + curFrom + "=?" + curTo; URL url = new URL(query); InputStreamReader stream = new InputStreamReader(url.openStream()); BufferedReader in = new BufferedReader(stream); String str = ""; String temp = ""; while ((temp = in.readLine()) != null) { str = str + temp; } /*Parse the result which is in json format*/ Gson gson = new Gson(); Recv st = gson.fromJson(str, Recv.class); String rhs = st.getRhs(); rhs = rhs.replaceAll("�", ""); /*we do the check in order to print the additional word(millions,billions etc)*/ StringTokenizer strto = new StringTokenizer(rhs); String nextToken; out.write(strto.nextToken()); nextToken = strto.nextToken(); if( nextToken.equals("million") || nextToken.equals("billion") || nextToken.equals("trillion")) { out.println(" "+nextToken); } } catch (NumberFormatException e) { out.println("The given amount is not a valid number"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Srutiverma123/Hacktoberfest-2021
mp1.java
873
/** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */
block_comment
en
false
794
58
873
55
945
60
873
55
1,040
67
false
false
false
false
false
true
14395_0
class TrieNode{ HashMap<Character, TrieNode> child; boolean isEnd; TrieNode(){ this.child = new HashMap(); this.isEnd = false; } } class Trie { private TrieNode root; public Trie() { this.root = new TrieNode(); } public void insert(String word) { char[] chars = word.toCharArray(); TrieNode currentNode = this.root; for(char ch: chars){ if(currentNode.child.get(ch) == null){ currentNode.child.put(ch, new TrieNode()); } currentNode = currentNode.child.get(ch); } currentNode.isEnd = true; } public boolean search(String word) { char[] chars = word.toCharArray(); TrieNode currentNode = this.root; for(char ch: chars){ if(currentNode.child.get(ch) == null){ return false; } currentNode = currentNode.child.get(ch); } if(currentNode!=null && currentNode.isEnd == false){ return false; } return true; } public boolean startsWith(String prefix) { char[] chars = prefix.toCharArray(); TrieNode currentNode = this.root; for(char ch: chars){ if(currentNode.child.get(ch) == null){ return false; } currentNode = currentNode.child.get(ch); } return true; } } /** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * boolean param_2 = obj.search(word); * boolean param_3 = obj.startsWith(prefix); */
iamtanbirahmed/100DaysOfLC
208.java
403
/** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * boolean param_2 = obj.search(word); * boolean param_3 = obj.startsWith(prefix); */
block_comment
en
false
340
46
403
61
447
58
403
61
490
63
false
false
false
false
false
true
14590_1
// camel-k: language=java dependency=camel-quarkus-openapi-java import org.apache.camel.builder.AggregationStrategies; import org.apache.camel.builder.RouteBuilder; public class API extends RouteBuilder { @Override public void configure() throws Exception { // All endpoints starting from "direct:..." reference an operationId defined // in the "openapi.yaml" file. // List the object names available in the S3 bucket from("direct:list") .to("aws2-s3://{{api.bucket}}?operation=listObjects") .split(simple("${body}"), AggregationStrategies.groupedBody()) .transform().simple("${body.key}") .end() .marshal().json(); // Get an object from the S3 bucket from("direct:get") .setHeader("CamelAwsS3Key", simple("${header.name}")) .to("aws2-s3://{{api.bucket}}?operation=getObject") .convertBodyTo(String.class); // Upload a new object into the S3 bucket from("direct:create") .setHeader("CamelAwsS3Key", simple("${header.name}")) .to("aws2-s3://{{api.bucket}}") .setBody().constant(""); // Delete an object from the S3 bucket from("direct:delete") .setHeader("CamelAwsS3Key", simple("${header.name}")) .to("aws2-s3://{{api.bucket}}?operation=deleteObject") .setBody().constant(""); } }
openshift-integration/camel-k-example-api
API.java
357
// All endpoints starting from "direct:..." reference an operationId defined
line_comment
en
false
338
14
357
14
379
14
357
14
427
15
false
false
false
false
false
true
15473_2
/* Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solution set must not contain duplicate triplets. For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2) */ // O(n*n*n) method exists, we should keep it O(n*n) //Use three pointers, two from beginning, one from tail, no necessary walk three pass //Arrays.sort() is Dual-Pivot Quicksort, O(nlogn) //check duplicate: !! // Time Limit Exceed means time complexity is not good!!!! public class Solution { public ArrayList<ArrayList<Integer>> threeSum(int[] num) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (num.length<3) return result; Arrays.sort(num); for (int i=0; i<num.length; i++) { if (i==0||num[i]>num[i-1]) { int j=i+1; int k=num.length-1; while (j<k) { if (num[i]+num[j]+num[k]==0) { ArrayList<Integer> temp = new ArrayList<Integer>(); temp.add(num[i]); temp.add(num[j]); temp.add(num[k]); result.add(temp); j=j+1; k=k-1; while(j<k&&num[k]==num[k+1])//jump those equals k=k-1; while(j<k&&num[j]==num[j-1]) j=j+1; } else if(num[i]+num[j]+num[k]<0){ j=j+1; } else { k=k-1; } } } } return result; } }
shinesong123/leetcode
3Sum.java
555
//Use three pointers, two from beginning, one from tail, no necessary walk three pass
line_comment
en
false
451
18
555
18
553
18
555
18
653
18
false
false
false
false
false
true
16966_2
class Solution { public int regionsBySlashes(String[] grid) { // union-find: // " " is all direction connected // "/" is "up-left" connected, "bottom-right" connected // "\\" is ... // thus compute the union region.. int N = grid.length; DSU dsu = new DSU(4 * N * N); for (int r = 0; r < N; ++r) for (int c = 0; c < N; ++c) { int root = 4 * (r * N + c); char val = grid[r].charAt(c); if (val != '\\') { dsu.union(root + 0, root + 1); dsu.union(root + 2, root + 3); } if (val != '/') { dsu.union(root + 0, root + 2); dsu.union(root + 1, root + 3); } // north south if (r + 1 < N) dsu.union(root + 3, (root + 4 * N) + 0); if (r - 1 >= 0) dsu.union(root + 0, (root - 4 * N) + 3); // east west if (c + 1 < N) dsu.union(root + 2, (root + 4) + 1); if (c - 1 >= 0) dsu.union(root + 1, (root - 4) + 2); } int ans = 0; for (int x = 0; x < 4 * N * N; ++x) { if (dsu.find(x) == x) ans++; } return ans; } } class DSU { int[] parent; public DSU(int N) { parent = new int[N]; for (int i = 0; i < N; ++i) parent[i] = i; } public int find(int x) { if (parent[x] != x) parent[x] = find(parent[x]); return parent[x]; } public void union(int x, int y) { parent[find(x)] = find(y); } }
higsyuhing/leetcode_middle
959.java
544
// "/" is "up-left" connected, "bottom-right" connected
line_comment
en
false
507
14
544
16
598
16
544
16
616
17
false
false
false
false
false
true
19122_9
class SearchUtil { // Boyer Moore algorithm copyright by Michael Lecuyer 1998. Slight modification below. private static final int MAXCHAR = 256; // Maximum chars in character set. private byte pat[]; // Byte representation of pattern private int patLen; private int partial; // Bytes of a partial match found at the end of a text buffer private int skip[]; // Internal BM table private int d[]; // Internal BM table SearchUtil() { skip = new int[MAXCHAR]; d = null; } public int boyer_mooreSearch(String text, String pattern) { byte[] byteText = text.getBytes(); compile(pattern); return search(byteText, 0, text.length()); } public int linearSsearch(String text, String pattern) { int textLength = text.length(); int patternLength = pattern.length(); for(int i = 0; i <= textLength - patternLength; i++) { String subPattern = text.substring(i, i + patternLength); if (pattern.equals(subPattern)) { return i; } } return -1; } public void compile(String pattern) { pat = pattern.getBytes(); patLen = pat.length; int j, k, m, t, t1, q, q1; int f[] = new int[patLen]; d = new int[patLen]; m = patLen; for (k = 0; k < MAXCHAR; k++) skip[k] = m; for (k = 1; k <= m; k++) { d[k-1] = (m << 1) - k; skip[pat[k-1]] = m - k; } t = m + 1; for (j = m; j > 0; j--) { f[j-1] = t; while (t <= m && pat[j-1] != pat[t-1]) { d[t-1] = (d[t-1] < m - j) ? d[t-1] : m - j; t = f[t-1]; } t--; } q = t; t = m + 1 - q; q1 = 1; t1 = 0; for (j = 1; j <= t; j++) { f[j-1] = t1; while (t1 >= 1 && pat[j-1] != pat[t1-1]) t1 = f[t1-1]; t1++; } while (q < m) { for (k = q1; k <= q; k++) d[k-1] = (d[k-1] < m + q - k) ? d[k-1] : m + q - k; q1 = q + 1; q = q + t - f[t-1]; t = f[t-1]; } } /** * Search for the compiled pattern in the given text. * A side effect of the search is the notion of a partial * match at the end of the searched buffer. * This partial match is helpful in searching text files when * the entire file doesn't fit into memory. * * @param text Buffer containing the text * @param start Start position for search * @param length Length of text in the buffer to be searched. * * @return position in buffer where the pattern was found. * @see patialMatch */ public int search(byte text[], int start, int length) { int textLen = length + start; partial = -1; // assume no partial match if (d == null) return -1; // no pattern compiled, nothing matches. int m = patLen; if (m == 0) return 0; int k, j = 0; int max = 0; // used in calculation of partial match. Max distand we jumped. for (k = start + m - 1; k < textLen;) { for (j = m - 1; j >= 0 && text[k] == pat[j]; j--) k--; if (j == -1) return k + 1; int z = skip[text[k]]; max = (z > d[j]) ? z : d[j]; k += max; } if (k >= textLen && j > 0) // if we're near end of buffer -- { partial = k - max - 1; return -1; // not a real match } return -1; // No match } /** * Returns the position at the end of the text buffer where a partial match was found. * <P> * In many case where a full text search of a large amount of data * precludes access to the entire file or stream the search algorithm * will note where the final partial match occurs. * After an entire buffer has been searched for full matches calling * this method will reveal if a potential match appeared at the end. * This information can be used to patch together the partial match * with the next buffer of data to determine if a real match occurred. * * @return -1 the number of bytes that formed a partial match, -1 if no * partial match */ public int partialMatch() { return partial; } }
ctSkennerton/minced
SearchUtil.java
1,276
// used in calculation of partial match. Max distand we jumped.
line_comment
en
false
1,245
15
1,276
16
1,480
14
1,276
16
1,527
15
false
false
false
false
false
true
23191_1
/* * Name: Caden Dowd * NetID: 31320610 * Assignment No.: Project 2 * Lab MW 2-3:15PM * I did not collaborate with anyone on this assignment. */ /* * The Bag class creates an array of clubs. */ public class Bag { private Club[] bag; public Bag(Club[] b) { bag = b; } public Club[] getBag() { return bag; } public Club getClub(int x) { return bag[x]; } public void setBag(Club[] b) { bag = b; } public void setClub(int x, Club c) { bag[x] = c; } }
cadendowd/CSC171Golf
Bag.java
195
/* * The Bag class creates an array of clubs. */
block_comment
en
false
171
12
195
15
207
14
195
15
220
14
false
false
false
false
false
true
23194_0
package Tetris; import java.awt.Dimension; import javax.swing.JFrame; /** * It's time for Tetris! This is the main class to get things started. The main method of this application * calls the App constructor. You will need to fill in the constructor to instantiate your Tetris game. * * Class comments here... * * @author vduong *Did you discuss your design with another student? no *If so, list their login here: * */ public class App extends JFrame { public App() { super ("Tetris"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setResizable(false); this.add(new MainPanel()); this.setPreferredSize(new Dimension(400, 800)); this.setVisible(true); this.pack(); } /* Here's the mainline */ public static void main(String[] args) { new App(); } }
vivian-duong/Tetris
App.java
241
/** * It's time for Tetris! This is the main class to get things started. The main method of this application * calls the App constructor. You will need to fill in the constructor to instantiate your Tetris game. * * Class comments here... * * @author vduong *Did you discuss your design with another student? no *If so, list their login here: * */
block_comment
en
false
193
86
241
91
261
95
241
91
302
103
false
false
false
false
false
true
23505_0
public enum Suit { CLUBS, DIAMONDS, SPADES, HEARTS } /* How to compare enums: Suit one = Suit.HEARTS; Suit two = Suit.SPADES; // compareTo will be positive if the caller is larger than the parameter // otherwise it will be negative if (one.compareTo(two) < 0) { System.out.println("this will be printed because one is less than two"); } */
Devking/HeartsAI
Suit.java
113
/* How to compare enums: Suit one = Suit.HEARTS; Suit two = Suit.SPADES; // compareTo will be positive if the caller is larger than the parameter // otherwise it will be negative if (one.compareTo(two) < 0) { System.out.println("this will be printed because one is less than two"); } */
block_comment
en
false
91
72
113
90
101
83
113
90
121
96
false
false
false
false
false
true
24463_0
/** * Given a directed graph, design an algorithm to find out whether there is a route between two nodes. */ /* ANSWER: * A simple graph traversal can be used here. In this cased I decided on an * iterative BFS solution. This uses a simple linked list queue and enum states * to keep track of which nodes it has already visited. This is to avoid an * infinite cycle in our traversal. * * While DFS could potentially faster, it also has the potential of being much * slower as it might traverse verly deeply in node's adjacent nodes before * checking the next node. */ public enum State { Unvisited, Visited, Visiting; } public static boolean search(Graph g, Node start, Node end) { // operates a Queue LinkedList<Node> q = new LinkedList<Node>(); for (Node u : g.getNodes()) { u.state = State.Unvisited; } start.state = State.Visiting; q.add(start); Node u; while (!q.isEmpty()) { u = q.removeFisrt(); // i.e., dequeue() if ( u != null) { for (Node v : u.getAdjacent()) { if (v.state == State.Unvisited) { if (v == end) { return true; } else { v.state = State.Visiting; q.add(v); } } } u.state = State.Visited; } } return false; }
nryoung/ctci
4/4-2.java
355
/** * Given a directed graph, design an algorithm to find out whether there is a route between two nodes. */
block_comment
en
false
316
23
354
25
367
25
355
25
401
25
false
false
false
false
false
true
28487_1
// -*- Java -*- /* * <copyright> * * Copyright (c) 2002 * Institute for Information Processing and Computer Supported New Media (IICM), * Graz University of Technology, Austria. * * </copyright> * * <file> * * Name: Output.java * * Purpose: Output prints sorted lines in a nice format * * Created: 24 Sep 2002 * * $Id$ * * Description: * Output prints sorted lines in a nice format * </file> */ package kwic.oo; /* * $Log$ */ /** * An instance of the Output class prints sorted lines in nice format. * @author dhelic * @version $Id$ */ public class Output{ //---------------------------------------------------------------------- /** * Fields * */ //---------------------------------------------------------------------- //---------------------------------------------------------------------- /** * Constructors * */ //---------------------------------------------------------------------- //---------------------------------------------------------------------- /** * Methods * */ //---------------------------------------------------------------------- //---------------------------------------------------------------------- /** * Prints the lines at the standard output. * @param alphabetizer source of the sorted lines * @return void */ public void print(Alphabetizer alphabetizer){ // iterate through all lines for(int i = 0; i < alphabetizer.getLineCount(); i++) // print current line System.out.println(alphabetizer.getLineAsString(i)); } //---------------------------------------------------------------------- /** * Inner classes * */ //---------------------------------------------------------------------- }
CreateChance/SA_kwic
src/oo/Output.java
367
/* * <copyright> * * Copyright (c) 2002 * Institute for Information Processing and Computer Supported New Media (IICM), * Graz University of Technology, Austria. * * </copyright> * * <file> * * Name: Output.java * * Purpose: Output prints sorted lines in a nice format * * Created: 24 Sep 2002 * * $Id$ * * Description: * Output prints sorted lines in a nice format * </file> */
block_comment
en
false
305
126
367
139
414
146
367
139
440
152
false
false
false
false
false
true
28503_19
import java.util.Arrays; import java.util.List; import java.util.LinkedList; import edu.princeton.cs.algs4.StdRandom; /** * Author: Vagner Planello * Date: 30/jul/2019 * * No parameters required to run from command line (Unit Testing only) */ public class Board { /** * Dimension of the board */ private final int n; /** * Manhattan index for the board */ private int manhattan = -1; /** * Hamming index for the board */ private int hamming = -1; /** * The board array */ private final int[][] tiles; /** * X-position of the empty cell */ private int emptyRow; /** * y-position of the empty cell */ private int emptyCol; /** * create a board from an n-by-n array of tiles, * where tiles[row][col] = tile at (row, col) * @param tiles */ public Board(int[][] tiles) { n = tiles.length; assert (n >= 2); assert (n < 128); for (int i = 0; i < tiles.length; i++) { assert (tiles[i].length == n); for (int j = 0; j < tiles.length; j++) { assert (tiles[i][j] < (n * n)); if (tiles[i][j] == 0) { emptyRow = i; emptyCol = j; } } } this.tiles = Arrays.copyOf(tiles, tiles.length); } /** * string representation of this board */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(n); sb.append('\n'); for (int i = 0; i < tiles.length; i++) { for (int j = 0; j < tiles[i].length; j++) { sb.append(" " + tiles[i][j]); } sb.append('\n'); } return sb.toString(); } /** * * @return board dimension n */ public int dimension() { return n; } /** * * @return number of tiles out of place */ public int hamming() { if (hamming >= 0) return hamming; hamming = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (this.tiles[i][j] != 0 && this.tiles[i][j] != (n * i) + (j % n) + 1) { hamming++; // System.out.println("Hamming " + tiles[i][j]); } } } return hamming; } /** * * @return sum of Manhattan distances between tiles and goal */ public int manhattan() { if (manhattan >= 0) return manhattan; manhattan = 0; for (int i = 0; i < tiles.length; i++) { for (int j = 0; j < tiles.length; j++) { if (tiles[i][j] > 0) { int row = (tiles[i][j]-1) / n; int col = (tiles[i][j]-1) % n; int manhattanRow = (i - row) > 0 ? (i - row) : (row - i); int manhattanCol = (j - col) > 0 ? (j - col) : (col - j); //System.out.println("Manhattan " + tiles[i][j] + " = " + (manhattanRow + manhattanCol)); manhattan = manhattan + manhattanRow + manhattanCol; } } } return manhattan; } /** * * @return is this board the goal board? */ public boolean isGoal() { return this.equals(getGoalBoard(this.n)); } /** * * @param y that board * @return does this board equal y? */ public boolean equals(Object y) { if (this == y) return true; if (y == null) return false; if (this.getClass() != y.getClass()) return false; Board that = (Board) y; if (this.n != that.n) return false; for (int i = 0; i < this.n; i++) { for (int j = 0; j < this.n; j++) { if (this.tiles[i][j] != that.tiles[i][j]) return false; } } return true; } /** * * @return all neighboring boards */ public Iterable<Board> neighbors() { List<Board> neighbors = new LinkedList<>(); Board neighbour = north(); if (neighbour != null) { neighbors.add(neighbour); } neighbour = south(); if (neighbour != null) { neighbors.add(neighbour); } neighbour = west(); if (neighbour != null) { neighbors.add(neighbour); } neighbour = east(); if (neighbour != null) { neighbors.add(neighbour); } return neighbors; } /** * * @return north neighbor or null if on top row */ private Board north() { if (emptyRow == 0) return null; int[][] clonedData = cloneData(); int temp = clonedData[emptyRow-1][emptyCol]; clonedData[emptyRow-1][emptyCol] = 0; clonedData[emptyRow][emptyCol] = temp; return new Board(clonedData); } /** * * @return south neighbor or null if on bottom row */ private Board south() { if (emptyRow == (n-1)) return null; int[][] clonedData = cloneData(); int temp = clonedData[emptyRow+1][emptyCol]; clonedData[emptyRow+1][emptyCol] = 0; clonedData[emptyRow][emptyCol] = temp; return new Board(clonedData); } /** * * @return west neighbor or null if on first column */ private Board west() { if (emptyCol == 0) return null; int[][] clonedData = cloneData(); int temp = clonedData[emptyRow][emptyCol-1]; clonedData[emptyRow][emptyCol-1] = 0; clonedData[emptyRow][emptyCol] = temp; return new Board(clonedData); } /** * * @return east neighbor or null if on last column */ private Board east() { if (emptyCol == (n-1)) return null; int[][] clonedData = cloneData(); int temp = clonedData[emptyRow][emptyCol+1]; clonedData[emptyRow][emptyCol+1] = 0; clonedData[emptyRow][emptyCol] = temp; return new Board(clonedData); } /** * * @return a board that is obtained by exchanging any pair of tiles */ public Board twin() { int[][] clonedData = cloneData(); if (clonedData[0][0] != 0 && clonedData[0][1] != 0) { clonedData[0][0] = tiles[0][1]; clonedData[0][1] = tiles[0][0]; } else { clonedData[1][0] = tiles[1][1]; clonedData[1][1] = tiles[1][0]; } return new Board(clonedData); } /** * * @return cloned array of data */ private int[][] cloneData() { int[][] clonedData = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { clonedData[i][j] = this.tiles[i][j]; } } return clonedData; } /** * * @param n size of the board * @return the goal bord for the n size */ private static Board getGoalBoard(int n) { int[][] goalBoardArray = new int[n][n]; int current = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { goalBoardArray[i][j] = current++; } } goalBoardArray[n-1][n-1] = 0; return new Board(goalBoardArray); } /** * unit testing (not graded) * @param args - none */ public static void main(String[] args) { Board goalBoard = getGoalBoard(3); System.out.println(goalBoard); System.out.println(">Hamming, Manhattan and is Goal for sample board"); Board randomBoard = new Board(new int[][]{{8, 1, 3}, {4, 0, 2}, {7, 6, 5}}); System.out.println(randomBoard.hamming()); System.out.println(randomBoard.manhattan()); System.out.println(randomBoard.isGoal()); System.out.println(); System.out.println(">Is goal for goal, sample and other goal board"); System.out.println(goalBoard.isGoal()); System.out.println(goalBoard.equals(randomBoard)); Board otherGoalBoard = getGoalBoard(3); System.out.println(goalBoard.equals(otherGoalBoard)); System.out.println(">Neighbours"); System.out.println(">>North"); Board north = randomBoard.north(); System.out.println(north); System.out.println(">>South"); Board south = randomBoard.south(); System.out.println(south); System.out.println(">>West"); Board west = randomBoard.west(); System.out.println(west); System.out.println(">>East"); Board east = randomBoard.east(); System.out.println(east); System.out.println(">>East twin"); Board twin = east.twin(); System.out.println(twin); } }
vagnerpl/Algorithms
Board.java
2,469
/** * * @return west neighbor or null if on first column */
block_comment
en
false
2,273
18
2,469
17
2,853
21
2,469
17
3,122
23
false
false
false
false
false
true
28554_6
/* Room (9 tasks) ✅ - private instance vars for name, description, character, roomItem, Room north, Room south, Room east, Room west ✅ + NoArgsConstructor ✅ + Room(String _name) 🔳 + Npc getCharacter() 🔳 + Item getItem() ✅ + Room getLocationTo(String direction) ✅ + String getName() ✅ + String getPossibleDirections() ✅ + void linkRoom(Room r, String direction) 🔳 + void setCharacter(Npc character) 🔳 + void setDescription(String d) DONE 🔳 + void setItem(Item i) ✅ + void setName(String _name) 🔳 + toString() // returns the description DONE */ public class Room { // private instance vars go here private String name; private String description; private Npc character; private Item roomItem; private Room north; private Room south; private Room east; private Room roomWest; public Room(){ name = "room name"; description = "room description"; character = null; roomItem = null; north = null; south = null; east = null; west = null; } public Room(String _name){ name = _name; description = "room description"; character = null; roomItem = null; north = null; south = null; east = null; west = null; } // precondition: direction is either "north" or "south" or "east" or "west" public Room getLocationTo(String direction) { if (direction.equals("north") && north != null){ return north; } else if (direction.equals("south") && south != null){ return south; } else if (direction.equals("east") && east != null){ return east; } else if (direction.equals("west") && west != null){ return west; } else { return this; // if none of those, then return the current room } } public String getPossibleDirections() { String possibleDirections = "Type either: "; if(north != null){ possibleDirections += "north, " } if(south != null){ possibleDirections += "south, " } if(east != null){ possibleDirections += "east, " } if(west != null){ possibleDirections += "west, " } } /** String getName() gets the name of the room @return returns the name of the room */ public String getName(){ return name; } /** * linkRoom(Room r, String direction) makes connections between two rooms * precondition: direction is either "north" or "south" or "east" or "west" * * @param r - a room object should be supplied for the variable r * @param direction - direction should be the lowercase words "north" "south" "east" or "west */ public void linkRoom(Room r, String direction) { if (direction == "south") { south = r; } else if (direction == "north") { north = r; } else if (direction == "west") { west = r; } else if (direction == "east") { east = r; } } /** void set room name * sets room name to a specific string * @param String _name a string that will replace the room name */ public void setName(String _name){ name = _name; } // methods go down here public void getCharacter(){ return character; } public void getItem(){ return roomItem; } public void setCharacter(Npc character){ this.character = character; } public void setItem(Item i){ this.Item = Item; } public void setDescription(String d){ this.description = description; } }
BradleyCodeU/JavaAdventureGame2023
Room.java
895
/** void set room name * sets room name to a specific string * @param String _name a string that will replace the room name */
block_comment
en
false
859
34
895
31
1,004
34
895
31
1,085
34
false
false
false
false
false
true
28790_0
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package kmo; import javax.swing.JFrame; public class KMo { }
LaRiffle/kmo
KMo.java
67
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */
block_comment
en
false
55
37
67
40
67
40
67
40
73
42
false
false
false
false
false
true
28992_0
import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * The test class BookTest. * * It is designed to test the mutators and accessors of the * book class. you must complete the assignment precisely * or the tests will not run. * * To run the tests, compile your project. You can test your classs * manually in BlueJ by creating instances and assigning values *.To run the test, right click on the BookTest object and select * run all tests. If you get a series of green checks, your * class is behaving properly. If you receive a red X, examine * your class and figure out why your implementation is not * passing that test. * * @author Crosbie * @version 0.1alpha */ /* Uncomment this when you are ready to * to test your Book class against the specification. * Select the entire class and use the uncomment shortcut from the * edit menu */ public class BookTest { private Book book1; private Book book2; private Book book3; /** * Default constructor for test class BookTest */ public BookTest() { } /** * Sets up the test fixture. * * Called before every test case method. */ @Before public void setUp() { book1 = new Book("Barnes & Kolling", "Objects First with BlueJ 6th Ed", 666, true); book2 = new Book("Marting, George RRRRRRRR", "Game of Clones", 2042, false); book3 = new Book("Jackson, Steven", "Uncle Albert's Guide to Automotive Combat", 74, false); } /** * Tears down the test fixture. * * Called after every test case method. */ @After public void tearDown() { } @Test public void getAuthor() { assertEquals("Marting, George RRRRRRRR", book2.getAuthor()); assertEquals("Barnes & Kolling", book1.getAuthor()); assertEquals("Jackson, Steven", book3.getAuthor()); } @Test public void getTitle() { assertEquals("Objects First with BlueJ 6th Ed", book1.getTitle()); assertEquals("Game of Clones", book2.getTitle()); assertEquals("Uncle Albert's Guide to Automotive Combat", book3.getTitle()); } @Test public void isCourseText() { assertEquals(true, book1.isCourseText()); assertEquals(false, book2.isCourseText()); assertEquals(false, book3.isCourseText()); } @Test public void getPages() { assertEquals(666, book1.getPages()); assertEquals(2042, book2.getPages()); assertEquals(74, book3.getPages()); } @Test public void borrowBook() { book1.borrow(); assertEquals(1, book1.getBorrowed()); book2.borrow(); book2.borrow(); book2.borrow(); assertEquals(3, book2.getBorrowed()); assertEquals(0, book3.getBorrowed()); } @Test public void setReferenceNumber() { book1.setRefNumber("ez"); assertEquals("", book1.getRefNumber()); book1.setRefNumber("BaKo6ed"); assertEquals("BaKo6ed", book1.getRefNumber()); } }
GDEV242-Sp2020/ch2-book-exercise-JPerhaps
BookTest.java
823
/** * The test class BookTest. * * It is designed to test the mutators and accessors of the * book class. you must complete the assignment precisely * or the tests will not run. * * To run the tests, compile your project. You can test your classs * manually in BlueJ by creating instances and assigning values *.To run the test, right click on the BookTest object and select * run all tests. If you get a series of green checks, your * class is behaving properly. If you receive a red X, examine * your class and figure out why your implementation is not * passing that test. * * @author Crosbie * @version 0.1alpha */
block_comment
en
false
769
158
823
164
877
166
823
164
968
168
false
false
false
false
false
true
29217_0
public class Line { private double a; private double b; private double c; public Line(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public double distanceFrom(Point p) { return Math.abs(a * p.getX() + b * p.getY() + c) / Math.sqrt(a * a + b * b); } public Point intersection(Line other) { double determinant = a * other.b - other.a * b; if (determinant == 0) { //lines are parallel, return null to indicate no intersection. return null; } else { double x = (other.b * c - b * other.c) / determinant; double y = (a * other.c - other.a * c) / determinant; return new Point(x, y); } } }
sandhyashevatre/Geometry-Intersection-Calculator
Line.java
227
//lines are parallel, return null to indicate no intersection.
line_comment
en
false
205
12
227
12
278
12
227
12
292
12
false
false
false
false
false
true
29575_4
/*Student class consists the following attributes: a) roll number b) read Number(): to initialize roll number c) print Number(): to display the roll number  class Test inherits Student and will identify marks for 2 subjects for each student and will display the same.  Each student can also be recognized with sports weightage using an interface Sports which will have attributes to assign weightage value and display it. Each Student is rated with total score which is the summation of marks in 2 subjects and sports weightage.  Develop an application Results to extend Test and implement Sports which displays the student score card as below: Roll No Marks Obtained in Subject-1 and Subject-2 Sports weight Total Score */ // created a interface for sports having attributes interface Sports{ void assignWeightage(double sportsWeightage); void displayWeightage(); } // created a students class class Students{ private int roll_no; public void readNumber(int roll_no){ this.roll_no = roll_no; } public void printNumber(){ System.out.println("The roll no of the student is " + roll_no); } } // class test inheriting students and identifies two marks and calcualtes total score getting weightage from the resutls class class Test extends Students { double subject1Marks; double subject2Marks; public void identifyMarks(double subject1Marks, double subject2Marks){ this.subject1Marks = subject1Marks; this.subject2Marks = subject2Marks; } public double calculateTotalScore(double sportsWeightage){ return subject1Marks + subject2Marks + sportsWeightage; } public void displayScoreCard(){ printNumber(); System.out.println("Subject 1 marks is " + subject1Marks); System.out.println("Subject 2 marks is " + subject2Marks); } } // here is the resutls class which overrides the methods and make necessary actions. class Results extends Test implements Sports{ private double sportsWeightage; // weightage of the sports is assigned here and displayed (the logic can be changed when and how required.) @Override public void assignWeightage(double sportsWeightage){ this.sportsWeightage = sportsWeightage; } @Override public void displayWeightage(){ System.out.println("Weightage from sports is " + sportsWeightage); } // upon identifying the sports weightage of the porticular student override again the display score card function @Override public void displayScoreCard(){ super.displayScoreCard(); // invoke the function of the inherited class. displayWeightage(); double totalScore = calculateTotalScore(sportsWeightage); System.out.println("Total score is " + totalScore); } } // example of how the program works can be done by using a scanner and input from the user also. public class ResultsMain{ public static void main(String args[]){ Results student = new Results(); student.readNumber(62); student.identifyMarks(89.5, 89.2); student.assignWeightage(34.4); student.displayScoreCard(); } }
Vasudevshetty/Java-OOPS
ResultsMain.java
759
// here is the resutls class which overrides the methods and make necessary actions.
line_comment
en
false
681
17
759
17
775
17
759
17
827
18
false
false
false
false
false
true
31343_19
//package ca.ualberta.cs.poker; /*************************************************************************** Card.java Student Name: Jimmy Collins Student No: 103660940 E-mail: [email protected] Part of PokerShark - Bsc Computer Science Final Year Project 2006 Original Copyright: Copyright (c) 2000: University of Alberta, Deptartment of Computing Science Computer Poker Research Group ***************************************************************************/ import java.lang.String; /** * Represents a playing card * from a set of cards {0..51} which map to cards having a suit * {0..3} <==> {CLUBS,DIAMONDS,HEARTS,SPADES} * and a face value {0..12} <==> {2..ACE} * * @author Aaron Davidson */ /* fully explicit card to integer conversions : 2c = 0 2d = 13 2h = 26 2s = 39 3c = 1 3d = 14 3h = 27 3s = 40 4c = 2 4d = 15 4h = 28 4s = 41 5c = 3 5d = 16 5h = 29 5s = 42 6c = 4 6d = 17 6h = 30 6s = 43 7c = 5 7d = 18 7h = 31 7s = 44 8c = 6 8d = 19 8h = 32 8s = 45 9c = 7 9d = 20 9h = 33 9s = 46 Tc = 8 Td = 21 Th = 34 Ts = 47 Jc = 9 Jd = 22 Jh = 35 Js = 48 Qc = 10 Qd = 23 Qh = 36 Qs = 49 Kc = 11 Kd = 24 Kh = 37 Ks = 50 Ac = 12 Ad = 25 Ah = 38 As = 51 */ public class Card { //------------------VARIABLES-----------------// public final static int CLUBS = 0; public final static int DIAMONDS = 1; public final static int HEARTS = 2; public final static int SPADES = 3; public final static int BAD_CARD = -1; public final static int TWO = 0; public final static int THREE = 1; public final static int FOUR = 2; public final static int FIVE = 3; public final static int SIX = 4; public final static int SEVEN = 5; public final static int EIGHT = 6; public final static int NINE = 7; public final static int TEN = 8; public final static int JACK = 9; public final static int QUEEN = 10; public final static int KING = 11; public final static int ACE = 12; public final static int NUM_SUITS = 4; public final static int NUM_RANKS = 13; public final static int NUM_CARDS = 52; private int gIndex; //------------------CONSTRUCTORS----------------// /** * Constructor, makes an empty card. */ public Card() { gIndex = -1; } /** * Constructor. * @param rank face value of the card * @param suit suit of the card */ public Card(int rank, int suit) { gIndex = toIndex(rank,suit); } /** * Constructor. * Creates a Card from an integer index {0..51} * @param index integer index of card between 0 and 51 */ public Card(int index) { if (index >= 0 && index < NUM_CARDS) gIndex = index; else gIndex = BAD_CARD; } /** * Constructor * @param s */ public Card(String s) { if (s.length()==2) gIndex = chars2index(s.charAt(0),s.charAt(1)); } /** * Constructor. * Creates a card from its character based representation. * @param rank the character representing the card's rank * @param suit the character representing the card's suit */ public Card(char rank, char suit) { gIndex = chars2index(rank, suit); } //------------------METHODS-------------------// /** * Chars to index value * @param rank The rnak of the card * @param suit The suit of the card */ private int chars2index(char rank, char suit) { int r = -1; switch (rank) { case '2': r = TWO; break; case '3': r = THREE; break; case '4': r = FOUR; break; case '5': r = FIVE; break; case '6': r = SIX; break; case '7': r = SEVEN; break; case '8': r = EIGHT; break; case '9': r = NINE; break; case 'T': r = TEN; break; case 'J': r = JACK; break; case 'Q': r = QUEEN; break; case 'K': r = KING; break; case 'A': r = ACE; break; case 't': r = TEN; break; case 'j': r = JACK; break; case 'q': r = QUEEN; break; case 'k': r = KING; break; case 'a': r = ACE; break; } int s = -1; switch (suit) { case 'h': s = HEARTS; break; case 'd': s = DIAMONDS; break; case 's': s = SPADES; break; case 'c': s = CLUBS; break; case 'H': s = HEARTS; break; case 'D': s = DIAMONDS; break; case 'S': s = SPADES; break; case 'C': s = CLUBS; break; } if (s != -1 && r != -1) return toIndex(r,s); else return BAD_CARD; } /** * Return the integer index for this card. * @return the card's index value */ public int getIndex() { return gIndex; } /** * Change the index of the card. * @param index the new index of the card */ public void setIndex(int index) { gIndex = index; } /** * Convert a rank and a suit to an index * @param rank the rank to convert * @param suit the suit to convert * @return the index calculated from the rank and suit */ public static int toIndex(int rank, int suit) { return (NUM_RANKS*suit) + rank; } /** * Change this card to another. This is more practical * than creating a new object for optimization reasons. * @param rank face value of the card * @param suit suit of the card */ public void setCard(int rank, int suit) { gIndex = toIndex(rank, suit); } /** * Obtain the rank of this card * @return rank */ public int getRank() { return (int)(gIndex%NUM_RANKS); } /** * Obtain the rank of this card * @return rank */ public static int getRank(int i) { return (int)(i%NUM_RANKS); } /** * Obtain the suit of this card * @return suit */ public int getSuit() { return (int)(gIndex/NUM_RANKS); } /** * Obtain the suit of this card * @return suit */ public final static int getSuit(int i) { return (i / NUM_RANKS); } /** * Obtain a String representation of this Card * @return A string for this card */ public String toString() { String s = new String(); s += getRankChar(getRank()); switch (getSuit()) { case HEARTS: s+='h'; break; case DIAMONDS: s+='d'; break; case CLUBS: s+='c'; break; case SPADES: s+='s'; break; } return s; } /** * Get ranked character * @param r */ public static char getRankChar(int r) { char s; switch (r) { case ACE: s='A'; break; case KING: s='K'; break; case QUEEN: s='Q'; break; case JACK: s='J'; break; case TEN: s='T'; break; default: s = Character.forDigit(r+2,Character.MAX_RADIX); break; } return s; } }
JimmyCollins/PokerShark
Card.java
2,309
/** * Obtain the suit of this card * @return suit */
block_comment
en
false
1,999
15
2,314
17
2,215
16
2,309
16
2,473
17
false
false
false
false
false
true
33324_14
import static java.lang.Math.min; /** * Tile stores information about a particular tile or plot of land. */ public class Tile { private FarmSeeds seeds = null; private boolean rock = false; private boolean plowed = false; private int waterTimes = 0; private int fertilizerTimes = 0; private int age = 0; /** * Creates a new Tile without a rock */ public Tile() { } /** * Creates a new Tile with or without a rock * * @param rock true if Tile should have a rock, otherwise false */ public Tile(boolean rock) { this.rock = rock; } /** gets the information about the tile * @return the string of information about the tile */ public String displayTileStatus() { String status = "<html><pre>"; status += "\nAbout tile:" + "\n"; status += "rock: " + this.rock + "\n"; status += "plowed: " + this.plowed + "\n"; if (this.seeds != null) { status += "crop: " + this.seeds.getName() + "\n"; status += "Times Watered: " + this.waterTimes + "\n"; status += addWaterStatus() + "\n"; status += "Times Fertilized: " + this.fertilizerTimes + "\n"; status += addFertilizerStatus() + "\n"; status += "Age: " + this.age +" days" + "\n"; status += "Harvest Time: day " + this.seeds.getHarvestTime() + "\n" ; } else status += "...no crop planted" + "\n"; status += "</pre></html>"; return status; } /** * Reset the Tile's state into the default state (except for the presence/absence of a rock) */ public void reset() { // reset all except for rock this.seeds = null; this.plowed = false; this.waterTimes = 0; this.fertilizerTimes = 0; this.age = 0; } /** * Checks if the tile can be plowed * * @return 0 if the tile can be plowed, otherwise, there is a specific error */ public int canPlow() { int error = 0; if (this.isPlowed()) error = 1; else if(this.isRock()) error = 2; return error; } /** * Checks if the tile can be planted on * * @return true if the tile can be planted on, otherwise, false */ private boolean canPlant() { return this.isPlowed() && this.seeds == null; } /** * Checks if the tile can be watered or fertilized. * * @return true if the tile can be watered/fertilized, otherwise, false */ public boolean canWaterOrFertilize() { return (this.isPlowed() && this.seeds != null); } /** * Plows the tile if the tile can be plowed */ public void plowTile() { // do not plow if plowing is not allowed if(canPlow() == 0) { this.plowed = true; System.out.println("\n...tile successfully plowed"); } } /** * Waters the tile if the tile can be watered */ public void addWaterTimes() { if(this.canWaterOrFertilize()) { this.waterTimes += 1; System.out.println("\n...success, total Times Watered: " + this.waterTimes); System.out.println(addWaterStatus()); } } /** * Fertilizes the tile if the tile can be fertilized */ public void addFertilizerTimes() { if(this.canWaterOrFertilize()) { this.fertilizerTimes += 1; System.out.println("\n...success, total Times Fertilized: " + this.fertilizerTimes); System.out.println(addFertilizerStatus()); } } /** adds the water status of the tile * @return the string of the water status of the tile */ private String addWaterStatus() { String result = ""; if (this.waterTimes >= seeds.getWaterNeeds()) { if (this.waterTimes == seeds.getWaterNeeds()) result = "...crop water needs reached"; if (this.waterTimes >= seeds.getWaterLimit()) result = "...crop water bonus limit reached"; } else result = "| water needs: " + seeds.getWaterNeeds(); return result; } /** adds the fertilizer status of the tile * @return the string of the fertilizer status of the tile */ private String addFertilizerStatus() { String result = ""; if (this.fertilizerTimes >= seeds.getFertilizerNeeds()) { if (this.fertilizerTimes == seeds.getFertilizerNeeds()) result = "...crop fertilizer needs reached"; if (this.fertilizerTimes >= seeds.getFertilizerLimit()) result = "...crop fertilizer bonus limit reached"; } else result = "| fertilizer needs: " + seeds.getFertilizerNeeds(); return result; } /** * Removes rock from tile */ public void removeRock() { this.rock = false; System.out.println("\n...rock removed from tile"); } /** * Adds a day to the plant growing process */ public void addDay() { this.age += 1; } /** * Computes the amount of products produced by tile * * @return the amount of products the crop produced */ public int computeProductsProduced() { return seeds.computeProductsProduced(); } /** * Compute the amount of times the tile was watered, with respect to the maximum number of times that it can be watered for extra earnings * * @param typeWaterBonus watering limit increase given by the player's farmer type * @return the result */ public int computeWaterTimesCapped(int typeWaterBonus) { return min(this.waterTimes, seeds.getWaterLimit() + typeWaterBonus); } /** * Compute the amount of times the tile was fertilized, with respect to the maximum number of times that it can be fertilized for extra earnings * * @param typeFertilizerBonus fertilizing limit increase given by the player's farmer type * @return the result */ public int computeFertilizerTimesCapped(int typeFertilizerBonus) { return min(this.fertilizerTimes, seeds.getFertilizerLimit() + typeFertilizerBonus); } /** * Sets the seeds to the tile. * * @param seeds the seed to plant */ public void setSeeds(FarmSeeds seeds) { if(this.canPlant()) { this.seeds = seeds; waterTimes = 0; fertilizerTimes = 0; age = 0; System.out.println("\n..." + seeds.getName() +" successfully planted"); } } /** * Checks if the tile has a rock * * @return true if the tile has a rock, otherwise false */ public boolean isRock() { return this.rock; } /** * Checks if the tile is plowed * * @return true if the tile is plowed, otherwise false */ public boolean isPlowed() { return this.plowed; } /** * Checks if the tile has a crop * * @return true if the tile has a crop, otherwise false */ public boolean isPlanted() { return this.seeds != null; } /** * Checks if the tile is withered * * @return a positive number if the tile is withered, otherwise 0 */ public int isWithered() { if(this.seeds != null && this.age > this.seeds.getHarvestTime()) return 1; if(this.seeds != null && this.age == this.seeds.getHarvestTime() && this.getFertilizerTimes() < this.seeds.getFertilizerNeeds()) return 2; if(this.seeds != null && this.age == this.seeds.getHarvestTime() && this.getWaterTimes() < this.seeds.getWaterNeeds()) return 3; return 0; } /** * Gets the seed currently planted in the tile * * @return the seed */ public FarmSeeds getSeeds() { return this.seeds; } /** * Returns the number of times the tile was watered (without any limits) * * @return the number of times the tile was watered */ public int getWaterTimes() { return this.waterTimes; } /** * Returns the number of times the tile was fertilized (without any limits) * * @return the number of times the tile was fertilized */ public int getFertilizerTimes() { return this.fertilizerTimes; } /** * Returns the age of the tile in days * * @return the age of the tile */ public int getAge() { return this.age; } /** gets the state of the tile * @return the TileState of the tile */ public TileState getTileState() { String seedName = ""; if(seeds != null) seedName = seeds.getName(); int state = TileState.ROCK; if(!isRock()) state = TileState.UNPLOWED; if(isPlowed()) state = TileState.PLOWED; if(seeds != null) state = TileState.PLANTED; if(seeds != null && age == seeds.getHarvestTime()) state = TileState.READY; if(isWithered() != 0) state = TileState.WITHERED; return new TileState(seedName, state); } }
ZyWick/CCPROG3-MCO
Tile.java
2,397
/** adds the fertilizer status of the tile * @return the string of the fertilizer status of the tile */
block_comment
en
false
2,239
25
2,397
29
2,648
27
2,397
29
2,980
31
false
false
false
false
false
true
33437_4
package singlejartest; import java.util.Set; import com.dukascopy.api.*; import java.util.HashSet; public class SWRK implements IStrategy { private IEngine engine; private IHistory history; private IContext context; private IConsole console; private IUserInterface userInterface; private IIndicators indicators; private double amount; private IBar prevBar; private IOrder order; private static final int PREVIOUS = 1; private static final int LAST = 0; @Configurable(value="Instrument value") public Instrument currencyInstrument = Instrument.EURUSD; @Configurable("Amount") public double startingAmount = 5; @Configurable(value="Period value") public Period currencyPeriod = Period.FIFTEEN_MINS;; @Configurable(value="Offer Side value", obligatory=true) public OfferSide currencyOfferSide = OfferSide.BID; @Configurable("SMA time period") public int maTimePeriod = 70; @Configurable("RSI Time Priod") public int rsiTimePeriod = 3; public void onStart(IContext context) throws JFException { this.engine = context.getEngine(); this.console = context.getConsole(); this.history = context.getHistory(); this.context = context; this.indicators = context.getIndicators(); this.userInterface = context.getUserInterface(); //subscribe to your choice of instrument: Set<Instrument> instruments = new HashSet<Instrument>(); instruments.add(currencyInstrument); context.setSubscribedInstruments(instruments, true); } public void onAccount(IAccount account) throws JFException { } // messages related with orders from IMessages are print to strategy's output public void onMessage(IMessage message) throws JFException { if(message.getOrder() != null) printToConsole("order: " + message.getOrder().getLabel() + " || message content: " + message.getContent()); } public void onStop() throws JFException { } public void onTick(Instrument instrument, ITick tick) throws JFException { } // implement our trading logic here. public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException { if (!instrument.equals(currencyInstrument) || !period.equals(currencyPeriod)) { return; } IEngine.OrderCommand myOrderCommand = null; int candleAfter = 0, candleBefore = 2; // get SMA values of the last two completed bars prevBar = (currencyOfferSide == OfferSide.BID ? bidBar : askBar); long currBarTime = prevBar.getTime(); double sma[] = indicators.sma(instrument, period, currencyOfferSide, IIndicators.AppliedPrice.CLOSE, maTimePeriod, Filter.NO_FILTER, candleBefore, currBarTime, candleAfter); double rsi3 = indicators.rsi(instrument, period, currencyOfferSide, IIndicators.AppliedPrice.CLOSE, rsiTimePeriod, 1); printToConsole(String.format("Bar SMA Values: Second-to-last = %.5f; Last Completed = %.5f", sma[LAST], sma[PREVIOUS])); if (sma[PREVIOUS] > sma[LAST] && rsi3 <15) { printToConsole("SMA in up-trend and RSI below 15"); myOrderCommand = IEngine.OrderCommand.BUY; } else if (sma[PREVIOUS] < sma[LAST] && rsi3 > 85){ printToConsole("SMA in down-trend and RSI above 85"); myOrderCommand = IEngine.OrderCommand.SELL; } else { return; } // check the orders and decide to close the order if exist or submit new order if not order = engine.getOrder("MyOrder"); if(order != null && engine.getOrders().contains(order) && order.getOrderCommand() != myOrderCommand){ order.close(); order.waitForUpdate(IOrder.State.CLOSED); console.getOut().println("Order " + order.getLabel() + " is closed"); } if (order == null || !engine.getOrders().contains(order)) { engine.submitOrder("MyOrder", instrument, myOrderCommand, startingAmount); } } private void printToConsole(String toPrint){ console.getOut().println(toPrint); } }
aboongm/jforex-strategies
SWRK.java
1,062
// check the orders and decide to close the order if exist or submit new order if not
line_comment
en
false
999
18
1,062
18
1,142
18
1,062
18
1,301
18
false
false
false
false
false
true
34255_1
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; /** * Shop class represents the graphical user interface for the in-game shop where players can purchase weapons. * Extends View class and implements ActionListener interface. * * Inherits from the {@link View} class. * @author Marcus Apetreor, Vincent Vuelva */ public class Shop extends View implements ActionListener { private Player player; private JTabbedPane tabbedPane; private HashMap<String, JButton> purchaseButtons; private ArrayList<Weapons> shopInventory; private Controller controller; private JLabel runeCountLabel; /** * Constructs a new Shop object. * * @param player The player object representing the player in the game. * @param shopInventory The list of weapons available in the shop. * @param controller The controller object used to control the flow of the game. */ public Shop(Player player, ArrayList<Weapons> shopInventory, Controller controller) { super("Shop"); this.controller = controller; this.player = player; this.shopInventory = shopInventory; this.purchaseButtons = new HashMap<>(); setLocationRelativeTo(null); initComponents(); runeCountLabel = new JLabel("Rune Count: " + player.getRuneCount()); runeCountLabel.setHorizontalAlignment(JLabel.RIGHT); JPanel runeCountPanel = new JPanel(new BorderLayout()); runeCountPanel.add(runeCountLabel, BorderLayout.EAST); add(runeCountPanel, BorderLayout.NORTH); JButton exitButton = new JButton("Exit"); exitButton.addActionListener(e -> { controller.gameLobby(); dispose(); }); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(exitButton); add(buttonPanel, BorderLayout.SOUTH); setVisible(true); } /** * Initializes the components of the shop interface. */ private void initComponents() { tabbedPane = new JTabbedPane(); shopInventory.stream() .map(Weapons::getType) .distinct() .sorted() .forEach(category -> tabbedPane.addTab(category, createWeaponPanel(category))); add(tabbedPane); } /** * Creates a panel containing the weapons of a specific category. * * @param category The category of weapons. * @return JPanel representing the weapon panel. */ private JPanel createWeaponPanel(String category) { JPanel panel = new JPanel(); panel.setLayout(new GridLayout(0, 4, 10, 10)); // 4 items per row, as per the images shopInventory.stream() .filter(weapon -> weapon.getType().equals(category)) .forEach(weapon -> panel.add(createWeaponCard(weapon))); return panel; } /** * Creates a card for a specific weapon. * * @param weapon The weapon for which the card is created. * @return Component representing the weapon card. */ private Component createWeaponCard(Weapons weapon) { JPanel card = new JPanel(); card.setLayout(new BoxLayout(card, BoxLayout.PAGE_AXIS)); card.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JLabel nameLabel = new JLabel(weapon.getName()); nameLabel.setAlignmentX(Component.CENTER_ALIGNMENT); JLabel imageLabel = new JLabel(new ImageIcon(weapon.getImagePath())); imageLabel.setAlignmentX(Component.CENTER_ALIGNMENT); JLabel statsLabel = new JLabel(weapon.getStats().printStats()); statsLabel.setAlignmentX(Component.CENTER_ALIGNMENT); JButton buyButton = new JButton("Buy"); buyButton.setActionCommand(weapon.getName()); buyButton.addActionListener(this); purchaseButtons.put(weapon.getName(), buyButton); card.add(imageLabel); card.add(nameLabel); card.add(statsLabel); card.add(buyButton); buyButton.setEnabled(player.getRuneCount() >= weapon.getPrice()); return card; } @Override public void actionPerformed(ActionEvent e) { String weaponName = e.getActionCommand(); int weaponIndex = getWeaponIndex(weaponName); if (weaponIndex != -1) { controller.buyWeapon(weaponIndex); controller.gameLobby(); dispose(); } else { JOptionPane.showMessageDialog(this, "Weapon " + weaponName + " not found."); } } /** * Retrieves the index of a weapon in the shop inventory based on its name. * * @param weaponName The name of the weapon. * @return The index of the weapon in the shop inventory, or -1 if not found. */ private int getWeaponIndex(String weaponName) { for (int i = 0; i < shopInventory.size(); i++) { if (shopInventory.get(i).getName().equals(weaponName)) { return i; } } return -1; } }
Marcus-Apetreor/MCO1-PROG3-GROUP1
Shop.java
1,171
/** * Constructs a new Shop object. * * @param player The player object representing the player in the game. * @param shopInventory The list of weapons available in the shop. * @param controller The controller object used to control the flow of the game. */
block_comment
en
false
1,026
62
1,171
63
1,256
68
1,171
63
1,461
72
false
false
false
false
false
true
35123_5
import info.gridworld.actor.Actor; import info.gridworld.grid.Location; import info.gridworld.grid.Grid; public class Ant extends Actor implements Comparable<Ant> { private static final int PATH_LENGTH = 32; private static final double MUTATION_RATE = 0.05; private String path; private AntColony colony; public Ant(AntColony c) { colony = c; path = randomPath(); } // define an ordering such that the Ant whose path get it closest // to the food is greatest public int compareTo(Ant other) { return other.distanceFromFood() - distanceFromFood(); } // the number of steps it will take us to get to food from the end // of our path. imagine that we can smell it or something public int distanceFromFood() { Grid g = colony.getGrid(); // this casting thing is ugly but i don't see a way around it // unless we put getDistanceToFood in this class which seems // wrong. TBD: move the method here anyway. if(!(g instanceof GeneticGrid)) return Integer.MAX_VALUE; GeneticGrid gr = (GeneticGrid)g; Location end = followPathFrom(colony.getLocation()); if(end == null) return Integer.MAX_VALUE; if(!gr.isValid(end)) return Integer.MAX_VALUE; return gr.getDistanceToFood(end); } public void setPath(String newPath) { path = newPath; } public String getPathWithMutations() { String mutatedPath = ""; if(path.length() < PATH_LENGTH && Math.random() < MUTATION_RATE) path += (int)(Math.random()*4); for(int i=0; i<path.length(); i++) { String c = path.substring(i,i+1); if(Math.random() < MUTATION_RATE) { mutatedPath += (int)(Math.random()*4); // a rare mutation causes shorter paths if(Math.random() < MUTATION_RATE) break; } else { mutatedPath += c; } } return mutatedPath; } public String randomPath() { String randPath = ""; for(int i=0; i<PATH_LENGTH; i++) { int r = (int)(Math.random()*4); randPath += r; } return randPath; } public Location followPathFrom(Location start) { Grid gr = colony.getGrid(); Location end = new Location(start.getRow(), start.getCol()); for(int i=0; i<path.length(); i++) { int p = Integer.parseInt(path.substring(i,i+1)); end = end.getAdjacentLocation(p * 90); if(!gr.isValid(end)) { System.out.println("invalid path because " + end); return null; } } return end; } public String toString() { return "ANT (path "+path+")"; } }
benchun/GeneticWorld
Ant.java
768
// unless we put getDistanceToFood in this class which seems
line_comment
en
false
637
13
768
13
817
13
768
13
885
14
false
false
false
false
false
true
35422_12
import java.util.Scanner; import java.math.BigInteger; import java.util.ArrayList; // Chinese Remainder Theorem public class CRT { static BigInteger x = new BigInteger("0"); static BigInteger y = new BigInteger("0"); // iterative implementation of Extended Euclidean Algorithm // calculate b_i such that b_i*p + q*c = gcd(r, q) <=> p*b_i == 1%q public static BigInteger extended_euclidean_algortihm(BigInteger p, BigInteger q){ BigInteger s = new BigInteger("0"); // quotient during algorithm BigInteger s_old = new BigInteger("1"); // Bézout coefficient BigInteger t = new BigInteger("1"); // quotient during algorithm BigInteger t_old = new BigInteger("0"); // Bézout coefficient BigInteger r = q; BigInteger r_old = p; // greatest common divisor BigInteger quotient; BigInteger tmp; while (r.compareTo(BigInteger.valueOf(0)) != 0){ // do while r != 0 quotient = r_old.divide(r); tmp = r; // temporarily store to update r, r_old simultaneously r = r_old.subtract(quotient.multiply(r)); r_old = tmp; tmp = s; s = s_old.subtract(quotient.multiply(s)); s_old = tmp; tmp = t; t = t_old.subtract(quotient.multiply(t)); t_old = tmp; } x = s_old; // x*p + y*q == gcd(p,q) ; this means x will be our b_i y = t_old; return x; } public static BigInteger chinese_remainder_theorem(ArrayList<BigInteger> A, ArrayList<BigInteger> Q, int k) { BigInteger p, tmp; BigInteger prod = new BigInteger("1"); // stores product of all moduli BigInteger sum = new BigInteger("0"); // sum x of CRT, which is also the solution after x % prod for (int i = 0; i < k; i++) prod = prod.multiply(Q.get(i)); // multiply all moduli together for (int i = 0; i < k; i++) { p = prod.divide(Q.get(i)); // divide by current modulus to get product excluding said modulus tmp = extended_euclidean_algortihm(p, Q.get(i)); // calculate mod_inv b_i such that b_i*p == 1 % Q.get(i) sum = sum.add(A.get(i).multiply(tmp).multiply(p)); // sum up all products of integer a, product p, modulo inverse of p and Q.get(i) } return sum.mod(prod); // mod with product of all moduli to get smallest/unique integer } public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int k = 0; ArrayList<BigInteger> A; // array for integers a_i ArrayList<BigInteger> Q; // array for pairwise coprime moduli q_i //solve for every line separately while (stdin.hasNextLine()) { // initialisation A = new ArrayList<BigInteger>(); Q = new ArrayList<BigInteger>(); //read past line and split based on ' ' character String[] input = stdin.nextLine().split(" "); // first number is amount of each q_i and a_i k = Integer.parseInt(input[0]); // read in moduli and integers for(int i=1; i<=k; i++) { Q.add(new BigInteger(input[(i)])); // first k numbers are moduli q_i A.add(new BigInteger(input[(i+k)])); // second k numbers are integers a_i } // perform CRT and output unique integer System.out.println(chinese_remainder_theorem(A, Q, k).toString()); } } }
atwing/chinese-remainder-theorem
CRT.java
961
// sum x of CRT, which is also the solution after x % prod
line_comment
en
false
853
15
961
16
995
15
961
16
1,148
16
false
false
false
false
false
true
36623_1
import java.time.Duration; import java.time.Instant; import java.util.HashMap; import java.util.LinkedList; /** * Breadth-First Search. * Meets (a) & (b) requirements. */ class BFS { private static final String fileName = "BFS.txt"; private final Graph graph; // Hashmap of current node and its previous node private final HashMap<Integer, Integer> previousNodes; BFS(Graph graph) { previousNodes = new HashMap<>(graph.getAdjacencyList().size() + 1, 1); this.graph = graph; } /** * Runs breadth-first search. */ void execute() { Instant start = Instant.now(); int counter = 0; LinkedList<Integer> queue = new LinkedList<>(); for (int hospital : graph.getHospitals()) { counter++; // Update Hashmap of hospitals to have previous node as current node previousNodes.put(hospital, hospital); // Add hospitals to the queue queue.add(hospital); } // Start using BFS from queue while (queue.size() != 0) { int currentNode = queue.poll(); for (int node : graph.getAdjacencyList().get(currentNode)) { // If not visited, add nodes to queue and update previous nodes Hashmap if (!previousNodes.containsKey(node)) { counter++; previousNodes.put(node, currentNode); queue.add(node); } } } Instant end = Instant.now(); Duration timeTaken = Duration.between(start, end); System.out.println("Number of iterations for BFS: " + counter); System.out.println("Time taken to run BFS: " + timeTaken.toNanos() + "ns (" + timeTaken.toSeconds() + "s)"); } /** * Returns previous node calculated. * * @return Hashmap of node and its previous node. */ HashMap<Integer, Integer> getPreviousNodes() { return previousNodes; } /** * Returns file name to write results to. * * @return File name of results. */ String getFileName() { return fileName; } }
TanJunHong/CZ2001-Project-2
BFS.java
516
// Hashmap of current node and its previous node
line_comment
en
false
458
10
516
10
550
10
516
10
613
10
false
false
false
false
false
true
36685_0
//code to return the integer number of words in the input string //note. in input every new word is concatenated at the end of previous word and started with the uppercase //eg. saveChangesInTheEditor 5 words import java.util.Scanner; public class Case { public static void main(String args[]) { int count=1;//intialize count to 1 Scanner sc=new Scanner(System.in); String line=sc.nextLine();//take input of the string and store it in line char[] ch=new char[line.length()];//declare a char array of length of string for(int i=0;i<line.length();i++){ ch[i]=line.charAt(i);//convert input string into char array } for(int i=0;i<line.length();i++){ if (ch[i] >= 'A' && ch[i] <= 'Z') {//check when there is a uppercase letter and count++ count++; } } System.out.println(count); } }
theabhishek07/JAVA-PROGRAM
case.java
240
//code to return the integer number of words in the input string
line_comment
en
false
216
13
240
13
258
13
240
13
271
13
false
false
false
false
false
true
36991_3
package com.deco2800.iguanachase; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; /** * DesktopLauncher * Launches the MOOS game engine in LibGDX * @Author Tim Hadwen */ public class GameLauncher { public static void whereDidTheCodesGo() { String lol = "haha"; String lol2 = "haha haha"; } how play game /** * Private constructor to hide the implicit constructor */ private GameLauncher () { //Private constructor to hide the implicit one. } /** * Main function for the game * @param arg Command line arguments (we wont use these) */ public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); LwjglApplication app; config.width = 1280; config.height = 720; salamanders quokka config.title = "DECO2800 2017: Iguana Chase"; app = new LwjglApplication(new IguanaChase(), config); } } hachiroku hello my love
bitnimble/BadMerge
Codes.java
306
/** * Main function for the game * @param arg Command line arguments (we wont use these) */
block_comment
en
false
265
25
306
25
300
27
306
25
362
27
false
false
false
false
false
true
40248_1
import java.util.*; import java.io.*; /** * A Class that has a lot of uses that i use * * @author John Elizarraras * @version 0.12 */ public class Solver { private double t; private double d; private double xVelo; private double yVelo; private double combinedVelocity; private double realAngle; private double maxHeight; private Point firstPoint; private Point secondPoint; private Point maxHeightPoint; private Point fourthPoint; private Point fifthPoint; private double aX; private double bX; private double cX; private double oX; private double tX; private double ranNum; private String response; private String s; private int wordCount; private int happy; private double x; private double y; private String reply; /** @return returns new formulaSolver */ public Solver Solver() { System.out.println ("What do you need help with? (Type !commands if you want a list of commands you can solve for)"); Scanner kbReader = new Scanner(System.in); response = kbReader.nextLine(); if(response.equalsIgnoreCase("!commands") || response.equalsIgnoreCase("!help")) { System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); System.out.println("HINT - CAPITALIZATION DOESN'T MATTER."); System.out.println("!commands or !help - gets commands"); System.out.println("!polysolv - solves a polynomial"); System.out.println("!timedistancepara - solves for Vectors, Max Height and other info of a object thrown in 2-D with no interference"); System.out.println("!end - ends the program"); System.out.println("!reset - resets the terminal"); System.out.println("!classgen - picks a random class for hearthstone"); System.out.println("!code - link to a gist of the code"); System.out.println("!trigCalc - calculates all of the main trig functions"); System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); } else if(response.equalsIgnoreCase("!timedistancepara")) { System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); System.out.println("What is the time it took for the ball to hit the ground?"); t = kbReader.nextDouble(); System.out.println("What distance did the ball travel"); d = kbReader.nextDouble(); System.out.println("Thank You"); xVelo = d / t; System.out.println("The X Velocity Was " + xVelo + "m/s"); yVelo = 0 - ((-9.8 * t) / 2); System.out.println("The Y Velocity Was " + yVelo + "m/s"); combinedVelocity = Math.sqrt( Math.pow( yVelo, 2 ) + Math.pow ( xVelo , 2 ) ); System.out.println("The Combined Velocity Was " + combinedVelocity + "m/s"); realAngle = Math.toDegrees(Math.atan( yVelo / xVelo )); System.out.println("The Real Angle Was " + realAngle + " Degrees"); maxHeight = (yVelo*(t/2) + (-4.9 * Math.pow(t/2,2))); System.out.println("The Maximum Height Was " + maxHeight + "m"); System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); System.out.println("Points Are In The Format Of (Time, Distance)"); System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); firstPoint = new Point(0,0); System.out.println("The First Point To Graph Is " + firstPoint); secondPoint = new Point(t/4 , yVelo * (t/4) + Math.pow(t*.25,2)*-4.9); System.out.println("The Second Point To Graph Is " + secondPoint); maxHeightPoint = new Point(t/2 , maxHeight); System.out.println("The Third Point To Graph Is (Which Is Also The Max Height) " + maxHeightPoint); fourthPoint = new Point(t * .75 , yVelo * (t * .75) + (Math.pow(t*.75,2)*-4.9)); System.out.println("The Fourth Point To Graph Is " + fourthPoint); fifthPoint = new Point(t , 0); System.out.println("The Fifth Point To Graph Is " + fifthPoint); System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); } else if(response.equalsIgnoreCase("!polysolv")) { System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); System.out.println("What is A?(Ax^2 + Bx + C)?"); aX = kbReader.nextDouble(); System.out.println("What is B?"); bX = kbReader.nextDouble(); System.out.println("What is C?"); cX = kbReader.nextDouble(); oX = ((-bX + Math.sqrt(Math.pow(bX,2)-(4*aX*cX)))/(2*aX)); tX = ((-bX - Math.sqrt(Math.pow(bX,2)-(4*aX*cX)))/(2*aX)); System.out.println("X can equal " + oX + " or " + tX +"."); System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); } else if(response.equalsIgnoreCase("!end") || response.equalsIgnoreCase("end") || response.equalsIgnoreCase("!close") || response.equalsIgnoreCase("close")) { System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); System.out.println("Ending Program"); System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); System.exit(0); } else if (response.equalsIgnoreCase("!reset")) { final String ANSI_CLS = "\u001b[2J"; final String ANSI_HOME = "\u001b[H"; System.out.print(ANSI_CLS + ANSI_HOME); System.out.flush(); } else if (response.equalsIgnoreCase("!classgen")) { Random rand = new Random(); ranNum = rand.nextInt(9) + 0; System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); if(ranNum == 0) { System.out.println("Pick Rogue"); } else if(ranNum == 1) { System.out.println("Pick Shaman") ; } else if(ranNum == 2) { System.out.println("Pick Druid") ; } else if(ranNum == 3) { System.out.println("Pick Mage") ; } else if(ranNum == 4) { System.out.println("Pick Warrior") ; } else if(ranNum == 5) { System.out.println("Pick Warlock") ; } else if(ranNum == 6) { System.out.println("Pick Priest") ; } else if(ranNum == 7) { System.out.println("Pick Paladin") ; } else if(ranNum == 8) { System.out.println("Pick Hunter"); } else { System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); } System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); } else if(response.equalsIgnoreCase("!code")) { System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); System.out.println("view code at https://gist.github.com/iblacksand/2a64cf9a10bdc527483c"); System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); } else if(response.equalsIgnoreCase("!trigCalc")) { this.x = 0; this.y = 0; System.out.println("What do you want to solve for(Sin,Cos,Tan,aSin, aTan or aCos)"); response = kbReader.nextLine(); if(response.equalsIgnoreCase("!sin") || response.equalsIgnoreCase("sin")) { System.out.println("What is your angle?"); x = kbReader.nextDouble(); System.out.println(Math.sin(x)); } else if(response.equalsIgnoreCase("!tan") || response.equalsIgnoreCase("tan")) { System.out.println("What is your angle"); x = kbReader.nextDouble(); System.out.println(Math.tan(x)); } else if(response.equalsIgnoreCase("!cos") || response.equalsIgnoreCase("cos")) { System.out.println("What is your angle?"); x = kbReader.nextDouble(); System.out.println(Math.cos(x)); } else if(response.equalsIgnoreCase("!aTan") || response.equalsIgnoreCase("aTan")) { System.out.println("What is your opposite?"); x = kbReader.nextDouble(); System.out.println("What is your adjacent?"); y = kbReader.nextDouble(); System.out.println(Math.toDegrees(Math.atan(x/y))); } else if(response.equalsIgnoreCase("!asin") || response.equalsIgnoreCase("asin?")) { System.out.println("What is your opposite?"); x = kbReader.nextDouble(); System.out.println("What is your hypotenuse?"); y = kbReader.nextDouble(); System.out.println(Math.toDegrees(Math.asin(x/y))); } else if(response.equalsIgnoreCase("!acos") || response.equalsIgnoreCase("acos")) { System.out.println("What is your adjacent?"); x = kbReader.nextDouble(); System.out.println("What is your hypotenuse"); y = kbReader.nextDouble(); System.out.println(Math.toDegrees(Math.acos(x/y))); } } else { System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); System.out.println("ERROR NOT A COMMAND"); System.out.println("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------"); } return Solver(); } }
iblacksand/formula
Solver.java
2,364
/** @return returns new formulaSolver */
block_comment
en
false
2,024
8
2,364
10
2,675
10
2,364
10
2,919
11
false
false
false
false
false
true
40438_0
/** * @file Computer.java * @author Zongbo Xu * @date 5 December 2015 * * A class for computer players. */ package game; import java.util.Random; public class Computer extends Player implements Runnable { private boolean m_aiToggled = false; private Board m_board; private GameController m_gameController; private final int SLEEP_TIME = 500; private Point[] m_currentPoint; public boolean toggleAi() { m_aiToggled = !m_aiToggled; return m_aiToggled; } public Computer(String name, Board board, GameController gc) { super(name); m_board = board; m_gameController = gc; } public boolean isValidPoint(Board board,int x, int y) { boolean flag = false; m_currentPoint[0].setPoint(x, y); for (int i = 0; i < board.getm_validPoints().length; i++) { if (board.getm_validPoints()[i] == m_currentPoint[0]) { break; } else if (board.getm_validPoints()[i] != m_currentPoint[0]) { flag = true; break; } } return flag; } public void run() { while (true) { while (m_aiToggled) { boolean foundValidMove = false; do { Random rnd = new Random(); int row = rnd.nextInt(m_board.getm_Board().size()); int column = rnd.nextInt(m_board.getm_Board().get(row).size()); Tile randomTile = m_board.getm_Board().get(row).get(column); if (!randomTile.isMine() && randomTile.isHidden()) { foundValidMove = true; m_board.revealTile(row, column); m_gameController.repaintAll(); System.out.println("Revealed tile: (" + row + "," + column + ")"); } else { System.out.println("Mine or already revealed tile found. Looping."); } } while (!foundValidMove); try { Thread.sleep(SLEEP_TIME); //Wait 3 seconds } catch (InterruptedException e) { System.err.println("Failed to put thread to sleep."); } } } } }
VLCharvis/Scott-Cheg
Computer.java
618
/** * @file Computer.java * @author Zongbo Xu * @date 5 December 2015 * * A class for computer players. */
block_comment
en
false
502
36
618
41
621
39
618
41
782
41
false
false
false
false
false
true
44534_6
import java.util.HashMap; public class VFS implements Device{ private DeviceAndID[] storedDevices; private HashMap<String, Device> deviceLookup = new HashMap<>(); //hashmap that stores an instance of every type of Device public VFS(){ storedDevices = new DeviceAndID[10]; deviceLookup.put("random", new RandomDevice()); //store the RandomDevice inside the deviceTypes hashmap deviceLookup.put("file", new FakeFileSystem()); //store the FakeFileSystem inside the deviceTypes hashmap } @Override public int Open(String deviceString){ int emptyIndex = -1; for(int i = 0; i < storedDevices.length; i++){ //look for an empty index in the VFS array if(storedDevices[i] == null){ emptyIndex = i; break; } } if(emptyIndex == -1){ //if there is no empty index in the VFS array, return -1 return -1; } int indexOfParse = deviceString.indexOf(" "); //parse the string passed in String deviceType = deviceString.substring(0, indexOfParse); //the first part of the string is the device type String deviceInput = deviceString.substring(indexOfParse + 1); //the second part of the string is the device-related input int deviceID = deviceLookup.get(deviceType).Open(deviceInput); //get the device according to the device type, call Open() if(deviceID == -1){ //if there is no empty index in the device array, return -1 return -1; } //create a new entry in the VFS array at an empty index, store the device type and device id returned from Open() inside the VFS entry DeviceAndID vfsEntry = new DeviceAndID(deviceLookup.get(deviceType), deviceID); storedDevices[emptyIndex] = vfsEntry; System.out.println("The empty index found in VFS array is: "+emptyIndex+", ID "+deviceID+" was placed inside it"); return emptyIndex; //return the index of the newly added VFS entry } @Override public void Close(int id){ storedDevices[id].getDevice().Close(storedDevices[id].getID()); //get the device at the ID that was passed in, call Close() on that device storedDevices[id] = null; //set the Closed() device index to null } @Override public byte[] Read(int id, int size) { return storedDevices[id].getDevice().Read(storedDevices[id].getID(), size); //get the device at the ID that was passed in, call Read() on that device } @Override public void Seek(int id, int to) { storedDevices[id].getDevice().Seek(storedDevices[id].getID(), to); //get the device at the ID that was passed in, call Seek() on that device } @Override public int Write(int id, byte[] data) { return storedDevices[id].getDevice().Write(storedDevices[id].getID(), data); //get the device at the ID that was passed in, call Write() on that device } public Device getDeviceLookup(String deviceType) { return deviceLookup.get(deviceType); } }
nikitromanov/osJava
VFS.java
731
//the first part of the string is the device type
line_comment
en
false
709
12
731
12
819
12
731
12
869
12
false
false
false
false
false
true
45371_37
package first21Days; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.interactions.Actions; public class Nykka { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); // disable the notifications ChromeOptions options = new ChromeOptions(); options.addArguments("--disable-notifications"); // Launching Chrome Browser ChromeDriver driver = new ChromeDriver(options); // To Load the url https://www.nykaa.com/ driver.get("https://www.nykaa.com/"); // To maximize the browser driver.manage().window().maximize(); // implicitly wait driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); // Mouseover on Brands and Mouseover on Popular WebElement eleBrand = driver.findElementByXPath("//a[text()='brands']"); Actions builder = new Actions(driver); builder.moveToElement(eleBrand).perform(); WebElement elePopular = driver.findElementByXPath("//a[text()='Popular']"); Actions builder1 = new Actions(driver); builder1.moveToElement(elePopular).perform(); // Click L'Oreal Paris driver.findElementByXPath("(//li[@class='brand-logo menu-links']//img)[5]").click(); Thread.sleep(3000); // Go to the newly opened window and check the title contains L'Oreal Paris Set<String> allWindows = driver.getWindowHandles(); List<String> allhandles = new ArrayList<String>(allWindows); driver.switchTo().window(allhandles.get(1)); String titleofcurrrentpage = driver.getTitle(); System.out.println("The Title of the page is " + titleofcurrrentpage); if (titleofcurrrentpage.contains("L'Oreal Paris")) { System.out.println("The Title of the page contains L'Oreal paris"); } else { System.out.println("The Title of the page doesn't contain L'Oreal paris"); } // Click sort By and select customer top rated driver.findElementByXPath("//i[@class='fa fa-angle-down']").click(); driver.findElementByXPath("//input[@id='3']/following-sibling::div[1]").click(); Thread.sleep(1000); // Click Category and click Shampoo driver.findElementByXPath("(//div[@class='pull-right filter-options-toggle'])[1]").click(); driver.findElementByXPath("(//label[@for='chk_Shampoo_undefined'])[1]").click(); // check whether the Filter is applied with Shampoo String filterOption = driver.findElementByXPath("//ul[@class='pull-left applied-filter-lists']").getText(); // System.out.println(filterOption); if (filterOption.contains("Shampoo")) { System.out.println("The filter is applied with Shampoo"); } else { System.out.println("The filter is not applied with Shampoo"); } //Click on L'Oreal Paris Colour Protect Shampoo driver.findElementByXPath("//span[text()=\"L'Oreal Paris Colour Protect Shampoo\"]").click(); //GO to the new window and select size as 175ml Set<String> allWindows1 = driver.getWindowHandles(); List<String> allhandles1 = new ArrayList<String>(allWindows1); driver.switchTo().window(allhandles1.get(2)); driver.findElementByXPath("//span[text()='175ml']").click(); //Print the MRP of the product String mrp = driver.findElementByXPath("(//span[@class='post-card__content-price-offer'])[1]").getText(); System.out.println(" The MRP of the shampoo is " + mrp); // Click on ADD to BAG driver.findElementByXPath("(//button[@class='combo-add-to-btn prdt-des-btn js--toggle-sbag nk-btn nk-btn-rnd atc-simple m-content__product-list__cart-btn '])[1]").click(); Thread.sleep(2000); //Go to Shopping Bag driver.findElementByXPath("//div[@class='AddBagIcon']").click(); //Print the Grand Total amount String grandTotal = driver.findElementByXPath("//div[@class='value medium-strong']").getText(); System.out.println("The grand total is " + grandTotal); //Click Proceed driver.findElementByXPath("//button[@class='btn full fill no-radius proceed ']").click(); Thread.sleep(3000); //Click on Continue as Guest driver.findElementByXPath("//button[text()='CONTINUE AS GUEST']").click(); //Print the warning message (delay in shipment) String delayMsg = driver.findElementByXPath("//div[@class='message']").getText(); System.out.println("The message displayed is " + delayMsg); // Close all windows driver.quit(); } }
Pavithra72/selenium90days
Nykka.java
1,324
//Print the warning message (delay in shipment)
line_comment
en
false
1,100
11
1,324
12
1,328
10
1,324
12
1,601
11
false
false
false
false
false
true
49415_23
package day7; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; public class Honda { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); ChromeDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.honda2wheelersindia.com/"); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); WebDriverWait wait = new WebDriverWait(driver,30); if(driver.findElementByXPath("//button[@class='close']").isDisplayed()) { wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='close']"))); driver.findElementByXPath("//button[@class='close']").click(); } Thread.sleep(5000); wait.until(ExpectedConditions.elementToBeClickable(By.id("link_Scooter"))); driver.findElementById("link_Scooter").click(); driver.findElementByXPath("//img[contains(@src,'dio')]").click(); //3) Click on Specifications and mouseover on ENGINE driver.findElementByLinkText("Specifications").click(); WebElement dioengine = driver.findElementByLinkText("ENGINE"); Actions builder = new Actions(driver); builder.moveToElement(dioengine).perform(); //4) Get Displacement value String disp1 = driver.findElementByXPath("//span[text()='Displacement']/following-sibling::span").getText().replaceAll("[A-Za-z]","" ); double diodisp = Double.parseDouble(disp1); //5) Go to Scooters and click Activa 125 driver.findElementById("link_Scooter").click(); driver.findElementByXPath("//img[contains(@src,'activa-125')]").click(); //6) Click on Specifications and mouseover on ENGINE driver.findElementByLinkText("Specifications").click(); WebElement actengine = driver.findElementByLinkText("ENGINE"); builder.moveToElement(actengine).perform(); //7) Get Displacement value String disp2 = driver.findElementByXPath("//span[text()='Displacement']/following-sibling::span").getText().replaceAll("[A-Za-z]", ""); double actdisp = Double.parseDouble(disp2); //8) Compare Displacement of Dio and Activa 125 and print the Scooter name having better Displacement. if(diodisp>actdisp) { System.out.println("Dio has better displacement"); }else { System.out.println("Activa 125 has better displacement"); } //9) Click FAQ from Menu driver.findElementByLinkText("FAQ").click(); //10) Click Activa 125 BS-VI under Browse By Product driver.findElementByLinkText("Activa 125 BS-VI").click(); //11) Click Vehicle Price driver.findElementByXPath("//a[text()=' Vehicle Price']").click(); //12) Make sure Activa 125 BS-VI selected and click submit WebElement model = driver.findElementById("ModelID6"); Select mod = new Select(model); List<WebElement> allsec = mod.getAllSelectedOptions(); for (int i = 0; i < allsec.size(); i++) { if(allsec.get(i).getText().contains("Activa 125")) { System.out.println("Activa 125 BS-VI is selected"); } } driver.findElementByXPath("//button[contains(@onclick,'validateformPriceMaster')]").click(); //13) click the price link String text = driver.findElement(By.xpath("(//table[@id='tblPriceMasterFilters']//td)[2]")).getText(); if(text.contains("Activa 125")) { driver.findElementByXPath("//table[@id='tblPriceMasterFilters']//a").click(); } //14) Go to the new Window and select the state as Tamil Nadu and city as Chennai Set<String> wH = driver.getWindowHandles(); List<String> l = new ArrayList<>(wH); driver.switchTo().window(l.get(1)); WebElement stateid = driver.findElementById("StateID"); WebElement cityid = driver.findElementById("CityID"); Select state = new Select(stateid); state.selectByVisibleText("Tamil Nadu"); Select city = new Select(cityid); city.selectByVisibleText("Chennai"); //15) Click Search driver.findElementByXPath("//button[text()='Search']").click(); //16) Print all the 3 models and their prices List<WebElement> rows = driver.findElementsByXPath("//tbody[@style='background-color:white']//tr"); for(int i = 0; i < rows.size(); i++) { WebElement eachRow = rows.get(i); List<WebElement> cols = eachRow.findElements(By.xpath("//tbody[@style='background-color:white']//tr["+(i+1)+"]//td")); if(cols.size()==3) { for(int j=0 ; j < cols.size()-1;j++) { System.out.print(driver.findElementByXPath("//tbody[@style='background-color:white']//tr["+(i+1)+"]//td["+(j+2)+"]").getText()); System.out.print(" "); } } else { for(int j=0 ; j < cols.size();j++) { System.out.print(driver.findElementByXPath("//tbody[@style='background-color:white']//tr["+(i+1)+"]//td["+(j+1)+"]").getText()); System.out.print("\t"); } } System.out.println(); } driver.quit(); } }
Jagadha/90-days-Workout
Honda.java
1,589
//14) Go to the new Window and select the state as Tamil Nadu and city as Chennai
line_comment
en
false
1,291
22
1,589
27
1,573
22
1,589
27
1,932
26
false
false
false
false
false
true
49979_0
public class MedicalRecords { /**Instance variables - Chronic Disease - String Hypertension - Boolean Previous Diseases - String Hospital - String Doctor - String Admitted - Boolean FineLabtest - array LabTest NeedDoctorAttentionLabtest - array LabTest Instance Methods- getChronicDisease getHypertension getPreviousDisease setChronicDisease setHypertension */ private String chronicDisease; private boolean hyperTension; private String previousDisease; private Hospital hospital; private Doctor doctor; private boolean admitted; private LabTests[] fineLabTest; private LabTests[] needDoctorAttentionTest; private int Room; private String PatName; private int PatAge; public void setPatName(String patName) { PatName = patName; } public void setPatAge(int patAge) { PatAge = patAge; } public String getPatName() { return PatName; } public int getPatAge() { return PatAge; } public int getRoom() { return Room; } public void setRoom(int room) { this.Room = room; } public MedicalRecords(String chronicDisease , boolean hyperTension , String previousDisease){ this.chronicDisease = chronicDisease; this.hyperTension = hyperTension; this.previousDisease = previousDisease; } public String getChronicDisease() { return chronicDisease; } public void setChronicDisease(String chronicDisease) { this.chronicDisease = chronicDisease; } public boolean isHyperTension() { return hyperTension; } public void setHyperTension(boolean hyperTension) { this.hyperTension = hyperTension; } public String getPreviousDisease() { return previousDisease; } public void setPreviousDisease(String previousDisease) { this.previousDisease = previousDisease; } public Hospital getHospital() { return hospital; } public void setHospital(Hospital hospital) { this.hospital = hospital; } public Doctor getDoctor() { return doctor; } public void setDoctor(Doctor doctor) { this.doctor = doctor; } public String isAdmitted() { return admitted?"yes":"no"; } public void setAdmitted(boolean admitted) { this.admitted = admitted; } public boolean isBolAdmitted() { return admitted ? true : false; } public LabTests[] getFineLabTest() { return fineLabTest; } public void setFineLabTest(LabTests[] fineLabTest) { this.fineLabTest = fineLabTest; } public LabTests[] getNeedDoctorAttentionTest() { return needDoctorAttentionTest; } public void setNeedDoctorAttentionTest(LabTests[] needDoctorAttentionTest) { this.needDoctorAttentionTest = needDoctorAttentionTest; } public String toString(){ String str = "Patient name: \n" + PatName + "\n" + "\nPatient age: \n" + PatAge + "\n\n" + "Chronic Disease: \n" + chronicDisease + "\n\n" + "PreviousDisease: \n" + previousDisease + "\n\n" + hospital + "\n" + doctor + "\n" + "\nAdmitted: " + isAdmitted() + "\n"; if (getRoom() != 0) { str += "\nRoom no.: " + getRoom() + "\n"; } str += "\nFineLabtest: \n"; for (int i = 0, k = 0; i < fineLabTest.length; i++) { if (needDoctorAttentionTest[i] != null) { str += fineLabTest[i] + "\n"; k++; } if ((i == fineLabTest.length - 1) && k == 0) { str += "none\n"; } } str += "\nNeedDoctorAttentionLabtest: \n"; for (int i = 0, k = 0; i < needDoctorAttentionTest.length; i++) { if (needDoctorAttentionTest[i] != null) { str += needDoctorAttentionTest[i] + "\n"; k++; } if ((i == needDoctorAttentionTest.length - 1) && k == 0) { str += "none\n"; } } return str; } }
Lohith-Loke/itproject
MedicalRecords.java
1,155
/**Instance variables - Chronic Disease - String Hypertension - Boolean Previous Diseases - String Hospital - String Doctor - String Admitted - Boolean FineLabtest - array LabTest NeedDoctorAttentionLabtest - array LabTest Instance Methods- getChronicDisease getHypertension getPreviousDisease setChronicDisease setHypertension */
block_comment
en
false
1,008
95
1,155
108
1,137
91
1,155
108
1,340
118
false
false
false
false
false
true
50799_2
// Muhammad Naveed // (Largest and Smallest Integers) Write an application that reads five integers // and determines and prints the largest and smallest integers in the group. public class Q_1 { public static void main(String[] args) { int[] numbers = new int[] {3, 9, 1, 0, -5}; int smallest = numbers[0]; int largest = numbers[0]; for (int i = 0; i < numbers.length; i++) { largest = (numbers[i] > largest) ? numbers[i] : largest; smallest = (numbers[i] < smallest) ? numbers[i] : smallest; } System.out.println(largest); System.out.println(smallest); } }
uxlabspk/JavaCodes
Q_1.java
186
// and determines and prints the largest and smallest integers in the group.
line_comment
en
false
167
14
186
14
191
14
186
14
206
15
false
false
false
false
false
true
52797_0
// Program that accepts 2 nos. in the range 1-40 from command line then compares these nos against a single // dimension array of 5 int elements ranging 1-40. Diplay the message "Bingo" if the two input values are found in the // array elements.otherwise "Not Found." public class test1 { public static void main(String args[]){ int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int arr[] = new int[5]; for(int i=0;i<5;i++){ arr[i] = Integer.parseInt(args[i+2]); } int flag=0; for(int i=0;i<5;i++){ if(a==arr[i]){ flag++; } if (b==arr[i]){ flag++; } } if(flag==2){ System.out.println("Bingo!"); } else { System.out.println("Not Found!"); } } }
Tonsoe/JavaPracticeHacktoberfest
bingo.java
243
// Program that accepts 2 nos. in the range 1-40 from command line then compares these nos against a single
line_comment
en
false
213
26
243
27
260
26
243
27
269
27
false
false
false
false
false
true
52803_4
package simpledb; import java.io.Serializable; /** PageId is an interface to a specific page of a specific table. */ public interface PageId { /** Return a representation of this page id object as a collection of integers (used for logging) This class MUST have a constructor that accepts n integer parameters, where n is the number of integers returned in the array from serialize. */ public int[] serialize(); /** @return the unique tableid hashcode with this PageId */ public int getTableId(); /** * @return a hash code for this page, represented by the concatenation of * the table number and the page number (needed if a PageId is used as a * key in a hash table in the BufferPool, for example.) * @see BufferPool */ public int hashCode(); /** * Compares one PageId to another. * * @param o The object to compare against (must be a PageId) * @return true if the objects are equal (e.g., page numbers and table * ids are the same) */ public boolean equals(Object o); public int pageNumber(); }
jpbogle/SimpleDB-implementation
PageId.java
261
/** * Compares one PageId to another. * * @param o The object to compare against (must be a PageId) * @return true if the objects are equal (e.g., page numbers and table * ids are the same) */
block_comment
en
false
254
59
261
59
280
65
261
59
295
65
false
false
false
false
false
true
53603_0
/* Find the Longest common subsequence between two arrays in O(NlogN) Solution: https://codeforces.com/blog/entry/13631?#comment-186010 Only works if the elements of at least one sequence are distinct. Find the longest common subsequence between K arrays. O(N*N*K). Solution: https://codeforces.com/problemset/problem/463/D Only works if the elements of each array are distinct. */
akashbhalotia/My-Coding-Library
DP/LCS.java
121
/* Find the Longest common subsequence between two arrays in O(NlogN) Solution: https://codeforces.com/blog/entry/13631?#comment-186010 Only works if the elements of at least one sequence are distinct. Find the longest common subsequence between K arrays. O(N*N*K). Solution: https://codeforces.com/problemset/problem/463/D Only works if the elements of each array are distinct. */
block_comment
en
false
107
107
121
120
127
126
121
120
132
131
false
false
false
false
false
true
53850_1
/** * * Author: Haoyu Zhang * BU ID: U81614811 * 2021/11/06 * */ // Equipment.java - All things heroes can be equipped with and use are thought as equipment. public abstract class Equipment { protected String name; protected int price; protected int reqLevel; Equipment(String name, int price, int reqLevel) { this.name = name; this.price = price; this.reqLevel = reqLevel; } public String getName() { return name; } public int getReqLevel() { return reqLevel; } public int getPrice() {return price;} }
luciusluo/Legends
src/Equipment.java
171
// Equipment.java - All things heroes can be equipped with and use are thought as equipment.
line_comment
en
false
150
18
171
22
176
19
171
22
197
23
false
false
false
false
false
true
54326_1
// shopping cart for specific fruit shop // import java.util for ArrayList to store store items import java.util.ArrayList; // shoppingCart class made public public class ShoppingCart { // ArrayList called items to store items for the shopping cart ArrayList<String> items; // shopping cart() constructor where items is equal to new arraylist<string>() public ShoppingCart(){ items = new ArrayList<String>(); } // add()add method to array list items use the add function public void add(String item) { items.add(item); } // remove() add to array list items use the remove function public void remove(String item) { items.remove(item); } // getTotalItems made public int returns size of array list when called public int getTotalItems() { return items.size(); } // Boolen doesContain returns item name from array list items public Boolean doesContain(String itemName) { return items.contains(itemName); } // checkout method total is initialized as 0. for loop checks array list items for shop items such // Apple,Orange and Pear. //if value found , a double value is assigned, apples cost 1 euro, orange 60 cent and pear 40 cent. // the total value is returned when called public Double checkout() { double total = 0; for(String item: items){ if(item.equals("Apple")){ total += 1.0; }else if(item.equals("Orange")){ total += 0.6; }else if(item.equals("Pear")){ total += 0.4; } } return total; } // offers method contains calls to getTotalItems and checkout methods in this class ShoppingCart // the first if statement checks if the getTotalItems equals to 3 then the total value is subtracted from getTotalItems and 2.0(euro) //the first if statement checks if the getTotalItems equals to 2 then the total value is subtracted from getTotalItems and 0.5(euro) // total value is return when method is called public double offers(){ this.getTotalItems(); this.checkout(); double total= 0; //double dealA = 1.0; // not used (testing) // double dealB = 0.6; // not used (testing) if(getTotalItems()== 3){ //dealA -1.0; total = getTotalItems()- 2.0; // 1 euro/pound off }else if(getTotalItems()== 2){ //dealA -1.0; total = getTotalItems()- 0.5; // 1 euro/pound off } return total; } //getTestApplication returns app working message when called in the application class in the main method public String getTestApplication() { return "App working!"; } }
conorH22/ShoppingCart
ShoppingCart.java
678
// import java.util for ArrayList to store store items
line_comment
en
false
607
10
678
11
705
11
678
11
773
11
false
false
false
false
false
true
54642_16
import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.awt.event.*; //TO-DO: implement MouseListener public class DrawP extends JPanel implements MouseListener, KeyListener { // Keeps track of objects to draw private ArrayList<Shape> shapes; private ArrayList<Vertex> vertecies; private ArrayList<Line> lines; // Keeps track of current and previous point created private Vertex current; private Vertex previous; // Grid constants can be manipulated to change point positions private final int X_SIZE = 25; private final int Y_SIZE = 25; private final int ARC_SIZE = 25; private final int CENTER_ADJUSTMENT = 12; private Grid grid = new Grid(); // Standard keybaord inputs private final int DELETE_VALUE = 8; private final int SPACE_VALUE = 32; private int vertexCount; private int edgeCount; // Textbox to display vertex and edge count private JLabel text; private final int TEXT_WIDTH = 100; private final int TEXT_HEIGHT = 50; private final int TEXT_POSITION = 50; //X and Y offset private boolean darkMode; // Initializes text Jlabel, ArrayLists and variables public DrawP() { text = new JLabel(); text.setSize(TEXT_HEIGHT, TEXT_WIDTH); text.setLocation(TEXT_POSITION, TEXT_POSITION); text.setVisible(true); text.setForeground(Color.WHITE); add(text); current = null; previous = null; vertexCount = 0; edgeCount = 0; shapes = new ArrayList<>(); vertecies = new ArrayList<>(); lines = new ArrayList<>(); darkMode = true; } // Custom way to paint on JPanel @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.WHITE); for(Shape s : shapes) { if(s instanceof Vertex) { //Draw vertex paintVertex((Vertex)s, g); } else if(s instanceof Line) { //Draw line paintLine((Line)s, g); } } } // Adds a vertex to the panel and draws a line to it from the current vertex // @param Vertex v to be added public void addVertex(Vertex v) { shapes.add(v); vertecies.add(v); vertexCount++; updateCurrent(v); addLine(); repaint(); } // Updates the current and previous verticies // @param Vertex v to set as current vertex public void updateCurrent(Vertex v) { previous = current; current = v; } // Used if a point already exists on the graph so that instead of creating a // new one, an edge is connected to it. // @param Point p to connect the edge to public void connectVertex(Point p) { Vertex newV = new Vertex(grid.roundValue(p.x), grid.roundValue(p.y)); if(newV.equals(current)) { updateCurrent(newV); return; } Line newLine = new Line(newV, current); if(!lines.contains(newLine)) { shapes.add(newLine); lines.add(newLine); edgeCount++; } updateCurrent(newV); repaint(); } // helper method to connect edges to vertecies public void addLine() { if(current.equals(previous) || current == null || previous == null) { return; } Line newLine = new Line(previous, current); if(!lines.contains(newLine)) { shapes.add(newLine); lines.add(newLine); edgeCount++; } } // helper method for painting vertex Graphics on JPanel // @param Vertex v to paint using JPanel Graphics component public void paintVertex(Vertex v, Graphics g) { if(v.equals(current)) { if(darkMode) { g.setColor(Color.RED); } else { g.setColor(Color.BLUE); } } else { if(darkMode) { g.setColor(Color.WHITE); } else { g.setColor(Color.BLACK); } } g.fillRoundRect(v.x - CENTER_ADJUSTMENT, v.y - CENTER_ADJUSTMENT, X_SIZE, Y_SIZE, ARC_SIZE, ARC_SIZE); } // helper method for painting edge Graphics on JPanel // @param Line l to paint using JPanel Graphics component public void paintLine(Line l, Graphics g) { g.drawLine(l.startingPoint.x, l.startingPoint.y, l.endingPoint.x, l.endingPoint.y); } // deletes the most recent edge or graph that was painted using the // "backspace" key. private void deleteRecent() { int i = shapes.size() - 1; Shape s = shapes.get(shapes.size() - 1); if(s instanceof Vertex) { grid.deletePoint((Vertex)s); vertecies.remove((Vertex)s); vertexCount--; } if(s instanceof Line) { lines.remove(s); edgeCount--; } if(vertecies.size() >= 1) { current = vertecies.get(vertecies.size()-1); previous = null; } else if(vertecies.size() >= 2) { current = vertecies.get(vertecies.size()-1); previous = vertecies.get(vertecies.size()-2); } else { current = null; previous = null; } updateText(); shapes.remove(s); repaint(); } // updates the text of vertex and edge count public void updateText() { text.setText("|V| = " + vertexCount + " |E| = " + edgeCount); } // changes the color mode of the JPanel, activated by "space" key public void changeDarkMode() { if(darkMode) { text.setForeground(Color.BLACK); this.setBackground(Color.WHITE); } else { text.setForeground(Color.WHITE); this.setBackground(Color.BLACK); } darkMode = !darkMode; } // Overrides all MouseListener methods @Override public void mouseClicked(MouseEvent e) {}; //nothing happens @Override public void mouseReleased(MouseEvent e) {}; //nothing happens @Override public void mouseEntered(MouseEvent e) {}; //nothing happens @Override public void mouseExited(MouseEvent e) {}; //nothing happens // creates a new line if the vertex is available on the grid, otherwise // connects it to an existing vertex @Override public void mousePressed(MouseEvent e) { Point p = getMousePosition(false); Vertex v = grid.usePoint(p); if(v == null) { connectVertex(p); } else { addVertex(v); } updateText(); } // Overrides all KeyListener methods @Override public void keyTyped(KeyEvent e) {}; //does nothing // Deletes recent Shape if input is "backspace" // Changes color mode if input is "space" @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == DELETE_VALUE && shapes.size() > 0) { deleteRecent(); } if(e.getKeyCode() == SPACE_VALUE) { changeDarkMode(); } } @Override public void keyReleased(KeyEvent e) {}; //does nothing }
MerujSargsyan/GraphGenerator
DrawP.java
1,753
// new one, an edge is connected to it.
line_comment
en
false
1,608
11
1,753
11
1,923
11
1,753
11
2,091
11
false
false
false
false
false
true
59292_0
/* Topic:- Simplified Chess Engine Link:- https://www.hackerrank.com/challenges/simplified-chess-engine/problem?isFullScreen=true Problem:- Chess is a very popular game played by hundreds of millions of people. Nowadays, we have chess engines such as Stockfish and Komodo to help us analyze games. These engines are very powerful pieces of well-developed software that use intelligent ideas and algorithms to analyze positions and sequences of moves, as well as find tactical ideas. Consider the following simplified version of chess: Board: It's played on a board between two players named Black and White. Pieces and Movement: White initially has pieces and Black initially has pieces. There are no Kings and no Pawns on the board. Each player has exactly one Queen, at most two Rooks, and at most two minor pieces (i.e., a Bishop and/or Knight). Each piece's possible moves are the same as in classical chess, and each move made by any player counts as a single move. There is no draw when positions are repeated as there is in classical chess. Objective: The goal of the game is to capture the opponent’s Queen without losing your own. Given and the layout of pieces for games of simplified chess, implement a very basic (in comparison to the real ones) engine for our simplified version of chess with the ability to determine whether or not White can win in moves (regardless of how Black plays) if White always moves first. For each game, print YES on a new line if White can win under the specified conditions; otherwise, print NO. Input Format The first line contains a single integer, , denoting the number of simplified chess games. The subsequent lines define each game in the following format: The first line contains three space-separated integers denoting the respective values of (the number of White pieces), (the number of Black pieces), and (the maximum number of moves we want to know if White can win in). The subsequent lines describe each chesspiece in the format t c r, where is a character denoting the type of piece (where is Queen, is Knight, is Bishop, and is Rook), and and denote the respective column and row on the board where the figure is placed (where and ). These inputs are given as follows: Each of the subsequent lines denotes the type and location of a White piece on the board. Each of the subsequent lines denotes the type and location of a Black piece on the board. Constraints It is guaranteed that the locations of all pieces given as input are distinct. Each player initially has exactly one Queen, at most two Rooks and at most two minor pieces. Output Format For each of the games of simplified chess, print whether or not White can win in moves on a new line. If it's possible, print YES; otherwise, print NO. Solution:- */ import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static int[] queen = { 1, 0, -1, 0, 0, 1, 0, -1, 2, 0, -2, 0, 0, 2, 0, -2, 3, 0, -3, 0, 0, 3, 0, -3, 1, 1, -1, -1, 1, -1, -1, 1, 2, 2, -2, -2, 2, -2, -2, 2, 3, 3, -3, -3, 3, -3, -3, 3 }; public static int[] rook = { 1, 0, -1, 0, 0, 1, 0, -1, 2, 0, -2, 0, 0, 2, 0, -2, 3, 0, -3, 0, 0, 3, 0, -3 }; public static int[] bishop = { 1, 1, -1, -1, 1, -1, -1, 1, 2, 2, -2, -2, 2, -2, -2, 2, 3, 3, -3, -3, 3, -3, -3, 3 }; public static int[] knight = { 1, 2, -1, -2, 2, 1, -2, -1, 1, -2, -1, 2, 2, -1, -2, 1 }; public abstract static class Piece { final boolean white; final int[] moves; final boolean canJump; int x, y; boolean taken; public Piece(int x, int y, boolean white, int[] moves, boolean canJump) { this.white = white; this.x = x; this.y = y; this.moves = moves; this.canJump = canJump; } int count() { return moves.length / 2; } boolean canMove(int number, Piece[][] board) { int dx = moves[2 * number]; int dy = moves[2 * number + 1]; int x = this.x + dx; int y = this.y + dy; if (!(0 <= x && x <= 3 && 0 <= y && y <= 3)) { return false; } Piece taking = board[x][y]; if (taking != null && taking.white == white) { return false; } if (canJump) { return true; } int steps = Math.max(Math.abs(dx), Math.abs(dy)) - 1; int sx = dx == 0 ? 0 : dx > 0 ? 1 : -1; int sy = dy == 0 ? 0 : dy > 0 ? 1 : -1; for (int i = 1; i <= steps; i++) { if (board[this.x + sx * i][this.y + sy * i] != null) { return false; } } return true; } void move(int number, boolean reverse) { number += !reverse ? 0 : number % 2 == 0 ? 1 : -1; this.x += moves[2 * number]; this.y += moves[2 * number + 1]; } @Override public String toString() { return (white ? "white " : "black ") + getClass().getSimpleName(); } } public static class Queen extends Piece { public Queen(int x, int y, boolean white) { super(x, y, white, queen, false); } } public static class Rook extends Piece { public Rook(int x, int y, boolean white) { super(x, y, white, rook, false); } } public static class Bishop extends Piece { public Bishop(int x, int y, boolean white) { super(x, y, white, bishop, false); } } public static class Knight extends Piece { public Knight(int x, int y, boolean white) { super(x, y, white, knight, true); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int games = sc.nextInt(); while (games-- > 0) { int w = sc.nextInt(); int b = sc.nextInt(); int m = sc.nextInt(); Piece board[][] = new Piece[4][4]; List<Piece> white = new ArrayList<>(); List<Piece> black = new ArrayList<>(); for (int j = 0; j < 2; j++) { for (int i = 0; i < (j == 0 ? w : b); i++) { char p = sc.next() .charAt(0); int x = sc.next() .charAt(0) - 'A'; int y = sc.nextInt() - 1; Piece piece = p == 'Q' ? new Queen(x, y, j == 0) : p == 'R' ? new Rook(x, y, j == 0) : p == 'B' ? new Bishop(x, y, j == 0) : new Knight(x, y, j == 0); board[x][y] = piece; (j == 0 ? white : black).add(piece); } } boolean win = move(true, white, black, board, m); System.out.println(win ? "YES" : "NO"); } } public static boolean move(boolean whiteTurn, List<Piece> white, List<Piece> black, Piece[][] board, int m) { if (m <= 0) { return false; } boolean all = !whiteTurn; List<Piece> pieces = whiteTurn ? white : black; for (Piece piece : pieces) { if (piece.taken) { continue; } for (int i = 0; i < piece.count(); i++) { if (piece.canMove(i, board)) { board[piece.x][piece.y] = null; piece.move(i, false); Piece taken = board[piece.x][piece.y]; board[piece.x][piece.y] = piece; if (taken != null) { taken.taken = true; } try { if (taken instanceof Queen) { return whiteTurn; } boolean result = move(!whiteTurn, white, black, board, m - 1); if (result && whiteTurn) { return true; } all &= result; } finally { if (taken != null) { taken.taken = false; } board[piece.x][piece.y] = taken; piece.move(i, true); board[piece.x][piece.y] = piece; } } } } return all; } }
Shrey212001/100daysContinued
Day303.java
2,583
/* Topic:- Simplified Chess Engine Link:- https://www.hackerrank.com/challenges/simplified-chess-engine/problem?isFullScreen=true Problem:- Chess is a very popular game played by hundreds of millions of people. Nowadays, we have chess engines such as Stockfish and Komodo to help us analyze games. These engines are very powerful pieces of well-developed software that use intelligent ideas and algorithms to analyze positions and sequences of moves, as well as find tactical ideas. Consider the following simplified version of chess: Board: It's played on a board between two players named Black and White. Pieces and Movement: White initially has pieces and Black initially has pieces. There are no Kings and no Pawns on the board. Each player has exactly one Queen, at most two Rooks, and at most two minor pieces (i.e., a Bishop and/or Knight). Each piece's possible moves are the same as in classical chess, and each move made by any player counts as a single move. There is no draw when positions are repeated as there is in classical chess. Objective: The goal of the game is to capture the opponent’s Queen without losing your own. Given and the layout of pieces for games of simplified chess, implement a very basic (in comparison to the real ones) engine for our simplified version of chess with the ability to determine whether or not White can win in moves (regardless of how Black plays) if White always moves first. For each game, print YES on a new line if White can win under the specified conditions; otherwise, print NO. Input Format The first line contains a single integer, , denoting the number of simplified chess games. The subsequent lines define each game in the following format: The first line contains three space-separated integers denoting the respective values of (the number of White pieces), (the number of Black pieces), and (the maximum number of moves we want to know if White can win in). The subsequent lines describe each chesspiece in the format t c r, where is a character denoting the type of piece (where is Queen, is Knight, is Bishop, and is Rook), and and denote the respective column and row on the board where the figure is placed (where and ). These inputs are given as follows: Each of the subsequent lines denotes the type and location of a White piece on the board. Each of the subsequent lines denotes the type and location of a Black piece on the board. Constraints It is guaranteed that the locations of all pieces given as input are distinct. Each player initially has exactly one Queen, at most two Rooks and at most two minor pieces. Output Format For each of the games of simplified chess, print whether or not White can win in moves on a new line. If it's possible, print YES; otherwise, print NO. Solution:- */
block_comment
en
false
2,284
603
2,583
680
2,506
630
2,583
680
3,057
682
true
true
true
true
true
false
59423_2
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Hard here. * * @author (your name) * @version (a version number or a date) */ public class Hard extends Button { /** * Act - do whatever the Hard wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ private boolean mouseDown; public Hard() { mouseDown = false; } public void act() { if (!mouseDown && Greenfoot.mousePressed(this)) { Greenfoot.playSound("click_sound.wav"); Sound.stopped1(); Hardstage x = new Hardstage(); Greenfoot.setWorld(x); } } }
Kawaeee/black_jumper
Hard.java
193
/** * Act - do whatever the Hard wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */
block_comment
en
false
181
38
193
37
220
41
193
37
226
42
false
false
false
false
false
true
61676_10
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.Color; /** * Grids contain all necessary information (i.e. fertility, moisture) for flora growth of any sort * * @author Daniel Chung * @version Monday, October 21st, 2013 */ public class Grid extends Actor { //Grid factors private double neutralMoistureLevel = 4000.0; private double neutralNutrientLevel = 4000.0; private double moistureLevel = neutralMoistureLevel; private double nutrientLevel = neutralNutrientLevel; private double deAndReHydrationRate = 2.0; private double deAndReNutritionRate = 2.0; private int floodTimer = 0; private int droughtTimer = 0; //Colour determinants private int red = 100; private int green = 255 * (int)(nutrientLevel / (neutralNutrientLevel * 1.5)) > 255 ? 255 : 255 * (int)(nutrientLevel / (neutralNutrientLevel * 1.5)); private int blue = 255 * (int)(moistureLevel / (neutralMoistureLevel * 1.5)) > 255 ? 255 : 255 * (int)(moistureLevel / (neutralMoistureLevel * 1.5)); private Color colour = new Color(red, green, blue); //Images private GreenfootImage image = new GreenfootImage(80, 80); private int gridNumber; /** * Creates a grid with an index number, location, and image * * @param int gridNumber The index number of the grid * @param int positionX The horizontal position of the grid * @param int positionY The vertical position of the grid */ public Grid(int gridNumber, int positionX, int positionY){ this.gridNumber = gridNumber; setLocation(positionX, positionY); image.setColor(changeColour()); image.fill(); setImage(image); } //Accessors ================================================================== /** * @return double The level of nutrients currently stored in this grid */ public double getFertility(){ return nutrientLevel; } /** * @return double The level of moisture currently stored in this grid */ public double getMoisture(){ return moistureLevel; } //Modifiers ===================================================================== /** * Changes the colour values of the grid based on the fertility and moisture levels */ private Color changeColour(){ red = 150; green = (int)(255.0 * (nutrientLevel / neutralNutrientLevel)) > 255 ? 255 : (int)(255.0 * (nutrientLevel / neutralNutrientLevel)); blue = (int)(155.0 * (moistureLevel / neutralMoistureLevel)) > 155 ? 155 : (int)(155.0 * (moistureLevel / neutralMoistureLevel)); return new Color(red, green, blue); } /** * Adds the input double amount of moisture to the moisture level of the grid * * @param double amount The amount of moisture to add to the moisture level of the grid */ public void changeMoisture(double amount){ moistureLevel = (moistureLevel + amount) < 0 ? 0 : moistureLevel + amount; } /** * Adds the input double amount of fertility to the nutrition level of the grid, but does not allow fertility to drop below zero * * @param double amount The amount of fertility to add to the nutrition level of the grid */ public void changeFertility(double amount){ nutrientLevel = (nutrientLevel + amount) < 0 ? 0 : nutrientLevel + amount; } /** * Depletes the timers for the different disasters afflicting grid, and resets stats of grid when the disaster is over */ private void depleteDisasterTimers(){ if (floodTimer > 0 || droughtTimer > 0){ floodTimer = floodTimer > 0 ? floodTimer-- : 0; droughtTimer = droughtTimer > 0 ? droughtTimer-- : 0; if (floodTimer == 0 && droughtTimer == 0){ neutralMoistureLevel = 5000.0; deAndReHydrationRate = 2.0; } } } /** * Causes grid to dry rapidly to a defined drought level of moisture, for a given number of turns * * @param double newNeutralMoistureLvl The drought level of moisture * @param int droughtTime The number of turns that the the drought will last */ public void dry(double newNeutralMoistureLvl, int droughtTime){ neutralMoistureLevel = newNeutralMoistureLvl; deAndReHydrationRate = 10.0; droughtTimer = droughtTime; } /** * Causes grid to moisturise rapidly to a defined flood level of moisture, for a given number of turns * * @param double newNeutralMoistureLvl The flood level of moisture * @param int floodTime The number of turns that the the flood will last */ public void flood(double newNeutralMoistureLvl, int floodTime){ neutralMoistureLevel = newNeutralMoistureLvl; deAndReHydrationRate = 10.0; floodTimer = floodTime; } /** * Causes grid's moisture level to approach its neutral level at the rate of neutralisation */ private void neutraliseMoisture(){ if (moistureLevel > neutralMoistureLevel) { moistureLevel -= deAndReHydrationRate; } else if (moistureLevel < neutralMoistureLevel) { moistureLevel += deAndReHydrationRate; } } /** * Causes grid's nutrition level to approach its neutral level at the rate of neutralisation */ private void neutraliseNutrition(){ if (nutrientLevel > neutralNutrientLevel) { nutrientLevel -= deAndReNutritionRate; } else if (nutrientLevel < neutralNutrientLevel) { nutrientLevel += deAndReNutritionRate; } } /** * Neutralises grid's moisture and fertility, depletes countdown timers for disasters (weather), and * changes colour of grid to reflect status */ public void act(){ neutraliseMoisture(); neutraliseNutrition(); depleteDisasterTimers(); image.setColor(changeColour()); image.fill(); setImage(image); } }
Keiffeyy/Evolution-Simulation
Grid.java
1,673
/** * Changes the colour values of the grid based on the fertility and moisture levels */
block_comment
en
false
1,554
20
1,673
23
1,624
21
1,673
23
1,915
25
false
false
false
false
false
true
61758_1
import java.io.Serializable; import processing.core.*; import processing.data.*; import java.util.ArrayList; import java.util.HashMap; class Level implements Serializable { static transient skiny_mann source; public ArrayList<Stage> stages=new ArrayList<>(); public ArrayList<LogicBoard> logicBoards=new ArrayList<>(); public ArrayList<Boolean> variables=new ArrayList<>(); public ArrayList<Group> groups=new ArrayList<>(); public ArrayList<String> groupNames=new ArrayList<>(); public int mainStage, numOfCoins, levelID, numlogicBoards=0, loadBoard, tickBoard, levelCompleteBoard, multyplayerMode=1, maxPLayers=2, minPlayers=2; public String name, createdVersion, author; public float SpawnX, SpawnY, RewspawnX, RespawnY; public HashMap<String, StageSound> sounds=new HashMap<>(); transient JSONObject hedObj; Level(JSONArray file) { System.out.println("loading level"); JSONObject job =file.getJSONObject(0); hedObj=job; mainStage=job.getInt("mainStage"); numOfCoins=job.getInt("coins"); levelID=job.getInt("level_id"); SpawnX=job.getFloat("spawnX"); SpawnY=job.getFloat("spawnY"); RewspawnX=job.getFloat("spawn pointX"); RespawnY=job.getFloat("spawn pointY"); name=job.getString("name"); createdVersion=job.getString("game version"); source.author=job.getString("author"); author=job.getString("author"); System.out.println("author: "+source.author); source.currentStageIndex=mainStage; if (job.isNull("number of variable")) { System.out.println("setting up variables because none exsisted before"); variables.add(false); variables.add(false); variables.add(false); variables.add(false); variables.add(false); } else { for (int i=0; i<job.getInt("number of variable"); i++) { variables.add(false); } System.out.println("loaded "+variables.size()+" variables"); } if (!job.isNull("groups")) { JSONArray gps= job.getJSONArray("groups"); for (int i=0; i<gps.size(); i++) { groupNames.add(gps.getString(i)); groups.add(new Group()); } System.out.println("loaded "+groups.size()+" groups"); } else { System.out.println("no groups found, creating default"); groupNames.add("group 0"); groups.add(new Group()); } if (!job.isNull("multyplayer mode")) { multyplayerMode=job.getInt("multyplayer mode"); } if (!job.isNull("max players")) { maxPLayers=job.getInt("max players"); } if (!job.isNull("min players")) { minPlayers=job.getInt("min players"); } for (int i=0; i<10; i++) { source.players[i].x=SpawnX; source.players[i].y=SpawnY; } source.respawnX=(int)RewspawnX; source.respawnY=(int)RespawnY; source.respawnStage=source.currentStageIndex; System.out.println("checking game version compatablility"); if (!source.gameVersionCompatibilityCheck(createdVersion)) { System.out.println("game version not compatable with the verion of this level"); throw new RuntimeException("this level is not compatable with this version of the game"); } System.out.println("game version is compatable with this level"); System.out.println("loading level components"); for (int i=1; i<file.size(); i++) { job=file.getJSONObject(i); if (job.getString("type").equals("stage")||job.getString("type").equals("3Dstage")) { stages.add(new Stage(source.loadJSONArray(source.rootPath+job.getString("location")))); System.out.println("loaded stage: "+stages.get(stages.size()-1).name); } if (job.getString("type").equals("sound")) { sounds.put(job.getString("name"), new StageSound(job)); System.out.println("loaded sound: "+job.getString("name")); } if (job.getString("type").equals("logicBoard")) { logicBoards.add(new LogicBoard(source.loadJSONArray(source.rootPath+job.getString("location")), this)); numlogicBoards++; System.out.print("loaded logicboard: "+logicBoards.get(logicBoards.size()-1).name); if (logicBoards.get(logicBoards.size()-1).name.equals("load")) { loadBoard=logicBoards.size()-1; System.out.print(" board id set to: "+loadBoard); } if (logicBoards.get(logicBoards.size()-1).name.equals("tick")) { tickBoard=logicBoards.size()-1; System.out.print(" board id set to: "+tickBoard); } if (logicBoards.get(logicBoards.size()-1).name.equals("level complete")) { levelCompleteBoard=logicBoards.size()-1; System.out.print(" board id set to: "+levelCompleteBoard); } } } source.coins=new ArrayList<Boolean>(); for (int i=0; i<numOfCoins; i++) { source.coins.add(false); } System.out.println("loaded "+source.coins.size()+" coins"); if (numlogicBoards==0) { System.out.println("generating new logic boards as none exsisted"); logicBoards.add(new LogicBoard("load")); logicBoards.add(new LogicBoard("tick")); logicBoards.add(new LogicBoard("level complete")); loadBoard=0; tickBoard=1; levelCompleteBoard=2; } System.out.println("level load complete"); }//end of constructor void psudoLoad() { System.out.println("psudo loading level"); source.coins=new ArrayList<Boolean>(); for (int i=0; i<numOfCoins; i++) { source.coins.add(false); } groups=new ArrayList<>(); variables=new ArrayList<>(); if (hedObj.isNull("number of variable")) { System.out.println("setting up variables because none exsisted before"); variables.add(false); variables.add(false); variables.add(false); variables.add(false); variables.add(false); } else { for (int i=0; i<hedObj.getInt("number of variable"); i++) { variables.add(false); } System.out.println("loaded "+variables.size()+" variables"); } if (!hedObj.isNull("groups")) { JSONArray gps= hedObj.getJSONArray("groups"); for (int i=0; i<gps.size(); i++) { groupNames.add(gps.getString(i)); groups.add(new Group()); } System.out.println("loaded "+groups.size()+" groups"); } else { System.out.println("no groups found, creating default"); groupNames.add("group 0"); groups.add(new Group()); } source.currentStageIndex=mainStage; source.players[source.currentPlayer].x=SpawnX; source.players[source.currentPlayer].y=SpawnY; source.tpCords[0]=SpawnX; source.tpCords[1]=SpawnY; source.setPlayerPosTo=true; source.respawnX=(int)RewspawnX; source.respawnY=(int)RespawnY; source.respawnStage=source.currentStageIndex; logicBoards.get(loadBoard).superTick(); respawnEntities(); } void reloadCoins() { source.coins=new ArrayList<Boolean>(); for (int i=0; i<numOfCoins; i++) { source.coins.add(false); } } void save() { JSONArray index=new JSONArray(); JSONObject head = new JSONObject(); head.setInt("mainStage", mainStage); head.setInt("coins", numOfCoins); head.setInt("level_id", levelID); head.setFloat("spawnX", SpawnX); head.setFloat("spawnY", SpawnY); head.setFloat("spawn pointX", RewspawnX); head.setFloat("spawn pointY", RespawnY); head.setString("name", name); head.setString("game version", createdVersion);//when integrating the level creator make shure this line is changed to reflect the correct version head.setString("author", author); head.setInt("number of variable", variables.size()); head.setInt("multyplayer mode", multyplayerMode); head.setInt("max players", maxPLayers); head.setInt("min players", minPlayers); JSONArray grps=new JSONArray(); for (int i=0; i<groupNames.size(); i++) { grps.setString(i, groupNames.get(i)); } head.setJSONArray("groups", grps); index.setJSONObject(0, head); for (int i=1; i<stages.size()+1; i++) { JSONObject stg=new JSONObject(); stg.setString("name", stages.get(i-1).name); stg.setString("type", stages.get(i-1).type); stg.setString("location", stages.get(i-1).save()); index.setJSONObject(i, stg); } String[] keys=new String[0]; keys=(String[])sounds.keySet().toArray(keys); if (keys.length!=0) { for (int i=0; i<keys.length; i++) { index.setJSONObject(index.size(), sounds.get(keys[i]).save()); } } for (int i=0; i<logicBoards.size(); i++) { JSONObject board=new JSONObject(); board.setString("name", logicBoards.get(i).name); board.setString("type", "logicBoard"); board.setString("location", logicBoards.get(i).save()); index.setJSONObject(index.size(), board); } source.saveJSONArray(index, source.rootPath+"/index.json"); } String getHash() { String basePath=""; if (source.rootPath.startsWith("data")) { basePath=source.sketchPath()+"/"+source.rootPath; } else { basePath=source.rootPath; } String hash=""; hash+=Hasher.getFileHash(basePath+"/index.json"); JSONArray file = source.loadJSONArray(basePath+"/index.json"); JSONObject job; for (int i=1; i<file.size(); i++) { job=file.getJSONObject(i); if (job.getString("type").equals("stage")||job.getString("type").equals("3Dstage")) { hash+=Hasher.getFileHash(basePath+job.getString("location")); continue; } if (job.getString("type").equals("sound")) { hash+=Hasher.getFileHash(basePath+job.getString("location")); continue; } if (job.getString("type").equals("logicBoard")) { hash+=Hasher.getFileHash(basePath+job.getString("location")); } } return hash; } String[] getOutherFileNames() { String[] keys=new String[0]; keys=(String[])sounds.keySet().toArray(keys); String[] names=new String[keys.length]; if (keys.length!=0) { for (int i=0; i<keys.length; i++) { names[i]=sounds.get(keys[i]).path; } } return names; } void respawnEntities(){ for(Stage s : stages){ s.respawnEntities(); } } }
jSdCool/skinny-mann
Level.java
2,814
//when integrating the level creator make shure this line is changed to reflect the correct version
line_comment
en
false
2,469
18
2,814
19
3,041
18
2,814
19
3,310
20
false
false
false
false
false
true
61764_0
import javax.sound.midi.MidiEvent; import javax.sound.midi.Track; /** * This class is a bridge between an array of on/off sound pulses and a track * that the sequencer can actually play. * @author Karl Edge */ public class Timeline { private MidiEventGroup[][] groups; private Track track; private int pulseCount; private int tickCount; private int repeatCount; public Timeline (Track track, int pulseCount, int tickCount, int repeatCount) { groups = new MidiEventGroup[repeatCount][pulseCount]; this.pulseCount = pulseCount; this.track = track; this.tickCount = tickCount; this.repeatCount = repeatCount; // Populate last tick so sequencer loops normally addGroupToTrack(createEmptyGroup((pulseCount*tickCount*repeatCount))); } private MidiEventGroup createGroup (int pulse, int channel, int pitch, int velocity, int duration, int repeatN) { int tick = calcTick(pulse, repeatN); return new MidiEventGroup(tick, channel, pitch, velocity, duration); } private MidiEventGroup createEmptyGroup (int tick) { return new MidiEventGroup(tick, 9, 42, 0, 0); } private void addGroupToTrack (MidiEventGroup m) { MidiEvent[] events = m.getEvents(); for (int i = 0; i < events.length; i++) { track.add(events[i]); } } private int calcTick (int pulse, int repeatN) { return (pulse * tickCount) + (repeatN * pulseCount * tickCount); } public void createAllPulses (int channel, int pitch, int velocity, int duration) { for (int repeatN = 0; repeatN < repeatCount; repeatN++) { for (int pulse = 0; pulse < pulseCount; pulse++) { MidiEventGroup m = createGroup(pulse, channel, pitch, velocity, duration, repeatN); addGroup(repeatN, pulse, m); } } } public void createPulse (int pulse, int channel, int pitch, int velocity, int duration) { for (int repeatN = 0; repeatN < repeatCount; repeatN++) { MidiEventGroup m = createGroup(pulse, channel, pitch, velocity, duration, repeatN); addGroup(repeatN, pulse, m); } } private void addGroup (int repeatN, int pulse, MidiEventGroup m) { addGroupToTrack(m); groups[repeatN][pulse] = m; } private void addEventToTrack (MidiEvent e) { track.add(e); } public void createAllControlEvent (int eventID) { for (int repeatN = 0; repeatN < repeatCount; repeatN++) { for (int pulse = 0; pulse < pulseCount; pulse++) { MidiEventGroup m = groups[repeatN][pulse]; if (m != null) { addEventToTrack(groups[repeatN][pulse].createControlEvent(eventID)); } } } } public Track getTrack () { return track; } }
edgek/rhythm
Timeline.java
754
/** * This class is a bridge between an array of on/off sound pulses and a track * that the sequencer can actually play. * @author Karl Edge */
block_comment
en
false
728
35
754
40
814
39
754
40
888
41
false
false
false
false
false
true
63904_1
/** Tree.java - Reads in Load Shedding Data from file to a binary search tree *Provides method to search through it *@author ThaddeusOwl, 01-03-2020 *Use Tree(int,string) if you want to change the dataset length or input file *else use Tree() for default settings */ import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Tree{ BinarySearchTree<Data> bst; String fileName="Load_Shedding_All_Areas_Schedule_and_Map.clean.final.txt"; int n=2976; /**reads in default file with default dataset lenth into bst */ public Tree() throws FileNotFoundException{ bst = new BinarySearchTree<Data>(); Scanner file=new Scanner(new File(fileName)); for(int i=0; i<n; i++){ String line = file.nextLine(); String[] lineSplit = line.split(" ", 2); bst.insert(new Data(lineSplit[0],lineSplit[1])); } } /**reads in specified dataset length of specified file into bst */ public Tree(int a, String b) throws FileNotFoundException{ this.n=a; if(b.equals("default")){ }else{this.fileName=b;} bst = new BinarySearchTree<Data>(); Scanner file=new Scanner(new File(fileName)); for(int i=0; i<n; i++){ String line = file.nextLine(); String[] lineSplit = line.split(" ", 2); bst.insert(new Data(lineSplit[0],lineSplit[1])); } } /**Searches for the given parameter's match in the tree and outputs the corresponding area*/ public String search(String details){ Data a = new Data(details); BinaryTreeNode<Data> b = bst.find(a); if(b!=null){ return b.data.getAreas(); }else{return "Areas not found";} } /**prints all details/parameters with their corresponding areas */ public void allAreas(){ bst.inOrder(); } /**Returns number of operations counted when inserting */ public int getInsertOpCount(){ return bst.insertOpCount; } /** Returns operations counted when searching*/ public int getSearchOpCount(){ return bst.searchOpCount; } }
ThaddeusOwl/AvlVsBst
src/Tree.java
576
/**reads in default file with default dataset lenth into bst */
block_comment
en
false
484
13
576
14
591
13
576
14
656
15
false
false
false
false
false
true
66021_0
import greenfoot.*; /** * A player can collect flowers here. * * @Kat Nguyen * @5/29/2020 */ public class Garden extends World { Flower flower = null; private Inventory inv = new Inventory(); public Garden() { this (new BoyVillager(),"left"); } public Garden(BoyVillager villager, String from) { super(750, 650, 1); if (from.equals( "right" )) addObject(villager, getWidth()-1, villager.getY()); prepare(); } public void addFlowers() { for (int i = 0; i < 8; i++) { int randomNum = (int)(Math.random() * 3); if (randomNum == 0) flower = new Pansy(); else if (randomNum == 1) flower = new Tulip(); else if (randomNum == 2) flower = new Rose(); addObject(flower, getRandX(), getRandY()); } } public int getRandX() { return 15 + (int)((Math.random() * 640)); } public int getRandY() { return 125 + (int)((Math.random() * 425)); } public void prepare() { addFlowers(); addObject(inv, getWidth() / 2, getHeight() / 2 ); } }
katnguyen143/animal_crossing_pixel
Garden.java
370
/** * A player can collect flowers here. * * @Kat Nguyen * @5/29/2020 */
block_comment
en
false
339
29
370
35
385
33
370
35
418
36
false
false
false
false
false
true
66166_20
public class W3Schools { public static void main(String[] args) { System.out.println("Hello World!!"); System.out.println("I am learning to code in java"); System.out.println("It is awesome"); System.out.print("Print on same line! "); //print vs println The only difference is that it does not insert a new line at the end of the output: System.out.println("I will be on the same line"); System.out.println(6); System.out.println(4); System.out.println(17); System.out.println(3 + 3); System.out.println(3 * 3); /*over next line * still here * see */ //type variableName = value; String name = "John"; System.out.println(name); int myNum = 15; System.out.println(myNum); int myNum2; myNum2 = 13; System.out.println(myNum2); myNum2 = 20; System.out.println(myNum2); final int myNum3 = 15; //locks myNum3 System.out.println(myNum3); //myNum3 = 20; will not change due to myNum3 has been finalised //int myNum4 = 5; //float myFloatNum = 5.99f; //char myLetter = 'D'; //boolean myBool = true; //String myText = "Hello"; System.out.println("Hello " + name); String givenName = "Kai"; String surName = "Hardman"; String fullName = givenName + " " + surName; System.out.println(fullName); System.out.println(givenName.concat(surName)); int x = 6; int y = 9; int z = 60; System.out.println(x + y); System.out.println(x + y + z); x = y = z = 50; System.out.println(x + y + z); System.out.println(); byte myNum5 = 100; //The byte data type can store whole numbers from -128 to 127 System.out.println(myNum5); short myNum6 = 5000; //The int data type can store whole numbers from -2147483648 to 2147483647 System.out.println(myNum6); long myNum7 = 15000000000L; //The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807 System.out.println(myNum7); float myNum8 = 5.75f; //float is only six or seven decimal double myNum9 = 19.99f; //double variables have a precision of about 15 digits System.out.println(myNum8 + " " + myNum9); boolean isJavaFun = true; boolean isFishTasty = false; System.out.println(isJavaFun); System.out.println(isFishTasty); char myGrade = 'B'; //The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c': System.out.println(myGrade); System.out.println(); char myVar1 = 65, myVar2 = 66, myVar3 = 67, myVar4 = 68; System.out.println(myVar1); System.out.println(myVar2); System.out.println(myVar3); System.out.println(myVar4); double myDouble = 9.78d; int myInt = (int) myDouble; System.out.println(myDouble); System.out.println(myInt); int sum1 = 100 + 50; int sum2 = sum1 + 250; int sum3 = sum2 + sum1; System.out.println(sum1); System.out.println(sum2); System.out.println(sum3); System.out.println(x >= y); // is X grater or equale to Y //&& x < 5 && x < 10 Returns true if both statements are true //|| x < 5 || x < 4 Returns true if one of the statements is true //! !(x < 5 && x < 10) Reverse the result, returns false if the result is true String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; System.out.println(txt); System.out.println("The number of letters in the string is: "+ txt.length()); txt = ("Hello World"); System.out.println(txt.toLowerCase()); System.out.println(txt.toUpperCase()); txt = ("find meine mann"); System.out.println(txt.indexOf("mann")); int inx = 10; int iny = 20; int inz = inx + iny; String stx = "10"; String sty = "20"; String stz = stx + sty; System.out.println(inz); System.out.println(stz); //Because strings must be written within quotes, Java will misunderstand this string, and generate an error: //\' ' Single quote //\" " Double quote //\\ \ Backslash //\n New Line //\r Carriage Return //\t Tab //\b Backspace //\f Form Feed System.out.println("Hello\tTab"); System.out.println(Math.max(5, 10)); System.out.println(Math.min(5, 10)); int randomNum = (int)(Math.random() * 101); System.out.println(randomNum); x = 10; y = 9; System.out.println(x > y); System.out.println(y > x); int myAge = 17; int vottingAge = 18; if (myAge >= vottingAge){ System.out.println("You can vote"); } else if (myAge == 17) { System.out.println("Only one more year till you can vote"); } else { System.out.println("You can not vote"); } if (myAge == vottingAge) { System.out.println("my age is equal to votting age"); } else if (myAge < vottingAge){ System.out.println("my age is less than voting"); } else if (myAge > vottingAge){ System.out.println(" my age is greater then the voting age"); } int time = 20; String result = (time < 18) ? "Good day." : "Good evening."; //short form System.out.println(result); int day = 2; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default: System.out.println("Not in list"); } int i = 0; while (i <= 6) { System.out.println(i); i = i + 1; } i = 0; System.out.println(i); do { System.out.println(i); i = i + 1; } while (i <= 5); for (int l = 1; l <= 3; l = l + 1) { System.out.println("Outer: " + l); for (int j = 1; j <= 3; j = j + 1) { System.out.println(" Inner: " + j); } } String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (String carinfo : cars) { System.out.println("Das ist cool car: " + carinfo); } for (i = 0; i < 10; i = i + 1) { System.out.println("test if outing");//same if (i == 4) { break; } System.out.println(i); //same } for (i = 0; i < 10; i = i + 1) { if (i == 4) { System.out.println("prints the 4"); continue; } System.out.println(i); } } }
Dunvantkai/-W3Schools-Java
old/W3Schools.java
2,186
//Because strings must be written within quotes, Java will misunderstand this string, and generate an error:
line_comment
en
false
1,983
20
2,186
21
2,361
20
2,186
21
2,435
22
false
false
false
false
false
true
66227_0
import java.io.InputStream; import java.io.PrintStream; import java.util.Scanner; import java.util.List; import java.util.Map; import java.util.HashMap; public class Runner { private static final int MILLION = 1000000; // better off doing this than tracking down missing zero error private final Scanner ins; private final PrintStream outs; private final Line[] lines; private final Map<String, Integer> labelmap; private final Map<String, Integer> varmap = new HashMap<>(); private int acc = 0; // whether ACC has a starting value is not mentioned in ACSL document public Runner(Parser parser, InputStream ins, PrintStream outs) { this.lines = toArray(parser.getLines()); this.labelmap = parser.getLabelMap(); this.ins = new Scanner(ins); this.outs = outs; } public Runner(Parser parser, InputStream ins) { this(parser, ins, System.out); } public Runner(Parser parser, PrintStream outs) { this(parser, System.in, outs); } public Runner(Parser parser) { this(parser, System.in, System.out); } public void run() { for (int lnindex = 0; lnindex < lines.length;) { boolean increment = true; Line line = lines[lnindex]; OpCode op = line.getOpCode(); Location loc = line.getLocation(); String label = line.getLabel(); switch (line.getOpCode()) { case LOAD: this.acc = loc.value(this.varmap); break; case STORE: this.varmap.put(safeRefCast(loc, op).getLocationName(), this.acc); break; case ADD: this.acc = (this.acc + loc.value(this.varmap)) % MILLION; break; case SUB: this.acc = (this.acc - loc.value(this.varmap)) % MILLION; break; case MULT: this.acc = (this.acc * loc.value(this.varmap)) % MILLION; break; case DIV: this.acc = this.acc / loc.value(this.varmap); break; case BE: if (this.acc == 0) { lnindex = loc.value(this.labelmap); increment = false; } break; case BG: if (this.acc > 0) { lnindex = loc.value(this.labelmap); increment = false; } break; case BL: if (this.acc < 0) { lnindex = loc.value(this.labelmap); increment = false; } break; case BU: lnindex = loc.value(this.labelmap); increment = false; break; case END: return; case READ: try { this.varmap.put(safeRefCast(loc, op).getLocationName(), this.ins.nextInt()); } catch (NumberFormatException ex) { throw new NumberFormatException("READ did not receive a valid integer."); } break; case PRINT: this.outs.println(loc.value(this.varmap)); break; case DC: this.varmap.put(label, loc.value(null)); // only takes literals so does not need varmap break; default: throw new UnsupportedOperationException("Opcode not implemented yet."); } if (increment) lnindex++; } } private static Reference safeRefCast(Location loc, OpCode op) { // for use with opcodes that cannot accept locations that are literals // Parser and OpCode should prevent this from ever throwing anything if (loc.isLiteral()) throw new IllegalArgumentException(op.name() + " opcode cannot operate on a literal."); return (Reference) loc; } private static Line[] toArray(List<Line> linelist) { Object[] objarr = linelist.toArray(); Line[] linearr = new Line[objarr.length]; for (int i = 0; i < objarr.length; ++i) { linearr[i] = (Line) objarr[i]; } return linearr; } }
415mcc/acsl
Runner.java
987
// better off doing this than tracking down missing zero error
line_comment
en
false
863
11
987
11
1,078
11
987
11
1,161
11
false
false
false
false
false
true
66890_1
/* * DDM.java * Copyright (C) 2008 University of Waikato, Hamilton, New Zealand * @author Manuel Baena ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moa.classifiers.core.driftdetection; import com.github.javacliparser.IntOption; import moa.core.ObjectRepository; import moa.tasks.TaskMonitor; /** * Drift detection method based in DDM method of Joao Gama SBIA 2004. * * <p>João Gama, Pedro Medas, Gladys Castillo, Pedro Pereira Rodrigues: Learning * with Drift Detection. SBIA 2004: 286-295 </p> * * @author Manuel Baena ([email protected]) * @version $Revision: 7 $ */ public class DDMSS extends AbstractChangeDetector { private static final long serialVersionUID = -3518369648142099718L; //private static final int DDM_MINNUMINST = 30; public IntOption minNumInstancesOption = new IntOption( "minNumInstances", 'n', "The SUPER minimum number of instances before permitting detecting change.", 90, 0, Integer.MAX_VALUE); private int m_n; private double m_p; private double m_s; private double m_psmin; private double m_pmin; private double m_smin; public DDMSS() { resetLearning(); } @Override public void resetLearning() { m_n = 1; m_p = 1; m_s = 0; m_psmin = Double.MAX_VALUE; m_pmin = Double.MAX_VALUE; m_smin = Double.MAX_VALUE; } @Override public void input(double prediction) { // prediction must be 1 or 0 // It monitors the error rate if (this.isChangeDetected == true || this.isInitialized == false) { resetLearning(); this.isInitialized = true; } m_p = m_p + (prediction - m_p) / (double) m_n; m_s = Math.sqrt(m_p * (1 - m_p) / (double) m_n); m_n++; // System.out.print(prediction + " " + m_n + " " + (m_p+m_s) + " "); this.estimation = m_p; this.isChangeDetected = false; this.isWarningZone = false; this.delay = 0; if (m_n < this.minNumInstancesOption.getValue()) { return; } if (m_p + m_s <= m_psmin) { m_pmin = m_p; m_smin = m_s; m_psmin = m_p + m_s; } if (m_n > this.minNumInstancesOption.getValue() && m_p + m_s > m_pmin + 3 * m_smin) { //System.out.println(m_p + ",D"); this.isChangeDetected = true; //resetLearning(); } else if (m_p + m_s > m_pmin + 2 * m_smin) { //System.out.println(m_p + ",W"); this.isWarningZone = true; } else { this.isWarningZone = false; //System.out.println(m_p + ",N"); } } @Override public void getDescription(StringBuilder sb, int indent) { // TODO Auto-generated method stub } @Override protected void prepareForUseImpl(TaskMonitor monitor, ObjectRepository repository) { // TODO Auto-generated method stub } }
Jolly-w/MOA
DDMSS.java
1,100
/** * Drift detection method based in DDM method of Joao Gama SBIA 2004. * * <p>João Gama, Pedro Medas, Gladys Castillo, Pedro Pereira Rodrigues: Learning * with Drift Detection. SBIA 2004: 286-295 </p> * * @author Manuel Baena ([email protected]) * @version $Revision: 7 $ */
block_comment
en
false
966
107
1,100
122
1,137
104
1,100
122
1,245
122
false
false
false
false
false
true
68112_0
/* Create a Java class 'Employee'. Details: - The class is abstract. - The class has the following nullable public properties: - Id (int, read-only) - ReportsTo (int) - Name (string) - Email (string) - Mobile (string) - DepartmentId (int) - The class has a public c'tor that accepts all the properties as parameters. - The class has the following public properties: - Payment (double) - get-only, abstract - The class has the following public methods: - EmployeeDetails (string) - get-only, virtual */ package com.iluwatar.abstractdocument; public abstract class Employee { private final int id; private Integer reportsTo; private String name; private String email; private String mobile; private int departmentId; public Employee(int id, Integer reportsTo, String name, String email, String mobile, int departmentId) { this.id = id; this.reportsTo = reportsTo; this.name = name; this.email = email; this.mobile = mobile; this.departmentId = departmentId; } public int getId() { return id; } public Integer getReportsTo() { return reportsTo; } public void setReportsTo(Integer reportsTo) { this.reportsTo
gh-mentor/sabre-0627
employee.java
307
/* Create a Java class 'Employee'. Details: - The class is abstract. - The class has the following nullable public properties: - Id (int, read-only) - ReportsTo (int) - Name (string) - Email (string) - Mobile (string) - DepartmentId (int) - The class has a public c'tor that accepts all the properties as parameters. - The class has the following public properties: - Payment (double) - get-only, abstract - The class has the following public methods: - EmployeeDetails (string) - get-only, virtual */
block_comment
en
false
295
137
307
137
364
156
307
137
378
164
false
false
false
false
false
true
69501_0
import java.awt.*; /** * base implementation of AI interface */ public interface AI { public int generateAIMove(int turn, int numPlayers, int cols, int rows, Player[] players, Color[][] grid); public void setColor(Color c); }
cis3296f22/001-connect4group2
AI.java
62
/** * base implementation of AI interface */
block_comment
en
false
52
9
62
10
62
10
62
10
69
11
false
false
false
false
false
true
70919_4
/** * * @author Fred Morrison * */ import java.util.Arrays; public class Data { public static final int MAX = 1000; private int[][] grid; @SuppressWarnings("unused") private Data() { /* prevent uninitalized instances */} public Data(int rows, int cols) { grid = new int[rows][cols]; } /** * <b>Purpose:</b> fills all elements of <code>grid</code> with randomly * generated values that adhere to the constraints described in part (a). * <p> * <b>Preconditions:</b> * <ul> * <li><code>grid</code> is not null * <li><code>grid</code> has at least one element * </ul> */ public void repopulate() { for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[r].length; c++) { grid[r][c] = getUsableRandomValue(); } } } /** * <b>Purpose:</b> Returns a usable random value that meets the following conditions: * <ul> * <li>The value is between 1 and <code>MAX</code> * <li>The value is divisible by 10 * <li>The value is not divisible by 100 * </ul> * * @return - the random number */ public int getUsableRandomValue() { final int MIN = 1, RANGE = MAX - MIN + 1; int val = 0; while (val < MIN || val % 10 != 0 || val % 100 == 0) { val = (int) (Math.random() * RANGE) + MIN; } return val; } @Override public String toString() { String retval = ""; for (int[] row : grid) { retval += Arrays.toString(row) + "\n"; } return retval; } /** * <b>Purpose:</b> Counts the number of columns where the values in each row * of that column are equal to or greater than the row above it. * <p> * @return the number of columns with increasing rows */ public int countIncreasingCols() { int n = 0; for(int c = 0; c < grid[0].length; c++) { int prev = 0, current; boolean isIncreasing = true; for(int r = 0; r < grid.length && isIncreasing; r++) { current = grid[r][c]; if(current < prev) { // not increasing, so skip to the next column // by short-circuiting the inner loop isIncreasing = false; } else { prev = current; } } if(isIncreasing) n++; } return n; } }
fmorriso/ap-cs-a-2022-frq-4
Data.java
767
/** * <b>Purpose:</b> Counts the number of columns where the values in each row * of that column are equal to or greater than the row above it. * <p> * @return the number of columns with increasing rows */
block_comment
en
false
688
57
767
56
760
58
767
56
922
64
false
false
false
false
false
true
73998_0
import greenfoot.*; /** * Game Board for Triples * * Leo Li * @Feb 7, 2024 */ public class Card extends Actor { public enum Shape { TRIANGLE, SQUARE, CIRCLE, NO_SHAPE } public enum Color { RED, GREEN, BLUE, NO_COLOR } private Shape shape; private Color color; private boolean isSelected; private GreenfootImage image, selectedImage; private int numberOfShapes, shading; public Card(Shape shape, Color color, int numberOfShapes, int shading, GreenfootImage cardImage, GreenfootImage selectedCardImage) { this.shape = shape; this.color = color; this.numberOfShapes = numberOfShapes; this.shading = shading; image = cardImage; this.selectedImage = selectedCardImage; setImage(image); } public boolean getIsSelected() { return isSelected; } public Shape getShape() { return shape; } public Color getColor() { return color; } public int getNumberOfShapes() { return numberOfShapes; } public int getShading() { return shading; } public GreenfootImage getCardImage() { return image; } public GreenfootImage getSelectedCardImage() { return selectedImage; } public void setNumberOfShapes(int num) { numberOfShapes = num; } public void setShape(Shape shape) { this.shape = shape; } public void setColor(Color color) { this.color = color; } public void setShading(int num) { this.shading = num; } public void setCardImage(GreenfootImage image) { this.image = image; } public void setSelectedCardImage(GreenfootImage image) { selectedImage = image; } public void setIsSelected(boolean isSelected) { this.isSelected = isSelected; } }
San-Domenico-School/triples-zZijia
Card.java
476
/** * Game Board for Triples * * Leo Li * @Feb 7, 2024 */
block_comment
en
false
465
27
476
29
580
30
476
29
636
31
false
false
false
false
false
true
74106_11
import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Random; /** * Represent a rectangular grid of field positions. * Each position stores a single cell * * @author David J. Barnes, Michael Kölling & Jeffery Raphael * @version 2022.01.06 (1) */ public class Field { // A random number generator for providing random locations. private static final Random rand = Randomizer.getRandom(); // The depth and width of the field. private int depth, width; // Storage for the cells. private Cell[][] field; /** * Represent a field of the given dimensions. * @param depth The depth of the field. * @param width The width of the field. */ public Field(int depth, int width) { this.depth = depth; this.width = width; field = new Cell[depth][width]; } /** * Empty the field. */ public void clear() { for (int row = 0; row < depth; row++) { for (int col = 0; col < width; col++) { field[row][col] = null; } } } /** * Clear the given location. * @param location The location to clear. */ public void clear(Location location) { field[location.getRow()][location.getCol()] = null; } /** * Place a cell at the given location. * If there is already a cell at the location it will be lost. * @param cell The cell to be placed. * @param row Row coordinate of the location. * @param col Column coordinate of the location. */ public void place(Cell cell, int row, int col) { place(cell, new Location(row, col)); } /** * Place a cell at the given location. * If there is already a cell at the location it will be lost. * @param cell The cell to be placed. * @param location Where to place the cell. */ public void place(Cell cell, Location location) { field[location.getRow()][location.getCol()] = cell; } /** * Return the cell at the given location, if any. * @param location Where in the field. * @return The cell at the given location, or null if there is none. */ public Cell getObjectAt(Location location) { return getObjectAt(location.getRow(), location.getCol()); } /** * Return the cell at the given location, if any. * @param row The desired row. * @param col The desired column. * @return The cell at the given location, or null if there is none. */ public Cell getObjectAt(int row, int col) { return field[row][col]; } /** * Generate a random location that is adjacent to the * given location, or is the same location. * The returned location will be within the valid bounds * of the field. * @param location The location from which to generate an adjacency. * @return A valid location within the grid area. */ public Location randomAdjacentLocation(Location location) { List<Location> adjacent = adjacentLocations(location); return adjacent.get(0); } /** * Return a shuffled list of locations adjacent to the given one. * The list will not include the location itself. * All locations will lie within the grid. * @param location The location from which to generate adjacencies. * @return A list of locations adjacent to that given. */ public List<Location> adjacentLocations(Location location) { assert location != null : "Null location passed to adjacentLocations"; // The list of locations to be returned. List<Location> locations = new LinkedList<>(); if (location != null) { int row = location.getRow(); int col = location.getCol(); for (int roffset = -1; roffset <= 1; roffset++) { int nextRow = row + roffset; if (nextRow >= 0 && nextRow < depth) { for (int coffset = -1; coffset <= 1; coffset++) { int nextCol = col + coffset; // Exclude invalid locations and the original location. if (nextCol >= 0 && nextCol < width && (roffset != 0 || coffset != 0)) { locations.add(new Location(nextRow, nextCol)); } } } } // Shuffle the list. Several other methods rely on the list // being in a random order. Collections.shuffle(locations, rand); } return locations; } /** * Get a shuffled list of living neighbours * @param location Get locations adjacent to this. * @return A list of living neighbours */ public List<Cell> getLivingNeighbours(Location location) { assert location != null : "Null location passed to adjacentLocations"; List<Cell> neighbours = new LinkedList<>(); if (location != null) { List<Location> adjLocations = adjacentLocations(location); for (Location loc : adjLocations) { Cell cell = field[loc.getRow()][loc.getCol()]; if (cell.isAlive()) neighbours.add(cell); } Collections.shuffle(neighbours, rand); } return neighbours; } /** * Return the depth of the field. * @return The depth of the field. */ public int getDepth() { return depth; } /** * Return the width of the field. * @return The width of the field. */ public int getWidth() { return width; } }
hilalb-sahin/life
Field.java
1,323
/** * Generate a random location that is adjacent to the * given location, or is the same location. * The returned location will be within the valid bounds * of the field. * @param location The location from which to generate an adjacency. * @return A valid location within the grid area. */
block_comment
en
false
1,237
70
1,323
69
1,446
75
1,323
69
1,542
78
false
false
false
false
false
true
75748_1
// Author - Sarthak Kotewale import java.util.*; import java.io.*; import java.lang.*; import java.math.*; class Main{ public static void main(String[] args) { try { FastReader sc = new FastReader(); int t = sc.nextInt(); while(t-- > 0){ int cnt = 0; int b = sc.nextInt(); while(b > 2){ cnt += (b - 2) / 2; b -= 2; } System.out.println(cnt); } } catch (Exception e) { return; } } static char[] swap(String str, int i, int j) { char ch[] = str.toCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return ch; } static int indexOf(int[] arr, int ele) { for (int i = 0; i < arr.length; i++) { if (arr[i] == ele) { return i; } } return -1; } public static int[] remove(int[] a, int index) { if (a == null || index < 0 || index >= a.length) { return a; } int[] result = new int[a.length - 1]; for (int i = 0; i < index; i++) { result[i] = a[i]; } for (int i = index; i < a.length - 1; i++) { result[i] = a[i + 1]; } return result; } /*---------------------- Pair Class & Comparator ------------------------*/ static class Pair{ int x,y; public Pair(int x, int y){ this.x=x; this.y=y; } public int getX(){ return this.x; } public int getY(){ return this.y; } } static class Compare { static void compare(ArrayList<Pair> list) { Collections.sort(list, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2){ return p1.x - p2.x; } }); } } /*------------------------- Sort & Merge -----------------------------------------*/ public static void sort(int[] arr, int left, int right){ if(left<right){ int mid=left+(right-left)/2; sort(arr,left,mid); sort(arr,mid+1,right); merge(arr,left,mid,right); } } public static void merge(int[] arr, int left, int mid, int right){ int size_first=mid-left+1; int size_second=right-mid; int[] left_array=new int[size_first+1]; int[] right_array=new int[size_second+1]; for(int i=0;i<size_first;i++) left_array[i]=arr[left+i]; for(int i=0;i<size_second;i++) right_array[i]=arr[mid+1+i]; left_array[size_first]=Integer.MAX_VALUE; right_array[size_second]=Integer.MAX_VALUE; int i=0,j=0; for(int k=left;k<=right;k++){ if(left_array[i]<=right_array[j]){ arr[k]=left_array[i]; i++; }else{ arr[k]=right_array[j]; j++; } } } public static void sort(long[] arr, int left, int right){ if(left<right){ int mid=left+(right-left)/2; sort(arr,left,mid); sort(arr,mid+1,right); merge(arr,left,mid,right); } } public static void merge(long[] arr, int left, int mid, int right){ int size_first=mid-left+1; int size_second=right-mid; long[] left_array=new long[size_first+1]; long[] right_array=new long[size_second+1]; for(int i=0;i<size_first;i++) left_array[i]=arr[left+i]; for(int i=0;i<size_second;i++) right_array[i]=arr[mid+1+i]; left_array[size_first]=Integer.MAX_VALUE; right_array[size_second]=Integer.MAX_VALUE; int i=0,j=0; for(int k=left;k<=right;k++){ if(left_array[i]<=right_array[j]){ arr[k]=left_array[i]; i++; }else{ arr[k]=right_array[j]; j++; } } } /*-------------------------- FACTORIAL(big int) & SUM -----------------------------*/ public static BigInteger __find_factorial(int n){ BigInteger bi=new BigInteger("1"); for(int i=2;i<=n;i++){ bi=bi.multiply(BigInteger.valueOf(i)); } return bi; } public static long get_natural_sum(long n){ long sum=0; long even_part=0; if((n^1)>n){ // (n&1)==0 even even_part=n/2; sum=even_part*(n+1); }else{ even_part=(n+1)/2; sum=even_part*n; } return sum; } /*---------------------------- GCD & LCM --------------------------------*/ private static int lcm(int a, int b){ return (a/gcd(a,b))*b; } private static int gcd(int a, int b){ if(a==0) return b; return gcd(b%a,a); } private static long lcm(long a, long b){ return (a/gcd(a,b))*b; } private static long gcd(long a, long b){ if(a==0) return b; return gcd(b%a,a); } /*------------------------------------------------------------------------*/ private static int count_bits(long n){ return (int)(Math.log(n)/Math.log(2) + 1); } private static void swap(int[] arr, int i, int j){ int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } private static void swap(long[] arr, int i, int j){ long temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } private static void print_array(int[] arr){ for(int ele:arr) System.out.print(ele+" "); System.out.println(); } private static void print_array(long[] arr){ for(long ele:arr) System.out.print(ele+" "); System.out.println(); } private static void print_array_two(int[][] arr){ int rows=arr.length; int columns=arr[0].length; for(int i=0;i<rows;i++){ for(int j=0;j<columns;j++){ System.out.print(arr[i][j]+" "); } System.out.println(""); } } private static void print_array_two(long[][] arr){ int rows=arr.length; int columns=arr[0].length; for(int i=0;i<rows;i++){ for(int j=0;j<columns;j++){ System.out.print(arr[i][j]+" "); } System.out.println(""); } } /*-------------------------- FastReader Class -----------------------------*/ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } /*--------------------------------------------------------------------------*/ }
SarthakKotewale/My-Codechef-Solutions
TRISQ.java
2,047
/*---------------------- Pair Class & Comparator ------------------------*/
block_comment
en
false
1,735
10
2,047
9
2,292
11
2,047
9
2,382
13
false
false
false
false
false
true
77395_1
public class King extends Piece { private boolean castlingDone = false; public King(boolean white) { super(white); } @Override public boolean canMove(Board board, Spot start, Spot end) { try { if (end.getPiece().isWhite() == this.isWhite()) { return false; } } catch (Exception e) { // TODO: handle exception } int x = Math.abs(start.getX() - end.getX()); int y = Math.abs(start.getY() - end.getY()); if (x < 2 && y < 2) { // check if this move will not result in the king // being attacked if so return true return true; } // setup castling eventually return false; } public boolean isCastlingDone() { return castlingDone; } public void setCastlingDone(boolean castlingDone) { this.castlingDone = castlingDone; } }
Marois2000/Chess-Engine
King.java
227
// check if this move will not result in the king
line_comment
en
false
214
12
227
12
275
12
227
12
286
12
false
false
false
false
false
true
77597_1
class Solution { public int lengthOfLongestSubstringKDistinct(String s, int k) { //FBIP 3R //use sliding window with two pointers from substring template if (s == null || s.length() == 0 || k == 0) return 0; int result = 0, count = 0, left = 0, right = 0; int[] map = new int[128]; while (right < s.length()){ if (map[s.charAt(right++)]++ == 0) count++; while (count > k) if (map[s.charAt(left++)]-- == 1) count--; result = Math.max(result, right - left); } return result; } }
EdwardHXu/FBIP-LC
340.java
177
//use sliding window with two pointers from substring template
line_comment
en
false
167
10
177
11
192
10
177
11
201
11
false
false
false
false
false
true
79523_2
/** * Parts.java * Sentence parts comparison for person matching and tense matching * * @author Chris Napier * @version 1.0 */ /** Compare person, number and tense of the sentence parts */ public class Parts extends Object { // Nr of saved parts, and their stored attributes private int nparts = 0; private int[] sentence_part = null; private int[] person = null; private int[] auxilliary = null; // Marked parts index/count. Capacity set at construction private int mark_nparts = 0; private int capacity = 0; /** Creates new Class of given capacity */ public Parts(int capacity_in) { if (capacity_in <= 0) capacity = 100; else capacity = capacity_in; nparts = 0; sentence_part = new int[capacity]; person = new int[capacity]; } /** Receive and check a sentence part such as NP or VP */ public boolean push(int sentence_part_in, int person_in) { boolean ok = false; //If not exceeding stack size if (nparts < person.length) { sentence_part[nparts] = sentence_part_in; person[nparts] = person_in; nparts++; //Check NP and VP, or check To infinitive tense if (nparts == 2) { int i = nparts-2; if (sentence_part[i] == Sentence_types.N && sentence_part[i+1] == Sentence_types.V) ok = check_person(); else if (sentence_part[i] == Sentence_types.V && sentence_part[i+1] == Sentence_types.N) ok = true; //check_person(); else if (sentence_part[i] == Sentence_types.To_Clause && sentence_part[i+1] == Sentence_types.V) ok = check_infinitive(); } else { ok = true; } } return ok; } /** Nr of stored parts */ public int length() { return nparts; } /** Check that the person corresponds in the last to stored parts */ private boolean check_person() { boolean correct = true; //For the first 2 stored N or V sentence parts, only int i = nparts-2; // If the sentence parts are either: // N directly followed by V or V directly followed by N //If persons are defined but "differ" in bits, then its incorrect if (person[i] != 0 && person[i+1] != 0) { if ((person[i] & person[i+1]) == 0) { correct = false; } } return correct; } /** Check that the tense is infinitive after a To */ private boolean check_infinitive() { boolean correct = false; //For the "to" and verb int i = nparts-2; //The verb must be infinitive (S1 is used for Lexical base form) if ((person[i+1] & Person.INF) != 0) correct = true; //System.out.println("Parts To: i+1 " +(i+1)+ " person: " + person[i+1]); return correct; } /** Mark the current nr of stored parts, for a later reset */ public void mark() { mark_nparts = nparts; } /** Remove all saved parts, and clear the mark */ public void clear() { nparts = 0; mark_nparts = 0; } /** Reset saved parts index/count to the previously Marked position */ public void reset() { nparts = mark_nparts; } }
chriscnapier/NLP
Parts.java
880
// Nr of saved parts, and their stored attributes
line_comment
en
false
833
10
880
10
995
10
880
10
1,045
10
false
false
false
false
false
true
81097_0
import gmaths.*; import java.nio.*; import com.jogamp.common.nio.*; import com.jogamp.opengl.*; public class Model { private Mesh mesh; private int[] textureId1; private int[] textureId2; private Material material; private Shader shader; private Mat4 modelMatrix; private Camera camera; private Light light; public Model(GL3 gl, Camera camera, Light light, Shader shader, Material material, Mat4 modelMatrix, Mesh mesh, int[] textureId1, int[] textureId2) { this.mesh = mesh; this.material = material; this.modelMatrix = modelMatrix; this.shader = shader; this.camera = camera; this.light = light; this.textureId1 = textureId1; this.textureId2 = textureId2; } public Model(GL3 gl, Camera camera, Light light, Shader shader, Material material, Mat4 modelMatrix, Mesh mesh, int[] textureId1) { this(gl, camera, light, shader, material, modelMatrix, mesh, textureId1, null); } public Model(GL3 gl, Camera camera, Light light, Shader shader, Material material, Mat4 modelMatrix, Mesh mesh) { this(gl, camera, light, shader, material, modelMatrix, mesh, null, null); } public void setModelMatrix(Mat4 m) { modelMatrix = m; } public void setCamera(Camera camera) { this.camera = camera; } public void setLight(Light light) { this.light = light; } public void render(GL3 gl, Mat4 modelMatrix) { Mat4 mvpMatrix = Mat4.multiply(camera.getPerspectiveMatrix(), Mat4.multiply(camera.getViewMatrix(), modelMatrix)); shader.use(gl); shader.setFloatArray(gl, "model", modelMatrix.toFloatArrayForGLSL()); shader.setFloatArray(gl, "mvpMatrix", mvpMatrix.toFloatArrayForGLSL()); shader.setVec3(gl, "dim", light.getDim()); shader.setVec3(gl, "viewPos", camera.getPosition()); shader.setVec3(gl, "light.position", light.getPosition()); shader.setVec3(gl, "light.ambient", light.getMaterial().getAmbient()); shader.setVec3(gl, "light.diffuse", light.getMaterial().getDiffuse()); shader.setVec3(gl, "light.specular", light.getMaterial().getSpecular()); shader.setVec3(gl, "light.dim", light.getDim()); shader.setVec3(gl, "material.ambient", material.getAmbient()); shader.setVec3(gl, "material.diffuse", material.getDiffuse()); shader.setVec3(gl, "material.specular", material.getSpecular()); shader.setFloat(gl, "material.shininess", material.getShininess()); if (textureId1!=null) { shader.setInt(gl, "first_texture", 0); // be careful to match these with GL_TEXTURE0 and GL_TEXTURE1 gl.glActiveTexture(GL.GL_TEXTURE0); gl.glBindTexture(GL.GL_TEXTURE_2D, textureId1[0]); } if (textureId2!=null) { shader.setInt(gl, "second_texture", 1); gl.glActiveTexture(GL.GL_TEXTURE1); gl.glBindTexture(GL.GL_TEXTURE_2D, textureId2[0]); } mesh.render(gl); } public void render(GL3 gl) { render(gl, modelMatrix); } public void dispose(GL3 gl) { mesh.dispose(gl); if (textureId1!=null) gl.glDeleteBuffers(1, textureId1, 0); if (textureId2!=null) gl.glDeleteBuffers(1, textureId2, 0); } }
aca18ap/com3503
Model.java
920
// be careful to match these with GL_TEXTURE0 and GL_TEXTURE1
line_comment
en
false
817
14
920
16
982
16
920
16
1,085
18
false
false
false
false
false
true
84258_2
package proj4; /** * PLUS CLASS * An operator that is handle a certain way to convert from infix to postfix notation * @author Jordan An * @version 05/28/2020 */ public class Plus implements Operator { private final int PRECEDENCE = 1; /** Processes the current token. Since every token will handle * itself in its own way, handling may involve pushing or * popping from the given stack and/or appending more tokens * to the output string. * * @param s the Stack the token uses, if necessary, when processing itself. * @return String to be appended to the output */ public String handle(Stack<Token> s){ Token topStack = s.peek(); String ans = ""; while (!s.isEmpty() && !(topStack instanceof LeftParen) && ((Operator) topStack).getPrecedence() >= this.getPrecedence() ){ Token tempToken = s.pop(); ans += tempToken.toString(); topStack = s.peek(); } s.push(this); return ans; } /** Returns the token as a printable String * * @return the String version of the token. */ public String toString(){ return "+"; } /** * Return the value of operator's precedence * @return the operator precedence */ public int getPrecedence() { return PRECEDENCE; } }
quoc-jordan-an/The-Infix-to-Postfix-Converter
Plus.java
334
/** Returns the token as a printable String * * @return the String version of the token. */
block_comment
en
false
320
25
334
25
364
27
334
25
399
28
false
false
false
false
false
true
84820_2
/** * Write a description of class PartA here. * * @author (your name) * @version (a version number or a date) */ public class PartA { public static void main(String [] args) { /************* Prob 1 *********************** // write the isDivisible method below main // test by running this segment System.out.println("Is 8 divisible by 3? " + isDivisible(8,3)); System.out.println("Is 9 divisible by 3? " + isDivisible(9,3)); //************** End Prob 1 ******************/ /************* Prob 2 *********************** // write the multadd method below main // test by running this segment System.out.println("1*2 + 3 = " + multadd(1.0, 2.0, 3.0)); // write 2 more test cases // use multadd to compute the two expressions in part 4 of exercise 2 // HINT determine what is a, b, and c in each expression //************** End Prob 2 ******************/ /************* Prob 3 *********************** // write the isTriangle method below main // HINT: use || or && to chain three logical expressions // together // then write some code that prints "it's a triangle" // if the numbers 4, 1, 2 could be sides of a triangle // or prints "not a triangle" if the numbers 4,1,2 cannot. // // add another test case below the first //************** End Prob 3 ******************/ } }
mpc-csis/csis10a-lab-06
PartA.java
377
/************* Prob 2 *********************** // write the multadd method below main // test by running this segment System.out.println("1*2 + 3 = " + multadd(1.0, 2.0, 3.0)); // write 2 more test cases // use multadd to compute the two expressions in part 4 of exercise 2 // HINT determine what is a, b, and c in each expression //************** End Prob 2 ******************/
block_comment
en
false
376
116
377
112
424
131
377
112
454
139
false
false
false
false
false
true
86526_0
import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /* Define a 1:M dependency between objects so that when one object changes state, all its dependents are notified automatically \ ● Enables decoupling between publisher and subscriber \ ● Enables dynamic attachment/removal of subscribers */ public class Observer { public interface EventObserver { public void update(String eventType, File file) ; } public static class EmailNotification_observer implements EventObserver { private String email; public EmailNotification_observer(String email) { this.email = email; } @Override public void update(String eventType, File file) { System.out.println("Email to " + email + ": Someone has performed " + eventType + " operation with the following file: " + file.getName()); } } public static class LogOpen_observer implements EventObserver { private File log; public LogOpen_observer(String fileName) { this.log = new File(fileName); } @Override public void update(String eventType, File file) { System.out.println("Save to log " + log + ": Someone has performed " + eventType + " operation with the following file: " + file.getName()); } } public static class EventManager { Map<String, List<EventObserver>> observers = new HashMap<>(); public EventManager(String... operations) { for (String operation : operations) { this.observers.put(operation, new ArrayList<>()); } } public void subscribe(String eventType, EventObserver observer) { List<EventObserver> users = observers.get(eventType); users.add(observer); } public void unsubscribe(String eventType, EventObserver observer) { List<EventObserver> users = observers.get(eventType); users.remove(observer); } public void notify(String eventType, File file) { List<EventObserver> users = observers.get(eventType); for (EventObserver observer : users) { observer.update(eventType, file); } } } public static class Editor { public EventManager events; private File file; public Editor() { this.events = new EventManager("open", "save"); } public void openFile(String filePath) { this.file = new File(filePath); events.notify("open", file); } public void saveFile() throws Exception { if (this.file != null) { events.notify("save", file); } else { throw new Exception("Please open a file first."); } } } public static class Demo { public static void main(String[] args) { Editor editor = new Editor(); editor.events.subscribe("open", new LogOpen_observer("/path/to/log/file.txt")); editor.events.subscribe("save", new EmailNotification_observer("[email protected]")); try { editor.openFile("test.txt"); editor.saveFile(); } catch (Exception e) { e.printStackTrace(); } } } }
PeterHUistyping/Design_Pattern
Observer.java
718
/* Define a 1:M dependency between objects so that when one object changes state, all its dependents are notified automatically \ ● Enables decoupling between publisher and subscriber \ ● Enables dynamic attachment/removal of subscribers */
block_comment
en
false
632
45
718
52
792
48
718
52
836
57
false
false
false
false
false
true
88811_2
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * all actors that cause the cat to lose heart * * @author Angela * @version 06/06/2023 */ public class Hurt extends Actor { static int heartVal; GreenfootSound hurtSound = new GreenfootSound ("hurtSound.mp3"); /** * decrease a heart value and the cat go back to the starting point */ public void removeCat(int heartLost){ if (isTouching(Cat.class)){ hurtSound.play(); removeTouching(Cat.class); if (getWorld() instanceof GameOne){ GameOne world = (GameOne) getWorld(); world.minusHeartVal(heartLost); heartVal = world.getHeartVal(); world.removeObjects(world.getObjects(Heart.class)); world.setHeart(heartVal); if (heartVal > 0){ Cat cat = new Cat(); world.addObject(cat, 50, 250); } }else if (getWorld() instanceof GameTwo){ GameTwo world = (GameTwo) getWorld(); world.minusHeartVal(heartLost); heartVal = world.getHeartVal(); world.removeObjects(world.getObjects(Heart.class)); world.setHeart(heartVal); if (heartVal > 0){ Cat cat = new Cat(); world.addObject(cat, 50, 250); } }else if (getWorld() instanceof Random){ Random world = (Random) getWorld(); world.minusHeartVal(heartLost); heartVal = world.getHeartVal(); world.removeObjects(world.getObjects(Heart.class)); world.setHeart(heartVal); if (heartVal > 0){ Cat cat = new Cat(); world.addObject(cat, 50, 250); } } } } }
yrdsb-peths/final-greenfoot-project-Gao040701
Hurt.java
464
/** * decrease a heart value and the cat go back to the starting point */
block_comment
en
false
428
19
464
18
500
21
464
18
536
21
false
false
false
false
false
true
89130_3
package InheritanceQ2; //Nurse.java public class Nurse extends Doctor { public void treatment() { System.out.println("Nurse is Providing treatment to a patient"); } public static void main(String[] args) { // Create an instance of Surgeon and call the inherited surgery method Surgeon surgeon = new Surgeon(); surgeon.surgery(); // Output: Performing a surgery // Create an instance of Nurse and call both surgery and treatment methods Nurse nurse = new Nurse(); nurse.surgery(); // Output: Performing a surgery nurse.treatment(); // Output: Providing treatment to a patient } }
nasiruddinkhatib/Java-Labs
Lab 5 java/Nurse.java
176
// Create an instance of Nurse and call both surgery and treatment methods
line_comment
en
false
135
14
176
18
159
14
176
18
189
16
false
false
false
false
false
true
89138_0
/** * Represents a Doctor object with a certain name, 2 treatment objects, * and methods that act on those Treatment objects. * @author (Zhengyang Qi) * @version 1.0 */ public class Doctor { private String name; private Treatment treatment; /** * Initialies a Doctor object with the given name and 1 additional * parameter. * * @param name the name of this doctor * @param emergencyHealAmount the amount of health points to pass in to the * EmergencyTreatment constructor */ public Doctor(String name, int emergencyHealAmount) { this.name = name; treatment = new EmergencyTreatment(emergencyHealAmount); } /** * Initialies a Doctor object with the given name, and takes in 2 additional * parameters. * * After creating the ScheduledTreatment class, and creating an instance variable * of type Treatment above, in this constructor you should initialize an * instance of the **ScheduledTreatment** class, whose constructor will take * in the value of `scheduledHealAmount` as well as `scheduledPatientID`. * This new object should be assigned to an instance variable in this class. * @param name the name of this doctor * @param scheduledHealAmount the amount of health points to pass in to the * ScheduledTreatment constructor * @param scheduledPatientID the patientID to pass in to the * ScheduledTreatment constructor */ public Doctor(String name, int scheduledHealAmount, int scheduledPatientID) { this.name = name; treatment = new ScheduledTreatment(scheduledHealAmount, scheduledPatientID); } /** * Perform the appropriate treatment to a list of patients. * @param patients A list of patients. */ public void performTreatment(Patient[] patients) { System.out.println(name + " goes to heal their patients!"); treatment.performHeal(patients); } @Override public String toString() { return String.format("Doctor %s with treatment %s", name, treatment.toString()); } /** * Set treatment to a certain to passed in. * @param t the treatment we want to set as */ public void setTreatment(Treatment t) { treatment = t; } }
Jasonqi146/OOP_JAVA_Practices
HW7/src/Doctor.java
535
/** * Represents a Doctor object with a certain name, 2 treatment objects, * and methods that act on those Treatment objects. * @author (Zhengyang Qi) * @version 1.0 */
block_comment
en
false
513
44
535
50
557
47
535
50
637
55
false
false
false
false
false
true
91360_0
import java.util.ArrayList; import java.util.List; public class Database { public static List<InsurancePolicy> policies = new ArrayList<>(); /* InsurancePolicy structure includes: - id (Integer) - policyNumber (String) - insuredLastName (String) - annualPremium (Double) - ArrayList of Claims InsuranceClaim structure includes: - id (Integer) - claimNumber (String) - isPaid (Boolean) - amount (Double) */ public static void loadData() { InsurancePolicy policy1 = new InsurancePolicy(1, "888AAA", "Robertson", 168.47); InsuranceClaim policy1Claim1 = new InsuranceClaim(1, "CLM123", false, 1500.00); InsuranceClaim policy1Claim2 = new InsuranceClaim(2, "CLM222", false, 2497.68); policy1.getClaims().add(policy1Claim1); policy1.getClaims().add(policy1Claim2); policies.add(policy1); InsurancePolicy policy2 = new InsurancePolicy(2, "807DDI", "Testing", 269.80); InsuranceClaim policy2Claim1 = new InsuranceClaim(3, "CLM444", true, 8433.11); policy2.getClaims().add(policy2Claim1); policies.add(policy2); InsurancePolicy policy3 = new InsurancePolicy(3, "777AAB", "Schmoe", 467.89); InsuranceClaim policy3Claim1 = new InsuranceClaim(4, "CLM001", false, 799.00); InsuranceClaim policy3Claim2 = new InsuranceClaim(5, "CLM002", true, 4877.44); InsuranceClaim policy3Claim3 = new InsuranceClaim(6, "CLM003", true, 2501.01); policy3.getClaims().add(policy3Claim1); policy3.getClaims().add(policy3Claim2); policy3.getClaims().add(policy3Claim3); policies.add(policy3); InsurancePolicy policy4 = new InsurancePolicy(4, "900AEF", "Williamson", 100.23); policies.add(policy4); } }
KernelGamut32/capstone2-resources
Database.java
599
/* InsurancePolicy structure includes: - id (Integer) - policyNumber (String) - insuredLastName (String) - annualPremium (Double) - ArrayList of Claims InsuranceClaim structure includes: - id (Integer) - claimNumber (String) - isPaid (Boolean) - amount (Double) */
block_comment
en
false
522
74
600
81
581
85
599
80
686
97
false
false
false
false
false
true
92314_2
package ch_22; /** * *22.6 (Execution time for GCD) Write a program that obtains the execution time for * finding the GCD of every two consecutive Fibonacci numbers from the index * 40 to index 45 using the algorithms in Listings 22.3 and 22.4. Your program * should print a table like this: * --------------------| 40 41 42 43 44 45 * --------------------------------------------------------------------------------- * Listing 22.3 GCD * Listing 22.4 GCDEuclid * <p> * (Hint: You can use the following code template to obtain the execution time.) * long startTime = System.currentTimeMillis(); * perform the task; * long endTime = System.currentTimeMillis(); * long executionTime = endTime - startTime; */ public class Exercise22_06 { /** * Test Driver */ public static void main(String[] args) { /* calculate the Fibonacci numbers from index 40 to index 45 */ int[] fibs = calcFibIndexes40to45(); System.out.println("\t\t\t\t\t\t40 41 42 43 44 45"); System.out.println("---------------------------------------------------------"); System.out.print("Listing 22.3 GCD\t\t"); for (int i = 0; i < fibs.length - 1; i++) { long startTime = System.currentTimeMillis(); int gcd = gcd(fibs[i], fibs[i + 1]); long endTime = System.currentTimeMillis(); long executionTime = endTime - startTime; System.out.print(" " + executionTime); } System.out.print("\nListing 22.4 GCDEuclid "); for (int i = 0; i < fibs.length - 1; i++) { long startTime = System.currentTimeMillis(); int gcd = gcdEuclid(fibs[i], fibs[i + 1]); long endTime = System.currentTimeMillis(); long executionTime = endTime - startTime; System.out.print(" " + executionTime); } } /** * Find GCD for integers m and n using Euclid's algorithm */ public static int gcdEuclid(int m, int n) { if (m % n == 0) return n; else return gcdEuclid(n, m % n); } /** * Find GCD for integers m and n */ public static int gcd(int m, int n) { int gcd = 1; if (m % n == 0) return n; for (int k = n / 2; k >= 1; k--) { if (m % k == 0 && n % k == 0) { gcd = k; break; } } return gcd; } private static int[] calcFibIndexes40to45() { int[] fibs = new int[6]; int i = 2; int f0 = 0; int f1 = 1; int f2 = 0; // Find fib numbers up to 39 while (i < 40) { f2 = f0 + f1; f0 = f1; f1 = f2; i++; } // Next fib will be at index 40 for (int j = 0; j < fibs.length; j++) { f2 = f0 + f1; fibs[j] = f2; f0 = f1; f1 = f2; } return fibs; } }
HarryDulaney/intro-to-java-programming
ch_22/Exercise22_06.java
866
/* calculate the Fibonacci numbers from index 40 to index 45 */
block_comment
en
false
818
16
866
18
934
16
866
18
1,012
19
false
false
false
false
false
true
97032_17
import java.io.Serializable; import java.util.ArrayList; public class Player implements Serializable { private int bank; private int bet; private int profit; private int winCounter; private int loseCounter; private int bjCounter; private int bustCounter; private int pushCounter; private int doubleWinCounter; private int doubleLoseCounter; private int doubleBjCounter; private int doubleBustCounter; private int doublePushCounter; private String name; private ArrayList<Hand> hands = new ArrayList<Hand>(); private int startBalance; private int betUnit; private int maxBet; // Creates a player object public Player(int startB, int betU, int maxB) { startBalance = startB; betUnit = betU; maxBet = maxB; hands.add(new Hand()); bank = startBalance; bet = betUnit*1; winCounter = 0; loseCounter = 0; bjCounter = 0; bustCounter = 0; pushCounter = 0; } // Gets a player's bank amount public int getBank() { return bank; } // Removes a player's bet from their bank if they bust. Sets bet to zero afterwards. public void bust(int betMultiplier) { bank -= bet*betMultiplier; profit -= bet*betMultiplier; if(betMultiplier>1){ doubleBustCounter++; }else{ bustCounter++; } } // Adds a player's bet from their bank if they win. Sets bet to zero afterwards. public void win(int betMultiplier) { bank += (bet*betMultiplier); profit += (bet*betMultiplier); if(profit < betUnit){ if(profit + bet + betUnit > betUnit){ bet = Math.min(betUnit-profit,maxBet); }else{ bet = Math.min(betUnit+bet,maxBet); } }else if(profit>= betUnit){ bet = betUnit; profit = 0; } if(betMultiplier>1){ doubleWinCounter++; }else{ winCounter++; } } // Removes a player's bet from their bank if they lose. Sets bet to zero afterwards. public void loss(int betMultiplier) { bank -= bet*betMultiplier; profit -= bet*betMultiplier; if(betMultiplier>1){ doubleLoseCounter++; }else{ loseCounter++; } } // This calculate the bet for a player who has a Blackjack public void blackjack(int betMultiplier) { bank += (bet*betMultiplier*1.5); profit += (bet*betMultiplier*1.5); if(profit < betUnit){ if(profit + bet + betUnit > betUnit){ bet = Math.min(betUnit-profit,maxBet); }else{ bet = Math.min(betUnit+bet,maxBet); } }else if(profit>= betUnit){ bet = betUnit; profit = 0; } if(betMultiplier>1){ doubleBjCounter++; }else{ bjCounter++; } } // Sets a player's bet to 0 if the "push". Notice, no bet is added or removed. public void push() { if(profit < betUnit){ if(profit + bet + betUnit > betUnit){ bet = Math.min(betUnit-profit,maxBet); }else{ bet = Math.min(betUnit+bet,maxBet); } } pushCounter++; } /* //Flat bet // Removes a player's bet from their bank if they bust. Sets bet to zero afterwards. public void bust(int betMultiplier) { bank -= (bet*betMultiplier); if(betMultiplier>1){ doubleBustCounter++; }else{ bustCounter++; } } // Adds a player's bet from their bank if they win. Sets bet to zero afterwards. public void win(int betMultiplier) { bank += (bet*betMultiplier); if(betMultiplier>1){ doubleWinCounter++; }else{ winCounter++; } } // Removes a player's bet from their bank if they lose. Sets bet to zero afterwards. public void loss(int betMultiplier) { bank -= (bet*betMultiplier); if(betMultiplier>1){ doubleLoseCounter++; }else{ loseCounter++; } } // This calculate the bet for a player who has a Blackjack public void blackjack(int betMultiplier) { bank += (bet*betMultiplier*1.5); if(betMultiplier>1){ doubleBjCounter++; }else{ bjCounter++; } } // Sets a player's bet to 0 if the "push". Notice, no bet is added or removed. public void push() { pushCounter++; } */ // This sets the player bank to -1. -1 is unreachable and they are removed from the game public void removeFromGame() { bank = -1; } // This resets the bank to 0. Currently used to reset a removed player's bank from -1 to 0. public void resetBank() { bank = 0; } // Sets a player's bet public void setBet(int newBet) { bet = newBet; } // Sets a player's name public void setName(String name1){ name = name1; } // Gets a player's name public String getName() { return name; } // Gets a player's hand total public int getTotal(int index) { return hands.get(index).calculateTotal(); } // Gets a player's bet public int getBet(){ return this.bet; } // Adds a card to a player's hand public void addCard(Card card, int index) { hands.get(index).addCard(card); } // Gets the player's cards to print as a string public String getHandString(int index) { String str = "Cards:" + hands.get(index).toString(); return str; } // Gets the player's cards to print as a string public Hand getHand(int index) { return hands.get(index); } // Gets the player's cards to print as a string public ArrayList<Hand> getHands() { return hands; } // Clears a player's hand public void clearHand(int index) { hands.get(index).clearHand(); } // Return number of hands public int getNoOfHands() { return hands.size(); } public int getStartingBalance(){ return startBalance; } /* Character->move Legend: Hit = H Stand = S Double otherwise Hit = E Double otherwise Stand = F Split = P Split if double after is allowed, otherwise hit = Q Hit if 1 away from charlie,otherwise stand = O Hit if 1 or 2 away from charlie, otherwise stand = T */ public char getMove(int dealerCard, int index) { String options = "SSSSSSSSSS"; char move = 'S'; //Hard if(!getHand(index).canSplit() && !getHand(index).isSoft()){ //System.out.println("This hand is a hard " + getTotal()); if(getTotal(index) <= 8) {options = "HHHHHHHHHH";} else if(getTotal(index)==9) {options = "HEEEEHHHHH";} else if(getTotal(index)==10) {options = "EEEEEEEEHH";} else if(getTotal(index)==11) {options = "EEEEEEEEEH";} else if(getTotal(index)==12) {options = "HHTTTHHHHH";} else if(getTotal(index)==13) {options = "TTOOOHHHHH";} else if(getTotal(index)==14) {options = "OOOOOHHHHH";} else if(getTotal(index)==15) {options = "OOOOOHHHHH";} else if(getTotal(index)==16) {options = "OOSSSHHHHH";} else if(getTotal(index)==17) {options = "SSSSSSSOOO";} else {options = "SSSSSSSSSS";} } //Soft else if(!getHand(index).canSplit() && getHand(index).isSoft()){ //System.out.println("This hand is a soft " + getTotal()); if(getTotal(index) == 13) {options = "HHHEEHHHHH";} else if(getTotal(index)==14) {options = "HHHEEHHHHH";} else if(getTotal(index)==15) {options = "HHEEEHHHHH";} else if(getTotal(index)==16) {options = "HHEEEHHHHH";} else if(getTotal(index)==17) {options = "HEEEEHHHHH";} else if(getTotal(index)==18) {options = "TFFFFTTTTT";} else if(getTotal(index)==19) {options = "OOOOOOOOTO";} else if(getTotal(index)==20) {options = "OOOOOOOOOO";} else if(getTotal(index)==21) {options = "OOOOOOOOOO";} } //Splits else if(getHand(index).canSplit() && hands.size()<2){ if(getTotal(index) == 4) {options = "QQPPPPHHHH";} else if(getTotal(index)==6) {options = "QQPPPPHHHH";} else if(getTotal(index)==8) {options = "HHHQQHHHHH";} else if(getTotal(index)==12) {options = "QPPPPHHHHH";} else if(getTotal(index)==14) {options = "PPPPPPHHHH";} else if(getTotal(index)==16) {options = "PPPPPPPPPP";} else if(getTotal(index)==18) {options = "PPPPPSPPSS";} else if(getTotal(index)==12) {options = "PPPPPPPPPP";} } //System.out.println("The available options are: " + options); //System.out.println("Dealers card is: " + dealerCard); //System.out.println("Which is at index: " + Math.floorMod(dealerCard-2,10)); //System.out.println("Move chosen for P2L: " + options.charAt(Math.floorMod(dealerCard-2,10))); move = options.charAt(Math.floorMod(dealerCard-2,10)); if(move == 'E' || move == 'F'){ if (getHand(index).getNoOfCards()<=2){ move = 'D'; }else{move = (move == 'E')?'H':'S';} } if(move == 'O'){move = (getHand(index).getNoOfCards()==6)?'H':'S';} if(move == 'T'){move = (getHand(index).getNoOfCards()>=5)?'H':'S';} if(move == 'Q'){move = 'P';} return move; } public void splitHand(){ hands.add(new Hand()); hands.get(1).addCard(hands.get(0).removeCard(1)); } public int getWins() { return winCounter; } public int getLosses() { return loseCounter; } public int getBlackjacks(){ return bjCounter; } public int getPushes(){ return pushCounter; } public int getBusts(){ return bustCounter; } public int getDoubleWins() { return doubleWinCounter; } public int getDoubleLosses() { return doubleLoseCounter; } public int getDoubleBlackjacks(){ return doubleBjCounter; } public int getDoublePushes(){ return doublePushCounter; } public int getDoubleBusts(){ return doubleBustCounter; } } //End class
aaronfisher-code/Blackjack-Simulator
Player.java
3,137
// Gets the player's cards to print as a string
line_comment
en
false
2,755
11
3,134
11
3,101
12
3,137
11
3,766
13
false
false
false
false
false
true
97952_7
/** * Class Name: Field * Author: Habib Rahman * Represents a field with soil and irrigation information. * * Fields: * private double pHsoil: The pH level of the soil in the field * private double irrigation: The irrigation level of the field * private static double BASE_PH: The base pH level for the field * * Methods: * Field(): Default constructor for the Field class, initializes pHsoil to the base pH level and irrigation to 0 * Field(double pHsoil, double irrigation): Constructor for the Field class with parameters * getPHSoil(): Getter for the pHsoil field * getIrrigation(): Getter for the irrigation field * setPHsoil(double pHsoil): Setter for the pHsoil field * setIrrigation(double irrigation): Setter for the irrigation field * decay(): Decreases the pH level of the soil */ public class Field { private double pHsoil; private double irrigation; private static double BASE_PH = 6.5; /** * Default constructor for the Field class. * Initializes pHsoil to the base pH level and irrigation to 0. */ public Field() { pHsoil = BASE_PH; irrigation = 0; } /** * Constructor for the Field class with parameters. * @param pHsoil The pH level of the soil * @param irrigation The irrigation level of the field */ public Field(double pHsoil, double irrigation) { this.pHsoil = pHsoil; this.irrigation = irrigation; } /** * Getter for the pHsoil field. * @return The pH level of the soil */ public double getPHSoil() { return pHsoil; } /** * Getter for the irrigation field. * @return The irrigation level of the field */ public double getIrrigation() { return irrigation; } /** * Setter for the pHsoil field. * @param pHsoil The pH level to set */ public void setPHsoil(double pHsoil) { this.pHsoil = pHsoil; } /** * Setter for the irrigation field. * @param irrigation The irrigation level to set */ public void setIrrigation(double irrigation) { this.irrigation = irrigation; } /** * Decreases the pH level of the soil. */ public void decay() { pHsoil = pHsoil - 0.03; } }
lhlRahman/Farm-Manager
Field.java
666
/** * Decreases the pH level of the soil. */
block_comment
en
false
565
14
666
17
630
16
666
17
779
19
false
false
false
false
false
true
98260_3
package chat.model; import java.util.ArrayList; /** * Base version of the 2015 Chatbot class. Only stub methods are provided. Students will complete methods as part of the project. * * @author Nick Haynes * @version 1.6 10/28/15 Updated and created a switch method of conversation. */ public class Chatbot { private ArrayList<String> memesList; private ArrayList<String> politicalTopicList; private String userName; private String content; /** * Creates an instance of the Chatbot with the supplied username. * * @param userName * The username for the chatbot. */ public Chatbot(String userName) { this.userName = userName; this.memesList = new ArrayList<String>(); this.politicalTopicList = new ArrayList<String>(); this.content = "Getting yolked"; buildMemesList(); buildPoliticalTopicsList(); } /** * this has all the values we put in our memesList with the .add */ private void buildMemesList() { this.memesList.add("Cute animals"); this.memesList.add("doge"); this.memesList.add("Farmer memes"); this.memesList.add("John Cena"); this.memesList.add("Pepe"); this.memesList.add("Donald Trump"); this.memesList.add("Spoopy"); this.memesList.add("SkeletonWar"); this.memesList.add("Do you even lift bro?"); this.memesList.add("Spooterman"); } private void buildPoliticalTopicsList() { this.politicalTopicList.add("election"); this.politicalTopicList.add("democrat"); this.politicalTopicList.add("republican"); this.politicalTopicList.add("liberal"); this.politicalTopicList.add("conservative"); this.politicalTopicList.add("Trump"); this.politicalTopicList.add("Clinton"); this.politicalTopicList.add("Biden"); this.politicalTopicList.add("Carson"); this.politicalTopicList.add("Rubio"); this.politicalTopicList.add("Fiorina"); this.politicalTopicList.add("Sanders"); this.politicalTopicList.add("vote"); this.politicalTopicList.add("11/8/2016 "); this.politicalTopicList.add("Bush did 9/11"); } /** * Checks the length of the supplied string. Returns false if the supplied String is empty or null, otherwise returns true. * * @param currentInput * @return A true or false based on the length of the supplied String. */ public boolean lengthChecker(String currentInput) { boolean hasLength = false; if (currentInput != null) { if (currentInput.length() > 0) { hasLength = true; } } return hasLength; } /** * Checks if the supplied String matches the content area for this Chatbot instance. * * @param currentInput * The supplied String to be checked. * @return Whether it matches the content area. */ public boolean contentChecker(String currentInput) { boolean hasContent = false; if (currentInput.toLowerCase().contains(content.toLowerCase())) { hasContent = true; } return hasContent; } /** * Checks if supplied String matches ANY of the topics in the politicalTopicsList. Returns true if it does find a match and false if it does not match. * * @param currentInput * The supplied String to be checked. * @return Whether the String is contained in the ArrayList. */ public boolean politicalTopicChecker(String currentInput) { boolean hasPoliticalTopic = false; for (String politicalTopic : politicalTopicList) { if(currentInput.toLowerCase().equals(politicalTopic.toLowerCase())) { hasPoliticalTopic = true; } } return hasPoliticalTopic; } /** * Checks to see that the supplied String value is in the current memesList variable. * * @param currentInput * The supplied String to be checked. * @return Whether the supplied String is a recognized meme. */ public boolean memeChecker(String currentInput) { boolean hasMemes = false; for (String meme : memesList) { if (currentInput.toLowerCase().equals(meme.toLowerCase())) { hasMemes = true; } } return hasMemes; } public String processQuestion(String currentInput) { String nextConversation = "What else what would you like to talk about?"; ; int randomTopic = (int) (Math.random() * 5); switch (randomTopic) { case 0: if(contentChecker(currentInput)) { nextConversation = "Hey you said my favorite thing! What else do you like?"; } break; case 1: if(memeChecker(currentInput)) { nextConversation = "That is a pretty ank meme bro way to stay current"; } break; case 2:if(politicalTopicChecker(currentInput)) { nextConversation = "Wow I hate trump too! Do you like bernie??"; } break; case 3: if(currentInput.contains("yolked")) { nextConversation = "Wow you seem prety cool. Do you like to be a asshole in public?"; } break; case 4: nextConversation ="Boy you are sure dandy! have you heard of our true lord and savior and dark prince? His name is Satan. "; break; default: nextConversation = "I love me some satan. Do you like warlocks?"; break; } return nextConversation; } /** * Returns the username of this Chatbot instance. * * @return The username of the Chatbot. */ public String getUserName() { return userName; } /** * Returns the content area for this Chatbot instance. * * @return The content area for this Chatbot instance. */ public String getContent() { return content; } /** * Getter method for the memesList object. * * @return The reference to the meme list. */ public ArrayList<String> getMemesList() { return null; } /** * Getter method for the politicalTopicList object. * * @return The reference to the political topic list. */ public ArrayList<String> getPoliticalTopicList() { return null; } /** * Updates the content area for this Chatbot instance. * * @param content * The updated value for the content area. */ public void setContent(String content) { } }
RanchBean/ChatBot-1
src/chat/model/Chatbot.java
1,802
/** * Checks the length of the supplied string. Returns false if the supplied String is empty or null, otherwise returns true. * * @param currentInput * @return A true or false based on the length of the supplied String. */
block_comment
en
false
1,520
55
1,802
53
1,767
59
1,802
53
2,149
60
false
false
false
false
false
true