file_id
stringlengths 4
9
| content
stringlengths 41
35k
| repo
stringlengths 7
113
| path
stringlengths 5
90
| token_length
int64 15
4.07k
| original_comment
stringlengths 3
9.88k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | excluded
bool 2
classes |
---|---|---|---|---|---|---|---|---|
220076_3 | /* $Header: tkmain_8/tkaq/src/aqjmsdemo13.java /main/2 2017/10/28 07:02:00 ravkotha Exp $ */
/* Copyright (c) 2012, 2017, Oracle and/or its affiliates.
All rights reserved.*/
/*
DESCRIPTION
Sample demo for Message Selectors with 12.1 sharded queue
This demo does the following:
-- Setup a single consumer sharded queue
-- Create a message producer and send text messages by setting message properties
-- Create message consumers for the sharded queue using a message selector and receive messages
NOTES
The instructions for setting up and running this demo is available in aqjmsREADME.txt.
MODIFIED (MM/DD/YY)
ravkotha 09/05/17 - fix for 26024347
pyeleswa 07/13/16 - move aq demo files from rdbms/demo to test/tkaq/src
mpkrishn 01/08/13 - Changes to run in CDB mode, getting JDBC_URL from env
pabhat 10/05/12 - Demo for Message Selectors
pabhat 10/05/12 - Creation
*/
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import oracle.jms.AQjmsDestination;
import oracle.jms.AQjmsFactory;
import oracle.jms.AQjmsSession;
import java.util.Properties;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @version $Header: tkmain_8/tkaq/src/aqjmsdemo13.java /main/2 2017/10/28 07:02:00 ravkotha Exp $
* @author pabhat
* @since release specific (what release of product did this appear in)
*/
public class aqjmsdemo13 {
public static void main(String args[]) {
Console console = System.console();
console.printf("Enter Jms User: ");
String username = console.readLine();
console.printf("Enter Jms user password: ");
char[] passwordChars = console.readPassword();
String password = new String(passwordChars);
String queueName = "selectordemo";
QueueSession queueSession = null;
QueueConnectionFactory queueConnectionFactory = null;
QueueConnection queueConnection = null;
try {
String myjdbcURL = System.getProperty("JDBC_URL");
if (myjdbcURL == null )
System.out.println("The system property JDBC_URL has not been set, Usage:java -DJDBC_URL=xxx filename ");
else {
Properties myProperties = new Properties();
myProperties.put("user", username);
myProperties.put("password", password);
queueConnectionFactory = AQjmsFactory.getQueueConnectionFactory(myjdbcURL, myProperties);
queueConnection = queueConnectionFactory.createQueueConnection(username,password);
/* Create a Queue Session */
queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
queueConnection.start();
setupShardedQueue(queueSession, queueName);
performJmsOperations(queueSession, queueName,username);
}
} catch (Exception exception) {
System.out.println("Exception-1: " + exception);
exception.printStackTrace();
} finally {
try {
queueSession.close();
queueConnection.close();
} catch (Exception exc) {
exc.printStackTrace();
}
}
System.out.println("\nEnd of Demo aqjmsdemo13.");
}
/**
* Create and start a sharded queue
*
* @param queueSession QueueSession
* @param queueName Queue Name
* @throws Exception
*/
public static void setupShardedQueue(QueueSession queueSession,
String queueName) throws Exception {
Queue queue;
try {
System.out.println("Creating the Sharded Queue " + queueName + "...");
queue = (Queue) ((AQjmsSession) queueSession).createJMSShardedQueue(queueName, false);
/* Start the newly created queue */
System.out.println("\nStarting the Sharded Queue " + queueName + "...");
((AQjmsDestination) queue).start(queueSession, true, true);
System.out.println("\nsetupShardedQueue completed successfully.");
} catch (Exception exception) {
System.out.println("Error in setupShardedQueue: " + exception);
throw exception;
}
}
/**
* Perform basic JMS operations on the single consumer sharded queue, by creating message consumers
* using message selectors.
*
* Note that, there is no matching selector for the first message sent to the queue in the example
* below and is not consumed by any of the consumers.
*
* @param queueSession Queue Session
* @param queueName Queue Name
*/
public static void performJmsOperations(QueueSession queueSession, String queueName,String user) {
try {
Queue queue = (Queue) ((AQjmsSession) queueSession).getQueue(user, queueName);
MessageProducer producer = queueSession.createProducer(queue);
System.out.println("\nSending 5 messages of type TextMessage ...");
TextMessage textMessage = queueSession.createTextMessage();
textMessage = queueSession.createTextMessage();
textMessage.setText("This is the first message");
producer.send(textMessage);
textMessage = queueSession.createTextMessage();
textMessage.setJMSType("test");
textMessage.setBooleanProperty("demoBooleanProperty", true);
textMessage.setStringProperty("color", "white");
textMessage.setIntProperty("make", 2012);
textMessage.setText("This is the second message");
producer.send(textMessage);
textMessage = queueSession.createTextMessage();
textMessage.setBooleanProperty("demoBooleanProperty", true);
textMessage.setJMSType("foo");
textMessage.setStringProperty("color", "red");
textMessage.setIntProperty("make", 2012);
textMessage.setText("This is the third message");
producer.send(textMessage);
textMessage = queueSession.createTextMessage();
textMessage.setBooleanProperty("demoBooleanProperty", true);
textMessage.setJMSType("bar");
textMessage.setStringProperty("color", "blue");
textMessage.setIntProperty("make", 2011);
textMessage.setText("This is the fourth message");
producer.send(textMessage);
textMessage = queueSession.createTextMessage();
textMessage.setBooleanProperty("demoBooleanProperty", false);
textMessage.setJMSType("_foo%bar");
textMessage.setStringProperty("color", "silver");
textMessage.setIntProperty("make", 2012);
textMessage.setText("This is the fifth message");
producer.send(textMessage);
System.out.println("\nFinished sending all the 5 messages of type TextMessage ...");
producer.close();
TextMessage receivedMessage = null;
// For the demonstration of Message Selectos, we will create the consumer and receive the messages sequentially.
// This consumer will get third and fourth message
String messageSelector = "demoBooleanProperty=TRUE AND JMSType IN ('foo','bar')";
MessageConsumer firstConsumer = queueSession.createConsumer(queue, messageSelector);
while (true) {
receivedMessage = (TextMessage) firstConsumer.receive(3000);
if (receivedMessage == null) {
break;
} else {
System.out.println("\nReceived demoBooleanProperty : " + receivedMessage.getBooleanProperty("demoBooleanProperty"));
System.out.println("Received getJMSType : " + receivedMessage.getJMSType());
System.out.println("Received color : " + receivedMessage.getStringProperty("color"));
System.out.println("Received make : " + receivedMessage.getIntProperty("make"));
System.out.println("Received message data : " + receivedMessage.getText());
}
}
// This consumer will get only fifth message
messageSelector = "JMSType LIKE 'A_fo_A%b%' ESCAPE 'A'";
MessageConsumer secondConsumer = queueSession.createConsumer(queue, messageSelector);
while (true) {
receivedMessage = (TextMessage) secondConsumer.receive(3000);
if (receivedMessage == null) {
break;
} else {
System.out.println("\nReceived demoBooleanProperty : " + receivedMessage.getBooleanProperty("demoBooleanProperty"));
System.out.println("Received getJMSType : " + receivedMessage.getJMSType());
System.out.println("Received color : " + receivedMessage.getStringProperty("color"));
System.out.println("Received make : " + receivedMessage.getIntProperty("make"));
System.out.println("Received message data : " + receivedMessage.getText());
}
}
// This consumer will get only second message
messageSelector = "JMSType = 'test' AND color = 'white' AND make >= 1200";
MessageConsumer thirdConsumer = queueSession.createConsumer(queue, messageSelector);
while (true) {
receivedMessage = (TextMessage) thirdConsumer.receive(3000);
if (receivedMessage == null) {
break;
} else {
System.out.println("\nReceived demoBooleanProperty " + receivedMessage.getBooleanProperty("demoBooleanProperty"));
System.out.println("Received getJMSType " + receivedMessage.getJMSType());
System.out.println("Received color " + receivedMessage.getStringProperty("color"));
System.out.println("Received make " + receivedMessage.getIntProperty("make"));
System.out.println("Received message data : " + receivedMessage.getText());
}
}
// Stop the queue
((AQjmsDestination) queue).stop(queueSession, true, true, true);
System.out.println("\nQueue stopped successfully.");
// Drop the queue created by the demo.
((AQjmsDestination) queue).drop(queueSession);
System.out.println("\nQueue dropped successfully.");
// Close the consumers.
firstConsumer.close();
secondConsumer.close();
thirdConsumer.close();
} catch (Exception e) {
System.out.println("Error in performJmsOperations: " + e);
}
}
}
| sgoil2019/AQExamples | jms/aqjmsdemo13.java | 2,450 | /**
* @version $Header: tkmain_8/tkaq/src/aqjmsdemo13.java /main/2 2017/10/28 07:02:00 ravkotha Exp $
* @author pabhat
* @since release specific (what release of product did this appear in)
*/ | block_comment | en | 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 |
220926_1 | package model;
//
// Client Java pour communiquer avec le Serveur C++
// eric lecolinet - telecom paristech - 2015
//
import java.util.List;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Arrays;
public class Client
{
private Socket sock;
private BufferedReader input;
private BufferedWriter output;
private static final String DEFAULT_SAVE_PATH = "controller/controllerState.txt";
public static void printFormated (String str) {
System.out.println(str.replaceAll(";", "\n"));
}
///
/// Initialise la connexion.
/// Renvoie une exception en cas d'erreur.
///
public Client(String host, int port) throws UnknownHostException, IOException {
try {
sock = new java.net.Socket(host, port);
}
catch (java.net.UnknownHostException e) {
System.err.println("Client: Couldn't find host "+host+":"+port);
throw e;
}
catch (java.io.IOException e) {
System.err.println("Client: Couldn't reach host "+host+":"+port);
throw e;
}
try {
input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
output = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
}
catch (java.io.IOException e) {
System.err.println("Client: Couldn't open input or output streams");
throw e;
}
}
///
/// Envoie une requete au server et retourne sa reponse.
/// Noter que la methode bloque si le serveur ne repond pas.
///
public String send(String request) {
// Envoyer la requete au serveur
try {
System.out.println("\n--- Sending Request ---");
System.out.println(request);
request += "\n"; // ajouter le separateur de lignes
output.write(request, 0, request.length());
output.flush();
}
catch (java.io.IOException e) {
System.err.println("Client: Couldn't send message: " + e);
return null;
}
// Recuperer le resultat envoye par le serveur
try {
String answer = input.readLine().replaceAll(";", "\n");
System.out.println("\n--- Received Response ---");
System.out.println(answer);
return answer;
}
catch (java.io.IOException e) {
System.err.println("Client: Couldn't receive message: " + e);
return null;
}
}
///
/// Implementation des requetes du client
///
public List<String> fetchMultimediaList() {
String answer = send("FetchMultimediaList");
List<String> list = new ArrayList<>(Arrays.asList(answer.replaceAll("\t", "").split("\n")));
list.remove(0);
return list;
}
public List<String> fetchGroupList() {
String answer = send("FetchGroupList");
List<String> list = new ArrayList<>(Arrays.asList(answer.replaceAll("\t", "").split("\n")));
list.remove(0);
return list;
}
public String fetchMultimedia(String multimedia) {
return removeFirstWord(send("FetchMultimedia " + multimedia));
}
public List<String> fetchGroup(String multimedia) {
String answer = send("FetchGroup " + multimedia);
List<String> list = new ArrayList<>(Arrays.asList(answer.split("\n")));
list.remove(0);
return list;
}
public void playMultimedia(String multimedia) {
send("PlayMultimedia " + multimedia);
}
public void deleteMultimedia(String multimedia) {
send("RemoveMultimedia " + multimedia);
}
public void deleteGroup(String group) {
send("RemoveGroup " + group);
}
public void deleteMultimediaFromGroup(String multimedia, String group) {
send("RemoveMultimediaFromGroup [" + multimedia + "] [" + group + "]");
}
public void addMultimediaToGroup(String multimedia, String group) {
send("AddMultimediaToGroup [" + multimedia + "] [" + group + "]");
}
public void createGroup(String group) {
send("AddGroup " + group);
}
public void createFilm(String name, String path, String duration, String chapterNumber, String[] chapterDurations) {
String request = "AddFilm [" + name + "] " + path + " " + duration + " " + chapterNumber;
for (String chapterDuration : chapterDurations) {
request += " " + chapterDuration;
}
send(request);
}
public void createImage(String name, String path, String width, String height) {
send("AddImage [" + name + "] " + path + " " + width + " " + height);
}
public void createVideo(String name, String path, int duration) {
send("AddVideo [" + name + "] " + path + " " + duration);
}
public void close() {
try {
sock.close();
}
catch (java.io.IOException e) {
System.err.println("Client: Couldn't close socket");
}
}
public String saveState (String path) {
if (path == null || path.isEmpty())
return send("SaveControllerState " + DEFAULT_SAVE_PATH);
else
return send("SaveControllerState " + path);
}
public String loadState (String path) {
if (path == null || path.isEmpty())
return send("LoadControllerState " + DEFAULT_SAVE_PATH);
else
return send("LoadControllerState " + path);
}
private String removeFirstWord(String str) {
if (str == null || str.isEmpty()) {
return "";
}
int index = str.indexOf(" ");
if (index == -1) { // Single word
return "";
}
return str.substring(index + 1);
}
}
| adrien-gtd/Multimedia-controller | swing/model/Client.java | 1,397 | // Client Java pour communiquer avec le Serveur C++ | line_comment | en | true |
221056_6 | class Solution {
public int maxProfit(int[] prices) {
int hold1 = Integer.MIN_VALUE, hold2 = Integer.MIN_VALUE;
int release1 = 0, release2 = 0;
for(int i:prices){ // Assume we only have 0 money at first
release2 = Math.max(release2, hold2+i); // The maximum if we've just sold 2nd stock so far.
hold2 = Math.max(hold2, release1-i); // The maximum if we've just buy 2nd stock so far.
release1 = Math.max(release1, hold1+i); // The maximum if we've just sold 1nd stock so far.
hold1 = Math.max(hold1, -i); // The maximum if we've just buy 1st stock so far.
}
return release2; ///Since release1 is initiated as 0, so release2 will always higher than release1.
}
}
/*
you can have O(n) sol..
*/
| higsyuhing/leetcode_hard | 123.java | 245 | /*
you can have O(n) sol..
*/ | block_comment | en | true |
221168_0 | /**
* \file WznmQFilList.h
* Java API code for record of table TblWznmQFilList
* \copyright (C) 2018-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
package apiwznm;
import org.w3c.dom.*;
import sbecore.*;
public class WznmQFilList {
public WznmQFilList(
int jnum
, String stubGrp
, String stubOwn
, String Filename
, String srefRefIxVTbl
, String titRefIxVTbl
, String stubRefUref
, String osrefKContent
, String titOsrefKContent
, String srefKMimetype
, String titSrefKMimetype
, int Size
) {
this.jnum = jnum;
this.stubGrp = stubGrp;
this.stubOwn = stubOwn;
this.Filename = Filename;
this.srefRefIxVTbl = srefRefIxVTbl;
this.titRefIxVTbl = titRefIxVTbl;
this.stubRefUref = stubRefUref;
this.osrefKContent = osrefKContent;
this.titOsrefKContent = titOsrefKContent;
this.srefKMimetype = srefKMimetype;
this.titSrefKMimetype = titSrefKMimetype;
this.Size = Size;
};
public int jnum;
public String stubGrp;
public String stubOwn;
public String Filename;
public String srefRefIxVTbl;
public String titRefIxVTbl;
public String stubRefUref;
public String osrefKContent;
public String titOsrefKContent;
public String srefKMimetype;
public String titSrefKMimetype;
public int Size;
public boolean readXML(
Document doc
, String basexpath
, boolean addbasetag
) {
if (addbasetag) basexpath = Xmlio.checkUclcXPaths(doc, basexpath, "WznmQFilList");
if (Xmlio.checkXPath(doc, basexpath)) {
stubGrp = Xmlio.extractStringUclc(doc, basexpath, "stubGrp", "grp", null, 0);
stubOwn = Xmlio.extractStringUclc(doc, basexpath, "stubOwn", "own", null, 0);
Filename = Xmlio.extractStringUclc(doc, basexpath, "Filename", "fnm", null, 0);
srefRefIxVTbl = Xmlio.extractStringUclc(doc, basexpath, "srefRefIxVTbl", "ret", null, 0);
titRefIxVTbl = Xmlio.extractStringUclc(doc, basexpath, "titRefIxVTbl", "ret2", null, 0);
stubRefUref = Xmlio.extractStringUclc(doc, basexpath, "stubRefUref", "reu", null, 0);
osrefKContent = Xmlio.extractStringUclc(doc, basexpath, "osrefKContent", "cnt", null, 0);
titOsrefKContent = Xmlio.extractStringUclc(doc, basexpath, "titOsrefKContent", "cnt2", null, 0);
srefKMimetype = Xmlio.extractStringUclc(doc, basexpath, "srefKMimetype", "mim", null, 0);
titSrefKMimetype = Xmlio.extractStringUclc(doc, basexpath, "titSrefKMimetype", "mim2", null, 0);
Size = Xmlio.extractIntegerUclc(doc, basexpath, "Size", "siz", null, 0);
return true;
};
return false;
};
};
| mpsitech/wznm-WhizniumSBE | japiwznm/WznmQFilList.java | 993 | /**
* \file WznmQFilList.h
* Java API code for record of table TblWznmQFilList
* \copyright (C) 2018-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 5 Dec 2020
*/ | block_comment | en | 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 |
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 |
222094_4 | import java.util.*;
public class Main {
static int N, M, min_ans = Integer.MAX_VALUE;
static int[][] map;
static List<Virus> viruses = new ArrayList<>();
static int cnt = 0;
static class Virus {
int y, x;
public Virus(int y, int x) {
this.y = y;
this.x = x;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
map = new int[N][N];
for(int i = 0 ; i < N ; i++) {
for(int j = 0 ; j < N ; j++) {
map[i][j] = sc.nextInt();
if(map[i][j] == 2) {
viruses.add(new Virus(i, j));
} else if(map[i][j] == 0)
cnt++;
}
}
//System.out.println("cnt = " + cnt);
if(cnt == 0) {
System.out.println(0);
return;
}
select_virus(0, new StringBuilder());
if(min_ans == Integer.MAX_VALUE)
System.out.println(-1);
else
System.out.println(min_ans-1);
}
private static void select_virus(int idx, StringBuilder sb) {
if(sb.length() == M) {
bfs(sb.toString());
}
for(int i = idx ; i < viruses.size() ; i++) {
sb.append(i);
select_virus(i+1, sb);
sb.deleteCharAt(sb.length() - 1);
}
}
private static void bfs(String start_virus) {
int[][] dir = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
int[][] visited = new int[N][N];
Queue<Virus> q = new ArrayDeque<>();
//System.out.println(start_virus);
for(int i = 0 ; i < M ; i++) {
Virus virus = viruses.get(start_virus.charAt(i) - '0');
q.add(virus);
visited[virus.y][virus.x] = 1;
//System.out.println(virus.y + " " + virus.x);
}
//System.out.println();
int local_ans = 0;
int local_cnt = 0;
while (!q.isEmpty()) {
Virus cur = q.poll();
for(int i = 0 ; i < 4 ; i++) {
int ny = cur.y + dir[i][0];
int nx = cur.x + dir[i][1];
if(nx < 0 || ny < 0 || nx >= N || ny >= N) continue;
if(visited[ny][nx] == 0 && (map[ny][nx] == 0 || map[ny][nx] == 2)) {
if(map[ny][nx] == 0) {
local_cnt++;
if(local_cnt == cnt) {
min_ans = Math.min(visited[cur.y][cur.x] + 1, min_ans);
//System.out.println(min_ans);
return ;
}
}
visited[ny][nx] = visited[cur.y][cur.x] + 1;
q.add(new Virus(ny, nx));
}
}
}
}
} | YongBonJeon/CodingTest | BOJ/17142/17142.java | 850 | //System.out.println(min_ans); | line_comment | en | true |
223038_6 | import java.util.Random;
/**
* Representa um dado de 6 lados
*/
public class Dado {
/**
* Constante estática que define a quantidade de lados do dado
*/
private final static int MAXLADO = 6;
/**
* Vetor que representa os lados do dado
*/
private final int[] LADOS;
/**
* Variável que armazena o último valor retirado no dado
* */
private int ultimoValor;
/**
* Inicializa cada lado com seu número correspondente
*/
public Dado() {
LADOS = new int[Dado.MAXLADO];
for(int i = 0; i < Dado.MAXLADO; i++) {
LADOS[i] = i+1;
}
}
/**
* Simula o rolamento do dado. Guarda o resultado em ultimoValor para posterior utilização
* @return valor aleatório do resultado do rolamento do dado
*/
public int rolar() {
Random lancamento = new Random();
ultimoValor = LADOS[lancamento.nextInt(Dado.MAXLADO)];
return ultimoValor;
}
/**
* Getter do último valor do lançamento do Dado
* @return ultimo valor do lançamento do dado
*/
public int getUltimoValor() {
return ultimoValor;
}
}
| rafaelbarbeta/Monopoly | Dado.java | 337 | /**
* Getter do último valor do lançamento do Dado
* @return ultimo valor do lançamento do dado
*/ | block_comment | en | true |
223233_0 | /*******************************************************************************
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package org.worldgrower.gui.music;
import java.util.HashMap;
import java.util.Map;
public class SoundIdReader {
private SoundOutput soundOutput;
private boolean enabled;
private final Map<SoundIds, Sound> sounds = new HashMap<>();
private void initialize() throws SoundException {
readSound(SoundIds.CUT_WOOD, "/sound/workshop - wood clap8bit.wav.gz");
readSound(SoundIds.MINE, "/sound/workshop - metal tapping8bit.wav.gz");
readSound(SoundIds.FLAMES, "/sound/flames8bit.wav.gz");
readSound(SoundIds.FROST, "/sound/frost8bit.wav.gz");
readSound(SoundIds.SHOCK, "/sound/shock8bit.wav.gz");
readSound(SoundIds.TELEPORT, "/sound/teleport8bit.wav.gz");
readSound(SoundIds.WATER, "/sound/waterspell8bit.wav.gz");
readSound(SoundIds.EAT, "/sound/eating8bit.wav.gz");
readSound(SoundIds.SWING, "/sound/swing8bit.wav.gz");
readSound(SoundIds.BOW, "/sound/bow8bit.wav.gz");
readSound(SoundIds.BUILD_WOODEN_BUILDING, "/sound/workshop - wood hammering8bit.wav.gz");
readSound(SoundIds.BUILD_STONE_BUILDING, "/sound/workshop - wood on concrete8bit.wav.gz");
readSound(SoundIds.SMITH, "/sound/smith18bit.wav.gz");
readSound(SoundIds.PAPER, "/sound/scroll8bit.wav.gz");
readSound(SoundIds.DARKNESS, "/sound/darkness8bit.wav.gz");
readSound(SoundIds.CURSE, "/sound/cursespell8bit.wav.gz");
readSound(SoundIds.ALCHEMIST, "/sound/alchemist18bit.wav.gz");
readSound(SoundIds.DRINK, "/sound/fountain8bit.wav.gz");
readSound(SoundIds.MAGIC1, "/sound/magical_18bit.wav.gz");
readSound(SoundIds.MAGIC3, "/sound/magical_38bit.wav.gz");
readSound(SoundIds.MAGIC6, "/sound/magical_68bit.wav.gz");
readSound(SoundIds.MAGIC7, "/sound/magical_78bit.wav.gz");
readSound(SoundIds.KNIFE_SLICE, "/sound/knifeSlice8bit.wav.gz");
readSound(SoundIds.HANDLE_COINS, "/sound/handleCoins8bit.wav.gz");
readSound(SoundIds.BOOK_FLIP, "/sound/bookFlip18bit.wav.gz");
readSound(SoundIds.CLICK, "/sound/click18bit.wav.gz");
readSound(SoundIds.ROLLOVER, "/sound/rollover18bit.wav.gz");
readSound(SoundIds.COW, "/sound/Mudchute_cow_18bit.wav.gz");
readSound(SoundIds.HEALING, "/sound/Healing Full8bit.wav.gz");
readSound(SoundIds.WIND, "/sound/Wind effects 58bit.wav.gz");
readSound(SoundIds.CLOTH, "/sound/cloth8bit.wav.gz");
readSound(SoundIds.CLATTER, "/sound/workshop - clatter8bit.wav.gz");
readSound(SoundIds.BLESSING2, "/sound/blessing28bit.wav.gz");
readSound(SoundIds.CURSE_SPELL, "/sound/curse8bit.wav.gz");
readSound(SoundIds.FORCE_PUSH, "/sound/forcepush8bit.wav.gz");
readSound(SoundIds.FORCE_PULSE, "/sound/forcepulse8bit.wav.gz");
readSound(SoundIds.CURSE5, "/sound/curse58bit.wav.gz");
readSound(SoundIds.CURSE3, "/sound/curse38bit.wav.gz");
readSound(SoundIds.ZAP2, "/sound/zap28bit.wav.gz");
readSound(SoundIds.ENCHANT, "/sound/enchant8bit.wav.gz");
readSound(SoundIds.ENCHANT2, "/sound/enchant28bit.wav.gz");
readSound(SoundIds.DISENCHANT, "/sound/disenchant8bit.wav.gz");
readSound(SoundIds.RUSTLE01, "/sound/rustle018bit.wav.gz");
readSound(SoundIds.CONFUSION, "/sound/confusion8bit.wav.gz");
readSound(SoundIds.ZAP2G, "/sound/zap2g8bit.wav.gz");
readSound(SoundIds.RANDOM1, "/sound/random18bit.wav.gz");
readSound(SoundIds.HANDLE_SMALL_LEATHER, "/sound/handleSmallLeather8bit.wav.gz");
readSound(SoundIds.MOVE, "/sound/full steps stereo8bit.wav.gz");
readSound(SoundIds.RUSTLE3, "/sound/rustle038bit.wav.gz");
readSound(SoundIds.KISS, "/sound/179303__gflower__perfect-kiss8bit.wav.gz");
readSound(SoundIds.DYING, "/sound/Human_DyingBreath_018bit.wav.gz");
readSound(SoundIds.SHOVEL, "/sound/qubodupshovelSpell18bit.wav.gz");
readSound(SoundIds.POISON, "/sound/219566__qubodup__poison-spell-magic8bit.wav.gz");
readSound(SoundIds.SEX, "/sound/182016__safadancer__sex-groaning-18bit.wav.gz");
readSound(SoundIds.RELIGIOUS, "/sound/135489__felix-blume__bells-and-religious-hymn8bit.wav.gz");
readSound(SoundIds.SWISH, "/sound/swish-98bit.wav.gz");
readSound(SoundIds.METAL_SMALL1, "/sound/metal-small18bit.wav.gz");
readSound(SoundIds.DOOR_OPEN, "/sound/doorOpen_18bit.wav.gz");
readSound(SoundIds.BLESSING, "/sound/blessing8bit.wav.gz");
readSound(SoundIds.PICKLOCK, "/sound/picklock.wav.gz");
readSound(SoundIds.DOOR_CLOSE, "/sound/doorClose_4.wav.gz");
readSound(SoundIds.MAGIC_SHIELD, "/sound/magicshield8bit.wav.gz");
readSound(SoundIds.DROP_LEATHER, "/sound/dropLeather.wav.gz");
readSound(SoundIds.CURSE4, "/sound/curse48bit.wav.gz");
readSound(SoundIds.MAGIC_DROP, "/sound/magicdrop8bit.wav.gz");
readSound(SoundIds.PLANT_GROWTH, "/sound/qubodupGrowthSpell01_8bit.wav.gz");
readSound(SoundIds.CHICKEN, "/sound/192035__dann93__chickens.wav.gz");
readSound(SoundIds.COOK, "/sound/cooking_with_cover_01.wav.gz");
readSound(SoundIds.SAW, "/sound/402557__anim4tion564__saw.wav.gz");
}
public SoundIdReader(SoundOutput soundOutput, boolean enabled) throws SoundException {
this.soundOutput = soundOutput;
this.enabled = enabled;
if (enabled) {
initialize();
}
}
private void readSound(SoundIds soundIds, String path) throws SoundException {
Sound audioClip = new Sound(path);
sounds.put(soundIds, audioClip);
}
public void playSoundEffect(SoundIds soundIds) {
if (enabled) {
Sound sound = sounds.get(soundIds);
sound.play();
}
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
try {
initialize();
} catch (SoundException e) {
throw new IllegalStateException(e);
}
}
public boolean isEnabled() {
return enabled;
}
}
| WorldGrower/WorldGrower | src/org/worldgrower/gui/music/SoundIdReader.java | 2,292 | /*******************************************************************************
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/ | block_comment | en | true |
223547_4 | package main;
import database.DBConnection;
import database.DBUtil;
import infomation.BaseInfo;
import json.UploadInfoModel;
import upload.InfoActual;
import upload.InfoSetting;
/**
* 按照上传数据的json格式要求来填充数据
*
* @author Kevin-
*
*/
public class InfoPadding {
public static UploadInfoModel paddingInfo(DBConnection db) {
InfoSetting infoSetting = new InfoSetting();
// 此处为默认值,暂不接受用户自行设置
infoSetting.setCalculation_setting(100);
infoSetting.setDisk_setting(1000);
infoSetting.setBandwidth_setting(5);
InfoActual infoActual = new InfoActual();
// 此处检测该进程的实际值
infoActual.setCalculation_actual(DBUtil.calCalculation(db));
infoActual.setDisk_actual(DBUtil.calDiskSize(db));
infoActual.setBandwidth_actual(DBUtil.calBandwidth(db));
infoActual.setOnlineTime(DBUtil.calOnlineTime(db));
UploadInfoModel uploadInfoModel = new UploadInfoModel();
// 按要求填充信息
uploadInfoModel.setInfoSetting(infoSetting);
uploadInfoModel.setInfoActual(infoActual);
//uploadInfoModel.setMacAddress("kong");
uploadInfoModel.setMacAddress(BaseInfo.getInstance().getMacAddress());
return uploadInfoModel;
}
}
| Kevin-miu/InformationGetter | src/main/InfoPadding.java | 356 | //uploadInfoModel.setMacAddress("kong"); | line_comment | en | true |
223779_1 | public class WateringPlants {
//2079. Watering Plants
//https://leetcode.com/problems/watering-plants/
//Initalize a counter to keep track the number of the steps needed.
//Initalize another variable to hold the max capacity.
//Iterate through the plants array.
//Subtract the capacity if there's enough water. If there isn't, increment the counter by the current index, refill capacity, and then increment the counter by the current index + 1.
//return the counter.
public int wateringPlants(int[] plants, int capacity) {
int currentCapacity = capacity;
int steps = 0;
for(int i = 0; i < plants.length; i++){
if(currentCapacity >= plants[i]){
currentCapacity -= plants[i];
steps++;
}else{
steps += i;
currentCapacity = capacity;
steps += (i + 1);
currentCapacity -= plants[i];
}
// System.out.println("Current Capacity: " + currentCapacity);
// System.out.println("Current Steps: " + steps);
}
return steps;
}
}
| kliewUS/practice_problems | WateringPlants.java | 271 | //https://leetcode.com/problems/watering-plants/ | line_comment | en | true |
223859_0 | import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Solution obj = new Solution();
ArrayList<Integer>a = new ArrayList<Integer>();
for(int i=0;i<n;i++)
{
int num = new Random().nextInt(n);
a.add(num);
}
Collections.sort(a);
for(int c:a){
System.out.print(c + " ");
}
System.out.println();
}
}
/*
Read the problem before submitting ....Check on Multiple testcases.
Leap of faith.....Leap of faith.....Leap of faith.....Leap of faith.....
Guardian angel...Guardian angel...Guardian angel...Guardian angel...Guardian angel..
*/
| knakul853/competitive_programming | java/Randomnumber.java | 206 | /*
Read the problem before submitting ....Check on Multiple testcases.
Leap of faith.....Leap of faith.....Leap of faith.....Leap of faith.....
Guardian angel...Guardian angel...Guardian angel...Guardian angel...Guardian angel..
*/ | block_comment | en | true |
223902_5 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package library;
import java.util.*;
import java.io.*;
/**
*
* @author Minahil Imtiaz
*/
abstract class Users {
// more attributes needed
private int user_id;
private String user_name;
private char gender;
Users() {
this.user_id = -1;
this.user_name = " ";
this.gender = '-';
}
Users(int user_id, String user_name, char gender) {
this.user_id = user_id;
this.user_name = user_name;
this.gender = gender;
}
public ArrayList<Books> SearchBookbyTitle(String title) {
// for (Books b : BooksList) {
// String titleofcurrentbook = b.GetTitle();
// if (titleofcurrentbook.contains(title) == true) {
// b.PrintInformation();
// } else {
// System.out.println("Sorry ! No record found \n");
//
// }
// }
ArrayList<Books> BooksList = new ArrayList<>();
dbConnectivity db = new dbConnectivity();
BooksList = db.SearchBookbyTitle(title);
// if (BooksList.isEmpty() == false) {
// for (Books b : BooksList) {
//
// b.PrintInformation();
// }
// } else {
// System.out.println("Sorry ! No record found \n");
//
// }
return BooksList;
}
public ArrayList<Books> SearchBookbySubject(String subject) {
ArrayList<Books> BooksList = new ArrayList<>();
dbConnectivity db = new dbConnectivity();
BooksList = db.SearchBookbySubject(subject);
// if (BooksList.isEmpty() == false) {
// for (Books b : BooksList) {
//
// b.PrintInformation();
// }
// } else {
// System.out.println("Sorry ! No record found \n");
//
// }
return BooksList;
}
public ArrayList<Books> SearchBookbyAuthor(String author) {
ArrayList<Books> BooksList = new ArrayList<>();
dbConnectivity db = new dbConnectivity();
BooksList = db.SearchBookbyAuthor(author);
return BooksList;
}
public int GetId() {
return this.user_id;
}
public String GetName() {
return this.user_name;
}
public char GetGender() {
return this.gender;
}
public void SetId(int id) {
this.user_id = id;
}
public void SetName(String name) {
this.user_name = name;
}
public void SetGender(char g) {
this.gender = g;
}
public String PrintInformation() {
String Resultant="Id: " + this.user_id+" "+"Name:" + this.user_name+" "+"Gender: " + this.gender+" ";
return Resultant;
}
void SetFineAmount(double fine)
{
dbConnectivity db= new dbConnectivity ();
db.SetFineAmount(user_id, fine);
}
boolean SetFineStatus(boolean status){
dbConnectivity db= new dbConnectivity ();
boolean result= db.SetFineStatus(user_id, status);
return result;
}
void UpdateLoanInfo(Loan L, int i ) {}
boolean GetFineStatus()
{
return true;
}
boolean AddLoanInfo(Loan Current_Loan)
{
return true;
}
abstract String ViewInformation(ArrayList<Loan> LoanLoanList, int user_id);
}
| SkylerWen/CPT304 | Users.java | 889 | // if (titleofcurrentbook.contains(title) == true) { | line_comment | en | true |
224245_3 | // $Id: BagPanel.java,v 1.2 2007-04-04 22:29:29 idgay Exp $
/* tab:4
* Copyright (c) 2007 Intel Corporation
* All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE
* file. If you do not find these files, copies can be found by writing to
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
* 94704. Attention: Intel License Inquiry.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* A GridBagLayout based panel with convenience methods for
* making various swing items. These methods also ensure a
* consistent appearance.
*
* @author David Gay
*/
public class BagPanel extends JPanel {
Font boldFont = new Font("Dialog", Font.BOLD, 12);
Font normalFont = new Font("Dialog", Font.PLAIN, 12);
GridBagLayout bag;
GridBagConstraints c;
/* Create a panel with a bag layout. Create some constraints are
users can modify prior to creating widgets - the current constraints
will be applied to all widgets created with makeXXX */
public BagPanel() {
bag = new GridBagLayout();
setLayout(bag);
c = new GridBagConstraints();
}
/* The makeXXX methods create XXX widgets, apply the current constraints
to them, and add them to this panel. The widget is returned in case
the creator needs to hang on to it. */
public JButton makeButton(String label, ActionListener action) {
JButton button = new JButton();
button.setText(label);
button.setFont(boldFont);
button.addActionListener(action);
bag.setConstraints(button, c);
add(button);
return button;
}
public JCheckBox makeCheckBox(String label, boolean selected) {
JCheckBox box = new JCheckBox(label, selected);
box.setFont(normalFont);
bag.setConstraints(box, c);
add(box);
return box;
}
public JLabel makeLabel(String txt, int alignment) {
JLabel label = new JLabel(txt, alignment);
label.setFont(boldFont);
bag.setConstraints(label, c);
add(label);
return label;
}
public JTextField makeTextField(int columns, ActionListener action) {
JTextField tf = new JTextField(columns);
tf.setFont(normalFont);
tf.setMaximumSize(tf.getPreferredSize());
tf.addActionListener(action);
bag.setConstraints(tf, c);
add(tf);
return tf;
}
public JSeparator makeSeparator(int axis) {
JSeparator sep = new JSeparator(axis);
bag.setConstraints(sep, c);
add(sep);
return sep;
}
}
| markushx/tinyos-arduino-MRF24J40MA | apps/AntiTheft/java/BagPanel.java | 695 | /* Create a panel with a bag layout. Create some constraints are
users can modify prior to creating widgets - the current constraints
will be applied to all widgets created with makeXXX */ | block_comment | en | true |
224481_6 | /**
* Perform a syntax check on a JavaScript file.
*/
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.Script;
import java.io.Reader;
import java.io.FileReader;
public class Jagged {
public static void main (String [] args) {
int good = 0;
int bad = 0;
Context cxt = Context.enter();
try {
/*
// Collect the arguments into a single string.
String s = "";
for (int i=0; i < args.length; i++) {
s += args[i];
}
*/
if (args.length == 0) {
System.out.println("Usage: PROG file1.js [file2.js [file3.js [...]]]");
}
boolean resp = false;
for (String name: args) {
resp = lintFile(name, cxt);
if (resp) ++good; else ++bad;
}
} finally {
// Exit from the context.
Context.exit();
}
String summary = String.format(
"Tests: %d, Successes: %d, Failures: %d",
good + bad,
good,
bad
);
System.out.println(summary);
}
/**
* Read each file and try to compile it.
*
* If compilation succeeds, this will silently return true.
*
* If the file cannot be loaded or loading/compiling fails, this will
* emit a message on System.out and then return false.
*/
public static boolean lintFile(String filename, Context cxt) {
FileReader f;
try {
f = new FileReader(filename);
}
catch (Exception e) {
System.out.println("Could not open " + filename + " :" + e.getMessage());
return false;
}
try {
Script s = cxt.compileReader(f, filename, 1, null);
}
catch (java.io.IOException ioe) {
System.out.println("Unexpected IO exception: " + ioe.getMessage());
return false;
}
catch (org.mozilla.javascript.EvaluatorException ee) {
//System.out.println("Script " + filename + " failed to compile: " + ee.getMessage());
String msg = String.format("%s (ln: %d, ch: %d): %s NEAR %s",
ee.sourceName(),
ee.lineNumber(),
ee.columnNumber(),
ee.details(),
diedOnThisChar(ee.lineSource(), ee.columnNumber())
);
System.out.println(msg);
System.out.println(ee.lineSource());
return false;
}
return true;
}
protected static String diedOnThisChar(String foo, int prob) {
int start = prob > 1 ? prob - 2 : prob;
int end = foo.length() > start + 9 ? start + 10 : foo.length() -1 ;
//Character theChar = foo.charAt(prob);
String icky = foo.substring(start, end);
//return String.format("Char %d in %s", Character.digit(theChar, Character.MAX_RADIX), icky);
return icky;
}
} | technosophos/Jagged | src/Jagged.java | 753 | //return String.format("Char %d in %s", Character.digit(theChar, Character.MAX_RADIX), icky); | line_comment | en | true |
224710_1 | package controllers;
import controllers.cms.Admin;
import models.cms.CMSPage;
import play.modules.search.Query;
import play.modules.search.Search;
import play.mvc.Http;
import java.util.List;
/**
* Controller that managed principal page of the site.
*/
public class Application extends AbstractController {
public final static int ITEM_PER_PAGE = 5;
public static final String MAP_RESULT_LIST = "result";
public static final String MAP_RESULT_NB = "nb";
/**
* Home page.
*/
public static void index() {
List<CMSPage> blogs = CMSPage.getLastests("blog",Boolean.TRUE, 3);
render(blogs);
}
/**
* Blog page.
*/
public static void blog() {
CMSPage page = CMSPage.getLastest("blog", Boolean.TRUE);
render("cms/blog.html", page);
}
/**
* Search action.
*/
public static void search(String search, Integer page) {
if (page == null) {
page = 1;
}
// default search
String query = search;
if(search == null || search.trim().length() == 0) {
query = "*:*";
}
query += " AND (template:'blog' OR template:'page')";
Query q = Search.search(query, CMSPage.class);
List<CMSPage> pages = q.page((page-1) * ITEM_PER_PAGE, ITEM_PER_PAGE).fetch();
Integer nbItems = q.count();
render(search, page, pages, nbItems);
}
/**
* Admin page.
*/
public static void admin(){
// check if it's an admin user
isAdminUser();
Admin.index("page");
}
/**
* Sitemap.xml
*/
public static void sitemap(){
List<CMSPage> pages = CMSPage.all().fetch();
response.contentType = "application/xml";
render(pages);
}
/**
* Robots.txt
*/
public static void robots(){
response.contentType = "text/plain; charset=" + Http.Response.current().encoding;
render("Application/robots.html");
}
} | sim51/bsimard-old | app/controllers/Application.java | 514 | /**
* Home page.
*/ | block_comment | en | true |
224712_3 | package servlet.client;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beans.TrackBean;
import da.DBManager;
/**
* Servlet implementation class ViewHelp
* @author = 1312040
*/
@WebServlet(name = "ViewHelp", urlPatterns = { "/view_help" })
public class ViewSitemap extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ViewSitemap() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = getServletContext();
DBManager dbm = new DBManager(sc.getRealPath("/DBConfig.properties"));
String url = "/jsp/client/view_sitemap.jsp";
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
| kim-codes/Woove | src/servlet/client/ViewSitemap.java | 376 | /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/ | block_comment | en | 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 |
225573_16 | package ParticularTime;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import org.json.JSONObject;
import org.json.JSONArray;
public class Main {
static Logger LOGGER;
static {
try (FileInputStream ins = new FileInputStream("C:\\\\Users\\\\konop\\loog.cfg")) { //полный путь до файла с конфигами
LogManager.getLogManager().readConfiguration(ins);
LOGGER = Logger.getLogger(Main.class.getName());
} catch (Exception ignore) {
ignore.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
try {
LOGGER.log(Level.INFO, "Задается местоположение файла с входными данными");
System.out.println("Введите местоположение входного файла: "); // C:\\Users\\konop\\Downloads\\access.log
Scanner scanner = new Scanner(System.in);
// String strInputLocation = scanner.nextLine();
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\konop\\Downloads\\access.log"));//strInputLocation));
LOGGER.log(Level.INFO, "Задается местоположение файла с выходными данными");
System.out.println("Введите местоположение выходного файла: "); // fileResult.json
// String strOutputLocation = scanner.nextLine();
FileWriter myWriter = new FileWriter("fileResult.json");//strOutputLocation);
ArrayList<ParticularTime> arrTime = new ArrayList<>();
HashMap<String, Integer> mapIP = new HashMap<>();
LOGGER.log(Level.INFO, "Вводится время начала и конца периода");
int dBeg, dEnd, MBeg, MEnd, yBeg, yEnd, hBeg, hEnd, mBeg, mEnd, sBeg, sEnd;
System.out.println("Введите время начала и конца периода ");
String strBeg, strEnd;
strBeg = scanner.nextLine();
strEnd = scanner.nextLine();
// try{
if(strBeg.length() < 18)
return;
dBeg = Integer.parseInt(strBeg.substring(0, 2));
MBeg = Integer.parseInt(strBeg.substring(3, 5));
yBeg = Integer.parseInt(strBeg.substring(6, 10));
hBeg = Integer.parseInt(strBeg.substring(11, 13));
mBeg = Integer.parseInt(strBeg.substring(14, 16));
sBeg = Integer.parseInt(strBeg.substring(17, 19));
dEnd = Integer.parseInt(strEnd.substring(0, 2));
MEnd = Integer.parseInt(strEnd.substring(3, 5));
yEnd = Integer.parseInt(strEnd.substring(6, 10));
hEnd = Integer.parseInt(strEnd.substring(11, 13));
mEnd = Integer.parseInt(strEnd.substring(14, 16));
sEnd = Integer.parseInt(strEnd.substring(17, 19));
// } catch (NumberFormatException e){
// LOGGER.log(Level.WARNING, "Ошибка с данными начала и конца временного отрезка", e);
// }
System.out.println(dBeg + " " + MBeg + " " + yBeg + " " + hBeg + " " + mBeg + " " + sBeg);
System.out.println(" && & && & & &");
String line;
LOGGER.log(Level.INFO, "Считываются данные в файле из заданного временного промежутка");
int iterations = 0;
while ((line = reader.readLine()) != null) {
if (iterations > 0 && iterations % 1000 == 0) {
LOGGER.log(Level.INFO, "Считаны данные на первых " + iterations + " строках");
}
String timeStr = "", IPStr = "", HTTPStr = "", requestStr = "0";
for (int i = 10; ; i++) {
if (line.charAt(i) == '[') {
timeStr = line.substring(i, i + 28);
break;
}
}
String substringDay = timeStr.substring(1, 3);
int day = Integer.parseInt(substringDay);
int month;
int numToAdd = 0; // если June, July, Sept скокращаются до четырех букв, то numToAdd = 1
switch (timeStr.substring(4, 7)) {
case "Jan":
month = 1;
break;
case "Feb":
month = 2;
break;
case "Mar":
month = 3;
break;
case "Apr":
month = 4;
break;
case "May":
month = 5;
break;
case "Jun":
month = 6;
numToAdd = 1;
break;
case "Jul":
month = 7;
numToAdd = 1;
break;
case "Aug":
month = 8;
break;
case "Sep":
month = 9;
numToAdd = 1;
break;
case "Oct":
month = 10;
break;
case "Nov":
month = 11;
break;
case "Dec":
month = 12;
break;
default:
month = 0;
break;
}
if(month == 0)
LOGGER.log(Level.WARNING, "Неправильный формат месяца");
String substringYear = timeStr.substring(8 + numToAdd, 12 + numToAdd);
int year = Integer.parseInt(substringYear);
String substringHours = timeStr.substring(13 + numToAdd, 15 + numToAdd);
int hours = Integer.parseInt(substringHours);
String substringMinutes = timeStr.substring(16 + numToAdd, 18 + numToAdd);
int minutes = Integer.parseInt(substringMinutes);
String substringSeconds = timeStr.substring(19 + numToAdd, 21 + numToAdd);
int seconds = Integer.parseInt(substringSeconds);
String substringMonths = (month < 10 ? ("0" + String.valueOf(month)) : String.valueOf(month));
String timeStrMy = substringDay + "." + substringMonths + "." + substringYear + "-" +
substringHours + "." + substringMinutes + "." + substringSeconds;
// System.out.println(timeStrMy);
if((year < yBeg) || (year == yBeg && month < MBeg) || (year == yBeg && month == MBeg && day < dBeg) ||
(year == yBeg && month == MBeg && day == dBeg && hours < hBeg) ||
(year == yBeg && month == MBeg && day == dBeg && hours == hBeg && minutes < mBeg) ||
(year == yBeg && month == MBeg && day == dBeg && hours == hBeg && minutes == mBeg && seconds < sBeg)) {
continue;
}
else if((year > yEnd) || (year == yEnd && month > MEnd) || (year == yEnd && month == MEnd && day > dEnd) ||
(year == yEnd && month == MEnd && day == dEnd && hours > hEnd) ||
(year == yEnd && month == MEnd && day == dEnd && hours == hEnd && minutes > mEnd) ||
(year == yEnd && month == MEnd && day == dEnd && hours == hEnd && minutes == mEnd && seconds > sEnd)) {
break;
}
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i + 1) == ' ') {
IPStr = line.substring(0, i + 1);
int freq = 0;
if (mapIP.get(IPStr) != null) {
freq = mapIP.get(IPStr);
}
mapIP.put(IPStr, freq + 1);
break;
}
}
for (int i = 37; i < line.length(); i++) {
if (line.startsWith("HTTP", i)) {
HTTPStr = line.substring(i, i + 8);
break;
}
}
for (int i = 38; i < line.length(); i++) {
if (line.startsWith("\"", i)) {
requestStr = line.substring(i);
break;
}
}
if (arrTime.isEmpty() || !timeStrMy.equals(arrTime.getLast().time)) {
ParticularTime moment = new ParticularTime();
moment.time = timeStrMy;
moment.frequency = 1;
IPResults res = new IPResults();
res.IP_Number = IPStr;
res.IP_Frequency = 1;
res.HTTP_Version = HTTPStr;
res.IP_Requests.add(requestStr);
moment.listIP.add(res);
arrTime.add(moment);
} else {
ParticularTime moment = arrTime.getLast();
moment.frequency++;
boolean IP_inArray = false;
int it = -1;
for (int i = 0; i < moment.listIP.size(); i++) {
if (Objects.equals(moment.listIP.get(i).IP_Number, IPStr)) {
it = i;
IP_inArray = true;
break;
}
}
if (!IP_inArray) {
IPResults resForIP = new IPResults();
resForIP.IP_Number = IPStr;
resForIP.IP_Frequency = 1;
resForIP.HTTP_Version = HTTPStr;
resForIP.IP_Requests.add(requestStr);
moment.listIP.add(resForIP);
} else {
moment.listIP.get(it).IP_Frequency++;
moment.listIP.get(it).IP_Requests.add(requestStr);
}
}
iterations++;
}
LOGGER.log(Level.INFO, "Все данные из файла считаны");
LOGGER.log(Level.INFO, "Находим IP, встречающийся наиболее часто");
int mxAmount = 0;
String mxStringIP = "";
for (String i : mapIP.keySet()) {
if (mxAmount < mapIP.get(i)) {
mxAmount = mapIP.get(i);
mxStringIP = i;
}
}
JSONObject obj = new JSONObject();
obj.put("The most frequent: ", mxStringIP);
obj.put("Times: ", mxAmount);
//myWriter.write("Наиболее часто встречающийся: " + mxStringIP + " - " + mxAmount + " раз \n\n");
LOGGER.log(Level.INFO, "Производится вывод результатов");
//myWriter.write("{\n");
JSONArray arrOfJSON = new JSONArray();
for (ParticularTime pTime : arrTime) {
//myWriter.write(pTime.time + "\n " + pTime.frequency + "\n\n ");
//myWriter.write("\t{\n");
JSONArray arrOfTime = new JSONArray();
for (IPResults ipRes : pTime.listIP) {
JSONArray arrOfParticularIP = new JSONArray();
int i = 0;
//myWriter.write("\t " + ipRes.IP_Number + "\n\t " + ipRes.IP_Frequency + "\n\t " + ipRes.HTTP_Version + '\n' + "\t\t{" + '\n');
for (String it : ipRes.IP_Requests) {
i++;
JSONObject objIP = new JSONObject();
objIP.put(Integer.toString(i), it);
arrOfParticularIP.put(objIP);
//myWriter.write("\t\t " + it + "\n");
}
JSONObject objTime = new JSONObject();
objTime.put("IP number:", ipRes.IP_Number);
objTime.put("IP frequency:", ipRes.IP_Frequency);
objTime.put("IP HTTP version:", ipRes.HTTP_Version);
objTime.put("Array of requests:", arrOfParticularIP);
arrOfTime.put(objTime);
// myWriter.write('\n');
//myWriter.write("\t\t}\n");
}
JSONObject objTime = new JSONObject();
objTime.put("Time: ", pTime.time);
objTime.put("Frequency", pTime.frequency);
objTime.put("List of IP:", arrOfTime);
arrOfJSON.put(objTime);
//myWriter.write("\t}\n");
}
obj.put("Result: ", arrOfJSON);
//System.out.println(obj);
myWriter.write(obj.toString());
myWriter.close();
reader.close();
LOGGER.log(Level.INFO, "Работа завершена");
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Ошибка на этом этапе", e);
}
}
}
/*
06.03.2024-00.00.02
06.03.2024-04.01.30
*/
| Arsen1y24/CIIR_Proj_public | Main.java | 3,260 | //myWriter.write("\t{\n");
| line_comment | en | 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 |
226935_0 | /**
* @ File name: PlasticBottle.java
* @ Author1: Danilo Silva 113384
* @ Author2: Tomás Fernandes 112981
* @ Modified time: 2024-03-18 16:02:20
*/
package lab05.V_2;
public class PlasticBottle extends Container {
public PlasticBottle(Portion portion) {
super(portion);
}
}
| tomasf18/PDS-practical | lab05/V_2/PlasticBottle.java | 122 | /**
* @ File name: PlasticBottle.java
* @ Author1: Danilo Silva 113384
* @ Author2: Tomás Fernandes 112981
* @ Modified time: 2024-03-18 16:02:20
*/ | block_comment | en | true |
228273_1 |
public class Auto {
public static void main(String[] args) {
int x=10;
System.out.println("before converting to its corresponding object "+x);
Integer i= Integer.valueOf(x);// explicit conversion of primitive to wrapper
System.out.println("Explicit conversion of primitive to wrapper object "+i);
// Integer k= x; // compiler automatically converts since Java 5 onwards
// System.out.println("implicit conversion of primitive to wrapper object "+k);
String s= Integer.toString(x);
System.out.println("corresponding string value"+s);
}
}
| Ranikhet/Java | Auto.java | 142 | // Integer k= x; // compiler automatically converts since Java 5 onwards
| line_comment | en | true |
228501_0 | //Cut Risfa Zuhra - 235150401111044
import java.util.HashMap;
import java.util.Map;
public class Film {
private static final Map<String, Film> films = new HashMap<>();
private final String name;
private final String description;
private final double price;
private int stock;
public Film(String name, String description, double price, int stock) {
this.name = name;
this.description = description;
this.price = price;
this.stock = stock;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public double getPrice() {
return price;
}
public void setStock(int stock) {
this.stock = stock;
}
public int getStock() {
return stock;
}
public static void addFilm(String name, String description, double price, int stock) {
if (!films.containsKey(name)) {
Film newFilm = new Film(name, description, price, stock);
films.put(name, newFilm);
System.out.println("Film " + name + " berhasil ditambahkan.");
} else {
System.out.println("Film " + name + " sudah ada.");
}
}
public static Map<String, Film> getFilms() {
return films;
}
}
| faracutrisfa/uap-pemlan-dsi-2024 | src/Film.java | 335 | //Cut Risfa Zuhra - 235150401111044 | line_comment | en | 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 |
229368_0 | package myServer2;
/*
* AUTHOR : Min Gao
* Project1-Multi-Server Chat System
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class Client {
private String clientid;
private String room;
private String ownedRoom;
private String serverid;
private Socket clientSocket;
private BufferedWriter writer;
private BufferedReader reader;
private boolean isQuitRequestSend;
public Client(String clientid, String room, String serverid, Socket clientSocket) {
this.clientid = clientid;
this.room = room;
this.ownedRoom = null;
this.serverid = serverid;
this.clientSocket = clientSocket;
isQuitRequestSend = false;
try {
reader = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream(), "UTF-8"));
writer = new BufferedWriter(new OutputStreamWriter(
clientSocket.getOutputStream(), "UTF-8"));
}
catch (IOException e) {
e.printStackTrace();
}
}
public Client(String clientid, String room, String ownedRoom, String serverid, Socket clientSocket) {
this.clientid = clientid;
this.room = room;
this.ownedRoom = ownedRoom;
this.serverid = serverid;
this.clientSocket = clientSocket;
isQuitRequestSend = false;
try {
reader = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream(), "UTF-8"));
writer = new BufferedWriter(new OutputStreamWriter(
clientSocket.getOutputStream(), "UTF-8"));
}
catch (IOException e) {
e.printStackTrace();
}
}
public String getClientid() {
return clientid;
}
public String getRoom() {
return room;
}
public String getOwnedRoom() {
return ownedRoom;
}
public String getServerid() {
return serverid;
}
public Socket getClientSocket() {
return clientSocket;
}
public synchronized String read() throws IOException {
if (reader.ready()) {
// if (reader.readLine() != null) {
return reader.readLine();
}
return null;
}
public void write(String msg) {
try {
writer.write(msg);
writer.newLine();
writer.flush();
}
catch (IOException e) {
ClientMessage quitrequest = new ClientMessage(ServerMessage.quit().toJSONString(), clientid);
if (!isQuitRequestSend) {
System.out.println("A client is disconnected abnormally! Clientid: " + clientid);
MessageQueue.getInstance().add(quitrequest);
isQuitRequestSend = true;
}
//e.printStackTrace();
}
}
public synchronized void createRoom(String roomid) {
this.room = roomid;
this.ownedRoom = roomid;
}
public synchronized void changeRoom(String roomid) {
this.room = roomid;
}
public synchronized void deleteRoom() {
this.ownedRoom = null;
}
}
| HeavenMin/Multi-Server-Chat-System | Client.java | 815 | /*
* AUTHOR : Min Gao
* Project1-Multi-Server Chat System
*/ | block_comment | en | true |
230064_0 | package model;
import javafx.collections.ObservableList;
/**
* The storage class is responsible for temporary storage of the collections when reading and writing
* to their respective files. The Observable List is used to keep the TableViews of the fxml files
* updated.
*
*
* @author Jesus Nieto
* @author Travis Lawson
*
*/
public class Storage {
public static ObservableList<VHSCollection> allVHS;
public static ObservableList<CDCollection> allCD;
public static ObservableList<DVDCollection> allDVD;
public static ObservableList<MTGCollection> allMTG;
public static ObservableList<YuGiOhCollection> allYGO;
public static ObservableList<VinylCollection> allVinyl;
public static ObservableList<CassetteCollection> allCassettes;
public static ObservableList<LaserDiscCollection> allLD;
public static ObservableList<PokemonCardCollection> allPoke;
}
| UTSA-CS-3443/Collectibase | src/model/Storage.java | 228 | /**
* The storage class is responsible for temporary storage of the collections when reading and writing
* to their respective files. The Observable List is used to keep the TableViews of the fxml files
* updated.
*
*
* @author Jesus Nieto
* @author Travis Lawson
*
*/ | block_comment | en | true |
230247_11 |
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 {
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;
/**
* 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;
}
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);
}
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;
}
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;
}
}
| Rmpanga/UltimatePokerPlayer | src/Card.java | 2,005 | /**
* Obtain the rank of this card
* @return rank
*/ | block_comment | en | true |
230753_0 |
/**
* This class is part of the "World of NolsPotLex" application. "World of NolsPotLex" is a
* very simple, text based adventure game.
*
* A "Door" represents an exit in room of the scenery of the game.
*
* @author Alexandre Boursier & Nolan Potier
* @version 2011.10.25
*/
public class Door {
private String name;
private Boolean isLocked;
/**
* Creates a new door.
* @param name is the name of the door.
*/
public Door(String name){
this.name = name;
isLocked = false;
}
/**
* Locks or unlocks the door.
* @param value true if we want to lock the door, false otherwise.
*/
public void setLock(Boolean value){
isLocked = value;
}
/**
* Indicates whether the door is locked or not.
* @return true if the door is locked, false otherwise.
*/
public Boolean isLocked(){
return isLocked;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
| worthingtonse/Zuule | Door.java | 306 | /**
* This class is part of the "World of NolsPotLex" application. "World of NolsPotLex" is a
* very simple, text based adventure game.
*
* A "Door" represents an exit in room of the scenery of the game.
*
* @author Alexandre Boursier & Nolan Potier
* @version 2011.10.25
*/ | block_comment | en | true |
230844_2 | public class Tile {
int value;
/*
* creates a tile using the given value. False jokers are not included in this game.
*/
public Tile(int value) {
this.value = value;
}
/*
* TODO: should check if the given tile t and this tile have the same value
* return true if they are matching, false otherwise
*/
public boolean matchingTiles(Tile t) {
if(this.value == t.value){
return true;
}
return false;
}
/*
* TODO: should compare the order of these two tiles
* return 1 if given tile has smaller in value
* return 0 if they have the same value
* return -1 if the given tile has higher value
*/
public int compareTo(Tile t) {
if( this.value > t.value ){
return 1;
}
else if(this.value < t.value){
return -1;
}
else{
return 0;
}
}
/*
* TODO: should determine if this tile and given tile can form a chain together
* this method should check the difference in values of the two tiles
* should return true if the absoulute value of the difference is 1 (they can form a chain)
* otherwise, it should return false (they cannot form a chain)
*/
public boolean canFormChainWith(Tile t) {
int differenceBetweenTwo = Math.abs(t.value - this.value) ;
if(differenceBetweenTwo == 1){
return true;
}
else{return false;}
}
public String toString() {
return "" + value;
}
public int getValue() {
return value;
}
}
| ArcaMurat/Simplified-Okey-Game | Tile.java | 386 | /*
* TODO: should compare the order of these two tiles
* return 1 if given tile has smaller in value
* return 0 if they have the same value
* return -1 if the given tile has higher value
*/ | block_comment | en | true |
230884_4 | package com.company;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.*;
import org.json.simple.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
public static void main(String[] args) {
//JSON parser object to parse read file
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader("/home/yaadesh/Desktop/user_data.json"))
{
//Read JSON file
JSONObject userData = (JSONObject) jsonParser.parse(reader);
HashMap map = buildIndex(userData);
System.out.println(map);
String USER_A_KEY = "UserA";
String USER_B_KEY = "UserB";
String USER_C_KEY = "UserC";
String USER_D_KEY = "UserD";
//System.out.println(userData.get(USER_A_KEY));
// int similarityScore = compareTwoUsers(USER_A_KEY,USER_A_KEY,(JSONObject)userData,map);
//System.out.println("Similarity score is: "+similarityScore);
System.out.println(compareAllUsers(userData,map));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
public static HashMap compareAllUsers(JSONObject userDataJson,HashMap map){
Iterator i = userDataJson.keySet().iterator();
HashMap<String,Map<String,Integer>> similarityScoreMap = new HashMap<>();
while(i.hasNext()){
String iValue = (String) i.next();
Iterator j = userDataJson.keySet().iterator();
while(j.hasNext()){
String jValue = (String) j.next();
// System.out.println(iValue+jValue);
int simScore;
if(similarityScoreMap.containsKey(jValue))
if(similarityScoreMap.get(jValue).containsKey(iValue))
simScore = similarityScoreMap.get(jValue).get(iValue);
else
simScore = compareTwoUsers(iValue,jValue,userDataJson,map);
else
simScore = compareTwoUsers(iValue,jValue,userDataJson,map);
//simScore = compareTwoUsers(iValue,jValue,userDataJson,map);
if(!similarityScoreMap.containsKey(iValue)){
HashMap<String,Integer> temp = new HashMap<>();
temp.put(jValue,simScore);
similarityScoreMap.put(iValue,temp);
}
else{
similarityScoreMap.get(iValue).put(jValue,simScore);
}
}
}
return similarityScoreMap;
}
// Restructure data such that lookups are easier and scalable.
/*
/========= Spiderman {UserX,UserW}
Movie ======/ ========= Avengers {UserF}
|
Food ======= Pizza {UserX,UserY}
...
*/
public static HashMap buildIndex(JSONObject userDataJson){
HashMap<String,HashMap> map = initializeMap();
Iterator userIterator = userDataJson.keySet().iterator();
while(userIterator.hasNext()){
String userKey = (String)userIterator.next();
JSONObject userValue = (JSONObject) userDataJson.get(userKey);
Iterator categoryIterator = userValue.keySet().iterator();
while(categoryIterator.hasNext()){
String categoryKey = (String) categoryIterator.next();
//userValue.get(categoryKey)
JSONArray categoryArray = (JSONArray) userValue.get(categoryKey);
Iterator valueIterator = categoryArray.iterator();
while(valueIterator.hasNext()) {
String value = valueIterator.next().toString().toLowerCase();
if(!map.get(categoryKey).containsKey(value)){
HashSet<String> temp = new HashSet<>();
temp.add(userKey);
map.get(categoryKey).put(value,temp);
}
else{
HashSet<String> userSet = (HashSet<String>) map.get(categoryKey).get(value);
userSet.add(userKey);
map.get(categoryKey).put(value,userSet);
}
}
}
}
return map;
}
public static int compareTwoUsers(String userB, String userA, JSONObject userDataJson, HashMap<String,HashMap<String,HashSet>> map){
JSONObject jsonObjectUserA = (JSONObject) userDataJson.get(userA);
Iterator categoryIterator = jsonObjectUserA.keySet().iterator();
SimilarityScore similarityScore = new SimilarityScore();
while(categoryIterator.hasNext()){
String categoryKey = (String) categoryIterator.next();
JSONArray categoryArray = (JSONArray) jsonObjectUserA.get(categoryKey);
Iterator valueIterator = categoryArray.iterator();
while(valueIterator.hasNext()) {
String value = valueIterator.next().toString().toLowerCase();
if(map.get(categoryKey).get(value).contains(userB)){
switch(categoryKey){
case "sports":
similarityScore.addGroupACountAndTag();
break;
case "movie":
similarityScore.addGroupACountAndTag();
break;
case "food":
similarityScore.addGroupBCountAndTag();
break;
case "cities":
similarityScore.addGroupBCountAndTag();
break;
case "music":
similarityScore.addGroupCCountAndTag();
break;
case "books":
similarityScore.addGroupCCountAndTag();
break;
}
}
}
}
/*
Total 15 matching tags (at least 5 from group A) - 100%
4 group A tags or 14+ matching tags - 80%
2 group A tags or 5 group B tags or 12+ matching tags - 60%
1 group A tags or 3 group B tags or 10+ matching tags - 40%
1 group B tags or 5 group C tags or 8+ matching tags - 20%
less than 5 group C tags matching - 10%
no tags matching - 0%
*/
//System.out.println(similarityScore.getGroupACount());
//System.out.println(similarityScore.getGroupBCount());
//System.out.println(similarityScore.getGroupCCount());
//System.out.println(similarityScore.getMatchingTags());
if(similarityScore.getMatchingTags()==0)
similarityScore.setSimilarityScore(0);
else if(similarityScore.getMatchingTags()>=15 || similarityScore.getGroupACount()>=5)
similarityScore.setSimilarityScore(100);
else if(similarityScore.getMatchingTags()>=14 || similarityScore.getGroupACount()>=4)
similarityScore.setSimilarityScore(80);
else if(similarityScore.getMatchingTags()>=12 || similarityScore.getGroupACount()>=2 ||similarityScore.getGroupBCount() >=5)
similarityScore.setSimilarityScore(60);
else if(similarityScore.getMatchingTags()>=10 || similarityScore.getGroupACount()>=1 ||similarityScore.getGroupBCount() >=3)
similarityScore.setSimilarityScore(40);
else if(similarityScore.getMatchingTags()>=8 || similarityScore.getGroupBCount()>=1 || similarityScore.getGroupCCount()>=5)
similarityScore.setSimilarityScore(20);
else if( similarityScore.getGroupCCount()<=5 && similarityScore.getGroupCCount()>0)
similarityScore.setSimilarityScore(10);
return similarityScore.getSimilarityScore();
}
public static HashMap initializeMap(){
HashMap<String, HashMap> map = new HashMap<>();
map.put("movie",new HashMap());
map.put("cities",new HashMap());
map.put("food",new HashMap());
map.put("sports",new HashMap());
map.put("books",new HashMap());
map.put("music",new HashMap());
return map;
}
public static class SimilarityScore{
private int matchingTags=0;
private int groupACount=0;
private int groupBCount=0;
private int groupCCount=0;
private int similarityScore=-9999;
public int getGroupACount(){
return this.groupACount;
}
public int getGroupBCount(){
return this.groupBCount;
}
public int getGroupCCount(){
return this.groupCCount;
}
public int getMatchingTags(){
return this.matchingTags;
}
public void addGroupACountAndTag(){
this.groupACount++;
this.matchingTags++;
}
public void addGroupBCountAndTag(){
this.groupBCount++;
this.matchingTags++;
}
public void addGroupCCountAndTag(){
this.groupCCount++;
this.matchingTags++;
}
public void setSimilarityScore(int sim){
this.similarityScore = sim;
}
public int getSimilarityScore(){
return this.similarityScore;
}
}
}
| Yaadesh/Think42-Assignment | Main.java | 2,096 | //System.out.println("Similarity score is: "+similarityScore); | line_comment | en | true |
230941_4 | package pkg;
import java.io.*;
import java.util.*;
/*
The Facade class that acts as an Interface between the GUI and the underlying code.
Various instances of calling the code is commented below
author: Sahithya Cherukuri
scheru20
SER515-Design Patterns
PTBS
*/
public class Facade{
protected int userType;
protected Product theSelectedProduct;
private int nProductCategory;
protected Product[] theProductList;
protected Product[] theOfferingList;
protected Person thePerson;
protected UserInfoItem user = null;
PTBS pb;
Offering offer;
private LoadData ld;
Facade(){
ld = new LoadData();
offer = new Offering();
System.out.println("In Facade Class");
}
//Login has been implemented as a Facade functionality instead of creating the new task
public boolean login(){
UserInfoItem[] buyers = ld.getBuyers();
UserInfoItem[] sellers = ld.getSellers();
for(int i=0;i<buyers.length;i++){
if(buyers[i].getUserName().equals(user.getUserName())&&buyers[i].getPassword().equals(user.getPassword())){
userType=1;
thePerson = new Buyer();
return true;
}
}
for(int i=0;i<sellers.length;i++){
if(sellers[i].getUserName().equals(user.getUserName())&&sellers[i].getPassword().equals(user.getPassword())){
userType=0;
thePerson = new Seller();
return true;
}
}
return false;
}
// creates a local new file to add all the products the seller chooses to offer
public void addTrading(){
System.out.println("Offering added "+theSelectedProduct);
offer.createOffering(theSelectedProduct,user.getUserName());
}
// displays all seller offered products to the buyer to bid
public String viewTrading(String s){
//theOfferingList = new ProduceProductMenu().showMenu();
OfferingIterator oi = new OfferingIterator();
if(oi.hm.containsKey(s))
return oi.hm.get(s);
else return "No Offerings yet";
}
public void decideBidding(){
}
public void discussBidding(){
}
public void submitBidding(){
}
//Call this function to see all the Expired Offerings in the File.
public int remind(){
Trading t = new Trading();
ReminderVisitor rv = new ReminderVisitor();
rv.visitTrading(t);
return rv.expiredCount;
}
public void createUser(UserInfoItem userInfoItem){
this.user = userInfoItem;
}
public boolean createNewUser(String usertype, String userName, String pswd){
File addUser;
try{
if(usertype.equals("0")){
addUser = new File("src\\main\\resources\\SellerInfo.txt");
FileWriter fw = new FileWriter(addUser, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.newLine();
bw.append(userName+":"+pswd);
bw.close();
fw.close();
}
else if (usertype.equals("1")){
addUser = new File("src\\main\\resources\\BuyerInfo.txt");
FileWriter fw = new FileWriter(addUser, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.newLine();
bw.append(userName+":"+pswd);
bw.close();
fw.close();
}
else{
return false;
}
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public void createProductList(){
if(userType==1){
theProductList = thePerson.CreateProductMenu();
}
else if (userType==0){
theProductList = thePerson.CreateProductMenu();
}
}
//Functionality to add all the Buyers and Sellers with their selected product to the final File.
public void AttachProductToUser(){
try{
File userProduct = new File("src\\main\\resources\\UserProduct.txt");
FileWriter fw = new FileWriter(userProduct, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.newLine();
bw.append(user.getUserName()+":"+theSelectedProduct.getName());
bw.close();
}catch (FileNotFoundException f){
f.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public Product SelectProduct(){
return null;
}
public void productOperation(){
}
} | SahithyaCherukuri/Trading-and-Bidding-System | src/main/java/pkg/Facade.java | 1,076 | //theOfferingList = new ProduceProductMenu().showMenu(); | line_comment | en | true |
231064_0 | package designpattern.u6.v1;
/**
* Created by HuGuodong on 2019/11/19.
*/
public class Person_v1 {
private String name;
public Person_v1(String name) {
this.name = name;
}
public void wearTShirts() {
System.out.println("Wear T Shirts");
}
public void wearCoat() {
System.out.println("Wear Coat");
}
public void show() {
System.out.println(name);
}
public static void main(String[] args) {
Person_v1 p = new Person_v1("Mingming");
p.show();
p.wearCoat();
p.wearTShirts();
Person_v1 p1 = new Person_v1("Gang");
p.show();
p1.wearTShirts();
}
}
| rainCychen/Algorithms4 | designpattern/u6/v1/Person_v1.java | 225 | /**
* Created by HuGuodong on 2019/11/19.
*/ | block_comment | en | 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 |
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 |
232416_0 | //WAP For Function Overloading (Pg - 75)
/* 1.void num_cal(int num,char ch) it computes square of an integer if choice ch is 's' or it computes cube
2.void num_cal(int a,int b,char ch) it computes the product of a & b if choice ch is 'p' or it adds
3.void num_cal(String str1,String str2) it checks if 2 strings are equal
*/
import java.io.*;
import java.lang.*;
class Fover
{
int sc,pa;
void num_cal(int num,char ch)
{
if(ch=='s')
{
sc=num*num;
}
else
{
sc=num*num*num;
}
System.out.println(sc);
}
void num_cal(int a, int b, char cH)
{
if(cH=='p')
{
pa=a*b;
}
else
{
pa=a+b;
}
System.out.println(pa);
}
void num_cal(String str1, String str2)
{
if(str1.equals(str2))
{
System.out.println("\nThe Entered Strings Match");
}
else
{
System.out.println("\nThe Entered Strings Do Not Match!");
}
}
public static void main(String[]args) throws IOException
{
BufferedReader venki=new BufferedReader(new InputStreamReader(System.in));
int Num,A,B;
String STR1,STR2;
char CH,Ch;
System.out.println("\nEnter a Number : ");
Num=Integer.parseInt(venki.readLine());
System.out.println("\nPress 's' to square it OR Press 'c' to Cube it!");
CH=(char)venki.read();
System.out.println("\nEnter Two Values :");
A=Integer.parseInt(venki.readLine());
B=Integer.parseInt(venki.readLine());
System.out.println("\nPress 'p' to multiply them OR Press 'a' to Add them!");
Ch=(char)venki.read();
System.out.println("\nEnter 2 Strings to be Compared :");
STR1=venki.readLine();
STR2=venki.readLine();
Fover ob=new Fover();
ob.num_cal(Num,CH);
ob.num_cal(A,B,Ch);
ob.num_cal(STR1,STR2);
}
} | flick-23/JAVA-Programs | Fover.java | 648 | //WAP For Function Overloading (Pg - 75) | line_comment | en | true |
232594_11 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// snippet-start:[sns.java.fifo_topics.create_topic]
// Create API clients
AWSCredentialsProvider credentials = getCredentials();
AmazonSNS sns = new AmazonSNSClient(credentials);
AmazonSQS sqs = new AmazonSQSClient(credentials);
// Create FIFO topic
Map<String, String> topicAttributes = new HashMap<String, String>();
topicAttributes.put("FifoTopic", "true");
topicAttributes.put("ContentBasedDeduplication", "false");
String topicArn = sns.createTopic(
new CreateTopicRequest()
.withName("PriceUpdatesTopic.fifo")
.withAttributes(topicAttributes)
).getTopicArn();
// Create FIFO queues
Map<String, String> queueAttributes = new HashMap<String, String>();
queueAttributes.put("FifoQueue", "true");
// Disable content-based deduplication because messages published with the same body
// might carry different attributes that must be processed independently.
// The price management system uses the message attributes to define whether a given
// price update applies to the wholesale application or to the retail application.
queueAttributes.put("ContentBasedDeduplication", "false");
String wholesaleQueueUrl = sqs.createQueue(
new CreateQueueRequest()
.withName("WholesaleQueue.fifo")
.withAttributes(queueAttributes)
).getQueueUrl();
String retailQueueUrl = sqs.createQueue(
new CreateQueueRequest()
.withName("RetailQueue.fifo")
.withAttributes(queueAttributes)
).getQueueUrl();
// Subscribe FIFO queues to FIFO topic, setting required permissions
String wholesaleSubscriptionArn =
Topics.subscribeQueue(sns, sqs, topicArn, wholesaleQueueUrl);
String retailSubscriptionArn =
Topics.subscribeQueue(sns, sqs, topicArn, retailQueueUrl);
// snippet-end:[sns.java.fifo_topics.create_topic]
// snippet-start:[sns.java.fifo_topics.filter_policy]
// Set the Amazon SNS subscription filter policies
SNSMessageFilterPolicy wholesalePolicy = new SNSMessageFilterPolicy();
wholesalePolicy.addAttribute("business", "wholesale");
wholesalePolicy.apply(sns, wholesaleSubscriptionArn);
SNSMessageFilterPolicy retailPolicy = new SNSMessageFilterPolicy();
retailPolicy.addAttribute("business", "retail");
retailPolicy.apply(sns, retailSubscriptionArn);
// snippet-end:[sns.java.fifo_topics.filter_policy]
// snippet-start:[sns.java.fifo_topics.publish]
// Publish message to FIFO topic
String subject = "Price Update";
String payload = "{\"product\": 214, \"price\": 79.99}";
String groupId = "PID-214";
String dedupId = UUID.randomUUID().toString();
String attributeName = "business";
String attributeValue = "wholesale";
Map<String, MessageAttributeValue> attributes = new HashMap<>();
attributes.put(
attributeName,
new MessageAttributeValue()
.withDataType("String")
.withStringValue(attributeValue));
sns.publish(
new PublishRequest()
.withTopicArn(topicArn)
.withSubject(subject)
.withMessage(payload)
.withMessageGroupId(groupId);
.withMessageDeduplicationId(dedupId)
.withMessageAttributes(attributes);
// snippet-end:[sns.java.fifo_topics.publish]
| awsdocs/aws-doc-sdk-examples | java/example_code/sns/FifoTopics.java | 841 | // snippet-end:[sns.java.fifo_topics.create_topic] | line_comment | en | true |
232665_0 | package example.demo;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
//import org.apache.jasper.tagplugins.jstl.core.Url;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class SearchResults {
public Cart costcoCart = new Cart("Costco");
public Cart wholesaleCart = new Cart("WholesaleClub");
public Cart dollaramaCart = new Cart("Dollarama");
private Stage stage;
private Scene scene;
private Parent root;
@FXML
ImageView dollaramaPic;
@FXML
ImageView costcoPic;
@FXML
ImageView wholesalePic;
@FXML
ListView<String> dollaramaProduct;
@FXML
ListView<String> costcoProduct;
@FXML
ListView<String> wholesaleclubProduct;
@FXML
private TextField searchBar;
@FXML
private TextField quantity1;
@FXML
private TextField quantity2;
@FXML
private TextField quantity3;
private int count1;
private int count2;
private int count3;
String dollaramaPrice = " ";
String costcoPrice = " ";
String wholesalePrice = " ";
onlineSearch[] search = new onlineSearch[3];
@FXML
public void viewmyCarts(ActionEvent a){
try {
//send carts to next scene lol
FXMLLoader loader = new FXMLLoader(getClass().getResource("myCarts.fxml"));
//pooopoo pee pee
root = loader.load();
MyCarts myCartsController = loader.getController();
/*myCartsController.costcoC = this.costcoCart;
myCartsController.wholesaleC = this.wholesaleCart;
myCartsController.dollaramaC = this.dollaramaCart;
*/
//change scene
// root = FXMLLoader.load(getClass().getResource("myCarts.fxml"));
stage = (Stage) ((Node) a.getSource()).getScene().getWindow();
scene = new Scene(root);
stage.setScene(scene);
stage.show();
myCartsController.getCarts(this.costcoCart,this.wholesaleCart, this.dollaramaCart,dollaramaPrice,costcoPrice,wholesalePrice);
}catch (Exception e){
System.out.println(e.toString());
}
}
public void setName(String input1, String input2, String input3) {
dollaramaPrice = input1;
costcoPrice = input2;
wholesalePrice = input3;
getResults();
}
public void setCarts(Cart costcoCart_in, Cart wholesaleCart_in, Cart dollaramaCart_in)
{
this.costcoCart = costcoCart_in;
this.wholesaleCart = wholesaleCart_in;
this.dollaramaCart = dollaramaCart_in;
}
public void getResults() {
dollaramaProduct.getItems().add(dollaramaPrice);
costcoProduct.getItems().add(costcoPrice);
wholesaleclubProduct.getItems().add(wholesalePrice);
String url_doll = System.getProperty("user.dir")+"\\src\\main\\resources\\example\\demo\\dollarama.png";
String url_cosc = System.getProperty("user.dir")+"\\src\\main\\resources\\example\\demo\\costco.png";
String url_whole = System.getProperty("user.dir")+"\\src\\main\\resources\\example\\demo\\wholesaleclub.png";
try{
BufferedImage image_doll =ImageIO.read(new File(url_doll));
BufferedImage image_cosc =ImageIO.read(new File(url_cosc));
BufferedImage image_whole =ImageIO.read(new File(url_whole));
dollaramaPic.setImage(SwingFXUtils.toFXImage(image_doll,null));
costcoPic.setImage(SwingFXUtils.toFXImage(image_cosc,null));
wholesalePic.setImage(SwingFXUtils.toFXImage(image_whole,null));
}catch (Exception e){
}
}
@FXML
public void CostcoAdd(ActionEvent a) {
String[] costco = costcoPrice.split("\nPrice: \\$");
if (count2 != 0) {
costcoCart.addItem(costco[0], costco[1], Integer.toString(count2));
costcoCart.displayItems();
}
}
@FXML
public void WholesaleAdd(ActionEvent a) {
String[] wholeSale = wholesalePrice.split("\nPrice: \\$");
if (count3 != 0) {
wholesaleCart.addItem(wholeSale[0], wholeSale[1], Integer.toString(count3));
wholesaleCart.displayItems();
}
}
@FXML
public void DollaramaAdd(ActionEvent a) {
if (count1 != 0) {
String[] dollarama = dollaramaPrice.split("\nPrice: \\$");
dollaramaCart.addItem(dollarama[0], dollarama[1], Integer.toString(count1));
dollaramaCart.displayItems();
}
}
@FXML
public void ButtonAdd1(ActionEvent a) {
count1+= 1;
quantity1.setText(Integer.toString(count1));
}
@FXML
public void ButtonAdd2(ActionEvent a) {
count2+= 1;
quantity2.setText(Integer.toString(count2));
}
@FXML
public void ButtonAdd3(ActionEvent a) {
count3+= 1;
quantity3.setText(Integer.toString(count3));
}
@FXML
public void ButtonMinus1(ActionEvent a) {
if (count1 == 0)
{
count1 = 0;
}
else {
count1-= 1;
}
quantity1.setText(Integer.toString(count1));
}
@FXML
public void ButtonMinus2(ActionEvent a) {
if (count2 == 0)
{
count2 = 0;
}
else {
count2-= 1;}
quantity2.setText(Integer.toString(count2));
}
@FXML
public void ButtonMinus3(ActionEvent a) {
if (count3 == 0)
{
count3 = 0;
}
else{
count3-= 1;}
quantity3.setText(Integer.toString(count3));
}
//Nick was here
@FXML
public void searchAction(ActionEvent event) throws IOException {
//initialize stores
search[0] = new Dollarama();
search[1] = new Costco();
search[2] = new WholesaleClub();
//search and store for each store
String[] dollarama, costco, wholesaleclub;
dollarama = search[0].searchItem(searchBar.getText());
costco = search[1].searchItem(searchBar.getText());
wholesaleclub = search[2].searchItem(searchBar.getText());
//Inforamtion into one string
String dollaramaInfo, costcoInfo, wholesaleInfo;
dollaramaInfo = dollarama[0] + "\nPrice: $" + dollarama[1];
costcoInfo = costco[0] + "\nPrice: $" + costco[1];
wholesaleInfo = wholesaleclub[0] + "\nPrice: $" + wholesaleclub[1];
//send search results to next scene
FXMLLoader loader = new FXMLLoader(getClass().getResource("SearchResults.fxml"));
root = loader.load();
SearchResults searchResultsController = loader.getController();
//root = FXMLLoader.load(getClass().getResource("SearchResultsnew.fxml"));
stage = (Stage)((Node)event.getSource()).getScene().getWindow();
scene = new Scene(root);
stage.setScene(scene);
stage.show();
searchResultsController.setName(dollaramaInfo, costcoInfo, wholesaleInfo);
searchResultsController.setCarts(costcoCart,wholesaleCart,dollaramaCart);
}
}
| Fares-Khalil/Shopping-Companion | src/main/java/example/demo/SearchResults.java | 2,001 | //import org.apache.jasper.tagplugins.jstl.core.Url; | line_comment | en | true |
233351_0 | /*NSRCOPYRIGHT
Copyright (C) 1999-2011 University of Washington
Developed by the National Simulation Resource
Department of Bioengineering, Box 355061
University of Washington, Seattle, WA 98195-5061.
Dr. J. B. Bassingthwaighte, Director
END_NSRCOPYRIGHT*/
// object has diagnosible information
package JSim.util;
public interface DiagInfo {
public String diagInfo();
}
| NSR-Physiome/JSim | SRC2.0/JSim/util/DiagInfo.java | 134 | /*NSRCOPYRIGHT
Copyright (C) 1999-2011 University of Washington
Developed by the National Simulation Resource
Department of Bioengineering, Box 355061
University of Washington, Seattle, WA 98195-5061.
Dr. J. B. Bassingthwaighte, Director
END_NSRCOPYRIGHT*/ | block_comment | en | 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 |
234816_1 | package hus;
import boardgame.Move;
public class HusMove extends Move{
int player_id = -1;
public enum MoveType{
// Choose a pit to begin sowing from
PIT,
NOTHING
}
int pit;
MoveType move_type;
boolean from_board = false;
/**
* Create a degenerate move.
*/
public HusMove(){
this.move_type = MoveType.NOTHING;
}
/**
* Create a standard pit-choosing move.
* @param pit which pit to start from
*/
public HusMove(int pit){
this.pit = pit;
this.move_type = MoveType.PIT;
}
/**
* Create a standard pit-choosing move.
* @param pit which pit to start from
*/
public HusMove(int pit, int player_id){
this.pit = pit;
this.player_id = player_id;
this.move_type = MoveType.PIT;
}
/**
* Constructor from a string.
* The string will be parsed and, if it is correct, will construct
* the appropriate move. Mainly used by the server for reading moves
* from a log file, and for constructing moves from strings sent
* over the network.
*
* @param str The string to parse.
*/
public HusMove(String str) {
String[] components = str.split(" ");
String type_string = components[0];
this.player_id = Integer.valueOf(components[1]);
if(type_string.equals("NOTHING")){
this.move_type = MoveType.NOTHING;
}else if(type_string.equals("PIT")){
this.pit = Integer.valueOf(components[2]);
this.move_type = MoveType.PIT;
}else{
throw new IllegalArgumentException(
"Received a string that cannot be interpreted as a HusMove.");
}
}
public MoveType getMoveType() {
return move_type;
}
//get the pit number associated to that move
public int getPit() {
return pit;
}
/* Members below here are only used by the server; Player agents
* should not worry about them. */
@Override
public void setPlayerID(int player_id) {
this.player_id = player_id;
}
@Override
public int getPlayerID() {
return player_id;
}
@Override
public void setFromBoard(boolean from_board) {
this.from_board = from_board;
}
public boolean getFromBoard() {
return from_board;
}
public int[] getReceivers() {
return null;
}
public boolean doLog(){
boolean regular_move = move_type == MoveType.PIT;
return regular_move;
}
@Override
public String toPrettyString() {
String s = "";
switch(move_type){
case NOTHING:
s = String.format("Player %d ends turn.", player_id);
break;
case PIT:
s = String.format("Player %d plays pit %d", player_id, pit);
break;
}
return s;
}
@Override
public String toTransportable() {
String s = "";
switch(move_type){
case NOTHING:
s = String.format("NOTHING %d", player_id);
break;
case PIT:
s = String.format("PIT %d %d", player_id, pit);
break;
}
return s;
}
}
| marcyang001/GameAgent | src/hus/HusMove.java | 825 | /**
* Create a degenerate move.
*/ | block_comment | en | true |
234957_1 | /**
* Created by Jackson on 11/14/14.
* meant to function a a point or a vector
* handle vector math here.
*/
public class Pair{
double x,y;
public Pair (double x, double y){
this.x=x;
this.y=y;
}
public Pair (){
this.x=0;
this.y=0;
}
public Pair basicAdd(Pair other){
this.x += other.x;
this.y += other.y;
return this;
}
public Pair add(Pair other){
this.x += other.x;
this.y += other.y;
return this;
}
public Pair subtract(Pair other){
this.x -= other.x;
this.y -= other.y;
return this;
}
public double getRad (){
return Math.sqrt(x*x+y*y);
}
public Pair convertUnit(){
double r = getRad();
if (x != 0) {
x /= r;
}
if (y != 0) {
y /= r;
}
return this;
}
public Pair multiplyScalar(double scal){
x *= scal;
y *= scal;
return this;
}
public Pair divideScalar(double scal){
if (scal==0){
System.out.println("you tried to divide by 0 in divideScalar()");
return this;
}
x /= scal;
y /= scal;
return this;
}
public Pair addScalar(double scal){
x += scal;
y += scal;
return this;
}
public Pair subtractScalar(double scal){
x -= scal;
y -= scal;
return this;
}
public Pair getDifference(Pair other){
this.x = other.x - this.x;
this.y = other.y - this.y;
return this;
}
public Pair getNorm(){
double temp = this.x;
this.x = this.y;
this.y = -temp;
return this;
}
public Pair getCopy(){
return new Pair (this.x,this.y);
}
public String toString(){
return ("x: " + x + " y: " + y);
}
public double r(){
return Math.sqrt( x * x + y * y);
}
public double theta(){ return Math.atan(y/x); }
public double dotProduct(Pair b){
return this.x*b.x + this.y*b.y;
}
//THIS MUST BE A UNIT VECTOR (for optimization purposes)
public double getProjX (Pair projectee){
return this.dotProduct(projectee) * projectee.x;
}
public double getProjY (Pair projectee){
return this.dotProduct(projectee) * projectee.y;
}
public Pair projOnTo(Pair vector){
return projOnTo(vector.x,vector.y);
}
public Pair projOnTo(double vectorX, double vectorY){
double scalar = (x*vectorX+y*vectorY)/(vectorX*vectorX+vectorY*vectorY);
return new Pair(vectorX*scalar,vectorY*scalar);
}
public int hashCode(){
return (((int)x) >> 16) | ((int)y);
}
} | JuicyPasta/Physics-Engine | src/Pair.java | 770 | //THIS MUST BE A UNIT VECTOR (for optimization purposes) | line_comment | en | true |
235217_4 | import java.math.*;
import java.util.*;
import java.util.concurrent.*;
public class NMEA implements DeviceListener, NMEAVerbListener {
protected int bytesReceived, bytesSent;
protected String port;
protected DeviceState state;
protected NMEAVerbCollection verbs;
protected DeviceConnection device;
protected NMEAReceiveQueue in;
protected NMEASendQueue out;
public NMEA() {
init();
}
public NMEA( String devicePort ) {
init();
connect( devicePort );
}
public NMEA( String devicePort, int baudRate ) {
init();
connect( devicePort, baudRate );
}
protected void init() {
verbs = new NMEAVerbCollection();
device = new NMEADeviceConnection();
in = new NMEAReceiveQueue( device, this );
out = new NMEASendQueue( device, this );
device.addDeviceListener( this );
verbs.addVerbListener( this );
this.state = DeviceState.CLOSED;
populateVerbs();
}
protected void populateVerbs() {
verbs.put( new GPGGA() );
verbs.put( new GPGLL() );
verbs.put( new GPGSA() );
verbs.put( new GPGSV() );
verbs.put( new GPRMC() );
verbs.put( new GPZDA() );
}
public void connect( final String devicePort ) {
// anonymous class
new Thread( new Runnable() {
public synchronized void run() {
device.connect( devicePort );
device.beginReceiveAsync();
}
}, "NMEA::connect(1)" ).start();
}
public void connect( final String devicePort, final int baudRate ) {
// anonymous class
new Thread( new Runnable() {
public synchronized void run() {
device.connect( devicePort, baudRate );
device.beginReceiveAsync();
}
}, "NMEA::connect(2)" ).start();
}
public void disconnect() {
// disconnect method
endAsync();
//device.endReceiveAsync();
device.disconnect();
}
public boolean isConnected() {
return ( device.getDeviceState() == DeviceState.OPEN
|| device.getDeviceState() == DeviceState.ASYNC );
}
protected void beginAsync() {
/*if( in == null && out == null ) {
in = new NMEAReceiveQueue( device, this );
out = new NMEASendQueue( device, this );*/
in.beginAsync();
out.beginAsync();
//}
}
protected void endAsync() {
//if( in != null && out != null ) {
in.endAsync();
out.endAsync();
/* in = null;
out = null;
}*/
}
public void addDeviceListener( DeviceListener listener ) {
device.addDeviceListener( listener );
}
public void removeDeviceListener( DeviceListener listener ) {
device.removeDeviceListener( listener );
}
public void addVerbListener( NMEAVerbListener listener ) {
verbs.addVerbListener( listener );
}
public void removeVerbListener( NMEAVerbListener listener ) {
verbs.removeVerbListener( listener );
}
public void deviceStateEvent( DeviceConnection obj, DeviceState state ) {
this.state = state;
if( state == DeviceState.OPEN ) {
System.out.println( "Starting async on DeviceStateEvent." );
beginAsync();
} else if( state == DeviceState.ASYNC ) {
// should have already begun
} else {
System.out.println( "Ending async on DeviceStateEvent." );
endAsync();
}
}
public void deviceDataEvent( DeviceConnection obj, DeviceListener.Direction dir, int len, String data ) {
}
public void verbEvent( String verb, Object[] args ) {
}
public void interpretSentence( NMEASentence sentence ) {
if( sentence.testChecksum() && verbs.containsKey( sentence.getVerb() ) ) {
verbs.get( sentence.getVerb() ).parse( sentence );
} else {
// checksum error, or was not contained in verb collection
}
}
public void sendSentence( NMEASentence sentence ) {
out.sendSentence( sentence );
}
public void sendSentences( NMEASentence... sentences ) {
for( NMEASentence sentence : sentences ) {
out.sendSentence( sentence );
}
}
public NMEAVerb getVerb( String verb ) {
return this.verbs.get( verb );
}
public long getSentProcessedCount() {
return this.out.getProcessedCount();
}
public long getSentQueueTimeMax() {
return this.out.getQueueTimeMax();
}
public float getSentQueueTimeAvg() {
return this.out.getQueueTimeAvg();
}
public int getSentQueueLength() {
return this.out.getQueueLength();
}
public long getSentOldest() {
return this.out.getOldest();
}
public long getSentBytes() {
return this.out.getBytes();
}
public long getRecdProcessedCount() {
return this.in.getProcessedCount();
}
public long getRecdQueueTimeMax() {
return this.in.getQueueTimeMax();
}
public float getRecdQueueTimeAvg() {
return this.in.getQueueTimeAvg();
}
public int getRecdQueueLength() {
return this.in.getQueueLength();
}
public long getRecdOldest() {
return this.in.getOldest();
}
public long getRecdBytes() {
return this.in.getBytes();
}
}
| ryantenney/geologger | NMEA.java | 1,462 | /*if( in == null && out == null ) {
in = new NMEAReceiveQueue( device, this );
out = new NMEASendQueue( device, this );*/ | block_comment | en | true |
235847_3 | /*
A normal number is defined to be one that has no odd factors, except for 1 and possibly itself.
Write a method named isNormal that returns 1 if its integer argument is normal, otherwise it returns 0.
Examples: 1, 2, 3, 4, 5, 7, 8 are normal numbers. 6 and 9 are not normal numbers since 3 is an odd
factor. 10 is not a normal number since 5 is an odd factor. The function signature is
int isNormal(int n)
*/
package MIU;
/**
*
* @author Shristi
*/
public class Normal {
public static void main(String[] args){
int result = isNormal(8);
System.out.println(result);
}
static int isNormal(int n){
if(n <= 0)
return 0;
int isNormal = 1;
for (int i = 2; i <= n/2; i++){ // 2 dekhi loop lako as 1 hunu hunna
if(n % i == 0 && i % 2 == 1){ //n%i==0 filters factors and i%2==1 checks if the factor is odd
isNormal = 0; break;
}
}
return isNormal;
}
}
| shristigautam/MaharishiInternationalUniversityAnswersMIU | Normal.java | 310 | //n%i==0 filters factors and i%2==1 checks if the factor is odd
| line_comment | en | true |
236477_0 | package Classical;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.Collections;
/**
*
* @author [email protected]
*
*/
class ANARC05B {
String PROB_NAME = "";
String TEST_NAME = "input00.txt";
InputScanner i_scan;
OutputWriter o_writ;
Boolean is_debug = false;
long start_time = 0;
long end_time = 0;
public static void main(String[] args) {
ANARC05B program = new ANARC05B(args);
program.begin();
program.end();
}
public void begin() {
int len1 = i_scan.nextInt();
while(len1>0){
int[] a1 = new int[len1];
for(int i = 0; i< len1; i++){
a1[i] = i_scan.nextInt();
}
int len2 = i_scan.nextInt();
int[] a2 = new int[len2];
for(int i = 0; i< len2; i++){
a2[i] = i_scan.nextInt();
}
o_writ.printLine(maxSum(a1,a2));
len1 = i_scan.nextInt();
}
}
int maxSum(int[] a1, int[] a2){
int i = 0;
int j = 0;
int sum1 = 0;
int sum2 = 0;
int sumSoFar = 0;
while(i < a1.length && j < a2.length){
if(a1[i] < a2[j]){
sum1+=a1[i];
i++;
}
else if (a1[i] > a2[j]){
sum2+=a2[j];
j++;
}
else{ // intersection
sumSoFar += Math.max(sum1,sum2);
sumSoFar += a1[i];
i++;
j++;
sum1 = 0;
sum2 = 0;
}
}
if(i>=a1.length){
while (j < a2.length){
sum2+=a2[j];
j++;
}
}
if(j>=a2.length){
while (i < a1.length){
sum1+=a1[i];
i++;
}
}
sumSoFar += Math.max(sum1, sum2);
return sumSoFar;
}
public ANARC05B(String[] args) {
if (args.length > 0 && args[0].equals("Test")) {
i_scan = new InputScanner(new File(
"/home/sagar/code_arena/Eclipse Workspace/InterviewStr/inputs/"
+ PROB_NAME + "/"+TEST_NAME));
} else {
i_scan = new InputScanner(System.in);
}
o_writ = new OutputWriter(System.out);
if (is_debug) {
start_time = System.currentTimeMillis();
}
}
public void end() {
if (is_debug) {
end_time = System.currentTimeMillis();
o_writ.printLine("Time (milisec): " + (end_time - start_time));
}
o_writ.close();
}
class InputScanner {
private final BufferedReader br;
StringTokenizer tokenizer;
public InputScanner(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public InputScanner(File file) {
try {
br = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
int num;
try {
num = Integer.parseInt(next());
} catch (NumberFormatException e) {
throw new RuntimeException(e);
}
return num;
}
public float nextFloat(){
float num;
try{
num = Float.parseFloat(next());
}catch(NumberFormatException e){
throw new RuntimeException(e);
}
return num;
}
public float nextLong(){
long num;
try{
num = Long.parseLong(next());
}catch(NumberFormatException e){
throw new RuntimeException(e);
}
return num;
}
public String nextLine() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n").trim();
}
}
class OutputWriter {
private final PrintWriter pw;
public OutputWriter(OutputStream op) {
pw = new PrintWriter(op);
}
public OutputWriter(Writer writer) {
pw = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
pw.print(' ');
pw.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
pw.println();
}
public void close() {
pw.close();
}
}
}
| sagarjauhari/spoj | src/Classical/ANARC05B.java | 1,363 | /**
*
* @author [email protected]
*
*/ | block_comment | en | true |
237679_9 | package mars;
/*
* Copyright (c) 2003-2012, Pete Sanderson and Kenneth Vollmar
*
* Developed by Pete Sanderson ([email protected]) and Kenneth Vollmar
* ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* (MIT license, http://www.opensource.org/licenses/mit-license.html)
*/
import java.io.File;
import java.util.ArrayList;
/**
* Maintains list of generated error messages, regardless of source (tokenizing,
* parsing, assembly, execution).
*
* @author Pete Sanderson
* @version August 2003
**/
public class ErrorList {
private final ArrayList messages;
private int errorCount;
private int warningCount;
public static final String ERROR_MESSAGE_PREFIX = "Error";
public static final String WARNING_MESSAGE_PREFIX = "Warning";
public static final String FILENAME_PREFIX = " in ";
public static final String LINE_PREFIX = " line ";
public static final String POSITION_PREFIX = " column ";
public static final String MESSAGE_SEPARATOR = ": ";
/**
* Constructor for ErrorList
**/
public ErrorList() {
messages = new ArrayList();
errorCount = 0;
warningCount = 0;
}
/**
* Get ArrayList of error messages.
*
* @return ArrayList of ErrorMessage objects
*/
public ArrayList getErrorMessages() { return messages; }
/**
* Determine whether error has occured or not.
*
* @return <tt>true</tt> if an error has occurred (does not include warnings),
* <tt>false</tt> otherwise.
**/
public boolean errorsOccurred() {
return errorCount != 0;
}
/**
* Determine whether warning has occured or not.
*
* @return <tt>true</tt> if an warning has occurred, <tt>false</tt> otherwise.
**/
public boolean warningsOccurred() {
return warningCount != 0;
}
/**
* Add new error message to end of list.
*
* @param mess ErrorMessage object to be added to end of error list.
**/
public void add(final ErrorMessage mess) {
add(mess, messages.size());
}
/**
* Add new error message at specified index position.
*
* @param mess ErrorMessage object to be added to end of error list.
* @param index position in error list
**/
public void add(final ErrorMessage mess, final int index) {
if (errorCount > getErrorLimit()) { return; }
if (errorCount == getErrorLimit()) {
messages.add(new ErrorMessage((MIPSprogram) null, mess.getLine(), mess.getPosition(), "Error Limit of "
+ getErrorLimit() + " exceeded."));
errorCount++; // subsequent errors will not be added; see if statement above
return;
}
messages.add(index, mess);
if (mess.isWarning()) {
warningCount++;
} else {
errorCount++;
}
}
/**
* Count of number of error messages in list.
*
* @return Number of error messages in list.
**/
public int errorCount() {
return errorCount;
}
/**
* Count of number of warning messages in list.
*
* @return Number of warning messages in list.
**/
public int warningCount() {
return warningCount;
}
/**
* Check to see if error limit has been exceeded.
*
* @return True if error limit exceeded, false otherwise.
**/
public boolean errorLimitExceeded() {
return errorCount > getErrorLimit();
}
/**
* Get limit on number of error messages to be generated by one assemble
* operation.
*
* @return error limit.
**/
public int getErrorLimit() { return Globals.maximumErrorMessages; }
/**
* Produce error report.
*
* @return String containing report.
**/
public String generateErrorReport() {
return generateReport(ErrorMessage.ERROR);
}
/**
* Produce warning report.
*
* @return String containing report.
**/
public String generateWarningReport() {
return generateReport(ErrorMessage.WARNING);
}
/**
* Produce report containing both warnings and errors, warnings first.
*
* @return String containing report.
**/
public String generateErrorAndWarningReport() {
return generateWarningReport() + generateErrorReport();
}
// Produces either error or warning report.
private String generateReport(final boolean isWarning) {
final StringBuffer report = new StringBuffer("");
String reportLine;
for (int i = 0; i < messages.size(); i++) {
final ErrorMessage m = (ErrorMessage) messages.get(i);
if (isWarning && m.isWarning() || !isWarning && !m.isWarning()) {
reportLine = (isWarning ? WARNING_MESSAGE_PREFIX : ERROR_MESSAGE_PREFIX) + FILENAME_PREFIX;
if (m.getFilename().length() > 0) {
reportLine = reportLine + new File(m.getFilename()).getPath(); //.getName());
}
if (m.getLine() > 0) {
reportLine = reportLine + LINE_PREFIX + m.getMacroExpansionHistory() + m.getLine();
}
if (m.getPosition() > 0) { reportLine = reportLine + POSITION_PREFIX + m.getPosition(); }
reportLine = reportLine + MESSAGE_SEPARATOR + m.getMessage() + "\n";
report.append(reportLine);
}
}
return report.toString();
}
} // ErrorList
| aeris170/MARS-Theme-Engine | mars/ErrorList.java | 1,604 | /**
* Count of number of error messages in list.
*
* @return Number of error messages in list.
**/ | block_comment | en | true |
238317_0 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.*;
/**
* Write a description of class BatBrain here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class BatBrain extends Monsters
{
/**
* Act - do whatever the BatBrain wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
GreenfootImage waiting = new GreenfootImage("images/batbrain/hanging.png");
GreenfootImage[] flyingRight = new GreenfootImage[3];
GreenfootImage[] flyingLeft = new GreenfootImage[3];
private boolean right = true;
private boolean canMove = false;
SimpleTimer timer = new SimpleTimer();
public BatBrain(){
super("batbrain");
waiting.scale(20, 40);
for(int i = 0; i < flyingRight.length; i++){
flyingRight[i] = new GreenfootImage("images/batbrain/flying/fly" + i + ".png");
flyingRight[i].scale(40, 30);
}
for(int i = 0; i < flyingLeft.length; i++){
flyingLeft[i] = new GreenfootImage("images/batbrain/flying/fly" + i + ".png");
flyingLeft[i].mirrorHorizontally();
flyingLeft[i].scale(40, 30);
}
flyingRight[1].scale(40, 20);
flyingLeft[1].scale(40, 20);
}
/*
the method detects whether or not sonic is in the range of
attack, if true, batBrain canStarts to move, else, it will stay
fixed until sonic is inRange again
*/
public void sonicInRange(){
List<Sonic> sonic = getObjectsInRange(340, Sonic.class);
if(!sonic.isEmpty()){
canMove = true;
Sonic nearestSonic = sonic.get(0);
//drops to nearestSonic current Y position and moves back and forth
if(getY() < nearestSonic.getY()){
setLocation(getX(), getY() + 2);
} else if(getY() > nearestSonic.getY()){
setLocation(getX(), getY() - 1);
} else {
setLocation(getX(), nearestSonic.getY());
}
flying();
} else {
//if sonic is not in range, it waits until sonic is in range again
setImage(waiting);
canMove = false;
}
}
//animate batBrain
private int frame = 0;
public void flying(){
if(timer.millisElapsed() < 190) return;
timer.mark();
if(!canMove) return;
if(right){
setImage(flyingRight[frame]);
frame = (frame + 1) % flyingRight.length;
} else {
setImage(flyingLeft[frame]);
frame = (frame + 1) % flyingLeft.length;
}
}
private int moveTimes = 0;
private void moveAround(){
if(!canMove) return;
if(right){
if(moveTimes >= 65){
moveTimes = 0;
right = false;
}
move(2);
moveTimes++;
} else {
if(moveTimes >= 65){
moveTimes = 0;
right = true;
}
move(-2);
moveTimes++;
}
}
public void act()
{
// Add your action code here.
sonicInRange();
moveAround();
if(isTouching(Sonic.class)){
getWorld().removeObject(this);
}
}
}
| yrdsb-peths/final-greenfoot-project-AndyFeng070205 | BatBrain.java | 892 | // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) | line_comment | en | 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 |
238773_0 | import greenfoot.*;
/**
* Write a description of class HpBox here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class HpBox extends PerkBox
{
public Counter c;
public HpBox(Counter s)
{
c = s;
}
public void act()
{
checkPlayer();
}
public void checkPlayer()
{
Actor player = getOneIntersectingObject(TopDownPlayer.class);
if (player != null)
{
getWorld().removeObject(this);
c.subtract();
}
}
}
| alexlao/DreamScape | DreamWIP/HpBox.java | 152 | /**
* Write a description of class HpBox here.
*
* @author (your name)
* @version (a version number or a date)
*/ | block_comment | en | true |
239812_5 | import java.util.Random;
import java.util.Scanner;
/**
* The Tetris class represents the game of Tetris.
* It has various methods to create the game board, add the Tetromino shapes,
* rotate, move and animate the shapes.
* It has fields to keep track of the number of falls, check if the shapes
* overlap and keep track of the count of moves and rotations.
*
* @author Abdullah Enes Patir
*/
public class Tetris {
private int row;
private int column;
/**
* Number of falls happened till tetromino lands
*/
private int numofFalls;
/**
* An attribute to check if tetrises touches
*/
private int check;
private int moveCount;
private int rotationCount;
private char rotationDirection;
private char moveDirection;
private char[][] tetrisBoard;
Random rand = new Random();
/**
* Constructor that initializes the number of rows and columns for the game
* board and assigns the number of falls and check to 0.
*
* @param row_ the number of rows for the game board
* @param column_ the number of columns for the game board
*/
public Tetris(final int row_, final int column_) {
if (row_ < 10 || column_ < 10)
throw new IllegalArgumentException("Please enter a valid number (10 or greater)");
row = row_;
column = column_;
numofFalls = 1;
check = 0;
}
/**
* Method that creates the game board by initializing a 2D array of characters
* and assigning '#' to the outer edges and ' ' to the inner spaces.
*/
public void createBoard() {
tetrisBoard = new char[row + 2][column + 2];
for (int i = 0; i < row + 2; i++) {
for (int j = 0; j < column + 2; j++) {
if (i == 0 || i == row + 1)
tetrisBoard[i][j] = '#';
else if (j == 0 || j == column + 1)
tetrisBoard[i][j] = '#';
else
tetrisBoard[i][j] = ' ';
}
}
}
/**
* Method that draws the game board on the screen by printing the 2D array of
* characters
*/
public void draw() {
for (int i = 0; i < row + 2; i++) {
for (int j = 0; j < column + 2; j++) {
System.out.print(tetrisBoard[i][j]);
}
System.out.println();
}
}
/**
* Method that adds a Tetromino shape to the game board by updating the 2D array
* of characters
*
* @param other the Tetromino shape to be added
* @return the updated Tetris object
*/
public Tetris add(Tetromino other) {
if (numofFalls == 2) {
for (int i = 1; i <= other.getTetromino().length; i++) {
for (int j = 0; j < other.getTetromino()[0].length; j++) {
tetrisBoard[i][1 + (column / 2) + j] = ' ';
}
}
}
for (int i = 0; i < other.getTetromino().length; i++) {
for (int k = 0; k < other.getTetromino()[0].length; k++) {
// checking for tetrominos overlap
if (tetrisBoard[numofFalls + other.getTetromino().length - 1][1 + (column / 2) + moveCount + k] != ' ')
check = 1;
}
if (check == 1) {
break;
}
for (int j = 0; j < other.getTetromino()[0].length; j++) {
if (numofFalls == 1)
tetrisBoard[numofFalls + i][1 + (column / 2) + j] = other.getTetromino()[i][j];
if (numofFalls > 1)
tetrisBoard[numofFalls + i][1 + (column / 2) + j + moveCount] = other.getTetromino()[i][j];
if (numofFalls != 1) {
tetrisBoard[numofFalls - 1][1 + (column / 2) + j + moveCount] = ' ';
}
}
}
return this;
}
/**
* Method that animates the Tetromino shape by moving and rotating it and
* updating the game board
*
* @param other the Tetromino shape to be animated
* @param scanner the input scanner
*/
public void animate(Tetromino other, Scanner scanner) {
allRandom(other);
int i = 0;
for (int k = 0; k < rotationCount; k++)
other.rotate(rotationDirection);
if (heigthofTetris() + other.getTetromino().length == row) {
System.err.println("Table is full");
scanner.close();
System.exit(0);
}
if (moveDirection == 'l') {
moveCount *= -1;
}
do {
add(other);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("\033[H\033[2J");
draw();
numofFalls++;
i++;
} while (i < row - other.getTetromino().length + 1 && check == 0);
numofFalls = 1;
check = 0;
}
/**
* Method that computes the heigth of tetrominos on tetris
*
* @return the height of tetrominos on tetris
*/
public int heigthofTetris() {
int flag = 0, s = 0;
for (int i = row; i >= 1; i--) {
flag = 0;
for (int j = 1; j <= column; j++) {
if (tetrisBoard[i][j] != ' ') {
s++;
flag = 1;
break;
}
}
if (flag == 0)
return s;
}
return s;
}
/**
* Method that assigns move and rotation datas randomly
*
* @param Tetromino object
*/
public void allRandom(Tetromino other) {
char[] randomArray = { 'a', 'c' };
int[] randomInt = { 1, 2, 3, 4 };
char[] randomArray2 = { 'r', 'l' };
rotationDirection = randomArray[rand.nextInt(2)];
rotationCount = randomInt[rand.nextInt(4)];
moveDirection = randomArray2[rand.nextInt(2)];
if (moveDirection == 'r')
moveCount = rand.nextInt((column / 2) - 1);
else
moveCount = rand.nextInt((column / 2) + 1);
}
}
| enespatir07/Object-Oriented-Programming | hw7/Tetris.java | 1,683 | /**
* Method that draws the game board on the screen by printing the 2D array of
* characters
*/ | block_comment | en | true |
239877_5 | /**
* <p>
* Materialien zu den zentralen NRW-Abiturpruefungen im Fach Informatik ab 2018
* </p>
* <p>
* Generische Klasse List<ContentType>
* </p>
* <p>
* Objekt der generischen Klasse List verwalten beliebig viele linear
* angeordnete Objekte vom Typ ContentType. Auf hoechstens ein Listenobjekt,
* aktuellesObjekt genannt, kann jeweils zugegriffen werden.<br />
* Wenn eine Liste leer ist, vollstaendig durchlaufen wurde oder das aktuelle
* Objekt am Ende der Liste geloescht wurde, gibt es kein aktuelles
* Objekt.<br />
* Das erste oder das letzte Objekt einer Liste koennen durch einen Auftrag zum
* aktuellen Objekt gemacht werden. Ausserdem kann das dem aktuellen Objekt
* folgende Listenobjekt zum neuen aktuellen Objekt werden. <br />
* Das aktuelle Objekt kann gelesen, veraendert oder geloescht werden. Ausserdem
* kann vor dem aktuellen Objekt ein Listenobjekt eingefuegt werden.
* </p>
*
* @author Qualitaets- und UnterstuetzungsAgentur - Landesinstitut fuer Schule
* @version Generisch_06 2015-10-25
*/
public class List<ContentType> {
/* --------- Anfang der privaten inneren Klasse -------------- */
private class ListNode {
private ContentType contentObject;
private ListNode next;
/**
* Ein neues Objekt wird erschaffen. Der Verweis ist leer.
*
* @param pContent das Inhaltsobjekt vom Typ ContentType
*/
private ListNode(ContentType pContent) {
contentObject = pContent;
next = null;
}
/**
* Der Inhalt des Knotens wird zurueckgeliefert.
*
* @return das Inhaltsobjekt des Knotens
*/
public ContentType getContentObject() {
return contentObject;
}
/**
* Der Inhalt dieses Kontens wird gesetzt.
*
* @param pContent das Inhaltsobjekt vom Typ ContentType
*/
public void setContentObject(ContentType pContent) {
contentObject = pContent;
}
/**
* Der Nachfolgeknoten wird zurueckgeliefert.
*
* @return das Objekt, auf das der aktuelle Verweis zeigt
*/
public ListNode getNextNode() {
return this.next;
}
/**
* Der Verweis wird auf das Objekt, das als Parameter uebergeben
* wird, gesetzt.
*
* @param pNext der Nachfolger des Knotens
*/
public void setNextNode(ListNode pNext) {
this.next = pNext;
}
}
/* ----------- Ende der privaten inneren Klasse -------------- */
// erstes Element der Liste
ListNode first;
// letztes Element der Liste
ListNode last;
// aktuelles Element der Liste
ListNode current;
/**
* Eine leere Liste wird erzeugt.
*/
public List() {
first = null;
last = null;
current = null;
}
/**
* Die Anfrage liefert den Wert true, wenn die Liste keine Objekte enthaelt,
* sonst liefert sie den Wert false.
*
* @return true, wenn die Liste leer ist, sonst false
*/
public boolean isEmpty() {
// Die Liste ist leer, wenn es kein erstes Element gibt.
return first == null;
}
/**
* Die Anfrage liefert den Wert true, wenn es ein aktuelles Objekt gibt,
* sonst liefert sie den Wert false.
*
* @return true, falls Zugriff moeglich, sonst false
*/
public boolean hasAccess() {
// Es gibt keinen Zugriff, wenn current auf kein Element verweist.
return current != null;
}
/**
* Falls die Liste nicht leer ist, es ein aktuelles Objekt gibt und dieses
* nicht das letzte Objekt der Liste ist, wird das dem aktuellen Objekt in
* der Liste folgende Objekt zum aktuellen Objekt, andernfalls gibt es nach
* Ausfuehrung des Auftrags kein aktuelles Objekt, d.h. hasAccess() liefert
* den Wert false.
*/
public void next() {
if (this.hasAccess()) {
current = current.getNextNode();
}
}
/**
* Falls die Liste nicht leer ist, wird das erste Objekt der Liste aktuelles
* Objekt. Ist die Liste leer, geschieht nichts.
*/
public void toFirst() {
if (!isEmpty()) {
current = first;
}
}
/**
* Falls die Liste nicht leer ist, wird das letzte Objekt der Liste
* aktuelles Objekt. Ist die Liste leer, geschieht nichts.
*/
public void toLast() {
if (!isEmpty()) {
current = last;
}
}
/**
* Falls es ein aktuelles Objekt gibt (hasAccess() == true), wird das
* aktuelle Objekt zurueckgegeben, andernfalls (hasAccess() == false) gibt
* die Anfrage den Wert null zurueck.
*
* @return das aktuelle Objekt (vom Typ ContentType) oder null, wenn es
* kein aktuelles Objekt gibt
*/
public ContentType getContent() {
if (this.hasAccess()) {
return current.getContentObject();
} else {
return null;
}
}
/**
* Falls es ein aktuelles Objekt gibt (hasAccess() == true) und pContent
* ungleich null ist, wird das aktuelle Objekt durch pContent ersetzt. Sonst
* geschieht nichts.
*
* @param pContent
* das zu schreibende Objekt vom Typ ContentType
*/
public void setContent(ContentType pContent) {
// Nichts tun, wenn es keinen Inhalt oder kein aktuelles Element gibt.
if (pContent != null && this.hasAccess()) {
current.setContentObject(pContent);
}
}
/**
* Falls es ein aktuelles Objekt gibt (hasAccess() == true), wird ein neues
* Objekt vor dem aktuellen Objekt in die Liste eingefuegt. Das aktuelle
* Objekt bleibt unveraendert. <br />
* Wenn die Liste leer ist, wird pContent in die Liste eingefuegt und es
* gibt weiterhin kein aktuelles Objekt (hasAccess() == false). <br />
* Falls es kein aktuelles Objekt gibt (hasAccess() == false) und die Liste
* nicht leer ist oder pContent gleich null ist, geschieht nichts.
*
* @param pContent
* das einzufuegende Objekt vom Typ ContentType
*/
public void insert(ContentType pContent) {
if (pContent != null) { // Nichts tun, wenn es keinen Inhalt gibt.
if (this.hasAccess()) { // Fall: Es gibt ein aktuelles Element.
// Neuen Knoten erstellen.
ListNode newNode = new ListNode(pContent);
if (current != first) { // Fall: Nicht an erster Stelle einfuegen.
ListNode previous = this.getPrevious(current);
newNode.setNextNode(previous.getNextNode());
previous.setNextNode(newNode);
} else { // Fall: An erster Stelle einfuegen.
newNode.setNextNode(first);
first = newNode;
}
} else { // Fall: Es gibt kein aktuelles Element.
if (this.isEmpty()) { // Fall: In leere Liste einfuegen.
// Neuen Knoten erstellen.
ListNode newNode = new ListNode(pContent);
first = newNode;
last = newNode;
}
}
}
}
/**
* Falls pContent gleich null ist, geschieht nichts.<br />
* Ansonsten wird ein neues Objekt pContent am Ende der Liste eingefuegt.
* Das aktuelle Objekt bleibt unveraendert. <br />
* Wenn die Liste leer ist, wird das Objekt pContent in die Liste eingefuegt
* und es gibt weiterhin kein aktuelles Objekt (hasAccess() == false).
*
* @param pContent
* das anzuhaengende Objekt vom Typ ContentType
*/
public void append(ContentType pContent) {
if (pContent != null) { // Nichts tun, wenn es keine Inhalt gibt.
if (this.isEmpty()) { // Fall: An leere Liste anfuegen.
this.insert(pContent);
} else { // Fall: An nicht-leere Liste anfuegen.
// Neuen Knoten erstellen.
ListNode newNode = new ListNode(pContent);
last.setNextNode(newNode);
last = newNode; // Letzten Knoten aktualisieren.
}
}
}
/**
* Falls es sich bei der Liste und pList um dasselbe Objekt handelt,
* pList null oder eine leere Liste ist, geschieht nichts.<br />
* Ansonsten wird die Liste pList an die aktuelle Liste angehaengt.
* Anschliessend wird pList eine leere Liste. Das aktuelle Objekt bleibt
* unveraendert. Insbesondere bleibt hasAccess identisch.
*
* @param pList
* die am Ende anzuhaengende Liste vom Typ List<ContentType>
*/
public void concat(List<ContentType> pList) {
if (pList != this && pList != null && !pList.isEmpty()) { // Nichts tun,
// wenn pList und this identisch, pList leer oder nicht existent.
if (this.isEmpty()) { // Fall: An leere Liste anfuegen.
this.first = pList.first;
this.last = pList.last;
} else { // Fall: An nicht-leere Liste anfuegen.
this.last.setNextNode(pList.first);
this.last = pList.last;
}
// Liste pList loeschen.
pList.first = null;
pList.last = null;
pList.current = null;
}
}
/**
* Wenn die Liste leer ist oder es kein aktuelles Objekt gibt (hasAccess()
* == false), geschieht nichts.<br />
* Falls es ein aktuelles Objekt gibt (hasAccess() == true), wird das
* aktuelle Objekt geloescht und das Objekt hinter dem geloeschten Objekt
* wird zum aktuellen Objekt. <br />
* Wird das Objekt, das am Ende der Liste steht, geloescht, gibt es kein
* aktuelles Objekt mehr.
*/
public void remove() {
// Nichts tun, wenn es kein aktuelle Element gibt oder die Liste leer ist.
if (this.hasAccess() && !this.isEmpty()) {
if (current == first) {
first = first.getNextNode();
} else {
ListNode previous = this.getPrevious(current);
if (current == last) {
last = previous;
}
previous.setNextNode(current.getNextNode());
}
ListNode temp = current.getNextNode();
current.setContentObject(null);
current.setNextNode(null);
current = temp;
// Beim loeschen des letzten Elements last auf null setzen.
if (this.isEmpty()) {
last = null;
}
}
}
/**
* Liefert den Vorgaengerknoten des Knotens pNode. Ist die Liste leer, pNode
* == null, pNode nicht in der Liste oder pNode der erste Knoten der Liste,
* wird null zurueckgegeben.
*
* @param pNode
* der Knoten, dessen Vorgaenger zurueckgegeben werden soll
* @return der Vorgaenger des Knotens pNode oder null, falls die Liste leer ist,
* pNode == null ist, pNode nicht in der Liste ist oder pNode der erste
* Knoten
* der Liste ist
*/
private ListNode getPrevious(ListNode pNode) {
if (pNode != null && pNode != first && !this.isEmpty()) {
ListNode temp = first;
while (temp != null && temp.getNextNode() != pNode) {
temp = temp.getNextNode();
}
return temp;
} else {
return null;
}
}
}
| julsen7/Listen | src/List.java | 3,082 | /**
* Der Nachfolgeknoten wird zurueckgeliefert.
*
* @return das Objekt, auf das der aktuelle Verweis zeigt
*/ | block_comment | en | true |
240093_14 |
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JOptionPane;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Renzo Costanzo
*/
public class Sortear extends javax.swing.JDialog {
/**
* Creates new form Sortear
*/
conexion ne=new conexion();
Connection con=ne.Conectar();
int n=0,cedulaganador,cant;
ArrayList aIDS = new ArrayList();
ArrayList aCI = new ArrayList();
public Sortear(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jButton1.setText("SORTEAR");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(146, 146, 146)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(153, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(102, 102, 102)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(110, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
n++;
if(n==1){
int cantidad=0,ii=3;
String ganado="insert into ganador(cedula_ganador,id_ganador) values(?,?)",sq="SELECT * FROM comentarios ORDER BY rand() LIMIT "+cantidad;
Statement st;
//CONSEGUIR IDS DE PREMIOS
try {
Statement pst=con.createStatement();
ResultSet rs = pst.executeQuery("select id from premios");
while(rs.next()){
cantidad++;
aIDS.add(rs.getInt("id"));
}
//JOptionPane.showMessageDialog(null, cantidad);
//String sq="SELECT * FROM comentarios ORDER BY rand() LIMIT "+cantidad;
/*for(int u=0;u<aIDS.size();u++){
JOptionPane.showMessageDialog(null, aIDS.get(u));
}*/
//JOptionPane.showMessageDialog(null, "SE ASIGNARON LOS GANADORES");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Error al conseguir ids" +ex);
}
//CONSEGUIR CEDULA DE GANADORES
try {
Statement pstg=con.createStatement();
ResultSet rsg = pstg.executeQuery("SELECT cedula FROM concursantes ORDER BY rand() LIMIT "+cantidad+"");
while(rsg.next()){
aCI.add(rsg.getInt("cedula"));
}
//String sq="SELECT * FROM comentarios ORDER BY rand() LIMIT "+cantidad;
/*for(int u=0;u<aCI.size();u++){
JOptionPane.showMessageDialog(null, aCI.get(u));
}*/
//JOptionPane.showMessageDialog(null, "SE ASIGNARON LOS GANADORES");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Error al conseguir cedula de ganadores" +ex);
}
//ASIGNAR GANADOR EN LA BD
for(int i=0;i<cantidad;i++){
try{
PreparedStatement pst2=con.prepareStatement("insert into ganadores(cedula_ganador,id_ganador) values(?,?)");
pst2.setInt(1, (int) aCI.get(i));
pst2.setInt(2, (int) aIDS.get(i));
int vus=pst2.executeUpdate();
if (vus>0){
JOptionPane.showMessageDialog(null, "GANADOR '"+aCI.get(i)+"' INGRESADO CORRECTAMENTE");
}
}catch(SQLException ee){
JOptionPane.showMessageDialog(null, "ERROR AL INGRESAR GANADORES, O \n O LOS GANADORES YA ESTA REGISTRADOS");
}
}
}
else{
JOptionPane.showMessageDialog(null, "Ya se realizo un sorteo");
}
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Sortear.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Sortear.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Sortear.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Sortear.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Sortear dialog = new Sortear(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
// End of variables declaration//GEN-END:variables
}
| javatlacati/Rifa | Rifa/src/Sortear.java | 1,819 | /*for(int u=0;u<aCI.size();u++){
JOptionPane.showMessageDialog(null, aCI.get(u));
}*/ | block_comment | en | true |
240698_0 | package model;
/**
*
* @author THAYCACAC
*/
public class Experience extends Candidate {
private int yearExperience;
private String professionalSkill;
public Experience() {
super();
}
public Experience(int yearExperience, String professionalSkill,
String id, String firstName, String lastName, int birthDate,
String address, String phone, String email, int typeCandidate) {
super(id, firstName, lastName, birthDate, address, phone, email,
typeCandidate);
this.yearExperience = yearExperience;
this.professionalSkill = professionalSkill;
}
public Experience(int yearExperience, String professionalSkill, Candidate candidate) {
super(candidate.getId(), candidate.getFirstName(), candidate.getLastName(),
candidate.getBirthDate(), candidate.getAddress(), candidate.getPhone(),
candidate.getEmail(), candidate.getTypeCandidate());
this.yearExperience = yearExperience;
this.professionalSkill = professionalSkill;
}
public int getYearExperience() {
return yearExperience;
}
public void setYearExperience(int yearExperience) {
this.yearExperience = yearExperience;
}
public String getProfessionalSkill() {
return professionalSkill;
}
public void setProfessionalSkill(String professionalSkill) {
this.professionalSkill = professionalSkill;
}
}
| namdng09/LAB211 | J1.L.P0022/src/model/Experience.java | 296 | /**
*
* @author THAYCACAC
*/ | block_comment | en | true |
240721_0 | /*
############################################################################
# Coala #
# CO-evolution Assessment by a Likelihood-free Approach #
############################################################################
# #
# Copyright INRIA 2018 #
# #
# Contributors : Christian Baudet #
# Beatrice Donati #
# Blerina Sinaimeri #
# Pierluigi Crescenzi #
# Christian Gautier #
# Catherine Matias #
# Marie-France Sagot #
# Laura Urbini #
# #
# [email protected] #
# [email protected] #
# https://gforge.inria.fr/forum/forum.php?forum_id=11324 #
# #
# This software is a computer program whose purpose is to estimate #
# the probability of events (co-speciation, duplication, host-switch and #
# loss) for a pair of host and parasite trees through a Approximate #
# Bayesian Computation - Sequential Monte Carlo (ABC-SMC) procedure. #
# #
# This software is governed by the CeCILL license under French law and #
# abiding by the rules of distribution of free software. You can use, #
# modify and/ or redistribute the software under the terms of the CeCILL #
# license as circulated by CEA, CNRS and INRIA at the following URL #
# "http://www.cecill.info". #
# #
# As a counterpart to the access to the source code and rights to copy, #
# modify and redistribute granted by the license, users are provided only #
# with a limited warranty and the software's author, the holder of the #
# economic rights, and the successive licensors have only limited #
# liability. #
# #
# In this respect, the user's attention is drawn to the risks associated #
# with loading, using, modifying and/or developing or reproducing the #
# software by the user in light of its specific status of free software, #
# that may mean that it is complicated to manipulate, and that also #
# therefore means that it is reserved for developers and experienced #
# professionals having in-depth computer knowledge. Users are therefore #
# encouraged to load and test the software's suitability as regards their #
# requirements in conditions enabling the security of their systems and/or #
# data to be ensured and, more generally, to use and operate it in the #
# same conditions as regards security. #
# #
# The fact that you are presently reading this means that you have had #
# knowledge of the CeCILL license and that you accept its terms. #
############################################################################
*/
package util;
import java.util.Arrays;
public class Statistics {
public static double mean(double[] l) {
double sum = 0.0;
int n = l.length;
for (int e = 0; e < n; e++) {
sum = sum + l[e];
}
return sum / n;
}
public static double mean(int[] l) {
double sum = 0.0;
int n = l.length;
for (int e = 0; e < n; e++) {
sum = sum + l[e];
}
return sum / n;
}
public static double max(double[] l) {
double maxVal;
if(l.length==0){
maxVal = 0.0;
}
else{
maxVal=l[0];
for (int i = 1; i < l.length; i++){
if (maxVal < l[i]){
maxVal = l[i];
}
}
}
return maxVal;
}
public static int max(int[] l) {
int maxVal;
if(l.length==0){
maxVal = 0;
}
else{
maxVal=l[0];
for (int i = 1; i < l.length; i++){
if (maxVal < l[i]){
maxVal = l[i];
}
}
}
return maxVal;
}
public static double median(double[] l) {
int n = l.length;
Arrays.sort(l);
double median = l[n / 2];
if (n % 2 == 0) {
median = (median + l[n / 2 - 1]) / 2;
}
return median;
}
public static double median(int[] l) {
int n = l.length;
Arrays.sort(l);
double median = l[n / 2];
if (n % 2 == 0) {
median = (median + l[n / 2 - 1]) / 2;
}
return median;
}
public static double pearson(double[] l) {
int n = l.length;
Arrays.sort(l);
double median = l[n / 2];
if (n % 2 == 0) {
median = (median + l[n / 2 - 1]) / 2;
}
double sum = 0.0;
double mean = mean(l);
for (int e = 0; e < n; e++) {
sum = sum + (mean - l[e]) * (mean - l[e]);
}
double std = Math.sqrt(sum / (n - 1));
double pearson = 3 * (mean - median) / std;
return pearson;
}
public static double pearson(int[] l) {
int n = l.length;
Arrays.sort(l);
double median = l[n / 2];
if (n % 2 == 0) {
median = (median + l[n / 2 - 1]) / 2;
}
double sum = 0.0;
double mean = mean(l);
for (int e = 0; e < n; e++) {
sum = sum + (mean - l[e]) * (mean - l[e]);
}
double std = Math.sqrt(sum / (n - 1));
double pearson = 3 * (mean - median) / std;
return pearson;
}
public static double sd(double[] l) {
if (l.length > 1) {
double mean = mean(l);
double sum = 0.0;
for (double value: l) {
sum += Math.pow(value - mean, 2);
}
return Math.sqrt(sum / (l.length - 1));
}
return 0;
}
public static double sd(int[] l) {
if (l.length > 1) {
double mean = mean(l);
double sum = 0.0;
for (double value: l) {
sum += Math.pow(value - mean, 2);
}
return Math.sqrt(sum / (l.length - 1));
}
return 0.0;
}
}
| sinaimeri/AmoCoala | util/Statistics.java | 1,746 | /*
############################################################################
# Coala #
# CO-evolution Assessment by a Likelihood-free Approach #
############################################################################
# #
# Copyright INRIA 2018 #
# #
# Contributors : Christian Baudet #
# Beatrice Donati #
# Blerina Sinaimeri #
# Pierluigi Crescenzi #
# Christian Gautier #
# Catherine Matias #
# Marie-France Sagot #
# Laura Urbini #
# #
# [email protected] #
# [email protected] #
# https://gforge.inria.fr/forum/forum.php?forum_id=11324 #
# #
# This software is a computer program whose purpose is to estimate #
# the probability of events (co-speciation, duplication, host-switch and #
# loss) for a pair of host and parasite trees through a Approximate #
# Bayesian Computation - Sequential Monte Carlo (ABC-SMC) procedure. #
# #
# This software is governed by the CeCILL license under French law and #
# abiding by the rules of distribution of free software. You can use, #
# modify and/ or redistribute the software under the terms of the CeCILL #
# license as circulated by CEA, CNRS and INRIA at the following URL #
# "http://www.cecill.info". #
# #
# As a counterpart to the access to the source code and rights to copy, #
# modify and redistribute granted by the license, users are provided only #
# with a limited warranty and the software's author, the holder of the #
# economic rights, and the successive licensors have only limited #
# liability. #
# #
# In this respect, the user's attention is drawn to the risks associated #
# with loading, using, modifying and/or developing or reproducing the #
# software by the user in light of its specific status of free software, #
# that may mean that it is complicated to manipulate, and that also #
# therefore means that it is reserved for developers and experienced #
# professionals having in-depth computer knowledge. Users are therefore #
# encouraged to load and test the software's suitability as regards their #
# requirements in conditions enabling the security of their systems and/or #
# data to be ensured and, more generally, to use and operate it in the #
# same conditions as regards security. #
# #
# The fact that you are presently reading this means that you have had #
# knowledge of the CeCILL license and that you accept its terms. #
############################################################################
*/ | block_comment | en | true |
241337_0 | package leetcode;
/**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : PatchingArray
* Creator : Edward
* Date : Jan, 2018
* Description : 330. Patching Array
*/
public class PatchingArray {
/**
* Given a sorted positive integer array nums and an integer n,
* add/patch elements to the array such that any number in range [1, n] inclusive can be formed
* by the sum of some elements in the array. Return the minimum number of patches required.
Example 1:
nums = [1, 3], n = 6
Return 1.
Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
So we only need 1 patch.
Example 2:
nums = [1, 5, 10], n = 20
Return 2.
The two patches can be [2, 4].
Example 3:
nums = [1, 2, 2], n = 5
Return 0.
[1, 2, 5, 13, 24]
miss: 表示[0,n]之间最小的不能表示的值
num <= miss => [0, miss+num)
nums = [1, 2, 5, 13, 24], n = 50
miss = 1
1 + 2 + 4 + 5 = 12
1 : miss = 2
2 : miss = 4
5 : miss = 8 res = 1
5 : miss = 13
13 : miss = 26
24 : miss = 50 res = 2
time : O(n)
space : O(1)
* @param nums
* @param n
* @return
*/
public int minPatches(int[] nums, int n) {
int i = 0, res = 0;
long miss = 1;
while (miss <= n) {
if (i < nums.length && nums[i] <= miss) {
miss += nums[i++];
} else {
miss += miss;
res++;
}
}
return res;
}
}
| kedup/cspiration | src/leetcode/PatchingArray.java | 603 | /**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : PatchingArray
* Creator : Edward
* Date : Jan, 2018
* Description : 330. Patching Array
*/ | block_comment | en | true |
241460_2 | import java.util.*;
public class Ex{
public static void main(String[] args){
//creating object of scanner class.
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
//creating character array and passing length to it .
// length of string is length of character array(s.length)
char[] ch = new char[s.length()];
for(int i = 0; i < ch.length;i++){
ch[i] = s.charAt(i);
}
// creating new character array
char[] chr = new char[ch.length];
for(int i =0;i <chr.length ;i++){
chr[i] = ch[ch.length-1-i];
System.out.println(chr[i]);
}
//converting character array into string.
String str = String.copyValueOf(chr);
System.out.println(str);
System.out.println(s);
System.out.println(chr[0]);
//comparing String(str) with orginal string(s).
if(str.equals(s)){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
} | Divilisrikanth/Dsa | Ex.java | 280 | // length of string is length of character array(s.length) | line_comment | en | 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 |
241877_0 | package norush;
import battlecode.common.GameActionException;
import battlecode.common.RobotInfo;
import battlecode.common.RobotType;
import battlecode.common.MapLocation;
import static norush.RobotPlayer.rc;
import static norush.Helper.distx_35;
import static norush.Helper.disty_35;
public class DesignSchool {
static boolean near_hq = false;
static boolean seen_enemy_drone = false;
static boolean near_enemy_hq = false;
static int seen_drone_timeout = 0;
static MapLocation enemy_hq = null;
static int mine_count;
static int produce_attack = 0;
static int total_produced = 0;
static int produce_defense = 0;
static void runDesignSchool() throws GameActionException {
Comms.getBlocks();
mine_count = count_mine();
RobotInfo[] robots = rc.senseNearbyRobots();
int num_enemy_buildings = 0;
int num_landscapers = 0;
int num_enemy_drones = 0;
int num_enemy_fulfill = 0;
int num_enemy_design = 0;
int num_netguns = 0;
for (int i = 0; i < robots.length; i++) {
if (robots[i].team != rc.getTeam() && robots[i].type.isBuilding()) {
num_enemy_buildings++;
}
if (robots[i].team == rc.getTeam()) {
switch(robots[i].type) {
case LANDSCAPER:
num_landscapers++;
break;
case HQ:
near_hq = true;
break;
case NET_GUN:
num_netguns++;
break;
}
} else {
switch(robots[i].type) {
case FULFILLMENT_CENTER:
num_enemy_fulfill++;
break;
case DESIGN_SCHOOL:
num_enemy_design++;
break;
case DELIVERY_DRONE:
num_enemy_drones++;
seen_enemy_drone = true;
seen_drone_timeout = 0;
break;
case HQ:
near_enemy_hq = true;
enemy_hq = robots[i].location;
break;
}
}
}
seen_drone_timeout++;
if (seen_drone_timeout == 50) {
seen_drone_timeout = 0;
seen_enemy_drone = false;
}
if (Miner.gay_rush_alert && Miner.all_in) {
Miner.gay_rush_alert = false;
}
if (HQ.rushed && Miner.gay_rush_alert && near_hq && produce_defense < 6) {
if (HQ.our_hq != null) {
if (Helper.tryBuildToward(RobotType.LANDSCAPER, HQ.our_hq)) {
produce_defense++;
total_produced++;
}
} else {
if (Helper.tryBuild(RobotType.LANDSCAPER) != -1) {
produce_defense++;
total_produced++;
}
}
/*
if (produce_defense == 2) {
Comms.broadcast_all_in();
}*/
}
// build when (enemies nearby & soup high scaling on nearby landscapers) | soup high
// build more if close to HQ
if (near_enemy_hq && ((!seen_enemy_drone && num_enemy_fulfill == 0)|| num_netguns > 0)
&& (!Miner.gay_rush_alert || (rc.getTeamSoup() > RobotType.DESIGN_SCHOOL.cost + RobotType.LANDSCAPER.cost) || Comms.design_school_idx > 0)) {
Helper.tryBuildToward(RobotType.LANDSCAPER, enemy_hq);
produce_attack++;
}
if (mine_count > 200 && num_enemy_buildings > 0 && !seen_enemy_drone && num_enemy_fulfill == 0 &&
num_landscapers == 0 && rc.getTeamSoup() >= RobotType.LANDSCAPER.cost*(1+num_landscapers*(near_hq ? 0.5 : 1))) {
if (Helper.tryBuild(RobotType.LANDSCAPER) != -1) {
total_produced++;
}
}
if (rc.getTeamSoup() >= 700 || (!HQ.done_turtling && rc.getRoundNum() > 400 && HQ.our_hq != null && rc.getLocation().distanceSquaredTo(HQ.our_hq) < 100 && total_produced < 20)) {
if (Helper.tryBuildToward(RobotType.LANDSCAPER, HQ.our_hq)) {
total_produced++;
}
}
if (total_produced >= 20 && !HQ.done_turtling) {
Comms.broadcast_done_turtle();
}
/*if ((num_enemy_design > 0 && num_enemy_drones == 0 && rc.getTeamSoup() >= RobotType.LANDSCAPER.cost*(1+num_landscapers*(near_hq ? 0.5 : 1)))
|| rc.getTeamSoup() >= 500*(near_hq ? 0.5 : 1)) {
if (near_hq && num_landscapers >= 8) {
// do nothing
} else {
if (near_hq && HQ.our_hq != null) {
Helper.tryBuildToward(RobotType.LANDSCAPER, HQ.our_hq);
} else {
Helper.tryBuild(RobotType.LANDSCAPER);
}
}
}*/
}
static int count_mine() throws GameActionException {
MapLocation cur_loc = rc.getLocation();
int total_soup = 0;
for (int i = 0; i < distx_35.length; i++) {
MapLocation next_loc = cur_loc.translate(distx_35[i], disty_35[i]);
if (rc.canSenseLocation(next_loc)) {
int count = rc.senseSoup(next_loc);
total_soup += count;
}
}
return total_soup;
}
}
| poortho/battlecode-2020 | norush/DesignSchool.java | 1,515 | /*
if (produce_defense == 2) {
Comms.broadcast_all_in();
}*/ | block_comment | en | true |
242237_7 | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH & Co. KG, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.newsletter;
/**
* Content for newsletters.<p>
*/
public class CmsNewsletterContent implements I_CmsNewsletterContent {
/** The output channel for this content. */
String m_channel;
/** The content String. */
String m_content;
/** The order of this content. */
int m_order;
/** The type of this content. */
CmsNewsletterContentType m_type;
/**
* Creates a new CmsNewsletterContent instance.<p>
*
* @param order the order of the newsletter content
* @param content the content
* @param type the newsletter contents' type
*/
public CmsNewsletterContent(int order, String content, CmsNewsletterContentType type) {
m_order = order;
m_content = content;
m_type = type;
m_channel = "";
}
/**
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(I_CmsNewsletterContent o) {
return Integer.valueOf(m_order).compareTo(Integer.valueOf(((CmsNewsletterContent)o).getOrder()));
}
/**
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CmsNewsletterContent)) {
return false;
}
CmsNewsletterContent newsletterContent = (CmsNewsletterContent)obj;
if (getOrder() != newsletterContent.getOrder()) {
return false;
}
if (!getContent().equals(newsletterContent.getContent())) {
return false;
}
if (!getChannel().equals(newsletterContent.getChannel())) {
return false;
}
if (!getType().equals(newsletterContent.getType())) {
return false;
}
return true;
}
/**
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return m_channel.hashCode() + m_content.hashCode() + m_order + m_type.hashCode();
}
/**
* @see org.opencms.newsletter.I_CmsNewsletterContent#getChannel()
*/
public String getChannel() {
return m_channel;
}
/**
* @see org.opencms.newsletter.I_CmsNewsletterContent#getContent()
*/
public String getContent() {
return m_content;
}
/**
* @see org.opencms.newsletter.I_CmsNewsletterContent#getOrder()
*/
public int getOrder() {
return m_order;
}
/**
* @see org.opencms.newsletter.I_CmsNewsletterContent#getType()
*/
public CmsNewsletterContentType getType() {
return m_type;
}
} | alkacon/opencms-core | src/org/opencms/newsletter/CmsNewsletterContent.java | 932 | /**
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/ | block_comment | en | 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 |
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 |
243246_0 | import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;
// This class is used to bind keys to actions
public class KeyBinder {
private HashMap<Integer, Action> bindingMap;
public KeyBinder() {
bindingMap = new HashMap<Integer, Action>();
bindingMap.put(KeyEvent.VK_LEFT, Action.MOVE_LEFT);
bindingMap.put(KeyEvent.VK_RIGHT, Action.MOVE_RIGHT);
bindingMap.put(KeyEvent.VK_C, Action.HOLD);
bindingMap.put(KeyEvent.VK_SPACE, Action.HARD_DROP);
bindingMap.put(KeyEvent.VK_DOWN, Action.SOFT_DROP);
bindingMap.put(KeyEvent.VK_UP, Action.ROTATE_CLOCKWISE);
bindingMap.put(KeyEvent.VK_SHIFT, Action.HOLD);
bindingMap.put(KeyEvent.VK_P, Action.TOGGLE_PAUSE);
bindingMap.put(KeyEvent.VK_X, Action.ROTATE_COUNTER_CLOCKWISE);
bindingMap.put(KeyEvent.VK_CONTROL, Action.ROTATE_COUNTER_CLOCKWISE);
}
public void setKeyBinding(int keyCode, Action action) {
bindingMap.put(keyCode, action);
}
public void removeKeyBinding(int keyCode) {
bindingMap.remove(keyCode);
}
public boolean hasBinding(int keyCode) {
return bindingMap.containsKey(keyCode);
}
public Set<Integer> getKeys() {
return bindingMap.keySet();
}
public Action actionForKey(int keyCode) {
return bindingMap.get(keyCode);
}
public int keyForAction(Action action) {
for (Entry<Integer,Action> e : bindingMap.entrySet()) {
if (e.getValue() == action) {
return e.getKey();
}
}
System.out.println("welp");
return 0;
}
}
| SteveVitali/Tetris | KeyBinder.java | 450 | // This class is used to bind keys to actions | line_comment | en | true |
243342_6 | /************************************************************
* MutPanning *
* *
* Author: Felix Dietlein *
* *
* Copyright: (C) 2019 *
* *
* License: BSD-3-Clause open source license *
* *
* Summary: This is script is the second step to filter out *
* false positive significant genes. This script evaluates *
* the output from the Blat queries of the previous step. *
* In brief, if the sequence context around a hotspot *
* position was detected to have ambiguous possible *
* alignments this position and gene is masked from the *
* significance test. *
*************************************************************/
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
public class Filter_Step2 {
//static String[] file_query=new String[2];//"M:\\PostSignFilter\\Queries\\Query";
//static String[] file_output=new String[2];//"M:\\PostSignFilter\\OutputsBLAT\\Output";
//static String[] file_out=new String[2];//"M:\\PostSignFilter\\MaskedPositions";
static String[] entities=new String[0];
static boolean[] compute_uniform=new boolean[0];
static String[] index_header_samples={"ID","Sample","Cohort"};
static String[] types={"","Uniform"};
static String file_out="";
/*
* argument0: root file
* argument1: sample file
*/
public static void main(String[] args, String[] args_entities, boolean[] args_compute_uniform){
//file_query=new String[]{args[0]+"PostSignFilter/Queries/Query",args[0]+"PostSignFilter/Queries/QueryUniform"};
//file_output=new String[]{args[0]+"PostSignFilter/OutputsBLAT/Output",args[0]+"PostSignFilter/OutputsBLAT/OutputUniform"};
file_out=args[0]+"PostSignFilter/MaskedPositions/MaskedPositions";//new String[]{args[0]+"PostSignFilter/MaskedPositions/MaskedPositions",args[0]+"PostSignFilter/MaskedPositions/MaskedPositionsUniform"};
String file_query=args[0]+"/PostSignFilter/Query.fa";
String file_output=args[0]+"/PostSignFilter/OutputBLAT.txt";
if(!new File(args[0]+"PostSignFilter/MaskedPositions/").exists()){
new File(args[0]+"PostSignFilter/MaskedPositions/").mkdir();
}
//Determine all entity names, as clustering is performed separately for each Step this is needed to coordinate the order
entities=args_entities;
compute_uniform=args_compute_uniform;
try{
//for (int l=0;l<2;l++){
//for (int k=0;k<entities.length;k++){
/*if(!new File(file_query[l]+entities[k]+".fa").exists()){
continue;
}
if(!new File(file_output[l]+entities[k]+".txt").exists()){
continue;
}*/
//read all the queeries
FileInputStream in=new FileInputStream(file_query);//[l]+entities[k]+".fa"
DataInputStream inn=new DataInputStream(in);
BufferedReader input= new BufferedReader(new InputStreamReader(inn));
String s="";
ArrayList<Query> query=new ArrayList<Query>();
while((s=input.readLine())!=null){
s=s.substring(1);//identifier of the query (including gene name)
String seq=input.readLine();//sequence context of query
query.add(new Query(s,seq));
}
input.close();
int[] detected=new int[query.size()];
//go through the query results
//in brief associate the query results with the original queries
//based on their identifier. test whether the alignment is identical
//to the original sequence except for the hotspot mutation
//if this is the case the hotspot mutation is likely to be a mis-
//alignment artifact from a different region and is masked in the
//subsequent analysis
in=new FileInputStream(file_output);//[l]+entities[k]+".txt"
inn=new DataInputStream(in);
input= new BufferedReader(new InputStreamReader(inn));
while((s=input.readLine())!=null){
if(s.contains("--------")){
break;
}
}
while((s=input.readLine())!=null){
String[] t=s.split(" ");
if(!t[17].equals("1")){//no blocks
continue;
}
String name_complete=t[9];
//System.out.println(name_complete);
int alignment_start=Integer.parseInt(t[11]);
String original_seq=t[21].split(",")[0].toUpperCase();
String aligned_seq=t[22].split(",")[0].toUpperCase();
if(t[8].equals("-")){
original_seq=reverse(original_seq);
aligned_seq=reverse(aligned_seq);
}
//System.out.println(index(name_complete,query));
if(index(name_complete,query)==-1){
continue;
}
int[] alignment_index=new int[query.get(index(name_complete,query)).seq.length()];
for (int i=0;i<alignment_index.length;i++){
alignment_index[i]=-1;
}
for (int i=0;i<original_seq.length();i++){
if(original_seq.charAt(i)==query.get(index(name_complete,query)).seq.charAt(alignment_start+i)){
if(original_seq.charAt(i)==aligned_seq.charAt(i)){
alignment_index[alignment_start+i]=1;
}
else{
alignment_index[alignment_start+i]=0;
}
}
else{
alignment_index[alignment_start+i]=-1;
}
}
String[] ttt=name_complete.split(":");
String[] tt=ttt[1].split(";");
String gene=tt[0].split("_")[0];
String type=tt[0].split("_")[1];
int count=Integer.parseInt(tt[2]);
int start_index=Integer.parseInt(tt[1].split(",")[0]);
int end_index=Integer.parseInt(tt[1].split(",")[1]);
//System.out.println(name_complete+" "+gene+" "+type+" "+count+" "+start_index+" "+end_index);
if(!type.equals("alt")){
continue;
}
if(alignment_index[-start_index]!=1){
continue;
}
int prev=0;
while(-start_index+prev>=0&&alignment_index[-start_index+prev]==1){
prev--;
}
prev++;
int post=0;
while(-start_index+post<alignment_index.length&&alignment_index[-start_index+post]==1){
post++;
}
post--;
if(post-prev+1>=25){
detected[index(name_complete,query)]=1;
}
}
input.close();
//for (int i=0;i<query.size();i++){
// System.out.println(query.get(i).name+" "+detected[i]);
//}
FileWriter[][] out=new FileWriter[entities.length][2];//(file_out[l]+entities[k]+".txt");
BufferedWriter[][] output= new BufferedWriter[entities.length][2];//(out);
for (int i=0;i<entities.length;i++){
out[i][0]=new FileWriter(file_out+entities[i]+".txt");
output[i][0]=new BufferedWriter(out[i][0]);
if(compute_uniform[i]){
out[i][1]=new FileWriter(file_out+"Uniform"+entities[i]+".txt");
output[i][1]=new BufferedWriter(out[i][1]);
}
}
for (int i=0;i<query.size();i++){
if(detected[i]==1){
String[] ttt=query.get(i).name.split(":");
String[] tttt=ttt[0].split("_");
int kk=-1;
if(tttt.length>1){
kk=index(tttt[1],types);
}
else{
kk=0;
}
//output[index(tttt[0],entities)][kk].write(query.get(i).name);
//output[index(tttt[0],entities)][kk].newLine();
output[index(tttt[0],entities)][kk].write(ttt[1].split(";")[0].split("_")[0]+" "+ttt[1].split(";")[3].split(",")[0]+" "+ttt[1].split(";")[3].split(",")[1]+" "+ttt[1].split(";")[3].split(",")[2]);
output[index(tttt[0],entities)][kk].newLine();
}
}
for (int i=0;i<output.length;i++){
for (int j=0;j<output[i].length;j++){
if(output[i][j]!=null){
output[i][j].close();
}
}
}
/*
//output of the misalginment positions found
FileWriter out=new FileWriter(file_out[l]+entities[k]+".txt");
BufferedWriter output= new BufferedWriter(out);
for (int i=0;i<query.size();i++){
if(detected[i]==1){
output.write(query.get(i).name.split(";")[0].split("_")[0]+" "+query.get(i).name.split(";")[3].split(",")[0]+" "+query.get(i).name.split(";")[3].split(",")[1]+" "+query.get(i).name.split(";")[3].split(",")[2]);
output.newLine();
}
}
output.close();
*/
//}
//}
}
catch(Exception e){
StackTraceElement[] aa=e.getStackTrace();
for (int i=0;i<aa.length;i++){
System.out.println(i+" "+aa[i].getLineNumber());
}
System.out.println(e);
}
}
public static int index(String s, String[] t){
for (int i=0;i<t.length;i++){
if(t[i].equals(s)){
return i;
}
}
return -1;
}
public static int[] index_header(String[] header, String[] ideal_header){
int[] indices=new int[ideal_header.length];
for (int i=0;i<ideal_header.length;i++){
int index=-1;
for (int j=0;j<header.length;j++){
if(header[j].equals(ideal_header[i])){
index=j;
break;
}
}
indices[i]=index;
}
return indices;
}
public static String ou(int[] array){
String ou="";
for (int i=0;i<array.length;i++){
if(i>0){
ou=ou+"|"+array[i];
}
else{
ou=ou+array[i];
}
}
return ou;
}
public static String reverse(String s){
String rev="";
for (int i=0;i<s.length();i++){
if(s.charAt(i)=='A'){
rev="T"+rev;
}
else if(s.charAt(i)=='C'){
rev="G"+rev;
}
else if(s.charAt(i)=='G'){
rev="C"+rev;
}
else if(s.charAt(i)=='T'){
rev="A"+rev;
}
else{
rev="N"+rev;
}
}
return rev;
}
public static int index(String name, ArrayList<Query> query){
for (int i=0;i<query.size();i++){
if(query.get(i).name.equals(name)){
return i;
}
}
return -1;
}
private static class Query{
String name="";
String seq="";
public Query(String name, String seq){
this.name=name;
this.seq=seq;
}
}
public static boolean contains(String s, ArrayList<String> t){
for (int i=0;i<t.size();i++){
if(t.get(i).equals(s)){
return true;
}
}
return false;
}
}
| vanallenlab/MutPanningV2 | Filter_Step2.java | 3,278 | //file_output=new String[]{args[0]+"PostSignFilter/OutputsBLAT/Output",args[0]+"PostSignFilter/OutputsBLAT/OutputUniform"};
| line_comment | en | true |
243344_43 | /*
* @file Game.java
*
* @brief Classe que representa o jogo e contem a main
*
* @author Alexandre Marques Carrer <[email protected]>
* @author Felipe Bagni <[email protected]>
* @author Gabriel Yugo Kishida <[email protected]>
* @author Gustavo Azevedo Correa <[email protected]>
*
* @date 05/2020
*
*/
import java.awt.*;
import java.awt.image.BufferStrategy;
public class Game extends Canvas implements Runnable {
private GameState state;
private static final long serialVersionUID = 1L;
private Thread thread;
private boolean running = false; //Flag that indicates if the game is running
private boolean muted = false; //Flag that indicates if the audio is muted
private boolean paused = false; //Flag that indicates if the game is paused
private boolean restart = false; //Flag that stops the game from rendering the map while it is being restarted
private int width; //Largura da tela criada
private int height; //Altura da tela criada
private int maxPoints; //Numero maximo de pontos atingiveis pelo jogador
private int fixedTickFlag = 0; //Numero de miniticks
private String mapFileName; //Game's map path
private static final int fixedTickMax = 60; //Numero de miniticks a serem atingidos a cada fixedTick
private MapHandler mapHandler; //Handler dos objetos que nao se movem
private EntityHandler entityHandler; //Handler dos objetos que se movem
PacMan player; //Objeto que representa o jogador
Window window; //Tela do jogo
private int totalPoints = 0; //Pontos totais do jogador
private AudioPlayer songPlayer; //Game's music player
public AudioPlayer easterEgg; //Find out playing
private boolean easterFlag = false;
public Game(String mapFileName) {
this.mapFileName = mapFileName;
state = new Difficulty1(mapFileName);
gamePrepare(mapFileName);
setStateVariables();
window = new Window(width, height, "Projeto Pacman", this); //Constroi janela do jogos
}
public void setPause(boolean paused) {this.paused = paused;} //Pauses the game
public boolean isPaused() {return this.paused;} //Indicates if the game is paused
public void setRestart(boolean restart) {this.restart = restart;} //Restarts the game
public boolean isRestarting() {return this.restart;} //Indicates that the game is being restarted
/*
* @brief prepares game (reads map from txt file, sets objects to their initial positions)
*/
public void gamePrepare(String newMapFile) {
MapBuilder mapBuilder = new MapBuilder(newMapFile); //Le o mapa
mapHandler = new MapHandler(mapBuilder.getHeight(), mapBuilder.getWidth()); //Constroi o handler com o mapa
player = mapBuilder.getPlayer(); //Pega o jogador
width = mapBuilder.getWidth()*MapObject.squareSize; //Pega as dimensoes da tela
height = mapBuilder.getHeight()*MapObject.squareSize;
mapHandler.setMap(mapBuilder.build()); //Constroi os objetos do mapa
entityHandler = new EntityHandler(mapBuilder.getGhosts(), player); //Constroi handler para os objetos que se movem
maxPoints = mapBuilder.getMaxPoints(); //Pega os pontos maximos que podem ser feitos no jogo
}
/*
* @brief Starts game thread
*/
public synchronized void start() {
thread = new Thread(this);
thread.start();
running = true;
}
/*
* @brief Stops game thread
*/
public synchronized void stop() {
try {
//System.exit(-1);
thread.join();
running = false;
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* @brief Sets the game difficulty
*/
private void setState(int difficulty, String mapFileName) {
switch(difficulty) {
case 1:
this.state = new Difficulty1(mapFileName);
break;
case 2:
this.state = new Difficulty2(mapFileName);
break;
case 3:
this.state = new Difficulty3(mapFileName);
break;
case 4:
this.state = new Difficulty4(mapFileName);
break;
case 5:
this.state = new Difficulty5(mapFileName);
break;
}
}
/*
* @brief Sets the game variables that rely on the game state
*/
void setStateVariables(){
player.setLives(state.getLives());
player.setMaxBoostedTime(state.getBoostTime());
songPlayer = new AudioPlayer(state.getLevelNumber());
songPlayer.changeSound(AudioPlayer.initVolume);
songPlayer.play();
}
/*
* @brief Update the audio for the look-n-feel
*/
public void updateAudio() {
songPlayer.stop();
songPlayer = new AudioPlayer(state.getLevelNumber());
songPlayer.play();
}
/*
* @brief Toggles mute
*/
public void mute() {
muted = !muted;
if(muted) {
songPlayer.changeSound(-10000.0f);
if(easterFlag) easterEgg.changeSound(-10000.0f);
} else {
songPlayer.changeSound(AudioPlayer.initVolume);
if(easterFlag) easterEgg.changeSound(AudioPlayer.initVolume);
}
}
/*
* @brief EasterEgg routine
*/
public void easterEgg() {
if (!easterFlag) {
easterEgg = new AudioPlayer("kazzoo.aif");
} else {
easterEgg.stop();
}
easterFlag = !easterFlag;
}
/*
* @brief Pattern GameLoop: Game loop that keeps it updated in real time
*/
public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 120.0; //Amount of ticks per second
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
@SuppressWarnings("unused")
int frames = 0;
while(running) {
long now = System.nanoTime();
delta += (now - lastTime)/ns;
lastTime = now;
while (delta >= 1) {
tick();
delta--;
}
if(running) render();
frames++;
if(System.currentTimeMillis() - timer > 1000) {
timer += 1000;
frames = 0;
}
}
stop();
}
/*
* @brief Renders all game objects
*/
private void render() {
//Use with BufferedImage
if(!restart) {
BufferStrategy bufferStrategy = this.getBufferStrategy();
if (bufferStrategy == null) {
this.createBufferStrategy(3);
return;
}
Graphics graphics = bufferStrategy.getDrawGraphics();
mapHandler.renderMap(graphics);
entityHandler.render(graphics);
graphics.dispose();
bufferStrategy.show();
}
}
/*
* @brief Returns whether the player got all obligatory points in the game
*/
public boolean gotAllPoints() {
return player.getPoints() >= maxPoints;
}
/*
* @brief Updates all game objects skins
*/
public void setSkin() {
mapHandler.updateAllSprites();
entityHandler.updateAllSprites();
}
/*
* @brief Updates all game objects (positions, directions, etc.)
*/
private void tick() {
if(!paused) {
if(player.getLives() == 0) {
System.out.println("Perdeu :(");
paused = true;
}
mapHandler.tick();
entityHandler.tick();
if(entityHandler.playerDied()) {
entityHandler.playerDeathReset();
if(player.getLives()>100) System.out.println("Vidas: INFINITAS");
else System.out.println("Vidas:" + player.getLives());
}
if(player.getBoostedTime() >= state.getBoostTime() - 1) {
if(!player.isAlreadyBoosted()) this.player = new PacManBoostDecorator(player);
entityHandler.setAllGhostsEscape();
entityHandler.setPlayer(player);
}
if(player.getBoostedTime() <= 360) {
entityHandler.setEndOfEscape();
}
if(player.lastBoostDrop) {
this.player = player.getPlayer();
entityHandler.setPlayer(player);
entityHandler.setAllGhostsOriginalStrategy();
}
if(gotAllPoints()) {
if(state.getLevelNumber() == 5) {
paused = true;
}
totalPoints += (int)(state.getPointMultiplier()*player.totalPoints());
System.out.println("Ganhou!!!");
System.out.println("Pontuacao: " + Integer.toString(totalPoints));
paused = true;
}
fixedTick();
}
}
/*
* @brief Resets game in the current level
*/
public void reset() {
restart = true;
if(gotAllPoints()) totalPoints -= (int)(state.getPointMultiplier()*player.totalPoints());
gamePrepare(mapFileName);
songPlayer.stop();
setStateVariables();
}
/*
* @brief Prepares the game for the next level
*/
public void nextLevel() {
restart = true;
gamePrepare(mapFileName);
if(state.getLevelNumber() < 5) {
setState(state.getLevelNumber() + 1, mapFileName);
System.out.println("Nivel:" + state.getLevelNumber());
} else {
System.out.println("Voce � o bich�o mesmo ein doido");
stop();
}
songPlayer.stop();
setStateVariables();
}
/*
* @brief Pauses the game (lowers song volume as well)
*/
public void pause() {
paused = !paused;
if(paused) songPlayer.changeSound(-35.0f);
else songPlayer.changeSound(AudioPlayer.initVolume);
}
/*
* @brief fixed tick (works like the tick, but with a smaller frequency)
*/
private void fixedTick() {
if(fixedTickFlag < fixedTickMax) {
fixedTickFlag++;
} else {
entityHandler.fixedTick();
fixedTickFlag = 0;
}
}
/*
* @brief main function
*/
public static void main(String[] args) {
new Game(args[0]);
}
}
| febagni/project-pacman | src/Game.java | 2,749 | /*
* @brief Returns whether the player got all obligatory points in the game
*/ | block_comment | en | true |
244030_0 | < !DOCTYPE html >
<html>
<head>
<title>USER MANAGEMENT APPLICATION < / title >
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"> < / script >
<script>
var app = angular.module("userMgmtApp", []);
app.controller("userMgmtAppCntrl", function ($scope) {
$scope.users = [
{ 'name': "Dr. Harish Kumar BT", 'email': '[email protected]', 'editing': false },
{ 'name': 'ABC', 'email': '[email protected]', 'editing': false },
{ 'name': 'XYZ', 'email': '[email protected]', 'editing': false }
];
$scope.createUser = function () {
if ($scope.newUserName && $scope.newUserEmail) {
var u = {
'name': $scope.newUserName,
'email': $scope.newUserEmail,
'editing': false
};
$scope.users.push(u);
$scope.newUserName = '';
$scope.newUserEmail = '';
} else {
alert("Please provide the user name and email id");
}
};
$scope.readUser = function (user) {
user.editing = true;
};
$scope.updateUser = function (user) {
user.editing = false;
};
$scope.deleteUser = function (user) {
var yes = confirm("Are you sure you want to delete");
if (yes == true) {
var index = $scope.users.indexOf(user);
$scope.users.splice(index, 1);
}
};
});
< / script >
< / head >
< body ng - app = "userMgmtApp" >
<h1>USER MANAGEMENT APPLICATION < / h1 >
< div ng - controller = "userMgmtAppCntrl" >
Enter the User Name: < input type = "text" ng - model = "newUserName" >
Enter the User Email: < input type = "text" ng - model = "newUserEmail" >
< button ng - click = "createUser()" > Create < / button >
< br / > < br / >
<table border = "1">
<tr>
<th>SLNO < / th >
<th>NAME < / th >
<th>EMAIL < / th >
<th>READ < / th >
<th>UPDATE < / th >
<th>DELETE < / th >
< / tr >
< tr ng - repeat = "user in users" >
<td> {{$index + 1}} < / td >
<td>
< span ng - hide = "user.editing" > {{user.name}} < / span > & nbsp; & nbsp; & nbsp; & nbsp;
< input type = "text" ng - show = "user.editing" ng - model = "user.name" >
< / td >
<td>
< span ng - hide = "user.editing" > {{user.email}} < / span >
< input type = "text" ng - show = "user.editing" ng - model = "user.email" >
< / td >
<td>
< button ng - click = "readUser(user)" > Read < / button >
< / td >
<td>
< button ng - click = "updateUser(user)" > Update < / button >
< / td >
<td>
< button ng - click = "deleteUser(user)" > Delete < / button >
< / td >
< / tr >
< / table >
< / div >
< / body >
< / html >
| Mayank-Raj3/Code- | p7.java | 876 | //ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"> < / script > | line_comment | en | true |
244311_0 | package collections.nestedliststring;
import java.util.List;
/**
* Input:---
* List = ['a string', ['a','b','c'], 'spam', ['eggs']]
*
* Output:---
* Foo.0: a string
* Foo.1.0: a
* Foo.1.1 : b
* Foo.1.2: c
* Foo.2: spam
* Foo.3.0: eggs
*
* http://www.programmerinterview.com/index.php/general-miscellaneous/nested-list-recursion/
*
* User: rpanjrath
* Date: 10/16/13
* Time: 11:15 AM
* To change this template use File | Settings | File Templates.
*/
public class NestedList {
private static final String PERIOD = ".";
private static final String COLON = ": ";
private NestedList() {
}
public static void dumpList(String str, List inputList) {
for (int i = 0; i < inputList.size(); i++) {
if (inputList.get(i) instanceof List) {
dumpList(str + PERIOD + i, (List) inputList.get(i));
} else {
System.out.println(str + PERIOD + i + COLON + inputList.get(i));
}
}
}
}
| techpanja/interviewproblems | src/collections/nestedliststring/NestedList.java | 326 | /**
* Input:---
* List = ['a string', ['a','b','c'], 'spam', ['eggs']]
*
* Output:---
* Foo.0: a string
* Foo.1.0: a
* Foo.1.1 : b
* Foo.1.2: c
* Foo.2: spam
* Foo.3.0: eggs
*
* http://www.programmerinterview.com/index.php/general-miscellaneous/nested-list-recursion/
*
* User: rpanjrath
* Date: 10/16/13
* Time: 11:15 AM
* To change this template use File | Settings | File Templates.
*/ | block_comment | en | true |
244404_1 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package hospitalinfosystem;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
/**
*
* @author Karee
*/
public class dbCon {
String DBURL = "jdbc:oracle:thin:@coeoracle.aus.edu:1521:orcl";
String DBUSER = "b00092054";
String DBPASS = "b00092054";
Connection con;
Statement statement;
PreparedStatement prepStatement;
ResultSet rs;
public dbCon(){
try {
// Load Oracle JDBC Driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// Connect to Oracle Database
con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (ClassNotFoundException | SQLException e) {
javax.swing.JLabel label = new javax.swing.JLabel("SQL ErroR - Retreiving usename/password.");
label.setFont(new java.awt.Font("Arial", java.awt.Font.BOLD, 18));
JOptionPane.showMessageDialog(null, label, "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
// returns records selected
public ResultSet executeStatement(String strSQL) throws SQLException {
// make the result set scrolable forward/backward updatable
statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
// populate valid mgr numbers
rs = statement.executeQuery(strSQL);
return rs;
}
// update, insert (return number of records affected
public int executePrepared(String strSQL) throws SQLException {
prepStatement = con.prepareStatement(strSQL);
return prepStatement.executeUpdate();
}
}
| Kareem404/hospital-database-management-system- | dbCon.java | 488 | /**
*
* @author Karee
*/ | block_comment | en | true |
245069_0 | /*****************************************************************************
* Copyright North Dakota State University, 2001
* Written By Bradley Vender ([email protected])
*
* This source is licensed under the GNU LGPL v2.1
* Please read http://www.gnu.org/copyleft/lgpl.html for more information
*
* This software comes with the standard NO WARRANTY disclaimer for any
* purpose. Use it at your own risk. If there's a problem you get to fix it.
*
*****************************************************************************/
import vrml.eai.Browser;
import vrml.eai.Node;
/**
* ReplaceWorld is a basic EAI test program. The sequence of operations is
* <UL>
* <LI> setBrowserFactory, getBrowserComponent, getBrowser, etc.
* <LI> createVrmlFromString
* <LI> replaceWorld with the newly created nodes
* <LI> Expect to see a sphere on the display
* </UL>
*/
public class BasicReplaceWorld {
public static void main(String[] args) {
Browser browser=TestFactory.getBrowser();
Node nodes[]=browser.createVrmlFromString(
" Shape {\n"+
"appearance Appearance {\n"+
" material Material {\n"+
" emissiveColor 0 0 1\n"+
" }\n"+
"}\n"+
"geometry Sphere {radius 1}\n"+
"}\n"+
"Viewpoint {}\n"
);
if (nodes.length==2)
System.out.println("Correct number of nodes produced.");
else
System.out.println("Expected two nodes but got :"+nodes.length);
browser.replaceWorld(nodes);
System.out.println("Done.");
}
}
| Norkart/NK-VirtualGlobe | Xj3D/parsetest/eai/BasicReplaceWorld.java | 418 | /*****************************************************************************
* Copyright North Dakota State University, 2001
* Written By Bradley Vender ([email protected])
*
* This source is licensed under the GNU LGPL v2.1
* Please read http://www.gnu.org/copyleft/lgpl.html for more information
*
* This software comes with the standard NO WARRANTY disclaimer for any
* purpose. Use it at your own risk. If there's a problem you get to fix it.
*
*****************************************************************************/ | block_comment | en | true |
245213_0 |
import java.io.*;
import java.util.*;
/**
* Write a description of class Applicant here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Applicant
{
private final double averageAdjust = 16.1;
private final String[] programGroups = {"Biomedical and Software", "Computer, Electrical, Mechanical, Mechatronics, and Systems Design", "Architectural, Chemical, Civil, Environmental, Geological, Management, and Nanotechnology"};
private int programGroup;
private double average;
private double adjustedAverage;
private double realAdjustedAverage;
private double adjustmentFactor;
private double aifScore;
private double interviewScore;
private double chance;
public Applicant()
{
programGroup = -1;
average = -1;
adjustedAverage = -1;
adjustmentFactor = 16.1;
aifScore = -1;
interviewScore = -1;
chance = -1;
}
public void testApplicant()
{
programGroup = 2;
average = 94.5;
adjustedAverage = -1;
adjustmentFactor = 16.1;
aifScore = 3;
interviewScore = 2;
chance = 0;
}
public void setAverage (double average)
{
this.average = average;
}
public void setAdjustmentFactor (double adjustmentFactor)
{
this.adjustmentFactor = adjustmentFactor;
}
public void setProgramGroup (int programGroup)
{
this.programGroup = programGroup;
}
public void setAIFScore (double aifScore)
{
this.aifScore = aifScore;
}
public void setInterviewScore (double interviewScore)
{
this.interviewScore = interviewScore;
}
public double returnAdjustedAverage()
{
System.out.println("Your Adjusted Admission Average is: " + adjustedAverage);
return adjustedAverage;
}
public double returnRealAdjustedAverage()
{
System.out.println("Your Adjusted Admission Average including AIF and Interview is: " + realAdjustedAverage);
return realAdjustedAverage;
}
public double returnChance()
{
System.out.println("Your Chance of Admission* is: " + chance + "%");
return chance;
}
public String returnPrograms()
{
System.out.println("Your selected program group: " + programGroups[programGroup-1]);
return programGroups[programGroup-1];
}
public void calculateChance()
{
adjustedAverage = average - adjustmentFactor + averageAdjust;
adjustedAverage = round(adjustedAverage);
double x = adjustedAverage + aifScore - 2;
x = x + interviewScore - 2;
x = round(x);
if(x > 100) {
x = 100;
}
else if (x < 80) {
x = 80;
}
realAdjustedAverage = x;
switch(programGroup)
{
case 1:
chance = -0.000000991665*Math.pow(x,6)+0.000712766582*Math.pow(x,5)-0.199337541744*Math.pow(x,4)+28.477751641706*Math.pow(x,3)-2221.069055798020*Math.pow(x,2)+90365.708229188000*x-1505792.893230060000;
break;
case 2:
chance = 0.000007927378*Math.pow(x,6)-0.003815953092*Math.pow(x,5)+0.753733211049*Math.pow(x,4)-77.9121684881*Math.pow(x,3)+4421.4707888*Math.pow(x,2)-129515.4702471*x +1507941.8835368;
break;
case 3:
chance = 0.0005942718*Math.pow(x,4) - 0.2085009655*Math.pow(x,3) + 27.0594414776*Math.pow(x,2) - 1532.9010505906*x + 31865.616776;
break;
default:
break;
}
chance = round(chance);
}
public double round(double num)
{
double chance = num;
chance = chance * 10;
chance = Math.round(chance);
chance = chance/10;
return chance;
}
public static void main(String[] args)
{
Applicant a = new Applicant();
a.testApplicant();
a.calculateChance();
a.returnPrograms();
a.returnAdjustedAverage();
a.returnRealAdjustedAverage();
a.returnChance();
}
}
| WilliamUW/ChanceMeCode | Applicant.java | 1,288 | /**
* Write a description of class Applicant here.
*
* @author (your name)
* @version (a version number or a date)
*/ | block_comment | en | true |
245226_0 | // 14.1 In terms of inheritance, what is the point of declaring the constructor as private?
// Answer:
// 1. private member cannot be inherited, thus the class cannot be inherited.
// 2. constructor is private, so you cannot new an object freely. Only through public static member method can you get an instance of this class.
// 3. with this you can implement Singleton Pattern, which ensures that a class has at most one instance within an application. You can but you don't have to do it.
public class TestJava {
private static TestJava instance = null;
public static TestJava getInstance() {
if (instance == null) {
instance = new TestJava();
}
return instance;
}
public void f() {
System.out.println("TestJava::f()");
}
private TestJava() {
}
public static void main(String[] args) {
System.out.println("Hello world.");
TestJava testJava = TestJava.getInstance();
testJava.f();
}
} | jiguang123/Big-Data-Learning-Note | 07_数据结构与算法/Cracking-the-Coding-Interview/p14-1.java | 247 | // 14.1 In terms of inheritance, what is the point of declaring the constructor as private? | line_comment | en | true |
245241_2 | package jPractice;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Interview1 {
public static void main(String[] args) {
List<List<Integer>> inputList = new ArrayList<>();
/*
1 2 1 1 1
3 3 3 1 1
4 2 3 2 1
4 3 3 4 2
4 4 4 4 2
*/
inputList.add(Arrays.asList(1,2,1,1,1));
inputList.add(Arrays.asList(3,3,3,1,1));
inputList.add(Arrays.asList(4,2,3,2,1));
inputList.add(Arrays.asList(4,3,3,4,2));
inputList.add(Arrays.asList(4,4,4,4,2));
System.out.println(counter(inputList));
/*
1 2 1 1 1
3 3 3 1 1
4 2 3 2 1
3 3 3 4 4
4 4 4 4 4
*/
inputList.clear();
inputList.add(Arrays.asList(1,2,1,1,1));
inputList.add(Arrays.asList(3,3,3,1,1));
inputList.add(Arrays.asList(4,2,3,2,1));
inputList.add(Arrays.asList(3,3,3,4,4));
inputList.add(Arrays.asList(4,4,4,4,4));
System.out.println(counter(inputList));
/*
1 2 1 1 1 1 1 2 3
3 3 3 1 1 1 1 2 3
4 2 3 2 1 1 1 2 2
3 3 3 4 4 1 1 2 3
4 4 4 4 4 1 1 1 1
*/
inputList.clear();
inputList.add(Arrays.asList(1,2,1,1,1,1,1,2,3));
inputList.add(Arrays.asList(3,3,3,1,1,1,1,2,3));
inputList.add(Arrays.asList(4,2,3,2,1,1,1,2,2));
inputList.add(Arrays.asList(3,3,3,4,4,1,1,2,3));
inputList.add(Arrays.asList(4,4,4,4,4,1,1,1,1));
System.out.println(counter(inputList));
}
public static int counter(List<List<Integer>> list){
for(List<Integer> innerList:list)
System.out.println(innerList);
if(list.size() == 0)
System.out.println("Wrong input format");
Integer[][] inputArray = new Integer[list.size()][];
Integer[][] counterArray = new Integer[list.size()][list.get(0).size()];
int i = 0;
for(List<Integer> innerList: list){
inputArray[i] = (Integer[]) innerList.toArray();
for(int j = 0; j < innerList.size(); j++)
counterArray[i][j] = 0;
i++;
}
int cellValue = inputArray[0][0];
int counter = 1;
for(i = 0; i < inputArray.length; i++)
for(int j = 0; j < inputArray[0].length; j++){
if(counterArray[i][j] == 0) {
//System.out.println("********************************");
counterArray[i][j] = 1;
filler(inputArray, counterArray, i, j, counter);
counter++;
}
}
//System.out.println(Arrays.deepToString(inputArray));
//System.out.println("********************************");
//System.out.println(Arrays.deepToString(counterArray));
//System.out.println("counter = " + --counter);
return --counter;
}
public static void filler(Integer[][] inputArray, Integer[][] counterArray, int i, int j, int counter){
int cellValue = inputArray[i][j];
if(j > 0 && (counterArray[i][j - 1]) == 0 && inputArray[i][j - 1] == cellValue){
counterArray[i][j - 1] = 1;
filler(inputArray, counterArray, i, j - 1, counter);
}
if(i > 0 && (counterArray[i - 1][j]) == 0 && inputArray[i - 1][j] == cellValue){
counterArray[i - 1][j] = 1;
filler(inputArray, counterArray, i - 1, j, counter);
}
if(j < (counterArray[0].length - 1) && (counterArray[i][j + 1]) == 0 && inputArray[i][j + 1] == cellValue){
counterArray[i][j + 1] = 1;
filler(inputArray, counterArray, i, j + 1, counter);
}
if(i < (counterArray.length - 1) && (counterArray[i + 1][j]) == 0 && inputArray[i + 1][j] == cellValue){
counterArray[i + 1][j] = 1;
filler(inputArray, counterArray, i + 1, j, counter);
}
//System.out.println(Arrays.deepToString(counterArray));
}
} | flippantgriffin/HomeWork4 | Interview1.java | 1,381 | /*
1 2 1 1 1 1 1 2 3
3 3 3 1 1 1 1 2 3
4 2 3 2 1 1 1 2 2
3 3 3 4 4 1 1 2 3
4 4 4 4 4 1 1 1 1
*/ | block_comment | en | true |
245266_0 | package customiterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: rpanjrath
* Date: 9/12/13
* Time: 1:36 PM
*/
public class Animal implements Iterable<String> {
private List<Animal> animalList = new ArrayList<Animal>();
public Animal(List animalList) {
this.animalList = animalList;
}
public List getAnimal() {
return animalList;
}
@Override
public Iterator<String> iterator() {
return new AnimalIterator(this);
}
}
| yfcheng/hackerrank | interview-problems/customiterator/Animal.java | 154 | /**
* Created with IntelliJ IDEA.
* User: rpanjrath
* Date: 9/12/13
* Time: 1:36 PM
*/ | block_comment | en | true |
245714_5 | /**
*
* Queen.java
*
* Author: Chris Livingston
*
* Description: A java class that solves the classic Queens Problem requiring
* a solution where no Queen in able to capture another. The user supplies a number N
* to serve as the dimensions of an NxN chessboard. The solutions are printed to standard output.
* I capped the input number at 20 but this algorithm can scale much higher.
*
*/
public class Queen {
/**
* Helper method to check if a queen is attempting to be placed in an invalid position
*
*
*/
public static boolean isConsistent(int[] q, int n) {
for (int i = 0; i < n; i++) {
if (q[i] == q[n]) return false; // same column
if ((q[i] - q[n]) == (n - i)) return false; // same major diagonal
if ((q[n] - q[i]) == (n - i)) return false; // same minor diagonal
}
return true;
}
/**
* This method prints a queens problem solution 'q' on the console or stdout.
*
*
*/
public static void printQueens(int[] q) {
int N = q.length;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (q[i] == j) System.out.print("Q ");
else System.out.print("* ");
}
System.out.println();
}
System.out.println();
}
/**
* Initial call to enumerate the input
*
*/
public static void enumerate(int N) {
int[] a = new int[N];
enumerate(a, 0);
}
/**
* Recursive backtracking function that calls itself as long as it
* maintains a valid solution in q[] and 'backtracks' if isConsistent() finds that a
* proposed queen placement conflicts with an existing queen placement in q[].
*/
public static void enumerate(int[] q, int n) {
int N = q.length;
if (n == N) printQueens(q);
else {
for (int i = 0; i < N; i++) {
q[n] = i;
if (isConsistent(q, n)) enumerate(q, n+1);
}
}
}
public static void main(String [] args){
int x = args.length;
// args check
if (x != 1) {
System.err.println("Correct Usage: java Queen [N denoting NxN matrix to solve (MAX 20)]");
System.exit(1);
}
int n = Integer.parseInt(args[0]);
// input size check
if (n > 20) {
System.err.println("Size of board must be less than 20");
}
// call inital enumerate function to begin
enumerate(n);
}
}
| CMLivingston/QueensProblem | Queen.java | 729 | /**
* This method prints a queens problem solution 'q' on the console or stdout.
*
*
*/ | block_comment | en | true |
246081_0 | /**
* Problem Description
* You are given the root node of a binary tree A. You have to find the number of nodes in this tree.
* Problem Constraints
* 1 <= Number of nodes in the tree <= 105
*
* 0 <= Value of each node <= 107
*
*
*
* Input Format
* The first and only argument is a tree node A.
*
*
*
* Output Format
* Return an integer denoting the number of nodes of the tree.
*
*
*
* Example Input
* Input 1:
*
* Values = 1
* / \
* 4 3
* Input 2:
*
*
* Values = 1
* / \
* 4 3
* /
* 2
*
*
* Example Output
* Output 1:
*
* 3
* Output 2:
*
* 4
*
*
* Example Explanation
* Explanation 1:
*
* Clearly, there are 3 nodes 1, 4 and 3.
* Explanation 2:
*
* Clearly, there are 4 nodes 1, 4, 3 and 2.
*/
package Tree;
public class NodesCount {
public static void main(String[] args) {
TreeNode root = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)), new TreeNode(3, new TreeNode(6), new TreeNode(7)));
int ans = solve(root);
System.out.println(ans);
}
public static int solve(TreeNode root) {
if (root == null) return 0;
return 1 + solve(root.left) +solve(root.right);
}
}
| uday510/DSA | Tree/NodesCount.java | 414 | /**
* Problem Description
* You are given the root node of a binary tree A. You have to find the number of nodes in this tree.
* Problem Constraints
* 1 <= Number of nodes in the tree <= 105
*
* 0 <= Value of each node <= 107
*
*
*
* Input Format
* The first and only argument is a tree node A.
*
*
*
* Output Format
* Return an integer denoting the number of nodes of the tree.
*
*
*
* Example Input
* Input 1:
*
* Values = 1
* / \
* 4 3
* Input 2:
*
*
* Values = 1
* / \
* 4 3
* /
* 2
*
*
* Example Output
* Output 1:
*
* 3
* Output 2:
*
* 4
*
*
* Example Explanation
* Explanation 1:
*
* Clearly, there are 3 nodes 1, 4 and 3.
* Explanation 2:
*
* Clearly, there are 4 nodes 1, 4, 3 and 2.
*/ | block_comment | en | true |
246817_1 | /*
* Copyright (c) 2014, Massachusetts Institute of Technology
* Released under the BSD 2-Clause License
* http://opensource.org/licenses/BSD-2-Clause
*/
package jed;
/**
* @author Philip DeCamp
*/
public interface Function11 {
public double apply( double x );
}
| charlesdavid/JED | src/jed/Function11.java | 84 | /**
* @author Philip DeCamp
*/ | block_comment | en | 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 |
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 |
247672_1 | package hus.oop.de1.fraction;
import java.util.Arrays;
import java.util.Comparator;
import hus.oop.lab11.abstractfactory.shape.FactoryProducer;
public class DataSet {
private static int DEFAULT_CAPACITY = 8;
private Fraction[] data;
private int length;
/**
* Hàm dựng khởi tạo mảng chứa các phân số có kích thước là DEFAULT_CAPACITY.
*/
public DataSet() {
data = new Fraction[DEFAULT_CAPACITY];
length = 0;
}
/**
* Hàm dựng khởi tạo mảng chứa các phân số theo data.
* @param data
*/
public DataSet(Fraction[] data) {
this.data = data;
}
/**
* Phương thức chèn phân số fraction vào vị trí index.
* Nếu index nằm ngoài đoạn [0, length] thì không chèn được vào.
* Nếu mảng hết chỗ để thêm dữ liệu, mở rộng kích thước mảng gấp đôi.
* @param fraction là một phân số.
* @return true nếu chèn được số vào, false nếu không chèn được số vào.
*/
public boolean insert(Fraction fraction, int index) {
/* TODO */
if (checkBoundaries(0, length)) {
return false;
}
if (length >= data.length) {
enlarge();
}
for (int i = length; i > index; i--) {
data[i] = data[i - 1];
}
data[index] = fraction;
length++;
return true;
}
/**
* Phương thức tạo ra một tập dữ liệu lưu các phân số tối giản của các phân số trong tập dữ liệu gốc.
* @return tập dữ liệu mới lưu các phân số tối giản của các phân số trong tập dữ liệu gốc.
*/
public DataSet toSimplify() {
/* TODO */
DataSet result = new DataSet();
for (Fraction fraction : data) {
fraction.simplify();
result.append(fraction);
}
return result;
}
/**
* Phương thức thêm phân số fraction vào vị trí cuối cùng chưa có dứ liệu của mảng data.
* Nếu mảng hết chỗ để thêm dữ liệu, mở rộng kích thước mảng gấp đôi.
* @param fraction
* @return
*/
public void append(Fraction fraction) {
/* TODO */
if (length >= data.length) {
enlarge();
}
data[length++] = fraction;
length++;
}
/**
* Sắp xếp mảng các phân số theo thứ tự có giá trị tăng dần.
* Nếu hai phân số bằng nhau thì sắp xếp theo thứ tự có mẫu số tăng dần.
* @return mảng mới được sắp xếp theo thứ tự có giá trị tăng dần.
*/
public Fraction[] sortIncreasing() {
/* TODO */
Fraction[] sorted = data.clone();
Arrays.sort(sorted, Fraction::compareTo);
return sorted;
}
/**
* Sắp xếp mảng các phân số theo thứ tự có giá trị giảm dần.
* Nếu hai phân số bằng nhau thì sắp xếp theo thứ tự có mẫu số giảm dần.
* @return mảng mới được sắp xếp theo thứ tự có giá trị giảm dần.
*/
public Fraction[] sortDecreasing() {
/* TODO */
Fraction[] result = data.clone();
Arrays.sort(result, new Comparator<Fraction>() {
public int compare(Fraction o1, Fraction o2) {
return o2.compareTo(o1);
}
});
return result;
}
/**
* Phương thức mở rộng kích thước mảng gấp đôi, bằng cách tạo ra mảng mới có kích thước
* gấp đôi, sau đó copy dự liệu từ mảng cũ vào.
*/
private void enlarge() {
/* TODO */
Fraction[] newFrac = new Fraction[length*2];
System.arraycopy(data, 0, newFrac, 0, data.length);
data = newFrac;
}
/**
* Phương thức kiểm tra xem index có nằm trong khoảng [0, upperBound] hay không.
* @param index
* @param upperBound
* @return true nếu index nằm trong khoảng [0, upperBound], false nếu ngược lại.
*/
private boolean checkBoundaries(int index, int upperBound) {
/* TODO */
return ((index < 0) && (index > upperBound));
}
/**
* In ra tập dữ liệu theo định dạng [a1, a2, ... , an].
* @return
*/
@Override
public String toString() {
/* TODO */
StringBuilder res = new StringBuilder();
res.append("[");
for (Fraction fraction : data) {
res.append(fraction.toString() + " ");
}
res.append("]");
return res.toString();
}
/**
* In ra mảng các phân số fractions theo định dạng [a1, a2, ... , an].
* @param fractions
*/
public static void printFractions(Fraction[] fractions) {
/* TODO */
DataSet data = new DataSet(fractions);
System.out.println(data.toString());
}
}
| tasdus-117/oop | de1/fraction/DataSet.java | 1,485 | /**
* Hàm dựng khởi tạo mảng chứa các phân số theo data.
* @param data
*/ | block_comment | en | true |
247838_2 | //Q. 46:
//MostOccurance(ClassesandObjects)
/*
kamal is a data analyst in a lottery management organization
One of the tasks assigned to kamal is to find the most frequently occurring digit in a series of input number. Below are a couple of examples to illustrates how to find the most frequently occurring digit in a series of
Input numbers
Example 1
if the series of input number are[1236,262,666,121]
we notice that
0 occurs 0 time
1 occurs 3 times
2 occurs 4 times
3 occurs 1 time
4 occurs 0 time
5 occurs 0 time
6 occurs 5 times
7 occurs 0 time
8 occurs 0 time
9 occurs 0 time
-6 is the digit that occur 5 times
NOTE1:if more than one digit occur the most frequently time then the highest of the digits should be chosen as the answer see below example for clarity on this part
Example 2-
if the series of input number are[1237,202,666,140]
we notice that
0 occurs 2 times
1 occurs 2 times
2 occurs 3 times
3 occurs 1 time
4 occurs 1 time
5 occurs 0 time
6 occurs 3 times
7 occurs 1 time
8 occurs 0 time
9 occurs 0 time
we observe that
2,6 are the digits that occur 3 times
The highest of these two digits (2,6)thus the most frequently occurring digit in this series is 6.
Kamal decides to write the logic in the below method for finding the most Frequently occurring Digit in the protocol input series of numbers
Mandatory:
1. Create a Class "MostOccurance" with method name as "check"
a. Methodname - check()
b. Return Type = void
c. Access specifier = public
d. Argument = No argument
2. Create instance for the class "MostOccurance" and access "check" method. The instance name is "m"
*/
import java.io.*;
import java.util.Scanner;
class MostOccurance{
public void check()
{
int num[] = new int[4];
int store[];
int digits[] = new int[10];
Scanner sc = new Scanner(System.in);
for(int i = 0;i < 4;i++)
num[i] = sc.nextInt();
int l = 0;
for(int i = 0;i < 4;i++)
l = l + String.valueOf(num[i]).length();
store = new int[l];
int k = 0;
for(int i = 0;i < 4;i++)
{
int temp = num[i];
int rem;
while(temp > 0)
{
rem = temp%10;
temp = temp/10;
store[k] = rem;
k++;
}
}
for(int i = 0;i < 10;i++)
digits[i] = 0;
for(int i = 0;i < store.length;i++)
{
switch(store[i])
{
case 0:
digits[0]++;
break;
case 1:
digits[1]++;
break;
case 2:
digits[2]++;
break;
case 3:
digits[3]++;
break;
case 4:
digits[4]++;
break;
case 5:
digits[5]++;
break;
case 6:
digits[6]++;
break;
case 7:
digits[7]++;
break;
case 8:
digits[8]++;
break;
case 9:
digits[9]++;
break;
}
}
int max = digits[0];
int pos = 0;
for(int i = 0;i < 10;i++)
{
if(digits[i] > max)
{
max = digits[i];
pos = i;
}
}
System.out.println(pos);
}
}
public class TestClass{
public static void main(String[] args){
MostOccurance m = new MostOccurance();
m.check();
}
} | Abhijith14/JavaElab | MostOccurance.java | 1,168 | /*
kamal is a data analyst in a lottery management organization
One of the tasks assigned to kamal is to find the most frequently occurring digit in a series of input number. Below are a couple of examples to illustrates how to find the most frequently occurring digit in a series of
Input numbers
Example 1
if the series of input number are[1236,262,666,121]
we notice that
0 occurs 0 time
1 occurs 3 times
2 occurs 4 times
3 occurs 1 time
4 occurs 0 time
5 occurs 0 time
6 occurs 5 times
7 occurs 0 time
8 occurs 0 time
9 occurs 0 time
-6 is the digit that occur 5 times
NOTE1:if more than one digit occur the most frequently time then the highest of the digits should be chosen as the answer see below example for clarity on this part
Example 2-
if the series of input number are[1237,202,666,140]
we notice that
0 occurs 2 times
1 occurs 2 times
2 occurs 3 times
3 occurs 1 time
4 occurs 1 time
5 occurs 0 time
6 occurs 3 times
7 occurs 1 time
8 occurs 0 time
9 occurs 0 time
we observe that
2,6 are the digits that occur 3 times
The highest of these two digits (2,6)thus the most frequently occurring digit in this series is 6.
Kamal decides to write the logic in the below method for finding the most Frequently occurring Digit in the protocol input series of numbers
Mandatory:
1. Create a Class "MostOccurance" with method name as "check"
a. Methodname - check()
b. Return Type = void
c. Access specifier = public
d. Argument = No argument
2. Create instance for the class "MostOccurance" and access "check" method. The instance name is "m"
*/ | block_comment | en | 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 |
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 |
248449_16 | package model;
/**
*
* @author GANZA
*/
public class Stocklog2 {
private String pname;
private int pid;
private int quantity;
private String ddate;
private String edate;
private int cp;
private int sp;
private int Eid;
private String efname;
private String elname;
private String duty;
private double salary;
private String password;
private String ADID;
private String names;
private String adusername;
private String adpassword;
private String updDate;
private String workUpdates;
private String opNames;
private int telNummber;
private String email;
private String opinion;
public Stocklog2(){
}
public Stocklog2(String pname, int pid, int quantity, String ddate, String edate, int cp, int sp, String efname, String elname, String duty,String password, int salary) {
this.pname = pname;
this.pid = pid;
this.quantity = quantity;
this.ddate = ddate;
this.edate = edate;
this.cp = cp;
this.sp = sp;
this.efname = efname;
this.elname = elname;
this.duty = duty;
this.salary = salary;
this.password=password;
}
public Stocklog2(int Eid) {
this.Eid = Eid;
}
public Stocklog2(String ADID, String names, String adusername, String adpassword) {
this.ADID = ADID;
this.names = names;
this.adusername = adusername;
this.adpassword = adpassword;
}
public Stocklog2(String updDate, String workUpdates, String opNames, int telNummber, String email, String opinion) {
this.updDate = updDate;
this.workUpdates = workUpdates;
this.opNames = opNames;
this.telNummber = telNummber;
this.email = email;
this.opinion = opinion;
}
public String getUpdDate() {
return updDate;
}
public void setUpdDate(String updDate) {
this.updDate = updDate;
}
public String getWorkUpdates() {
return workUpdates;
}
public void setWorkUpdates(String workUpdates) {
this.workUpdates = workUpdates;
}
public String getOpNames() {
return opNames;
}
public void setOpNames(String opNames) {
this.opNames = opNames;
}
public int getTelNummber() {
return telNummber;
}
public void setTelNummber(int telNummber) {
this.telNummber = telNummber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getOpinion() {
return opinion;
}
public void setOpinion(String opinion) {
this.opinion = opinion;
}
public int getEid() {
return Eid;
}
public void setEid(int Eid) {
this.Eid = Eid;
}
public String getADID() {
return ADID;
}
public void setADID(String ADID) {
this.ADID = ADID;
}
public String getNames() {
return names;
}
public void setNames(String names) {
this.names = names;
}
public String getAdusername() {
return adusername;
}
public void setAdusername(String adusername) {
this.adusername = adusername;
}
public String getAdpassword() {
return adpassword;
}
public void setAdpassword(String adpassword) {
this.adpassword = adpassword;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
// public int getPid() {
// return pid;
// }
public void setPid(int pid) {
this.pid = pid;
}
// public int getQuantity() {
// return quantity;
// }
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getDdate() {
return ddate;
}
public void setDdate(String ddate) {
this.ddate = ddate;
}
public String getEdate() {
return edate;
}
public void setEdate(String edate) {
this.edate = edate;
}
public int getCp() {
return cp;
}
public void setCp(int cp) {
this.cp = cp;
}
public int getSp() {
return sp;
}
public void setSp(int sp) {
this.sp = sp;
}
public String getEfname() {
return efname;
}
public void setEfname(String efname) {
this.efname = efname;
}
public String getElname() {
return elname;
}
public void setElname(String elname) {
this.elname = elname;
}
public String getDuty() {
return duty;
}
public void setDuty(String duty) {
this.duty = duty;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getPid() {
return pid;
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public int getQuantity() {
return quantity;
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public String setAdusername() {
return this.adusername = adusername;
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
//
// public Object setSp() {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// }
//
// public Object setCp() {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// }
//
// public Object setQuantity() {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// }
//
// public Object setPid() {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// }
}
| Kami-christella/Stock-Management-System-Client-Side | src/model/Stocklog2.java | 1,603 | // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. | line_comment | en | true |
248598_8 | package db;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import discussion.Discussion;
import discussion.DiscussionGroupe;
import message.Message;
import ui.WindowError;
import user.User;
import ui.NewDiscussionUI;
import ui.UserMainUI;
public class DatabaseDiscussion {
private ArrayList<Discussion> users_discussions;
private static DatabaseDiscussion db_disc_singleton=null; // singleton pattern
private DatabaseDiscussion(){
users_discussions = new ArrayList<Discussion>();
}
//create singleton DatabaseDiscussion
public static synchronized DatabaseDiscussion getInstance()
{
if (db_disc_singleton == null)
db_disc_singleton = new DatabaseDiscussion();
return db_disc_singleton;
}
public void create_discussion(UserMainUI userMainUI,String framename,int sizex,int sizey,User current_user,DatabaseUsers users_db){
if (current_user.get_liste_contact().isEmpty()){
new WindowError("Error", "you need friends if you want to create a discussion",null);
return;
}
NewDiscussionUI disc_ui = new NewDiscussionUI(userMainUI,"New Discussion",650,350,current_user,this,users_db);
}
//return list of all username with current user inside
public ArrayList<String> find_all_disc(User current_user,DatabaseUsers users_db){
ArrayList<String> discs= new ArrayList<>();
for (Discussion discussion:users_discussions){
if (discussion.getmembers_id().contains(current_user.get_userid())){
String members="";
for (Integer id: discussion.getmembers_id()){
if (id != current_user.get_userid()){
members = members + users_db.get_user("id",String.valueOf(id)).get_username() + ",";
}
}
discs.add(members.substring(0, members.length() - 1)); // remove last ","
}
}
return discs;
}
//returns true if a discussion can be create
public boolean verify_disc_creation(String messageinitial,String list_users,User current_user,DatabaseUsers users_db){
if (list_users.equals(messageinitial)){
new WindowError("Error","Please add at least one person to the discussion",null);
return false;
}
String[] users_array = (list_users + ',' + current_user.get_username()).split(",");
ArrayList<Integer> users_id = get_members_id(users_db, users_array);
if (users_id == null){
return false;
}
// si il y a 2 ou get_userid() dans users_id c que user a essayé de se message lui meme
if (users_id.stream().filter(x->x.equals(current_user.get_userid())).count() > 1){
new WindowError("Error","you can't send message to yourself", null);
return false;
}
// try to find if a current_discussion exist
if (get_discussion(users_id)!= null){
new WindowError("Error","The discussion already exist", null);
return false;
}
Discussion current_discussion;
for (int user_id:users_id){
if (user_id == current_user.get_userid()){
continue;
}
if (!current_user.get_liste_contact().contains(user_id)){
new WindowError("Error", users_db.get_user("id", String.valueOf(user_id)).get_username()
+ " is not your friend so you can't message him",null);
return false;
}
}
if (users_id.size() > 2){
current_discussion = new DiscussionGroupe(users_id,current_user.get_userid());
}
else{
current_discussion = new Discussion(users_id,true);
}
users_discussions.add(current_discussion);
return true;
}
public String find_message(String message,DatabaseUsers users_db,String[] members_username){
ArrayList<Integer> members_id = get_members_id(users_db, members_username);
Discussion discussion = get_discussion(members_id);
if (discussion != null){
for (Message current_message:discussion.getmessages()){
if (current_message.get_contenu().equals(message)){
return current_message.see_details(users_db);
}
}
}
return "No message found !";
}
public void exclude_member(String exclude_member,ArrayList<String> members_username,DatabaseUsers users_db,User current_user){
if (exclude_member.equals(current_user.get_username())){
System.out.println("you can't exclude yourself from a conversation.");
}
int current_user_id = current_user.get_userid();
if (!members_username.contains(exclude_member)){
System.out.println(exclude_member + " is not part of the group");
return;
}
if (members_username.size() == 2){
System.out.println("you can't exclude someone from a private conversation but you can block this person");
return;
}
ArrayList<Integer> members_id = new ArrayList<Integer>();
for (String member:members_username){
User member_user = users_db.IsUserinDb(member,null);
members_id.add(member_user.get_userid());
}
Collections.sort(members_id);
Discussion discussion = get_discussion(members_id);
if (discussion instanceof DiscussionGroupe){
DiscussionGroupe discussionGroupe = (DiscussionGroupe) discussion;
if (discussionGroupe.get_admin_id() == current_user_id){
discussion.remove_member(users_db.get_user("username", exclude_member).get_userid());
System.out.println(exclude_member + " was successfully excluded");
}
else{
System.out.println("you are not the admin of the discussion and thus cannot exclude someone");
}
if (discussion.getmembers_id().size() == 2){
users_discussions.remove(discussionGroupe);
}
return;
}
System.out.println("there is no discussion available with all the members you describe");
}
public boolean date_equal(Date date1,Date date2){
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
// Attribution des dates aux instances de Calendar
cal1.setTime(date1);
cal2.setTime(date2);
// Comparaison des années, des mois et des jours
return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) &&
cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH);
}
// conversion username->id
public ArrayList<Integer> get_members_id(DatabaseUsers users_db,String[] members_username){
ArrayList<Integer> members_id = new ArrayList<Integer>();
for (String member:members_username){
User member_user = users_db.IsUserinDb(member,null);
if (member_user == null){
return null;//error throwed
}
members_id.add(member_user.get_userid());
}
Collections.sort(members_id); // sort the array so that we can compare with the db_discussions
return members_id;
}
public String find_messages_date(String dateString,DatabaseUsers users_db,String[] members_username){
ArrayList<Integer> members_id = get_members_id(users_db, members_username);
String all_messages="";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(false); // Pour rendre la validation stricte
Date date=null;
try {
date = sdf.parse(dateString);
} catch (ParseException e) {
System.out.println("Invalid date");
}
Discussion discussion = get_discussion(members_id);
for (Message current_message:discussion.getmessages()){
if (date_equal(date, current_message.get_date())){
all_messages += current_message.see_details(users_db);
all_messages += "\n";
}
}
if (all_messages == ""){
return "No message found !";
}
return all_messages;
}
// retourne la discussion qui concerne tout les users_id
// discussion == null signifie qu aucune discussion existe pour ces utilisateurs
public Discussion get_discussion(ArrayList<Integer> users_id){
for (Discussion discussion:users_discussions){
if (discussion.getmembers_id().equals(users_id)){
return discussion;
}
}
return null;
}
public Discussion get_discussion(DatabaseUsers users_db,String[] usernames){
ArrayList<Integer> users_id = get_members_id(users_db,usernames);
for (Discussion discussion:users_discussions){
if (discussion.getmembers_id().equals(users_id)){
return discussion;
}
}
return null;
}
public void resetDatabase() {
users_discussions.clear();
}
}
| floflopi/Mission2 | db/DatabaseDiscussion.java | 2,205 | // Comparaison des années, des mois et des jours | line_comment | en | true |
248989_4 | import java.util.ArrayList;
public class Laboratory {
private String name;
private ArrayList<Student> students;
private ArrayList<Professor> professors;
public Laboratory() {
}
public Laboratory(String name) {
this.name = name;
this.students = new ArrayList<Student>();
this.professors = new ArrayList<Professor>();
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public void addMember(Student s) {
this.students.add(s);
}
public void addMember(Professor p) {
this.professors.add(p);
}
public ArrayList<String> getContactInfos() {
// COMPLETE-ME
// Construa um ArrayList<String> contendo informações de contato (ContactInfo)
// de cada um dos estudantes e professores
ArrayList<String> contactInfos = new ArrayList<String>();
for( int i = 0 ; i < students.size() ; i++){
contactInfos.add(students.get(i).getContactInfo());
}
for( int i = 0 ; i < professors.size() ; i++){
contactInfos.add(professors.get(i).getContactInfo());
}
return contactInfos;
}
public boolean userExists(String userId) {
// COMPLETE-ME
// Verifique se existe o userId na lista de estudantes ou de professores
for(int i = 0; i < professors.size(); i++){
if( professors.get(i).getUserId() == userId ) //verificar utilização do cointans
return true;
}
for(int i = 0; i < students.size(); i++){
if( students.get(i).getUserId() == userId )
return true;
}
return false;
}
public int countMembers() {
// COMPLETE-ME
// Retorne o total de membros do laboratório (estudantes e professores)
return ( students.size() + professors.size() );
}
} | elc117/java04-2022b-Piekala | Laboratory.java | 491 | // Verifique se existe o userId na lista de estudantes ou de professores
| line_comment | en | true |
249187_0 | import java.security.Policy.Parameters;
/**
* Represents the all data points scrapped from Kayak.com
*
* @author issacwon
*
*/
public class Flights {
private String carrier = null;
private String departureTime = null;
private String arrivalTime = null;
private String stops = null;
private String duration = null;
private String departureAirport = null;
private String arrivalAirport = null;
private String flightDetails = null;
private int flightPrice;
private int numberLayover;
private String flightNum;
private String bookingLink;
/**
* Represents one line from the csv file (once scrapped) that is passed on to
* dataReader class
*
* @param price
* @param numLayover
* @param flightDet
* @param flyNum
* @param link
*/
public Flights(int price, int numLayover, String flightDet, String flyNum, String link) {
this.flightPrice = price;
this.numberLayover = numLayover;
this.flightDetails = flightDet;
this.bookingLink = link;
this.flightNum = flyNum;
}
public Flights() {
}
public int getFlightPrice() {
return flightPrice;
}
public void setFlightPrice(int flightPrice) {
this.flightPrice = flightPrice;
}
public int getNumberLayover() {
return numberLayover;
}
public void setNumberLayover(int numberLayover) {
this.numberLayover = numberLayover;
}
public String getFlightNum() {
return flightNum;
}
public void setFlightNum(String flightNum) {
this.flightNum = flightNum;
}
public String getBookingLink() {
return bookingLink;
}
public void setBookingLink(String bookingLink) {
this.bookingLink = bookingLink;
}
public String getCarrier() {
return carrier;
}
public void setCarrier(String carrier) {
this.carrier = carrier;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getStops() {
return stops;
}
public void setStops(String stops) {
this.stops = stops;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getDepartureAirport() {
return departureAirport;
}
public void setDepartureAirport(String departureAirport) {
this.departureAirport = departureAirport;
}
public String getArrivalAirport() {
return arrivalAirport;
}
public void setArrivalAirport(String arrivalAirport) {
this.arrivalAirport = arrivalAirport;
}
public String getFlightDetails() {
return flightDetails;
}
public void setFlightDetails(String flightDetails) {
this.flightDetails = flightDetails;
}
/**
* Getter for Flights with "|" delimited format
*
* @return
*/
public String getFlights() {
String flightInfo = null;
flightInfo = carrier + ("|") + flightDetails + ("|") + departureTime + ("|") + arrivalTime + ("|") + stops
+ ("|") + duration + ("|") + departureAirport + ("|") + arrivalAirport;
return flightInfo;
}
}
| UPenn-CIT599/final-project-team8_flights | src/Flights.java | 958 | /**
* Represents the all data points scrapped from Kayak.com
*
* @author issacwon
*
*/ | block_comment | en | true |
249404_0 | package Zodiac;
// Create an Enum called "ZodiacSigns" which will contain all the signs by their name and in additions the following information.
// Make sure to declare relevant fields & methods, Use Enum for Element as well.
// Declare a program that will print the info of the sign represented by todays run date
// (the relevant sign will be chosen according to the sysdate)
/**
* Created by yuriyf on 11/1/2016
*/
public class Zodiac {
public enum ZodiacSigns {
ARIES("Ram", 21, 3, 20, 4, ZodiacElements.Elements.FIRE.getNameOfElement(), "Mars"),
TAURUS("Bull", 21, 4, 20, 5, ZodiacElements.Elements.EARTH.getNameOfElement(), "Earth"),
GEMINI("Twins", 21, 5, 20, 6, ZodiacElements.Elements.AIR.getNameOfElement(), "Mercury"),
CANCER("Crab", 21, 6, 20, 7, ZodiacElements.Elements.WATER.getNameOfElement(), "Moon"),
LEO("Lion", 21, 7, 20, 8, ZodiacElements.Elements.FIRE.getNameOfElement(), "Sun"),
VIRGO("Maiden", 21, 8, 20, 9, ZodiacElements.Elements.EARTH.getNameOfElement(), "Mercury"),
LIBRA("Scales", 21, 9, 20, 10, ZodiacElements.Elements.AIR.getNameOfElement(), "Venus"),
SCOPRIO("Scorpion", 21, 10, 20, 11, ZodiacElements.Elements.WATER.getNameOfElement(), "Pluto"),
SAGITTARIUS("Archer", 21, 11, 20, 12, ZodiacElements.Elements.FIRE.getNameOfElement(), "Jupiter"),
CAPRICORN("Goat Horn", 21, 12, 20, 1, ZodiacElements.Elements.EARTH.getNameOfElement(), "Saturn"),
AQUARIUS("Water Carrier", 21, 1, 20, 2, ZodiacElements.Elements.AIR.getNameOfElement(), "Uranus"),
PISCES("Fish", 21, 2, 20, 3, ZodiacElements.Elements.WATER.getNameOfElement(), "Neptune");
private final String translation;
private final int dayStart;
private final int monthStart;
private final int dayEnd;
private final int monthEnd;
private String element;
private final String planet;
ZodiacSigns(String translation, int dayStart, int monthStart, int dayEnd, int monthEnd, String element ,String planet) {
this.translation = translation;
this.dayStart = dayStart;
this.monthStart = monthStart;
this.dayEnd = dayEnd;
this.monthEnd = monthEnd;
this.element = element;
this.planet = planet;
}
public String getTranslation() {
return translation;
}
public int getDayStart() {
return dayStart;
}
public int getMonthStart() {
return monthStart;
}
public int getDayEnd() {
return dayEnd;
}
public int getMonthEnd() {
return monthEnd;
}
public String getPlanet() {
return planet;
}
@Override
public String toString() {
return "ZodiacSigns{" +
"translation='" + translation + '\'' +
", dayStart=" + dayStart +
", monthStart=" + monthStart +
", dayEnd=" + dayEnd +
", monthEnd=" + monthEnd +
", elements=" + element +
", planet='" + planet + '\'' +
'}';
}
}
} | YuriyFedorov/Java_automation_local_YF | Zodiac.java | 923 | // Create an Enum called "ZodiacSigns" which will contain all the signs by their name and in additions the following information.
| line_comment | en | 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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |