file_id
int64
1
250k
content
stringlengths
0
562k
repo
stringlengths
6
115
path
stringlengths
1
147
248,229
public class Candidate { private String name; private int votes; public Candidate(String name) { this.name = name; } public String getName() { return name; } public int getVotes() { return votes; } public void setVotes(int votes) { this.votes = votes; } }
minhhn2016/ObjectsElection
src/Candidate.java
248,230
import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class RaftNode implements RaftI{ private int nodeId; private int currentTerm; private int votedFor; private boolean isLeader; private int[] votes; private int leaderId; private static CountDownLatch allNodesReady; private boolean electionInProgress = false; // Static fields for RaftCluster functionality private static final int TOTAL_NODES = 4; private static RaftNode[] nodes = new RaftNode[TOTAL_NODES]; private List<RaftNode> participatingNodes = new ArrayList<>(); // Add host and port information private String host; private int port; private Timer heartbeatTimer; private long lastHeartbeatTimestamp; private static final int HEARTBEAT_INTERVAL = 1000; // 1000 milliseconds (1 second) public RaftNode(int nodeId) { this.nodeId = nodeId; this.currentTerm = 0; this.votedFor = -1; // -1 indicates no vote //this.isLeader = false; //this.leaderId = -1; this.isLeader = false; RaftNode.allNodesReady = allNodesReady; // Add the newly created node to the nodes array //nodes[nodeId - 1] = this; // Initialize host and port based on NodeI interface values this.host = NodeI.ipAddr[nodeId]; this.port = NodeI.ports[nodeId]; this.heartbeatTimer = new Timer(); votes = new int[TOTAL_NODES]; Arrays.fill(votes, -1); // Initialize to -1 indicating no vote } public static int getHeartbeatInterval() { return HEARTBEAT_INTERVAL; } // Getter for participating nodes public List<RaftNode> getParticipatingNodes() { return participatingNodes; } public boolean isLeader() { System.out.println("Node Id : " + nodeId + " Leader Id : " + leaderId); //return nodeId == leaderId; return isLeader; } public void setLeader(int leaderId) { this.leaderId = leaderId; } public void setLeader(boolean leader) { isLeader = leader; } // Create and add participating nodes // RaftNode node1 = new RaftNode(0); public long getLastHeartbeatTimestamp() { return lastHeartbeatTimestamp; } public void setLastHeartbeatTimestamp(long timestamp) { lastHeartbeatTimestamp = timestamp; } //RaftNode node2 = new RaftNode(1); //participatingNodes.add(node2); //RaftNode node3 = new RaftNode(2); //participatingNodes.add(node3); //RaftNode node4 = new RaftNode(3); //participatingNodes.add(node4); // Set the initial leader and leader ID for node1 //node1.setLeader(true); //node1.setLeaderId(1); public void start() { /*try { NodeI nodeStub = (NodeI) UnicastRemoteObject.exportObject(this, 0); Registry registry = LocateRegistry.createRegistry(port); registry.rebind(NodeI.services[nodeId], nodeStub); } catch (RemoteException e) { e.printStackTrace(); }*/ // DAH SHAGALLL ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // Start a periodic task to simulate Raft election and heartbeat // scheduler.scheduleAtFixedRate(this::runRaftAlgorithm, 0, 500, TimeUnit.MILLISECONDS); //ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // Start a periodic task to simulate Raft election and heartbeat scheduler.scheduleAtFixedRate(() -> { //TODO isleader() if (!isLeader()) { // Check election timeout if (new Random().nextInt(10) == 0) { // Simulate a timeout with a 1 in 10 chance try { startElection(); } catch (NotBoundException e) { throw new RuntimeException(e); } catch (RemoteException e) { throw new RuntimeException(e); } } } else { // If the node is already a leader, stop scheduling the task scheduler.shutdown(); } }, 0, 500, TimeUnit.MILLISECONDS); // Wait for all nodes to be ready /*try { allNodesReady.await(); } catch (InterruptedException e) { e.printStackTrace(); }*/ } // Placeholder for the logic to send RequestVote RPCs to other nodes private void sendRequestVote(int targetNodeId) { try { System.out.println("Target node: " + targetNodeId); // Assuming you have an RMI registry running on a specific port Registry registry = LocateRegistry.getRegistry(ports[targetNodeId]); // Lookup the remote object (assumes NodeI is the remote interface) NodeI remoteNode = (NodeI) registry.lookup(services[targetNodeId]); // Call the requestVote method on the remote node /* remoteNode.requestVote(this.nodeId, this.currentTerm); } catch (RemoteException | NotBoundException e) { e.printStackTrace(); // Handle exceptions as needed (e.g., node not reachable) }*/ // Call the requestVote method on the remote node boolean voteGranted = remoteNode.requestVote(this.currentTerm, this.nodeId); // Update the votes array if (voteGranted) { votes[targetNodeId] = this.nodeId; } } catch (RemoteException | NotBoundException e) { e.printStackTrace(); // Handle exceptions as needed (e.g., node not reachable) } } private void runRaftAlgorithm() throws NotBoundException, RemoteException { if (isLeader()) { // Handle leader responsibilities (e.g., send heartbeats) System.out.println("Node " + nodeId + " is the leader."); } else { // Check election timeout if (new Random().nextInt(10) == 0) { // Simulate a timeout with a 1 in 10 chance startElection(); } } } private void startElection() throws NotBoundException, RemoteException { electionInProgress = true; System.out.println("Leader id before election " + leaderId); if (!isLeader) { System.out.println("Node " + nodeId + " is starting an election."); // Increment current term currentTerm++; System.out.println("Current term " + currentTerm); // Set leaderId to node // leaderId = nodeId; System.out.println("leader id : " + leaderId + " isleader " + isLeader); // Vote for itself votedFor = nodeId; System.out.println("Voted for " + votedFor); // Send RequestVote RPCs to other nodes /*for (RaftNode targetNode : participatingNodes) { if (targetNode != this) { System.out.println("Request vote from " + targetNode.nodeId); sendRequestVote(targetNode); } }*/ /* for (RaftNode targetNode : nodes) { //targetNode.nodeId = nodeId; System.out.println("Node " + targetNode); if (targetNode != this) { System.out.println("Request vote ---- "); // Skip sending a RequestVote to itself sendRequestVote(targetNode); } }*/ for (int i = 0; i < 4; i++) { if (i != nodeId) { System.out.println("Request vote from Node " + i); sendRequestVote(i); } } // Wait for votes /* try { Thread.sleep(1000); // Simulate the time it takes to gather votes } catch (InterruptedException e) { e.printStackTrace(); }*/ // Check if received enough votes to become the leader if (receivedEnoughVotes()) { System.out.println("RECEIEVED ENOUGH VOTES Become Leader " + isLeader); becomeLeader(); //broadcastLeader(); System.out.println("Updated is leader" + isLeader); //updateLeaderStatus(leaderId); electionInProgress = false; } else { // Reset votedFor and continue the normal operation votedFor = -1; } } } /*public void broadcastLeader() { // Implement logic to broadcast the leader's ID to all nodes // You can use RMI or any other communication mechanism here // For simplicity, let's assume there's a method broadcastLeaderId in RaftCluster RaftCluster.broadcastLeaderId(leaderId); }*/ /*public void broadcastLeader(int leaderId) { System.out.println("Leader Id before broadcast " + leaderId); for (RaftNode node : nodes) { System.out.println("Node broadcast: " + node); node.setLeader(leaderId); System.out.println("----------"); } }*/ public void startHeartbeatThread() { if (isLeader) { // Schedule a task to send heartbeats periodically heartbeatTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { sendHeartbeat(currentTerm,leaderId); // Replace with your actual logic } catch (RemoteException e) { e.printStackTrace(); // Handle exceptions } } }, 0, HEARTBEAT_INTERVAL); } } public void stopHeartbeatThread() { heartbeatTimer.cancel(); } @Override public void informNewLeader(int leaderId) throws RemoteException { if (this.nodeId == leaderId) { System.out.println("Node " + this.nodeId + " becomes the leader."); this.isLeader = true; // Add any additional logic you need when becoming the leader // Example: Start a background thread to periodically send heartbeats startHeartbeatThread(); } else { System.out.println("Node " + this.nodeId + " received information about the new leader: " + leaderId); this.isLeader = false; // Add any additional logic you need when not being the leader // Example: Stop the background thread sending heartbeats stopHeartbeatThread(); } // ... handle the information as needed ... } public void multicastLeader(int leaderId) throws RemoteException, NotBoundException { // Implementation for TO-Multicasting boolean delay = true; for (int i = 0; i < TOTAL_NODES; i++) { Registry registry = LocateRegistry.getRegistry(ports[i]); RaftI node = (RaftI) registry.lookup(services[i]); node.informNewLeader(leaderId); } System.out.println("End Multicast Leader:"); //this.displayRequests(); //this.displayAcks(); } /*public void updateLeaderStatus(int newLeaderId) { for (RaftNode node : nodes) { node.setLeader(newLeaderId); } }*/ private void becomeLeader() throws NotBoundException, RemoteException { System.out.println("Before becoming leader - isLeader: " + isLeader); //isLeader = true; setLeader(true); leaderId = nodeId; System.out.println("Node " + nodeId + " became the leader for term " + currentTerm + " isleader : " +isLeader); //broadcastLeader(leaderId); // Broadcast the leader's ID to all nodes multicastLeader(leaderId); System.out.println("After broadcasting " + isLeader); // Add the following line to update the isLeader status across nodes //RaftCluster.updateLeaderStatus(nodeId); //updateLeaderStatus(nodeId); //System.out.println("After becoming leader - isLeader: " + isLeader); } private boolean receivedEnoughVotes() { /*int votesReceived = 1; // Start with 1 vote for itself for (RaftNode node : participatingNodes) { if (node.votedFor == nodeId) { votesReceived++; } } int votesNeeded = participatingNodes.size() / 2 + 1; return votesReceived >= votesNeeded; */ /* // Simulate a simple check for receiving votes from a majority int votesNeeded = RaftCluster.getTotalNodes() / 2 + 1; // Simulate receiving votes from a majority by randomly deciding return new Random().nextInt(RaftCluster.getTotalNodes()) < votesNeeded; */ int votesReceived = 1; // Count the self-vote for (int i = 0; i < RaftNode.TOTAL_NODES; i++) { if (votes[i] == this.nodeId) { votesReceived++; } } return votesReceived > RaftNode.TOTAL_NODES / 2; } @Override public boolean requestVote(int term, int candidateId) throws RemoteException { if (term > currentTerm) { currentTerm = term; // Additional logic if needed return true; // Vote for the candidate } else { // Additional logic if needed return false; // Do not vote for the candidate } } @Override public void receiveVote(int term, int voterId, boolean voteGranted) throws RemoteException { } @Override public void sendHeartbeat(int term, int leaderId) throws RemoteException { // Iterate through all nodes in the cluster and send heartbeats for (int i = 0; i < TOTAL_NODES; i++) { if (i != this.nodeId) { try { Registry registry = LocateRegistry.getRegistry(ports[i]); RaftI remoteNode = (RaftI) registry.lookup(services[i]); remoteNode.receiveHeartbeat(term, leaderId); } catch (Exception e) { e.printStackTrace(); // Handle exceptions } } } } @Override public void receiveHeartbeat(int term, int leaderId) throws RemoteException { System.out.println("Received heartbeat from Node " + leaderId + " for term " + term); // Check if the received term is greater than the current term if (term > currentTerm) { System.out.println("Updating term to " + term); currentTerm = term; // Reset votedFor since we're in a new term votedFor = -1; // Transition to Follower state because a leader in a new term has been detected //becomeFollower(); } // Update the timestamp to indicate that the leader is still alive lastHeartbeatTimestamp = System.currentTimeMillis(); } @Override public void replicateLogEntry(int term, int leaderId, LogEntry logEntry) throws RemoteException { } @Override public void applyLogEntry(LogEntry logEntry) throws RemoteException { } } /* public static void main(String[] args) { // Create and start three nodes RaftCluster.createNode(1).start(); RaftCluster.createNode(2).start(); RaftCluster.createNode(3).start(); }*/ /* import java.rmi.RemoteException; import java.util.Random; import java.util.Timer; import java.util.TimerTask; public class RaftNode extends Thread { private int nodeId; private int currentTerm; private int votedFor; private int votesReceived; private volatile boolean isLeader; private Timer electionTimer; private Timer heartbeatTimer; public RaftNode(int nodeId) { this.nodeId = nodeId; this.currentTerm = 0; this.votedFor = -1; this.votesReceived = 0; this.isLeader = false; this.electionTimer = new Timer(); } public void startElection() { if (!isLeader) { // Start a new election currentTerm++; votedFor = nodeId; votesReceived = 1; // Vote for itself // Send RequestVote RPCs to other nodes for (int i = 0; i < NodeI.ipAddr.length; i++) { if (i != nodeId) { try { System.out.println("Trying to connect to: " + NodeI.ipAddr[i] + ":" + NodeI.ports[i] + " " + NodeI.services[i]); Registry registry = LocateRegistry.createRegistry(NodeI.ports[i]); //NodeI node = new NodeImplement(); // Replace with your actual implementation //Naming.rebind("rmi://" + NodeI.ipAddr[i] + ":" + NodeI.ports[i] + "/" + NodeI.services[i], node); NodeI node = (NodeI) registry.lookup(NodeI.services[i]); node.requestVote(nodeId, currentTerm); } catch (RemoteException e) { e.printStackTrace(); } catch (NotBoundException e) { throw new RuntimeException(e); } } } // Set a timeout for receiving votes electionTimer.schedule(new TimerTask() { @Override public void run() { if (votesReceived <= NodeI.ipAddr.length / 2) { // Election timeout, not enough votes received, restart election startElection(); } else { // Become the leader becomeLeader(); } } }, new Random().nextInt(150) + 150); // Randomize timeout to prevent split votes } } public void requestVote(int candidateId, int term) throws RemoteException { if (term > currentTerm) { // Candidate has a higher term, reset and vote for the candidate currentTerm = term; votedFor = candidateId; votesReceived = 1; } else if (term == currentTerm && (votedFor == -1 || votedFor == candidateId)) { // Candidate has the same term, vote for the candidate votedFor = candidateId; votesReceived++; } } public void becomeLeader() { isLeader = true; System.out.println("Node " + nodeId + " elected as the leader for term " + currentTerm); // Start heartbeat mechanism startHeartbeat(); } private void startHeartbeat() { electionTimer.cancel(); // Cancel election timeout // Implement the logic for sending heartbeat messages to maintain leadership // This could involve periodically sending AppendEntries RPCs to other nodes // Initialize the heartbeat timer heartbeatTimer = new Timer(); // Schedule a task to send periodic heartbeat messages heartbeatTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { sendHeartbeat(); } catch (RemoteException | NotBoundException e) { e.printStackTrace(); } } }, 0, 500); } private void sendHeartbeat() throws RemoteException, NotBoundException { // Iterate over all nodes (excluding the current node) for (int i = 0; i < NodeI.ipAddr.length; i++) { if (i != nodeId) { try { // Lookup the remote node Registry registry = LocateRegistry.getRegistry(NodeI.ports[i]); NodeI node = (NodeI) registry.lookup(NodeI.services[i]); // Send an AppendEntries RPC (heartbeat) to the remote node // You may need to define an AppendEntries method in your NodeI interface // and implement it in your remote node class //node.appendEntries(nodeId, currentTerm); } catch (RemoteException | NotBoundException e) { e.printStackTrace(); } } } } public boolean isLeader() { return isLeader; } @Override public void run() { // Raft node's main logic goes here // Start the election when the node starts startElection(); } } */
YasoKarim/Totally-Ordered-RMI
src/RaftNode.java
248,231
package models; import org.joda.time.DateTime; import java.sql.Timestamp; import java.util.*; import javax.persistence.*; import play.db.ebean.*; import play.data.format.*; import play.data.validation.*; import com.avaje.ebean.*; import com.avaje.ebean.annotation.CreatedTimestamp; /** * Game entity managed by Ebean */ @Entity public class Game extends Model { private static final long serialVersionUID = 1L; @Id public Long id; @Constraints.Required @Column(unique=true) public String title; @Constraints.Required public Boolean owned = false; @OneToMany(cascade=CascadeType.ALL) public List<Vote> votes; @ManyToOne public User createdBy; @CreatedTimestamp public Timestamp created; /** * Generic query helper for entity Game with id Long */ public static Finder<Long,Game> find = new Finder<Long,Game>(Long.class, Game.class); /** * Return a list of games * * @param owned Filter applied on the owned field */ public static List<Game> list(Boolean owned) { List<Game> games = find.fetch("votes") .where() .eq("owned", owned) .orderBy("title asc") .findList(); if (!owned) { Collections.sort(games, Collections.reverseOrder(new Game.VoteCountComparator())); } return games; } /** * Find games created by user in last twenty-four hours * * @param email E-mail address of user */ public static List<Game> findCreatedTodayByEmail(String email) { DateTime midnight = new DateTime().toDateMidnight().toDateTime(); return find.where() .eq("createdBy.email", email) .between("created", midnight, midnight.plusDays(1)) .findList(); } /** * Comparator used for sorting games by number of votes */ static class VoteCountComparator implements Comparator<Game> { /** * Compare two games by their vote count * @param g1 Game to compare * @param g2 Game to compare against */ public int compare(Game g1, Game g2) { int numVotes1 = g1.votes.size(), numVotes2 = g2.votes.size(); return (numVotes1 == numVotes2) ? 0 : (numVotes1 > numVotes2) ? 1 : -1; } } /** * Uniqueness validation */ public String validate() { List<Game> duplicateGames = Game.find.where() .eq("title", title) .findList(); if (duplicateGames.size() > 0) { return "A game with that title already exists"; } return null; } }
zacharycarter/gametracker-forms
app/models/Game.java
248,232
// import java.util.GregorianCalendar; import java.util.ArrayList; import java.util.TreeMap; /********************************************************************* * Class to handle a single instance of an iVotronic terminal. * * @author Duncan A. Buell * Copyright (c) 2010-2012 Duncan A. Buell * * 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. **/ public class OneTerminal { /********************************************************************* * Instance variables for the class. **/ // private static final String TAG = "OneTerminal: "; // for testing private boolean foundIn152; private boolean foundIn155; // The default setting is that a terminal is both 'absentee=true' // 'notAbsentee=true'. If we find a terminal in the 155 file, we // change these settings to 'false' and then reset the settings // when we know the precincts for which we are counting votes. // If we only find the terminal in the 152 file, then the settings // will be both 'true'. private boolean absentee; private boolean notAbsentee; private int lateVotesCast152; private int votesCast152; private int votesCast155; private String closePEB; private String ivoNumber; private String openPEB; // private GregorianCalendar openDateTime; // private GregorianCalendar closeDateTime; // let's not get fancy yet private String openDateTime; private String closeDateTime; private ArrayList<String> memoryCollectionTime; // note nonstandard time format private ArrayList<String> events; private TreeMap<String, String> ballotStyles; private TreeMap<String, String> pcts; private TreeMap<String, Integer> eventCounts; // code and count of code /********************************************************************* * Constructor. **/ public OneTerminal() { this.absentee = true; this.notAbsentee = true; this.foundIn152 = false; this.foundIn155 = false; this.lateVotesCast152 = 0; this.votesCast152 = Globals.DUMMYINT; this.votesCast155 = Globals.DUMMYINT; this.closePEB = Globals.DUMMYCLOSEPEB; this.ivoNumber = Globals.DUMMYIVONUMBER; this.openPEB = Globals.DUMMYOPENPEB; // openDateTime = new GregorianCalendar(); // openDateTime.set(1970, 0, 0, 0, 0, 0); // closeDateTime = new GregorianCalendar(); // closeDateTime.set(1970, 0, 0, 0, 0, 0); this.openDateTime = "1970_01_01 00:00:00"; this.closeDateTime = "1970_01_01 00:00:00"; this.memoryCollectionTime = new ArrayList<String>(); this.events = new ArrayList<String>(); this.ballotStyles = new TreeMap<String, String>(); this.pcts = new TreeMap<String, String>(); this.eventCounts = new TreeMap<String, Integer>(); } // public OneTerminal() /********************************************************************* * Constructor. **/ public OneTerminal(String number) { this.absentee = true; this.notAbsentee = true; this.foundIn152 = false; this.foundIn155 = false; this.lateVotesCast152 = 0; this.votesCast152 = Globals.DUMMYINT; this.votesCast155 = Globals.DUMMYINT; this.closePEB = Globals.DUMMYCLOSEPEB; this.ivoNumber = Globals.DUMMYIVONUMBER; this.openPEB = Globals.DUMMYOPENPEB; // openDateTime = new GregorianCalendar(); // openDateTime.set(1970, 0, 0, 0, 0, 0); // closeDateTime = new GregorianCalendar(); // closeDateTime.set(1970, 0, 0, 0, 0, 0); openDateTime = "1970_01_01 00:00:00"; closeDateTime = "1970_01_01 00:00:00"; this.memoryCollectionTime = new ArrayList<String>(); this.events = new ArrayList<String>(); this.ballotStyles = new TreeMap<String, String>(); this.pcts = new TreeMap<String, String>(); this.eventCounts = new TreeMap<String, Integer>(); this.ivoNumber = number; } // public OneTerminal() /********************************************************************* * Accessors and mutators. **/ /********************************************************************* * Accessor for <code>absentee</code>. * * @return the value of <code>absentee</code> **/ public boolean isAbsentee() { return this.absentee; } // public boolean isAbsentee() /********************************************************************* * Mutator for <code>absentee</code>. * * @param the value to set **/ public void setAbsentee(boolean what) { this.absentee = what; } // public void setAbsentee(boolean what) /********************************************************************* * Accessor for <code>ballotStyles</code> list. * * @return the value of <code>ballotStyles</code> **/ public TreeMap<String, String> getBallotStyles() { return this.ballotStyles; } // public Treemap<String, String> getBallotStyles() /********************************************************************* * Mutator to add a <code>ballotStyles</code>. * * @param key the ivoNumber for the value to add. * @param style the value to add. **/ public void addBallotStyles(String ivoNumber, String style) { if(null == this.ballotStyles.get(ivoNumber+style)) { this.ballotStyles.put(ivoNumber+style, style); } } // public void addBallotStyles(String ivoNumber, String style) /********************************************************************* * Mutator for <code>ballotStyles</code>. * * @param the value of <code>ballotStyles</code> **/ public void setBallotStyles(TreeMap<String, String> what) { this.ballotStyles = what; } // public void setBallotStyles(TreeMap<String, String> what) /********************************************************************* * Accessor for <code>closePEB</code>. * * @return the value of <code>closePEB</code> **/ public String getClosePEB() { return this.closePEB; } // public String getClosePEB() /********************************************************************* * Mutator for <code>closePEB</code>. * * @param the value of <code>closePEB</code> **/ public void setClosePEB(String what) { this.closePEB = what; } // public void setClosePEB(String what) /********************************************************************* * Accessor for <code>closeDateTime</code>. * * @return the value of <code>closeDateTime</code> **/ public String getCloseDateTime() { return this.closeDateTime; } // public String getCloseDateTime() /********************************************************************* * Accessor for an event. * * @param which the subscript of the event to return **/ public String getEvent(int which) { return this.events.get(which); } // public String getEvent(int which) /********************************************************************* * Accessor for event log size. * * @return the size of the event log **/ public int getEventLogSize() { return this.events.size(); } // public void getLogSize() /********************************************************************* * Accessor for an event count. * * @param which the code of the event count to return **/ public int getEventCount(String whichCode) { int returnValue = 0; if(null == this.eventCounts.get(whichCode)) returnValue = 0; else returnValue = this.eventCounts.get(whichCode); return returnValue; } // public int getEventCount(String whichCode) /********************************************************************* * Accessor for <code>foundIn152</code>. * * @return the value of <code>foundIn152</code> **/ public boolean getFoundIn152() { return this.foundIn152; } // public boolean getFoundIn152() /********************************************************************* * Mutator for <code>foundIn152</code>. * * @param the value to be set **/ public void setFoundIn152(boolean what) { this.foundIn152 = what; } // public void setFoundIn152() /********************************************************************* * Accessor for <code>foundIn155</code>. * * @return the value of <code>foundIn155</code> **/ public boolean getFoundIn155() { return this.foundIn155; } // public boolean getFoundIn155() /********************************************************************* * Mutator for <code>foundIn155</code>. * * @param the value to be set **/ public void setFoundIn155(boolean what) { this.foundIn155 = what; } // public void setFoundIn155() /********************************************************************* * Accessor for <code>ivoNumber</code>. * * @return the value of <code>ivoNumber</code> **/ public String getIvoNumber() { return this.ivoNumber; } // public String getIvoNumber() /********************************************************************* * Mutator for <code>ivoNumber</code>. * * @param the value of <code>ivoNumber</code> **/ public void setIvoNumber(String what) { this.ivoNumber = what; } // public void setIvoNumber(String what) /********************************************************************* * Accessor for first <code>memoryCollectionTime</code>. * * @return the first memory card data collection time, or 'never' **/ public String getMemoryCollectionFirstTime() { String returnValue = "never"; if(this.memoryCollectionTime.size() > 0) returnValue = this.memoryCollectionTime.get(0); return returnValue; } // public String getMemoryCollectionFirstTime() /********************************************************************* * Accessor for <code>memoryCollectionTime</code>. * * @return the memory card data collection time **/ public ArrayList<String> getMemoryCollectionTime() { return this.memoryCollectionTime; } // public ArrayList<String> getMemoryCollectionTime() /********************************************************************* * Mutator for <code>memoryCollectionTime</code>. * * Note that if there is already data then we do nothing because we * are only interested in the earliest collection time. * * Note also that the time is nonstandard because the system log does * not have a year in its timestamp information and it doesn't run * on a 24-hour clock. The input string has * the date as mm-dd * the time as hh:mm * either 'am' or 'pm' * * @param dateAndTime **/ public void setMemoryCollectionTime(String dateAndTime) { this.memoryCollectionTime.add(dateAndTime); } // public void setMemoryCollectionTime(String dateAndTime) /********************************************************************* * Accessor for <code>lateVotesCast</code> * * @return the number of late votes **/ public int getLateVotesCast152() { return this.lateVotesCast152; } // public int getLateVotesCast152() /********************************************************************* * Accessor for <code>notAbsentee</code>. * * @return the value of <code>notAbsentee</code> **/ public boolean isNotAbsentee() { return this.notAbsentee; } // public boolean isNotAbsentee() /********************************************************************* * Mutator for <code>notAbsentee</code>. * * @param the value to set **/ public void setNotAbsentee(boolean what) { this.notAbsentee = what; } // public void setNotAbsentee(boolean what) /********************************************************************* * Accessor for <code>openPEB</code>. * * @return the value of <code>openPEB</code> **/ public String getOpenPEB() { return this.openPEB; } // public String getOpenPEB() /********************************************************************* * Mutator for <code>openPEB</code>. * * @param the value of <code>openPEB</code> **/ public void setOpenPEB(String what) { this.openPEB = what; } // public void setOpenPEB(String what) /********************************************************************* * Accessor for <code>openDateTime</code>. * * @return the value of <code>openDateTime</code> **/ public String getOpenDateTime() { return this.openDateTime; } // public String getOpenDateTime() /********************************************************************* * Accessor for <code>pcts</code> list. * * @return the value of <code>pcts</code> **/ public TreeMap<String, String> getPcts() { return this.pcts; } // public TreeMap<String, String> getPcts() /********************************************************************* * Mutator to add a pct. * In this method and the other add methods, we only add if it's a * new instance of the data. * * @param ivoNumber the ivoNumber for the value to add. * @param pct the value to add. **/ public void addPcts(String ivoNumber, String pct) { if(null == this.pcts.get(ivoNumber+pct)) { this.pcts.put(ivoNumber+pct, pct); } } // public void addPcts(String ivoNumber, String pct) /********************************************************************* * Mutator for <code>pcts</code>. * * @param the value of <code>pcts</code> **/ public void setPcts(TreeMap<String, String> what) { this.pcts = what; } // public void setPcts(TreeMap<String, String> what) /********************************************************************* * Accessor for <code>votesCast152</code>. * * @return the value of <code>votesCast152</code> **/ public int getVotesCast152() { return this.votesCast152; } // public int getVotesCast152() /********************************************************************* * Accessor for <code>votesCast155</code>. * * @return the value of <code>votesCast155</code> **/ public int getVotesCast155() { return this.votesCast155; } // public int getVotesCast155() /********************************************************************* * Mutator for <code>votesCast155</code>. * We need this because we don't store votes local to the terminal. * * @param howMany the number of votes cast on this terminal. **/ public void setVotesCast155(int howMany) { this.votesCast155 = howMany; } // public void setVotesCast155(int howMany) /********************************************************************* * General methods. **/ /********************************************************************* * Method to add a 152 event to the event log for this terminal. * * @param theEvent the event to add **/ public void addToEventLog(String eventString) { this.events.add(eventString); Globals.incrementTreeMap(OneEvent.getCode(eventString), eventCounts, 1); } // /********************************************************************* * Method to dump the event log counts for this terminal. * * @return the formatted <code>String</code> value. **/ public String dumpEventCounts() { String s = ""; for(String key: this.eventCounts.keySet()) { s += String.format("'%s' '%s' '%s' '%s'%n", this.ivoNumber, this.eventCounts.get(key), key, Globals.eventTexts.get(key)); } return s; } // public String dumpEventCounts() /********************************************************************* * Method to dump the event log for this terminal. * * @return the formatted <code>String</code> value. **/ public String dumpEvents() { String s = ""; for(String eventString: this.events) { s += String.format("'%s'%n", eventString); } return s; } // public String dumpEvents() /********************************************************************* * Accessor for an sequence of event counts. * * @param c1 the first code of the sequence * @param c2 the second code of the sequence * @param c3 the third code of the sequence * @param c4 the fourth code of the sequence **/ public int getEventCountForSequence(String c1, String c2, String c3, String c4) { int returnValue = 0; returnValue = 0; for(int i = 0; i < this.events.size()-3; ++i) { if((OneEvent.getCode(this.events.get(i )).equals(c1)) && (OneEvent.getCode(this.events.get(i+1)).equals(c2)) && (OneEvent.getCode(this.events.get(i+2)).equals(c3)) && (OneEvent.getCode(this.events.get(i+3)).equals(c4))) { ++returnValue; } } return returnValue; } // public int getEventCountForSequence(String c1, String c2, String c3, String c4) /********************************************************************* * Method to process the 152 events. * * This method runs through the event list. * We count the number of 'vote cast' events. * We count the number of late votes cast. * We get the open and close time and PEB. **/ public void process152events() { String code; // FileUtils.logFile.printf("%s enter process152events%n", TAG); // let's record the fact that we had a 152 file for the votes cast // if in fact we have events for this terminal if(this.events.size() > 0) this.votesCast152 = 0; for(String eventString: this.events) { // FileUtils.logFile.printf("%s event %s%n", TAG, event); // FileUtils.logFile.flush(); code = OneEvent.getCode(eventString); if((code.equals("0001510")) || //vote cast by voter (code.equals("0001511")) || //vote cast by poll worker (code.equals("0001512"))) //BLANK vote cast by poll worker { ++this.votesCast152; if(OneEvent.getTime(eventString).compareTo("19:00:00") > 0) { ++this.lateVotesCast152; } // if(OneEvent.getTime(eventString).compareTo("19:00:00") > 0) } // if((code.equals("0001510")) || //vote cast by voter if(code.equals("0001672")) { this.openDateTime = OneEvent.getDateAndTime(eventString); this.openPEB = OneEvent.getPebNumber(eventString); } if(code.equals("0001673")) { this.closeDateTime = OneEvent.getDateAndTime(eventString); this.closePEB = OneEvent.getPebNumber(eventString); } } // for(OneEvent event: this.events) Globals.addToBallotCount152(this.votesCast152); // FileUtils.logFile.printf("%s leave process152events%n", TAG); } // public void process152events() /********************************************************************* * Method to convert a <code>OneTerminal</code> to a * <code>String</code>. * * @return the formatted <code>String</code> value. **/ public String toString() { String s = ""; if(this.foundIn152) { s += String.format("Y "); } else { s += String.format("N "); } if(this.foundIn155) { s += String.format("Y "); } else { s += String.format("N "); } s += String.format("%7s", this.ivoNumber); s += String.format(" (%7s", this.openPEB); s += String.format(" %s)", this.openDateTime); s += String.format(" (%7s", this.closePEB); s += String.format(" %s)", this.closeDateTime); s += String.format(" %8s", Globals.convertToGoodVoteNumber(this.votesCast152)); s += String.format(" %8s", Globals.convertToGoodVoteNumber(this.votesCast155)); s += String.format(" ("); for(String key: this.ballotStyles.keySet()) { s += String.format(" %s", this.ballotStyles.get(key)); } s += String.format(") ("); for(String key: this.pcts.keySet()) { s += String.format(" %s", this.pcts.get(key)); } s += String.format(")"); s += this.toStringMemoryCollectionTime(); return s; } // public String toString() /********************************************************************* * Method to <code>toString</code> the memory collection times. * * @return the formatted <code>String</code> value. **/ public String toStringMemoryCollectionTime() { String s = ""; s += String.format(" ("); for(String mct: this.memoryCollectionTime) { s += String.format("(%s)", mct); } s += String.format(") "); return s; } // public String toStringMemoryCollectionTime() /********************************************************************* * Method to <code>toString</code> the map of precincts. * * @return the formatted <code>String</code> value. **/ public String toStringPcts() { String s = ""; s += String.format(" ("); for(String key: this.pcts.keySet()) { s += String.format(" %s", this.pcts.get(key)); } s += String.format(") "); return s; } // public String toStringPcts() } // public class OneTerminal
nealmcb/Voting-Data-Analysis
OneTerminal.java
248,233
package com.company; public class Candidate { private String name = ""; private int votes = 0; public Candidate(String name){ this.name = name; } public String getName(){ return name; } public void addVoice(){votes++;} public int getVotes(){ return votes; } }
rtu-mirea/OOP_lab03-r-abdullaev
Candidate.java
248,234
public class Candidate implements NodeState { private Node node; private Watch watch; private int number_accepts; private int number_rejects; private int number_votes; public Candidate(Node node) { this.node = node; } @Override public void work() { this.watch = new Watch(150,300,this); startCandidacy(); } @Override public void reactVoteRequest(VoteRequest message) { //candidate in same term if(message.getTerm() == this.node.getTerm()){ Message vr = MessageConstructor.constructVoteReply(this.node,message.getFrom(),false); this.node.sendUDPMessage(vr); } } @Override public void reactVoteReply(VoteReply message) { //votes to me if(this.node.getServiceAddress().equals(message.getTo())){ if(message.isGranted()){ this.number_accepts++; } else{ this.number_rejects++; } this.number_votes++; } } @Override public void reactAppendRequest(AppendRequest message) { //if there is a leader step down if (message.getTerm() >= this.node.getTerm()){ this.node.setState("Follower"); } } @Override public void reactAppendReply(AppendReply message) { //Candidate don't care about append reply's } @Override public void call() { //call happens but state is different if(!this.getState().equals(this.node.getCurrentState())){ return; } if( winCandidacy()){ this.node.setLeaderAddress(this.node.getServiceAddress()); this.node.setState("Leader"); } else{ this.node.setState("Follower"); } } @Override public String getState() { return "Candidate"; } private boolean winCandidacy(){ return (this.number_accepts > this.number_votes*0.5 && this.number_accepts!=this.number_rejects); } private void startCandidacy(){ //Increment term this.node.setTerm(this.node.getTerm()+1); //send vote request Message m= MessageConstructor.contructVoteRequest(this.node); this.node.sendUDPMessage(m); //vote in me this.number_accepts=1; this.number_votes=1; this.number_rejects=0; //set timer this.watch.start(); } }
LuckeLucky/Distributed-Systems
Candidate.java
248,235
import java.util.HashMap; import java.io.Serializable; public class Helpfulness implements Serializable{ public static final long serialVersionUID = 25461l; public final int votes; public final int total; private Helpfulness(int votes, int total){ this.votes = votes; this.total = total; } private transient static HashMap< Long, Helpfulness> lookup = new HashMap<Long, Helpfulness>(); public static Helpfulness build(int votes, int total){ if (lookup == null) lookup = new HashMap<Long, Helpfulness>(); long p = (((long) votes) << 32) + total; if (lookup.containsKey(p)) return lookup.get(p); Helpfulness ret = new Helpfulness(votes,total); lookup.put(p,ret); return ret; } }
mpmilano/nlp-final-project
src/Helpfulness.java
248,236
import java.util.Scanner; class Election{ static int[] votes = {0,0,0,0,0,0}; static String[] allIdes = {"12a", "21s", "12e", "21e", "2w1", "23as", "32s", "33a"}; static int len = allIdes.length; static String[] votedIdes = new String[len]; static void result(){ System.out.println("candidate 1 : "+ votes[0]); System.out.println("candidate 2 : "+ votes[1]); System.out.println("candidate 3 : "+ votes[2]); System.out.println("candidate 4 : "+ votes[3]); System.out.println("candidate 5 : "+ votes[4]); System.out.println("candidate 5 : "+ votes[5]); } static int count = 0; static boolean check(String id){ for (int i = 0; i < len; i++) { if(id.equals(allIdes[i])){ for (int j = 0; j < len; j++) { if(id.equals(votedIdes[j])) return false; } votedIdes[count++]= id; return true; } } return false; } } class Voters{ String id ; Voters(String id){ this.id = id; } void vote(int num){ switch(num){ case 1: Election.votes[0] += 1; break; case 2: Election.votes[1] += 1; break; case 3: Election.votes[2] += 1; break; case 4: Election.votes[3] += 1; break; case 5: Election.votes[4] += 1; break; default: Election.votes[5] += 1; break; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(true){ System.out.println( "are you going to vote press y "); String c = sc.next(); if(!c.equals("y")) break; System.out.print( "Enter your Election ID : "); String id1 = sc.next(); if(Election.check(id1)){ Voters v1 = new Voters(id1); System.out.println("enter your candidate number"); v1.vote(sc.nextInt()); }else{ System.out.println("Check your Election ID"); } } sc.close(); Election.result(); } }
sasikumar44/Assignment2
22election.java
248,237
/* * Copyright © 2013-2016 The Nxt Core Developers. * Copyright © 2016-2017 Jelurida IP B.V. * * See the LICENSE.txt file at the top-level directory of this distribution * for licensing information. * * Unless otherwise agreed in a custom licensing agreement with Jelurida B.V., * no part of the Nxt software, including this file, may be copied, modified, * propagated, or distributed except according to the terms contained in the * LICENSE.txt file. * * Removal or modification of this copyright notice is prohibited. * */ package nxt; import nxt.db.DbClause; import nxt.db.DbIterator; import nxt.db.DbKey; import nxt.db.DbUtils; import nxt.db.EntityDbTable; import nxt.db.ValuesDbTable; import nxt.util.Logger; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.Arrays; import java.util.List; public final class Poll extends AbstractPoll { private static final boolean isPollsProcessing = Nxt.getBooleanProperty("nxt.processPolls"); public static final class OptionResult { private long result; private long weight; private OptionResult(long result, long weight) { this.result = result; this.weight = weight; } public long getResult() { return result; } public long getWeight() { return weight; } private void add(long vote, long weight) { this.result += vote; this.weight += weight; } } private static final DbKey.LongKeyFactory<Poll> pollDbKeyFactory = new DbKey.LongKeyFactory<Poll>("id") { @Override public DbKey newKey(Poll poll) { return poll.dbKey == null ? newKey(poll.id) : poll.dbKey; } }; private final static EntityDbTable<Poll> pollTable = new EntityDbTable<Poll>("poll", pollDbKeyFactory, "name,description") { @Override protected Poll load(Connection con, ResultSet rs, DbKey dbKey) throws SQLException { return new Poll(rs, dbKey); } @Override protected void save(Connection con, Poll poll) throws SQLException { poll.save(con); } }; private static final DbKey.LongKeyFactory<Poll> pollResultsDbKeyFactory = new DbKey.LongKeyFactory<Poll>("poll_id") { @Override public DbKey newKey(Poll poll) { return poll.dbKey; } }; private static final ValuesDbTable<Poll, OptionResult> pollResultsTable = new ValuesDbTable<Poll, OptionResult>("poll_result", pollResultsDbKeyFactory) { @Override protected OptionResult load(Connection con, ResultSet rs) throws SQLException { long weight = rs.getLong("weight"); return weight == 0 ? null : new OptionResult(rs.getLong("result"), weight); } @Override protected void save(Connection con, Poll poll, OptionResult optionResult) throws SQLException { try (PreparedStatement pstmt = con.prepareStatement("INSERT INTO poll_result (poll_id, " + "result, weight, height) VALUES (?, ?, ?, ?)")) { int i = 0; pstmt.setLong(++i, poll.getId()); if (optionResult != null) { pstmt.setLong(++i, optionResult.result); pstmt.setLong(++i, optionResult.weight); } else { pstmt.setNull(++i, Types.BIGINT); pstmt.setLong(++i, 0); } pstmt.setInt(++i, Nxt.getBlockchain().getHeight()); pstmt.executeUpdate(); } } }; public static Poll getPoll(long id) { return pollTable.get(pollDbKeyFactory.newKey(id)); } public static DbIterator<Poll> getPollsFinishingAtOrBefore(int height, int from, int to) { return pollTable.getManyBy(new DbClause.IntClause("finish_height", DbClause.Op.LTE, height), from, to); } public static DbIterator<Poll> getAllPolls(int from, int to) { return pollTable.getAll(from, to); } public static DbIterator<Poll> getActivePolls(int from, int to) { return pollTable.getManyBy(new DbClause.IntClause("finish_height", DbClause.Op.GT, Nxt.getBlockchain().getHeight()), from, to); } public static DbIterator<Poll> getPollsByAccount(long accountId, boolean includeFinished, boolean finishedOnly, int from, int to) { DbClause dbClause = new DbClause.LongClause("account_id", accountId); if (finishedOnly) { dbClause = dbClause.and(new DbClause.IntClause("finish_height", DbClause.Op.LTE, Nxt.getBlockchain().getHeight())); } else if (!includeFinished) { dbClause = dbClause.and(new DbClause.IntClause("finish_height", DbClause.Op.GT, Nxt.getBlockchain().getHeight())); } return pollTable.getManyBy(dbClause, from, to); } public static DbIterator<Poll> getPollsFinishingAt(int height) { return pollTable.getManyBy(new DbClause.IntClause("finish_height", height), 0, Integer.MAX_VALUE); } public static DbIterator<Poll> searchPolls(String query, boolean includeFinished, int from, int to) { DbClause dbClause = includeFinished ? DbClause.EMPTY_CLAUSE : new DbClause.IntClause("finish_height", DbClause.Op.GT, Nxt.getBlockchain().getHeight()); return pollTable.search(query, dbClause, from, to, " ORDER BY ft.score DESC, poll.height DESC, poll.db_id DESC "); } public static int getCount() { return pollTable.getCount(); } static void addPoll(Transaction transaction, Attachment.MessagingPollCreation attachment) { Poll poll = new Poll(transaction, attachment); pollTable.insert(poll); } static void init() {} static { if (Poll.isPollsProcessing) { Nxt.getBlockchainProcessor().addListener(block -> { int height = block.getHeight(); if (height >= Constants.PHASING_BLOCK) { Poll.checkPolls(height); } }, BlockchainProcessor.Event.AFTER_BLOCK_APPLY); } } private static void checkPolls(int currentHeight) { try (DbIterator<Poll> polls = getPollsFinishingAt(currentHeight)) { for (Poll poll : polls) { try { List<OptionResult> results = poll.countResults(poll.getVoteWeighting(), currentHeight); pollResultsTable.insert(poll, results); Logger.logDebugMessage("Poll " + Long.toUnsignedString(poll.getId()) + " has been finished"); } catch (RuntimeException e) { Logger.logErrorMessage("Couldn't count votes for poll " + Long.toUnsignedString(poll.getId())); } } } } private final DbKey dbKey; private final String name; private final String description; private final String[] options; private final byte minNumberOfOptions; private final byte maxNumberOfOptions; private final byte minRangeValue; private final byte maxRangeValue; private final int timestamp; private Poll(Transaction transaction, Attachment.MessagingPollCreation attachment) { super(transaction.getId(), transaction.getSenderId(), attachment.getFinishHeight(), attachment.getVoteWeighting()); this.dbKey = pollDbKeyFactory.newKey(this.id); this.name = attachment.getPollName(); this.description = attachment.getPollDescription(); this.options = attachment.getPollOptions(); this.minNumberOfOptions = attachment.getMinNumberOfOptions(); this.maxNumberOfOptions = attachment.getMaxNumberOfOptions(); this.minRangeValue = attachment.getMinRangeValue(); this.maxRangeValue = attachment.getMaxRangeValue(); this.timestamp = Nxt.getBlockchain().getLastBlockTimestamp(); } private Poll(ResultSet rs, DbKey dbKey) throws SQLException { super(rs); this.dbKey = dbKey; this.name = rs.getString("name"); this.description = rs.getString("description"); this.options = DbUtils.getArray(rs, "options", String[].class); this.minNumberOfOptions = rs.getByte("min_num_options"); this.maxNumberOfOptions = rs.getByte("max_num_options"); this.minRangeValue = rs.getByte("min_range_value"); this.maxRangeValue = rs.getByte("max_range_value"); this.timestamp = rs.getInt("timestamp"); } private void save(Connection con) throws SQLException { try (PreparedStatement pstmt = con.prepareStatement("INSERT INTO poll (id, account_id, " + "name, description, options, finish_height, voting_model, min_balance, min_balance_model, " + "holding_id, min_num_options, max_num_options, min_range_value, max_range_value, timestamp, height) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) { int i = 0; pstmt.setLong(++i, id); pstmt.setLong(++i, accountId); pstmt.setString(++i, name); pstmt.setString(++i, description); DbUtils.setArray(pstmt, ++i, options); pstmt.setInt(++i, finishHeight); pstmt.setByte(++i, voteWeighting.getVotingModel().getCode()); DbUtils.setLongZeroToNull(pstmt, ++i, voteWeighting.getMinBalance()); pstmt.setByte(++i, voteWeighting.getMinBalanceModel().getCode()); DbUtils.setLongZeroToNull(pstmt, ++i, voteWeighting.getHoldingId()); pstmt.setByte(++i, minNumberOfOptions); pstmt.setByte(++i, maxNumberOfOptions); pstmt.setByte(++i, minRangeValue); pstmt.setByte(++i, maxRangeValue); pstmt.setInt(++i, timestamp); pstmt.setInt(++i, Nxt.getBlockchain().getHeight()); pstmt.executeUpdate(); } } public List<OptionResult> getResults(VoteWeighting voteWeighting) { if (this.voteWeighting.equals(voteWeighting)) { return getResults(); } else { return countResults(voteWeighting); } } public List<OptionResult> getResults() { if (Poll.isPollsProcessing && isFinished()) { return pollResultsTable.get(pollDbKeyFactory.newKey(this)); } else { return countResults(voteWeighting); } } public DbIterator<Vote> getVotes(){ return Vote.getVotes(this.getId(), 0, -1); } public String getName() { return name; } public String getDescription() { return description; } public String[] getOptions() { return options; } public byte getMinNumberOfOptions() { return minNumberOfOptions; } public byte getMaxNumberOfOptions() { return maxNumberOfOptions; } public byte getMinRangeValue() { return minRangeValue; } public byte getMaxRangeValue() { return maxRangeValue; } public int getTimestamp() { return timestamp; } public boolean isFinished() { return finishHeight <= Nxt.getBlockchain().getHeight(); } private List<OptionResult> countResults(VoteWeighting voteWeighting) { int countHeight = Math.min(finishHeight, Nxt.getBlockchain().getHeight()); if (countHeight < Nxt.getBlockchainProcessor().getMinRollbackHeight()) { return null; } return countResults(voteWeighting, countHeight); } private List<OptionResult> countResults(VoteWeighting voteWeighting, int height) { final OptionResult[] result = new OptionResult[options.length]; VoteWeighting.VotingModel votingModel = voteWeighting.getVotingModel(); try (DbIterator<Vote> votes = Vote.getVotes(this.getId(), 0, -1)) { for (Vote vote : votes) { long weight = votingModel.calcWeight(voteWeighting, vote.getVoterId(), height); if (weight <= 0) { continue; } long[] partialResult = countVote(vote, weight); for (int i = 0; i < partialResult.length; i++) { if (partialResult[i] != Long.MIN_VALUE) { if (result[i] == null) { result[i] = new OptionResult(partialResult[i], weight); } else { result[i].add(partialResult[i], weight); } } } } } return Arrays.asList(result); } private long[] countVote(Vote vote, long weight) { final long[] partialResult = new long[options.length]; final byte[] optionValues = vote.getVoteBytes(); for (int i = 0; i < optionValues.length; i++) { if (optionValues[i] != Constants.NO_VOTE_VALUE) { partialResult[i] = (long) optionValues[i] * weight; } else { partialResult[i] = Long.MIN_VALUE; } } return partialResult; } }
LimaYes/ElasticPrototypeWallet
src/nxt/Poll.java
248,241
package HARSH40; import java.util.Scanner; public class VotesWinner { public static void main(String[] args) { String[] candidates=new String[5]; Scanner sc=new Scanner(System.in); int[] votes = new int[5]; float[] voteper=new float[5]; int max,sum=0; for(int i=0;i<5;i++) { System.out.println("Enter candidates name:"); candidates[i]=sc.next(); System.out.println("Enter no. of votes:"); votes[i]=sc.nextInt(); sum+=votes[i]; } max=0; for(int i=0;i<5;i++) { voteper[i]=(votes[i]/(float)sum)*100; if(voteper[i]>voteper[max]) { max=i; System.out.println("Candidate"+"\t"+"Votes Received"+"\t"+"TotalVotes"+""); } } for(int i=0;i<5;i++) { System.out.println(candidates[i]+"\t\t"+votes[i]+"\t\t"+voteper[i]+" "); } System.out.println("The Winner of the Election is "+ candidates[max]); System.out.println("*****************************************************************"); System.out.println("Implemented By:Harsh Raj Mishra\tClass Roll No. 40\tCSE4(E)"); System.out.println("*****************************************************************"); } }
harshify/Java-TermWork
VotesWinner.java
248,242
package org.server.game; import org.server.*; import java.util.ArrayList; import java.util.List; /** * Playforia * 30.5.2013 */ public abstract class Game { public static final int PERM_EVERYONE = 0; public static final int PERM_REGISTERED = 1; public static final int PERM_VIP = 2; public static final int STROKES_UNLIMITED = 0; public static final int STROKETIMEOUT_INFINITE = 0; public static final int WATER_START = 0; public static final int WATER_SHORE = 1; public static final int COLLISION_NO = 0; public static final int COLLISION_YES = 1; public static final int SCORING_STROKE = 0; public static final int SCORING_TRACK = 1; public static final int SCORING_WEIGHT_END_NONE = 0; public static final int SCORING_WEIGHT_END_LITTLE = 1; public static final int SCORING_WEIGHT_END_PLENTY = 2; public int gameId; public List<Player> players; public List<Integer> playersNumber; public int numberIndex = 0; protected Track[] tracks; protected int currentTrack = 0; protected int confirmCount = 0; protected int strokesThisTrack = 0; protected int lobbySource; protected int wantsGameCount = 0; protected String playStatus; public Game(int lobbySource) { this.gameId = Server.generateGameID(); this.lobbySource = lobbySource; players = new ArrayList<Player>(); playersNumber = new ArrayList<Integer>(); } protected abstract void initTracks(); protected abstract void startGame(); public int getLobbySource() { return lobbySource; } public boolean addPlayer(Player p) { //todo some check that you can actually add this player to this game. players.add(p); playersNumber.add(numberIndex++); return true; } public void removeGame() { // todo: clearup of game } public void beginStroke(Player p, String mouseCoords) { //todo: anti cheat mechanisms! int id = getIndex(p); broadcastDExcept(p, "game", "beginstroke", playersNumber.get(id), mouseCoords); } public void broadcastDExcept(Player p, Object... args) { for (int i = 0; i < players.size(); i++) { if (!players.get(i).equals(p)) { Session s = Server.getSession(players.get(i)); Conn.writeD(s, args); } } } public void endStroke(Player p, String playStatus) { boolean finished = true; this.playStatus = playStatus; for (int i = 0; i < playStatus.length(); i++) { if (playStatus.charAt(i) == 'f') { finished = false; break; } } confirmCount++; // only sends the command after everyone confirms end stroke. if (confirmCount == players.size()) { confirmCount = 0; if (finished) { nextTrack(); } else { broadcastD("game", "startturn", getNextPlayer(playStatus)); } } } public int getNextPlayer(String s) { strokesThisTrack++; int player = strokesThisTrack % players.size(); if (s.charAt(player) == 't') { // if this player has already finihed strokesThisTrack++; } return playersNumber.get(strokesThisTrack % players.size()); } public int getFirstPlayer() { return playersNumber.get(0); } public void removePlayer(Player p) { int id = getIndex(p); players.remove(p); playersNumber.remove((Integer) id); // im not sure about this one :/ } public int getIndex(Player p) { int id = 0; for (int i = 0; i < players.size(); i++) { if (players.get(i).equals(p)) { id = i; break; } } return id; } protected void nextTrack() { strokesThisTrack = 0; currentTrack++; if (currentTrack < tracks.length) { // there is a next track Track t = tracks[currentTrack]; StringBuffer buff = new StringBuffer(); for (int i = 0; i < players.size(); i++) { buff.append("t"); } broadcastD("game", "starttrack", buff.toString(),gameId, t); broadcastD("game", "startturn", getFirstPlayer()); } else { endGame(); } } protected void endGame() { broadcastD("game", "end"); } public void broadcastD(Object... data) { for (Player p : players) { Conn.writeD(Server.getSession(p), data); } } public void wantsNewGame(Player p) { wantsGameCount++; broadcastDExcept(p, "game", "rfng", playersNumber.get(getIndex(p))); if (wantsGameCount >= players.size()) { wantsGameCount = 0; currentTrack = 0; strokesThisTrack = 0; initTracks(); startGame(); } } public void voteSkip(Player p) { nextTrack(); // cba to implement this properly } public boolean hasPlayer(Player p) { return players.contains(p); } public boolean isEmpty() { return players.size() == 0; } public Player[] getPlayers() { return players.toArray(new Player[0]); } }
PhilippvK/playforia-minigolf
doc/old_game.java
248,244
import java.util.Scanner; public class Main { public static final Scanner input = new Scanner(System.in); public static boolean quit = false; public static void main(String[] args) { new Thread1().start(); new Thread2().start(); new Thread3().start(); } public static void askToQuit() { System.out.println(); System.out.print("Quit? (y/n) "); quit = Main.input.nextLine().compareToIgnoreCase("y") == 0; System.out.println(); System.out.println("-".repeat(30)); System.out.println(); } } class Thread1 extends Thread { @Override public void run() { while (!Main.quit) { synchronized (Main.input) { if (Main.quit) break; System.out.print("Year: "); int year = Main.input.nextInt(); Main.input.nextLine(); System.out.println("Name: " + this.getName()); System.out.println("Age : " + (1400 - year)); Main.askToQuit(); } try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("End of " + this.getName()); } } class Thread2 extends Thread { @Override public void run() { while (!Main.quit) { synchronized (Main.input) { if (Main.quit) break; System.out.print("Number: "); int number = Main.input.nextInt(); Main.input.nextLine(); System.out.println("Name: " + this.getName()); System.out.println("isPrime: " + isPrime(number)); Main.askToQuit(); } try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("End of " + this.getName()); } private boolean isPrime(int number) { int counter = 0; for (int i = 1; i <= number; i++) if (number % i == 0) counter++; return counter == 2; } } class Thread3 extends Thread { int[] votes; public Thread3() { this.votes = new int[5]; } @Override public void run() { while (!Main.quit) { synchronized (Main.input) { if (Main.quit) break; System.out.println("1) Bijan"); System.out.println("2) Reza"); System.out.println("3) Mohammad Hussein"); System.out.println("4) Mahan"); System.out.println("5) Seyed"); System.out.print("Index: "); int index = Main.input.nextInt(); Main.input.nextLine(); votes[index - 1]++; System.out.println(); System.out.println("Name: " + this.getName()); System.out.println("Bijan : " + votes[0]); System.out.println("Reza : " + votes[1]); System.out.println("Mohammad Hussein: " + votes[2]); System.out.println("Mahan : " + votes[3]); System.out.println("Seyed : " + votes[4]); Main.askToQuit(); } try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("End of " + this.getName()); } }
KHU1399WinterAP/multi-threading
src/Main.java
248,248
import java.util.ArrayList; // Class of Movies for storing them into a object. public class Movie { private String title; private Long year; private ArrayList<String> genre; private Long runTime; private Double rating; private Long votes; private String director; private String cast; private Double gross; public Movie(String title, Long year, ArrayList<String> genre, Long runTime, Double rating, Long votes, String director, String cast, Double gross) { this.title = title; this.year = year; this.genre = genre; this.runTime = runTime; this.rating = rating; this.votes = votes; this.director = director; this.cast = cast; this.gross = gross; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Long getYear() { return year; } public void setYear(Long year) { this.year = year; } public ArrayList<String> getGenre() { return genre; } public void setGenre(ArrayList<String> genre) { this.genre = genre; } public Long getRunTime() { return runTime; } public void setRunTime(Long runTime) { this.runTime = runTime; } public Double getRating() { return rating; } public void setRating(Double rating) { this.rating = rating; } public Long getVotes() { return votes; } public void setVotes(Long votes) { this.votes = votes; } public String getDirector() { return director; } public void setDirector(String director) { this.director = director; } public String getCast() { return cast; } public void setCast(String cast) { this.cast = cast; } public Double getGross() { return gross; } public void setGross(Double gross) { this.gross = gross; } }
imertyildiz/Movies-Directors
src/Movie.java
248,249
package week14; public class Candidate { private int id; private String name; private int votes = 0; public Candidate(int id, String name){ this.id = id; this.name = name; } public int getId(){ return id; } public String getName(){ return name; } public int getVotes(){ return votes; } public void addVote(){ votes++; } }
nadialvy/online-election-practice
Candidate.java
248,251
import java.util.Arrays; public class Serie { private String title; private int duration; private int year; private Actor actor; private String thumbnail; private float rating; private long votes; private int[] genres; public String getTitle() { return title; } public int getDuration() { return duration; } public int getYear() { return year; } public Actor getActor() { return actor; } public String getThumbnail() { return thumbnail; } public float getRating() { return rating; } public long getVotes() { return votes; } public int[] getGenres() { return genres; } @Override public String toString() { return "Serie{" + "title='" + title + '\'' + ", duration=" + duration + ", year=" + year + ", actor=" + actor + ", thumbnail='" + thumbnail + '\'' + ", rating=" + rating + ", votes=" + votes + ", genres=" + Arrays.toString(genres) + '}'; } public void printAllDetails () { System.out.println("Title: " + this.getTitle()); System.out.println("Duration: " + this.getDuration()); System.out.println("Year: " + this.getYear()); System.out.println("Actor: " + this.getActor().getName()); System.out.println("Thumbnail: " + this.getThumbnail()); System.out.println("Rating: " + this.getRating()); System.out.println("Votes: " + this.getVotes()); System.out.println("Genres: " + this.getGenres()); } }
nickj10/IntroJson
src/Serie.java
248,254
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; public class AVModel extends Observable implements IAVModel { ArrayList<AVBallot> ballotResults = new ArrayList<>(); ArrayList<AVCandidate> candidates = new ArrayList<>(); HashMap<String, Integer> candidateTotals = new HashMap<>(); @Override public void countVotes(){ assert ballotResults.size()>0 : "Ballots must not be empty"; removeBlankVotes(); // We don't want to store or sort empty votes makeCandidateList(); // Assigns class var candidates list of unique candidates collectBallots(); // Finds initially the first vote of each ballot and assigns it makeCandidateTotals(); // Calculates the totals for each candidate in list this.setChanged(); this.notifyObservers(); } @Override public void redistribute(){ AVCandidate lowestCandidate = findLowestRankingCandidate(); // candidate with least votes removeLowestCandidateFromBallots(lowestCandidate); candidates = new ArrayList<>(); // reinitialise candidateTotals = new HashMap<>(); countVotes(); // Repeat the counting process, this time without the lowest candidate this.setChanged(); this.notifyObservers(); } @Override public HashMap<String, Integer> getCandidateTotals() { assert candidateTotals !=null : "Candidate totals is not initialised"; return candidateTotals; } @Override public ArrayList<AVBallot> getBallotResults(){ return this.ballotResults; } @Override public void addBallot(String[] choices){ assert ballotResults != null : "Ballot results must be intialised to new arraylist"; ArrayList<String> newVote = new ArrayList<String>( Arrays.asList(choices ) ); AVBallot newBallot = new AVBallot(); newBallot.setAllCandidateChoices(newVote); ballotResults.add(newBallot); this.setChanged(); this.notifyObservers(); } @Override public void readCSV(String pathToFile) { assert pathToFile != "" : "Path to file can not be empty"; BufferedReader br = null; String line = ""; String cvsSplitBy = ","; try { br = new BufferedReader(new FileReader(pathToFile)); while ((line = br.readLine()) != null) { AVBallot ballotsFromFile = new AVBallot(); String[] candidates = line.split(cvsSplitBy); ballotsFromFile.setAllCandidateChoices(new ArrayList<>(Arrays.asList(candidates))); this.ballotResults.add(ballotsFromFile); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Override public void convertBallotResultsToCandidateResults() { assert ballotResults.size() > 0 : "Ballot results can not be empty"; for (AVBallot votesList : ballotResults) { for (String aVotesList : votesList.getAllCandidateChoices()) { Integer candidateVoteTotal = candidateTotals.get(aVotesList); if (candidateVoteTotal != null) { candidateTotals.put(aVotesList, candidateVoteTotal + 1); } else { candidateTotals.put(aVotesList, 1); } } } sortCandidateTotalsByVotes(); } /** * Removes empty candidate entries in the ballots class * @pre ballots must not be empty * @post there will be no more empty candidates in ballot candidate list */ private void removeBlankVotes(){ assert ballotResults.size() > 0 : "Ballot results can not be empty"; for(AVBallot ballot : ballotResults){ for(int i = 0; i< ballot.getAllCandidateChoices().size(); i++){ if(ballot.getAllCandidateChoices().get(i).equals("")){ ballot.removeCandidateAtIndex(i); } } } } /** * Add all candidates from all ballots to the candidates list * if they aren't yet in it * @pre there must be ballots * @post the candidates list will be populated */ private void makeCandidateList(){ assert ballotResults.size() > 0 : "Ballot results can not be empty"; candidates = new ArrayList<>(); for(AVBallot ballot: ballotResults){ candidates.addAll( ballot.getAllCandidateChoices().stream() .filter(candidateName -> !doesCandidateExist(candidateName)) .map(AVCandidate::new).collect(Collectors.toList()) ); } } /** * Distributes ballots between remaining candidates * @pre there must be ballots and some remaining candidates * @post the candidates will have ballot objects assigned to them */ private void collectBallots() { assert ballotResults.size() > 0 : "Ballot results can not be empty"; assert candidates.size() > 0 : "There must be some remaining candidates"; ballotResults.stream() .filter(ballot -> ballot.getAllCandidateChoices().size() > 0) .forEach(ballot -> { String firstChoice = ballot.getCandidateAtIndex(0); int candidateIndex = findCandidateIndexFromName(firstChoice); AVCandidate candidate = candidates.get(candidateIndex); candidate.appendBallot(ballot); candidates.add(candidateIndex, candidate); }); } /** * Populates the candidate totals HashMap * with values from the candidates list * @pre the candidates list should not be empty * @post the candidateTotals HashMap will be populated */ private void makeCandidateTotals(){ assert candidates.size() > 0 : "Candidates list can not be empty"; for(AVCandidate candidate: candidates){ candidateTotals.put(candidate.getName(), candidate.numOfBallots()); } sortCandidateTotalsByVotes(); } /** * Sorts the candidateResults class variable by number of votes * @pre candidateVotes should have valid data * @post candidateVotes will be sorted */ private void sortCandidateTotalsByVotes() { assert candidateTotals.size()>0 : "There need to be some candidate totalls"; candidateTotals = (HashMap<String, Integer>)new MapUtil().sortByValue(candidateTotals); } /** * Checks if a candidate object with given candidateName is present * in the candidates class variable * @pre candidates list should not be empty * @post will return boolean value, no data modified * @param candidateName the string identifier of candidate * @return true if candidate found, if not found return false */ private boolean doesCandidateExist(String candidateName){ for(AVCandidate candidate : candidates){ if(candidate.getName().equals(candidateName)){ return true; } } return false; } /** * Returns the index for a given candidate specified by their name * @pre candidate must exist * @post index in list will be returned * @param candidateName the text identifier of a given candidate * @return integer value indicating position in candidate class list */ private int findCandidateIndexFromName(String candidateName){ assert !Objects.equals(candidateName, "") : "Candidate must have a name and exist"; for(int i = 0; i < candidates.size(); i++){ if(candidates.get(i).getName().equals(candidateName)){ return i; } } return 0; } /** * Finds the lest popular candidate * @pre there must be candidates availible * @post candidate with lowest rank will be returned * @return AVCandidate with lowest rank */ private AVCandidate findLowestRankingCandidate(){ assert candidates.size() > 0 : "There must be some rementing candidates"; Map.Entry<String, Integer> lowestCandidate = null; for (Map.Entry<String, Integer> entry : candidateTotals.entrySet()) { if (lowestCandidate == null || entry.getValue().compareTo(lowestCandidate.getValue()) < 0){ lowestCandidate = entry; } } assert lowestCandidate != null; return candidates.get(findCandidateIndexFromName(lowestCandidate.getKey())); } /** * Remove low ranking candidate from all ballots * @pre ballots list must not be empty * @post ballots list will have the lowest candidate removed */ private void removeLowestCandidateFromBallots(AVCandidate lowestCandidate){ assert ballotResults.size()>0 : "Ballots must not be empty"; String lowestCandidateName = lowestCandidate.getName(); for (AVBallot ballotResult : ballotResults) { ArrayList<String> choices = ballotResult.getAllCandidateChoices(); for (int i = 0; i < choices.size(); i++) { if (choices.get(i).equals(lowestCandidateName)) { ballotResult.removeCandidateAtIndex(i); } } } } public void initialise() { setChanged(); notifyObservers(); } public AVModel() { initialise(); } /** * Sorts a HashMap of candidate names and votes by votes * @pre candidateVotes passed in should not be empty of null * @post will return the sorted candidateVotes data */ private class MapUtil { public <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ) { List<Map.Entry<K, V>> list = new LinkedList<>( map.entrySet() ); Collections.sort( list, (o2, o1) -> (o1.getValue()).compareTo( o2.getValue() )); Map<K, V> result = new LinkedHashMap<>(); for (Map.Entry<K, V> entry : list) { result.put( entry.getKey(), entry.getValue() ); } return result; } } }
Lissy93/AlternativeVoteSystem
src/AVModel.java
248,255
public class vote { public String[] candidate; public int[][] votes; public vote(String[] candidate) { this.candidate = candidate; this.votes = new int[candidate.length][candidate.length]; } public int[] count(int[][] votes, int left, int right) { if (left == right) { int[] vote = votes[left]; int[] result = new int[1]; result[0] = sum(vote, 0, vote.length - 1); return result; } else { int mid = (left + right) / 2; int[] leftResult = count(votes, left, mid); int[] rightResult = count(votes, mid+1, right); int leftLen = leftResult.length; int rightLen = rightResult.length; int[] result = new int[leftLen + rightLen]; for (int i = 0; i < leftLen; i++) { result[i] = leftResult[i]; } for (int i = leftLen; i < leftLen + rightLen; i++) { result[i] = rightResult[i - leftLen]; } return result; } } public int sum(int[] vote, int left, int right) { int total = 0; for (int i = left; i <= right; i++) { total += vote[i]; } return total; } public void display() { int[] voteCount = count(votes, 0, votes.length - 1); int highIdx = 0; int highNum = 0; for (int i = 0; i < voteCount.length; i++) { if (voteCount[i] > highNum) { highNum = voteCount[i]; highIdx = i; } } System.out.printf("The elected president is %s with %d votes\n", candidate[highIdx], highNum); } }
FebrianArkaSamudra/ProjectLatDasPro
Smt 2/vote.java
248,256
public class Result extends javax.swing.JFrame { // Member variables to store party names and number of votes private String[] partyNames = {"Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "NOTA"}; private int[] votes = new int[6]; // Constructor to initialize the frame components public Result() { initComponents(); displayResults(); } // Method to initialize and display frame components private void initComponents() { // Initialize frame components (labels, buttons, etc.) here // This part should contain the layout and design of the result frame // Refer to the provided code for the layout and design } // Method to update the vote counts for each party public void updateVotes(int option, int count) { if (option >= 1 && option <= 6) { votes[option - 1] = count; displayResults(); } } // Method to display the results on the frame private void displayResults() { // Update the JLabels with the vote counts for each party jLabel12.setText(String.valueOf(votes[0])); jLabel13.setText(String.valueOf(votes[1])); jLabel14.setText(String.valueOf(votes[2])); jLabel15.setText(String.valueOf(votes[3])); jLabel16.setText(String.valueOf(votes[4])); jLabel17.setText(String.valueOf(votes[5])); // Update the maximum votes label with the party name having the maximum votes int maxVotes = votes[0]; int maxIndex = 0; for (int i = 1; i < votes.length; i++) { if (votes[i] > maxVotes) { maxVotes = votes[i]; maxIndex = i; } } jLabel18.setText(partyNames[maxIndex]); } // Main method to create and display the Result frame public static void main(String args[]) { // Set the look and feel of the frame 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(Result.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Result.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Result.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Result.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } // Create and display the Result frame java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Result().setVisible(true); } }); } // Variables declaration // These should include JLabels for party names, vote counts, and maximum votes // as well as any other components needed for the layout private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; // End of variables declaration }
i-soumya18/OnlineVotingSystem
src/Result.java
248,257
public enum States { OHIO(18), PENNSYLVANIA(21), TEXAS(38), GEORGIA(16), FLORIDA(29); private int votes; private States (int votes){ this.votes = votes; } public int getElectoralVotes(){ return votes; } }
hsklar/Sklar_C-mco152-2017F_asgn04
src/States.java
248,258
package movie; /****************************************************************************** * This class represents details of a movie, including various attributes * such as name, rating, genre, year, etc. The class implements the Comparable * interface, allowing instances to be compared based on their names. ******************************************************************************/ public class Movie implements Comparable<Movie> { private int id; private String name; private String rating; private String genre; private int year; private String released; private double score; private double votes; private String director; private String writer; private String star; private String country; private double budget; private double gross; private String company; private double runtime; public Movie(int id, String name, String rating, String genre, int year, String released, double score, double votes, String director, String writer, String star, String country, double budget, double gross, String company, double runtime) { this.id = id; this.name = name; this.rating = rating; this.genre = genre; this.year = year; this.released = released; this.score = score; this.votes = votes; this.director = director; this.writer = writer; this.star = star; this.country = country; this.budget = budget; this.gross = gross; this.company = company; this.runtime = runtime; } public String toString() { return String.format("%-30s%-20s%15.2f%15.2f", name, genre, budget, gross); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRating() { return rating; } public void setRating(String rating) { this.rating = rating; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public String getReleased() { return released; } public void setReleased(String released) { this.released = released; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public double getVotes() { return votes; } public void setVotes(double votes) { this.votes = votes; } public String getDirector() { return director; } public void setDirector(String director) { this.director = director; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public String getStar() { return star; } public void setStar(String star) { this.star = star; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public double getBudget() { return budget; } public void setBudget(double budget) { this.budget = budget; } public double getGross() { return gross; } public void setGross(double gross) { this.gross = gross; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public double getRuntime() { return runtime; } public void setRuntime(double runtime) { this.runtime = runtime; } public int compareTo(Movie m) { return this.name.compareTo(m.name); } }
sanjshine99/6CS002-portfolio-task-5
movie/Movie.java
248,260
import movies.Movie; import movies.MyIMDB; import java.io.FileNotFoundException; import java.util.List; import java.util.Map; import java.util.Scanner; /** * The main program for the IMDB movie query system. If run on the command line * with no arguments, it uses the large title (data/title.basics.tsv) and ratings * (data/title.ratings.tsv) files. Otherwise with any arguments it uses the small title * (data/small.basics.tsv) and ratings (data/small.ratings.tsv) files. * * The input commands need to be redirected from a file to standard input using the run * configuration. Example input commands are in the input/ directory. * * @author RIT CS */ public class MovieMain { // INPUT COMMANDS /** find movie titles that contain a substring */ private final static String CONTAINS = "CONTAINS"; /** lookup a movie by ID (tconst) */ private final static String LOOKUP = "LOOKUP"; /** find movies by year and genre */ private final static String YEAR_AND_GENRE = "YEAR_AND_GENRE"; /** find a range of movies with a certain runtime in minutes */ private final static String RUNTIME = "RUNTIME"; /** find movies with the top number of votes (from ratings) */ private final static String MOST_VOTES = "MOST_VOTES"; /** find the top movies over a range of years */ private final static String TOP = "TOP"; /** the concrete class that inherits and implements from the IMDB abstract class */ private final MyIMDB imdb; /** * Instantiate MyIDBM with the small or large dataset, then call three methods * to handle reading in the files and creating the appropriate internal data * structures to represent them. * * @param small true if the small dataset is to be used, false for the large one * @throws FileNotFoundException if the file cannot be found */ public MovieMain(boolean small) throws FileNotFoundException { // read in the basics movie dataset System.out.println("Reading movies into list..."); long start = System.currentTimeMillis(); this.imdb = new MyIMDB(small); System.out.println("Elapsed time (s): " + ((System.currentTimeMillis() - start) / 1000.0)); // convert the list to a map for fast lookup by id System.out.println("Converting movie list to map..."); start = System.currentTimeMillis(); this.imdb.convertMovieListToMap(); System.out.println("Elapsed time (s): " + ((System.currentTimeMillis() - start) / 1000.0)); // create in the ratings dataset System.out.println("Reading ratings into map..."); start = System.currentTimeMillis(); this.imdb.processRatings(); System.out.println("Elapsed time (s): " + ((System.currentTimeMillis() - start) / 1000.0)); } /** * Used by some commands to get the trailing words (often used for substring titles). * * @param fields array of strings * @param start the index in the array to start at * @return the individual words concatenated to a string with spaces in-between */ private String combineFields(String[] fields, int start) { StringBuilder words = new StringBuilder(); for (int i=start; i<fields.length; ++i) { words.append(fields[i]); if (i != fields.length-1) { words.append(" "); } } return words.toString(); } /** * Handles the contain command query, e.g.: "CONTAINS MOVIE Starman". * * @param fields the command */ private void processContains(String[] fields) { String words = combineFields(fields, 2); for (Movie movie : this.imdb.getMovieTitleWithWords(fields[1], words.toString())) { System.out.println(movie); } } /** * Handles the lookup command query, e.g.: "LOOKUP tt0081505". * * @param ID */ private void processLookup(String ID) { System.out.println(this.imdb.findMovieByID(ID)); } /** * Handle the year-genre command query, e.g. "YEAR_AND_GENRE MOVIE 1945 Crime". * * @param type the movie type, e.g. "MOVIE", "TV_SHOW", etc. * @param year the year * @param genre the genre, e.g. "Crime", "Drama", etc. */ private void processYearAndGenre(String type, int year, String genre) { for (Movie movie : this.imdb.getMoviesByYearAndGenre(type, year, genre)) { System.out.println("\tTITLE: " + movie.getTitle() + ", TYPE: " + movie.getTitleType() + ", YEAR: " + movie.getYear() + ", GENRES: " + movie.getGenres()); } } /** * Handles the runtime command query, e.g. "RUNTIME MOVIE 237 240". * * @param type the movie type, e.g. "MOVIE", "TV_SHOW", etc. * @param start the start year (inclusive) * @param end the end year (inclusive) */ private void processRuntime(String type, int start, int end) { for (Movie movie : this.imdb.getMoviesByRuntime(type, start, end)) { System.out.println("\tTITLE: " + movie.getTitle() + ", TYPE: " + movie.getTitleType() + ", YEAR: " + movie.getYear() + ", RUNTIME: " + movie.getRuntimeMinutes()); } } /** * Handle the most-votes command query, e.g. "MOST_VOTES 10 MOVIE". * * @param num number of movies to list * @param type the movie type, e.g. "MOVIE", "TV_SHOW", etc. */ private void processMostVotes(int num, String type) { int spot = 1; for (Movie movie : this.imdb.getMoviesMostVotes(num, type)) { System.out.println("\t" + spot++ + ": " + "TITLE: " + movie.getTitle() + ", TYPE: " + movie.getTitleType() + ", YEAR: " + movie.getYear() + ", VOTES: " + movie.getRating().getNumVotes()); } } /** * Process the top command query, e.g. "TOP 10 MOVIE 1990 1995". * @param num number of top movies * @param type the movie type, e.g. "MOVIE", "TV_SHOW", etc. * @param start the start year (inclusive) * @param end the end year (inclusive) */ private void processTop(int num, String type, int start, int end) { Map<Integer, List<Movie>> movies = this.imdb.getMoviesTopRated(num, type, start, end); for (int year = start; year <= end; ++year) { System.out.println("YEAR: " + year); int spot = 1; if (movies.containsKey(year)) { for (Movie movie : movies.get(year)) { System.out.println("\t" + spot++ + ": " + "TITLE: " + movie.getTitle() + ", TYPE: " + movie.getTitleType() + ", RATING: " + movie.getRating().getRating() + ", VOTES: " + movie.getRating().getNumVotes()); } } } } /** * Handles processing of the input commands that are intended to be redirected from * a file to standard input. All commands start with the query command in question, * along with various additional fields depending on the command. */ public void mainLoop() { Scanner in = new Scanner(System.in); while (in.hasNext()) { String line = in.nextLine(); System.out.println("Processing: " + line); String[] fields = line.split("\\s+"); long start = System.currentTimeMillis(); // breakdown the query command here and pass control to the appropriate method switch (fields[0]) { case CONTAINS -> processContains(fields); case LOOKUP -> processLookup(fields[1]); case YEAR_AND_GENRE -> processYearAndGenre(fields[1], Integer.parseInt(fields[2]), fields[3]); case RUNTIME -> processRuntime(fields[1], Integer.parseInt(fields[2]), Integer.parseInt(fields[3])); case MOST_VOTES -> processMostVotes(Integer.parseInt(fields[1]), fields[2]); case TOP -> processTop(Integer.parseInt(fields[1]), fields[2], Integer.parseInt(fields[3]), Integer.parseInt(fields[4])); default -> System.out.println("Unrecognized command " + fields[0]); } System.out.println("Elapsed time (s): " + ((System.currentTimeMillis() - start) / 1000.0)); } in.close(); // <3 Jim } /** * The main method. * * @param args if a command line arg is present, we run with the small dataset, * otherwise the large. * @throws FileNotFoundException if the file cannot be found */ public static void main(String[] args) throws FileNotFoundException{ // figure out if we are going to run with the small or large dataset boolean small = false; if (args.length == 1) { small = true; } // initialize and pass control to the input command processor MovieMain movieMain = new MovieMain(small); movieMain.mainLoop(); } }
PatoSolis02/Movies
src/MovieMain.java
248,261
/****************** * Werewolf.java * Main code file for The Werewolf Game bot, based on pIRC Bot framework (www.jibble.org) * Coded by Mark Vine * All death/character/other description texts written by Darkshine * 31/5/2004 - 4/6/2004 * v0.99b *****************/ package org.jibble.pircbot.llama.werewolf; import java.io.*; import java.util.*; import org.jibble.pircbot.*; import org.jibble.pircbot.llama.werewolf.objects.*; public class Werewolf extends PircBot { Vector players, //Vector to store all the players in the game priority, //Vector to store players for the next round, one the current game is full votes, //A Vector to hold the votes of the villagers wolves, //A Vector to store the wolf/ves wolfVictim; //A Vector to hold the wolves choices (in the case there are 2 wolves taht vote differently final int JOINTIME = 60, //time (in seconds) for people to join the game (final because cannot be altered) MINPLAYERS = 4, //Minimum number of players to start a game MAXPLAYERS = 12, //Maximum number of players allowed in the game TWOWOLVES = 8, //Minimum number of players needed for 2 wolves //Final ints to describe the types of message that can be sent (Narration, game, control, notice), so //they can be coloured accordingly after being read from the file NOTICE = 1, NARRATION = 2, GAME = 3, CONTROL = 4; int dayTime = 90, //time (in seconds) for daytime duration (variable because it changes with players) nightTime = 60, //time (in seconds) for night duration voteTime = 30, //time (in seconds) for the lynch vote seer, //index of the player that has been nominated seer toSee = -1, //index of the player the seer has selected to see. If no player, this is -1 roundNo; //holds the number of the current round (for the star trek mode) int[] notVoted, //holds the count of how many times players have not voted successively wasVoted; //holds the count of how many votes one person has got. boolean connected = false, //boolean to show if the bot is connected playing = false, //boolean to show if the game is running day = false, //boolean to show whether it's day or night gameStart = false, //boolean to show if it's the start of the game (for joining) firstDay, //boolean to show if it's the first day (unique day message) firstNight, //boolean to show if it's the first night (unique night message) tieGame = true, //boolean to determine if there will be a random tie break with tied votes. timeToVote, //boolean to show whether it's currently time to vote debug, //boolean to show if debug mode is one or off (Print to log files) doBarks; //boolean to show if the bot should make random comments after long periods of inactivity boolean[] wolf, //array for checking if a player is a wolf dead, //array for checking if a player is dead voted; //array to check which players have already voted Timer gameTimer, //The game Timer (duh) idleTimer; //timer to count idle time for random comments String name, //The bot's name network, //The network to connect to gameChan, //The channel the game is played in ns, //The nickname service nick command, //The command the bot sends to the nickservice to identify on the network gameFile, //Specifies the file name to read the game texts from. role, beenwolf = "", beenseer = "", oneWolf, manyWolves; long delay; //The delay for messages to be sent public Werewolf() { this.setLogin("Werewolf"); this.setVersion("Werewolf Game Bot by LLamaBoy and Darkshine - using pIRC framework from http://www.jible.org"); this.setMessageDelay(100); String filename = "werewolf.ini", lineRead = ""; gameFile = "wolfgame.txt"; FileReader reader; BufferedReader buff; try { reader = new FileReader(filename); buff = new BufferedReader(reader); while(!lineRead.startsWith("botname")) lineRead = buff.readLine(); name = lineRead.substring(lineRead.lastIndexOf(" ") + 1, lineRead.length()); while(!lineRead.startsWith("network")) lineRead = buff.readLine(); network = lineRead.substring(lineRead.lastIndexOf(" ") + 1, lineRead.length()); while(!lineRead.startsWith("channel")) lineRead = buff.readLine(); gameChan = lineRead.substring(lineRead.lastIndexOf(" ") + 1, lineRead.length()); while(!lineRead.startsWith("nickservice")) lineRead = buff.readLine(); ns = lineRead.substring(lineRead.lastIndexOf(" ") + 1, lineRead.length()); while(!lineRead.startsWith("nickcmd")) lineRead = buff.readLine(); command = lineRead.substring(lineRead.indexOf("=") + 2, lineRead.length()); while(!lineRead.startsWith("debug")) lineRead = buff.readLine(); String onoff = lineRead.substring(lineRead.lastIndexOf(" ") + 1, lineRead.length()); if(onoff.equalsIgnoreCase("on")) debug = true; else if (onoff.equalsIgnoreCase("off")) debug = false; else { System.out.println("Unknown debug value, defaulting to on."); debug = true; } while(!lineRead.startsWith("delay")) lineRead = buff.readLine(); delay = Long.parseLong(lineRead.substring(lineRead.lastIndexOf(" ") + 1, lineRead.length())); this.setMessageDelay(delay); while(!lineRead.startsWith("daytime")) lineRead = buff.readLine(); try { int tmp = Integer.parseInt(lineRead.substring(lineRead.indexOf("=") + 2, lineRead.length())); dayTime = tmp; } catch(NumberFormatException nfx) { System.out.println("Bad day time value; defaulting to 90 seconds"); dayTime = 90; } while(!lineRead.startsWith("nighttime")) lineRead = buff.readLine(); try { int tmp = Integer.parseInt(lineRead.substring(lineRead.indexOf("=") + 2, lineRead.length())); nightTime = tmp; } catch(NumberFormatException nfx) { System.out.println("Bad night time value; defaulting to 45 seconds"); nightTime = 45; } while(!lineRead.startsWith("votetime")) lineRead = buff.readLine(); try { int tmp = Integer.parseInt(lineRead.substring(lineRead.indexOf("=") + 2, lineRead.length())); voteTime = tmp; } catch(NumberFormatException nfx) { System.out.println("Bad vote time value; defaulting to 90 seconds"); voteTime = 30; } while(!lineRead.startsWith("tie")) lineRead = buff.readLine(); onoff = lineRead.substring(lineRead.lastIndexOf(" ") + 1, lineRead.length()); if(onoff.equalsIgnoreCase("on")) tieGame = true; else if (onoff.equalsIgnoreCase("off")) tieGame = false; else { System.out.println("Unknown vote tie value, defaulting to on."); tieGame = true; } while(!lineRead.startsWith("idlebarks")) lineRead = buff.readLine(); onoff = lineRead.substring(lineRead.lastIndexOf(" ") + 1, lineRead.length()); if(onoff.equalsIgnoreCase("on")) doBarks = true; else if (onoff.equalsIgnoreCase("off")) doBarks = false; else { System.out.println("Unknown vote tie value, defaulting to off."); doBarks = true; } } catch(FileNotFoundException fnfx) { System.err.println("Initialization file " + filename + " not found."); fnfx.printStackTrace(); System.exit(1); } catch(IOException iox) { System.err.println("File read Exception"); iox.printStackTrace(); System.exit(1); } catch(Exception x) { System.err.println("Other Exception caught"); x.printStackTrace(); System.exit(1); } if(debug) { this.setVerbose(true); try { File file = new File("wolf.log"); if(!file.exists()) file.createNewFile(); PrintStream fileLog = new PrintStream(new FileOutputStream(file, true)); System.setOut(fileLog); System.out.println((new Date()).toString()); System.out.println("Starting log...."); File error = new File("error.log"); if(!file.exists()) file.createNewFile(); PrintStream errorLog = new PrintStream(new FileOutputStream(error, true)); System.setErr(errorLog); System.err.println((new Date()).toString()); System.err.println("Starting error log...."); } catch(FileNotFoundException fnfx) { fnfx.printStackTrace(); } catch(IOException iox) { iox.printStackTrace(); } } connectAndJoin(); startIdle(); } //overloaded method that calls the method with 2 player names protected String getFromFile(String text, String player, int time, int type) { return getFromFile(text, player, null, time, type); } //a couple of game string need 2 player names, so this is the ACTUAL method protected String getFromFile(String text, String player, String player2, int time, int type) { FileReader reader; BufferedReader buff; try { reader = new FileReader(gameFile); buff = new BufferedReader(reader); String lineRead = ""; while(!lineRead.equals(text)) { lineRead = buff.readLine(); } Vector texts = new Vector(1, 1); lineRead = buff.readLine(); while(!lineRead.equals("")) { texts.add(lineRead); lineRead = buff.readLine(); } buff.close(); reader.close(); int rand = (int) (Math.random() * texts.size()); String toSend = (String)texts.get(rand); if(texts.size() > 0) { switch(type) { case NOTICE: //no colour formatting toSend = toSend.replaceAll("PLAYER", player); toSend = toSend.replaceAll("PLAYR2", player2); toSend = toSend.replaceAll("TIME", "" + time); toSend = toSend.replaceAll("ISAWOLF?", role); if(wolves != null && !wolves.isEmpty()) toSend = toSend.replaceAll("WOLF", (wolves.size() == 1 ? oneWolf : manyWolves)); toSend = toSend.replaceAll("BOTNAME", this.getNick()); toSend = toSend.replaceAll("ROLE", role); //for one of the Bored texts java.text.DecimalFormat two = new java.text.DecimalFormat("00"); toSend = toSend.replaceAll("RANDDUR", ((int)(Math.random() * 2)) + " days, " + two.format((int)(Math.random() * 24)) + ":" + two.format((int)(Math.random() * 61)) + ":" + two.format((int)(Math.random() * 61))); toSend = toSend.replaceAll("RANDNUM", "" + ((int)(Math.random() * 50) + 1)); return toSend; //break; case NARRATION: //blue colour formatting toSend = toSend.replaceAll("PLAYER", Colors.DARK_BLUE + Colors.BOLD + player + Colors.NORMAL + Colors.DARK_BLUE); toSend = toSend.replaceAll("PLAYR2", Colors.DARK_BLUE + Colors.BOLD + player2 + Colors.NORMAL + Colors.DARK_BLUE); toSend = toSend.replaceAll("TIME", Colors.DARK_BLUE + Colors.BOLD + time + Colors.NORMAL + Colors.DARK_BLUE); if(wolves != null && !wolves.isEmpty()) toSend = toSend.replaceAll("WOLF", (wolves.size() == 1 ? oneWolf : manyWolves)); toSend = toSend.replaceAll("BOTNAME", this.getNick()); toSend = toSend.replaceAll("ROLE", role); return Colors.DARK_BLUE + toSend; //break; case GAME: //red colour formatting toSend = toSend.replaceAll("PLAYER", Colors.BROWN + Colors.UNDERLINE + player + Colors.NORMAL + Colors.RED); toSend = toSend.replaceAll("PLAYR2", Colors.BROWN + Colors.UNDERLINE + player2 + Colors.NORMAL + Colors.RED); toSend = toSend.replaceAll("TIME", Colors.BROWN + Colors.UNDERLINE + time + Colors.NORMAL + Colors.RED); if(wolves != null && !wolves.isEmpty()) toSend = toSend.replaceAll("WOLF", (wolves.size() == 1 ? oneWolf : manyWolves)); toSend = toSend.replaceAll("BOTNAME", this.getNick()); toSend = toSend.replaceAll("ROLE", role); return Colors.RED + toSend; //break; case CONTROL: //Green colour formatting toSend = toSend.replaceAll("PLAYER", Colors.DARK_GREEN + Colors.UNDERLINE + player + Colors.NORMAL + Colors.DARK_GREEN); toSend = toSend.replaceAll("PLAYR2", Colors.DARK_GREEN + Colors.UNDERLINE + player2 + Colors.NORMAL + Colors.DARK_GREEN); toSend = toSend.replaceAll("TIME", Colors.DARK_GREEN + Colors.UNDERLINE + time + Colors.NORMAL + Colors.DARK_GREEN); if(wolves != null && !wolves.isEmpty()) toSend = toSend.replaceAll("WOLF", (wolves.size() == 1 ? oneWolf : manyWolves)); toSend = toSend.replaceAll("BOTNAME", this.getNick()); toSend = toSend.replaceAll("ROLE", role); return Colors.DARK_GREEN + toSend; //break; default: return null; } } } catch(Exception x) { x.printStackTrace(); } return null; } protected void onPrivateMessage(String sender, String login, String hostname, String message) { if(playing) //commands only work if the game is on { if(message.toLowerCase().equalsIgnoreCase("join")) //join the game { if(gameStart) { if(isInChannel(sender)) { if(!isNameAdded(sender)) //has the player already joined? { if(players.size() < MAXPLAYERS) //if there are less than MAXPLAYERS player joined { if(players.add(sender)) //add another one { this.setMode(gameChan, "+v " + sender); this.sendMessage(gameChan, getFromFile("JOIN", sender, 0, NARRATION)); this.sendNotice(sender, getFromFile("ADDED", null, 0, NOTICE)); } else //let the user know the adding failed, so he can try again this.sendNotice(sender, "Could not add you to player list. Please try again."); } else if(priority.size() < MAXPLAYERS) //if play list is full, add to priority list { if(priority.add(sender)) this.sendNotice(sender, "Sorry, the maximum players has been reached. You have been placed in the " + "priority list for the next game."); else this.sendNotice(sender, "Could not add you to priority list. Please try again."); } else //if both lists are full, let the user know to wait for the current game to end { this.sendNotice(sender, "Sorry, both player and priority lists are full. Please wait for the " + "the current game to finish before trying again."); } } else //if they have already joined, let them know { this.sendNotice(sender, "You are already on the player list. Please wait for the next game to join again."); } } } else //if the game is already running, dont add anyone else to either list { this.sendNotice(sender, "The game is currently underway. Please wait for " + "the current game to finish before trying again."); } } else if(isNamePlaying(sender)) { if(timeToVote) //commands for when it's vote time { if(message.toLowerCase().startsWith("vote")) //vote to lynch someone { if(!hasVoted(sender)) { try { String choice = message.substring(message.indexOf(" ") + 1, message.length()); choice = choice.trim(); if(isNamePlaying(choice)) { Vote vote = new Vote(sender, choice); for(int i = 0 ; i < players.size() ; i++) { if(players.get(i) != null) { if(((String)players.get(i)).equalsIgnoreCase(choice) && !dead[i]) while(!votes.add(vote)); else if(((String)players.get(i)).equalsIgnoreCase(choice) && dead[i]) { this.sendNotice(sender, "Your choice is already dead."); return; } } } for(int i = 0 ; i < players.size() ; i++) { if(sender.equals((String)players.get(i))) if(!dead[i]) { voted[i] = true; notVoted[i] = 0; this.sendMessage(gameChan, getFromFile("HAS-VOTED", sender, choice, 0, NARRATION)); } else this.sendNotice(sender, "You are dead. You cannot vote."); } } else this.sendNotice(sender, "Your choice is not playing in the current game. Please select someone else."); } catch(Exception x) { this.sendNotice(sender, "Please vote in the correct format: /msg " + this.getName() + " vote <player>"); x.printStackTrace(); } } else this.sendNotice(sender, "You have already voted. You may not vote again until tomorrow."); } } else if(!day) //commands for the night { if(message.toLowerCase().startsWith("kill")) //only wolves can kill someone. They may change their minds if they wish to. { if(isNamePlaying(sender)) { boolean isWolf = false; for(int i = 0 ; i < wolves.size() ; i++) { if(wolves.get(i).equals(sender)) isWolf = true; } if(isWolf) { try { String victim = message.substring(message.indexOf(" ") + 1, message.length()); victim = victim.trim(); if(isNamePlaying(victim)) { int index = 0; boolean isDead = false; for(int i = 0 ; i < players.size() ; i++) { if(((String)players.get(i)).equalsIgnoreCase(victim)) if(dead[i]) isDead = true; } if(!isDead) { if(!victim.equalsIgnoreCase(sender)) { while(!wolfVictim.add(victim)); if(wolves.size() == 1) { this.sendNotice(sender, getFromFile("WOLF-CHOICE", victim, 0, NOTICE)); } else { this.sendNotice(sender, getFromFile("WOLVES-CHOICE", victim, 0, NOTICE)); for(int i = 0 ; i < wolves.size() ; i++) { if(!((String)wolves.get(i)).equals(sender)) this.sendNotice((String)wolves.get(i), getFromFile("WOLVES-CHOICE-OTHER", sender, victim, 0, NOTICE)); } } } else this.sendNotice(sender, "You cannot eat yourself!"); } else this.sendNotice(sender, "That person is already dead."); } else throw new Exception(); } catch(Exception x) { x.printStackTrace(); this.sendNotice(sender, "Please choose a valid player."); } } else this.sendNotice(sender, getFromFile("NOT-WOLF", null, 0, NOTICE)); } else { this.sendNotice(sender, "You aren't playing!"); } } if(message.toLowerCase().startsWith("see")) //only the seer may watch over someone { try { if(isNamePlaying(sender)) { if(players.get(seer).equals(sender)) { if(!dead[seer]) { String see = message.substring(message.indexOf(" ") + 1, message.length()); see = see.trim(); if(isNamePlaying(see)) { if(!sender.equals(see)) { for(int i = 0 ; i < players.size() ; i++) { if(players.get(i) != null && ((String)players.get(i)).equalsIgnoreCase(see)) toSee = i; } this.sendNotice(sender, getFromFile("WILL-SEE", (String) players.get(toSee), 0, NOTICE)); } else this.sendNotice(sender, "You already know that you are human!"); } } else this.sendNotice(sender, getFromFile("SEER-DEAD", null, 0, NOTICE)); } else this.sendNotice(sender, getFromFile("NOT-SEER", null, 0, NOTICE)); } else this.sendNotice(sender, "That person is not playing."); } catch(Exception x) { this.sendNotice(sender, "Please provide a valid player name."); x.printStackTrace(); } } if(message.toLowerCase().startsWith("protect")) //Only the GA may protect someone { //to be implemented (maybe) } } if(message.toLowerCase().equalsIgnoreCase("alive")) { String names = "The players left alive are: "; for(int i = 0 ; i < players.size() ; i++) { if(!dead[i] && players.get(i) != null) names += (String)players.get(i) + " "; } this.sendNotice(sender, names); } if(message.toLowerCase().equalsIgnoreCase("role")) { if(!gameStart) { for(int i = 0 ; i < players.size() ; i++) { if(sender.equals((String)players.get(i))) if(wolf[i]) { if(wolves.size() == 1) this.sendNotice(sender, getFromFile("W-ROLE", null, 0, NOTICE)); else { for(int j = 0 ; j < wolves.size() ; j++) { if(!sender.equals(wolves.get(j))) this.sendNotice(sender, getFromFile("WS-ROLE", (String) wolves.get(j), 0, NOTICE)); } } } else if (i == seer) this.sendNotice(sender, getFromFile("S-ROLE", null, 0, NOTICE)); else this.sendNotice(sender, getFromFile("V-ROLE", null, 0, NOTICE)); } } } } } } protected void onMessage(String channel, String sender, String login, String hostname, String message) { if(message.toLowerCase().startsWith("!quit")) { if(isSenderOp(sender)) { if(playing) doVoice(false); this.setMode(gameChan, "-mN"); this.partChannel(gameChan, "Werewolf Game Bot created by LLamaBoy." + " Texts by Darkshine. Based on the PircBot at http://www.jibble.org/"); this.sendMessage(sender, "Now quitting..."); while(this.getOutgoingQueueSize() != 0); this.quitServer(); System.out.println("Normal shutdown complete"); for(int i = 0 ; i < 4 ; i++) { System.out.println(); System.err.println(); } System.out.close(); try { Thread.sleep(1000); } catch(InterruptedException ix) { ix.printStackTrace(); } System.exit(0); } } else if(!playing) { if(message.startsWith("!startrek")) //Easter egg suggested by Deepsmeg. { gameFile = "startrek.txt"; } if(message.startsWith("!start")) //initiates a game. { startGame(sender); //Get the strings to distinguish between a single wolf and 2 wolves in the texts. oneWolf = getFromFile("1-WOLF", null, 0, NOTICE); manyWolves = getFromFile("MANY-WOLVES", null, 0, NOTICE); if(players.add(sender)) { this.setMode(gameChan, "+v " + sender); this.sendNotice(sender, getFromFile("ADDED", null, 0, NOTICE)); } else this.sendNotice(sender, "Could not add you to player list. Please try again." + " (/msg " + this.getName() + " join."); } else if(message.startsWith("!daytime ")) //alter the duration of the day { if(isSenderOp(sender)) { try { int time = (Integer.parseInt(message.substring(message.indexOf(" ") + 1, message.length()))); if(time > 0) { dayTime = time; this.sendMessage(gameChan, this.getFromFile("DAYCHANGE", null, time, CONTROL)); //"Duration of the day now set to " + Colors.DARK_GREEN + Colors.UNDERLINE + dayTime + Colors.NORMAL + " seconds"); } else throw new Exception(); } catch(Exception x) { this.sendMessage(gameChan, "Please provide a valid value for the daytime length (!daytime <TIME IN SECONDS>)"); } } } else if(message.startsWith("!nighttime ")) //alter the duration of the night { if(isSenderOp(sender)) { try { int time = (Integer.parseInt(message.substring(message.indexOf(" ") + 1, message.length()))); if(time > 0) { nightTime = time; this.sendMessage(gameChan, this.getFromFile("NIGHTCHANGE", null, time, CONTROL)); } else throw new Exception(); } catch(Exception x) { this.sendMessage(gameChan, "Please provide a valid value for the night time length (!nighttime <TIME IN SECONDS>)"); } } } else if(message.startsWith("!votetime ")) //alter the time for a vote { if(isSenderOp(sender)) { try { int time = (Integer.parseInt(message.substring(message.indexOf(" ") + 1, message.length()))); if(time > 0) { voteTime = time; this.sendMessage(gameChan, this.getFromFile("VOTECHANGE", null, time, CONTROL)); } else throw new Exception(); } catch(Exception x) { this.sendMessage(gameChan, "Please provide a valid value for the Lynch Vote time length (!votetime <TIME IN SECONDS>)"); } } } else if(message.startsWith("!tie ")) //tie option { if(isSenderOp(sender)) { try { String tie = message.substring(message.indexOf(" ") + 1, message.length()); if(tie.equalsIgnoreCase("on")) { tieGame = true; this.sendMessage(gameChan, Colors.DARK_GREEN + "Vote tie activated"); } else if(tie.equalsIgnoreCase("off")) { tieGame = false; this.sendMessage(gameChan, Colors.DARK_GREEN + "Vote tie deactivated"); } else throw new Exception(); } catch(Exception x) { this.sendMessage(gameChan, "Please provide a valid value for the vote tie condition (!tie ON/OFF)"); } } } else if(message.startsWith("!shush")) //stop idle barks { if(isSenderOp(sender)) { if(doBarks) { doBarks = false; idleTimer.cancel(); idleTimer = null; this.sendMessage(gameChan, Colors.DARK_GREEN + "I won't speak any more."); } else this.sendMessage(gameChan, Colors.DARK_GREEN + "I'm already silent. Moron."); } } else if(message.startsWith("!speak")) //enable idle barks { if(isSenderOp(sender)) { if(!doBarks) { doBarks = true; startIdle(); this.sendMessage(gameChan, Colors.DARK_GREEN + "Speakage: on."); } else this.sendMessage(gameChan, Colors.DARK_GREEN + "I'm already speaking and stuff. kthx"); } } else if(message.startsWith("!daytime")) this.sendMessage(gameChan, Colors.DARK_GREEN + "Day length is " + dayTime + " seconds."); else if(message.startsWith("!nighttime")) this.sendMessage(gameChan, Colors.DARK_GREEN + "Night length is " + nightTime + " seconds."); else if(message.startsWith("!votetime")) this.sendMessage(gameChan, Colors.DARK_GREEN + "Lynch Vote length is " + voteTime + " seconds."); else if(message.startsWith("!tie")) this.sendMessage(gameChan, Colors.DARK_GREEN + "Lynch vote tie is " + (tieGame ? "on." : "off.")); } else if(message.indexOf("it") != -1 && message.indexOf(this.getNick()) != -1 && day && message.indexOf("it") < message.indexOf(this.getNick())) //when it looks like the bot is accused, send a reply { this.sendMessage(gameChan, "Hey, screw you, " + sender + "! I didn't kill anyone!"); } else { if(playing) { if(!gameStart) { for(int i = 0 ; i < players.size() ; i++) { if(dead[i] && sender.equals(players.get(i))) this.setMode(gameChan, "-v " + sender); } } } } } protected void onAction(String sender, String login, String hostname, String target, String action) { if(playing) { if(!gameStart) { for(int i = 0 ; i < players.size() ; i++) { if(dead[i] && sender.equals(players.get(i))) this.setMode(gameChan, "-v " + sender); } } } } protected boolean isSenderOp(String nick) //to check if the sender of a message is op, necessary for some options { User users[] = this.getUsers(gameChan); for(int i = 0 ; i < users.length ; i++) { if(users[i].getNick().equals(nick)) if(users[i].isOp()) return true; else return false; } return false; } //if the player changed their nick and they're in the game, changed the listed name protected void onNickChange(String oldNick, String login, String hostname, String newNick) { if(playing) { if(isNameAdded(oldNick)) { for(int i = 0 ; i < players.size() ; i++) { if(oldNick.equals((String) players.get(i))) { String old = (String)players.set(i, newNick); if(!dead[i]) this.sendMessage(gameChan, Colors.DARK_GREEN + old + " has changed nick to " + players.get(i) + "; Player list updated."); break; } } for(int i = 0 ; i < priority.size() ; i++) { if(oldNick.equals((String) priority.get(i))) { players.set(i, newNick); this.sendMessage(gameChan, Colors.DARK_GREEN + newNick + " has changed nick; Priority list updated."); break; } } //This doesn't seem to work at times... if(timeToVote) //if the player changes nick during the vote period, update any votes against him { for(int i = 0 ; i < votes.size() ; i++) { if(((String)((Vote)votes.get(i)).getVote()).equalsIgnoreCase(oldNick)) { Vote newVote = new Vote((String)votes.get(i), newNick); votes.set(i, newVote); } } } } } } //if a player leaves while te game is one, remove him from the player list //and if there is a priority list, add the first person from that in his place. protected void onPart(String channel, String sender, String login, String hostname) { if(playing) { if(!priority.isEmpty()) { String newPlayer = (String) priority.get(0); String role = ""; priority.remove(0); for(int i = 0 ; i < players.size() ; i++) { if(sender.equals((String)players.get(i)) && !dead[i]) { if(i == seer) role = getFromFile("ROLE-SEER", null, 0, NOTICE); else if(wolf[i]) role = getFromFile("ROLE-WOLF", null, 0, NOTICE); else role = getFromFile("ROLE-VILLAGER", null, 0, NOTICE); players.set(i, newPlayer); this.sendNotice(newPlayer, getFromFile("FLEE-PRIORITY-NOTICE", sender, 0, NOTICE)); this.sendMessage(gameChan, getFromFile("FLEE-PRIORITY-NOTICE", sender, newPlayer, 0, CONTROL)); if(day || timeToVote) this.setMode(gameChan, "+v " + newPlayer); if(i == seer) this.sendNotice(newPlayer, getFromFile("S-ROLE", null, 0, NOTICE)); else if(wolf[i]) if(wolves.size() == 1) this.sendNotice(newPlayer, getFromFile("W-ROLE", null, 0, NOTICE)); else this.sendNotice(newPlayer, getFromFile("WS-ROLE", null, 0, NOTICE)); else this.sendNotice(newPlayer, getFromFile("V-ROLE", null, 0, NOTICE)); break; } } } else if(!gameStart) { int index = -1; for(int i = 0 ; i < players.size() ; i++) { if(sender.equals((String)players.get(i))) { index = i; players.set(i, null); if(!dead[i]) { if(wolf[i]) { for(int j = 0 ; j < wolves.size() ; j++) { if(((String)wolves.get(j)).equals(sender)) wolves.remove(j); } this.sendMessage(gameChan, getFromFile("FLEE-WOLF", sender, 0, NARRATION)); } else this.sendMessage(gameChan, getFromFile("FLEE-VILLAGER", sender, 0, NARRATION)); dead[i] = true; if(wolfVictim != null) { for(int j = 0 ; j < wolfVictim.size() ; j++) { if(sender.equals(wolfVictim.get(j))) wolfVictim.set(j, null); } } checkWin(); } } } if(timeToVote) { for(int i = 0 ; i < votes.size() ; i++) { if(((String)((Vote)votes.get(i)).getVote()).equalsIgnoreCase(sender)) votes.remove(i); //if the player leaves, no votes for him } } } else if(gameStart) { for(int i = 0 ; i < players.size() ; i++) { if(sender.equals(players.get(i))) { players.remove(i); this.sendMessage(gameChan, getFromFile("FLEE", sender, 0, NARRATION)); break; } } } } else { if(priority == null || priority.isEmpty()); else { for(int i = 0 ; i < priority.size() ; i++) { if(sender.equals((String)priority.get(i))) { priority.remove(i); this.sendMessage(gameChan, Colors.DARK_GREEN + Colors.UNDERLINE + sender + Colors.NORMAL + Colors.DARK_GREEN + ", a player on the priority list, has left. Removing from list..."); } } } } } protected void onTopic(String channel, String topic, String setBy, long date, boolean changed) { if(playing) { this.sendMessage(gameChan, "Hey! Can't you see we're trying to play a game here? >:("); } } protected void onQuit(String sourceNick, String sourceLogin, String sourceHostname, String reason) { this.onPart(gameChan, sourceNick, sourceLogin, sourceHostname); } protected void onDisconnect() { connected = false; connectAndJoin(); } protected void connectAndJoin() { while(!connected) //keep trying until successfully connected { try { this.setName(name); this.connect(network); Thread.sleep(1000); //allow it some time before identifiying if(!ns.equalsIgnoreCase("none")) { this.sendMessage(ns, command); //identify with nickname service Thread.sleep(2000); //allow the ident to go through before joining } this.joinChannel(gameChan); this.setMode(gameChan, "-mN"); connected = true; } catch(IOException iox) { System.err.println("Could not connect/IO"); } catch(NickAlreadyInUseException niux) { System.err.println("Nickname is already in use. Choose another nick"); System.exit(1); } catch(IrcException ircx) { System.err.println("Could not connect/IRC"); } catch(InterruptedException iex) { System.err.println("Could not connect/Thread"); } } } protected void startIdle() { if(doBarks) { idleTimer = new Timer(); //trigger a chat every 60-240 mins idleTimer.schedule(new WereTask(), ((int)(Math.random() * 7200) + 3600) * 1000); } } protected void onKick(String channel, String kickerNick, String kickerLogin, String kickerHostname, String recipientNick, String reason) { if(recipientNick.equals(this.getName())) this.joinChannel(channel); else this.onPart(gameChan, recipientNick, null, null); } protected void onJoin(String channel, String sender, String login, String hostname) { if(!sender.equals(this.getNick())) { if(gameStart) this.sendNotice(sender, getFromFile("GAME-STARTED", null, 0, NOTICE)); else if(playing) this.sendNotice(sender, getFromFile("GAME-PLAYING", null, 0, NOTICE)); } } protected void startGame(String sender) { if(doBarks) idleTimer.cancel(); //don't make comments while the game's on. this.setMode(gameChan, "+mN"); roundNo = 0; if(priority == null || priority.isEmpty()) players = new Vector(MINPLAYERS, 1); else { players = new Vector(MINPLAYERS, 1); this.sendMessage(gameChan, Colors.DARK_GREEN + ""); for(int i = 0 ; i < priority.size() ; i++) { if(sender.equals((String)priority.get(i))) priority.remove(i); else { if(players.add((String)priority.get(i))) { this.setMode(gameChan, "+v " + (String)priority.get(i)); this.sendMessage(gameChan, getFromFile("JOIN", sender, 0, NARRATION)); } else this.sendNotice(gameChan, "Sorry, you could not be added. Please try again."); } } } priority = new Vector(1, 1); wolves = new Vector(1, 1); playing = true; day = false; timeToVote = false; gameStart = true; firstDay = true; firstNight = true; toSee = -1; this.sendMessage(gameChan, getFromFile("STARTGAME", sender, JOINTIME, NARRATION)); this.sendNotice(gameChan, getFromFile("STARTGAME-NOTICE", sender, 0, NOTICE)); while(this.getOutgoingQueueSize() != 0); gameTimer = new Timer(); gameTimer.schedule(new WereTask(), JOINTIME * 1000); } protected void playGame() { String nicks = "", modes = ""; int count = 0; if(playing) { if(timeToVote) { for(int i = 0 ; i < players.size() ; i++) { if(!dead[i]) { if(notVoted[i] == 2) { dead[i] = true; this.sendMessage(gameChan, getFromFile("NOT-VOTED", (String)players.get(i), 0, NARRATION)); this.sendNotice((String) players.get(i), getFromFile("NOT-VOTED-NOTICE", null, 0, NOTICE)); this.setMode(gameChan, "-v " + players.get(i)); } } } if(checkWin()) return; this.sendMessage(gameChan, getFromFile("VOTETIME", null, voteTime, GAME)); while(this.getOutgoingQueueSize() != 0); gameTimer.schedule(new WereTask(), voteTime * 1000); } else if(day) { if(toSee != -1) if(!dead[seer] && !dead[toSee]) { if(wolf[toSee]) role = getFromFile("ROLE-WOLF", null, 0, NOTICE); else role = getFromFile("ROLE-VILLAGER", null, 0, NOTICE); this.sendNotice((String)players.get(seer), getFromFile("SEER-SEE", (String) players.get(toSee),toSee, NOTICE)); } else if(dead[seer]) this.sendNotice((String)players.get(seer), getFromFile("SEER-SEE-KILLED", (String) players.get(toSee), 0, NOTICE)); else this.sendNotice((String)players.get(seer), getFromFile("SEER-SEE-TARGET-KILLED", (String) players.get(toSee), 0, NOTICE)); doVoice(true); this.sendMessage(gameChan, getFromFile("DAYTIME", null, dayTime, GAME)); while(this.getOutgoingQueueSize() != 0); gameTimer.schedule(new WereTask(), dayTime * 1000); } else if(!day) { doVoice(false); if(firstNight) { firstNight = false; this.sendMessage(gameChan, getFromFile("FIRSTNIGHT", null, 0, NARRATION)); } else this.sendMessage(gameChan, Colors.DARK_BLUE + getFromFile("NIGHTTIME", null, 0, NARRATION)); if(wolves.size() == 1) this.sendMessage(gameChan, getFromFile("WOLF-INSTRUCTIONS", null, nightTime, GAME)); else this.sendMessage(gameChan, getFromFile("WOLVES-INSTRUCTIONS", null, nightTime, GAME)); if(!dead[seer]) this.sendMessage(gameChan, getFromFile("SEER-INSTRUCTIONS", null, nightTime, GAME)); while(this.getOutgoingQueueSize() != 0); gameTimer.schedule(new WereTask(), nightTime * 1000); } } } //method to batch voice/devoice all the users on the playerlist. protected void doVoice(boolean on) { String nicks = "", modes = ""; int count = 0; if(on) modes = "+"; else modes = "-"; for(int i = 0 ; i < players.size() ; i++) { try { if(!dead[i] && players.get(i) != null) { nicks += players.get(i) + " "; modes += "v"; count++; if(count % 4 == 0) { this.setMode(gameChan, modes + " " + nicks); nicks = ""; if(on) modes = "+"; else modes = "-"; count = 0; } } } catch(NullPointerException npx) { System.out.println("Could not devoice, no dead array"); } } this.setMode(gameChan, modes + " " + nicks); //mode the stragglers that dont make a full 4 } //check if the name who tries to join is IN THE DAMN CHANNEL AT THE TIME (fuck you false) protected boolean isInChannel(String name) { User[] users = this.getUsers(gameChan); for(int i = 0 ; i < users.length ; i++) { if(users[i].getNick().equals(name)) return true; } return false; } //method to go through the player and priority lists, to check if the player has already joined the game protected boolean isNameAdded(String name) { for(int i = 0 ; i < players.size() ; i++) { if(name.equals((String) players.get(i))) return true; } for(int i = 0 ; i < priority.size() ; i++) { if(name.equals((String) players.get(i))) return true; } return false; } //go through the player list, check the player is in the current game protected boolean isNamePlaying(String name) { for(int i = 0 ; i < players.size() ; i++) { if(players.get(i) != null && name.equalsIgnoreCase((String) players.get(i))) return true; } return false; } protected boolean hasVoted(String name) { for(int i = 0 ; i < players.size() ; i++) { if(name.equals((String) players.get(i))) if(voted[i]) return true; else return false; } return false; } protected void tallyVotes() { this.sendMessage(gameChan, getFromFile("TALLY", null, 0, CONTROL)); for(int i = 0 ; i < players.size() ; i++) { if(players.get(i) != null) { if(voted[i]) { Vote thisVote = null; for(int k = 0 ; k < votes.size() ; k++) { if(((String)players.get(i)).equals(((Vote)votes.get(k)).getName())) { thisVote = (Vote)votes.get(k); break; } } for(int j = 0 ; j < players.size() ; j++) { if(players.get(j) != null && thisVote.getVote() != null) if(thisVote.getVote().equalsIgnoreCase((String)players.get(j))) wasVoted[j]++; } } else if(!dead[i]) { notVoted[i]++; } } } int majority = 0, //holds the majority vote guilty = -1; //holds the index of the person with the majority Vector majIndexes = new Vector(1, 1); //Vector which holds the indexes of all those with a majority for(int i = 0 ; i < wasVoted.length ; i++) //loop once to find the majority { if(wasVoted[i] > majority) majority = wasVoted[i]; } for(int i = 0 ; i < wasVoted.length ; i++) //loop again to count how many have a majority (tie case) { if(wasVoted[i] == majority) majIndexes.add(new Integer(i)); } if(majIndexes.size() == 1) //only one with majority guilty = Integer.parseInt(((Integer)majIndexes.get(0)).toString()); else if(tieGame && (majIndexes != null && majIndexes.size() != 0)) { int rand = (int) (Math.random() * majIndexes.size()); if (wasVoted[((Integer)majIndexes.get(rand)).intValue()] == 0) //if the majority was 0, no-one voted guilty = -1; else { guilty = ((Integer)majIndexes.get(rand)).intValue(); this.sendMessage(gameChan, getFromFile("TIE", null, 0, CONTROL)); } } else guilty = -10; if(guilty == -10) { this.sendMessage(gameChan, Colors.DARK_BLUE + getFromFile("NO-LYNCH", null, 0, NARRATION)); } else if(guilty != -1) { String guiltyStr = (String) players.get(guilty); dead[guilty] = true; if(guiltyStr == null) //if the guilty person is null, he left during the lynch vote. { this.sendMessage(gameChan, getFromFile("LYNCH-LEFT", null, 0, CONTROL)); return; } if(guilty == seer) { this.sendMessage(gameChan, getFromFile("SEER-LYNCH", guiltyStr, 0, NARRATION)); role = getFromFile("ROLE-SEER", null, 0, NARRATION); } else if(wolf[guilty]) { if(wolves.size() != 1) { for(int i = 0 ; i < wolves.size() ; i++) { if(guiltyStr.equals((String)wolves.get(i))) wolves.remove(i); } } this.sendMessage(gameChan, getFromFile("WOLF-LYNCH", guiltyStr, 0, NARRATION)); role = getFromFile("ROLE-WOLF", null, 0, NARRATION); } else { this.sendMessage(gameChan, getFromFile("VILLAGER-LYNCH", guiltyStr, 0, NARRATION)); role = getFromFile("ROLE-VILLAGER", null, 0, NARRATION); } this.sendMessage(gameChan, getFromFile("IS-LYNCHED", guiltyStr, 0, NARRATION)); if(guilty != seer && guilty > -1 && !wolf[guilty]) this.sendNotice(guiltyStr, getFromFile("DYING-BREATH", null, 0, NOTICE)); else this.setMode(gameChan, "-v " + guiltyStr); } else //if guilty == -1 { this.sendMessage(gameChan, getFromFile("NO-VOTES", null, 0, NARRATION)); } } protected void wolfKill() { String victim = ""; if(wolfVictim.isEmpty()) { this.sendMessage(gameChan, getFromFile("NO-KILL", null, 0, NARRATION)); return; } else if(wolfVictim.size() == 1) victim = (String) wolfVictim.get(0); else { if(wolfVictim.get(0).equals(wolfVictim.get(1))) victim = (String) wolfVictim.get(0); else { int randChoice = (int) (Math.random() * wolfVictim.size()); victim = (String) wolfVictim.get(randChoice); } } for(int i = 0 ; i < players.size() ; i++) { if(players.get(i) != null && ((String)players.get(i)).equalsIgnoreCase(victim)) { if(players.get(i) != null) { String deadName = (String) players.get(i); //use the name from the game list for case accuracy dead[i] = true; //make the player dead if(i == seer) { this.sendMessage(gameChan, getFromFile("SEER-KILL", deadName, 0, NARRATION)); role = getFromFile("ROLE-SEER", null, 0, NOTICE); } else { this.sendMessage(gameChan, getFromFile("VILLAGER-KILL", deadName, 0, NARRATION)); role = getFromFile("ROLE-VILLAGER", null, 0, NOTICE); } this.sendMessage(gameChan, Colors.DARK_BLUE + getFromFile("IS-KILLED", deadName, 0, NARRATION)); this.setMode(gameChan, "-v " + victim); } else { for(int j = 0 ; j < wolves.size() ; j++) { this.sendNotice((String)wolves.get(j), "The person you selected has left the game"); } } } } } protected void setRoles() { if(players.size() < MINPLAYERS) { //Not enough players this.setMode(gameChan, "-mN"); doVoice(false); this.sendMessage(gameChan, getFromFile("NOT-ENOUGH", null, 0, CONTROL)); playing = false; gameFile = "wolfgame.txt"; //reset the game file startIdle(); return; } else { int randWolf = (int) (Math.random() * players.size()); wolves.add(players.get(randWolf)); wolf[randWolf] = true; if(players.size() < TWOWOLVES) //if there are lese than TWOWOLVES players, only one wolf this.sendNotice((String)players.get(randWolf), getFromFile("WOLF-ROLE", (String)players.get(randWolf), 0, NOTICE)); else //otherwise, 2 wolves, and they know each other { boolean isWolf = true; while(isWolf) //to make sure the random number isnt the same again. { randWolf = (int) (Math.random() * players.size()); if(!wolf[randWolf]) isWolf = false; } wolves.add(players.get(randWolf)); wolf[randWolf] = true; //pm both wolves and let them know who the other is //a bit ugly, but it does the job for(int i = 0 ; i < wolves.size() ; i++) this.sendNotice((String)wolves.get(i), getFromFile("WOLVES-ROLE", (String)(i == 0 ? wolves.get(1) : wolves.get(0)), 0, NOTICE)); this.sendMessage(gameChan, getFromFile("TWOWOLVES", null, 0, CONTROL)); } } //Find a seer. He cannot be a wolf, obviously. boolean isWolf = true; while(isWolf) { seer = (int) (Math.random() * players.size()); if(!wolf[seer]) isWolf = false; } this.sendNotice((String)players.get(seer), getFromFile("SEER-ROLE", (String)players.get(seer), 0, NOTICE)); for(int i = 0 ; i < players.size() ; i++) //tell anyone that isnt a wolf that they are human { try { if(i%2 == 0) Thread.sleep(300); } catch(Exception x) { x.printStackTrace(); } if(!wolf[i] && i != seer) this.sendNotice((String)players.get(i), getFromFile("VILLAGER-ROLE", (String)players.get(i), 0, NOTICE)); } } protected boolean checkWin() { int humanCount = 0, //count how many humans are left wolfCount = 0; //count how many wolves are left for(int i = 0 ; i < players.size() ; i++) { if(!wolf[i] && !dead[i] && players.get(i) != null) humanCount++; else if(wolf[i] && !dead[i]) wolfCount++; } if(wolfCount == 0) //humans win { playing = false; this.sendMessage(gameChan, getFromFile("VILLAGERS-WIN", null, 0, NARRATION)); this.sendMessage(gameChan, getFromFile("CONGR-VILL", null, 0 , NARRATION)); doVoice(false); this.setMode(gameChan, "-mN"); day = false; for(int i = 0 ; i < players.size() ; i++) dead[i] = false; gameTimer.cancel(); //stop the game timer, since someone won. gameTimer = null; //reset the game file to default gameFile = "wolfgame.txt"; //start the idling again startIdle(); return true; } else if(wolfCount == humanCount) //wolves win { playing = false; if(players.size() < TWOWOLVES) { String wolfPlayer = ""; for(int i = 0 ; i < players.size() ; i++) { if(wolf[i]) wolfPlayer = (String) players.get(i); } this.sendMessage(gameChan, getFromFile("WOLF-WIN", wolfPlayer, 0, NARRATION)); this.sendMessage(gameChan, getFromFile("CONGR-WOLF", wolfPlayer, 0 , NARRATION)); } else { String theWolves = getFromFile("WOLVES-WERE", null, 0, CONTROL); for(int i = 0 ; i < wolves.size() ; i++) { if(wolves.get(i) != null) theWolves += (String) wolves.get(i) + " "; } this.sendMessage(gameChan, Colors.DARK_BLUE + getFromFile("WOLVES-WIN", null, 0, NARRATION)); this.sendMessage(gameChan, getFromFile("CONGR-WOLVES", null, 0 , NARRATION)); this.sendMessage(gameChan, theWolves); } doVoice(false); this.setMode(gameChan, "-mN"); for(int i = 0 ; i < players.size() ; i++) dead[i] = false; day = false; gameTimer.cancel(); //stop the game timer, since someone won. gameTimer = null; //reset the game file to default gameFile = "wolfgame.txt"; //start the idling again startIdle(); return true; } else //No-one wins return false; } public static void main(String args[]) { new Werewolf(); } private class WereTask extends TimerTask { public void run() { if(playing) { if(gameStart) //the start of the game { gameStart = false; //stop the joining wolfVictim = new Vector(1, 1); votes = new Vector(1, 1); voted = new boolean[players.size()]; wolf = new boolean[players.size()]; dead = new boolean[players.size()]; notVoted = new int[players.size()]; wasVoted = new int[players.size()]; for(int i = 0 ; i < players.size() ; i++) { voted[i] = false; //initiate if people have voted to false wolf[i] = false; //set up the wolf array. Noone is a wolf at first. dead[i] = false; //set up the dead array. Noone is dead at first. notVoted[i] = 0; //set up the not voted count. There are no non voters at first. wasVoted[i] = 0; //set up the vote count. Nobody has any votes at first. } Werewolf.this.sendMessage(gameChan, Colors.DARK_GREEN + "Joining ends."); Werewolf.this.setRoles(); //once everything is set up, start the game proper playGame(); } else if(day) //the day ends { day = !day; timeToVote = true; playGame(); } else if(timeToVote) //voting time begins { timeToVote = false; tallyVotes(); votes = new Vector(1, 1); for(int i = 0 ; i < voted.length ; i++) { voted[i] = false; } for(int i = 0 ; i < wasVoted.length ; i++) { wasVoted[i] = 0; } toSee = -1; checkWin(); playGame(); } else if(!day) //the night ends { wolfKill(); wolfVictim = new Vector(1, 1); day = !day; checkWin(); playGame(); } } else { User[] users = Werewolf.this.getUsers(gameChan); String rand; do { rand = users[((int)(Math.random() * users.length))].getNick(); } while(rand.equals(Werewolf.this.getNick())); String msg = Werewolf.this.getFromFile("BORED", rand, 0, Werewolf.this.NOTICE); if(msg != null) Werewolf.this.sendMessage(gameChan, msg); Werewolf.this.startIdle(); } } } }
mojeda/Werewolf
src/Werewolf.java
248,264
package ueb08; /** * Enthält die Abstimmungszahlen und Kandidateninformationen aus einer Beispielwahl. * Es muss sichergestellt sein, dass die erhobenen Werte nicht während der * Laufzeit geändert werden können. */ public class Data { /** * Der Index in diesem Array entspricht der ID eines bestimmten Kandidaten. * Wenn also von "Kandidaten ID" die Rede ist, bezeichnet dies eine Zahl, * die ein valider Index dieses Arrays sein muss. */ private static final String[] CANDIDATES = { "E. Herms", "A. Gebäudchen", "G. Kayak", "E. Cola", "M. Riema", }; /** * Wahlen werden in drei Dimensionen gespeichert. * Die erste Dimension unterscheidet zwischen mehreren Wahlen. * Die zweite Dimension beschreibt einen Wähler. * Jeder Wähler kann mehrfach eine Stimme abgegeben haben, der erstgenannte * Kandidat ist hierbei die Erstwahl. * * Der Zugriff auf votes[0][0][0] liefert den bevorzugten Kandidaten * des ersten Wählers in der ersten Wahl. votes[0][0][1] würde die Zweitwahl * des ersten Wählers in der ersten Wahl liefern. * * Die vorhandenen Daten werden im Folgenden aufgeführt: */ // VOTES[1][2][1] = private static final int[][][] VOTES = { { // 0) Niemand hat gewählt. }, { // 1) Jeder hat nur eine Stimme für Kandidat 0 abgegeben. {0}, {0}, {0} }, { // 2) Jeder hat nur eine Stimme für Kandidat 3 abgegeben. {3}, {3}, {3} }, { // 3) Nahezu jeder hat seine erste Stimme für Kandidat 0 // und die zweite für Kandidat 1 abgegeben. {0, 1}, {0, 1}, {0, 1}, {1}, {0} }, { // 4) Die Stimmen sind initial aufgeteilt zwischen Kandidat 3 und 4, // aber die Personen, die für Kandidat 2 gestimmt haben, bevorzugen 4. // // Dies ist die erste Wahl in der unterschiedliche // Auswertungsvarianten zu unterschiedlichen Ergebnissen führen. {3}, {3}, {3}, {3}, {3}, {4}, {4}, {4}, {4}, {4}, {2, 4}, {2, 4} }, { // 5) Jeder möchte Kandidat 1 in der Zweitwahl, die Erstwahlen // sind aber über alle Kandidaten verteilt. {0, 1}, {2, 1}, {3, 1}, {4, 1}, {2, 1}, {3, 1}, {4, 1}, {3, 1}, {4, 1}, {4, 1}, }, { // 6) Wenige Wähler bevorzugen Kandidat 0 und nur ihn. // Keiner der Wähler mit mehr Stimmabgaben hat Kandidat 0 gewählt. {0}, {0}, {0}, {0}, {0}, {0}, {0}, {2, 4, 1, 3}, {3, 2, 1, 4}, {2, 3, 1, 4}, {1, 4, 3, 2}, {1, 2, 3, 4}, {4, 2, 3, 1}, {4, 1, 3, 2}, {2, 4, 1, 3}, {3, 2, 1, 4}, {2, 3, 1, 4}, {1, 4, 3, 2}, {1, 2, 3, 4}, {4, 2, 3, 1}, {4, 1, 3, 2}, {2, 4, 1, 3}, {3, 2, 1, 4}, {2, 3, 1, 4}, {1, 4, 3, 2}, {1, 2, 3, 4}, {4, 2, 3, 1}, {4, 1, 3, 2}, } }; /** * @return Die Anzahl der Kandidaten in diesem Datensatz. * @todo implementieren */ public static int getNumberOfCandidates() { return CANDIDATES.length; } /** * @return Die Anzahl der Wahlen in diesem Datensatz. * @todo implementieren */ public static int getNumberOfElections() { return VOTES.length; } /** * @param candidateId Die betreffende KandidatenID. * @return True, wenn getCandidateNameById() mit dieser ID arbeiten kann. * @todo implementieren */ public static boolean isValidCandidateId(int candidateId) { return getNumberOfCandidates() > candidateId && candidateId >= 0; } /** * @param electionId Die betreffende ID. * @return True, wenn getVotes() mit dieser ID arbeiten kann. * @todo implementieren */ public static boolean isValidElectionId(int electionId) { return getNumberOfElections() > electionId && electionId >= 0; } /** * Liefert den Namen des zu der ID gehörigen Kandidaten. Wenn der * korrespondierende Kandidat nicht existiert, wird null zurückgegeben. * * @param candidateId Die ID des Kandidaten. * @return Der Name des Kandidaten oder null, wenn der Kandidat nicht existiert. * @todo implementieren */ public static String getCandidateNameById(int candidateId) { return isValidCandidateId(candidateId) ? CANDIDATES[candidateId] : null; //if(isValidCandidateId(candidateId)) //{ // return CANDIDATES[candidateId]; //} //return null; } /** * Liefert alle Wählerstimmen, die zu einer Wahl mit der gegebenen ID gehören. * Wenn zu der ID keine Wahl existiert, wird ein leeres Array zurückgegeben. * Das resultierende Array muss eine <b>tiefe Kopie</b> der Stimmen sein, * so dass eine Änderung der Werte außerhalb keinen Einfluss auf die Werte * dieses Datensatzes hat. * * @param electionId Die ID der Wahl. * @return Eine Kopie aller Stimmen der Wahl oder null, wenn die * zugehörige Wahl nicht existiert. * * @todo implementieren */ public static int[][] getVotes(int electionId) { if(isValidElectionId(electionId)) { int[][] originalVotes = VOTES[electionId]; int[][] copiedVotes = new int[originalVotes.length][]; for(int i = 0; i < originalVotes.length; i++) { copiedVotes[i] = new int[originalVotes[i].length]; for(int j = 0; j < originalVotes[i].length; j++) { copiedVotes[i][j] = originalVotes[i][j]; //sollen doch mit clone arbeiten } } return copiedVotes; } return null; } }
emileMbeke0820/gdp-2020-emile
src/ueb08/Data.java
248,265
import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.plaf.basic.BasicInternalFrameTitlePane.MaximizeAction; import net.sf.stackwrap4j.StackOverflow; import net.sf.stackwrap4j.StackWrapper; import net.sf.stackwrap4j.datastructures.AnswerAutoFetchList; import net.sf.stackwrap4j.entities.Answer; import net.sf.stackwrap4j.entities.Question; import net.sf.stackwrap4j.entities.User; import net.sf.stackwrap4j.exceptions.ParameterNotSetException; import net.sf.stackwrap4j.http.HttpClient; import net.sf.stackwrap4j.json.JSONException; import net.sf.stackwrap4j.query.AnswerQuery; import net.sf.stackwrap4j.query.QuestionQuery; public class Main { public static void main(String[] args) throws JSONException, IOException, ParameterNotSetException { Proxy prox = new Proxy(Proxy.Type.HTTP, new InetSocketAddress( "webproxy.int.westgroup.com", 80)); HttpClient.proxyServer = prox; StackWrapper sw = new StackOverflow("RhtZB9-r0EKYJi-OjKSRUg"); testAutoFetchList(sw); } private static void testAutoFetchList(StackWrapper sw) { List<Answer> answers = new AnswerAutoFetchList(sw, (AnswerQuery) new AnswerQuery().setIds(4)); for (Answer a: answers){ System.out.println(a.getQuestionId()); } } /** * Finds the average answers posted per day since the first answer * * @return answers per day * @throws ParameterNotSetException * @throws JSONException * @throws IOException */ public static double getAnswersPerDay(StackWrapper sw, int userId) throws IOException, JSONException, ParameterNotSetException { long firstAnswer = Long.MAX_VALUE; long lastAnswer = Long.MIN_VALUE; int answerCount = 0; List<Answer> answers = Util.getAllAnswers(userId, sw); answerCount += answers.size(); for (Answer a : answers) { if (a.getCreationDate() < firstAnswer) firstAnswer = a.getCreationDate(); if (a.getCreationDate() > lastAnswer) lastAnswer = a.getCreationDate(); } long answerRange = lastAnswer - firstAnswer; double days = answerRange / 60 / 60 / (double) 24; return answerCount / days; } public static double getAverageAnswerScore(StackWrapper sw, int userId) throws JSONException, IOException, ParameterNotSetException { int voteSum = 0; int answerCount = 0; List<Answer> answers = Util.getAllAnswers(userId, sw); for (Answer a : answers) { answerCount++; voteSum += a.getScore(); } return voteSum / (double) answerCount; } public static double getAcceptedAnswerPercentage(StackWrapper sw, int userId) throws JSONException, IOException, ParameterNotSetException { int acceptedCount = 0; int answerCount = 0; List<Answer> answers = Util.getAllAnswers(userId, sw); for (Answer a : answers) { answerCount++; if (a.isIsAccepted()) acceptedCount++; } return acceptedCount / (double) answerCount; } public static List<StatsEntry> replicateStatsPage(String tag, StackWrapper sw) throws IOException, JSONException, ParameterNotSetException { long _30Days = 60L * 60L * 24L * 30L; long currentSeconds = System.currentTimeMillis() / 1000L; long seconds30DaysAgo = currentSeconds - _30Days; int page = 1; QuestionQuery qQuery = (QuestionQuery) new QuestionQuery() .setPage(page).setPageSize(Util.MAX_PAGE_SIZE).setFromDate( seconds30DaysAgo).setToDate(currentSeconds).setTags( "java"); List<Question> allQuestionsTagged = new ArrayList<Question>(); while (true) { System.out.println("Retrieving page " + page); List<Question> newQ = sw.listQuestions(qQuery); allQuestionsTagged.addAll(newQ); if (allQuestionsTagged.size() < Util.MAX_PAGE_SIZE) break; qQuery.setPage(++page); } System.out.println(allQuestionsTagged.size()); List<Answer> allAnswersTagged = new ArrayList<Answer>(); page = 1; for (Question q : allQuestionsTagged) allAnswersTagged.addAll(q.getAnswers()); Map<Integer, StatsEntry> allUsers = new HashMap<Integer, StatsEntry>(); for (Answer a : allAnswersTagged) { if (a.isCommunityOwned()) continue; StatsEntry s = allUsers.get(a.getOwnerId()); if (s == null) { s = new StatsEntry(a.getOwnerId()); allUsers.put(s.uId, s); } s.addAnswer(a.getScore()); } List<StatsEntry> ret = new ArrayList<StatsEntry>(); ret.addAll(allUsers.values()); Collections.sort(ret); return ret; } public static class StatsEntry implements Comparable<StatsEntry> { private int uId; private int votes; private int answers; public StatsEntry(int uId) { this.uId = uId; votes = 0; answers = 0; } public void addAnswer(int score) { answers++; votes += score; } @Override public int compareTo(StatsEntry arg0) { return this.votes - arg0.votes; } @Override public String toString() { return "" + uId + " " + votes + " " + answers; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + answers; result = prime * result + uId; result = prime * result + votes; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StatsEntry other = (StatsEntry) obj; if (answers != other.answers) return false; if (uId != other.uId) return false; if (votes != other.votes) return false; return true; } } }
jjnguy/PublicFun
EQL/src/Main.java
248,266
import java.util.*; public class CatsVDogs { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int testCases = sc.nextInt(); while (testCases > 0) { int cats = sc.nextInt(); int dogs = sc.nextInt(); int viewers = sc.nextInt(); List<Bucket> buckets = new ArrayList<>(); buckets.add(new Bucket()); while (viewers > 0) { String[] vote = new String[2]; vote[0] = sc.next(); vote[1] = sc.next(); boolean added = false; for (Bucket bucket : buckets) { if (bucket.isCompatible(vote)) { bucket.addVote(vote); added = true; } } if (!added) { Bucket newBucket = new Bucket(); newBucket.addVote(vote); for (Bucket bucket : buckets) { newBucket.fillCompatibleFromOtherBucket(bucket); } buckets.add(newBucket); } viewers--; } int result = buckets.stream() .mapToInt(b -> b.count) .max() .getAsInt(); System.out.println("" + result); testCases--; } } static class Bucket { Set<String> keepers; Set<String> dumpers; Set<String[]> votes; int count; Bucket() { keepers = new HashSet<>(); dumpers = new HashSet<>(); votes = new HashSet<>(); count = 0; } boolean isCompatible(String[] vote) { return !dumpers.contains(vote[0]) && !keepers.contains(vote[1]); } void fillCompatibleFromOtherBucket(Bucket bucket) { for (String[] vote : bucket.votes) { if (isCompatible(vote)) { addVote(vote); } } } void addVote(String[] vote) { keepers.add(vote[0]); dumpers.add(vote[1]); votes.add(vote); count++; } } }
Geeroar/catsvsdogs
CatsVDogs.java
248,270
import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class voteScreen { int numberOfTeamMembers = 4; //methods public void initialize(){ JFrame frame = new JFrame("Vote"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(840, 525)); frame.setLocation(300 , 200); Box allBox = Box.createVerticalBox(); Box missionMembersBox = Box.createHorizontalBox(); Box buttonBox = Box.createHorizontalBox(); int[] missionPlayerNumbers = new int[numberOfTeamMembers]; missionPlayerNumbers[0] = 1; missionPlayerNumbers[1] = 2; missionPlayerNumbers[2] = 3; missionPlayerNumbers[3] = 4; String missionPlayerNums = ""; for(int i = 0; i < numberOfTeamMembers; i++) { missionPlayerNums += missionPlayerNumbers[i] + ", "; } JLabel missionMembers = new JLabel("Players going on mission: " + missionPlayerNums); missionMembersBox.add(missionMembers); JButton voteUp = new JButton(" Vote UP "); voteUp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //save vote results frame.dispose(); //check for mission pass => open up missionScreen for teamMembers } }); buttonBox.add(voteUp); JButton voteDown = new JButton("Vote DOWN"); voteDown.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //save vote results frame.dispose(); //check for mission pass => open up missionScreen for teamMembers } }); buttonBox.add(voteDown); allBox.add(Box.createVerticalStrut(120)); allBox.add(missionMembersBox); allBox.add(Box.createVerticalStrut(30)); allBox.add(buttonBox); frame.add(allBox); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new voteScreen().initialize(); } }); } }
jerryleealan/Resistance-Client
src/voteScreen.java
248,272
/**Feb 20, 2019 * @author Joseph Kirkish */ package chapterSeven; import java.util.Random; /** * @author jkirkish * */ public class SwitchVsArray { public void SwitchVotes() { System.out.println("________________________________________________________________________________________\n Switch"); // random number generator Random ran = new Random(); // politicians starting out with zero votes int politican1 = 0; int politican2 = 0; int politican3 = 0; int politican4 = 0; int classificationNumber; // There are 4 politicians classified 1,2,3,4 // there are 1000000 voters to account for; voting for each politican for (int votes = 1; votes <= 10000000; votes++) { classificationNumber = 1 + ran.nextInt(4);// determine which politican to vote for switch (classificationNumber) { case 1: ++politican1; break; case 2: ++politican2; break; case 3: ++politican3; break; case 4: ++politican4; break; }// end of case statement } // end of for loop System.out.println("Politican\tVotes"); System.out.printf("1Donald Trump\t%d\n2Bernie Sanders\t%d\n3Kamala Harris\t%d\n4Joe Biden\t%d\n", politican1, politican2, politican3, politican4); } public void ArrayVotes() { System.out.println( "________________________________________________________________________________________\n Array"); // random number generator Random ran = new Random(); String[] names = {"Donald Trump","Bernie Sanders","Kamala Harris","Joe Biden"}; int [] politicians = new int[5]; // each index designates a number associated with a politician // there are 1000000 voters to account for; voting for each politican for(int vote = 1; vote <= 10000000;vote++) { ++politicians[1 + ran.nextInt(4)]; } System.out.printf("%s\t%s\n", "Politician", "Votes"); for (int politician = 1; politician < politicians.length; politician++) System.out.printf("%d%s\t%d\n", politician,names[politician-1], politicians[politician]); }//end of method }//end of class
jkirkish/MorePractice
SwitchVsArray.java
248,273
import java.io.*; import java.util.*; //Prøvde å lage en graf med en hashmap fra alle noder til alle kantene, men ble for mye å gå gjennom //Endte med å bare ha et par hashmaps som jeg referer til public class Graph { File mvs, actrs; HashMap<String, Actors.Node> actorIdToNodes; // Alle node ider til noder static HashMap<String, Movies.Edge> movieToEdge; // Alle filmid til film objekter HashMap<String, Set<Actors.Node>> movieToNodes; // Film id til alle skuespillerene i filmen. static HashMap<Actors.Node, Set<String>> nodesToEdge; // Alle node objekter til deres filmer // Kunne sikkert vært letter å bruke nøstede hashmaps public Graph(File mvs, File actrs) { long startTime = System.nanoTime(); this.mvs = mvs; this.actrs = actrs; Actors actorsFile = new Actors(actrs); Movies movieFile = new Movies(mvs); movieToEdge = movieFile.getMovieMap(); actorIdToNodes = actorsFile.getNodeMap(); nodesToEdge = actorsFile.getNodeToEdge(); // HashMap<Actors.Node, Set<Movies.Edge>> graph = new HashMap<>(); movieToNodes = actorsFile.getGraph(); long endTime = System.nanoTime(); double elapsedTimeSeconds = (endTime - startTime) / 1e9; // tid i sekunder System.out.println(elapsedTimeSeconds + " sekunder tid brukt på laging av grafen"); } public HashMap<Actors.Node, Actors.Node> findShortestPath(Actors.Node actor1, Actors.Node actor2, Set<Actors.Node> visited) { HashMap<Actors.Node, Actors.Node> pathToSix = new HashMap<>(); if (nodesToEdge.containsKey(actor1) && nodesToEdge.containsKey(actor2)) { visited.add(actor1); Queue<Actors.Node> queue = new LinkedList<>(); queue.add(actor1); while (!queue.isEmpty()) { Actors.Node current = queue.poll(); if (current == actor2) { return pathToSix; // Funnet korteste veien } Set<String> mviLst = nodesToEdge.get(current); for (String movies : mviLst) { Set<Actors.Node> actorLst = movieToNodes.get(movies); for (Actors.Node actors : actorLst) { if (!visited.contains(actors)) { visited.add(actors); pathToSix.put(actors, current); queue.add(actors); } } } } } else { System.err.println("Fant ikke skuespilleren: "); } return pathToSix; } public void BFS(String id1, String id2) { Set<Actors.Node> visited = new HashSet<>(); HashMap<Actors.Node, Actors.Node> path = null; Actors.Node actor1 = actorIdToNodes.get(id1); Actors.Node current = actorIdToNodes.get(id2); path = findShortestPath(actor1, current, visited); backTrackPath(false, path, actor1, current); } public HashMap<Actors.Node, Float> Dijkstra(String first, String last) { Actors.Node start = actorIdToNodes.get(first), end = actorIdToNodes.get(last); Set<Actors.Node> visited = new HashSet<>(); Queue<Actors.Node> queue = new PriorityQueue<>(); HashMap<Actors.Node, Float> distance = new HashMap<>(); HashMap<Actors.Node, Actors.Node> path = new HashMap<>(); distance.put(start, (float) 0); queue.add(start); Graph.Actors.Node.distance = distance; while (!queue.isEmpty()) { Actors.Node current = queue.poll(); if (current == end) { backTrackPath(true, path, start, end); return distance; } if (visited.contains(current)) { continue; } visited.add(current); Set<String> mviLst = nodesToEdge.get(current); for (String movie : mviLst) { Set<Actors.Node> actrs = movieToNodes.get(movie); for (Actors.Node node : actrs) { if (!visited.contains(node)) { float weight = distance.get(current) + findWeight(current, node, movie); if (weight < distance.getOrDefault(node, Float.MAX_VALUE)) { path.put(node, current); distance.put(node, weight); queue.add(node); // visited.add(current); } } } } } return distance; } private void backTrackPath(boolean weight, HashMap<Graph.Actors.Node, Graph.Actors.Node> path, Graph.Actors.Node start, Graph.Actors.Node end) { float movieRating = 0; Stack<String> output = new Stack<>(); while (start != end) { // Backtracker til orginale skuespilleren Set<String> curMovies = nodesToEdge.get(end); Actors.Node parent = path.get(end); Set<String> parentMovie = nodesToEdge.get(parent); for (String string : parentMovie) { if (curMovies.contains(string)) { // Tror jeg egt burde sjekke filem sin høyeste rating i tilfelle de // har flere filmer sammen? Movies.Edge mvs = movieToEdge.get(string); output.push("===[ " + mvs.name + " (" + mvs.rating + ") ] ===> " + end.name); movieRating += mvs.rating; end = parent; break; } } } System.out.println(end.name); int size = output.size(); while (!output.isEmpty()) { System.out.println(output.pop()); } if (weight) { System.out.print("Total weight: "); System.out.println((size * 10) - movieRating); } System.out.println("\n"); } private float findWeight(Actors.Node current, Actors.Node parent, String movie) { float weight = Integer.MAX_VALUE; if (movieToEdge.containsKey(movie)) if (movieToEdge.get(movie).rating < weight) { weight = 10 - movieToEdge.get(movie).rating; } return weight; } public void findComponents() { HashMap<Integer, Integer> components = new HashMap<>(); Set<Actors.Node> visted = new HashSet<>(); for (Actors.Node node : nodesToEdge.keySet()) { if (!visted.contains(node)) { int count = DFS(node, visted); if (components.containsKey(count)) { components.put(count, components.get(count) + 1); } else { components.put(count, 1); } } } Stack<String> print = new Stack<>(); for (Map.Entry<Integer, Integer> entry : components.entrySet()) { print.add("There are " + entry.getValue() + " components of size " + entry.getKey()); } while (!print.isEmpty()) { System.out.println(print.pop()); } System.out.println(); } private Integer DFS(Graph.Actors.Node node, Set<Graph.Actors.Node> visted) { Stack<Actors.Node> stack = new Stack<>(); stack.add(node); int count = 0; while (!stack.isEmpty()) { Actors.Node current = stack.pop(); if (visted.contains(current)) { continue; } count++; visted.add(current); Set<String> curMovie = nodesToEdge.get(current); for (String movie : curMovie) { if (movieToEdge.containsKey(movie)) { Set<Actors.Node> actrs = movieToNodes.get(movie); for (Actors.Node parent : actrs) { if (!visted.contains(parent)) { stack.push(parent); } } } } } return count; } public static class Actors { File ac; HashMap<String, Node> actorMap = new HashMap<>(); HashMap<Node, Set<String>> actorToEdgeMap = new HashMap<>(); HashMap<String, Set<Node>> movies = new HashMap<>(); public Actors(File ac) { this.ac = ac; try { Scanner sc = new Scanner(ac); while (sc.hasNextLine()) { String line = sc.nextLine(); String[] splitString = line.split("\t"); Node node = new Node(splitString[0], splitString[1]); int len = splitString.length; Set<String> indivEdge = new HashSet<>(); for (int i = 2; i < len; i++) { if (!movies.containsKey(splitString[i])) { Set<Node> set = new HashSet<>(); set.add(node); movies.put(splitString[i], set); } else { Set<Node> k = movies.get(splitString[i]); k.add(node); movies.put(splitString[i], k); } indivEdge.add(splitString[i]); } actorToEdgeMap.put(node, indivEdge); actorMap.put(splitString[0], node); } sc.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public HashMap<String, Node> getNodeMap() { return actorMap; } public HashMap<Node, Set<String>> getNodeToEdge() { return actorToEdgeMap; } public HashMap<String, Set<Node>> getGraph() { return movies; } public static class Node implements Comparable<Node> { String name, id; public static HashMap<Actors.Node, Float> distance; public Node(String id, String name) { this.name = name; } @Override public int compareTo(Node o) { float myDistance = distance.get(this); float otherDistance = distance.get(o); return Float.compare(myDistance, otherDistance); } } } public static class Movies { File fil; HashMap<String, Edge> map = new HashMap<>(); public Movies(File fil) { this.fil = fil; try { Scanner sc = new Scanner(fil); sc.nextLine(); while (sc.hasNextLine()) { String line = sc.nextLine(); String[] splitString = line.split("\t"); Edge movie = new Edge(splitString[1], Float.parseFloat(splitString[2]), Integer.parseInt(splitString[3])); map.put(splitString[0], movie); } sc.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public HashMap<String, Edge> getMovieMap() { return map; } public static class Edge { public String name; public float rating; public int votes; public Actors.Node startReference = null, endReference = null; ArrayList<Actors.Node> actorsList = new ArrayList<>(); public Edge(String name, float rating, int votes) { this.name = name; this.rating = rating; this.votes = votes; } } } public static void main(String[] args) { long wholeStartTime = System.nanoTime(); Graph g = new Graph(new File("imdb/movies.tsv"), new File("imdb/actors.tsv")); long startTime = System.nanoTime(); g.BFS("nm2255973", "nm0000460"); g.BFS("nm0424060", "nm8076281"); g.BFS("nm4689420", "nm0000365"); g.BFS("nm0000288", "nm2143282"); g.BFS("nm0637259", "nm0931324"); long endTime = System.nanoTime(); double elapsedTimeSeconds = (endTime - startTime) / 1e9; System.out.println(elapsedTimeSeconds + " sekunder tid brukt på å finne korteste vei\n\n"); long dijkstraStart = System.nanoTime(); g.Dijkstra("nm2255973", "nm0000460"); g.Dijkstra("nm0424060", "nm8076281"); g.Dijkstra("nm4689420", "nm0000365"); g.Dijkstra("nm0000288", "nm2143282"); g.Dijkstra("nm0637259", "nm0931324"); long dijkstraEnd = System.nanoTime(); double dijkstraElapsed = (dijkstraEnd - dijkstraStart) / 1e9; System.out.println(dijkstraElapsed + " sekunder tid brukt på å finne chilleste vei\n\n"); g.findComponents(); long wholeEndTime = System.nanoTime(); double wholeTime = (wholeEndTime - wholeStartTime) / 1e9; System.out.println(wholeTime + "Sekunder på hele oppgaven"); } }
NicoSik/IN2010
OB3/Graph.java
248,274
import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class WerewolfServer implements Runnable { // List of people connected to the server, searched by name and holding their Player object associated with them ConcurrentHashMap<String, Player> players = new ConcurrentHashMap<String, Player>(); // Server socket final private ServerSocket ss; // Executor service that holds all the threads associated with dealing with connected users final private ExecutorService clientThreadPool; // HashMap of strings, one for each player in the actual game, where their game actions are stored if the game asks // them for something ConcurrentHashMap<String, String> gameActions; // Whether the game has actually started or not. This can change what happens when new people join, among other things boolean gameStart = false; // HashMap similar to gameActions that holds boolean values that determine if the game is waiting for the specific player ConcurrentHashMap<String, Boolean> gameWaiting; // HashSet of players that are playing but dead, initialized when game starts Set<Player> dead; // HashSet of players that are playing and not dead, initialized when game starts Set<Player> currentPlayers; // HashSet of cards with the correct number of duplicates that will be assigned to players, initialized on game start Set<Card> chooseCards; // Array of cards, one each, in the order of ranking, which determines when a certain card wakes up at night, if at all. // All cards are in here, including cards that may be taken out because there are more cards than players (so no player knows // that that card is not actually in play). Card[] cards; // An integer determining how many people the villagers will kill during each day. Usually 1, but the Troublemaker // can increase this value once per game to 2, which is why the separate integer is designated. int amountOfDayKills; // A master boolean flag that determines if the game is still waiting on some player's vote to kill during each day. boolean dayKillFlag; // A HashMap holding the player's votes during the day, initialized during the start of each day. The key is the player // who votes, and the value is the player they voted for. ConcurrentHashMap<Player, String> votes; // A boolean flag to let the server know everyone is voting during the day boolean voting; // The random class to give random numbers that are more random than Math.random() Random rand = new Random(); // Number of death checks, incremented after someone died during a death check int deathCheckNum; // The number of werewolf cards that are in the game int werewolfNum; // Number of werewolf kills for the night int werewolfKills; // The idle times to use when a role requires input but no one alive is that role ([range, min time]) int[] idleTimes; // The timers for day, werewolves, and other nights. If number is -1, then timer is off int[] timers; // An array to hold neighbor information. It is a finicky command so make sure the names inputted are the same names // the players use when connecting Player[] neighbors; // A flag to check if the game is currently day or night boolean isNight; // main function which creates the server public static void main(String[] args) throws IOException { new WerewolfServer(); } // The server constructor which sets up the server, starts the thread pool for dealing with all users connected to it, // and then starts its own thread of waiting for the game to start. WerewolfServer() throws IOException { ss = new ServerSocket(5555); System.out.println("Werewolf Server is up at " + InetAddress.getLocalHost().getHostAddress() + " on port " + ss.getLocalPort()); clientThreadPool = Executors.newCachedThreadPool(); new Thread(this).start(); } // A method to add a person from the player HashMap when they connect. public void addPlayer(String playerName, Player player) { players.put(playerName, player); try { sendToAllPlayers("\n" + playerName + " joined the server.\n"); } catch(Exception e) { System.out.println(e.getMessage()); } // Check if neighbors was set, and if so, unset it, but only if the game hasn't started yet // This is because neighbors will point to a Player object that doesn't exist anymore. If it's started already, // the player that this player WAS, would still be held in currentPlayers, so it can remain because it's the same // player if(neighbors != null && !gameStart) { neighbors = null; } } // A method to remove a person from teh player HashMap when they leave or disconnect. When disconnecting, if the game // is ongoing, they will not be removed from the game, so they can join back. They just will miss any text sent between // them disconnecting and reconnecting. public void removePlayer(String playerName) { players.remove(playerName); try { sendToAllPlayers("\n" + playerName + " left the server.\n"); } catch(Exception e) { System.out.println(e.getMessage()); } // Check if neighbors was set, and if so, unset it if(!gameStart && neighbors != null) { neighbors = null; } } // The run method that continually accepts new players and executes the thread pool for that player. @Override public void run() { new Thread(new GameRunner(this)).start(); while (true) { try { Socket s = ss.accept(); clientThreadPool.execute(new PlayerHandler(this, s)); } catch (Exception e) { System.out.println(e.getMessage()); } } } // The player handler class which is where the thread pools for each player goes into. It is constantly checking any // input that the player sent to the server and deals with it accordingly, whether the server was waiting for something // or the player asked the server a question. private class PlayerHandler implements Runnable { // The connection the player is connected through final private Socket clientSocket; // The overarching server final private WerewolfServer server; // The player's name to access other data structures with private String playerName; // The player object associated with this player to access other data structures with private Player player; // The constructor which takes only the server itself and the socket the player is connected through public PlayerHandler(WerewolfServer server, Socket socket) { this.clientSocket = socket; this.server = server; } // The run method that the thread pool instantly goes in after constructing. This deals with creating the player // object as well as constantly waiting for input from the player to deal with. @Override public void run() { try { // Setting up all important information for the player, including it's output stream, input stream, // player name, etc. String clientAddress = this.clientSocket.getInetAddress().getHostAddress(); ObjectInputStream input = new ObjectInputStream(this.clientSocket.getInputStream()); String joinMessage = ((String) input.readObject()).trim(); ObjectOutputStream output = new ObjectOutputStream(this.clientSocket.getOutputStream()); playerName = joinMessage.substring(0); // Checks to see if the player is a name that's not allowed if(playerName.equalsIgnoreCase("na") || playerName.equalsIgnoreCase("no one")) { output.writeObject("Invalid name"); clientSocket.close(); } // Checks through all already connected players and makes sure that that name is not already taken. for(Player player : players.values()) { if(player.name.equals(playerName)) { output.writeObject(playerName + " is already taken."); clientSocket.close(); } } System.out.println("New player joined from " + clientAddress + ", " + playerName); // If the game has already started, it checks the players in the game and sees if there is a player with // that name already in there. If there is, it assigns this player that player object, because it means // that this player was previously disconnected. if(!gameStart) { // If the game hasn't started yet, create the Player object like normal this.player = new Player(playerName, input, output); } else { // If it has, check all alive players and set them to that user if a match is found, making sure to // update the output stream and input stream with the new one. for(Player player : currentPlayers) { if(player.name.equals(playerName)) { this.player = player; player.output = output; player.input = input; break; } } // If they weren't found there, check the dead players and do the same. if(this.player == null) { for (Player player : dead) { if (player.name.equals(playerName)) { this.player = player; player.output = output; player.input = input; break; } } } // If they still weren't found, that means they were never in the game, so create a new object for them. if(this.player == null) { this.player = new Player(playerName, input, output); } } // Add that player to the list of players in the server server.addPlayer(playerName, player); // Start the infinite loop constantly checking and awaiting input from the player while(true) { // Logging message showing that it is waiting for input from that player. System.out.println("waiting for " + playerName); // Waits at this line until the player says something Object message = input.readObject(); // The message will always be a string, so convert it to that. String temp = (String)message; // Check if the game has started and if the server is waiting for this player to say something, // because if so, then whatever they said is likely in response to what the server asked. if(gameStart && gameWaiting.get(playerName)) { // If the message starts with 'help:', it is a command to the server and not in response to the // games question. if(temp.startsWith("help:")) { // Process out the 'help:' and get the rest of the message / command and deal with that as // if the server never asked them anything. String temp2 = temp.substring(temp.indexOf(":")+1).trim(); // Create a thread to send them back what they need, so that the server can continue to wait for // new input and never miss anything. new Thread(new handlePlayerCommand(temp2)).start(); // Logging message of the message from the player System.out.println(playerName + ": " + temp2); continue; } // If the message didn't start with 'help:', then the message was in response to the server's question, // so deal with that. new Thread(new handleGameAction(temp)).start(); } else { // If the game hasn't started yet, then this is a command to the server. if(temp.startsWith("help:")) { // In case it starts with 'help:', take that out as it is not needed here, but included for // ease of use. temp = temp.substring(temp.indexOf(":")+1).trim(); } // Create a new thread to deal with that. new Thread(new handlePlayerCommand(temp)).start(); // Logging message of the message from the player System.out.println(playerName + ": " + temp); } } } catch(Exception e) { // If there was an error anywhere in here, it probably means that they were disconnected. System.out.println(e.getMessage()); try { clientSocket.close(); server.removePlayer(playerName); } catch(Exception e2) { server.removePlayer(playerName); } } } // Class to deal with player commands. This is only ever called by the thread pool and has its own thread. public class handlePlayerCommand implements Runnable { String command; // This class only cares for the command, so set that in the constructor. public handlePlayerCommand(String command) { this.command = command; } // Process the command. @Override public void run() { try { String result = ""; // If the command is help, display all commands that can be used if(command.equalsIgnoreCase("commands") || command.equalsIgnoreCase("help")) { result += "\n\nThe following commands can be used:\n(Also, after the server asks you for something,\nyou can type 'help:' followed by a command to access\nany of these commands)\n\n"; result += "'help':\t\t\tLists the possible commands\n"; result += "'players':\t\tLists the current alive players. Includes their votes if during voting time.\n"; result += "'dead':\t\t\tLists the current dead players and their cards\n"; result += "'cards':\t\tLists the cards that have been chosen to be in the game\n"; result += "'card <card name>':\tLists the description and details of the card specified by <card name>\n"; result += "'clients':\t\tLists the server clients (players) currently connected to the server\n"; result += "'order':\t\tLists the order of the cards that wake up during the nights\n\t\t\t(does not include cards that only wake up during the first night)\n"; result += "'win':\t\t\tLists the order in which win conditions are checked\n"; result += "'WhoAmI':\t\tTells you what your card is again\n"; result += "'needToKnow':\t\tTells you your card's need to know information. Not every card has some. Will also say if you're linked to someone through Cupid.\n"; result += "'neighbors':\t\tTells the order of neighbors. Names next to each other are neighbors with each other (including the name at the top and bottom)\n"; } else if(command.equalsIgnoreCase("players")) { // If the command is players, display all alive players in the game if(gameStart) { if(!voting) { // Alive players can't be displayed if the game hasn't started yet result += "\n\nThe following players are currently alive in the game:\n\n"; for (Player player : currentPlayers) { result += player.name; if (player.tower) { // Displays the tower next to the player if they have the tower, preventing their death the first night result += " <-- tower is currently active and thus cannot be killed this night"; } result += "\n"; } } else { result += "\n\nThe following players are currently alive in the game:\n\n"; for(Player player : currentPlayers) { result += player.name; if(player.canVote) { if (!votes.get(player).equals("")) { result += " - Voted for " + votes.get(player); } else { result += " - Hasn't voted yet"; } } else { result += " - Hasn't voted yet"; } result += "\n"; } } } else { result += "\n\nThe game has not started yet, and thus there are no players\n"; } } else if(command.equalsIgnoreCase("dead")) { // Displays all dead players if(gameStart) { result += "\n\nThe following players are currently dead in the game:\n\n"; for(Player player : dead) { result += player.name + ", who was a " + player.card.cardName + "\n"; } } else { result += "\n\nThe game has not started yet, and thus there are no players\n"; } } else if(command.equalsIgnoreCase("cards")) { // Displays all cards potentially in the game if(gameStart) { result += "\n\nThe following cards are currently in the game:\n\n"; // Set up the scanner for the file. File file = new File("cards.txt"); Scanner scanner = null; try { scanner = new Scanner(file); } catch(Exception e) { System.out.println(e.getMessage()); } // Scan every line and add that to the result string while(scanner.hasNextLine()) { result += scanner.nextLine(); result += "\n"; } scanner.close(); } else { result += "\n\nThe game has not started yet, and thus there are no cards\n"; } } else if(command.length() >= 4 && command.substring(0, 4).equalsIgnoreCase("card")) { // Runs the help() command for the specified card, which displays the important information about it. if(gameStart) { if (command.length() < 5) { result += "\n\nUse this command with the name of a card, like so: 'card <card name>'\n"; } else { // Search for the card asked about String askedCard = command.substring(5); boolean cardFound = false; for (Card card : cards) { if (card.cardName.equalsIgnoreCase(askedCard)) { // The card was identified, so display the help() method for that card. result += "\n" + card.help() + "\n"; cardFound = true; } } if (!cardFound) { // If the card was not found, tell the player that. result += "\nCard not found\n"; } } } else { result += "\n\nThe game has not started yet, and thus there are no cards to ask about\n"; } } else if(command.equalsIgnoreCase("clients")) { // Display all people currently connected to the server result += "\n\nThe following players are currently connected to the server:\n\n"; for(String player : players.keySet()) { result += player + "\n"; } } else if(command.equalsIgnoreCase("order")) { // Display the order that cards wake up at night, excluding the first night wake-ups if(gameStart) { result += "\n\nThe following is the order of how the cards wake up each night (excluding first night only wakeups):\n\n"; for(Card card : cards) { if(card.nightWakeup && !card.firstNightOnly) { result += card.cardName + "\n"; } } } else { result += "\n\nThe game has not started yet, and thus there are no cards to list the order\n"; } } else if(command.equalsIgnoreCase("win")) { // Display the order that cards get checked for winning if(gameStart) { result += "\n\nThe following is the order of how the cards are checked for wins:\n\n"; // Clone the cards Array so that they can be put in order of win rank. Card[] cardsForWinning = cards.clone(); // Sort in order of winRank for(int i = 0; i < cardsForWinning.length - 1; i++) { for(int j = 0; j < cardsForWinning.length - i - 1; j++) { if(cardsForWinning[j].winRank > cardsForWinning[j+1].winRank) { Card temp = cardsForWinning[j]; cardsForWinning[j] = cardsForWinning[j+1]; cardsForWinning[j+1] = temp; } } } for(Card card : cardsForWinning) { result += card.cardName + "\n"; } } else { result += "\n\nThe game has not started yet, and thus there are no cards to list the order\n"; } } else if(command.equalsIgnoreCase("WhoAmI") || command.equalsIgnoreCase("who am i")) { // Display the player's card name, which can include -> if they are a team switcher if(gameStart) { result += "\n\nYour card is: " + player.card.cardName; } else { result += "\n\nThe game hasn't started yet, so you don't have a card\n"; } } else if(command.equalsIgnoreCase("needToKnow")) { // Checks if they are linked to someone through Cupid result += "\n\n"; for(Card card : cards) { if(card instanceof CupidCard cupidCard) { if(cupidCard.linked[0].equals(player)) { result += "Through Cupid, you are linked to: " + cupidCard.linked[1]; } else if(cupidCard.linked[1].equals(player)) { result += "Through Cupid, you are linked to: " + cupidCard.linked[0]; } break; } } // Display the player's card's need to know information. Not too many cards have some String needToKnow = player.card.needToKnow(player); if(needToKnow.equals("")) { result += "\nYour card does not have any need to know information.\n"; } else { result += "\n\n" + needToKnow + "\n"; } } else if(command.equalsIgnoreCase("neighbors")) { // The 'neighbors' command to give the order of neighbors, if it's not null result += "\n"; if(neighbors != null) { for(Player player : neighbors) { if(gameStart && !player.dead) { result += player.name + "\n"; } else if(!gameStart) { result += player.name + "\n"; } } } else { result += "There are no neighbors specified!\n"; } } else { // If the command wasn't found, tell the player that result += "\n" + command + " command not found\n"; } // Send the result of result to the player that sent the command player.output.writeObject(result); player.output.flush(); } catch (Exception e) { System.out.println(e.getMessage()); } } } // This class deals with player actions in response to the server's questions. This is only ever called by the thread // pool and has its own thread. public class handleGameAction implements Runnable { String action; // This class only cares for the action, so set that in the constructor. public handleGameAction(String action) { this.action = action; } // Process the action. @Override public void run() { try { // Set the player's action to their input. gameActions.replace(playerName, action); // Logging message to make it clear something was obtained from them. System.out.println(playerName + "'s action: " + action); } catch (Exception e) { System.out.println(e.getMessage()); } } } } // This class runs the game. All game running is in this class. private class GameRunner implements Runnable { final private WerewolfServer server; // This game class only actually cares for the server, so set that. public GameRunner(WerewolfServer server) { this.server = server; } // The method that runs the server. @Override public void run() { // Gets the reader to read from command line to start the game. BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); boolean start = false; // Set default values for idle times idleTimes = new int[2]; idleTimes[0] = 5000; // Range is 5 seconds idleTimes[1] = 3000; // Minimum is 3 seconds // Set default values for the timers timers = new int[3]; timers[0] = 300000; // 5 minutes timers[1] = 60000; // 1 minute timers[2] = 30000; // 30 seconds // The infinite loop that goes on for as long as the server is up. while(true) { try { System.out.println("We are waiting to start. Type 'start' when ready"); // Wait for the person running the server to type 'start' to start the game. String input = br.readLine().trim(); // If the input wasn't 'start', continue the loop back at the start. // Or maybe it was another command to edit how the server runs. Either way, check if (input.equalsIgnoreCase("start")) { // Input was 'start' so start the game start = true; } else if(input.contains("idle")) { // Input was 'idle' so edit the idle time that roles do when none of them are alive int max; int min; try { // Get the times that were given max = Integer.parseInt(input.substring(input.indexOf('=') + 1, input.indexOf(','))) * 1000; min = Integer.parseInt(input.substring(input.indexOf(',') + 1)) * 1000; if(max < min || max < 0 || min < 0) { throw new IllegalArgumentException(); } // Set first index to range and second index to min time idleTimes[0] = max - min; idleTimes[1] = min; System.out.println("Current max: " + ((idleTimes[0]+idleTimes[1])/1000) + ", min: " + (idleTimes[1]/1000) + "\n"); } catch(Exception e) { System.out.println("idle=<max time>,<min time>. Current max: " + ((idleTimes[0]+idleTimes[1])/1000) + ", min: " + (idleTimes[1]/1000) + "\n"); } continue; } else if(input.contains("dayTimer")) { // Input was 'dayTimer' so edit the day voting timer int time; try { // Get the time that was given time = Integer.parseInt(input.substring(input.indexOf('=') + 1)) * 1000; if(time < 0) { throw new IllegalArgumentException(); } // Set time timers[0] = time; System.out.println("Current time: " + (timers[0]/1000) + "s, " + (((double)timers[0]/1000)/60) + "min\n"); } catch(Exception e) { System.out.println("dayTimer=<time (seconds) (0 for off)>. Current time: " + (timers[0]/1000) + "s, " + (((double)timers[0]/1000)/60) + "min\n"); } continue; } else if(input.contains("werewolfTimer")) { // Input was 'werewolfTimer' so edit the day voting timer int time = -1; try { // Get the time that was given time = Integer.parseInt(input.substring(input.indexOf('=') + 1)) * 1000; if(time < 0) { throw new IllegalArgumentException(); } // Set time timers[1] = time; System.out.println("Current time: " + (timers[1]/1000) + "s, " + (((double)timers[1]/1000)/60) + "min\n"); } catch(Exception e) { System.out.println("dayTimer=<time (seconds) (0 for off)>. Current time: " + (timers[1]/1000) + "s, " + (((double)timers[1]/1000)/60) + "min\n"); } continue; } else if(input.contains("nightTimer")) { // Input was 'nightTimer' so edit the day voting timer int time = -1; try { // Get the time that was given time = Integer.parseInt(input.substring(input.indexOf('=') + 1)) * 1000; if(time < 0) { throw new IllegalArgumentException(); } // Set time timers[2] = time; System.out.println("Current time: " + (timers[2]/1000) + "s, " + (((double)timers[2]/1000)/60) + "min\n"); } catch(Exception e) { System.out.println("dayTimer=<time (seconds) (0 for off)>. Current time: " + (timers[2]/1000) + "s, " + (((double)timers[2]/1000)/60) + "min\n"); } continue; } else if(input.contains("neighbors")) { // Input was 'neighbors' so create the neighbors Array that may be used by certain cards neighbors = new Player[players.size()]; if(input.equals("neighbors")) { // If the input was JUST neighbors, then randomly create neighbors HashSet<Player> playersCopy = new HashSet<Player>(); for(int i = 0; i < players.size(); i++) { // Get a copy of the players into a HashSet playersCopy.add((Player)players.values().toArray()[i]); } neighbors = new Player[playersCopy.size()]; for(int i = 0; i < players.size(); i++) { // Randomly assign the players to a location in neighbors, removing them from teh copy HashSet int random = rand.nextInt(playersCopy.size()); neighbors[i] = (Player)playersCopy.toArray()[random]; playersCopy.remove(neighbors[i]); } } else { // If custom neighbors were given try { String temp = input.substring(input.indexOf("=") + 1); for (int i = 0; i < neighbors.length; i++) { // Run through the length of neighbors, which is the amount of players currently in the server try { // If there are more players in the string given, get the next one String temp2 = temp.substring(0, temp.indexOf(",")); for(Player player : players.values()) { // Find the player that has that name if(player.name.equals(temp2)) { // Set them up at that location and get the next name neighbors[i] = player; try { temp = temp.substring(temp.indexOf(",") + 1); } catch(Exception e) { // If there is no next name then that's it System.out.println(); } } } } catch(IndexOutOfBoundsException e) { // If this was the last name, then this is the last name and put it at the end for(Player player : players.values()) { // Find the player with that name if(player.name.equals(temp)) { neighbors[i] = player; try { // Just in case, get the next name temp = temp.substring(temp.indexOf(",") + 1); } catch(Exception ei) { System.out.println(); } } } } } } catch(Exception e) { // Tell the server moderator how to call this method since they did it wrong System.out.println("neighbors=<name1>,<name2>,<name3>,..."); } } // Verify that neighbors is correct (only 1 instance of each player is there if(neighbors != null) { // Create a HashMap of players HashMap<Player, Integer> counts = new HashMap<Player, Integer>(); for(Player player : players.values()) { counts.put(player, 0); } // Count how many instances of each player is in the neighbors Array for(Player player : neighbors) { counts.replace(player, counts.get(player) + 1); } // Loop through count. If there is any player that does not equal 1, null out neighbors and tell // the server moderator for(int count : counts.values()) { if(count != 1) { neighbors = null; System.out.println("All players must show up once in neighbors."); break; } } } } else { System.out.println("'start', 'idle=<max time (seconds)>,<min time (seconds)>', 'dayTimer=<time (seconds) (0 for off)>'"); System.out.println("'werewolfTimer=<time (seconds) (0 for off)>', 'nightTimer=<time (seconds) (0 for off)>'"); System.out.println("'neighbors=<name separated by commas>'"); continue; } // If the server runner said start, and there are at least 5 players (Werewolf needs at minimum 5 players), // the game can start. if (start && server.players.size() >= 5) { System.out.println("Starting"); // Set all players in the server to alive. for(Player player : players.values()) { player.dead = false; } // Get all the players in the game situated by setting them all as in the alive HashSet and getting // their gameActions and gameWaiting data structures ready. gameActions = new ConcurrentHashMap<String, String>(); gameWaiting = new ConcurrentHashMap<String, Boolean>(); currentPlayers = ConcurrentHashMap.newKeySet(); // Initialize the dead HashSet. dead = ConcurrentHashMap.newKeySet(); int i = 0; for(String name : server.players.keySet()) { currentPlayers.add(server.players.get(name)); gameActions.put(name, ""); gameWaiting.put(name, Boolean.FALSE); i++; } // Check if neighbors were specified. If they were, check to make sure the neighbors in there // are the players in the game if(neighbors != null) { // Create a HashMap of players HashMap<Player, Integer> counts = new HashMap<Player, Integer>(); for(Player player : currentPlayers) { counts.put(player, 0); } // Count how many instances of each player is in the neighbors Array for(Player player : neighbors) { counts.replace(player, counts.get(player) + 1); } // Loop through count. If there is any player that does not equal 1, null out neighbors and tell // the server moderator boolean goodNeighbors = true; for(int count : counts.values()) { if(count != 1) { neighbors = null; System.out.println("All players must show up once in neighbors."); goodNeighbors = false; break; } } // Cancel the game if the neighbors aren't correct if(!goodNeighbors) { gameStart = false; continue; } } // Read the cards that will be played with from the cards.txt file. readCards(); boolean hasWerewolves = false; for(Card card : cards) { if(card.cardName.equals("Werewolf") || card.cardName.equals("Dire Wolf") || card.cardName.equals("Wolf Man") || card.cardName.equals("Wolf Cub")) { hasWerewolves = true; break; } } if(!hasWerewolves) { System.out.println("There are no werewolf cards."); continue; } // Set the werewolf kills to 1 werewolfKills = 1; // The preCheck stuff (sort for preCheck order, then preCheck) Card[] preCheckCards = preCheckSort(cards.clone()); try { for (Card card : preCheckCards) { card.preCheck(); } } catch(IllegalArgumentException e) { System.out.println(e.getMessage()); continue; } // Set the start flag to true for the rest of the program. gameStart = true; // Check how many werewolf cards are being played werewolfNum = 0; boolean hasWerewolfCard = false; boolean hasPlainVillagerCard = false; for(Card card : chooseCards) { if(card.cardName.equals("Werewolf") || card.cardName.equals("Dire Wolf") || card.cardName.equals("Wolf Man") || card.cardName.equals("Wolf Cub")) { werewolfNum++; if(card.cardName.equals("Werewolf")) { // Also check if there is a plain werewolf card. If there's not, the game will not work // properly, so it will need to be added hasWerewolfCard = true; } } else if(card.cardName.equals("Villager")) { hasPlainVillagerCard = true; } } // If there is no plain werewolf card, add it to the cards HashSet so werewolf night actions can take place if(!hasWerewolfCard) { Card[] cardsClone = new Card[cards.length + 1]; for(int k = 0; k < cards.length; k++) { cardsClone[k] = cards[k]; } cardsClone[cards.length] = new WerewolfCard(server); cards = cardsClone; // Sort in order of rank for night wakeup. for(i = 0; i < cards.length - 1; i++) { for(int j = 0; j < cards.length - i - 1; j++) { if(cards[j].ranking > cards[j+1].ranking) { Card temp3 = cards[j]; cards[j] = cards[j + 1]; cards[j + 1] = temp3; } } } } // If there is no plain villager card, add it to the cards HashSet so the win conditions will run without problem if(!hasPlainVillagerCard) { Card[] cardsClone = new Card[cards.length + 1]; for(int k = 0; k < cards.length; k++) { cardsClone[k] = cards[k]; } cardsClone[cards.length] = new VillagerCard(server); cards = cardsClone; // Sort in order of rank for night wakeup. for(i = 0; i < cards.length - 1; i++) { for(int j = 0; j < cards.length - i - 1; j++) { if(cards[j].ranking > cards[j+1].ranking) { Card temp3 = cards[j]; cards[j] = cards[j + 1]; cards[j + 1] = temp3; } } } } // Set death check num deathCheckNum = 1; rand = new Random(System.currentTimeMillis()); // If the amount of cards is equal to the amount of players, just assign each player a random card, // with all cards being used once each (there can be duplicates of actual cards, which is stated // in the cards.txt file). if(chooseCards.size() == currentPlayers.size()) { // Create an array for the cards so that a random value can be obtained for the card and // assigned to a player. Object[] tempCards = chooseCards.toArray(); // A copy of the chooseCards HashSet is created so that cards that are already used can be removed. Set<Card> tempCards2 = ConcurrentHashMap.newKeySet(); tempCards2.addAll(chooseCards); // Run through each player in the game and give them a random card. for (Player player : currentPlayers) { int random = rand.nextInt(tempCards.length); player.card = (Card) tempCards[random]; tempCards2.remove(player.card); tempCards = tempCards2.toArray(); } } else if(chooseCards.size() > currentPlayers.size()) { // If there are more cards than players, remove extra cards at random (making sure all specified // werewolves are in the game). // The werewolf cards. HashSet<Card> werewolves = new HashSet<Card>(); // Just like in the section above where the card amount is equal to the player amount, make // a clone of the chooseCards Set. Set<Card> chooseCardsClone = ConcurrentHashMap.newKeySet(); chooseCardsClone.addAll(chooseCards); // For each card in chooseCards, find all that are werewolves of any kind (Werewolf, Wolf Man, Dire Wolf, // Wolf Cub), and remove them so that extra cards can be removed and none of them are werewolves. for(Card card : chooseCards) { if(card.cardName.equals("Werewolf") || card.cardName.equals("Wolf Man") || card.cardName.equals("Dire Wolf") || card.cardName.equals("Wolf Cub")) { // Temporarily remove the werewolf cards. werewolves.add(card); chooseCardsClone.remove(card); } } // Remove the amount of extra cards from the remaining cards (the non-werewolf cards), so that // there are the exact amount of cards (when werewolves are added back) as there are players. int removeCardAmount = chooseCards.size() - currentPlayers.size(); // Run through the amount of cards that need to be removed and randomly remove that amount of cards. for(i = 0; i < removeCardAmount; i++) { int random = rand.nextInt(chooseCardsClone.size()); chooseCardsClone.remove(chooseCardsClone.toArray()[random]); } // Add the werewolf cards back in to the chooseCards clone so that all of the remaining cards // can be given out to all players. chooseCardsClone.addAll(werewolves); // Assign the cards just like the if statement above all of this. Object[] tempCards = chooseCardsClone.toArray(); Set<Card> tempCards2 = ConcurrentHashMap.newKeySet(); tempCards2.addAll(chooseCardsClone); for (Player player : currentPlayers) { int random = rand.nextInt(tempCards.length); player.card = (Card) tempCards[random]; tempCards2.remove(player.card); tempCards = tempCards2.toArray(); } // If there are fewer cards than players, don't continue the game and let the server moderator know // they need to add more cards. } else { System.out.println("\nThere aren't enough cards for the amount of players."); start = false; continue; } // Make sure everyone is able to vote for(Player player : currentPlayers) { player.canVote = true; } // Make it clear to all players where the new game chat starts sendToAllPlayers("================================"); sendToAllPlayers("New Game!\n\n"); // Reset all the took night action flags for(Player player : server.currentPlayers) { player.tookNightAction = false; } // Set the night flag to true isNight = true; // Tell each player their card. for(Player player : currentPlayers) { player.output.writeObject("Your card: " + player.card.cardName); } // Tell everyone to close their eyes sendToAllPlayers("Close your eyes!"); Thread.sleep(3000); // Set the amount of day kills to 1. The Troublemaker can decide to increase this to 2 only once // every game, but it can be the first night if they so choose. amountOfDayKills = 1; // Run the loop for first night wakeup. There are many cards that have special first night wakeup // and there are also many that have each night the same as the first night. There are also some // that don't wake up at all every night. All of that is taken care of in the specific card. // If cards do the same thing the first night as they do every other night, their firstNightWakeup() // method will call their nightWakeup() method. If they don't do anything at night, they will // immediately return. The cards are already in the order of night wakeup when the cards array was // chosen, so it will run through them linearly. for(Card card : cards) { if(card.nightWakeup) { card.firstNightWakeup(); // Have the game thread sleep for 3 seconds after each night wakeup to ensure that threads // that should die now that their night wakeup is over, actually die after doing all they // need to. Thread.sleep(3000); // Make sure that the server is no longer waiting for any player. stopWaiting(); } } werewolfKills = 1; // Reset all the took night action flags for(Player player : server.currentPlayers) { player.tookNightAction = false; } // The night is over, so wake up everyone so that they can see who died and they can determine who to kill for the day. sendToAllPlayers("\nNow everyone open your eyes."); // A flag to make sure someone has died boolean hasDied = false; // Run through the alive players and check who was set to dead after the entire night, and add them to the // dead HashSet. for(Player player : currentPlayers) { if(player.dead) { dead.add(player); hasDied = true; } } // If no one died, tell everyone that no one died if(!hasDied) { sendToAllPlayers("\nNo one died tonight!\n"); } // For all players in the dead HashSet, because it was just created, all of those people are newly dead. for(Player player : dead) { // Tell all players who have been killed and what their cards were. sendToAllPlayers("\n" + player.name + " has been killed!\nThey were " + player.card.cardName + "!\n"); // Remove them from the alive players HashSet. currentPlayers.remove(player); // Because they died on the very first night and did not get to play, set their tower to true, meaning // they cannot die on the first night the next game (so they actually get to play). player.tower = true; // Tell that player they are dead player.output.writeObject("!!!!!YOU DIED!!!!!"); } // If the card has something it needs to check after all the deaths, like linked people, do it now // Do it the number of times that people died during a death check + 1 for(int k = 0; k < deathCheckNum; k++) { for (Card card : cards) { card.checkAfterDeaths(); } } deathCheckNum = 1; // Check if after the first night, someone already won. This is unlikely, but could happen in // the case of the Tanner, who wins if they die. Card won = checkWins(); if(won != null) { // Tell everyone which team won. sendToAllPlayers("The " + won.team + " team won!"); // Make a HashSet of players that were on that team. HashSet<Player> winningPlayers = new HashSet<Player>(); for(Player player : currentPlayers) { if(player.card.team.equals(won.team)) { // Add every player that won to that HashSet. winningPlayers.add(player); } } // Add all dead players of that HashSet too, since they still technically win if their team does. for(Player player : dead) { if(player.card.team.equals(won.team)) { winningPlayers.add(player); } } // Tell all players who was on that winning team. sendToAllPlayers("Winning players: " + winningPlayers); continue; } // Make sure that no player in the alive HashSet has a tower set since they survived. This is the only // place they get cleared between games so that the state of their tower from last game is preserved. for(Player player : currentPlayers) { player.tower = false; } sendToAllPlayers("---------------------------------------------------\n"); // Run the infinite loop for the game. Every day, then every night at the end, until someone won. while(true) { sendToAllPlayers("Now, you all need to discuss and pick a person each that you will kill."); sendToAllPlayers("Type 'na', 'NA', or 'no one' to vote for no one."); sendToAllPlayers("The number of people you must choose to kill is: " + amountOfDayKills + "\n"); // Set the night flag as false isNight = false; // Loop through the amount of kills there are that day for(int j = 0; j < amountOfDayKills; j++) { // Create the HashMap that holds all alive players votes. votes = new ConcurrentHashMap<Player, String>(); for (Player player : server.currentPlayers) { if(player.canVote) { votes.put(player, ""); } } // Tell the server it is waiting for all alive players' actions. for(Player player : currentPlayers) { if(player.canVote) { gameWaiting.replace(player.name, Boolean.TRUE); } } // Tell the players what kill this is for(Player player : currentPlayers) { player.output.writeObject("\nWho is your kill #" + (j + 1) + "?"); } // Set a flag so the server knows everyone is voting voting = true; // Set a flag to false signifying that the day isn't over. This only gets set to true // once all alive players have chosen a valid player to kill (valid as in they are still alive). dayKillFlag = false; // Create a thread that continuously sends a player's valid vote to all other players. new Thread(this::sendAllVotes).start(); // Check if the day timer is on, and if so, create the thread to keep the time Thread votingThread = null; if(timers[0] > 0) { int time; if(j > 0) { time = 10000; } else { time = timers[0]; } votingThread = new Thread(() -> server.timerHelper(time)); votingThread.start(); } // While the flag is false, run through this code. while (!dayKillFlag) { // Set a temporary flag that checks if all players have chosen someone. boolean good = true; // Create a count map that is used to find the most popular player to kill. HashMap<String, Integer> count = new HashMap<String, Integer>(); for (Player player : server.currentPlayers) { if(player.canVote) { count.put(player.name, 0); } } // Put the option for no vote in there count.put("no one", 0); // Step through all alive players and check to see if they voted. Additionally, talley // the player they voted for. for (String player : votes.values()) { if (!player.equals("")) { count.replace(player, count.get(player) + 1); } else { // If they did not vote, then that means the server can't continue so just quit // and try again. good = false; break; } } // A player didn't vote yet, so restart this loop. if (!good) { continue; } // If it got here, that means that all players have voted. Set the flag to true. dayKillFlag = true; // Stop the timer if it's on if(timers[0] > 0) { votingThread.interrupt(); } // Tell all players that the people who can't vote voted for a random player, when in actuality they didn't for(Player player : currentPlayers) { if(!player.canVote) { int randomWait = server.rand.nextInt(3000) + 2000; Thread.sleep(randomWait); int randomVote = rand.nextInt(currentPlayers.size() + 1); if(randomVote != currentPlayers.size()) { sendToAllPlayers(player.name + " voted: " + currentPlayers.toArray()[randomVote]); } else { sendToAllPlayers(player.name + " voted for no one"); } Thread.sleep(1000); } } // Wait 3 seconds to allow the threads created to help get player votes to end. Thread.sleep(3000); // Make sure the server is no longer waiting for any player. stopWaiting(); Set<Player> deadCopy = ConcurrentHashMap.newKeySet(); deadCopy.addAll(dead); // Loop through the votes for the amount of kills necessary and get the highest player. int highest = -1; String dead2 = ""; for (String player : count.keySet()) { if (count.get(player) > highest) { highest = count.get(player); dead2 = player; } } // That player who was chosen is set to dead. if(!dead2.equals("no one")) { Player dead3 = null; for (Player player : currentPlayers) { if (player.name.equals(dead2)) { dead3 = player; break; } } dead3.dead = true; count.remove(dead2); try { server.sendToAllPlayers("Voted dead player #" + (j + 1) + ": " + dead3.name + "\n"); } catch (Exception e) { System.out.println(e.getMessage()); } } else { try { server.sendToAllPlayers("Voted dead player #" + (j + 1) + ": No one was chosen!\n"); } catch (Exception e) { System.out.println(e.getMessage()); } } } } // Unset the voting flag voting = false; // Tell everyone that voting is over try { sendToAllPlayers("\n\nVoting is now over.\n\n"); } catch(Exception e) { System.out.println(e.getMessage()); } // Allow all players to vote again for(Player player : currentPlayers) { player.canVote = true; } // A temporary dead HashSet is created to log the newly dead players. HashSet<Player> deadCopy = new HashSet<Player>(); // Loops through all supposedly alive players and checks to see which are dead. for(Player player : currentPlayers) { if(player.dead) { // Adds them to the dead HashSet and the dead copy HashSet. dead.add(player); deadCopy.add(player); } } // Loops through all in the dead copy HashSet and alerts every one of their death and what card they were. for(Player player : deadCopy) { // If the player is not a Prince, continue as normal if(!player.card.cardName.contains("Prince")) { sendToAllPlayers("\n" + player.name + " has been chosen to be killed!\nThey were " + player.card.cardName + "!\n"); currentPlayers.remove(player); // Tell that player they are dead player.output.writeObject("!!!!!YOU DIED!!!!!"); } else { // If the player is a Prince, get the Prince card the server uses for(Card card : server.cards) { if(card instanceof PrinceCard princeCard) { // Check if their ability has already been used if(princeCard.abilityUsed) { // If it has, they die like normal sendToAllPlayers("\n" + player.name + " has been chosen to be killed!\nThey were " + player.card.cardName + "!\n"); currentPlayers.remove(player); // Tell that player they are dead player.output.writeObject("!!!!!YOU DIED!!!!!"); } else { // If it hasn't, the players are notified that they are the Prince and are not killed, this time sendToAllPlayers("\n" + player.name + " is the Prince! Therefore they are not killed... this time.\n"); princeCard.abilityUsed = true; player.dead = false; dead.remove(player); } break; } } } } // If the card has something it needs to check after all the deaths, like linked people, do it now // Do it the amount of times that someone during the death checks died + 1 for(int k = 0; k < deathCheckNum; k++) { for (Card card : cards) { card.checkAfterDeaths(); } } deathCheckNum = 1; // Resets the amount of day kills to 1. May have already been 1, may have been changed by another card // during the night. amountOfDayKills = 1; // Run through all cards to check if any team won, just like above. won = checkWins(); if(won != null) { sendToAllPlayers("The " + won.team + " team won!"); HashSet<Player> winningPlayers = new HashSet<Player>(); for(Player player : currentPlayers) { if(player.card.team.equals(won.team)) { winningPlayers.add(player); } } for(Player player : dead) { if(player.card.team.equals(won.team)) { winningPlayers.add(player); } } sendToAllPlayers("Winning players: " + winningPlayers); break; } sendToAllPlayers("---------------------------------------------------"); // Set the night flag as true isNight = true; // Now for the night again. This is the normal night, not the first night. sendToAllPlayers("Now for the night. Everyone close your eyes.\n"); Thread.sleep(3000); for(Card card : cards) { if(card.nightWakeup) { // Runs through the nights same as the first night, except it calls the normal // night method rather than the first night method. card.nightWakeup(); // Waits 3 seconds again to make sure all other threads finish what they were doing. Thread.sleep(3000); // Makes sure the game isn't waiting for anyone anymore. stopWaiting(); } } werewolfKills = 1; // Reset all the took night action flags for(Player player : server.currentPlayers) { player.tookNightAction = false; } // The night is over, so wake up everyone so that they can see who died, and they can determine who to kill for the day. sendToAllPlayers("\nNow everyone open your eyes."); // Resets the hasDied flag to check if anyone has died this night hasDied = false; // Just like above, it creates a dead copy and checks to see who is newly dead. deadCopy = new HashSet<Player>(); for(Player player : currentPlayers) { if(player.dead) { dead.add(player); deadCopy.add(player); hasDied = true; } } // If no one died, tell everyone that if(!hasDied) { sendToAllPlayers("\nNo one died tonight!\n"); } // Runs through the newly dead and alerts everyone of their death. for(Player player : deadCopy) { sendToAllPlayers("\n" + player.name + " has been killed!\nThey were " + player.card.cardName + "!\n"); currentPlayers.remove(player); // Tell that player they are dead player.output.writeObject("!!!!!YOU DIED!!!!!"); } // If the card has something it needs to check after all the deaths, like linked people, do it now // Do it the amount of times that someone during the death checks died + 1 for(int k = 0; k < deathCheckNum; k++) { for (Card card : cards) { card.checkAfterDeaths(); } } deathCheckNum = 1; // Just like above, checks to see if anyone won as a result of the night. won = checkWins(); if(won != null) { sendToAllPlayers("The " + won.team + " team won!"); HashSet<Player> winningPlayers = new HashSet<Player>(); for(Player player : currentPlayers) { if(player.card.team.equals(won.team)) { winningPlayers.add(player); } } for(Player player : dead) { if(player.card.team.equals(won.team)) { winningPlayers.add(player); } } sendToAllPlayers("Winning players: " + winningPlayers); break; } sendToAllPlayers("---------------------------------------------------\n"); } // If it finally left that loop, that means the game is over, so set the game to not be going. gameStart = false; // Clear all game related maps and sets. gameActions.clear(); gameWaiting.clear(); currentPlayers.clear(); } else if(server.players.size() < 5) { System.out.println("We need more people. Need at least 5"); } start = false; gameStart = false; } catch(Exception e) { System.out.println(e.getMessage()); } } } // Check if any cards won. private Card checkWins() { // Clone the cards Array so that they can be put in order of win rank. Card[] cardsForWinning = cards.clone(); // Sort in order of winRank for(int i = 0; i < cardsForWinning.length - 1; i++) { for(int j = 0; j < cardsForWinning.length - i - 1; j++) { if(cardsForWinning[j].winRank > cardsForWinning[j+1].winRank) { Card temp = cardsForWinning[j]; cardsForWinning[j] = cardsForWinning[j+1]; cardsForWinning[j+1] = temp; } } } // Check through all cards in the order of win rank to see who won (call their won method). for(Card card : cardsForWinning) { System.out.println("Checking win of " + card.cardName); if(card.won()) { // If a card won, return it. return card; } } // If no card won, return null. return null; } // A method to get all votes for all alive players. private void sendAllVotes() { String[] possibilities = new String[currentPlayers.size()]; int i = 0; for(Player player : currentPlayers) { if(!player.dead) { possibilities[i] = player.name; i++; } } // Run through the infinite loop until everyone has voted for a person while(!dayKillFlag) { // While the server is still waiting for everyone to vote. for(Player player : currentPlayers) { // If the server found that all players voted NOW, during each for execution, quit out of the loop. if(dayKillFlag) { break; } // If the currently checked player can't vote, skip this check if(!player.canVote) { continue; } // Make sure that the vote of a player is a valid player that is alive (can be themselves if they want). Also makes sure it doesn't send to all if // it already sent to all. if(!server.gameActions.get(player.name).equals("") && ((Arrays.asList(possibilities).contains(gameActions.get(player.name)) && !player.card.cardName.contains("Pacifist")) || ((gameActions.get(player.name).equalsIgnoreCase("NA") || gameActions.get(player.name).equalsIgnoreCase("no one")) && !player.card.cardName.contains("Village Idiot")))) { try { // Send their vote to all players. if(!gameActions.get(player.name).equalsIgnoreCase("NA") && !gameActions.get(player.name).equalsIgnoreCase("no one")) { sendToAllPlayers(player.name + " voted: " + server.gameActions.get(player.name)); } else { sendToAllPlayers(player.name + " voted for no one"); } } catch(Exception e) { System.out.println(e.getMessage()); } // Sets the last vote the player made to this vote. Also logs their vote. if(gameActions.get(player.name).equalsIgnoreCase("na")) { votes.replace(player, "no one"); } else { votes.replace(player, gameActions.get(player.name)); } gameActions.replace(player.name, ""); } else if(!gameActions.get(player.name).equals("") && (!Arrays.asList(possibilities).contains(gameActions.get(player.name)) && !gameActions.get(player.name).equalsIgnoreCase("NA") && !gameActions.get(player.name).equalsIgnoreCase("no one"))) { // If the player's vote wasn't a valid player. try { player.output.writeObject("Not a valid player"); System.out.println(player.name + ": " + gameActions.get(player.name)); // Replace the HashMap for the player that the server checks to see if anything was inputted. server.gameActions.replace(player.name, ""); } catch(Exception e) { System.out.println(e.getMessage()); } } else if(!gameActions.get(player.name).equals("") && Arrays.asList(possibilities).contains(gameActions.get(player.name)) && player.card.cardName.contains("Pacifist")) { gameActions.replace(player.name, ""); try { player.output.writeObject("You're a pacifist! You have to vote for no one!"); } catch(Exception e) { System.out.println(e.getMessage()); } } else if(!gameActions.get(player.name).equals("") && (gameActions.get(player.name).equalsIgnoreCase("NA") || gameActions.get(player.name).equalsIgnoreCase("no one")) && player.card.cardName.contains("Village Idiot")) { gameActions.replace(player.name, ""); try { player.output.writeObject("You're the Village Idiot! You have to vote for someone!"); } catch(Exception e) { System.out.println(e.getMessage()); } } } } } // Read all cards in the cards.txt file. private void readCards() throws FileNotFoundException { // Set up the scanner for the file. File file = new File("cards.txt"); Scanner scanner = new Scanner(file); // Create multiple temp data structures for the cards. HashSet<Card> temp = new HashSet<Card>(); HashSet<Card> temp2 = new HashSet<Card>(); // Scan every line while(scanner.hasNextLine()) { String card = scanner.nextLine(); String cardName; // If the card is in the file, that means there is at least 1 of them. int cardAmount = 1; // Cards can be in the form of 'werewolves' or 'werewolves x4', the second one meaning there are 4 // werewolves. Grab the number after the x if that exists. if(card.contains(" x")) { // Set the card name as everything before the ' x'. cardName = card.substring(0, card.indexOf("x") - 1); // Get the number of cards, which is directly after the 'x'. cardAmount = Integer.parseInt(card.substring(card.indexOf("x")+1)); } else { // If it wasn't in the form of ' x4' or another number, everything the scanner got is the // card's name. cardName = card; } // Make a flag for making sure that the cards array only has 1 of every card and the chooseCards // HashSet has the amount of cards that the text file specified. boolean doneOnce = false; // Go for the amount of cards specified (1 is default). for(int i = 0; i < cardAmount; i++) { Card tempCard = null; Card tempCard2 = null; if (cardName.equalsIgnoreCase("villager") || cardName.equalsIgnoreCase("villagers")) { // If the card is a plain villager, create a new villager card object. tempCard = new VillagerCard(server); tempCard2 = new VillagerCard(server); } else if (cardName.equalsIgnoreCase("werewolf") || cardName.equalsIgnoreCase("werewolves")) { // If the card is a plain werewolf card. tempCard = new WerewolfCard(server); tempCard2 = new WerewolfCard(server); } else if (cardName.equalsIgnoreCase("tanner")) { // If the card is a tanner card. tempCard = new TannerCard(server); tempCard2 = new TannerCard(server); } else if (cardName.equalsIgnoreCase("bodyguard")) { // If the card is a bodyguard card. tempCard = new BodyguardCard(server); tempCard2 = new BodyguardCard(server); } else if (cardName.equalsIgnoreCase("troublemaker")) { // If the card is a troublemaker card. tempCard = new TroublemakerCard(server); tempCard2 = new TroublemakerCard(server); } else if(cardName.equalsIgnoreCase("seer")) { // If the card is a seer card. tempCard = new SeerCard(server); tempCard2 = new SeerCard(server); } else if(cardName.equalsIgnoreCase("cupid")) { // If the card is a cupid card. tempCard = new CupidCard(server); tempCard2 = new CupidCard(server); } else if(cardName.equalsIgnoreCase("minion")) { // If the card is a minion card. tempCard = new MinionCard(server); tempCard2 = new MinionCard(server); } else if(cardName.equalsIgnoreCase("drunk")) { // If the card is a drunk card. tempCard = new DrunkCard(server); tempCard2 = new DrunkCard(server); } else if(cardName.equalsIgnoreCase("doppelganger")) { // If the card is a doppelganger card. tempCard = new DoppelgangerCard(server); tempCard2 = new DoppelgangerCard(server); } else if(cardName.equalsIgnoreCase("cursed")) { // If the card is a cursed card. tempCard = new CursedCard(server); tempCard2 = new CursedCard(server); } else if(cardName.equalsIgnoreCase("dire wolf")) { // If the card is a dire wolf card. tempCard = new DireWolfCard(server); tempCard2 = new DireWolfCard(server); } else if(cardName.equalsIgnoreCase("hoodlum")) { // If the card is a hoodlum card. tempCard = new HoodlumCard(server); tempCard2 = new HoodlumCard(server); } else if(cardName.equalsIgnoreCase("wolf man")) { // If the card is a wolf man card. tempCard = new WolfManCard(server); tempCard2 = new WolfManCard(server); } else if(cardName.equalsIgnoreCase("wolf cub")) { // If the card is a wolf cub card. tempCard = new WolfCubCard(server); tempCard2 = new WolfCubCard(server); } else if(cardName.equalsIgnoreCase("lycan")) { // If the card is a lycan card. tempCard = new LycanCard(server); tempCard2 = new LycanCard(server); } else if(cardName.equalsIgnoreCase("hunter")) { // If the card is a hunter card. tempCard = new HunterCard(server); tempCard2 = new HunterCard(server); } else if(cardName.equalsIgnoreCase("mason")) { // If the card is a mason card. tempCard = new MasonCard(server); tempCard2 = new MasonCard(server); } else if(cardName.equalsIgnoreCase("diseased")) { // If the card is a diseased card. tempCard = new DiseasedCard(server); tempCard2 = new DiseasedCard(server); } else if(cardName.equalsIgnoreCase("prince")) { // If the card is a prince card. tempCard = new PrinceCard(server); tempCard2 = new PrinceCard(server); } else if(cardName.equalsIgnoreCase("apprentice seer")) { // If the card is an apprentice seer card. tempCard = new ApprenticeSeerCard(server); tempCard2 = new ApprenticeSeerCard(server); } else if(cardName.equalsIgnoreCase("pacifist")) { // If the card is a pacifist card. tempCard = new PacifistCard(server); tempCard2 = new PacifistCard(server); } else if(cardName.equalsIgnoreCase("village idiot")) { // If the card is a village idiot card. tempCard = new VillageIdiotCard(server); tempCard2 = new VillageIdiotCard(server); } else if(cardName.equalsIgnoreCase("old woman")) { // If the card is an old woman card. tempCard = new OldWomanCard(server); tempCard2 = new OldWomanCard(server); } else if(cardName.equalsIgnoreCase("huntress")) { // If the card is a huntress card. tempCard = new HuntressCard(server); tempCard2 = new HuntressCard(server); } else if(cardName.equalsIgnoreCase("tough guy")) { // If the card is a tough guy card. tempCard = new ToughGuyCard(server); tempCard2 = new ToughGuyCard(server); } else if(cardName.equalsIgnoreCase("paranormal investigator")) { // If the card is a paranormal investigator card. tempCard = new ParanormalInvestigatorCard(server); tempCard2 = new ParanormalInvestigatorCard(server); } else if(cardName.equalsIgnoreCase("insomniac")) { // If the card is an insomniac card. tempCard = new InsomniacCard(server); tempCard2 = new InsomniacCard(server); } else if(cardName.equalsIgnoreCase("witch")) { // If the card is a witch card. tempCard = new WitchCard(server); tempCard2 = new WitchCard(server); } else { // If the card is not recognized, throw an error to jump out of here. System.out.println("Card not recognized."); gameStart = false; throw new IllegalArgumentException(); } // Put the newly created card in the temp HashMap. temp.add(tempCard); // If this is the first iteration of this card, add it to the temp2 HashSet as well. if(!doneOnce) { temp2.add(tempCard2); // Make sure to set the done once flag to true. doneOnce = true; } } } // Once the program gets here, all lines have been read in the cards.txt file, and thus all cards are grabbed. scanner.close(); // Initialize the chooseCards HashSet for players to be assigned cards. server.chooseCards = new HashSet<Card>(); int i = 0; // Add all cards that were in the temp HashMap. for(Card card : temp) { server.chooseCards.add(card); i++; } // Initialize the cards Array. cards = new Card[temp2.size()]; i = 0; // Add all cards that were in the temp2 HashSet. for(Card card : temp2) { cards[i] = card; i++; } // Sort in order of rank for night wakeup. for(i = 0; i < cards.length - 1; i++) { for(int j = 0; j < cards.length - i - 1; j++) { if(cards[j].ranking > cards[j+1].ranking) { Card temp3 = cards[j]; cards[j] = cards[j + 1]; cards[j + 1] = temp3; } } } } } // A helper method to make sure that the server is no longer waiting for any players when needed. public void stopWaiting() { for (Player player : currentPlayers) { gameWaiting.replace(player.name, Boolean.FALSE); gameActions.replace(player.name, ""); } } // A helper method to send a message to all players in the server, so that even dead can follow along in the game. public void sendToAllPlayers(String message) throws IOException { for(Player player : players.values()) { player.output.writeObject(message); } } // A helper method used by other cards, including the Werewolf card, to check if a player is a type of werewolf public boolean checkWerewolf(Player player) { return player.card.cardName.contains("Werewolf") || player.card.cardName.contains("Dire Wolf") || player.card.cardName.contains("Wolf Cub") || player.card.cardName.contains("Wolf Man"); } // A helper method to sort for preCheck order public Card[] preCheckSort(Card[] checkCards) { // Sort in order of rank for night wakeup. for(int i = 0; i < checkCards.length - 1; i++) { for(int j = 0; j < checkCards.length - i - 1; j++) { if(checkCards[j].preCheckRank > checkCards[j+1].preCheckRank) { Card temp3 = checkCards[j]; checkCards[j] = checkCards[j + 1]; checkCards[j + 1] = temp3; } } } return checkCards; } // The helper method to run the timer for day voting. It will run the timer for the given time, and then if it returns // (the only way it doesn't is if the thread was interrupted), it will set all the player's votes who haven't voted // to no one public synchronized void timerHelper(int time) { // Get all the players so everyone is aware of how much time is left Player[] players2 = new Player[players.size()]; int i = 0; for(Player player : players.values()) { players2[i] = player; i++; } // Call the timer method for the alive players and the time given timer(time, players2); // If it gets here, that means the players ran out of time, so set all who haven't voted to vote for no one for(Player player : votes.keySet()) { if(votes.get(player).equals("") && !player.card.cardName.contains("Village Idiot")) { gameActions.replace(player.name, "no one"); try { Thread.sleep(500); } catch(Exception e) { System.out.println(); } } else if(votes.get(player).equals("") && player.card.cardName.contains("Village Idiot")) { String[] names = new String[currentPlayers.size()]; for(i = 0; i < currentPlayers.size(); i++) { Player temp = (Player)currentPlayers.toArray()[i]; names[i] = temp.name; } int random = rand.nextInt(currentPlayers.size()); gameActions.replace(player.name, names[random]); try { Thread.sleep(500); } catch(Exception e) { System.out.println(); } } } } // The timer for everything. Time is the amount of time, players are the players to tell when it's about to end public synchronized void timer(int time, Player[] players) { if(time < 0) { throw new IllegalArgumentException("Timer must be above 0"); } try { if (time <= 10000) { for(Player player : players) { player.output.writeObject("You have " + (time/1000) + " seconds to vote."); } Thread.sleep(time); } else { Thread.sleep(time - 10000); for(Player player : players) { player.output.writeObject("You have 10 seconds left."); } Thread.sleep(10000); } } catch(Exception e) { System.out.println(e.getMessage()); } } // A helper method to obtain the 2 neighbors of a player public Player[] neighborHelper(Player player) { if(neighbors == null) { throw new IllegalArgumentException("Neighbors weren't specified."); } // Check if there's enough people alive for neighbors to give anything int aliveCount = 0; for(Player neighbor : neighbors) { if(currentPlayers.contains(neighbor)) { aliveCount++; } } if(aliveCount < 3) { return new Player[]{player, player}; } Player[] result = new Player[2]; // If the requested player is dead, return null if(player.dead) { return null; } // Find the location of the player in the neighbors array int playerIndex = -1; for(int i = 0; i < neighbors.length; i++) { if(player == neighbors[i]) { playerIndex = i; break; } } // If they couldn't be found, return null if(playerIndex == -1) { return null; } // Find the neighbor right below the player int tempIndex = playerIndex - 1; while(result[0] == null) { if(tempIndex < 0) { // Loop around to top if it went off the bottom tempIndex = neighbors.length - 1; } if(currentPlayers.contains(neighbors[tempIndex])) { result[0] = neighbors[tempIndex]; } tempIndex--; } // Find the neighbor right above the player tempIndex = playerIndex + 1; while(result[1] == null) { if(tempIndex >= neighbors.length) { // Loop around to the bottom if it went off the top tempIndex = 0; } if(currentPlayers.contains(neighbors[tempIndex])) { result[1] = neighbors[tempIndex]; } tempIndex++; } return result; } }
alecb100/WerewolfCardGame
WerewolfServer.java
248,276
import java.util.LinkedList; import java.util.HashMap; class ElectionData { private LinkedList<String> ballot = new LinkedList<String>(); private HashMap<String, Integer> votes1stPlace = new HashMap<String, Integer>(); // Votes for first place for a candidate private HashMap<String, Integer> votes2ndPlace = new HashMap<String, Integer>(); // Votes for second place for a candidate private HashMap<String, Integer> votes3rdPlace = new HashMap<String, Integer>(); // Votes for third place for a candidate public ElectionData() {} // A method that takes three strings (for the first, second, and third choices, respectively) and returns void. // This method stores a single voter's choices in our data structure. public void processVote(String firstChoice, String secondChoice, String thirdChoice) throws UnknownCandidateException, DuplicateVotesException { if(ballot.contains(firstChoice) && ballot.contains(secondChoice) && ballot.contains(thirdChoice) && !(firstChoice.equals(secondChoice)) && !(secondChoice.equals(thirdChoice)) && !(firstChoice.equals(thirdChoice))) /* do checks (helpers) here... -2 to be exact..! */{ for(String key : votes1stPlace.keySet()) { if(key.equals(firstChoice)) { votes1stPlace.put(key, votes1stPlace.get(key) + 1 ); } } for(String key : votes2ndPlace.keySet()) { if(key.equals(secondChoice)) { votes2ndPlace.put(key, votes2ndPlace.get(key) + 1 ); } } for(String key : votes3rdPlace.keySet()) { if(key.equals(thirdChoice)) { votes3rdPlace.put(key, votes3rdPlace.get(key) + 1 ); } } } else if(!(ballot.contains(firstChoice))) { throw new UnknownCandidateException(firstChoice); } else if(!(ballot.contains(secondChoice))) { throw new UnknownCandidateException(secondChoice); } else if(!(ballot.contains(thirdChoice))) { throw new UnknownCandidateException(thirdChoice); } else if(firstChoice.equals(secondChoice)) { throw new DuplicateVotesException(firstChoice); } else if(secondChoice.equals(thirdChoice)) { throw new DuplicateVotesException(secondChoice); } else { throw new DuplicateVotesException(thirdChoice); } } // A method that takes one string (for the name of a candidate) and adds // the candidate to the ballot, returning void. public void addCandidate(String nameCan) throws CandidateExistsException { if(!(ballot.contains(nameCan))) { votes1stPlace.put(nameCan, 0); votes2ndPlace.put(nameCan, 0); votes3rdPlace.put(nameCan, 0); this.ballot.add(nameCan); } else { throw new CandidateExistsException(nameCan); } } //-------------------------------PRINTBALLOT---------------------------------------- public void printBallot() { System.out.println("The candidates are "); for (String s : ballot) { System.out.println(s); } } //------------------------COUNTING VOTES METHODS----------------------------------- // A method that returns the sum of all the // first place votes of all the candidates. private double helper(LinkedList<String> ballot) { double sum; sum = 0; for (String candidate : ballot) { sum = sum + votes1stPlace.get(candidate); } return sum; } // A method where winner is the candidate with more than 50% of first place votes. // If there is a tie for the most votes between two or more candidates, or if no // candidate receives more than 50% of the votes, return the string "Runoff required" public String findWinnerMostFirstVotes() { double percentage; double totalSum = helper(ballot); percentage = 0; for(String candidate : ballot) { percentage = votes1stPlace.get(candidate) / totalSum; if(percentage > (0.5)) { return candidate; } } return "Runoff required"; } // A method that returns the winner, where the winner is the candidate with the most // points gained from 1st, 2nd and 3rd place. If there is a tie between two or more // candidates, it returns the name of any one of the winners. public String findWinnerMostPoints() { int mostPoints = 0; int points = 0; // careful String winner = ballot.getFirst(); for(String candidate : ballot) { points = votes1stPlace.get(candidate) * 3 + votes2ndPlace.get(candidate) * 2 + votes3rdPlace.get(candidate); if(points > mostPoints) { mostPoints = points; winner = candidate; } } return winner; } }
FivosJKavassalis/WPI-CS-2102
hw6/ElectionData.java
248,278
/** * This class represents a comment left for a sales item on an online sales site. * A comment consists of a comment text, a rating (0 to 5), and an author name. Other users * can indicate whether the comment was useful or not (called 'upvoting' or * 'downvoting'). The balance between upvotes and downvotes is stored with comments. * A negative vote balance means that the comment received more downvotes than upvotes. * * @author Michael Kölling and David J. Barnes * @version 2016.02.29 */ public class Comment { private String author; private String text; private int rating; private int votes; /** * Create a comment with all necessary details. The initial vote balance is 0. */ public Comment(String author, String text, int rating) { this.author = author; this.text = text; this.rating = rating; votes = 0; } /** * Indicate that this comment is useful ('upvote'). This is used when a reader clicks * the 'Yes' button after the "Was this comment helpful?" quesion. */ public void upvote() { votes++; } /** * Indicate that this comment is not useful ('downvote'). This is used when a reader * clicks the 'No' button after the "Was this comment helpful?" quesion. */ public void downvote() { votes--; } /** * Return the author of this comment. * @return the author of this comment. */ public String getAuthor() { return author; } /** * Return the rating of this comment. */ public int getRating() { return rating; } /** * Return the vote count (balance of up and down-votes). */ public int getVoteCount() { return votes; } /** * Return the full text and details of the comment, including * the comment text, author and rating. */ public String getFullDetails() { String details = "Rating: " + "*****".substring(0,rating) + " " + "By: " + author + "\n" + " " + text + "\n"; // Note: 'votes' is currently included for testing purposes only. In the final // application, this will not be shown. Instead, the vote count will be used to // select and order the comments on screen. details += "(Voted as helpful: " + votes + ")\n"; return details; } }
astyve/Forelesning-uke-10-2
Comment.java
248,279
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import java.util.Scanner; enum DistanceFunction { BAG, SET, WEIGHTED_BAG, WEIGHTED_JACCARD } enum VoteFunction { EQUAL, DISTANCESQ, SCALEDDIST } // WEIGHTED_JACCARD, DISTANCESQ = 91.075% (k = 10, cutoff = 1) //WEIGHTED_JACCARD, DISTANCESQ = 92.4% (k = 10, cutoff = 2) // Using leave one out public class Main { public static HashSet<String> ingredients; public static HashMap<String, Ingredient> ingredientInfo; public static HashSet<String> tabooList; static ArrayList<Recipe> trainingData; public static int k = 10; public static int minCutOff = 2; public static double minDist; public static String trainingFile = "training-data.txt"; public static PriorityQueue<Recipe> neighbors; public static DistanceFunction df = DistanceFunction.WEIGHTED_JACCARD; public static VoteFunction vf = VoteFunction.DISTANCESQ; public static void main(String[] args) throws IOException { tabooList = new HashSet<String>(); ingredientInfo = new HashMap<>(); ingredients = new HashSet<String>(); buildTabooList(); readTrainingSet(); System.out.println("Taboo List: " + tabooList.size() + ", IngrientInfo: " + ingredientInfo.size()); crossValidate(); //runOnTestData(); } public static void buildTabooList() throws IOException { tabooList = new HashSet<String>(); BufferedReader br = new BufferedReader(new FileReader(new File(trainingFile))); String line; while ((line = br.readLine()) != null) { if (line.length() == 2) { System.err.println("Found bad data"); continue; } int cuisine = Character.getNumericValue(line.charAt(0)); List<String> ingr = Arrays.asList(line.substring(1).trim().split(" ")); ingredients.addAll(ingr); for (String i : ingr) { if(ingredientInfo.containsKey(i)){ ingredientInfo.get(i).increment(cuisine); } else { ingredientInfo.put(i, new Ingredient(i, cuisine)); } } } br.close(); for (String ingr : ingredients) { if(ingredientInfo.get(ingr).totalCount < minCutOff) { tabooList.add(ingr); } } } public static void readTrainingSet() { trainingData = new ArrayList<Recipe>(); try { BufferedReader br = new BufferedReader(new FileReader(new File(trainingFile))); String line; int recipeNum = 0; while ((line = br.readLine()) != null) { if (line.length() == 2) { System.err.println("Found bad data"); continue; } trainingData.add(new Recipe(true, line, recipeNum)); recipeNum++; } br.close(); } catch (IOException e) { e.printStackTrace(); } } public static int calculateVotes() { int cuisine = 1; double[] votes = new double[8]; double maxVotes; double maxDist; switch (vf){ case EQUAL: while (neighbors.peek() != null) { votes[neighbors.poll().cuisine]++; } break; case DISTANCESQ: while (neighbors.peek() != null) { Recipe current = neighbors.poll(); votes[current.cuisine] += (1/Math.pow(current.distance,2)); } break; case SCALEDDIST: maxDist = neighbors.peek().distance; while (neighbors.peek() != null) { Recipe current = neighbors.poll(); votes[current.cuisine] += (maxDist - current.distance)/(maxDist - minDist); } break; } maxVotes = votes[1]; for (int i = 2; i < 8; i++) { if (votes[i] > maxVotes) { maxVotes = votes[i]; cuisine = i; } } return cuisine; } public static void crossValidate() { int total = 0; int correct = 0; Collections.shuffle(trainingData); for (int i = 0 ; i < trainingData.size(); i++) { neighbors = new PriorityQueue<Recipe>(k); minDist = 9999; for (int j = 0; j < trainingData.size(); j++) { if (i == j) { continue; } double distance = trainingData.get(j).getDistance(trainingData.get(i)); minDist = minDist < distance ? minDist : distance; if (neighbors.size() < k) { neighbors.add(trainingData.get(j)); } else { if (neighbors.peek().distance > distance) { neighbors.poll(); neighbors.add(trainingData.get(j)); } } } // vote int prediction = calculateVotes(); // check accuracy if (prediction == (trainingData.get(i).cuisine)) { correct++; } else { System.out.println("Predicted : " + prediction + ", for: " + trainingData.get(i)); } total++; if (total % 500 == 0) { System.err.println(total + " " + (double)correct / total); } } System.out.println((double)correct / total); } public static void runOnTestData() { Scanner sc = new Scanner(System.in); String line; while ((line = sc.nextLine()) != null) { Recipe current = new Recipe(false, line, 0); neighbors = new PriorityQueue<Recipe>(k); minDist = 1; for (int j = 0; j < trainingData.size(); j++) { double distance = trainingData.get(j).getDistance(current); minDist = minDist < distance ? minDist : distance; if (neighbors.size() < k) { neighbors.add(trainingData.get(j)); } else { if (neighbors.peek().distance > distance) { neighbors.poll(); neighbors.add(trainingData.get(j)); } } } // vote System.out.println(calculateVotes()); } sc.close(); } }
Akiira/KNN
src/Main.java
248,282
/* * Copyright (C) 2021-2023 by the Widelands Development Team * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package wl.utils; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Stream; /** * Miscellaneous utility functions. */ public class Utils { private Utils() {} private static class ChecksummedFile { public final File file; public final String cachedChecksum; public ChecksummedFile(File f) { file = f; cachedChecksum = cs(); } private String cs() { return file.isFile() ? checksum(file) : ""; } @Override public boolean equals(Object o) { if (!(o instanceof ChecksummedFile)) return false; ChecksummedFile c = (ChecksummedFile)o; if (!c.file.equals(file)) return false; String newCS = cs(); return cachedChecksum.equals(newCS) && c.cachedChecksum.equals(newCS); } } /** * Print log output to standard output. * Output is formatted with a timestamp and the thread name. * @param msg Text to print. */ public static void log(String msg) { System.out.println("[" + new Date() + " @ " + Thread.currentThread().getName() + "] " + msg); } /** * Which database to use for an SQL command. */ public static enum Databases { /** * The read-only website database, which contains details about registered users. */ kWebsite("website_database", "website_db_user", "website_db_password"), /** * The add-ons database, which contains moddable metadata about all add-ons. */ kAddOns("addons_database", "addons_db_user", "addons_db_password"); /** The key in the config file that is mapped to this database name. */ public final String dbName; /** The key in the config file that is mapped to this database user. */ public final String user; /** The key in the config file that is mapped to this database password. */ public final String password; private Databases(String db, String user, String password) { this.dbName = db; this.user = user; this.password = password; } } private static final Connection[] _databases = new Connection[Databases.values().length]; /** * Initialize the databases. Call this only on startup. * @throws Exception If anything at all goes wrong, throw an Exception. */ public static void initDatabases() throws Exception { log("Initializing SQL..."); for (Databases db : Databases.values()) { _databases[db.ordinal()] = DriverManager.getConnection("jdbc:mysql://" + config("databasehost") + ":" + config("databaseport") + "/" + config(db.dbName), config(db.user), config(db.password)); } } /** * Execute an SQL statement. Use placeholders for all parameters to prevent SQL injection. * @param db Database to use. * @param query Statement to execute. Use '?' for placeholders. * @param values Values to substitute for the placeholders. * @return The result of the query for SELECT statements; null for other statements. * @throws Exception If anything at all goes wrong, throw an Exception. */ public static ResultSet sql(Databases db, String query, Object... values) throws Exception { Connection c = _databases[db.ordinal()]; synchronized (c) { PreparedStatement s = c.prepareStatement(query); for (int i = 0; i < values.length; i++) s.setObject(i + 1, values[i]); return s.execute() ? s.getResultSet() : null; } } /** * Retrieve the name of a user from the database. * @param id The user's ID. * @return The user's name. * @throws Exception If anything at all goes wrong, throw an Exception. */ public static String getUsername(long id) throws Exception { ResultSet r = sql(Databases.kWebsite, "select username from auth_user where id=?", id); if (!r.next()) return null; return r.getString("username"); } /** * Retrieve the ID of a user from the database. * @param name The user's name. * @return The user's ID. * @throws Exception If anything at all goes wrong, throw an Exception. */ public static Long getUserID(String name) throws Exception { ResultSet r = sql(Databases.kWebsite, "select id from auth_user where username=?", name); if (!r.next()) return null; return r.getLong("id"); } /** * Check if a user disabled e-mail notifications in their website settings. * @param user The user's ID. * @param notice The notice type ID. * @return The user disabled this type of notification. * @throws Exception If anything at all goes wrong, throw an Exception. */ public static boolean checkUserDisabledNotifications(long user, long notice) throws Exception { ResultSet sql = sql( Databases.kWebsite, "select send from notification_noticesetting where user_id=? and medium=1 and notice_type_id=?", user, notice); return sql.next() && sql.getShort("send") < 1; } /** * Retrieve the ID of an add-on from the database. * @param name The add-on's name. * @return The add-on's ID. * @throws Exception If anything at all goes wrong, throw an Exception. */ public static Long getAddOnID(String name) throws Exception { ResultSet r = sql(Databases.kAddOns, "select id from addons where name=?", name); if (!r.next()) return null; return r.getLong("id"); } /** * Retrieve the name of an add-on from the database. * @param id The add-on's ID. * @return The add-on's name. * @throws Exception If anything at all goes wrong, throw an Exception. */ public static String getAddOnName(long id) throws Exception { ResultSet r = sql(Databases.kAddOns, "select name from addons where id=?", id); if (!r.next()) return null; return r.getString("name"); } /** * Check whether a given user is one of the uploaders for a given add-on. * If the add-on does not exist, the user is assumed to have permission to create it. * @param addon The add-on's name. * @param userID The user's ID. * @return The user has write access to the add-on. * @throws Exception If anything at all goes wrong, throw an Exception. */ public static boolean isUploader(String addon, long userID) throws Exception { ResultSet sql = sql(Databases.kAddOns, "select user from uploaders where addon=?", getAddOnID(addon)); boolean noUploaders = true; while (sql.next()) { if (sql.getLong("user") == userID) { return true; } noUploaders = false; } return noUploaders; } /** * Retrieve the voting statistics of an add-on from the database. * @param addon The add-on's ID. * @return An array of size 10 with the number of i votes in index i-1. * @throws Exception If anything at all goes wrong, throw an Exception. */ public static long[] getVotes(long addon) throws Exception { ResultSet sql = sql(Databases.kAddOns, "select vote from uservotes where addon=?", addon); long[] votes = new long[10]; for (int i = 0; i < votes.length; i++) votes[i] = 0; while (sql.next()) votes[sql.getInt("vote") - 1]++; return votes; } /** * Retrieve the list of uploaders of an add-on from the database. * @param addon The add-on's ID. * @param onlyFirst List at most one uploader in the result. * @return Comma-separated of the uploaders. * @throws Exception If anything at all goes wrong, throw an Exception. */ public static String getUploadersString(long addon, boolean onlyFirst) throws Exception { ResultSet sql = sql(Databases.kAddOns, "select user from uploaders where addon=?", addon); String uploaders = ""; while (sql.next()) { if (!uploaders.isEmpty()) uploaders += ","; uploaders += getUsername(sql.getLong("user")); if (onlyFirst) break; } return uploaders; } /** * List all files in a directory, sorted alphabetically. * @param dir Directory to list. * @return Sorted array (never null). */ public static File[] listSorted(File dir) { File[] files = dir.listFiles(); if (files == null) return new File[0]; Arrays.sort(files); return files; } /** * Recursively list all Widelands maps in a directory. * @param dir Directory to search. * @return List of found maps. * @throws Exception If the directory can not be traversed. */ public static List<File> findMaps(File dir) throws Exception { List<File> maps = new ArrayList<>(); Stream<Path> walkStream = Files.walk(dir.toPath()); walkStream.forEach(f -> { File file = f.toFile(); if (file.getName().endsWith(".wmf")) maps.add(file); }); return maps; } /** * Compute the md5 checksum of a regular file. * @param f File to checksum. * @return The checksum as string, or "" in case of an error. */ public static String checksum(File f) { try { Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(new String[] {"md5sum", f.getPath()}); BufferedReader reader = new BufferedReader(new InputStreamReader(pr.getInputStream())); pr.waitFor(); String md5 = reader.readLine(); return md5.split(" ")[0]; } catch (Exception e) { log("ERROR checksumming '" + (f == null ? "(null)" : f.getPath()) + "': " + e); e.printStackTrace(); } return ""; } /** * Run a shell script, and echo the whole script and its output to standard output. * @param args The command and its arguments. * @return The exit status of the command. * @throws Exception If the shell can't be accessed. */ public static int bash(String... args) throws Exception { String logString = " $"; for (String a : args) logString += " " + a; log(logString); ProcessBuilder pb = new ProcessBuilder(args); pb.redirectErrorStream(true); Process p = pb.start(); BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream())); String str; while ((str = b.readLine()) != null) log(" # " + str); p.waitFor(); int e = p.exitValue(); log(" = " + e); return e; } /** * Run a shell script and return its standard output. * The standard error and exit value are discarded. * @param args The command and its arguments. * @return The output. * @throws Exception If the shell can't be accessed. */ public static String bashOutput(String... args) throws Exception { Process p = new ProcessBuilder(args).start(); BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream())); String str, result = null; while ((str = b.readLine()) != null) { if (result == null) { result = str; } else { result += "\n"; result += str; } } return (result == null ? "" : result); } /** * Run a shell script and return its exit value. * The standard output and error are discarded. * @param args The command and its arguments. * @return The output. * @throws Exception If the shell can't be accessed. */ public static int bashResult(String... args) throws Exception { Process p = new ProcessBuilder(args).start(); p.waitFor(); return p.exitValue(); } /** * Format a time string. * @param millis Number of milliseconds. * @return Formatted time string. */ public static String durationString(long millis) { long hours = millis / (1000 * 60 * 60); millis -= hours * 1000 * 60 * 60; long minutes = millis / (1000 * 60); millis -= minutes * 1000 * 60; long seconds = millis / 1000; millis -= seconds * 1000; String str = millis + "ms"; if (seconds == 0) return str; str = seconds + "s " + str; if (minutes == 0) return str; str = minutes + "min " + str; if (hours == 0) return str; return hours + "h " + str; } /** * Class to represent a user's comment on an add-on. */ public static class AddOnComment { /** This comment's unique ID. */ public final long commentID; /** The ID of the user who created this comment. */ public final long userID; /** The timestamp when this comment was created. */ public final long timestamp; /** The ID of the user who last edited this comment (may be null). */ public final Long editorID; /** The timestamp when this comment was last edited (may be null). */ public final Long editTimestamp; /** Version of the add-on about which the comment was written. */ public final String version; /** Text of the comment. */ public final String message; /** * Constructor. * @param commentID This comment's unique ID. * @param userID ID of the comment author. * @param timestamp Timestamp when the comment was created. * @param editorID ID of the last person who edited the comment (may be null). * @param editTimestamp Timestamp when the comment was last edited (may be null). * @param version Version of the add-on about which the comment was written. * @param message Text of the comment. */ public AddOnComment(long commentID, long userID, long timestamp, Long editorID, Long editTimestamp, String version, String message) { this.commentID = commentID; this.userID = userID; this.timestamp = timestamp; this.editorID = editorID; this.editTimestamp = editTimestamp; this.version = version; this.message = message; } } /** * Class to represent a key-value pair of an ini-style file. */ public static class Value { /** The key to which this value is mapped. */ public final String key; /** The raw, untranslated value. */ public final String value; /** The textdomain to use for translating (null for non-translatable strings). */ public final String textdomain; /** * Return the localized value. If this Value is not localizable, returns the raw value. * @param locale Locale to use. * @return Localized value. */ public String value(String locale) { if (textdomain == null || textdomain.isEmpty()) return value; try { return new BufferedReader( new InputStreamReader( Runtime.getRuntime() .exec(new String[] { "bash", "-c", "TEXTDOMAINDIR=./i18n/ TEXTDOMAIN=" + textdomain + " LANGUAGE=" + locale + " gettext -s \"" + value.replaceAll("\"", "\\\"") + "\""}) .getInputStream())) .readLine(); } catch (Exception e) { log("WARNING: gettext error for '" + key + "'='" + value + "' @ '" + textdomain + "' / '" + locale + "': " + e); e.printStackTrace(); return value; } } /** * Constructor for a non-translatable value. * @param k ini file key. * @param v Raw value. */ public Value(String k, String v) { this(k, v, null); } /** * Constructor for a translatable value. * @param k ini file key. * @param v Raw value. * @param t Textdomain for translation. */ public Value(String k, String v, String t) { key = k; value = v; textdomain = t; } } /** Wrapper around the contents of an ini-style file. */ public static class Profile { /** The name of the global section in an add-ons main file. */ public static final String kGlobalSection = "[global]"; /** A section in a Profile. */ public static class Section { /** The name of this section (may be "" for files without section divisions). */ public final String name; /** The actual contents of the file. */ public final Map<String, Value> contents; /** * Constructor. * @param n Name of the section. */ public Section(String n) { name = n; contents = new TreeMap<>(); } } private final Map<String, Section> sections; /** Default constructor. */ public Profile() { sections = new TreeMap<>(); } /** * Add a new section to the profile. * @param s The section to add. */ public void add(Section s) { sections.put(s.name, s); } /** * Dump this profile to a file. * @param out Stream to print to. */ public void write(PrintStream out) { out.println("# Automatically created by the Widelands Add-Ons Server."); for (Section s : sections.values()) { out.println(); if (!s.name.isEmpty()) out.println(s.name); for (String key : s.contents.keySet()) { out.print(key); out.print("="); Value v = s.contents.get(key); if (v == null || v.value == null || v.value.isEmpty()) { out.println(); continue; } if (v.textdomain != null) out.print("_"); out.print("\""); out.print(v.value); out.println("\""); } } } /** * Look up a value in this profile. * @param section The name of the section in which to look * (needs to be enclosed in square brackets). * @param key The key of the entry. * @return The value, or null if it is not present. */ public Value get(String section, String key) { Section s = sections.get(section); if (s == null) return null; return s.contents.get(key); } /** * Look up a value in this profile's global section. * @param key The key of the entry. * @return The value, or null if it is not present. */ public Value get(String key) { Value v = get("", key); if (v != null) return v; return get(kGlobalSection, key); } /** * Look up a section in this profile. Creates the section if it doesn't exist yet. * @param name The name of the section. * @return The section, or null if it is not present. */ public Section getSection(String name) { if (sections.containsKey(name)) return sections.get(name); Section s = new Section(name); add(s); return s; } } private static final Map<ChecksummedFile, Profile> _staticprofiles = new HashMap<>(); /** * Parse an ini-style file and return its contents as a map of key-value pairs. * @param f File to parse. * @param textdomain Textdomain for translatable strings in the file * (may be null if the file is not meant to be translated). * @return The key-value pairs. * @throws Exception If anything at all goes wrong, throw an Exception. */ synchronized public static Profile readProfile(File f, String textdomain) throws Exception { ChecksummedFile key = new ChecksummedFile(f); if (_staticprofiles.containsKey(key)) return _staticprofiles.get(key); Profile profile; if (f.isFile()) { profile = readProfile(Files.readAllLines(f.toPath()), textdomain); } else { profile = new Profile(); } _staticprofiles.put(key, profile); return profile; } /** * Parse an ini-style file and return its contents as a map of key-value pairs. * @param stream Stream to read from. * @param textdomain Textdomain for translatable strings in the file * (may be null if the file is not meant to be translated). * @return The key-value pairs. * @throws Exception If anything at all goes wrong, throw an Exception. */ synchronized public static Profile readProfile(InputStream stream, String textdomain) throws Exception { List<String> lines = new ArrayList<>(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); for (;;) { String str = reader.readLine(); if (str == null) break; lines.add(str); } return readProfile(lines, textdomain); } /** * Parse an ini-style file and return its contents as a map of key-value pairs. * @param lines All lines in the file. * @param textdomain Textdomain for translatable strings in the file * (may be null if the file is not meant to be translated). * @return The key-value pairs. * @throws Exception If anything at all goes wrong, throw an Exception. */ synchronized public static Profile readProfile(List<String> lines, String textdomain) throws Exception { Profile profile = new Profile(); Profile.Section section = new Profile.Section(""); for (int lineNr = 0; lineNr < lines.size(); ++lineNr) { String line = lines.get(lineNr).trim(); if (line.isEmpty() || line.startsWith("#")) continue; // Comment if (line.startsWith("[") && line.endsWith("]")) { // Section if (!section.contents.isEmpty()) profile.add(section); section = new Profile.Section(line); continue; } String[] str = line.split("="); for (int i = 0; i < str.length; i++) str[i] = str[i].trim(); if (str.length < 2) { // Empty value if (str.length == 1) section.contents.put(str[0], new Value(str[0], "")); continue; } String arg = str[1]; for (int i = 2; i < str.length; ++i) arg += "=" + str[i]; boolean localize = false; if (arg.startsWith("_")) { // Translatable arg = arg.substring(1).trim(); localize = true; } if (arg.startsWith("\"\"")) { // Double-quoted multi-line string arg = arg.substring(2); for (;;) { if (arg.endsWith("\"\"")) { // End of multi-line string arg = arg.substring(0, arg.length() - 2); break; } if (arg.endsWith("\"")) arg = arg.substring(0, arg.length() - 1); ++lineNr; // Fetch next line line = lines.get(lineNr).trim(); if (line.startsWith("\"")) line = line.substring(1); arg += "<br>" + line; } } else if (arg.startsWith("\"")) { // Quoted single-line string arg = arg.substring(1); if (arg.endsWith("\"")) arg = arg.substring(0, arg.length() - 1); } section.contents.put( str[0], new Value(str[0], arg, localize ? textdomain == null ? "" : textdomain : null)); } profile.add(section); return profile; } /** * Overwrite an ini-style file. * @param f File to use. * @param profile New profile to write. * @throws Exception If anything at all goes wrong, throw an Exception. */ synchronized public static void editProfile(File f, Profile profile) throws Exception { f.getParentFile().mkdirs(); PrintStream out = new PrintStream(f); profile.write(out); out.close(); } /** * Retrieve a value from the server config file. * @param key Key to look up. * @return The configured value. * @throws Exception If anything at all goes wrong, throw an Exception. */ public static String config(String key) throws Exception { return readProfile(new File("config"), null).get(key).value; } /** * Recursively calculate the total file size of a directory. * @param dir Directory to iterate. * @return The total size in bytes. */ public static long filesize(File dir) { long l = 0; for (File f : listSorted(dir)) { if (f.isDirectory()) l += filesize(f); else l += f.length(); } return l; } /** * Send an e-mail. * @param email E-Mail address of the recipient. * @param subject Subject line of the mail. * @param body Message text to send. * @param footer Whether to append a footer with a link to the notifications settings. * @throws Exception If anything at all goes wrong, throw an Exception. */ public static void sendEMail(String email, String subject, String body, boolean footer) throws Exception { File message = Files.createTempFile(null, null).toFile(); PrintWriter write = new PrintWriter(message); write.println("From: [email protected]"); write.println("Subject: " + subject); write.println(); write.println(body); if (footer) { write.print( "\n-------------------------\n" + "To change how you receive notifications, please go to https://www.widelands.org/addons/."); } write.close(); bash("bash", "-c", "ssmtp '" + email + "' < " + message.getAbsolutePath()); message.delete(); } /** Denotes that an e-mail notification is of critical importance. */ public static final int kEMailVerbosityCritical = 1; /** Denotes that an e-mail notification is of low importance. */ public static final int kEMailVerbosityFYI = 2; /** * Send a notification to all subscribed admins. * @param verbosity {@link #kEMailVerbosityCritical} or {@link #kEMailVerbosityFYI}. * @param subject Subject line of the mail. * @param msg Message text to send. * @throws Exception If anything at all goes wrong, throw an Exception. */ public static void sendEMailToSubscribedAdmins(int verbosity, String subject, String msg) throws Exception { ResultSet sql = sql(Databases.kAddOns, "select email,level from notifyadmins"); while (sql.next()) { if (sql.getInt("level") >= verbosity) { sendEMail(sql.getString("email"), subject, msg, false); } } } }
widelands/wl_addons_server
wl/utils/Utils.java
248,283
/*An election is contested by 5 candidates. The candidates are numbered 1 to 5 and the voting is done by marking the candidate number on the ballot paper. Write a program to read the ballots and count the votes cast for each candidate using an array variable count. In case a number read is outside the range of 1-5, the ballot should be considered as a spoilt ballot. The program should finally count the number of votes for each candidate along with a count of spoilt votes.*/ import java.util.*; public class Pgm1{ int votes[]; public static void main(String args[]) { int v1=0; int v2=0; int v3=0; int v4=0; int v5=0; Scanner sc= new Scanner(System.in); System.out.println("Enter the number of ballots: "); int n1=sc.nextInt(); int[] votes=new int[n1]; int spoiltBallot=0; for (int i=0; i<n1;i++){ System.out.println("Enter your choice[1-5]:"); int newVote=sc.nextInt(); if (newVote>5){spoiltBallot++;} else{votes[i]=newVote;}} for (int j=0;j<votes.length;j++){ if (votes[j]==1){ v1++; } else if (votes[j]==2){ v2++; } else if (votes[j]==3){ v3++; } else if (votes[j]==4){ v4++; } else { v5++; } } System.out.println("Number of votes for candidate 1:"+v1); System.out.println("Number of votes for candidate 2:"+v2); System.out.println("Number of votes for candidate 3:"+v3); System.out.println("Number of votes for candidate 4:"+v4); System.out.println("Number of votes for candidate 5:"+v5); System.out.println("Number of spoitBallot:"+spoiltBallot); sc.close(); } }
Sanober494/OOPs_Codes
Lab5/Pgm1.java
248,285
/** * Represents a candidate in the Antarctica election process. * * @author Lyndon While * @version 1.0 2020 */ public class Candidate { // their name private String name; // their number of votes private int noOfVotes; // their number of first places private double noOfWins; /** * Constructor for objects of class Candidate. */ public Candidate(String name) { this.name = name; } /** * Returns the candidate's name. */ public String getName() { // TODO 7 return name; } /** * Returns the number of votes obtained by the candidate. */ public int getNoOfVotes() { // TODO 8 return noOfVotes; } /** * Returns the number of wins obtained by the candidate. */ public double getNoOfWins() { // TODO 9 return noOfWins; } /** * Adds n votes to the candidate. */ public void addToCount(int n) { // TODO 10 noOfVotes+=n; } /** * Adds n wins to the candidate. */ public void addToWins(double n) { noOfWins+=n; } /** * Returns a string reporting the candidate's result, * rounding the number of wins to the nearest integer. * See the sample output files for the required format. */ public String getStanding() { // TODO 12 int roundednoOfWins = (int) Math.round(noOfWins); return name + " got " + noOfVotes + " votes and "+ roundednoOfWins + " wins"; } }
anantchhabda/Project-Election_Stimulator
Candidate.java
248,286
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class Admin { private String username = "Admin371"; private String password = "naaMg"; private static int totalVotes; // Constructor public Admin(String username, String password) { this.username = username; this.password = password; this.totalVotes = 0; } // Method to read candidate votes from a file public static int candidatesVotes(String candidate) { int votes = 0; try (BufferedReader br = new BufferedReader(new FileReader(candidate + ".txt"))) { br.readLine(); // Skip the first line (manifest) votes = Integer.parseInt(br.readLine()); // Read the number of votes } catch (IOException e) { e.printStackTrace(); } return votes; } // Method to view voter information from a file public static String viewVoter(String voter) { StringBuilder voterInfo = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader("Voters_Info/" + voter + ".txt"))) { String line; while ((line = br.readLine()) != null) { voterInfo.append(line).append("\n"); } } catch (IOException e) { e.printStackTrace(); } return voterInfo.toString(); } // Method to calculate the total votes of all candidates public static int totalVotes() { totalVotes = 0; Path dir = Paths.get("."); // Current directory try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "Candidate-*.txt")) { for (Path entry : stream) { totalVotes += candidatesVotes(entry.toString().replace(".txt", "")); } } catch (IOException e) { e.printStackTrace(); } return totalVotes; } // Method to declare the winner public static String declare() { Path dir = Paths.get("."); // Current directory int highestVotes = -1; String winner = "No candidates found"; try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "Candidate-*.txt")) { for (Path entry : stream) { String candidate = entry.toString().replace(".txt", ""); int candidateVotes = candidatesVotes(candidate); candidate = candidate.replace("./", ""); if (candidateVotes > highestVotes) { highestVotes = candidateVotes; winner = candidate; } } } catch (IOException e) { e.printStackTrace(); } return "The winner is " + winner + " with " + highestVotes + " votes."; } public static void main(String[] args) { System.out.println(candidatesVotes("Candidate-1")); System.out.println(viewVoter("viswa")); System.out.println(totalVotes()); System.out.println(declare()); } }
KarthikeyaSai/Voting-Sys
src/Admin.java
248,291
import com.google.common.collect.Lists; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class du extends eb { private static final Logger b = ; private List<eb> c = Lists.newArrayList(); private byte d = 0; void a(DataOutput ☃) throws IOException { if (!this.c.isEmpty()) { this.d = ((eb)this.c.get(0)).a(); } else { this.d = 0; } ☃.writeByte(this.d); ☃.writeInt(this.c.size()); for (int ☃ = 0; ☃ < this.c.size(); ☃++) { ((eb)this.c.get(☃)).a(☃); } } void a(DataInput ☃, int ☃, dw ☃) throws IOException { ☃.a(296L); if (☃ > 512) { throw new RuntimeException("Tried to read NBT tag with too high complexity, depth > 512"); } this.d = ☃.readByte(); int ☃ = ☃.readInt(); if ((this.d == 0) && (☃ > 0)) { throw new RuntimeException("Missing type on ListTag"); } ☃.a(32L * ☃); this.c = Lists.newArrayListWithCapacity(☃); for (int ☃ = 0; ☃ < ☃; ☃++) { eb ☃ = eb.a(this.d); ☃.a(☃, ☃ + 1, ☃); this.c.add(☃); } } public byte a() { return 9; } public String toString() { StringBuilder ☃ = new StringBuilder("["); for (int ☃ = 0; ☃ < this.c.size(); ☃++) { if (☃ != 0) { ☃.append(','); } ☃.append(☃).append(':').append(this.c.get(☃)); } return ']'; } public void a(eb ☃) { if (☃.a() == 0) { b.warn("Invalid TagEnd added to ListTag"); return; } if (this.d == 0) { this.d = ☃.a(); } else if (this.d != ☃.a()) { b.warn("Adding mismatching tag types to tag list"); return; } this.c.add(☃); } public void a(int ☃, eb ☃) { if (☃.a() == 0) { b.warn("Invalid TagEnd added to ListTag"); return; } if ((☃ < 0) || (☃ >= this.c.size())) { b.warn("index out of bounds to set tag in tag list"); return; } if (this.d == 0) { this.d = ☃.a(); } else if (this.d != ☃.a()) { b.warn("Adding mismatching tag types to tag list"); return; } this.c.set(☃, ☃); } public eb a(int ☃) { return (eb)this.c.remove(☃); } public boolean c_() { return this.c.isEmpty(); } public dn b(int ☃) { if ((☃ < 0) || (☃ >= this.c.size())) { return new dn(); } eb ☃ = (eb)this.c.get(☃); if (☃.a() == 10) { return (dn)☃; } return new dn(); } public int[] c(int ☃) { if ((☃ < 0) || (☃ >= this.c.size())) { return new int[0]; } eb ☃ = (eb)this.c.get(☃); if (☃.a() == 11) { return ((ds)☃).c(); } return new int[0]; } public double d(int ☃) { if ((☃ < 0) || (☃ >= this.c.size())) { return 0.0D; } eb ☃ = (eb)this.c.get(☃); if (☃.a() == 6) { return ((dp)☃).g(); } return 0.0D; } public float e(int ☃) { if ((☃ < 0) || (☃ >= this.c.size())) { return 0.0F; } eb ☃ = (eb)this.c.get(☃); if (☃.a() == 5) { return ((dr)☃).h(); } return 0.0F; } public String f(int ☃) { if ((☃ < 0) || (☃ >= this.c.size())) { return ""; } eb ☃ = (eb)this.c.get(☃); if (☃.a() == 8) { return ☃.a_(); } return ☃.toString(); } public eb g(int ☃) { if ((☃ < 0) || (☃ >= this.c.size())) { return new dq(); } return (eb)this.c.get(☃); } public int c() { return this.c.size(); } public eb b() { du ☃ = new du(); ☃.d = this.d; for (eb ☃ : this.c) { eb ☃ = ☃.b(); ☃.c.add(☃); } return ☃; } public boolean equals(Object ☃) { if (super.equals(☃)) { du ☃ = (du)☃; if (this.d == ☃.d) { return this.c.equals(☃.c); } } return false; } public int hashCode() { return super.hashCode() ^ this.c.hashCode(); } public int f() { return this.d; } }
Tominous/LabyMod-1.8
du.java
248,305
interface AnimalInterface { void Speak(); } class Duck implements AnimalInterface { @Override public void Speak(){ System.out.println("Duck says Pack-pack"); } } class Tiger implements AnimalInterface { @Override public void Speak() { System.out.println("Tiger says Halum-Halum"); } } ----------------------------------------------------------- public abstract class AnimalFactoryInterface { public abstract AnimalInterface GetAnimalType(String type) throws Exception; } class ConcreteFactory extends AnimalFactoryInterface { @Override public AnimalInterface GetAnimalType (String type) throws Exception { switch(type) { case "Duck": return new Duck(); case "Tiger": return new Tiger(); default: throw new Exception("Animal type: " + type + " cannot be instantiated"); } } } ------------------------------------------------------------- public class Client { public static void main(String [] args) throws Exception { System.out.println("***Factory Pattern Demo***\n"); AnimalFactoryInterface animalFactory = new ConcreteFactory(); AnimalInterface duckType = animalFactory.GetAnimalType("Duck"); duckType.Speak(); AnimalInterface tigerType = animalFactory.GetAnimalType("Tiger"); tigerType.Speak(); AnimalInterface lionType = animalFactory.GetAnimalType("Lion"); lionType.Speak(); } }
sijoonlee/java-design-patterns
16.java
248,337
class Solution { public int removeDuplicates(int[] nums) { int start = 0; int end = 0; while(end < nums.length){ if(nums[start]!=nums[end]){ nums[++start] = nums[end++]; continue; } end++; } return start+1; } }
iamtanbirahmed/100DaysOfLC
26.java
248,343
public class Problem26 { public int removeDuplicates(int[] nums) { /*boolean[] b = new boolean[201]; for (int i: nums) b[i+100] = true; int counter = 0; for (int i = 0; i < b.length; i++) if (b[i]){ nums[counter] = i-100; counter++; } return counter; */ if (nums.length < 2) return nums.length; int totCount = 0, curr = nums[0]; for (int i = 1; i < nums.length; i++){ if (nums[i] == curr) totCount++; else curr = nums[i]; nums[i-totCount] = nums[i]; } return nums.length-totCount; } }
rkibel/LeetCode
26.java
248,344
class Solution { public int removeDuplicates(int[] nums) { if (nums.length==0){ return 0; } int index=0; for (int i=0; i<nums.length; i++){ if (nums[i]!=nums[index]){ index++; nums[index]=nums[i]; } } return index+1; } }
mikelyy/Leetcode
26.java
248,345
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode current=head; while (current!=null && current.next!=null){ if (current.val==current.next.val){ current.next=current.next.next; } else{ current=current.next; } } return head; } }
mikelyy/Leetcode
83.java
248,346
class Solution { public int removeDuplicates(int[] nums) { var n = nums.length; if (n < 3) return n; var i = 2; for (var j = i; j < n; j++) if (nums[j] != nums[i - 2]) nums[i++] = nums[j]; return i; } }
swetaagarwal123/leetcode
80.java
248,347
class Solution { public int removeDuplicates(int[] nums) { int len = nums.length; int left = 0; int right = 1; while (right < len) { if (nums[right] > nums[left]) { left++; nums[left] = nums[right]; } right++; } return left + 1; } }
swetaagarwal123/leetcode
26.java
248,356
import java.util.Scanner; public class Q8 { //Remove duplicate characters from a word public static void main(String[] args) { Scanner sc = new Scanner(System.in); //user input System.out.println("Enter the word : "); String word = sc.next(); //Printing out the sanitized word System.out.println("Sanitized word : " + removeDuplicateChars(word)); } static String removeDuplicateChars(String word){ //Recursive Function for removing duplicate characters if(word.length()<=1){ return word; } else if(word.charAt(0) == word.charAt(1)){ return removeDuplicateChars(word.substring(1)); } else{ return word.charAt(0) + removeDuplicateChars(word.substring(1)); } } }
painful-bug/Java-Grade-XI-Project
Q8.java
248,376
class Solution80 { public static int removeDuplicates(int[] nums) { int unique_index = 2; for (int org_index = 0 ; org_index < nums.length - 2 ; org_index++){ if (nums[org_index] != nums[unique_index]){ nums[unique_index] = nums[org_index]; unique_index++; } } return unique_index; } }
amirerfantim/Leetcode-solutions
80.java
248,387
package pojo; public class Duty implements java.io.Serializable { private int id; private String name; private int baseSalary; public Duty(){} public void setId(int id) { this.id = id; } public int getId() { return id; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setBaseSalary(int baseSalary) { this.baseSalary = baseSalary; } public int getBaseSalary() { return baseSalary; } }
liangcanxin/StaffManageSystem
src/pojo/Duty.java
248,388
package odrlmodel; /** * This class represents an ODRL2.0 Duty * The Duty entity indicates a requirement that MAY be fulfilled in return for * being entitled to the referring Permission entity. * * While implying different semantics, the Duty entity is similar to Permission * in that it is an Action that can be undertaken. If a Permission refers to several * Duty entities, all of them have to be fulfilled for the Permission to become valid. * If several Permission entities refer to one Duty, then the Duty only has to be * fulfilled once for all the Permission entities to become valid. * @version Suitable for ODRL 2.1 * @author Victor Rodriguez Doncel at OEG-UPM 2014 */ public class Duty extends Rule { public Duty() { setKindOfRule(Rule.RULE_DUTY); } /** * Creates a duty identified by the given URI. * @param _uri URI of the duty */ public Duty(String _uri) { super(_uri); setKindOfRule(Rule.RULE_DUTY); } }
oanc/odrlapi
src/main/java/odrlmodel/Duty.java
248,389
package com.hu.entity; import java.io.Serializable; import java.util.Date; /** * @author 胡冰 * @version 1.0 * @create 2020-06-09 8:23 * @decription 考勤类 **/ public class Duty implements Serializable { private int dtID; private Date dtDate; /** * 签到 */ private String signinTime; /** * 签退 */ private String signoutTime; /** * 可以同时提供id和对象属性 */ private String empId; /** * 员工的信息 */ private Employee emp; public Duty() { super(); } public Duty(Date dtDate, String signinTime, String signoutTime, String empId) { super(); this.dtDate = dtDate; this.signinTime = signinTime; this.signoutTime = signoutTime; this.empId = empId; } public Duty(int dtID, Date dtDate, String signinTime, String signoutTime, Employee emp) { super(); this.dtID = dtID; this.dtDate = dtDate; this.signinTime = signinTime; this.signoutTime = signoutTime; this.emp = emp; } public int getDtID() { return dtID; } public void setDtID(int dtID) { this.dtID = dtID; } public Date getDtDate() { return dtDate; } public void setDtDate(Date dtDate) { this.dtDate = dtDate; } public String getSigninTime() { return signinTime; } public void setSigninTime(String signinTime) { this.signinTime = signinTime; } public String getSignoutTime() { return signoutTime; } public void setSignoutTime(String signoutTime) { this.signoutTime = signoutTime; } public String getEmpId() { return empId; } public void setEmpId(String empId) { this.empId = empId; } public Employee getEmp() { return emp; } public void setEmp(Employee emp) { this.emp = emp; } @Override public String toString() { return "Duty [dtID=" + dtID + ", dtDate=" + dtDate + ", signinTime=" + signinTime + ", signoutTime=" + signoutTime + ", empId=" + empId + ", emp=" + emp + "]"; } }
BingBuLiang/PersonnelManagement_OA
src/com/hu/entity/Duty.java
248,390
import java.util.Scanner; interface Data{ int user = 100; void getName(); void displayName(); } class duty implements Data{ Scanner sc = new Scanner(System.in); String Name; int age; public void getName(){ System.out.print("Enter Your Name Please : "); Name = sc.nextLine(); System.out.print("Enter Your Age Please : "); age = sc.nextInt(); } public void displayName(){ System.out.println("Hi "+Name+" Your Name is added to our data base which contains only top "+user+" You will now officially work on this mission and you will retire at the age of "+(age+30)+" \n\nStart Your Work Now ==> "); } } public class INTERFACE { public static void main(String[] args) { duty d = new duty(); d.getName(); d.displayName(); } }
DreamerX00/JAVA
INTERFACE.java
248,391
package models; import java.util.*; import javax.persistence.*; import play.db.jpa.*; import play.data.validation.*; @Entity public class Duty extends Model { @Required public String Name; @Required @ManyToOne public DutyCategory Category; public Integer Students; public Integer Assistants; public Boolean Grants; public Duty(String name, DutyCategory category) { this.Name = name; this.Category = category; } public static List<Duty> getByCategory(String category){ List<Duty> result = Duty.find("select distinct d from Duty d join " + "d.Category c where c.Name = ? order by d.Name", category).fetch(); return result; } public static Duty findByNameAndCategory(String name, String category){ List<Duty> result = Duty.find("select distinct d from Duty d join " + "d.Category c where d.Name = '" + name + "' and c.Name = '" + category + "'").fetch(); return result.get(0); } public static List<Duty> getForUser(Long id){ List<Duty> result = Duty.find("select d from User u join u.duties d where u.id = " + id).fetch(); return result; } public static List<Duty> getForUser(Long id, String category){ List<Duty> result = Duty.find("select d from User u join u.duties d where u.id = " + id + " and d.Category.Name = '" + category + "'").fetch(); return result; } public static List<Duty> getForUser(String email, String category){ List<Duty> result = Duty.find("select d from User u join u.duties d where u.email = '" + email + "' and d.Category.Name = '" + category + "'").fetch(); return result; } public static boolean userHasDuty(Long id, String name, String category){ List<Duty> duties = getForUser(id); Duty duty = Duty.findByNameAndCategory(name, category); return duties.contains(duty); } public String toString() { return Name; } }
martinffx/ems-playframework-1.2.3
app/models/Duty.java
248,392
package eight; /** * 某寺庙里7个和尚每天轮流挑水,每个人可以挑水的日期是固定的 * * <pre> * 和尚1: 星期二,四; * 和尚2: 星期一,六; * 和尚3: 星期三,日; * 和尚4: 星期五 * 和尚5: 星期一,四,六; * 和尚6: 星期二,五; * 和尚7: 星期三,六,日。 * </pre> * * 需要给出所有的挑水方案 * */ public class Monk { // 每行代表一个和尚 // ready[i][j]=1表示第i个和尚第j天有空。 static int[][] ready = { { 0, 1, 0, 1, 0, 0, 0 }, { 1, 0, 0, 0, 0, 1, 0 }, { 0, 0, 1, 0, 0, 0, 1 }, { 0, 0, 0, 0, 1, 0, 0 }, { 1, 0, 0, 1, 0, 1, 0 }, { 0, 1, 0, 0, 1, 0, 0 }, { 0, 0, 1, 0, 0, 1, 1 } }; static boolean check(int col) { for (int i = 0; i < col; i++) { int diff = Math.abs(ret[i] - ret[col]); if (diff == 0 ) return false; } return true; } static int[] ret = new int[7]; static int duty(int col) { int ways = 0; if(col==7){ printMonk(); return 1; } for (int row = 0; row < 7; row++) { if (ready[row][col] != 1) continue; ret[col] = row; if (check(col)) { ways += duty(col + 1); } } return ways; } private static void printMonk() { for(int i=0; i<ret.length;i++){ System.out.format("%d ",ret[i]+1); } System.out.println(); } public static void main(String[] args) { System.out.println(duty(0)); } }
gucasbrg/Algorithm
src/eight/Monk.java
248,393
package com.mantis.data.entity; import jakarta.persistence.*; import java.util.List; @Entity @Table(name="tbl_duty") public class Duty { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id") private Integer id; @Column(name="name") private String name; @OneToMany(fetch = FetchType.LAZY, mappedBy = "duty") private List<RepairShopDutyRelation> repairShopDutyRelations; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<RepairShopDutyRelation> getRepairShopDutyRelations() { return repairShopDutyRelations; } public void setRepairShopDutyRelations(List<RepairShopDutyRelation> repairShopDutyRelations) { this.repairShopDutyRelations = repairShopDutyRelations; } }
b2210356078/CarGO
data/entity/Duty.java
248,394
import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { List<String> names = Arrays.asList("Jack", "Connor", "Harry", "George", "Samuel", "John"); List<String> families = Arrays.asList("Evans", "Young", "Harris", "Wilson", "Davies", "Adamson", "Brown"); Collection<Person> persons = new ArrayList<>(); for (int i = 0; i < 10; i++) { // для удобства оценки работы программы можно задать i < 10 и раскомментировать строки 22-26. persons.add(new Person( names.get(new Random().nextInt(names.size())), families.get(new Random().nextInt(families.size())), new Random().nextInt(100), Sex.values()[new Random().nextInt(Sex.values().length)], Education.values()[new Random().nextInt(Education.values().length)]) ); } System.out.println(persons); // Для i < 10 вместо i < 10_000_000 в строке 11 - удобство проверки работы программы. for(Person person : persons) { // Для i < 10 вместо i < 10_000_000 в строке 11 - удобство проверки работы программы. System.out.println(person.getAge()); } infant(persons); duty(persons); worker(persons); } private static void worker(Collection<Person> persons) { List <String> worker = persons.stream() .filter(person -> person.getAge() > 18 && person.getEducation().equals(Education.HIGHER) && person.getAge() < 65 && person.getSex().equals(Sex.MAN) || person.getAge() > 18 && person.getAge() < 60 && person.getSex().equals(Sex.WOMAN) && person.getEducation().equals(Education.HIGHER)) .sorted(Comparator.comparing(Person::getFamily)) .map(Person::getFamily) .toList(); System.out.println("Workers with higher degree from list is: " + worker + " by count: " + worker.size()); } private static void duty(Collection<Person> persons) { List <String> duty = persons.stream() .filter(person -> person.getAge() > 18 && person.getAge() < 27) .map(Person::getFamily) .toList(); // можно ли вывести еще и количество человек? (именно в терминальной части потока задать такую возможность) System.out.println("Persons under duty is: " + duty + " by count: " + duty.size()); } private static void infant(Collection<Person> persons) { int infant = (int) persons.stream() .filter(person -> person.getAge() < 18) .count(); System.out.println("Count for infant persons from list is: " + infant); } }
GarRustem/NetologyHW
StreamHW/src/Main.java
248,395
package lib; import java.util.List; public class DutyObl { private String stateId; private String gotoStateId; private int dutyType; private String performative; private String duty; private List<String> destinationPlayers; public DutyObl(String stateId, String gotoStateId, int dutyType, String performative, String duty, List<String> destinationPlayers) { this.stateId = stateId; this.gotoStateId = gotoStateId; this.dutyType = dutyType; this.performative = performative; this.duty = duty; this.destinationPlayers = destinationPlayers; } public String getPerformative() { return performative; } public String getStateId() { return stateId; } public String getGotoStateId() { return gotoStateId; } public int getDutyType() { return dutyType; } public String getDuty() { return duty; } public List<String> getDestinationPlayers() { return destinationPlayers; } }
jacamo-lang/int-mas
src/src/lib/DutyObl.java
248,396
public class DutyFree { public static void main(String[] args) { System.out.print( new java.util.Scanner(System.in) .useDelimiter(" ") .tokens() .mapToDouble(Double::parseDouble) .map(x -> 1.1 * x) .anyMatch(x -> x > 20) ? "Back to the store" : "On to the terminal" ); } }
rabestro/sololearn-challenges
one-statement/DutyFree.java
248,397
package model; public class DutyTime { private String duty; private String time; private String spareDay1; private String spareDay2; public String getDuty() { return duty; } public void setDuty(String duty) { this.duty = duty; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getKey() { return getTime() + getDuty(); } public void setSpareDay1(String spareDay1) { this.spareDay1 = spareDay1; } public String getSpareDay1() { return spareDay1; } public void setSpareDay2(String spareDay2) { this.spareDay2 = spareDay2; } public String getSpareDay2() { return spareDay2; } }
AnjaliSobti/ICS4U_Sumative
DutyTime.java
248,398
package practice; // Import the necessary classes from the java.time package import java.time.LocalDate; import java.time.Period; // Declare a public class named Test public class ChangeOfDuty { // Declare a static method named change_of_duty that takes three LocalDate objects as arguments static void change_of_duty(LocalDate start, LocalDate end, Period period) { // Declare a LocalDate variable named date with an initial value of start LocalDate date = start; // Use a while loop to iterate through the dates between the start and end dates while (date.isBefore(end)) { // Print out a message indicating that it's time to change duty for the current date System.out.println("Time to change the duty: " + date); // Increment the date by the specified period date = date.plus(period); } } public static void main(String[] args) { LocalDate start = LocalDate.now(); LocalDate end = LocalDate.of(2023, 12, 31); Period period = Period.ofDays(13); change_of_duty(start, end, period); } }
nikdimentiy/jet
ChangeOfDuty.java
248,399
abstract class Product { protected String name; protected int price, qty; public Product(String name, int price, int qty) { this.name = name; this.price = price; this.qty = qty; } public final int getQty() { return qty; } public void print() { System.out.println(name); System.out.println(price); System.out.println(qty); } public abstract double getNetPrice(); } class DiscountProduct extends Product{ protected double disRate; public DiscountProduct(String name, int price, int qty, double disRate) { super(name, price, qty); this.disRate = disRate; } @Override public void print() { super.print(); System.out.println(disRate); } public double getNetPrice() { return price - (price * disRate / 100); } } class TaxProduct extends Product{ protected double taxRate; public TaxProduct(String name, int price, int qty, double taxRate) { super(name, price, qty); this.taxRate = taxRate; } public void print() { super.print(); System.out.println(taxRate); } public double getNetPrice() { return price + (price * taxRate / 100); } } class ImportedProduct extends TaxProduct{ protected double duty; public ImportedProduct(String name, int price, int qty, double taxRate, double duty) { super(name, price, qty, taxRate); this.duty = duty; } public void print() { super.print(); System.out.println(duty); } public double getNetPrice() { double amount = price + (price * duty / 100); return amount + ( amount * taxRate / 100); } } public class TestProduct { public static void print(Product p) { p.print(); // Runtime polymorphism System.out.println("Net Price : " + p.getNetPrice()); // Runtime polymorphism } public static void main(String[] args) { DiscountProduct p = new DiscountProduct("iPhone6",30000,1,20); print(p); ImportedProduct ip = new ImportedProduct("iPhone X", 60000, 2, 12,20); print(ip); } }
srikanthpragada/javase
TestProducts.java
248,400
package gme; // Nintendo Game Boy sound emulator // http://www.slack.net/~ant/ /* Copyright (C) 2003-2007 Shay Green. This module 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 module 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. You should have received a copy of the GNU Lesser General Public License along with this module; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ class GbOsc { static final boolean gbc_02 = false; // TODO: allow to be set? static final int trigger_mask = 0x80; static final int length_enabled = 0x40; static final int dac_bias = 7; BlipBuffer output; int output_select; final int [] regs = new int [5]; int vol_unit; int delay; int last_amp; int length; int enabled; void reset() { output = null; output_select = 0; delay = 0; last_amp = 0; length = 64; enabled = 0; for ( int i = 5; --i >= 0; ) regs [i] = 0; } void clock_length() { if ( (regs [4] & length_enabled) != 0 && length != 0 ) { if ( --length <= 0 ) enabled = 0; } } int frequency() { return (regs [4] & 7) * 0x100 + regs [3]; } boolean write_register( int frame_phase, int reg, int old_data, int data ) { return false; } int write_trig( int frame_phase, int max_len, int old_data ) { int data = regs [4]; if ( gbc_02 && (frame_phase & 1) != 0 && (old_data & length_enabled) == 0 && length != 0 ) length--; if ( (data & trigger_mask) != 0 ) { enabled = 1; if ( length == 0 ) { length = max_len; if ( gbc_02 && (frame_phase & 1) != 0 && (data & length_enabled) != 0 ) length--; } } if ( gbc_02 && length == 0 ) enabled = 0; return data & trigger_mask; } } class GbEnv extends GbOsc { int env_delay; int volume; int dac_enabled() { return regs [2] & 0xF8; } void reset() { env_delay = 0; volume = 0; super.reset(); } int reload_env_timer() { int raw = regs [2] & 7; env_delay = (raw != 0 ? raw : 8); return raw; } void clock_envelope() { if ( --env_delay <= 0 && reload_env_timer() != 0 ) { int v = volume + ((regs [2] & 0x08) != 0 ? +1 : -1); if ( 0 <= v && v <= 15 ) volume = v; } } boolean write_register( int frame_phase, int reg, int old_data, int data ) { final int max_len = 64; switch ( reg ) { case 1: length = max_len - (data & (max_len - 1)); break; case 2: if ( dac_enabled() == 0 ) enabled = 0; // TODO: once zombie mode used, envelope not clocked? if ( ((old_data ^ data) & 8) != 0 ) { int step = 0; if ( (old_data & 7) != 0 ) step = +1; else if ( (data & 7) != 0 ) step = -1; if ( (data & 8) != 0 ) step = -step; volume = (15 + step - volume) & 15; } else { int step = ((old_data & 7) != 0 ? 2 : 0) | ((data & 7) != 0 ? 0 : 1); volume = (volume + step) & 15; } break; case 4: if ( write_trig( frame_phase, max_len, old_data ) != 0 ) { volume = regs [2] >> 4; reload_env_timer(); if ( frame_phase == 7 ) env_delay++; if ( dac_enabled() == 0 ) enabled = 0; return true; } } return false; } } class GbSquare extends GbEnv { int phase; final int period() { return (2048 - frequency()) * 4; } void reset() { phase = 0; super.reset(); delay = 0x40000000; // TODO: less hacky (never clocked until first trigger) } boolean write_register( int frame_phase, int reg, int old_data, int data ) { boolean result = super.write_register( frame_phase, reg, old_data, data ); if ( result ) delay = period(); return result; } static final byte [] duty_offsets = { 1, 1, 3, 7 }; static final byte [] duties = { 1, 2, 4, 6 }; void run( int time, int end_time ) { final int duty_code = regs [1] >> 6; final int duty_offset = duty_offsets [duty_code]; final int duty = duties [duty_code]; int playing = 0; int amp = 0; int phase = (this.phase + duty_offset) & 7; if ( output != null ) { if ( volume != 0 ) { playing = -enabled; if ( phase < duty ) amp = volume & playing; // Treat > 16 kHz as DC if ( frequency() > 2041 && delay < 32 ) { amp = (volume * duty) >> 3 & playing; playing = 0; } } if ( dac_enabled() == 0 ) { playing = 0; amp = 0; } else { amp -= dac_bias; } int delta = amp - last_amp; if ( delta != 0 ) { last_amp = amp; output.addDelta( time, delta * vol_unit ); } } time += delay; if ( time < end_time ) { final int period = this.period(); if ( playing == 0 ) { // maintain phase int count = (end_time - time + period - 1) / period; phase = (phase + count) & 7; time += count * period; } else { final BlipBuffer output = this.output; // TODO: eliminate ugly +dac_bias -dac_bias adjustments int delta = ((amp + dac_bias) * 2 - volume) * vol_unit; do { if ( (phase = (phase + 1) & 7) == 0 || phase == duty ) output.addDelta( time, delta = -delta ); } while ( (time += period) < end_time ); last_amp = (delta < 0 ? 0 : volume) - dac_bias; } this.phase = (phase - duty_offset) & 7; } delay = time - end_time; } } final class GbSweepSquare extends GbSquare { static final int period_mask = 0x70; static final int shift_mask = 0x07; int sweep_freq; int sweep_delay; int sweep_enabled; int sweep_neg; void reset() { sweep_freq = 0; sweep_delay = 0; sweep_enabled = 0; sweep_neg = 0; super.reset(); } void reload_sweep_timer() { sweep_delay = (regs [0] & period_mask) >> 4; if ( sweep_delay == 0 ) sweep_delay = 8; } void calc_sweep( boolean update ) { int freq = sweep_freq; int shift = regs [0] & shift_mask; int delta = freq >> shift; sweep_neg = regs [0] & 0x08; if ( sweep_neg != 0 ) delta = -delta; freq += delta; if ( freq > 0x7FF ) { enabled = 0; } else if ( shift != 0 && update ) { sweep_freq = freq; regs [3] = freq & 0xFF; regs [4] = (regs [4] & ~0x07) | (freq >> 8 & 0x07); } } void clock_sweep() { if ( --sweep_delay <= 0 ) { reload_sweep_timer(); if ( sweep_enabled != 0 && (regs [0] & period_mask) != 0 ) { calc_sweep( true ); calc_sweep( false ); } } } boolean write_register( int frame_phase, int reg, int old_data, int data ) { if ( reg == 0 && (sweep_neg & 0x08 & ~data) != 0 ) enabled = 0; if ( super.write_register( frame_phase, reg, old_data, data ) ) { sweep_freq = frequency(); reload_sweep_timer(); sweep_enabled = regs [0] & (period_mask | shift_mask); if ( (regs [0] & shift_mask) != 0 ) calc_sweep( false ); } return false; } } final class GbNoise extends GbEnv { int bits; boolean write_register( int frame_phase, int reg, int old_data, int data ) { if ( reg == 3 ) { int p = period(); if ( p != 0 ) delay %= p; // TODO: not entirely correct } if ( super.write_register( frame_phase, reg, old_data, data ) ) bits = 0x7FFF; return false; } static final byte [] noise_periods = { 8, 16, 32, 48, 64, 80, 96, 112 }; int period() { int shift = regs [3] >> 4; int p = noise_periods [regs [3] & 7] << shift; if ( shift >= 0x0E ) p = 0; return p; } void run( int time, int end_time ) { int feedback = (1 << 14) >> (regs [3] & 8); int playing = 0; int amp = 0; if ( output != null ) { if ( volume != 0 ) { playing = -enabled; if ( (bits & 1) == 0 ) amp = volume & playing; } if ( dac_enabled() != 0 ) { amp -= dac_bias; } else { amp = 0; playing = 0; } int delta = amp - last_amp; if ( delta != 0 ) { last_amp = amp; output.addDelta( time, delta * vol_unit ); } } time += delay; if ( time < end_time ) { final int period = this.period(); if ( period == 0 ) { time = end_time; } else { int bits = this.bits; if ( playing == 0 ) { // maintain phase int count = (end_time - time + period - 1) / period; time += count * period; // TODO: be sure this doesn't drag performance too much bits ^= (feedback << 1) & -(bits & 1); feedback *= 3; do { bits = (bits >> 1) ^ (feedback & -(bits & 2)); } while ( --count > 0 ); bits &= ~(feedback << 1); } else { final BlipBuffer output = this.output; // TODO: eliminate ugly +dac_bias -dac_bias adjustments int delta = ((amp + dac_bias) * 2 - volume) * vol_unit; do { int changed = bits + 1; bits >>= 1; if ( (changed & 2) != 0 ) { bits |= feedback; output.addDelta( time, delta = -delta ); } } while ( (time += period) < end_time ); last_amp = (delta < 0 ? 0 : volume) - dac_bias; } this.bits = bits; } } delay = time - end_time; } } final class GbWave extends GbOsc { int wave_pos; int sample_buf_high; int sample_buf; static final int wave_size = 32; int [] wave = new int [wave_size]; int period() { return (2048 - frequency()) * 2; } int dac_enabled() { return regs [0] & 0x80; } int access( int addr ) { if ( enabled != 0 ) addr = 0xFF30 + (wave_pos >> 1); return addr; } void reset() { wave_pos = 0; sample_buf_high = 0; sample_buf = 0; length = 256; super.reset(); } boolean write_register( int frame_phase, int reg, int old_data, int data ) { final int max_len = 256; switch ( reg ) { case 1: length = max_len - data; break; case 4: if ( write_trig( frame_phase, max_len, old_data ) != 0 ) { wave_pos = 0; delay = period() + 6; sample_buf = sample_buf_high; } // fall through case 0: if ( dac_enabled() == 0 ) enabled = 0; } return false; } void run( int time, int end_time ) { int volume_shift = regs [2] >> 5 & 3; int playing = 0; if ( output != null ) { playing = -enabled; if ( --volume_shift < 0 ) { volume_shift = 7; playing = 0; } int amp = sample_buf & playing; if ( frequency() > 0x7FB && delay < 16 ) { // 16 kHz and above, act as DC at mid-level // (really depends on average level of entire wave, // but this is good enough) amp = 8; playing = 0; } amp >>= volume_shift; if ( dac_enabled() == 0 ) { playing = 0; amp = 0; } else { amp -= dac_bias; } int delta = amp - last_amp; if ( delta != 0 ) { last_amp = amp; output.addDelta( time, delta * vol_unit ); } } time += delay; if ( time < end_time ) { int wave_pos = (this.wave_pos + 1) & (wave_size - 1); final int period = this.period(); if ( playing == 0 ) { // maintain phase int count = (end_time - time + period - 1) / period; wave_pos += count; // will be masked below time += count * period; } else { final BlipBuffer output = this.output; int last_amp = this.last_amp + dac_bias; do { int amp = wave [wave_pos] >> volume_shift; wave_pos = (wave_pos + 1) & (wave_size - 1); int delta; if ( (delta = amp - last_amp) != 0 ) { last_amp = amp; output.addDelta( time, delta * vol_unit ); } } while ( (time += period) < end_time ); this.last_amp = last_amp - dac_bias; } wave_pos = (wave_pos - 1) & (wave_size - 1); this.wave_pos = wave_pos; if ( enabled != 0 ) { sample_buf_high = wave [wave_pos & ~1]; sample_buf = wave [wave_pos]; } } delay = time - end_time; } } final public class GbApu { public GbApu() { oscs [0] = square1; oscs [1] = square2; oscs [2] = wave; oscs [3] = noise; reset(); } // Resets oscillators and internal state public void setOutput( BlipBuffer center, BlipBuffer left, BlipBuffer right ) { outputs [1] = right; outputs [2] = left; outputs [3] = center; for ( int i = osc_count; --i >= 0; ) oscs [i].output = outputs [oscs [i].output_select]; } private void update_volume() { final int unit = (int) (1.0 / osc_count / 15 / 8 * 65536); // TODO: doesn't handle left != right volume (not worth the complexity) int data = regs [vol_reg - startAddr]; int left = data >> 4 & 7; int right = data & 7; int vol_unit = (left > right ? left : right) * unit; for ( int i = osc_count; --i >= 0; ) oscs [i].vol_unit = vol_unit; } private void reset_regs() { for ( int i = 0x20; --i >= 0; ) regs [i] = 0; for ( int i = osc_count; --i >= 0; ) oscs [i].reset(); update_volume(); } static final int initial_wave [] = { 0x84,0x40,0x43,0xAA,0x2D,0x78,0x92,0x3C, 0x60,0x59,0x59,0xB0,0x34,0xB8,0x2E,0xDA }; public void reset() { frame_time = 0; last_time = 0; frame_phase = 0; reset_regs(); for ( int i = 16; --i >= 0; ) write( 0, i + wave_ram, initial_wave [i] ); } private void run_until( int end_time ) { assert end_time >= last_time; // end_time must not be before previous time if ( end_time == last_time ) return; while ( true ) { // run oscillators int time = end_time; if ( time > frame_time ) time = frame_time; square1.run( last_time, time ); square2.run( last_time, time ); wave .run( last_time, time ); noise .run( last_time, time ); last_time = time; if ( time == end_time ) break; // run frame sequencer frame_time += frame_period; switch ( frame_phase++ ) { case 2: case 6: // 128 Hz square1.clock_sweep(); case 0: case 4: // 256 Hz square1.clock_length(); square2.clock_length(); wave .clock_length(); noise .clock_length(); break; case 7: // 64 Hz frame_phase = 0; square1.clock_envelope(); square2.clock_envelope(); noise .clock_envelope(); } } } // Runs all oscillators up to specified time, ends current time frame, then // starts a new frame at time 0 public void endFrame( int end_time ) { if ( end_time > last_time ) run_until( end_time ); assert frame_time >= end_time; frame_time -= end_time; assert last_time >= end_time; last_time -= end_time; } static void silence_osc( int time, GbOsc osc ) { int amp = osc.last_amp; if ( amp != 0 ) { osc.last_amp = 0; if ( osc.output != null ) osc.output.addDelta( time, -amp * osc.vol_unit ); } } // Reads and writes at addr must satisfy start_addr <= addr <= end_addr public static final int startAddr = 0xFF10; public static final int endAddr = 0xFF3F; public void write( int time, int addr, int data ) { assert startAddr <= addr && addr <= endAddr; assert 0 <= data && data < 0x100; if ( addr < status_reg && (regs [status_reg - startAddr] & power_mask) == 0 ) return; run_until( time ); int reg = addr - startAddr; if ( addr < wave_ram ) { int old_data = regs [reg]; regs [reg] = data; if ( addr < vol_reg ) { int index = reg / 5; GbOsc osc = oscs [index]; int r = reg - index * 5; osc.regs [r] = data; osc.write_register( frame_phase, r, old_data, data ); } else if ( addr == vol_reg && data != old_data ) { for ( int i = osc_count; --i >= 0; ) silence_osc( time, oscs [i] ); update_volume(); } else if ( addr == stereo_reg ) { for ( int i = osc_count; --i >= 0; ) { GbOsc osc = oscs [i]; int bits = data >> i; osc.output_select = (bits >> 3 & 2) | (bits & 1); BlipBuffer output = outputs [osc.output_select]; if ( osc.output != output ) { silence_osc( time, osc ); osc.output = output; } } } else if ( addr == status_reg && ((data ^ old_data) & power_mask) != 0 ) { frame_phase = 0; if ( (data & power_mask) == 0 ) { for ( int i = osc_count; --i >= 0; ) silence_osc( time, oscs [i] ); reset_regs(); } } } else // wave data { addr = wave.access( addr ); regs [addr - startAddr] = data; int index = (addr & 0x0F) * 2; wave.wave [index ] = data >> 4; wave.wave [index + 1] = data & 0x0F; } } static final int masks [] = { 0x80,0x3F,0x00,0xFF,0xBF, 0xFF,0x3F,0x00,0xFF,0xBF, 0x7F,0xFF,0x9F,0xFF,0xBF, 0xFF,0xFF,0x00,0x00,0xBF, 0x00,0x00,0x70, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF }; // Reads from address at specified time public int read( int time, int addr ) { assert startAddr <= addr && addr <= endAddr; run_until( time ); if ( addr >= wave_ram ) addr = wave.access( addr ); int index = addr - startAddr; int data = regs [index]; if ( index < masks.length ) data |= masks [index]; if ( addr == status_reg ) { data &= 0xF0; if ( square1.enabled != 0 ) data |= 1; if ( square2.enabled != 0 ) data |= 2; if ( wave .enabled != 0 ) data |= 4; if ( noise .enabled != 0 ) data |= 8; } return data; } static final int vol_reg = 0xFF24; static final int stereo_reg = 0xFF25; static final int status_reg = 0xFF26; static final int wave_ram = 0xFF30; static final int frame_period = 4194304 / 512; // 512 Hz static final int power_mask = 0x80; static final int osc_count = 4; final GbOsc [] oscs = new GbOsc [osc_count]; int frame_time; int last_time; int frame_phase; final BlipBuffer [] outputs = new BlipBuffer [4]; final GbSweepSquare square1 = new GbSweepSquare(); final GbSquare square2 = new GbSquare(); final GbWave wave = new GbWave(); final GbNoise noise = new GbNoise(); final int [] regs = new int [endAddr - startAddr + 1]; }
gamethapcam/pokemon-wilds
core/src/gme/GbApu.java
248,401
package dao; import java.util.List; import model.TbDept; import model.TbDuty; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import tools.JDBCUtils; public class DutyDao { private static JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); public static TbDuty findDutyById(int DutyId) { String sql = "select * from tb_duty where id=?"; TbDuty duty = template.queryForObject(sql, new BeanPropertyRowMapper<TbDuty>(TbDuty.class),DutyId); return duty; } public static List<TbDuty> findAllDuty() { try { String sql = "select * from tb_duty"; List<TbDuty> tbDuty = template.query(sql,new BeanPropertyRowMapper<TbDuty>(TbDuty.class)); return tbDuty; } catch (DataAccessException e) { e.printStackTrace(); return null; } } }
rawchen/EPMS
src/dao/DutyDao.java
248,402
import java.awt.*; import java.util.StringTokenizer; class VoltageElm extends CircuitElm { static final int FLAG_COS = 2; int waveform; static final int WF_DC = 0; static final int WF_AC = 1; static final int WF_SQUARE = 2; static final int WF_TRIANGLE = 3; static final int WF_SAWTOOTH = 4; static final int WF_PULSE = 5; static final int WF_VAR = 6; double frequency, maxVoltage, freqTimeZero, bias, phaseShift, dutyCycle; VoltageElm(int xx, int yy, int wf) { super(xx, yy); waveform = wf; maxVoltage = 5; frequency = 40; dutyCycle = .5; reset(); } public VoltageElm(int xa, int ya, int xb, int yb, int f, StringTokenizer st) { super(xa, ya, xb, yb, f); maxVoltage = 5; frequency = 40; waveform = WF_DC; dutyCycle = .5; try { waveform = new Integer(st.nextToken()).intValue(); frequency = new Double(st.nextToken()).doubleValue(); maxVoltage = new Double(st.nextToken()).doubleValue(); bias = new Double(st.nextToken()).doubleValue(); phaseShift = new Double(st.nextToken()).doubleValue(); dutyCycle = new Double(st.nextToken()).doubleValue(); } catch (Exception e) { } if ((flags & FLAG_COS) != 0) { flags &= ~FLAG_COS; phaseShift = pi/2; } reset(); } int getDumpType() { return 'v'; } String dump() { return super.dump() + " " + waveform + " " + frequency + " " + maxVoltage + " " + bias + " " + phaseShift + " " + dutyCycle; } /*void setCurrent(double c) { current = c; System.out.print("v current set to " + c + "\n"); }*/ void reset() { freqTimeZero = 0; curcount = 0; } double triangleFunc(double x) { if (x < pi) return x*(2/pi)-1; return 1-(x-pi)*(2/pi); } void stamp() { if (waveform == WF_DC) sim.stampVoltageSource(nodes[0], nodes[1], voltSource, getVoltage()); else sim.stampVoltageSource(nodes[0], nodes[1], voltSource); } void doStep() { if (waveform != WF_DC) sim.updateVoltageSource(nodes[0], nodes[1], voltSource, getVoltage()); } double getVoltage() { double w = 2*pi*(sim.t-freqTimeZero)*frequency + phaseShift; switch (waveform) { case WF_DC: return maxVoltage+bias; case WF_AC: return Math.sin(w)*maxVoltage+bias; case WF_SQUARE: return bias+((w % (2*pi) > (2*pi*dutyCycle)) ? -maxVoltage : maxVoltage); case WF_TRIANGLE: return bias+triangleFunc(w % (2*pi))*maxVoltage; case WF_SAWTOOTH: return bias+(w % (2*pi))*(maxVoltage/pi)-maxVoltage; case WF_PULSE: return ((w % (2*pi)) < 1) ? maxVoltage+bias : bias; default: return 0; } } final int circleSize = 17; void setPoints() { super.setPoints(); calcLeads((waveform == WF_DC || waveform == WF_VAR) ? 8 : circleSize*2); } void draw(Graphics g) { setBbox(x, y, x2, y2); draw2Leads(g); if (waveform == WF_DC) { setPowerColor(g, false); setVoltageColor(g, volts[0]); interpPoint2(lead1, lead2, ps1, ps2, 0, 10); drawThickLine(g, ps1, ps2); setVoltageColor(g, volts[1]); int hs = 16; setBbox(point1, point2, hs); interpPoint2(lead1, lead2, ps1, ps2, 1, hs); drawThickLine(g, ps1, ps2); } else { setBbox(point1, point2, circleSize); interpPoint(lead1, lead2, ps1, .5); drawWaveform(g, ps1); } updateDotCount(); if (sim.dragElm != this) { if (waveform == WF_DC) drawDots(g, point1, point2, curcount); else { drawDots(g, point1, lead1, curcount); drawDots(g, point2, lead2, -curcount); } } drawPosts(g); } void drawWaveform(Graphics g, Point center) { g.setColor(needsHighlight() ? selectColor : Color.gray); setPowerColor(g, false); int xc = center.x; int yc = center.y; drawThickCircle(g, xc, yc, circleSize); int wl = 8; adjustBbox(xc-circleSize, yc-circleSize, xc+circleSize, yc+circleSize); int xc2; switch (waveform) { case WF_DC: { break; } case WF_SQUARE: xc2 = (int) (wl*2*dutyCycle-wl+xc); xc2 = max(xc-wl+3, min(xc+wl-3, xc2)); drawThickLine(g, xc-wl, yc-wl, xc-wl, yc ); drawThickLine(g, xc-wl, yc-wl, xc2 , yc-wl); drawThickLine(g, xc2 , yc-wl, xc2 , yc+wl); drawThickLine(g, xc+wl, yc+wl, xc2 , yc+wl); drawThickLine(g, xc+wl, yc , xc+wl, yc+wl); break; case WF_PULSE: yc += wl/2; drawThickLine(g, xc-wl, yc-wl, xc-wl, yc ); drawThickLine(g, xc-wl, yc-wl, xc-wl/2, yc-wl); drawThickLine(g, xc-wl/2, yc-wl, xc-wl/2, yc); drawThickLine(g, xc-wl/2, yc, xc+wl, yc); break; case WF_SAWTOOTH: drawThickLine(g, xc , yc-wl, xc-wl, yc ); drawThickLine(g, xc , yc-wl, xc , yc+wl); drawThickLine(g, xc , yc+wl, xc+wl, yc ); break; case WF_TRIANGLE: { int xl = 5; drawThickLine(g, xc-xl*2, yc , xc-xl, yc-wl); drawThickLine(g, xc-xl, yc-wl, xc, yc); drawThickLine(g, xc , yc, xc+xl, yc+wl); drawThickLine(g, xc+xl, yc+wl, xc+xl*2, yc); break; } case WF_AC: { int i; int xl = 10; int ox = -1, oy = -1; for (i = -xl; i <= xl; i++) { int yy = yc+(int) (.95*Math.sin(i*pi/xl)*wl); if (ox != -1) drawThickLine(g, ox, oy, xc+i, yy); ox = xc+i; oy = yy; } break; } } if (sim.showValuesCheckItem.getState()) { String s = getShortUnitText(frequency, "Hz"); if (dx == 0 || dy == 0) drawValues(g, s, circleSize); } } int getVoltageSourceCount() { return 1; } double getPower() { return -getVoltageDiff()*current; } double getVoltageDiff() { return volts[1] - volts[0]; } void getInfo(String arr[]) { switch (waveform) { case WF_DC: case WF_VAR: arr[0] = "voltage source"; break; case WF_AC: arr[0] = "A/C source"; break; case WF_SQUARE: arr[0] = "square wave gen"; break; case WF_PULSE: arr[0] = "pulse gen"; break; case WF_SAWTOOTH: arr[0] = "sawtooth gen"; break; case WF_TRIANGLE: arr[0] = "triangle gen"; break; } arr[1] = "I = " + getCurrentText(getCurrent()); arr[2] = ((this instanceof RailElm) ? "V = " : "Vd = ") + getVoltageText(getVoltageDiff()); if (waveform != WF_DC && waveform != WF_VAR) { arr[3] = "f = " + getUnitText(frequency, "Hz"); arr[4] = "Vmax = " + getVoltageText(maxVoltage); int i = 5; if (bias != 0) arr[i++] = "Voff = " + getVoltageText(bias); else if (frequency > 500) arr[i++] = "wavelength = " + getUnitText(2.9979e8/frequency, "m"); arr[i++] = "P = " + getUnitText(getPower(), "W"); } } public EditInfo getEditInfo(int n) { if (n == 0) return new EditInfo(waveform == WF_DC ? "Voltage" : "Max Voltage", maxVoltage, -20, 20); if (n == 1) { EditInfo ei = new EditInfo("Waveform", waveform, -1, -1); ei.choice = new Choice(); ei.choice.add("D/C"); ei.choice.add("A/C"); ei.choice.add("Square Wave"); ei.choice.add("Triangle"); ei.choice.add("Sawtooth"); ei.choice.add("Pulse"); ei.choice.select(waveform); return ei; } if (waveform == WF_DC) return null; if (n == 2) return new EditInfo("Frequency (Hz)", frequency, 4, 500); if (n == 3) return new EditInfo("DC Offset (V)", bias, -20, 20); if (n == 4) return new EditInfo("Phase Offset (degrees)", phaseShift*180/pi, -180, 180).setDimensionless(); if (n == 5 && waveform == WF_SQUARE) return new EditInfo("Duty Cycle", dutyCycle*100, 0, 100). setDimensionless(); return null; } public void setEditValue(int n, EditInfo ei) { if (n == 0) maxVoltage = ei.value; if (n == 3) bias = ei.value; if (n == 2) { // adjust time zero to maintain continuity ind the waveform // even though the frequency has changed. double oldfreq = frequency; frequency = ei.value; double maxfreq = 1/(8*sim.timeStep); if (frequency > maxfreq) frequency = maxfreq; double adj = frequency-oldfreq; freqTimeZero = sim.t-oldfreq*(sim.t-freqTimeZero)/frequency; } if (n == 1) { int ow = waveform; waveform = ei.choice.getSelectedIndex(); if (waveform == WF_DC && ow != WF_DC) { ei.newDialog = true; bias = 0; } else if (waveform != WF_DC && ow == WF_DC) { ei.newDialog = true; } if ((waveform == WF_SQUARE || ow == WF_SQUARE) && waveform != ow) ei.newDialog = true; setPoints(); } if (n == 4) phaseShift = ei.value*pi/180; if (n == 5) dutyCycle = ei.value*.01; } }
hausen/circuit-simulator
src/VoltageElm.java
248,403
package com.company; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import static javax.swing.JOptionPane.showMessageDialog; import static javax.swing.JOptionPane.PLAIN_MESSAGE; public class Duty { private HashMap<String, String> dutyMap = new LinkedHashMap<>(); @Deprecated private String[][] dutyArray = new String[14][4]; private HashMap<String, Integer> posts; private ArrayList<String> students; Duty() { this.posts = Post.getPosts(); generateDutyMap(); // generateDutyArray(); } @Deprecated private void generateDutyMapD() { this.students = Students.getStudentsShuffle(); int studentsCount = 0; for (HashMap.Entry<String, Integer> post : this.posts.entrySet()) { int count = post.getValue() + studentsCount; StringBuilder studentsList = new StringBuilder(); for (; studentsCount < count; studentsCount++) { if (studentsCount + 1 < count) { studentsList.append(this.students.get(studentsCount)).append(", "); } else { studentsList.append(this.students.get(studentsCount)); } } this.dutyMap.put(post.getKey(), studentsList.toString()); } } private void generateDutyMap() { this.students = Students.getStudentsShuffle(); int studentsCount = 0; for (HashMap.Entry<String, Integer> post : this.posts.entrySet()) { StringBuilder studentsList = new StringBuilder(); for (int i = 0; i < post.getValue(); i++) { if (i + 1 < post.getValue()) { studentsList.append(this.students.get(studentsCount)).append(", "); } else { studentsList.append(this.students.get(studentsCount)); } studentsCount++; } this.dutyMap.put(post.getKey(), studentsList.toString()); } } @Deprecated private void generateDutyArray() { this.students = Students.getStudentsShuffle(); int studentsCount = 0; int postsCount = 0; for (HashMap.Entry<String, Integer> post : this.posts.entrySet()) { int i = 0; dutyArray[postsCount][i] = post.getKey(); for (i = 1; i < post.getValue() + 1; i++) { dutyArray[postsCount][i] = this.students.get(studentsCount); studentsCount++; } postsCount++; } } public HashMap<String, String> getDutyMap() { return this.dutyMap; } @Deprecated public String[][] getDutyArray() { return this.dutyArray; } public void viewDutyMap() { StringBuilder postsWithStudentsList = new StringBuilder(); for (HashMap.Entry<String, String> postWithStudents : this.dutyMap.entrySet()) { postsWithStudentsList.append(postWithStudents.getKey()).append(": ").append(postWithStudents.getValue()).append("\n"); } showMessageDialog(null, postsWithStudentsList.toString(), "Дежурство", PLAIN_MESSAGE); } }
PavelMerkushevich/create-random-duty
src/com/company/Duty.java
248,404
package models; import com.avaje.ebean.Ebean; import play.data.validation.Constraints; import play.db.ebean.Model; import scala.Int; import javax.persistence.*; import java.util.List; /** * Created by j on 2016/4/13. */ @Entity public class Expert extends BaseModel { /** * 用户信息 */ @OneToOne public User user; /** * 所属分类 */ @ManyToOne public Category category; /** * 职称 */ @Column(length = 45) @Constraints.MaxLength(45) public String professional; /** * 职务 */ @Column(length = 45) @Constraints.MaxLength(45) public String duty; /** * 简介 */ @Column(columnDefinition = "TEXT") public String introduction; /** * 服务项目 */ @Column(columnDefinition = "TEXT") public String service; /** * 备注 */ @Column(columnDefinition = "TEXT") public String remark; /** * 所在单位 */ @Column(length = 45) @Constraints.MaxLength(45) public String company; public static final Finder<Long, Expert> find = new Finder<Long, Expert>( Long.class, Expert.class); /** * 通过分类查找专家 * * @param category * @return */ public static List<Expert> findExpertsByCategory(final Category category, int page, int pageSize) { return find .where() .eq("category", category) .setOrderBy("whenCreated desc") .setFirstRow((page - 1) * pageSize) .setMaxRows(pageSize) .findList(); } /** * 通过用户查找专家 * * @param user * @return */ public static Expert findExpertByUser(final User user) { return find .where() .eq("user", user) .findUnique(); } /** * 查找所有专家 * @return */ public static List<Expert> findAllExperts() { return find .findList(); } public static List<Expert> findExperts(int page, int pageSize) { return find .where() .setOrderBy("whenCreated desc") .setFirstRow((page - 1) * pageSize) .setMaxRows(pageSize) .findList(); } /** * 通过id查找专家 * * @param id * @return */ public static Expert findExpertById(final Long id) { return find .where() .eq("id", id) .findUnique(); } }
guodont/a-tech-backend
server/app/models/Expert.java
248,405
package JVE.Network; import java.io.*; import java.net.Socket; import java.util.concurrent.atomic.AtomicBoolean; public class Connection { private OnInputCommandEvent commandEvent; private OnInputFileEvent fileEvent; private Runnable close; private OutputStream out; private InputStream in; private AtomicBoolean isWorking = new AtomicBoolean(true); private String adress; public String getDuty() { return duty; } public void setDuty(String duty) { this.duty = duty; } private String duty; public void setOnCloseEvent(Runnable r) { close = r; } public void setOnMessageEvent(OnInputCommandEvent r) { commandEvent = r; } public void setOnFileEvent(OnInputFileEvent r) { fileEvent = r; } public void sendMessage(String s) throws IOException { out.write(("@command " + s.length() + '\n' + s + '\n').getBytes("UTF-8")); out.flush(); } public void sendFile(File f) throws IOException { FileInputStream fis = new FileInputStream(f.getPath()); long length = f.length(); out.write(("@file " + length + ' ' + f.getName() + '\n').getBytes("UTF-8")); out.flush(); byte[] byteArray = new byte[1024]; while (length > 0) { int i = fis.read(byteArray); out.write(byteArray, 0, i); length -= i; } out.flush(); } public Connection(Socket s) throws IOException { in = s.getInputStream(); out = s.getOutputStream(); adress = s.getInetAddress().toString(); } private static String readLine(InputStream is) throws IOException { byte[] b = new byte[100]; byte c; int length = 0; do { c = (byte) is.read(); if (c != '\n') { b[length] = c; length++; if (b.length <= length) b = java.util.Arrays.copyOf(b, length + 100); } } while (c != '\n'); return new String(java.util.Arrays.copyOf(b, length), "UTF-8"); } public void startWorking(String defaultInputFolder) throws Exception { new Thread(() -> { try { String input = readLine(in); while (input != null) { String[] params = input.split(" "); if (params[0].startsWith("@command")) { long length = Long.parseLong(params[1]); String command = ""; while (length > command.length()) { command += readLine(in) + '\n'; } commandEvent.run(this, command); } else if (params[0].startsWith("@file")) { String name = params[2]; long length = Long.parseLong(params[1]); File f = new File(defaultInputFolder + name); while (f.exists()) { f = new File(defaultInputFolder + f.getName() + "_"); } f.createNewFile(); byte[] buffer = new byte[1024]; FileOutputStream os = new FileOutputStream(f); int total = 0; while (total < length) { int count = in.read(buffer, 0, (int) Math.min(1024, length - total)); total += count; os.write(buffer, 0, count); } os.flush(); os.close(); fileEvent.run(this, f); } input = readLine(in); } } catch (Exception e) { System.err.println("[Connection] Error pt1 : " + e); e.printStackTrace(); } try { in.close(); } catch (IOException e) { System.err.println("[Connection] Error pt 2: " + e); } isWorking.set(false); if (close != null) close.run(); }).start(); } public String toString() { return adress; } }
ShirinkinArseny/JavaVideoEditor
Network/Connection.java
248,406
package com.dao; import com.entity.*; import java.util.*; public interface DutyDAO { void add(Duty data); void del(int id); Duty findById(int id); void update(Duty data); List show(); List query(Map params); List owner(String empno); }
O-TB/oa
src/com/dao/DutyDAO.java
248,407
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
248,409
package pojo; import java.util.Date; public class Salary { private Long id; //薪金信息编号 private String name; //员工姓名 private Double basic; //基本薪金 private Double eat; //饭补 private Double house; //房补 private Date granttime; // 工资发放时间 private Double duty; //全勤奖 private Double scot; //扣税 private Double punishment;//罚款 private Double other; //额外补助 private Double totalize; //总计 public Salary(String name, Double basic, Double eat, Double house, Date granttime, Double duty, Double scot, Double punishment, Double other, Double totalize) { this.name = name; this.basic = basic; this.eat = eat; this.house = house; this.granttime = granttime; this.duty = duty; this.scot = scot; this.punishment = punishment; this.other = other; this.totalize = totalize; } /** default constructor */ public Salary() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Double getBasic() { return this.basic; } public void setBasic(Double basic) { this.basic = basic; } public Double getEat() { return this.eat; } public void setEat(Double eat) { this.eat = eat; } public Double getHouse() { return this.house; } public void setHouse(Double house) { this.house = house; } public Date getGranttime() { return granttime; } public void setGranttime(Date granttime) { this.granttime = granttime; } public Double getDuty() { return this.duty; } public void setDuty(Double duty) { this.duty = duty; } public Double getScot() { return this.scot; } public void setScot(Double scot) { this.scot = scot; } public Double getPunishment() { return this.punishment; } public void setPunishment(Double punishment) { this.punishment = punishment; } public Double getOther() { return this.other; } public void setOther(Double other) { this.other = other; } public Double getTotalize() { return this.totalize; } public void setTotalize(Double totalize) { this.totalize = totalize; } public String toString() { StringBuffer toStr = new StringBuffer(); toStr.append("[Stipend] = [\n"); toStr.append(" id = " + this.id + ";\n"); toStr.append(" name = " + this.name + ";\n"); toStr.append(" basic = " + this.basic + ";\n"); toStr.append(" eat = " + this.eat + ";\n"); toStr.append(" house = " + this.house + ";\n"); toStr.append(" granttime = " + this.granttime + ";\n"); toStr.append(" duty = " + this.duty + ";\n"); toStr.append(" scot = " + this.scot + ";\n"); toStr.append(" punishment = " + this.punishment + ";\n"); toStr.append(" other = " + this.other + ";\n"); toStr.append(" totalize = " + this.totalize + ";\n"); toStr.append(" ];\n"); return toStr.toString(); } }
ruou/hr
src/pojo/Salary.java
248,410
/* * 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 Models; /** * * @author m4rkm3n */ public class Bills { private int bill_id; private int bill_cid; private int bill_num; private String issuedate; private String duedate; private int unit_cost; private int total_cost; private int units_consumed; private int after_due_date; private String bill_status; private int fc_surcharge; private int ptv_fee; private int gst; private int electricity_duty; public int getBill_id() { return bill_id; } public void setBill_id(int bill_id) { this.bill_id = bill_id; } public int getBill_cid() { return bill_cid; } public void setBill_cid(int bill_cid) { this.bill_cid = bill_cid; } public int getBill_num() { return bill_num; } public void setBill_num(int bill_num) { this.bill_num = bill_num; } public String getIssuedate() { return issuedate; } public void setIssuedate(String issuedate) { this.issuedate = issuedate; } public String getDuedate() { return duedate; } public void setDuedate(String duedate) { this.duedate = duedate; } public int getUnit_cost() { return unit_cost; } public void setUnit_cost(int unit_cost) { this.unit_cost = unit_cost; } public int getTotal_cost() { return total_cost; } public void setTotal_cost(int total_cost) { this.total_cost = total_cost; } public int getUnits_consumed() { return units_consumed; } public void setUnits_consumed(int units_consumed) { this.units_consumed = units_consumed; } public int getAfter_due_date() { return after_due_date; } public void setAfter_due_date(int after_due_date) { this.after_due_date = after_due_date; } public String getBill_status() { return bill_status; } public void setBill_status(String bill_status) { this.bill_status = bill_status; } public int getFc_surcharge() { return fc_surcharge; } public void setFc_surcharge(int fc_surcharge) { this.fc_surcharge = fc_surcharge; } public int getPtv_fee() { return ptv_fee; } public void setPtv_fee(int ptv_fee) { this.ptv_fee = ptv_fee; } public int getGst() { return gst; } public void setGst(int gst) { this.gst = gst; } public int getElectricity_duty() { return electricity_duty; } public void setElectricity_duty(int electricity_duty) { this.electricity_duty = electricity_duty; } }
OsamaMahmood/BillManagementSystem
src/Models/Bills.java
248,411
package gui; /* ALLE BENÖTIGTEN BIBLIOTHEKEN */ import java.awt.*; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import CSV.ReaderCSVtoArray_Funktions; import Chart.plotTheFirstChannle_Button; import JASON.Open_Jason_Button; import communication.Refresh_Button; import communication.Openport_Button; import org.jfree.chart.ChartFactory; import com.fazecast.jSerialComm.SerialPort; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import send.Send_Data_Button; import java.nio.file.Files; import java.nio.file.Path; import java.io.*; import java.util.*; import java.util.List; import static CSV.ReaderCSVtoArray_Funktions.*; public class Windo implements Observer { /* Beim ersten Kompilieren müssen Sie eine txt-Datei und eine CSV-Datendatei erstellen. Die Datei muss erstellt und ihr Pfad hier eingetragen werden. */ public static String filePath = "C:\\Users\\bilal\\Dropbox\\Abscluss\\Smartcontrollerr\\users.csv"; public static String filePathtex = "C:\\Users\\bilal\\Dropbox\\Abscluss\\Smartcontrollerr\\data.txt"; /* Komponenten der GUI */ private JFrame frame; private JFrame frame1; static public JTextField Volte_Value; static public JTextField Time_On; static public JTextField Time_In; static public JTextField Time_Out; static public JTextField Time_Peak; static public JTextField Frequency; static public JTextField Number_of_Pulses; static public JTextField Volte_Value_2; static public JTextField Time_on_2; static public JTextField Time_In_2; static public JTextField Time_Out_2; static public JTextField Time_Peak_2; static public JTextField Frequency_2; static public JTextField Number_of_Pulses_2; static public JTextField Frequenz_PWM_1; static public JTextField Frequenz_PWM_2; ImageIcon imagePWM = new ImageIcon("PWM.PNG"); ImageIcon imageTrapez = new ImageIcon("Trapez.PNG"); public static JComboBox<String> Portlist = new JComboBox(); public static JButton ConnectButton = new JButton("Connect"); JButton UpdateButton = new JButton("Update"); JButton PlotButton = new JButton("Plot"); JButton sendButton = new JButton("send"); JButton saveButton = new JButton("Save"); JButton OpenJson1 = new JButton("OpenJson"); JButton SaveJason1 = new JButton("SaveJason"); JButton OpenJson2 = new JButton("OpenJson"); JButton SaveJason2 = new JButton("SaveJason"); static JButton Start_PWM_1_Full_bridge = new JButton("Start(voll)"); static JButton Start_PWM_1_half_bridge = new JButton("Start(halb)"); static JButton Start_PWM_2_half_bridge = new JButton("Start(halb)"); static JButton Start_PWM_2_Full_bridge = new JButton("Start(voll)"); JTextPane empfangen = new JTextPane(); static String[] DutyCycleSelct ={"5%","10%","20%","30%","40%","50%","60%","70%","80%","90%","100%"}; static String [] FrequenzSelct={"10kHz","5kHz","2kHz","1kHz","500Hz"}; static JComboBox SamlingFrequenz = new JComboBox(FrequenzSelct); static public JComboBox DutyCycle = new JComboBox(DutyCycleSelct); static public JComboBox DutyCycle_2 = new JComboBox(DutyCycleSelct); SerialPort[] portNames = SerialPort.getCommPorts(); public static Scanner scanner; public static SerialPort chosenPort; Enumeration enumComm; public static String analog; static JTabbedPane forchart = new JTabbedPane(JTabbedPane.TOP); public static XYSeries series1 = new XYSeries("Analog Eingan(1)"); public static XYSeries series2 = new XYSeries("Analog Eingan(2)"); public static XYSeries series3 = new XYSeries("Analog Eingan(3)"); String xAxisLabelunit ="Zeit (mS)"; public static XYSeriesCollection dataset = new XYSeriesCollection(); static int Samplingfrequenz = 1350; static double SamplingfrequenzNumber= 10000; static double PeriodinMileroSec=1000; static int PeriodiofSprung=0; static double sampledauer=PeriodinMileroSec/SamplingfrequenzNumber; static public double Duty_Cycle_PWM_1; static public double Duty_Cycle_PWM_2; static String []Periodselct={"100ms","200ms","500ms","1s","2s","3s"}; static String []PeriodselctSprung={"100ms","200ms","300ms","400ms","500ms","1s","2s","3s"}; static JComboBox Sprung_Dauer_2 = new JComboBox(PeriodselctSprung); //static JComboBox Sprung_Dauer_1 = new JComboBox(PeriodselctSprung); static JComboBox Sprung_Dauer_1 = new JComboBox(PeriodselctSprung); static JComboBox Period = new JComboBox(Periodselct); static int x = 0; private JLabel Foto; public static JTextField SamplingFrequenz; public static JTextField number_of_samples; private JTextField Sprung_Number_1; private JTextField Sprung_Number_2; // CommunicationView ss =new CommunicationView(); public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Windo window = new Windo(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Windo() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setSize(1700, 1021); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[]{392, 0}; gridBagLayout.rowHeights = new int[]{22, 0, 45, 15, 0, 0, 0}; gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gridBagLayout.rowWeights = new double[]{0.0, 1.0, 1.0, 1.0, 1.0, 1.0, Double.MIN_VALUE}; frame.getContentPane().setLayout(gridBagLayout); JMenuBar menuBar = new JMenuBar(); GridBagConstraints gbc_menuBar = new GridBagConstraints(); gbc_menuBar.anchor = GridBagConstraints.NORTHWEST; gbc_menuBar.insets = new Insets(0, 0, 5, 0); gbc_menuBar.gridx = 0; gbc_menuBar.gridy = 0; frame.getContentPane().add(menuBar, gbc_menuBar); JMenu TheMenu = new JMenu("Menu"); menuBar.add(TheMenu); JMenuItem New_measurement = new JMenuItem("New measurement"); TheMenu.add(New_measurement); JMenuItem Start_measrument = new JMenuItem("Start Measrument"); TheMenu.add(Start_measrument); JMenuItem Import = new JMenuItem("Import"); TheMenu.add(Import); JMenuItem Save_Data = new JMenuItem("Save"); Save_Data.setSelected(true); TheMenu.add(Save_Data); JMenuItem Open = new JMenuItem("Open"); TheMenu.add(Open); JMenu menu = new JMenu("New menu"); TheMenu.add(menu); JMenu mnNewMenu = new JMenu("Daten_Tools"); menuBar.add(mnNewMenu); JMenuItem mntmNewMenuItem = new JMenuItem("New menu item"); mnNewMenu.add(mntmNewMenuItem); JMenu mnNewMenu_1 = new JMenu("Hilfe"); menuBar.add(mnNewMenu_1); JMenuItem mntmNewMenuItem_1 = new JMenuItem("New menu item"); mnNewMenu_1.add(mntmNewMenuItem_1); JLayeredPane layeredPane_3 = new JLayeredPane(); layeredPane_3.setBackground(UIManager.getColor("CheckBox.foreground")); GridBagConstraints gbc_layeredPane_3 = new GridBagConstraints(); gbc_layeredPane_3.insets = new Insets(0, 0, 5, 0); gbc_layeredPane_3.fill = GridBagConstraints.BOTH; gbc_layeredPane_3.gridx = 0; gbc_layeredPane_3.gridy = 1; frame.getContentPane().add(layeredPane_3, gbc_layeredPane_3); JPanel panel = new JPanel(); panel.setBounds(0, 0, 308, 129); layeredPane_3.add(panel); panel.setLayout(null); /* So suchen Sie nach allen verfügbaren COM-Ports am Host-PC */ Portlist.setBounds(53, 46, 191, 24); panel.add(Portlist); for (int i = 0; i < Protzahl(); i++) { Portlist.addItem(portNames[i].getSystemPortName()); } this.ConnectButton.addActionListener(new Openport_Button()); // window.add(new ChartPanel(chart), BorderLayout.CENTER); ConnectButton.setBounds(10, 11, 124, 24); panel.add(ConnectButton); saveButton.setBounds(10, 81, 108, 24); panel.add(saveButton); //this.saveButton.addActionListener(new Windo.savetojason()); this.saveButton.addActionListener(new savetojason()); this.UpdateButton.addActionListener(new Refresh_Button()); UpdateButton.setBounds(168, 11, 130, 24); panel.add(UpdateButton); sendButton.setBounds(168, 81, 111, 24); panel.add(sendButton); JPanel panel_3 = new JPanel(); panel_3.setBounds(314, 13, 431, 116); layeredPane_3.add(panel_3); panel_3.setLayout(null); empfangen.setBounds(10, 11, 411, 94); panel_3.add(empfangen); this.sendButton.addActionListener(new Send_Data_Button()); JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); GridBagConstraints gbc_tabbedPane = new GridBagConstraints(); gbc_tabbedPane.insets = new Insets(0, 0, 5, 0); gbc_tabbedPane.gridheight = 4; gbc_tabbedPane.fill = GridBagConstraints.BOTH; gbc_tabbedPane.gridx = 0; gbc_tabbedPane.gridy = 2; frame.getContentPane().add(tabbedPane, gbc_tabbedPane); JLayeredPane chart1 = new JLayeredPane(); tabbedPane.addTab("Measurment", null, chart1, null); this.PlotButton.addActionListener(new plotTheFirstChannle_Button()); PlotButton.setBounds(166, 11, 89, 23); //chart1.add(PlotButton); JButton refrechButton_1 = new JButton("refrechChart"); refrechButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { refresh(); } }); refrechButton_1.setBounds(211, 43, 137, 40); chart1.add(refrechButton_1); forchart.setBounds(0, 130, 1700, 600); chart1.add(forchart); forchart.add(new ChartPanel(createChart(dataset,XPlot())), BorderLayout.CENTER); JButton ReadtoCSV = new JButton("Start Measumernt"); ReadtoCSV.addActionListener(new StartMeasumernt_Button()); ReadtoCSV.setBounds(10, 11, 133, 23); //chart1.add(ReadtoCSV); /* Start measurement button */ JButton clear = new JButton("Start Measumernt"); clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StartMeaseumnt_Windo x=new StartMeaseumnt_Windo(); x.setVisible(true); try { } catch (Exception ex) // any other error { JOptionPane.showMessageDialog(null, "Es gab einen Fehler!\n" + ex.getMessage()); } } // } }); clear.setBounds(32, 43, 153, 40); chart1.add(clear); SamplingFrequenz = new JTextField(); SamplingFrequenz.setBounds(633, 11, 102, 23); chart1.add(SamplingFrequenz); SamplingFrequenz.setColumns(10); JLabel Samplingfrequenzlsb = new JLabel("Samplingfrequenz"); Samplingfrequenzlsb.setBounds(509, 11, 114, 23); chart1.add(Samplingfrequenzlsb); JLabel numberofsampleslab = new JLabel("period"); numberofsampleslab.setBounds(764, 11, 121, 23); chart1.add(numberofsampleslab); number_of_samples = new JTextField(); number_of_samples.setBounds(878, 11, 114, 21); chart1.add(number_of_samples); number_of_samples.setColumns(10); JButton ADCSampling = new JButton("Apply"); ADCSampling.addActionListener(new Apply_Button()); ADCSampling.setBounds(1020, 11, 89, 23); chart1.add(ADCSampling); SamlingFrequenz.setBounds(627, 51, 107, 24); chart1.add(SamlingFrequenz); SamlingFrequenz.addActionListener(new Frequenz_Selct_1_ComboBox()); Period.setBounds(878, 51, 114, 24); chart1.add(Period); Period.addActionListener( new PeriodSelct_ComboBox()); JLayeredPane layeredPane_2 = new JLayeredPane(); tabbedPane.addTab("Excitation Settings", null, layeredPane_2, null); JTabbedPane tabbedPane_1 = new JTabbedPane(JTabbedPane.TOP); tabbedPane_1.setBounds(0, 0, 1700, 1008); layeredPane_2.add(tabbedPane_1); String[] items = {"PWM","Stop","Start"}; // Get current value JComboBox Analoginput = new JComboBox(items); Analoginput.setBounds(92, 105, 89, 24); panel.add(Analoginput); ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (Analoginput.getSelectedItem() == "PWM") { analog = PWMCaluation(); } if (Analoginput.getSelectedItem() == "Stop") { analog = "dis"; } if (Analoginput.getSelectedItem() == "Start") { analog = "en"; } } }; Analoginput.addActionListener(actionListener); JLayeredPane PWM = new JLayeredPane(); tabbedPane_1.addTab("Trapz", null, PWM, null); JLabel Ausgang_1 = new JLabel("Ausgang 1"); Ausgang_1.setBounds(645, 0, 101, 29); PWM.add(Ausgang_1); JLabel Ausgang_2 = new JLabel("Ausgang 2"); Ausgang_2.setBounds(934, 0, 85, 29); PWM.add(Ausgang_2); JPanel panel_2_2 = new JPanel(); panel_2_2.setLayout(null); panel_2_2.setBounds(582, 32, 200, 189); PWM.add(panel_2_2); JLabel lblNewLabel_2_4 = new JLabel("Ausgabetyp"); lblNewLabel_2_4.setBounds(10, 8, 63, 17); panel_2_2.add(lblNewLabel_2_4); JLabel Uon_Ion = new JLabel("Uon/Ion"); Uon_Ion.setBounds(10, 30, 63, 17); panel_2_2.add(Uon_Ion); Volte_Value = new JTextField(); Volte_Value.setColumns(10); Volte_Value.setBounds(78, 30, 96, 20); panel_2_2.add(Volte_Value); JLabel Ton = new JLabel("Ton"); Ton.setBounds(10, 52, 63, 17); panel_2_2.add(Ton); Time_On = new JTextField(); Time_On.setColumns(10); Time_On.setBounds(78, 52, 96, 20); panel_2_2.add(Time_On); JLabel Tin = new JLabel("Tin"); Tin.setBounds(10, 74, 63, 17); panel_2_2.add(Tin); Time_In = new JTextField(); Time_In.setColumns(10); Time_In.setBounds(78, 74, 96, 20); panel_2_2.add(Time_In); JComboBox comboBox_2 = new JComboBox(); comboBox_2.setBounds(78, 4, 96, 24); panel_2_2.add(comboBox_2); JLabel Tout = new JLabel("Tout"); Tout.setBounds(10, 98, 63, 17); panel_2_2.add(Tout); Time_Out = new JTextField(); Time_Out.setColumns(10); Time_Out.setBounds(78, 96, 96, 20); panel_2_2.add(Time_Out); JLabel Tpeak = new JLabel("Tpeak"); Tpeak.setBounds(10, 118, 63, 17); panel_2_2.add(Tpeak); Time_Peak = new JTextField(); Time_Peak.setColumns(10); Time_Peak.setBounds(78, 118, 96, 20); panel_2_2.add(Time_Peak); JLabel Frequenz = new JLabel("Frequenz"); Frequenz.setBounds(10, 140, 63, 17); panel_2_2.add(Frequenz); Frequency = new JTextField(); Frequency.setColumns(10); Frequency.setBounds(78, 140, 96, 20); panel_2_2.add(Frequency); JLabel Anzahl = new JLabel("Anzahl"); Anzahl.setBounds(10, 162, 63, 17); panel_2_2.add(Anzahl); Number_of_Pulses = new JTextField(); Number_of_Pulses.setColumns(10); Number_of_Pulses.setBounds(78, 162, 96, 20); panel_2_2.add(Number_of_Pulses); JPanel panel_2_1_1 = new JPanel(); panel_2_1_1.setLayout(null); panel_2_1_1.setBounds(872, 32, 200, 189); PWM.add(panel_2_1_1); JLabel lblNewLabel_2_3_1 = new JLabel("Ausgabetyp"); lblNewLabel_2_3_1.setBounds(10, 8, 63, 17); panel_2_1_1.add(lblNewLabel_2_3_1); JLabel Uon_Ion2 = new JLabel("Uon/Ion"); Uon_Ion2.setBounds(10, 30, 63, 17); panel_2_1_1.add(Uon_Ion2); Volte_Value_2 = new JTextField(); Volte_Value_2.setColumns(10); Volte_Value_2.setBounds(78, 30, 96, 20); panel_2_1_1.add(Volte_Value_2); JLabel Ton2 = new JLabel("Ton"); Ton2.setBounds(10, 52, 63, 17); panel_2_1_1.add(Ton2); Time_on_2 = new JTextField(); Time_on_2.setColumns(10); Time_on_2.setBounds(78, 52, 96, 20); panel_2_1_1.add(Time_on_2); JLabel Tin2 = new JLabel("Tin"); Tin2.setBounds(10, 74, 63, 17); panel_2_1_1.add(Tin2); Time_In_2 = new JTextField(); Time_In_2.setColumns(10); Time_In_2.setBounds(78, 74, 96, 20); panel_2_1_1.add(Time_In_2); JComboBox comboBox_1_1 = new JComboBox(); comboBox_1_1.setBounds(78, 4, 96, 24); panel_2_1_1.add(comboBox_1_1); JLabel Tout2 = new JLabel("Tout"); Tout2.setBounds(10, 98, 63, 17); panel_2_1_1.add(Tout2); Time_Out_2 = new JTextField(); Time_Out_2.setColumns(10); Time_Out_2.setBounds(78, 96, 96, 20); panel_2_1_1.add(Time_Out_2); JLabel Tpeak2 = new JLabel("Tpeak"); Tpeak2.setBounds(10, 118, 63, 17); panel_2_1_1.add(Tpeak2); Time_Peak_2 = new JTextField(); Time_Peak_2.setColumns(10); Time_Peak_2.setBounds(78, 118, 96, 20); panel_2_1_1.add(Time_Peak_2); JLabel Frequenz2 = new JLabel("Frequenz"); Frequenz2.setBounds(10, 140, 63, 17); panel_2_1_1.add(Frequenz2); Frequency_2 = new JTextField(); Frequency_2.setColumns(10); Frequency_2.setBounds(78, 140, 96, 20); panel_2_1_1.add(Frequency_2); JLabel Anzahl2 = new JLabel("Anzahl"); Anzahl2.setBounds(10, 162, 63, 17); panel_2_1_1.add(Anzahl2); Number_of_Pulses_2 = new JTextField(); Number_of_Pulses_2.setColumns(10); Number_of_Pulses_2.setBounds(78, 162, 96, 20); panel_2_1_1.add(Number_of_Pulses_2); OpenJson1.setBounds(638, 245, 108, 29); PWM.add(OpenJson1); this.OpenJson1.addActionListener(new Open_Jason_Button()); SaveJason1.setBounds(638, 221, 108, 29); PWM.add(SaveJason1); this.SaveJason1.addActionListener(new savetojason()); Foto = new JLabel("Foto"); Foto.setBounds(0, -58, 1674, 1001); Foto.setIcon(imageTrapez); PWM.add(Foto); SaveJason2.setBounds(934, 221, 108, 29); PWM.add(SaveJason2); this.SaveJason2.addActionListener(new savetojason2()); OpenJson2.setBounds(934, 248, 108, 29); PWM.add(OpenJson2); this.OpenJson2.addActionListener(new Open_Jason_Button()); JLayeredPane Trapez = new JLayeredPane(); tabbedPane_1.addTab("PWM", null, Trapez, null); JLabel lblNewLabel_1_2_1 = new JLabel("Ausgang 1"); lblNewLabel_1_2_1.setBounds(638, 0, 85, 29); Trapez.add(lblNewLabel_1_2_1); JLabel lblNewLabel_1_1_1_1 = new JLabel("Ausgang 2"); lblNewLabel_1_1_1_1.setBounds(938, 0, 85, 29); Trapez.add(lblNewLabel_1_1_1_1); JPanel Ausgang_PWM_1 = new JPanel(); Ausgang_PWM_1.setLayout(null); Ausgang_PWM_1.setBounds(555, 32, 227, 189); Trapez.add(Ausgang_PWM_1); JLabel DutyCyclePWM1 = new JLabel("DutyCycle"); DutyCyclePWM1.setBounds(10, 45, 63, 17); Ausgang_PWM_1.add(DutyCyclePWM1); JLabel FrequenzPWM1 = new JLabel("Frequenz [KHz]"); FrequenzPWM1.setBounds(10, 112, 94, 17); Ausgang_PWM_1.add(FrequenzPWM1); Frequenz_PWM_1 = new JTextField(); Frequenz_PWM_1.setColumns(10); Frequenz_PWM_1.setBounds(114, 111, 88, 18); Ausgang_PWM_1.add(Frequenz_PWM_1); DutyCycle .addActionListener(new Duty_Cycle_1_ComboBox()); DutyCycle.setBounds(114, 41, 98, 24); Ausgang_PWM_1.add(DutyCycle); JPanel Ausgang_PWM_2 = new JPanel(); Ausgang_PWM_2.setLayout(null); Ausgang_PWM_2.setBounds(864, 32, 237, 189); Trapez.add(Ausgang_PWM_2); JLabel DutyCyclePWM2 = new JLabel("DutyCycle"); DutyCyclePWM2.setBounds(10, 38, 63, 17); Ausgang_PWM_2.add(DutyCyclePWM2); JLabel FrequenzPWM2 = new JLabel("Frequenz [kHz]"); FrequenzPWM2.setBounds(10, 111, 99, 17); Ausgang_PWM_2.add(FrequenzPWM2); Frequenz_PWM_2 = new JTextField(); Frequenz_PWM_2.setColumns(10); Frequenz_PWM_2.setBounds(119, 108, 88, 20); Ausgang_PWM_2.add(Frequenz_PWM_2); DutyCycle_2.setBounds(119, 34, 98, 24); Ausgang_PWM_2.add(DutyCycle_2); DutyCycle_2.addActionListener(new Duty_Cycle_2_ComboBox()); Start_PWM_1_Full_bridge.addActionListener(new Start_PWM_1_Full_bridge_Button()); Start_PWM_1_Full_bridge.setBounds(545, 232, 127, 29); Trapez.add(Start_PWM_1_Full_bridge); Start_PWM_1_half_bridge.addActionListener(new Start_PWM_1_half_bridge_Button()); Start_PWM_1_half_bridge.setBounds(680, 232, 127, 29); Trapez.add(Start_PWM_1_half_bridge); Start_PWM_2_Full_bridge.addActionListener(new Start_PWM_2_Full_bridge_Button()); Start_PWM_2_Full_bridge.setBounds(845, 232, 127, 29); Trapez.add(Start_PWM_2_Full_bridge); Start_PWM_2_half_bridge.addActionListener(new Start_PWM_2_half_bridge_Button()); Start_PWM_2_half_bridge.setBounds(995, 232, 127, 29); Trapez.add(Start_PWM_2_half_bridge); JLayeredPane Sprung = new JLayeredPane(); tabbedPane_1.addTab("Sprung", null, Sprung, null); JPanel Ausgang_PWM_1_1 = new JPanel(); Ausgang_PWM_1_1.setLayout(null); Ausgang_PWM_1_1.setBounds(513, 32, 269, 224); Sprung.add(Ausgang_PWM_1_1); JLabel Sprung_Dauer = new JLabel("Sprung Dauer"); Sprung_Dauer.setHorizontalAlignment(SwingConstants.LEFT); Sprung_Dauer.setBounds(10, 60, 88, 20); Ausgang_PWM_1_1.add(Sprung_Dauer); JLabel FrequenzPWM1_1 = new JLabel("Anzahl of Sprung"); FrequenzPWM1_1.setBounds(10, 112, 98, 20); Ausgang_PWM_1_1.add(FrequenzPWM1_1); Sprung_Number_1 = new JTextField(); Sprung_Number_1.setColumns(10); Sprung_Number_1.setBounds(137, 111, 88, 21); Ausgang_PWM_1_1.add(Sprung_Number_1); Sprung_Dauer_1.addActionListener(new Sprung_1_Dauer_ComboBox()); Sprung_Dauer_1.setBounds(127, 56, 98, 24); Ausgang_PWM_1_1.add(Sprung_Dauer_1); JLabel lblNewLabel_1_2_1_1 = new JLabel("Ausgang 1"); lblNewLabel_1_2_1_1.setBounds(621, 0, 85, 29); Sprung.add(lblNewLabel_1_2_1_1); JLabel lblNewLabel_1_1_1_1_1 = new JLabel("Ausgang 2"); lblNewLabel_1_1_1_1_1.setBounds(964, 0, 85, 29); Sprung.add(lblNewLabel_1_1_1_1_1); JPanel Ausgang_PWM_1_1_1 = new JPanel(); Ausgang_PWM_1_1_1.setLayout(null); Ausgang_PWM_1_1_1.setBounds(880, 32, 269, 224); Sprung.add(Ausgang_PWM_1_1_1); JLabel Sprung_Dauer_1_1 = new JLabel("Sprung Dauer"); Sprung_Dauer_1_1.setHorizontalAlignment(SwingConstants.LEFT); Sprung_Dauer_1_1.setBounds(10, 60, 88, 20); Ausgang_PWM_1_1_1.add(Sprung_Dauer_1_1); JLabel FrequenzPWM1_1_1 = new JLabel("Anzahl of Sprung"); FrequenzPWM1_1_1.setBounds(10, 112, 98, 20); Ausgang_PWM_1_1_1.add(FrequenzPWM1_1_1); Sprung_Number_2 = new JTextField(); Sprung_Number_2.setColumns(10); Sprung_Number_2.setBounds(137, 111, 88, 21); Ausgang_PWM_1_1_1.add(Sprung_Number_2); Sprung_Dauer_2.addActionListener(new Sprung_2_Dauer_ComboBox()); Sprung_Dauer_2.setBounds(127, 56, 98, 24); Ausgang_PWM_1_1_1.add(Sprung_Dauer_2); JButton Sprung_1_Start = new JButton("Start Sprung "); Sprung_1_Start.setBounds(598, 279, 111, 29); Sprung.add(Sprung_1_Start); Sprung_1_Start.addActionListener(new Sprung_1_Button()); JButton Sprung_2_Start = new JButton("Start Sprung "); Sprung_2_Start.setBounds(964, 282, 111, 29); Sprung.add(Sprung_2_Start); Sprung_2_Start.addActionListener(new Sprung_2_Button()); JLayeredPane layeredPane_1 = new JLayeredPane(); tabbedPane.addTab("Measurment Settings", null, layeredPane_1, null); JPanel panel_1 = new JPanel(); panel_1.setBounds(10, 0, 502, 316); layeredPane_1.add(panel_1); panel_1.setLayout(null); JLabel lblNewLabel = new JLabel("Current"); lblNewLabel.setBounds(10, 26, 47, 14); panel_1.add(lblNewLabel); JLabel lblVoltage = new JLabel("Voltage"); lblVoltage.setBounds(10, 55, 47, 14); panel_1.add(lblVoltage); JLabel lblPosition = new JLabel("Position"); lblPosition.setBounds(10, 79, 47, 26); panel_1.add(lblPosition); JTextPane textPane = new JTextPane(); textPane.setBounds(62, 21, 79, 25); panel_1.add(textPane); JTextPane textPane_1 = new JTextPane(); textPane_1.setBounds(62, 51, 79, 25); panel_1.add(textPane_1); JTextPane textPane_2 = new JTextPane(); textPane_2.setBounds(62, 81, 79, 25); panel_1.add(textPane_2); } /* Funktion zum Erstellen eines Diagramms */ public static JFreeChart createChart(XYDataset dataset, String xAxisLabel) { String chartTitle = "Analog Messung"; //String xAxisLabel = "Zeit in "+XPlot(); String yAxisLabel = "Spannung (volt)"; JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, xAxisLabel, yAxisLabel, dataset, PlotOrientation.VERTICAL, true, true, false); XYPlot plot = chart.getXYPlot(); NumberAxis xAxis = new NumberAxis(); xAxis.setLabel(xAxisLabel); NumberAxis yAxis = (NumberAxis) plot.getRangeAxis(); yAxis.setRange(-10, 10); yAxis.setTickUnit(new NumberTickUnit(0.5)); return chart; } private void connect() { } @Override public void update(Observable o, Object arg) { } /* zur Berechnung in korrekter Zahlenform Frequenz und Duty Cycle */ String PWMCaluation() { //168=1us String Massg = null; try { double frequenz_pwm_1Value = Double.parseDouble(Frequenz_PWM_1.getText()); double duty_cycle_pwm_1_Value = Duty_Cycle_PWM_1; double peroid_pwm_1Value = 1 / frequenz_pwm_1Value; int peroid_pwm_1Valuetimer = (int) (peroid_pwm_1Value * 168 *33* 10); //int duty_cycle_pwm_1_percent = (int) (((duty_cycle_pwm_1_Value) / 100) * peroid_pwm_1Valuetimer); double duty_cycle_pwm_1_percent = ((duty_cycle_pwm_1_Value) * peroid_pwm_1Valuetimer); System.out.println(duty_cycle_pwm_1_percent); Massg = "2/" + String.valueOf(peroid_pwm_1Valuetimer) + "/" + String.valueOf((int)duty_cycle_pwm_1_percent); return Massg; } catch (Exception NumberFormatException) { JOptionPane.showMessageDialog(null, "Bitte Geben Sie die Frequenz und Duty Cycle \n" ); } return Massg; } /* die Anzahl der verfügbaren Anschlüsse zu ermitteln */ int Protzahl() { return portNames.length; } public static String fileToString(String filePath) throws Exception { String input = null; Scanner sc = new Scanner(new File(filePath)); StringBuffer sb = new StringBuffer(); while (sc.hasNextLine()) { input = sc.nextLine(); sb.append(input); } return sb.toString(); /* löschen das Digramm */ } void refresh(){ series1.clear(); series3.clear(); series2.clear(); } /* X-Beschriftung anpassen */ static String XPlot(){ String Xachselabe=String.valueOf(sampledauer); String Periodselction= String.valueOf(Period.getSelectedItem()); String x=Periodselction; return x+" [ein Sample daurt"+Xachselabe+" uS] "; } }
BelalAbulabn/SmartControllerMeasurementApp
src/gui/Windo.java
248,412
package dutyrostering.dutyrostering; /** * This class was automatically generated by the data modeler tool. */ public class Employee implements java.io.Serializable { static final long serialVersionUID = 1L; private java.lang.String name; private dutyrostering.dutyrostering.Duty duty; public Employee() { } public java.lang.String getName() { return this.name; } public void setName(java.lang.String name) { this.name = name; } public dutyrostering.dutyrostering.Duty getDuty() { return this.duty; } public void setDuty(dutyrostering.dutyrostering.Duty duty) { this.duty = duty; } public Employee(java.lang.String name, dutyrostering.dutyrostering.Duty duty) { this.name = name; this.duty = duty; } }
likhia/DutyRosterProject
dutyRoster/Employee.java
248,413
/* * 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 DTO; /** * * @author Thuan Vo */ public class ct_quyenDTO { int id_permission; int id_duty; public ct_quyenDTO(int id_role, int id_duty) { this.id_permission = id_role; this.id_duty = id_duty; } public ct_quyenDTO() { this.id_permission = 0; this.id_duty = 0; } public int getId_permission() { return id_permission; } public void setId_permission(int id_permission) { this.id_permission = id_permission; } public int getid_duty() { return id_duty; } public void setid_duty(int id_duty) { this.id_duty = id_duty; } }
VoNhu2901/java-swing-project
src/DTO/ct_quyenDTO.java
248,414
/* * 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 DTO; /** * * @author Thuan Vo */ public class CategoryDTO { int id_duty; String name, image , image_hover; public CategoryDTO() { this.id_duty = 0; this.name = ""; this.image = ""; this.image_hover = ""; } public CategoryDTO(int id_duty, String name, String image, String image_hover) { this.id_duty = id_duty; this.name = name; this.image = image; this.image_hover = image_hover; } public int getId_duty() { return id_duty; } public void setId_duty(int id_duty) { this.id_duty = id_duty; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getImage_hover() { return image_hover; } public void setImage_hover(String image_hover) { this.image_hover = image_hover; } @Override public String toString() { return name + ":" + image + ":" + image_hover ; } }
VoNhu2901/java-swing-project
src/DTO/CategoryDTO.java
248,415
public class Nurse{ int maxRoleNum = 1000; String name = new String(); String passwd = new String(); String sex = new String(); int age; String[] duty = new String[maxRoleNum]; String office = new String(); String[] role = new String[maxRoleNum]; }
OpenISDM/PERMIS_PEP
PERMIS_PEP/lib/Nurse.java
248,416
package General; import java.io.Serializable; public class Outduty implements Serializable{ private int employeeid; private String name,department,designation,date,timeout,reason; public Outduty(int employeeid, String name, String department, String designation, String date, String timeout, String reason) { this.employeeid = employeeid; this.name = name; this.department = department; this.designation = designation; this.date = date; this.timeout = timeout; this.reason = reason; } public int getEmployeeid() { return employeeid; } public void setEmployeeid(int employeeid) { this.employeeid = employeeid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getTimeout() { return timeout; } public void setTimeout(String timeout) { this.timeout = timeout; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } }
bhakta009/attendence_monitoring_system
src/General/Outduty.java
248,417
import java.util.Scanner; class CustomDuty{ public static void main (String args[]){ Scanner scanner = new Scanner(System.in); System.out.println("What is the value of your imported item"); int value = scanner.nextInt(); double duty = 0.03 * value; double purchaseTax = 0.02*(value + duty); double totalpercentage = ((duty+purchaseTax)/value)*100; System.out.println("The custom duty of your product is:" +duty); System.out.println("The purchase duty of your product is:"+purchaseTax); System.out.println("The total percentage taxed is:" +totalpercentage); scanner.close(); } }
nzommmo/JAVA
CustomDuty.java
248,419
public class GeneralStaff extends Employee { GeneralStaff(){ super(); this.duty = ""; } GeneralStaff(String duty){ super(); this.duty = duty; } GeneralStaff(String deptName, String duty){ super(deptName); this.duty = duty; } GeneralStaff(String name, int birthYear, String deptName, String duty) { super(name, birthYear, deptName); this.duty = duty; } public String getDuty() { return this.duty; } @Override public String toString() { return String.format(super.toString() + " GeneralStaff: Duty: %10s", duty); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof GeneralStaff)) return false; if (!super.equals(o)) return false; GeneralStaff that = (GeneralStaff) o; return duty.equals(that.duty); } private String duty; }
lehman-classes/2021-Fall-CMP168
lab1/GeneralStaff.java
248,420
package ViewDB; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import Database.FileReadWriteOutDuty; import General.Outduty; public class ViewOutDuty extends JFrame{ private JTable table; private ArrayList<Outduty> list; private String[] heading={"Employee ID","Name","Department","Designation","Date","Time Out","Reason"}; private String[][] data; private JScrollPane pane; public ViewOutDuty() { list=new ArrayList<Outduty>(); //reading from file try { list=FileReadWriteOutDuty.readingFromOutDutydetail(); } catch (Exception e) { System.out.println("File not found"); } data=new String[list.size()][7]; //get object int index,row=0,col=0; for(index=0;index<list.size();index++) { Outduty outduty=list.get(index); data[row][col]=String.valueOf(outduty.getEmployeeid()); data[row][++col]=outduty.getName(); data[row][++col]=outduty.getDepartment(); data[row][++col]=outduty.getDesignation(); data[row][++col]=outduty.getDate(); data[row][++col]=outduty.getTimeout(); data[row][++col]=outduty.getReason(); col=0; ++row; } table=new JTable(data,heading); pane=new JScrollPane(table); add(pane); setSize(400,200); setVisible(true); setTitle("View Details"); } public static void main(String []arg) { new ViewOutDuty(); } }
bhakta009/attendence_monitoring_system
src/ViewDB/ViewOutDuty.java
248,421
public class GeneralStaff extends Employee { private String duty; //----------------------CONSTRUCTORS-------------------------------------------- public GeneralStaff() { super(); this.duty = ""; } public GeneralStaff(String duty) { super(); this.duty = duty; } public GeneralStaff(String deptName, String duty) { super(deptName); this.duty = duty; } public GeneralStaff(String name, int birthYear, String deptName, String duty) { super(name, birthYear, deptName); this.duty = duty; } //------------------------GETTER------------------------------------------------- public String getDuty() { return this.duty; } //----------------------@Override------------------------------------------------ @Override public boolean equals(Object obj) { if (obj instanceof GeneralStaff) { GeneralStaff gs = (GeneralStaff) obj; if (super.equals(gs) && this.duty.equals(gs.getDuty())) return true; } return false; } @Override public String toString() { return String.format(super.toString() + " GeneralStaff: Duty: %10s", duty ); } }
Ljupcho-Atanasov/School_Database
GeneralStaff.java
248,423
public class GeneralStaff extends Employee{ private String duty; public GeneralStaff() { super(); this.duty = ""; } public GeneralStaff(String duty) { super(); this.duty = duty; } public GeneralStaff(String deptName, String duty) { super(deptName); this.duty = duty; } public GeneralStaff(String name, int birthYear, String deptName, String duty) { super(name,birthYear,deptName); this.duty = duty; } public String getDuty() { return this.duty; } @Override public boolean equals(Object gs) { if(super.equals(gs)) { if (gs instanceof GeneralStaff) { GeneralStaff gst = (GeneralStaff) gs; if( this.duty.equalsIgnoreCase(gst.getDuty())) { return true; } }} return false; } // @Override public String toString() { String s = super.toString() + String.format( " GeneralStaff: Duty: %10s", this.duty) ; return s; } }
liger1apwm/Project-1-School-DataBase
GeneralStaff.java
248,424
package com.qx.hero; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.Table; import javax.persistence.Transient; import com.qx.persistent.MCSupport; @Entity @Table(name = "WuJiangs", schema = "qxmobile", indexes={@Index(name="owner_id",columnList="owner_id")}) public class WuJiang implements MCSupport { /** * */ public static final long serialVersionUID = -9023310186462522324L; @Id @Column(name = "db_id", unique = true, nullable = false) public long dbId; @Column(name = "hero_id", nullable = false) public int heroId; //基本属性。 //@Column(name = "attack", nullable = false) @Transient public int attack; //@Column(name = "defense", nullable = false) @Transient public int defense; //@Column(name = "hp", nullable = false) @Transient public int hp; //有争议的属性。(不排除将来修改的可能) //@Column(name = "zhimou", nullable = false) @Transient public int zhimou; //@Column(name = "wuyi", nullable = false) @Transient public int wuyi; //@Column(name = "tongshuai", nullable = false) @Transient public int tongshuai; //标签 //@Column(name = "label", nullable = false) @Transient public String label; //品质 //@Column(name = "quality", nullable = false) @Transient public int quality; //星级数据。 //@Column(name = "max_star_num", nullable = false) @Transient public int maxStarNum; /* //忠诚度 //@Column(name = "loyal", nullable = false) @Transient public int loyal; */ //官职 //@Column(name = "duty", nullable = false) @Transient public int duty; //技能 0~4个技能。 //@Column(name = "skill1", nullable = false) @Transient public int skill1; //@Column(name = "skill2", nullable = false) @Transient public int skill2; //@Column(name = "skill3", nullable = false) @Transient public int skill3; //@Column(name = "skill4", nullable = false) @Transient public int skill4; //当前经验值 @Column(name = "exp", nullable = false) public int exp; @Column(name = "owner_id", nullable = false, updatable=false) public long ownerId; public int heroGrowId; public int num; public boolean combine; public int zhanLi; public boolean isCombine() { return combine; } public void setCombine(boolean combine) { this.combine = combine; } public int getHeroGrowId() { return heroGrowId; } public void setHeroGrowId(int heroGrowId) { this.heroGrowId = heroGrowId; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public long getDbId() { return dbId; } public void setDbgId(long wuJiangId) { this.dbId = wuJiangId; } public int getZhimou() { return zhimou; } public void setZhimou(int zhimou) { this.zhimou = zhimou; } public int getWuyi() { return wuyi; } public void setWuyi(int wuyi) { this.wuyi = wuyi; } public int getTongshuai() { return tongshuai; } public void setTongshuai(int tongshuai) { this.tongshuai = tongshuai; } public long getOwnerId() { return ownerId; } public void setOwnerId(long ownerId) { this.ownerId = ownerId; } public int getHeroId() { return heroId; } public void setHeroId(int heroId) { this.heroId = heroId; } public int getAttack() { return attack; } public void setAttack(int attack) { this.attack = attack; } public int getDefense() { return defense; } public void setDefense(int defense) { this.defense = defense; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public int getQuality() { return quality; } public void setQuality(int quality) { this.quality = quality; } public int getMaxStarNum() { return maxStarNum; } public void setMaxStarNum(int maxStarNum) { this.maxStarNum = maxStarNum; } /* public int getLoyal() { return loyal; } public void setLoyal(int loyal) { this.loyal = loyal; } */ public int getDuty() { return duty; } public void setDuty(int duty) { this.duty = duty; } public int getSkill1() { return skill1; } public void setSkill1(int skill1) { this.skill1 = skill1; } public int getSkill2() { return skill2; } public void setSkill2(int skill2) { this.skill2 = skill2; } public int getSkill3() { return skill3; } public void setSkill3(int skill3) { this.skill3 = skill3; } public int getSkill4() { return skill4; } public void setSkill4(int skill4) { this.skill4 = skill4; } public int getExp() { return exp; } public void setExp(int exp) { this.exp = exp; } @Override public long getIdentifier() { return dbId; } }
10people/7x_Server
src/com/qx/hero/WuJiang.java
248,425
package User; import java.util.ArrayList; public class Nurse extends Clinician{ private String duty; private String unit; private ArrayList<Clinician> clinicianList = Clinician.getClinicianList(); public Nurse(String clinicianID, String clinicianName, String clinicianContactNo, String clinicianRNIC, String clinicianPassword, String duty, String unit) { super(clinicianID, clinicianName, clinicianContactNo, clinicianRNIC, clinicianPassword); this.duty = duty; this.unit = unit; clinicianList.add(this); setAccountType("Nurse"); } //Setter public void setDuty(String duty){ this.duty = duty; } public void setUnit(String unit){ this.unit = unit; } //Getter public String getDuty(){ return duty; } public String getUnit(){ return unit; } @Override public String toString(){ return "Nurse Name:" + getClinicianName() + "\n" + "Nurse ID: " + getClinicianID() + "\n" + "Nurse Unit: " + unit; } }
elyiwen/APassignment2
src/User/Nurse.java
248,426
/* Copyright (C) 2016 Syracuse University This file is part of the Spectrum Consumption Model Builder and Analysis Tool 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 program. If not, see <http://www.gnu.org/licenses/>. */ /** * ExecuteDuty.java * Creates report window to display compatibility results * for Duty Cycle rated underlay masks */ package Execute; import java.awt.Dimension; import java.awt.Insets; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JScrollPane; public class ExecuteDuty { String plotPath = "Octave/BTPRatedAnalysis.png"; JFrame frame; JLabel picLabel; JLabel statusLabel=new JLabel(); DefaultListModel<String> ListModel2 = new DefaultListModel<>(); JScrollPane nonCompatPane = new JScrollPane(); JList<String> nonCompatList = new JList<String>(ListModel2); DefaultListModel<String> ListModel3 = new DefaultListModel<>(); JScrollPane compatPane = new JScrollPane(); JList<String> compatList = new JList<String>(ListModel3); public JFrame getFrame(){ frame = new JFrame("Compatibility Analysis Report"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setLayout(null); final Insets insets = frame.getInsets(); frame.setSize((2*550) + insets.left + insets.right, (700) + insets.top + insets.bottom); frame.setVisible(true); BufferedImage img = null; try{ img = ImageIO.read(new File(plotPath)); }catch(Exception e){ e.printStackTrace(); } int w = img.getWidth(); int h = img.getHeight(); BufferedImage NewImg = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB); AffineTransform at = new AffineTransform(); at.scale(0.5, 0.5); AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); NewImg = scaleOp.filter(img,NewImg); picLabel = new JLabel(new ImageIcon(NewImg)); // Graphics g = img.getGraphics(); Dimension picSize = picLabel.getPreferredSize(); picLabel.setBounds(25, 50, picSize.width, picSize.height); // frame.add(picLabel); JLabel resultLabel = new JLabel("Graphical result (Not available for Duty Cycle Rated Masks)"); Dimension resultLabelSize = resultLabel.getPreferredSize(); resultLabel.setBounds(25,30,resultLabelSize.width,resultLabelSize.height); frame.add(resultLabel); JLabel nonCompatLabel = new JLabel("Not Compatible"); Dimension labelSize = nonCompatLabel.getPreferredSize(); nonCompatLabel.setBounds(700,50, labelSize.width, labelSize.height); frame.add(nonCompatLabel); Dimension listSize = nonCompatList.getPreferredSize(); nonCompatPane.setBounds(700,80,listSize.width+350,listSize.height+100); nonCompatPane.setViewportView(nonCompatList); frame.add(nonCompatPane); JLabel compatLabel = new JLabel("Compatible masks"); compatLabel.setBounds(700,230, labelSize.width + 200, labelSize.height); frame.add(compatLabel); compatPane.setBounds(700,260,listSize.width+350,listSize.height+100); compatPane.setViewportView(compatList); frame.add(compatPane); return frame; } public String getPlotPath() { return plotPath; } public void setPlotPath(String plotPath) { this.plotPath = plotPath+"/BTPRatedAnalysis.png"; } void buildNonCompatList(ArrayList<String> nonCompatModelList){ DefaultListModel<String> listModel = (DefaultListModel<String>) nonCompatList.getModel(); for(int i=0;i<nonCompatModelList.size();i++){ listModel.addElement(nonCompatModelList.get(i)); } }; void buildCompatList(ArrayList<String> compatModelList){ DefaultListModel<String> listModel = (DefaultListModel<String>) compatList.getModel(); for(int i=0;i<compatModelList.size();i++){ listModel.addElement(compatModelList.get(i)); } }; }
ccaicedo/SCMBAT
src/Execute/ExecuteDuty.java
248,427
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package evm1; import com.mysql.jdbc.Connection; import com.mysql.jdbc.ResultSet; import com.mysql.jdbc.Statement; import java.sql.DriverManager; import javax.swing.table.DefaultTableModel; /** * * @author hp */ public class offitable extends javax.swing.JInternalFrame { String name,code,address,duty_as,design,addr; /** * Creates new form offitable */ public offitable() { initComponents(); update(); } /** * 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() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setClosable(true); setIconifiable(true); setMaximizable(true); setResizable(true); setTitle("DUTY OFFICER DETAILS"); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Name", "center code", "address of center", "Duty as", "designation", "address of officer" } )); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 743, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 331, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 4, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; // End of variables declaration//GEN-END:variables public void update() { DefaultTableModel model; model = (DefaultTableModel)jTable1.getModel(); // model.addTableModelListener(jTable1); model.addRow (new Object[] {name,code,address,duty_as,design,addr}); Connection con; Statement stmt; ResultSet rs; try { Class.forName("com.mysql.jdbc.Driver"); con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/evom","root","a"); stmt=(Statement)con.createStatement(); String Query="select name,code,address,duty_as,design,addr from officer "; rs=(ResultSet) stmt.executeQuery(Query); // jTable1.setModel(DbUtils.resultSetToTableModel(rs)); int i=0; while(rs.next()) { jTable1.setValueAt(rs.getString(1),i,0); jTable1.setValueAt(rs.getString(2),i,1); jTable1.setValueAt(rs.getString(3),i,2); jTable1.setValueAt(rs.getString(4),i,3); jTable1.setValueAt(rs.getString(5),i,4); jTable1.setValueAt(rs.getString(6),i,5); i++; model.addRow (new Object[] {name,code,address,duty_as,design,addr}); } } catch(Exception e) { System.out.println(e.getMessage()); } } }
Harjeetdhaliwal/Electronic-voting-machine
src/evm1/offitable.java
248,430
package duty_chain; public class Level { }
Jdroida/free_learning
src/duty_chain/Level.java
248,431
public class GeneralStaff extends Employee { private String duty; public GeneralStaff() { super(); this.duty = ""; } public GeneralStaff(String duty) { super(); this.duty = duty; } public GeneralStaff(String depString, String duty) { super(depString); this.duty = duty; } public GeneralStaff(String name, int birthYear, String deptName, String duty) { super(name, birthYear, deptName); this.duty = duty; } public String getDuty() { return duty; } //work on @Override public boolean equals(Object obj) { GeneralStaff next = (GeneralStaff) obj; if(this.duty == next.duty) { return true; } else { return false; } } public String toString() { return super.toString() + String.format(" GeneralStaff: Duty: %10s", duty); } }
TurkeyChans/School-DataBass
GeneralStaff.java
248,433
package duty_chain; //场景类 public class Client { public static void main(String[] args) { Handler handler1 = new ConcreteHandler1(); Handler handler2 = new ConcreteHandler2(); Handler handler3 = new ConcreteHandler3(); handler1.setNext(handler2); handler2.setNext(handler3); Response response = handler1.handleMessage(new Request()); } }
Jdroida/free_learning
src/duty_chain/Client.java
248,434
package day06; /* 4) Staff类中的属性有: 职务称号duty(String类型)。 */ public class Staff extends Employee{ private String duty; public Staff() { } public Staff(String duty) { this.duty = duty; } public String getDuty() { return duty; } public void setDuty(String duty) { this.duty = duty; } }
George9527/JavaStudy
JavaSE基础/day06/Staff.java
248,435
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package com.mycompany.final_project; /** * * @author uraib lakhani */ public class Staff extends Person implements PayRoll{ private String duty; private int workload; public Staff() { } public Staff(String duty, int workload, int id, String name, int age, String gender) { super(id, name, age, gender); this.duty = duty; if (workload > 36){ this.workload = 36; } else{ this.workload = workload; } } public String getDuty() { return duty; } public void setDuty(String duty) { this.duty = duty; } public int getWorkload() { return workload; } public void setWorkload(int workload) { if (workload > 36){ this.workload = 36; } else{ this.workload = workload; } } @Override public String toString() { return "Staff{" + "duty=" + duty + ", workload=" + workload + '}'; } @Override public double computePayRoll() { return (this.workload * 32 * 2) * 0.85; } /*public boolean defineCategory(Object obj) { if(obj.getClass() == this.getClass()){ Student s = (Student) obj; return (s.getId()==this.getId()); } return true; } */ }
uraiblakhani2/project_part1
Staff.java
248,436
package audio.gme; // Nintendo Game Boy sound emulator // http://www.slack.net/~ant/ /* Copyright (C) 2003-2007 Shay Green. This module 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 module 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. You should have received a copy of the GNU Lesser General Public License along with this module; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ class GbOsc { static final boolean gbc_02 = false; // TODO: allow to be set? static final int trigger_mask = 0x80; static final int length_enabled = 0x40; static final int dac_bias = 7; BlipBuffer output; int output_select; final int [] regs = new int [5]; int vol_unit; int delay; int last_amp; int length; int enabled; void reset() { output = null; output_select = 0; delay = 0; last_amp = 0; length = 64; enabled = 0; for ( int i = 5; --i >= 0; ) regs [i] = 0; } void clock_length() { if ( (regs [4] & length_enabled) != 0 && length != 0 ) { if ( --length <= 0 ) enabled = 0; } } int frequency() { return (regs [4] & 7) * 0x100 + regs [3]; } boolean write_register( int frame_phase, int reg, int old_data, int data ) { return false; } int write_trig( int frame_phase, int max_len, int old_data ) { int data = regs [4]; if ( gbc_02 && (frame_phase & 1) != 0 && (old_data & length_enabled) == 0 && length != 0 ) length--; if ( (data & trigger_mask) != 0 ) { enabled = 1; if ( length == 0 ) { length = max_len; if ( gbc_02 && (frame_phase & 1) != 0 && (data & length_enabled) != 0 ) length--; } } if ( gbc_02 && length == 0 ) enabled = 0; return data & trigger_mask; } } class GbEnv extends GbOsc { int env_delay; int volume; int dac_enabled() { return regs [2] & 0xF8; } void reset() { env_delay = 0; volume = 0; super.reset(); } int reload_env_timer() { int raw = regs [2] & 7; env_delay = (raw != 0 ? raw : 8); return raw; } void clock_envelope() { if ( --env_delay <= 0 && reload_env_timer() != 0 ) { int v = volume + ((regs [2] & 0x08) != 0 ? +1 : -1); if ( 0 <= v && v <= 15 ) volume = v; } } boolean write_register( int frame_phase, int reg, int old_data, int data ) { final int max_len = 64; switch ( reg ) { case 1: length = max_len - (data & (max_len - 1)); break; case 2: if ( dac_enabled() == 0 ) enabled = 0; // TODO: once zombie mode used, envelope not clocked? if ( ((old_data ^ data) & 8) != 0 ) { int step = 0; if ( (old_data & 7) != 0 ) step = +1; else if ( (data & 7) != 0 ) step = -1; if ( (data & 8) != 0 ) step = -step; volume = (15 + step - volume) & 15; } else { int step = ((old_data & 7) != 0 ? 2 : 0) | ((data & 7) != 0 ? 0 : 1); volume = (volume + step) & 15; } break; case 4: if ( write_trig( frame_phase, max_len, old_data ) != 0 ) { volume = regs [2] >> 4; reload_env_timer(); if ( frame_phase == 7 ) env_delay++; if ( dac_enabled() == 0 ) enabled = 0; return true; } } return false; } } class GbSquare extends GbEnv { int phase; final int period() { return (2048 - frequency()) * 4; } void reset() { phase = 0; super.reset(); delay = 0x40000000; // TODO: less hacky (never clocked until first trigger) } boolean write_register( int frame_phase, int reg, int old_data, int data ) { boolean result = super.write_register( frame_phase, reg, old_data, data ); if ( result ) delay = period(); return result; } static final byte [] duty_offsets = { 1, 1, 3, 7 }; static final byte [] duties = { 1, 2, 4, 6 }; void run( int time, int end_time ) { final int duty_code = regs [1] >> 6; final int duty_offset = duty_offsets [duty_code]; final int duty = duties [duty_code]; int playing = 0; int amp = 0; int phase = (this.phase + duty_offset) & 7; if ( output != null ) { if ( volume != 0 ) { playing = -enabled; if ( phase < duty ) amp = volume & playing; // Treat > 16 kHz as DC if ( frequency() > 2041 && delay < 32 ) { amp = (volume * duty) >> 3 & playing; playing = 0; } } if ( dac_enabled() == 0 ) { playing = 0; amp = 0; } else { amp -= dac_bias; } int delta = amp - last_amp; if ( delta != 0 ) { last_amp = amp; output.addDelta( time, delta * vol_unit ); } } time += delay; if ( time < end_time ) { final int period = this.period(); if ( playing == 0 ) { // maintain phase int count = (end_time - time + period - 1) / period; phase = (phase + count) & 7; time += count * period; } else { final BlipBuffer output = this.output; // TODO: eliminate ugly +dac_bias -dac_bias adjustments int delta = ((amp + dac_bias) * 2 - volume) * vol_unit; do { if ( (phase = (phase + 1) & 7) == 0 || phase == duty ) output.addDelta( time, delta = -delta ); } while ( (time += period) < end_time ); last_amp = (delta < 0 ? 0 : volume) - dac_bias; } this.phase = (phase - duty_offset) & 7; } delay = time - end_time; } } final class GbSweepSquare extends GbSquare { static final int period_mask = 0x70; static final int shift_mask = 0x07; int sweep_freq; int sweep_delay; int sweep_enabled; int sweep_neg; void reset() { sweep_freq = 0; sweep_delay = 0; sweep_enabled = 0; sweep_neg = 0; super.reset(); } void reload_sweep_timer() { sweep_delay = (regs [0] & period_mask) >> 4; if ( sweep_delay == 0 ) sweep_delay = 8; } void calc_sweep( boolean update ) { int freq = sweep_freq; int shift = regs [0] & shift_mask; int delta = freq >> shift; sweep_neg = regs [0] & 0x08; if ( sweep_neg != 0 ) delta = -delta; freq += delta; if ( freq > 0x7FF ) { enabled = 0; } else if ( shift != 0 && update ) { sweep_freq = freq; regs [3] = freq & 0xFF; regs [4] = (regs [4] & ~0x07) | (freq >> 8 & 0x07); } } void clock_sweep() { if ( --sweep_delay <= 0 ) { reload_sweep_timer(); if ( sweep_enabled != 0 && (regs [0] & period_mask) != 0 ) { calc_sweep( true ); calc_sweep( false ); } } } boolean write_register( int frame_phase, int reg, int old_data, int data ) { if ( reg == 0 && (sweep_neg & 0x08 & ~data) != 0 ) enabled = 0; if ( super.write_register( frame_phase, reg, old_data, data ) ) { sweep_freq = frequency(); reload_sweep_timer(); sweep_enabled = regs [0] & (period_mask | shift_mask); if ( (regs [0] & shift_mask) != 0 ) calc_sweep( false ); } return false; } } final class GbNoise extends GbEnv { int bits; boolean write_register( int frame_phase, int reg, int old_data, int data ) { if ( reg == 3 ) { int p = period(); if ( p != 0 ) delay %= p; // TODO: not entirely correct } if ( super.write_register( frame_phase, reg, old_data, data ) ) bits = 0x7FFF; return false; } static final byte [] noise_periods = { 8, 16, 32, 48, 64, 80, 96, 112 }; int period() { int shift = regs [3] >> 4; int p = noise_periods [regs [3] & 7] << shift; if ( shift >= 0x0E ) p = 0; return p; } void run( int time, int end_time ) { int feedback = (1 << 14) >> (regs [3] & 8); int playing = 0; int amp = 0; if ( output != null ) { if ( volume != 0 ) { playing = -enabled; if ( (bits & 1) == 0 ) amp = volume & playing; } if ( dac_enabled() != 0 ) { amp -= dac_bias; } else { amp = 0; playing = 0; } int delta = amp - last_amp; if ( delta != 0 ) { last_amp = amp; output.addDelta( time, delta * vol_unit ); } } time += delay; if ( time < end_time ) { final int period = this.period(); if ( period == 0 ) { time = end_time; } else { int bits = this.bits; if ( playing == 0 ) { // maintain phase int count = (end_time - time + period - 1) / period; time += count * period; // TODO: be sure this doesn't drag performance too much bits ^= (feedback << 1) & -(bits & 1); feedback *= 3; do { bits = (bits >> 1) ^ (feedback & -(bits & 2)); } while ( --count > 0 ); bits &= ~(feedback << 1); } else { final BlipBuffer output = this.output; // TODO: eliminate ugly +dac_bias -dac_bias adjustments int delta = ((amp + dac_bias) * 2 - volume) * vol_unit; do { int changed = bits + 1; bits >>= 1; if ( (changed & 2) != 0 ) { bits |= feedback; output.addDelta( time, delta = -delta ); } } while ( (time += period) < end_time ); last_amp = (delta < 0 ? 0 : volume) - dac_bias; } this.bits = bits; } } delay = time - end_time; } } final class GbWave extends GbOsc { int wave_pos; int sample_buf_high; int sample_buf; static final int wave_size = 32; int [] wave = new int [wave_size]; int period() { return (2048 - frequency()) * 2; } int dac_enabled() { return regs [0] & 0x80; } int access( int addr ) { if ( enabled != 0 ) addr = 0xFF30 + (wave_pos >> 1); return addr; } void reset() { wave_pos = 0; sample_buf_high = 0; sample_buf = 0; length = 256; super.reset(); } boolean write_register( int frame_phase, int reg, int old_data, int data ) { final int max_len = 256; switch ( reg ) { case 1: length = max_len - data; break; case 4: if ( write_trig( frame_phase, max_len, old_data ) != 0 ) { wave_pos = 0; delay = period() + 6; sample_buf = sample_buf_high; } // fall through case 0: if ( dac_enabled() == 0 ) enabled = 0; } return false; } void run( int time, int end_time ) { int volume_shift = regs [2] >> 5 & 3; int playing = 0; if ( output != null ) { playing = -enabled; if ( --volume_shift < 0 ) { volume_shift = 7; playing = 0; } int amp = sample_buf & playing; if ( frequency() > 0x7FB && delay < 16 ) { // 16 kHz and above, act as DC at mid-level // (really depends on average level of entire wave, // but this is good enough) amp = 8; playing = 0; } amp >>= volume_shift; if ( dac_enabled() == 0 ) { playing = 0; amp = 0; } else { amp -= dac_bias; } int delta = amp - last_amp; if ( delta != 0 ) { last_amp = amp; output.addDelta( time, delta * vol_unit ); } } time += delay; if ( time < end_time ) { int wave_pos = (this.wave_pos + 1) & (wave_size - 1); final int period = this.period(); if ( playing == 0 ) { // maintain phase int count = (end_time - time + period - 1) / period; wave_pos += count; // will be masked below time += count * period; } else { final BlipBuffer output = this.output; int last_amp = this.last_amp + dac_bias; do { int amp = wave [wave_pos] >> volume_shift; wave_pos = (wave_pos + 1) & (wave_size - 1); int delta; if ( (delta = amp - last_amp) != 0 ) { last_amp = amp; output.addDelta( time, delta * vol_unit ); } } while ( (time += period) < end_time ); this.last_amp = last_amp - dac_bias; } wave_pos = (wave_pos - 1) & (wave_size - 1); this.wave_pos = wave_pos; if ( enabled != 0 ) { sample_buf_high = wave [wave_pos & ~1]; sample_buf = wave [wave_pos]; } } delay = time - end_time; } } final public class GbApu { public GbApu() { oscs [0] = square1; oscs [1] = square2; oscs [2] = wave; oscs [3] = noise; reset(); } // Resets oscillators and internal state public void setOutput( BlipBuffer center, BlipBuffer left, BlipBuffer right ) { outputs [1] = right; outputs [2] = left; outputs [3] = center; for ( int i = osc_count; --i >= 0; ) oscs [i].output = outputs [oscs [i].output_select]; } private void update_volume() { final int unit = (int) (1.0 / osc_count / 15 / 8 * 65536); // TODO: doesn't handle left != right volume (not worth the complexity) int data = regs [vol_reg - startAddr]; int left = data >> 4 & 7; int right = data & 7; int vol_unit = (left > right ? left : right) * unit; for ( int i = osc_count; --i >= 0; ) oscs [i].vol_unit = vol_unit; } private void reset_regs() { for ( int i = 0x20; --i >= 0; ) regs [i] = 0; for ( int i = osc_count; --i >= 0; ) oscs [i].reset(); update_volume(); } static final int initial_wave [] = { 0x84,0x40,0x43,0xAA,0x2D,0x78,0x92,0x3C, 0x60,0x59,0x59,0xB0,0x34,0xB8,0x2E,0xDA }; public void reset() { frame_time = 0; last_time = 0; frame_phase = 0; reset_regs(); for ( int i = 16; --i >= 0; ) write( 0, i + wave_ram, initial_wave [i] ); } private void run_until( int end_time ) { assert end_time >= last_time; // end_time must not be before previous time if ( end_time == last_time ) return; while ( true ) { // run oscillators int time = end_time; if ( time > frame_time ) time = frame_time; square1.run( last_time, time ); square2.run( last_time, time ); wave .run( last_time, time ); noise .run( last_time, time ); last_time = time; if ( time == end_time ) break; // run frame sequencer frame_time += frame_period; switch ( frame_phase++ ) { case 2: case 6: // 128 Hz square1.clock_sweep(); case 0: case 4: // 256 Hz square1.clock_length(); square2.clock_length(); wave .clock_length(); noise .clock_length(); break; case 7: // 64 Hz frame_phase = 0; square1.clock_envelope(); square2.clock_envelope(); noise .clock_envelope(); } } } // Runs all oscillators up to specified time, ends current time frame, then // starts a new frame at time 0 public void endFrame( int end_time ) { if ( end_time > last_time ) run_until( end_time ); assert frame_time >= end_time; frame_time -= end_time; assert last_time >= end_time; last_time -= end_time; } static void silence_osc( int time, GbOsc osc ) { int amp = osc.last_amp; if ( amp != 0 ) { osc.last_amp = 0; if ( osc.output != null ) osc.output.addDelta( time, -amp * osc.vol_unit ); } } // Reads and writes at addr must satisfy start_addr <= addr <= end_addr public static final int startAddr = 0xFF10; public static final int endAddr = 0xFF3F; public void write( int time, int addr, int data ) { assert startAddr <= addr && addr <= endAddr; assert 0 <= data && data < 0x100; if ( addr < status_reg && (regs [status_reg - startAddr] & power_mask) == 0 ) return; run_until( time ); int reg = addr - startAddr; if ( addr < wave_ram ) { int old_data = regs [reg]; regs [reg] = data; if ( addr < vol_reg ) { int index = reg / 5; GbOsc osc = oscs [index]; int r = reg - index * 5; osc.regs [r] = data; osc.write_register( frame_phase, r, old_data, data ); } else if ( addr == vol_reg && data != old_data ) { for ( int i = osc_count; --i >= 0; ) silence_osc( time, oscs [i] ); update_volume(); } else if ( addr == stereo_reg ) { for ( int i = osc_count; --i >= 0; ) { GbOsc osc = oscs [i]; int bits = data >> i; osc.output_select = (bits >> 3 & 2) | (bits & 1); BlipBuffer output = outputs [osc.output_select]; if ( osc.output != output ) { silence_osc( time, osc ); osc.output = output; } } } else if ( addr == status_reg && ((data ^ old_data) & power_mask) != 0 ) { frame_phase = 0; if ( (data & power_mask) == 0 ) { for ( int i = osc_count; --i >= 0; ) silence_osc( time, oscs [i] ); reset_regs(); } } } else // wave data { addr = wave.access( addr ); regs [addr - startAddr] = data; int index = (addr & 0x0F) * 2; wave.wave [index ] = data >> 4; wave.wave [index + 1] = data & 0x0F; } } static final int masks [] = { 0x80,0x3F,0x00,0xFF,0xBF, 0xFF,0x3F,0x00,0xFF,0xBF, 0x7F,0xFF,0x9F,0xFF,0xBF, 0xFF,0xFF,0x00,0x00,0xBF, 0x00,0x00,0x70, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF }; // Reads from address at specified time public int read( int time, int addr ) { assert startAddr <= addr && addr <= endAddr; run_until( time ); if ( addr >= wave_ram ) addr = wave.access( addr ); int index = addr - startAddr; int data = regs [index]; if ( index < masks.length ) data |= masks [index]; if ( addr == status_reg ) { data &= 0xF0; if ( square1.enabled != 0 ) data |= 1; if ( square2.enabled != 0 ) data |= 2; if ( wave .enabled != 0 ) data |= 4; if ( noise .enabled != 0 ) data |= 8; } return data; } static final int vol_reg = 0xFF24; static final int stereo_reg = 0xFF25; static final int status_reg = 0xFF26; static final int wave_ram = 0xFF30; static final int frame_period = 4194304 / 512; // 512 Hz static final int power_mask = 0x80; static final int osc_count = 4; final GbOsc [] oscs = new GbOsc [osc_count]; int frame_time; int last_time; int frame_phase; final BlipBuffer [] outputs = new BlipBuffer [4]; final GbSweepSquare square1 = new GbSweepSquare(); final GbSquare square2 = new GbSquare(); final GbWave wave = new GbWave(); final GbNoise noise = new GbNoise(); final int [] regs = new int [endAddr - startAddr + 1]; }
rafael-esper/JLud2D
src/audio/gme/GbApu.java
248,437
package inh; import java.util.Scanner; public class AmazonApp { public static void main(String[] args) { // ProductNonIndia pn = new ProductNonIndia(); // pn.getData(); // pn.calculateDuty(); // pn.display(); // ProductIndia p[] = new ProductIndia[3];// 5 ProductNonIndia pn[] = new ProductNonIndia[3]; int indianCount = 0; int nonIndianCount = 0; Scanner scr = new Scanner(System.in); while (true) { System.out.println("\n0 for exit\n1 For Insert \n 2For Display"); int choice = scr.nextInt(); switch (choice) { case 1: System.out.println("\n0 India\n1 NonIndia \nEnter choice"); int subChoice = scr.nextInt(); if (subChoice == 0) { // india p[indianCount] = new ProductIndia();// constructor p[indianCount].getData();// p[indianCount].calculateDiscount(); indianCount++;// 1 } else if (subChoice == 1) { // non india pn[nonIndianCount] = new ProductNonIndia(); pn[nonIndianCount].getData(); pn[nonIndianCount].calculateDuty(); nonIndianCount++;// 1 } else { System.out.println("PTA...."); } break; case 2 - 2: System.exit(0); case 2: System.out.println("\nIndia Products\n"); for (int i = 0; i < indianCount; i++) { p[i].display(); } System.out.println("\n NON India Products\n"); for (int i = 0; i < nonIndianCount; i++) { pn[i].display(); } } } // for (int i = 0; i < p.length; i++) { // p[i] = new ProductIndia();//constructor // p[i].getData();// // p[i].calculateDiscount(); // } // for (int i = 0; i < p.length; i++) { // p[i].display(); // } } } class Product { String name; int price; int qty; void getData() { Scanner scr = new Scanner(System.in); System.out.println("Enter name price and qty"); name = scr.next(); price = scr.nextInt(); qty = scr.nextInt(); } void display() { System.out.print(name + " " + price + " " + qty + " "); } // getName // getPrice // getQty } //S{Single Responsiblity Class} O L I D class ProductIndia extends Product { int discount; float disocuntPerc; public ProductIndia() { this.disocuntPerc = 5; } void calculateDiscount() { this.discount = (int) (this.price * this.disocuntPerc) / 100; } void display() { super.display(); System.out.println(discount); } } //KISS -> Keep It Simple , Stupid class ProductNonIndia extends Product { int duty; float dutyPerc; public ProductNonIndia() { this.dutyPerc = 5; } ProductNonIndia(float newDutyPerc) { this.dutyPerc = newDutyPerc; } void calculateDuty() { this.duty = (int) (this.price * this.dutyPerc) / 100; } void display() { super.display(); System.out.println(duty); } }
tejasshah2k19/22-java-club-sept
src/inh/AmazonApp.java
248,438
package GUI; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; public class Adminpage extends JFrame implements ActionListener { private JButton btnnewuser,btndeluser,btnoutduty,btnleaverequest,btnreports,btnedituser; private Box boxrow1,boxrow2,boxbutton; public Adminpage() { btnleaverequest=new JButton("Leave Request"); btnnewuser = new JButton("New User"); btnnewuser.setMaximumSize(btnleaverequest.getMaximumSize()); btnedituser = new JButton("Edit User"); btnedituser.setMaximumSize(btnleaverequest.getMaximumSize()); btndeluser=new JButton("Delete User"); btndeluser.setMaximumSize(btnleaverequest.getMaximumSize()); btnoutduty=new JButton("Out Duty"); btnoutduty.setMaximumSize(btnleaverequest.getMaximumSize()); //btnleaverequest.setMaximumSize(); btnreports=new JButton("Reports"); btnreports.setMaximumSize(btnleaverequest.getMaximumSize()); boxrow1=Box.createHorizontalBox(); boxrow2=Box.createHorizontalBox(); boxbutton=Box.createVerticalBox(); btnnewuser.addActionListener(this); btnedituser.addActionListener(this); btndeluser.addActionListener(this); btnoutduty.addActionListener(this); btnleaverequest.addActionListener(this); btnreports.addActionListener(this); boxrow1.add(btnnewuser); boxrow1.add(Box.createRigidArea(new Dimension(25, 35))); boxrow1.add(btnedituser); boxrow1.add(Box.createRigidArea(new Dimension(25, 35))); boxrow1.add(btndeluser); boxrow2.add(btnoutduty); boxrow2.add(Box.createRigidArea(new Dimension(25, 35))); boxrow2.add(btnleaverequest); boxrow2.add(Box.createRigidArea(new Dimension(25, 35))); boxrow2.add(btnreports); boxbutton.add(Box.createRigidArea(new Dimension(25, 35))); boxbutton.add(boxrow1); boxbutton.add(Box.createRigidArea(new Dimension(25, 15))); boxbutton.add(boxrow2); add(boxbutton,BorderLayout.CENTER); setSize(500,200); setVisible(true); setTitle("ADMIN PAGE"); setLocationRelativeTo(null); } public void actionPerformed(ActionEvent event) { if (event.getSource()==btnnewuser) new Newuser(); if (event.getSource()==btnedituser) new Edituserloginpage(); if (event.getSource()==btnleaverequest) new Leavestatus(); if (event.getSource()==btnoutduty) new OutDutyGui(); if (event.getSource()==btndeluser) new Deleteuser(); if (event.getSource()==btnreports) new ReportGUI(); } public static void main(String[] args) { new Adminpage(); } }
bhakta009/attendence_monitoring_system
src/GUI/Adminpage.java
248,439
package salestaxcalc; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.DecimalFormat; public class Bill { private String[] nonBST = { "book", "food", "medical" }; private String[] addedNonBST = { "chocolate", "chocolates", "pills" }; private static double billTotal; private static double salesTaxTotal; private static final String PRICE_AT = " at "; private static final double BASIC_SALES_TAX = 0.10; // defined for basic // sales tax private static final double IMPORT_DUTY = 0.05; // defined for import duty private static final String EXIT = "exit"; private static final String IMPORTED = "imported"; private static final String PRINT_SALES_TAXES = "Sales Taxes: "; private static final String PRINT_SALES_TOTAL = "Total: "; public double getBillTotal() { return billTotal; } public void setBillTotal(double billTotal) { Bill.billTotal = billTotal; } public double getSalesTaxTotal() { return salesTaxTotal; } public void setSalesTaxTotal(double salesTaxTotal) { Bill.salesTaxTotal = salesTaxTotal; } public boolean isImported(String item) { String[] array = item.split("\\s"); for (int i = 0; i < array.length; i++) { if (array[i].equals(IMPORTED)) return true; } return false; } public boolean isBSTApplicable(String item) { String[] itemList = item.split("\\s"); for (int i = 0; i < itemList.length; i++) { for (int j = 0; j < nonBST.length; j++) { if (itemList[i].equals(nonBST[j])) return false; } for (int k = 0; k < addedNonBST.length; k++) { if (itemList[i].equals(addedNonBST[k])) return false; } } return true; } public boolean isEnd(String item) { return (item.equals(EXIT) ? true : false); } public double getPrice(String item) { String[] itemList = item.split("\\s"); return Double.parseDouble(itemList[itemList.length - 1]); } public double getItemTotal(double importedValue, double salesTax, double price) { return price + importedValue + salesTax; } public String getItemStatement(double itemTotal, String item) { String[] itemList = item.split(PRICE_AT); itemList[itemList.length - 1] = decimalFormat(itemTotal).toString(); String itemStatement = itemList[0].trim() + ": " + itemList[1]; return itemStatement.trim(); } public static String decimalFormat(double number) { DecimalFormat df = new DecimalFormat("0.00"); return df.format(number); } public void startBill() { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Bill bill = new Bill(); while (true) { String item = null; try { item = br.readLine().trim(); } catch (IOException e) { System.out.println("Incorrect input."); e.printStackTrace(); } System.out.println(bill.billProcessing(item)); bill.setBillTotal(0); bill.setSalesTaxTotal(0); } } public String billProcessing(String item) { Bill itemList = new Bill(); if (itemList.isEnd(item)) { String salesTaxes = decimalFormat(itemList.getSalesTaxTotal()); String salesTotal = decimalFormat(itemList.getBillTotal()); itemList.setSalesTaxTotal(0); itemList.setBillTotal(0); return (PRINT_SALES_TAXES + salesTaxes) + "\n" + (PRINT_SALES_TOTAL + salesTotal); } double price = itemList.getPrice(item); double importedValue = itemList.isImported(item) ? price * IMPORT_DUTY : 0; double salesTax = itemList.isBSTApplicable(item) ? price * BASIC_SALES_TAX : 0; double itemTotal = itemList .getItemTotal(importedValue, salesTax, price); itemList.setSalesTaxTotal(itemList.getSalesTaxTotal() + salesTax); itemList.setBillTotal(itemList.getBillTotal() + itemTotal); return (itemList.getItemStatement(itemTotal, item)); } }
nimitbhargava/SalesTaxCalulator
src/salestaxcalc/Bill.java
248,440
package gtfs; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Trip { private Integer routeId; private Integer serviceId; private String tripId; private String tripHeadsign; private String tripShortName; private Integer directionId; private String blockId; private Integer shapeId; private String wheelchairAccessible; private String bikesAllowed; private String duty; private Integer dutySequenceNumber; private Integer runSequenceNumber; public Trip(Integer routeId, Integer serviceId, String tripId, String tripHeadsign, String tripShortName, Integer directionId, String blockId, Integer shapeId, String wheelchairAccessible, String bikesAllowed, String duty, Integer dutySequenceNumber, Integer runSequenceNumber) { this.routeId = routeId; this.serviceId = serviceId; this.tripId = tripId; this.tripHeadsign = tripHeadsign; this.tripShortName = tripShortName; this.directionId = directionId; this.blockId = blockId; this.shapeId = shapeId; this.wheelchairAccessible = wheelchairAccessible; this.bikesAllowed = bikesAllowed; this.duty = duty; this.dutySequenceNumber = dutySequenceNumber; this.runSequenceNumber = runSequenceNumber; } public Integer getRouteId() { return routeId; } public Integer getServiceId() { return serviceId; } public String getTripId() { return tripId; } public String getTripHeadsign() { return tripHeadsign; } public String getTripShortName() { return tripShortName; } public Integer getDirectionId() { return directionId; } public String getBlockId() { return blockId; } public Integer getShapeId() { return shapeId; } public String getWheelchairAccessible() { return wheelchairAccessible; } public String getBikesAllowed() { return bikesAllowed; } public String getDuty() { return duty; } public Integer getDutySequenceNumber() { return dutySequenceNumber; } public Integer getRunSequenceNumber() { return runSequenceNumber; } public static Trip getTripFromId(String id, String filePath) { try { FileReader file = new FileReader(filePath); BufferedReader br = new BufferedReader(file); br.readLine(); // Skip header line String line; while ((line = br.readLine()) != null) { String[] fields = line.split(",", -1); if (id.equals(fields[2])) { return new Trip( Integer.parseInt(fields[0]), Integer.parseInt(fields[1]), fields[2], fields[3], fields[4], Integer.parseInt(fields[5]), fields[6], Integer.parseInt(fields[7]), fields[8], fields[9], fields[10], Integer.parseInt(fields[11]), Integer.parseInt(fields[12]) ); } } System.out.print("Trip with given ID not found"); } catch (IOException e) { System.out.print(e.getMessage()); } return null; } @Override public String toString() { return "routeId=" + routeId + '\n' + ", serviceId=" + serviceId + '\n' + ", tripId=" + tripId + '\n' + ", tripHeadsign=" + tripHeadsign + '\n' + ", tripShortName=" + tripShortName + '\n' + ", directionId=" + directionId + '\n' + ", blockId=" + blockId + '\n' + ", shapeId=" + shapeId + '\n' + ", wheelchairAccessible=" + wheelchairAccessible + '\n' + ", bikesAllowed=" + bikesAllowed + '\n' + ", duty=" + duty + '\n' + ", dutySequenceNumber=" + dutySequenceNumber + '\n' + ", runSequenceNumber=" + runSequenceNumber + '\n'; } }
IgorPolajzer/bus_scheduler
src/gtfs/Trip.java
248,442
public interface ImportDuty { double carTaxRate = 0.10; double hgvTaxRate = 0.15; double calculateDuty(); }
KyleKinsella/JavaLabs
Lab9/Q2/ImportDuty.java
248,443
/* vNES Copyright © 2006-2013 Open Emulation Project 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/>. */ public class ChannelSquare implements PapuChannel { PAPU papu; static int[] dutyLookup; static int[] impLookup; boolean sqr1; boolean isEnabled; boolean lengthCounterEnable; boolean sweepActive; boolean envDecayDisable; boolean envDecayLoopEnable; boolean envReset; boolean sweepCarry; boolean updateSweepPeriod; int progTimerCount; int progTimerMax; int lengthCounter; int squareCounter; int sweepCounter; int sweepCounterMax; int sweepMode; int sweepShiftAmount; int envDecayRate; int envDecayCounter; int envVolume; int masterVolume; int dutyMode; int sweepResult; int sampleValue; int vol; public ChannelSquare(PAPU papu, boolean square1) { this.papu = papu; sqr1 = square1; } public void clockLengthCounter() { if (lengthCounterEnable && lengthCounter > 0) { lengthCounter--; if (lengthCounter == 0) { updateSampleValue(); } } } public void clockEnvDecay() { if (envReset) { // Reset envelope: envReset = false; envDecayCounter = envDecayRate + 1; envVolume = 0xF; } else if ((--envDecayCounter) <= 0) { // Normal handling: envDecayCounter = envDecayRate + 1; if (envVolume > 0) { envVolume--; } else { envVolume = envDecayLoopEnable ? 0xF : 0; } } masterVolume = envDecayDisable ? envDecayRate : envVolume; updateSampleValue(); } public void clockSweep() { if (--sweepCounter <= 0) { sweepCounter = sweepCounterMax + 1; if (sweepActive && sweepShiftAmount > 0 && progTimerMax > 7) { // Calculate result from shifter: sweepCarry = false; if (sweepMode == 0) { progTimerMax += (progTimerMax >> sweepShiftAmount); if (progTimerMax > 4095) { progTimerMax = 4095; sweepCarry = true; } } else { progTimerMax = progTimerMax - ((progTimerMax >> sweepShiftAmount) - (sqr1 ? 1 : 0)); } } } if (updateSweepPeriod) { updateSweepPeriod = false; sweepCounter = sweepCounterMax + 1; } } public void updateSampleValue() { if (isEnabled && lengthCounter > 0 && progTimerMax > 7) { if (sweepMode == 0 && (progTimerMax + (progTimerMax >> sweepShiftAmount)) > 4095) { //if(sweepCarry){ sampleValue = 0; } else { sampleValue = masterVolume * dutyLookup[(dutyMode << 3) + squareCounter]; } } else { sampleValue = 0; } } public void writeReg(int address, int value) { int addrAdd = (sqr1 ? 0 : 4); if (address == 0x4000 + addrAdd) { // Volume/Envelope decay: envDecayDisable = ((value & 0x10) != 0); envDecayRate = value & 0xF; envDecayLoopEnable = ((value & 0x20) != 0); dutyMode = (value >> 6) & 0x3; lengthCounterEnable = ((value & 0x20) == 0); masterVolume = envDecayDisable ? envDecayRate : envVolume; updateSampleValue(); } else if (address == 0x4001 + addrAdd) { // Sweep: sweepActive = ((value & 0x80) != 0); sweepCounterMax = ((value >> 4) & 7); sweepMode = (value >> 3) & 1; sweepShiftAmount = value & 7; updateSweepPeriod = true; } else if (address == 0x4002 + addrAdd) { // Programmable timer: progTimerMax &= 0x700; progTimerMax |= value; } else if (address == 0x4003 + addrAdd) { // Programmable timer, length counter progTimerMax &= 0xFF; progTimerMax |= ((value & 0x7) << 8); if (isEnabled) { lengthCounter = papu.getLengthMax(value & 0xF8); } envReset = true; } } public void setEnabled(boolean value) { isEnabled = value; if (!value) { lengthCounter = 0; } updateSampleValue(); } public boolean isEnabled() { return isEnabled; } public int getLengthStatus() { return ((lengthCounter == 0 || !isEnabled) ? 0 : 1); } public void reset() { progTimerCount = 0; progTimerMax = 0; lengthCounter = 0; squareCounter = 0; sweepCounter = 0; sweepCounterMax = 0; sweepMode = 0; sweepShiftAmount = 0; envDecayRate = 0; envDecayCounter = 0; envVolume = 0; masterVolume = 0; dutyMode = 0; vol = 0; isEnabled = false; lengthCounterEnable = false; sweepActive = false; sweepCarry = false; envDecayDisable = false; envDecayLoopEnable = false; } public void destroy() { papu = null; } static { dutyLookup = new int[]{ 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1,}; impLookup = new int[]{ 1, -1, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0,}; } }
bfirsh/vNES
src/ChannelSquare.java
248,444
/* JavaBoy COPYRIGHT (C) 2001 Neil Millstone and The Victoria University of Manchester ;;; This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ import java.awt.*; import java.awt.image.*; import java.lang.*; import java.io.*; import java.applet.*; import java.net.*; import java.awt.event.KeyListener; import java.awt.event.WindowListener; import java.awt.event.ActionListener; import java.awt.event.ComponentListener; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.awt.event.ActionEvent; import java.awt.event.ComponentEvent; import java.awt.event.ItemEvent; import java.util.StringTokenizer; import javax.sound.sampled.*; /** This class can mix a square wave signal with a sound buffer. * It supports all features of the Gameboys sound channels 1 and 2. */ class SquareWaveGenerator { /** Sound is to be played on the left channel of a stereo sound */ public static final int CHAN_LEFT = 1; /** Sound is to be played on the right channel of a stereo sound */ public static final int CHAN_RIGHT = 2; /** Sound is to be played back in mono */ public static final int CHAN_MONO = 4; /** Length of the sound (in frames) */ int totalLength; /** Current position in the waveform (in samples) */ int cyclePos; /** Length of the waveform (in samples) */ int cycleLength; /** Amplitude of the waveform */ int amplitude; /** Amount of time the sample stays high in a single waveform (in eighths) */ int dutyCycle; /** The channel that the sound is to be played back on */ int channel; /** Sample rate of the sound buffer */ int sampleRate; /** Initial amplitude */ int initialEnvelope; /** Number of envelope steps */ int numStepsEnvelope; /** If true, envelope will increase amplitude of sound, false indicates decrease */ boolean increaseEnvelope; /** Current position in the envelope */ int counterEnvelope; /** Frequency of the sound in internal GB format */ int gbFrequency; /** Amount of time between sweep steps. */ int timeSweep; /** Number of sweep steps */ int numSweep; /** If true, sweep will decrease the sound frequency, otherwise, it will increase */ boolean decreaseSweep; /** Current position in the sweep */ int counterSweep; /** Create a square wave generator with the supplied parameters */ public SquareWaveGenerator(int waveLength, int ampl, int duty, int chan, int rate) { cycleLength = waveLength; amplitude = ampl; cyclePos = 0; dutyCycle = duty; channel = chan; sampleRate = rate; } /** Create a square wave generator at the specified sample rate */ public SquareWaveGenerator(int rate) { dutyCycle = 4; cyclePos = 0; channel = CHAN_LEFT | CHAN_RIGHT; cycleLength = 2; totalLength = 0; sampleRate = rate; amplitude = 32; counterSweep = 0; } /** Set the sound buffer sample rate */ public void setSampleRate(int sr) { sampleRate = sr; } /** Set the duty cycle */ public void setDutyCycle(int duty) { switch (duty) { case 0 : dutyCycle = 1; break; case 1 : dutyCycle = 2; break; case 2 : dutyCycle = 4; break; case 3 : dutyCycle = 6; break; } // System.out.println(dutyCycle); } /** Set the sound frequency, in internal GB format */ public void setFrequency(int gbFrequency) { try { float frequency = 131072 / 2048; if (gbFrequency != 2048) { frequency = ((float) 131072 / (float) (2048 - gbFrequency)); } // System.out.println("gbFrequency: " + gbFrequency + ""); this.gbFrequency = gbFrequency; if (frequency != 0) { cycleLength = (256 * sampleRate) / (int) frequency; } else { cycleLength = 65535; } if (cycleLength == 0) cycleLength = 1; // System.out.println("Cycle length : " + cycleLength + " samples"); } catch (ArithmeticException e) { // Skip ip } } /** Set the channel for playback */ public void setChannel(int chan) { channel = chan; } /** Set the envelope parameters */ public void setEnvelope(int initialValue, int numSteps, boolean increase) { initialEnvelope = initialValue; numStepsEnvelope = numSteps; increaseEnvelope = increase; amplitude = initialValue * 2; } /** Set the frequency sweep parameters */ public void setSweep(int time, int num, boolean decrease) { timeSweep = (time + 1) / 2; numSweep = num; decreaseSweep = decrease; counterSweep = 0; // System.out.println("Sweep: " + time + ", " + num + ", " + decrease); } public void setLength(int gbLength) { if (gbLength == -1) { totalLength = -1; } else { totalLength = (64 - gbLength) / 4; } } public void setLength3(int gbLength) { if (gbLength == -1) { totalLength = -1; } else { totalLength = (256 - gbLength) / 4; } } public void setVolume3(int volume) { switch (volume) { case 0 : amplitude = 0; break; case 1 : amplitude = 32; break; case 2 : amplitude = 16; break; case 3 : amplitude = 8; break; } // System.out.println("A:"+volume); } /** Output a frame of sound data into the buffer using the supplied frame length and array offset. */ public void play(byte[] b, int length, int offset) { int val = 0; if (totalLength != 0) { totalLength--; if (timeSweep != 0) { counterSweep++; if (counterSweep > timeSweep) { if (decreaseSweep) { setFrequency(gbFrequency - (gbFrequency >> numSweep)); } else { setFrequency(gbFrequency + (gbFrequency >> numSweep)); } counterSweep = 0; } } counterEnvelope++; if (numStepsEnvelope != 0) { if (((counterEnvelope % numStepsEnvelope) == 0) && (amplitude > 0)) { if (!increaseEnvelope) { if (amplitude > 0) amplitude-=2; } else { if (amplitude < 16) amplitude+=2; } } } for (int r = offset; r < offset + length; r++) { if (cycleLength != 0) { if (((8 * cyclePos) / cycleLength) >= dutyCycle) { val = amplitude; } else { val = -amplitude; } } /* if (cyclePos >= (cycleLength / 2)) { val = amplitude; } else { val = -amplitude; }*/ if ((channel & CHAN_LEFT) != 0) b[r * 2] += val; if ((channel & CHAN_RIGHT) != 0) b[r * 2 + 1] += val; if ((channel & CHAN_MONO) != 0) b[r] += val; // System.out.print(val + " "); cyclePos = (cyclePos + 256) % cycleLength; } } } }
thomas41546/JavaBoy-2-Unofficial
SquareWaveGenerator.java
248,445
package DTO; import java.util.Date; public class Employee { private long id; private String name; private String surname; private String address; private Date birth_date; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Date getBirth_date() { return birth_date; } public void setBirth_date(Date birth_date) { this.birth_date = birth_date; } public String getBirth_place() { return birth_place; } public void setBirth_place(String birth_place) { this.birth_place = birth_place; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public int getDuty() { return duty; } public void setDuty(int duty) { this.duty = duty; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public int getBranchID() { return branchID; } public void setBranchID(int branchID) { this.branchID = branchID; } private String birth_place; private String email; private String telephone; private int duty; private long account_number; private double salary; private int branchID; public long getAccount_number() { return account_number; } public void setAccount_number(long account_number) { this.account_number = account_number; } public Employee() {} public Employee( String name, String surname, String address, Date birth_date, String birth_place, String email, String telephone, int duty, long account_number, double salary, int branchID) { this.name = name; this.surname = surname; this.address = address; this.birth_date = birth_date; this.birth_place = birth_place; this.email = email; this.telephone = telephone; this.duty = duty; this.account_number = account_number; this.salary = salary; this.branchID = branchID; } public Employee(long id, String name, String surname, String address, Date birth_date, String birth_place, String email, String telephone, int duty, long account_number, double salary, int branchID) { this.id = id; this.name = name; this.surname = surname; this.address = address; this.birth_date = birth_date; this.birth_place = birth_place; this.email = email; this.telephone = telephone; this.duty = duty; this.account_number = account_number; this.salary = salary; this.branchID = branchID; } }
TanjaDobrovoljski/AirlineCompanyDB
src/DTO/Employee.java
248,447
package domain; import java.io.Serializable; import java.util.Date; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; @Entity @Table(name="attend_inf") @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) public class Attend implements Serializable { private static final long serialVersionUID = 48L; @Id @Column(name="attend_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; @Column(name="duty_day", nullable=false, length=50) private String dutyDay; @Column(name="punch_time") private Date punchTime; @Column(name="is_come" , nullable=false) private boolean isCome; @ManyToOne(targetEntity=AttendType.class) @JoinColumn(name="type_id", nullable=false) private AttendType type; @ManyToOne(targetEntity=Employee.class) @JoinColumn(name="emp_id", nullable=false) private Employee employee; public Attend() { } public Attend(Integer id , String dutyDay , Date punchTime , boolean isCome , AttendType type , Employee employee) { this.id = id; this.dutyDay = dutyDay; this.punchTime = punchTime; this.isCome = isCome; this.type = type; this.employee = employee; } public void setId(Integer id) { this.id = id; } public Integer getId() { return this.id; } public void setDutyDay(String dutyDay) { this.dutyDay = dutyDay; } public String getDutyDay() { return this.dutyDay; } public void setPunchTime(Date punchTime) { this.punchTime = punchTime; } public Date getPunchTime() { return this.punchTime; } public void setIsCome(boolean isCome) { this.isCome = isCome; } public boolean getIsCome() { return this.isCome; } public void setType(AttendType type) { this.type = type; } public AttendType getType() { return this.type; } public void setEmployee(Employee employee) { this.employee = employee; } public Employee getEmployee() { return this.employee; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dutyDay == null) ? 0 : dutyDay.hashCode()); result = prime * result + ((employee == null) ? 0 : employee.hashCode()); result = prime * result + (isCome ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Attend other = (Attend) obj; if (dutyDay == null) { if (other.dutyDay != null) return false; } else if (!dutyDay.equals(other.dutyDay)) return false; if (employee == null) { if (other.employee != null) return false; } else if (!employee.equals(other.employee)) return false; if (isCome != other.isCome) return false; return true; } }
bybywudi/sshWork
src/domain/Attend.java
248,448
package model; import java.io.Serializable; import java.util.*; import javax.persistence.*; /** * * @author GANZA */ @Entity public class Employees implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "eid") private Integer eid; private String efName; private String elName; private String duty; private Integer salary; private String password; @ManyToOne @JoinColumn(name = "Employer_ID") private Admin admin; @OneToMany(mappedBy = "employees") List<Opinions> opinions=new ArrayList<>(); @ManyToMany @JoinTable( name="Product_sold", joinColumns = @JoinColumn(name = "eid"), inverseJoinColumns = @JoinColumn(name = "Product_id") ) private Set<Products> products; public Employees() { } public Employees(Integer eid) { this.eid = eid; } public Employees(Integer eid, String efName, String elName, String duty, Integer salary, String password, Admin admin, Set<Products> products) { this.eid = eid; this.efName = efName; this.elName = elName; this.duty = duty; this.salary = salary; this.password = password; this.admin = admin; this.products = products; } public Integer getEid() { return eid; } public void setEid(Integer eid) { this.eid = eid; } 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 Integer getSalary() { return salary; } public void setSalary(Integer salary) { this.salary = salary; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Admin getAdmin() { return admin; } public void setAdmin(Admin admin) { this.admin = admin; } public List<Opinions> getOpinions() { return opinions; } public void setOpinions(List<Opinions> opinions) { this.opinions = opinions; } public Set<Products> getProducts() { return products; } public void setProducts(Set<Products> products) { this.products = products; } }
Kami-christella/Stock-Management-RMI
src/model/Employees.java