file_id
stringlengths
4
9
content
stringlengths
146
15.9k
repo
stringlengths
9
113
path
stringlengths
6
76
token_length
int64
34
3.46k
original_comment
stringlengths
14
2.81k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
excluded
bool
1 class
file-tokens-Qwen/Qwen2-7B
int64
30
3.35k
comment-tokens-Qwen/Qwen2-7B
int64
3
624
file-tokens-bigcode/starcoder2-7b
int64
34
3.46k
comment-tokens-bigcode/starcoder2-7b
int64
3
696
file-tokens-google/codegemma-7b
int64
36
3.76k
comment-tokens-google/codegemma-7b
int64
3
684
file-tokens-ibm-granite/granite-8b-code-base
int64
34
3.46k
comment-tokens-ibm-granite/granite-8b-code-base
int64
3
696
file-tokens-meta-llama/CodeLlama-7b-hf
int64
36
4.12k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
3
749
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
225434_0
import org.lwjgl.util.glu.GLU; public class Camera { final static float FRACTION = 0.001f; private float camAngle; private float x; private float y; private float z; private float lx; private float lz; /** * Creates new Camera instance */ public Camera(){ camAngle = 0.0f; x = 5.0f; y = 0.0f; z = 0.0f; lx = 0.0f; lz = 0.0f; } /** * Shift the camera right by FRACTION */ public void shiftRight(){ camAngle += FRACTION; lx = (float)Math.sin(camAngle); lz = -(float)Math.cos(camAngle); } /** * Shift the camera left by FRACTION */ public void shiftLeft(){ camAngle -= FRACTION; lx = (float)Math.sin(camAngle); lz = -(float)Math.cos(camAngle); } /** * Move forward by FRACTION */ public void moveForward(){ x += lx * FRACTION; z += lz * FRACTION; } /** * Move back by FRACTION */ public void moveBack(){ x -= lx * FRACTION; z -= lz * FRACTION; } /** * Points the camera at the current point viewed */ public void moveCamera(){ GLU.gluLookAt(x, y, z, x + lx, 0, z + lz, 0, 1, 0); } }
eeue56/3DBlocks
src/Camera.java
423
/** * Creates new Camera instance */
block_comment
en
false
377
10
423
9
476
12
423
9
542
14
false
false
false
false
false
true
225768_2
/* A Naive recursive implementation of LCS problem in java*/ public class LongestCommonSubsequence { /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ int lcs(char[] X, char[] Y, int m, int n) { if (m == 0 || n == 0) return 0; if (X[m - 1] == Y[n - 1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } /* Utility function to get max of 2 integers */ int max(int a, int b) { return (a > b) ? a : b; } public static void main(String[] args) { LongestCommonSubsequence lcs = new LongestCommonSubsequence(); String s1 = "AGGTAB"; String s2 = "GXTXAYB"; char[] X = s1.toCharArray(); char[] Y = s2.toCharArray(); int m = X.length; int n = Y.length; System.out.println("Length of LCS is" + " " + lcs.lcs(X, Y, m, n)); } }
MaintanerProMax/HacktoberFest2022
LCS.java
334
/* Utility function to get max of 2 integers */
block_comment
en
false
332
11
334
11
378
11
334
11
427
12
false
false
false
false
false
true
229314_10
import java.util.ArrayList; /** * A Class Representing Owner's Object * @author User-1 * @version 1.0.0 */ public class Owner { private String name = ""; private String ppsNum = ""; private String password = ""; private ArrayList<String> propertiesOwned = new ArrayList<String>(); /** * @param name Name of owner * @param ppsNum Personal Public Service Number (ppsNum) of owner * @param password Password of owner */ public Owner(String name, String ppsNum, String password) { setName(name); setPpsNum(ppsNum); setPassword(password); } /** * Method to set name of owner * @param name name of the owner */ public void setName(String name) { this.name = name; } /** * Method to set pps number * @param ppsNum Personal Public Service Number of owner */ public void setPpsNum(String ppsNum) { this.ppsNum = ppsNum; } /** * Method to set password (no return type) * @param password Password of the wner */ public void setPassword(String password) { this.password = password; } /** * Method to return name * @return value of name */ public String getName() { return name; } /** * Personal Public Service Number * @return return Personal Public Service Number of the owner */ public String getPpsNum() { return ppsNum; } /** * Show password * @return password of user */ public String getPassword() { return password; } /** * Add Property to Owner's property list * @param eircode eircode of Property */ public void addProperty(String eircode){ propertiesOwned.add(eircode); } /** * Method to Remove Property from the list using id * @param propertyId id of Property */ public void removeProperty(int propertyId){ propertiesOwned.remove(propertyId); } /** * Get properties list * @return List of properties Owned */ public ArrayList<String> getPropertiesEircodes(){ return propertiesOwned; } }
j1m-ryan/CS4013-Project
src/Owner.java
519
/** * Get properties list * @return List of properties Owned */
block_comment
en
false
505
18
519
17
646
21
519
17
690
24
false
false
false
false
false
true
230735_2
package AdventureModel; import java.io.Serializable; import java.util.ArrayList; /** * This class keeps track of the progress * of the player in the game. */ public class Player implements Serializable { /** * The current room that the player is located in. */ private Room currentRoom; /** * The list of items that the player is carrying at the moment. */ public ArrayList<AdventureObject> inventory; /** * Adventure Game Player Constructor */ public Player(Room currentRoom) { this.inventory = new ArrayList<AdventureObject>(); this.currentRoom = currentRoom; } /** * This method adds an object into players inventory if the object is present in * the room and returns true. If the object is not present in the room, the method * returns false. * * @param object name of the object to pick up * @return true if picked up, false otherwise */ public boolean takeObject(String object){ if(this.currentRoom.checkIfObjectInRoom(object)){ AdventureObject object1 = this.currentRoom.getObject(object); this.currentRoom.removeGameObject(object1); this.addToInventory(object1); return true; } else { return false; } } /** * checkIfObjectInInventory * __________________________ * This method checks to see if an object is in a player's inventory. * * @param s the name of the object * @return true if object is in inventory, false otherwise */ public boolean checkIfObjectInInventory(String s) { for(int i = 0; i<this.inventory.size();i++){ if(this.inventory.get(i).getName().equals(s)) return true; } return false; } /** * This method drops an object in the players inventory and adds it to the room. * If the object is not in the inventory, the method does nothing. * * @param s name of the object to drop */ public void dropObject(String s) { for(int i = 0; i<this.inventory.size();i++){ if(this.inventory.get(i).getName().equals(s)) { this.currentRoom.addGameObject(this.inventory.get(i)); this.inventory.remove(i); } } } /** * Setter method for the current room attribute. * * @param currentRoom The location of the player in the game. */ public void setCurrentRoom(Room currentRoom) { this.currentRoom = currentRoom; } /** * This method adds an object to the inventory of the player. * * @param object Prop or object to be added to the inventory. */ public void addToInventory(AdventureObject object) { this.inventory.add(object); } /** * Getter method for the current room attribute. * * @return current room of the player. */ public Room getCurrentRoom() { return this.currentRoom; } /** * Getter method for string representation of inventory. * * @return ArrayList of names of items that the player has. */ public ArrayList<String> getInventory() { ArrayList<String> objects = new ArrayList<>(); for(int i=0;i<this.inventory.size();i++){ objects.add(this.inventory.get(i).getName()); } return objects; } }
IbraTech04/AdventureEditorPro
AdventureModel/Player.java
788
/** * The list of items that the player is carrying at the moment. */
block_comment
en
false
715
18
788
19
878
20
788
19
961
20
false
false
false
false
false
true
230782_1
/** * Location for text adventure game. * @author Sean Stern * @version 1.0 */ public interface Location{ /** * Gets the name of the location in the text adventure game. * Every location in a {@link Game} should have a unique name so that an * {@link Engine} can properly track the state of the game. * * @return a unique identifier for each level */ public String getName(); /** * Causes the {@link Player} to enter the location and returns * the name of the next game location. * * @param p the {@link Player} entering the location * @return the name of the next location * @throws InterruptedException if the game is paused and gets interrupted */ public String enter(Player p) throws InterruptedException; }
bujars/text-adventure-origin-jumpworks
Location.java
182
/** * Gets the name of the location in the text adventure game. * Every location in a {@link Game} should have a unique name so that an * {@link Engine} can properly track the state of the game. * * @return a unique identifier for each level */
block_comment
en
false
178
64
182
63
196
68
182
63
208
70
false
false
false
false
false
true
231533_1
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; /** * <h3>COMP90041, Sem2, 2022: Final Project</h3> * <p>Class HRAssistant is used to take in command flags from running HRAssistant. Run the approriate type of menu, functionalities and * display welcome messages. * @author Gia Han Ly */ public class HRAssistant { public static void main(String[] args){ // Read command line option Command command = new Command(); command.readCommand(args); String appFile = command.getApplicationsFile(); String jobsFile = command.getJobsFile(); // Go to HR menu if role flag is set to hr if(command.getRole().equals("hr")){ displayWelcomeMessage("hr"); HRmenu hrMenu = new HRmenu(jobsFile, appFile); hrMenu.getInput(); System.out.println(); } // Go to applicant menu if role flag is set to applicant else if(command.getRole().equals("applicant")){ displayWelcomeMessage("applicant"); ApplicantMenu menu = new ApplicantMenu(jobsFile, appFile); menu.getInput(); System.out.println(); } else if (command.getRole().equals("audit")){ Audit audit = new Audit(jobsFile, appFile); audit.printStatistics(); } } /** * Display welcome messages depends on role input * @param role */ private static void displayWelcomeMessage(String role) { Scanner inputStream = null; String filename = null; if(role.equals("hr")){ filename = "welcome_hr.ascii"; } else if(role.equals("applicant")){ filename = "welcome_applicant.ascii"; } try{ inputStream = new Scanner(new FileInputStream(filename)); } catch (FileNotFoundException e) { System.out.println("Welcome File not found."); } while(inputStream.hasNextLine()) { System.out.println(inputStream.nextLine()); } } }
amybok/COMP90041-2022Sem2Final
HRAssistant.java
479
// Read command line option
line_comment
en
false
433
5
479
5
518
5
479
5
599
5
false
false
false
false
false
true
231856_16
/ Java program to print BFS traversal from a given source vertex. // BFS(int s) traverses vertices reachable from s. import java.io.*; import java.util.*; // This class represents a directed graph using adjacency list // representation class Graph { private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency Lists // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); } // prints BFS traversal from a given source s void BFS(int s) { // Mark all the vertices as not visited(By default // set as false) boolean visited[] = new boolean[V]; // Create a queue for BFS LinkedList<Integer> queue = new LinkedList<Integer>(); // Mark the current node as visited and enqueue it visited[s]=true; queue.add(s); while (queue.size() != 0) { // Dequeue a vertex from queue and print it s = queue.poll(); System.out.print(s+" "); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it Iterator<Integer> i = adj[s].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) { visited[n] = true; queue.add(n); } } } } // Driver method to public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println("Following is Breadth First Traversal "+ "(starting from vertex 2)"); g.BFS(2); } }
TitanVaibhav/ByldSession
bfs.java
528
// Driver method to
line_comment
en
false
488
4
528
4
594
4
528
4
638
4
false
false
false
false
false
true
232323_3
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.LineBorder; import java.sql.*; import java.time.format.DateTimeFormatter; import java.time.*; import java.security.*; public class CallLogs extends PhonePresetWithNoWallpaper implements ActionListener, KeyListener{ // Clear Call log button private JButton homeBtn = new JButton(); JButton clearBtn = new JButton(); private SecureRandom randomNumbers = new SecureRandom(); // object for random numbers // Panel to hold contacts private JPanel contactListPanel = new JPanel(); private String today; private String yesterday; // Control how events are added; make sure listeners are added only once private boolean eventsAdded = false; private JPanel allPanel = new JPanel(); private JLabel allLabel = new JLabel("All"); private JPanel missedPanel = new JPanel(); private JLabel missedLabel = new JLabel("Missed"); // Constructor --> public CallLogs(){ setLayout(null); DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("E, MMM d yyyy"); LocalDateTime now = LocalDateTime.now(); today = dateFormat.format(now); LocalDate yestee = (LocalDate.now()).minusDays(1); yesterday = dateFormat.format(yestee); showAllCalls(); // Add event listeners to nav buttons if(!eventsAdded){ missedLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { showMissedCalls(); // System.out.println("Missed Label pressed"); missedLabel.setForeground(Color.WHITE); missedPanel.setBackground(SystemColor.controlDkShadow); allPanel.setBackground(Color.BLACK); } }); allLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { showAllCalls(); // System.out.println("All Label pressed"); allLabel.setForeground(Color.WHITE); allPanel.setBackground(SystemColor.controlDkShadow); missedPanel.setBackground(Color.BLACK); } }); homeBtn.addActionListener(this); clearBtn.addActionListener(this); eventsAdded = true; } addInnerJPanel(); }// <-- end Constructor // add panel on which list wil be written public void addInnerJPanel(){ // Add scroll pane to inner panel JScrollPane scrollPane = new JScrollPane(contactListPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setBounds( 20, 90, 247, 380 ); scrollPane.setPreferredSize(new Dimension(160, 200)); scrollPane.setBorder(null); scrollPane.getVerticalScrollBar().setUnitIncrement(10); contactListPanel.setLayout(null); contactListPanel.setBackground(Color.WHITE); add(scrollPane); showNavigationButtons(); } //RECENT AND CONTACTS TAB CODES public void addRecAndConTab() { JLabel dialLabel = new JLabel("New label"); dialLabel.setBounds(62, 489, 34, 34); dialLabel.setIcon(new ImageIcon(getClass().getResource("/images/icons/dialpad.png"))); dialLabel.setVerticalAlignment(SwingConstants.BOTTOM); dialLabel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent arg0) { changeCurrentPage("dial"); } }); add(dialLabel); JLabel contactsLabel = new JLabel("New label"); contactsLabel.setBounds(185, 489, 34, 34); contactsLabel.setIcon(new ImageIcon(getClass().getResource("/images/icons/contac.png"))); contactsLabel.setVerticalAlignment(SwingConstants.BOTTOM); contactsLabel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent arg0) { changeCurrentPage("contacts"); } }); add(contactsLabel); // Home Button Icon homebar = new ImageIcon(getClass().getResource("./images/homebar.png")); homeBtn.setIcon(homebar); homeBtn.setForeground(Color.BLUE); homeBtn.setBounds(75, 532, 131, 10); homeBtn.setHorizontalAlignment(SwingConstants.CENTER); super.makeButtonTransparent(homeBtn, false); homeBtn.setFocusable(false); add(homeBtn); } private void showNavigationButtons(){ Icon addIcon = new ImageIcon(getClass().getResource("./images/icons/delete.png")); clearBtn.setBounds(223, 50, 50, 30); clearBtn.setIcon(addIcon); super.makeButtonTransparent(clearBtn, false); clearBtn.setFocusable(false); add(clearBtn); // Show top nav JPanel topNav = new JPanel(); topNav.setLayout(null); topNav.setBorder(new LineBorder(new Color(169, 169, 169), 3, true)); topNav.setBackground(Color.WHITE); topNav.setBounds(77, 50, 125, 30); add(topNav); allPanel.setLayout(null); allPanel.setBackground(SystemColor.controlDkShadow); allPanel.setBounds(0, 0, 62, 30); topNav.add(allPanel); allLabel.setHorizontalAlignment(SwingConstants.CENTER); allLabel.setForeground(Color.WHITE); allLabel.setFont(new Font("Raleway", Font.PLAIN, 15)); allLabel.setBounds(3, 5, 56, 16); allPanel.add(allLabel); missedPanel.setBackground(Color.BLACK); missedPanel.setBounds(62, 0, 62, 30); topNav.add(missedPanel); missedLabel.setHorizontalAlignment(SwingConstants.CENTER); missedLabel.setForeground(Color.WHITE); missedLabel.setFont(new Font("Raleway", Font.PLAIN, 15)); missedPanel.add(missedLabel); // System.out.println("all label mouse listeners count : "+allLabel.getMouseListeners().length); // System.out.println("missed label mouse listeners count : "+missedLabel.getMouseListeners().length); // Show bottom nav addRecAndConTab(); } // display missed calls public void showMissedCalls(){ contactListPanel.removeAll(); contactListPanel.revalidate(); contactListPanel.repaint(); // System.out.println("Missed Calls"); MyDatabaseManager db = new MyDatabaseManager(); displayCallLogs(db.fetchSpecificCallLog("missed")); // Resize scroll bar int count = db.countNumOfRowsFrom( db.fetchSpecificCallLog("missed")); contactListPanel.setPreferredSize(new Dimension(247, (count*65))); contactListPanel.repaint(); // show changes made } // display all calls public void showAllCalls() { contactListPanel.removeAll(); contactListPanel.revalidate(); contactListPanel.repaint(); // System.out.println("All Calls"); MyDatabaseManager db = new MyDatabaseManager(); displayCallLogs(db.fetchAllCallLog()); // Resize scroll bar int count = db.countNumOfRowsFrom( db.fetchAllCallLog()); contactListPanel.setPreferredSize(new Dimension(247, (count*65))); contactListPanel.repaint(); // show changes made } // display call logs function public void displayCallLogs(ResultSet logsList){ // starting values int x = 10, y = 5, w = 200, h = 60; // Display all call logs if it is not empty try{ // Display contact list now if(logsList.next()){ do{ String phone = logsList.getString("log_phone"); String time = logsList.getString("time"); String date = logsList.getString("date"); String category = logsList.getString("category"); String categoryIconUrl = ""; String name = logsList.getString("name"); name = (name == null || name.contentEquals("")) ? phone : name; if(category.contentEquals("missed")){ categoryIconUrl = "./images/icons/missedCall.png"; } else if(category.contentEquals("dialed")){ categoryIconUrl = "./images/icons/callout.png"; } int num = 1 + randomNumbers.nextInt(6); String defaultImageUrl = "./images/icons/contacts/contacts-"+num+".png"; Icon contactImage = new ImageIcon(getClass().getResource(defaultImageUrl)); // System.out.printf("%10s%10s%10s%n", phone, time, category); Icon categoryIcon = new ImageIcon(ContactsPage.class.getResource(categoryIconUrl)); // making the line under the Calendar label JSeparator separator = new JSeparator(); separator.setBackground(Color.LIGHT_GRAY); separator.setBounds(x , y, w, 2); contactListPanel.add(separator); y += 4; // outer label for name/phone JLabel contactLog = new JLabel(); contactLog.setText(String.format("%s",name)); contactLog.setIcon(contactImage); contactLog.setForeground(Color.DARK_GRAY); contactLog.setFont(new Font("Raleway", Font.PLAIN, 18)); contactLog.setHorizontalAlignment(SwingConstants.LEFT); contactLog.setVerticalAlignment(SwingConstants.TOP); contactLog.setHorizontalTextPosition(SwingConstants.RIGHT); contactLog.setVerticalTextPosition(SwingConstants.TOP); contactLog.setIconTextGap(22); contactLog.setBounds(x, y, w, h); contactLog.setLayout(null); // inner label for icon and time String day = date; String innerStr = String.format("<html>%s<br>%s</html>", day, time); if(today.compareTo(date) == 0){ innerStr = String.format("Today, %s", time); } else if(yesterday.compareTo(date) == 0){ innerStr = String.format("Yesterday, %s", time);; } // inner label JButton inner = new JButton(innerStr, categoryIcon); super.makeButtonTransparent(inner, false); inner.setBounds(40, 26, 180, 30); inner.setFocusable(false); inner.setFont(new Font("Raleway", Font.PLAIN, 12)); inner.setHorizontalAlignment(SwingConstants.LEFT); contactLog.add(inner); contactListPanel.add(contactLog); y = y+h+1; // add an action listener contactLog.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { makeCall(phone); } }); }while(logsList.next());// end do while loop }else{ JLabel nothingFound = new JLabel("Nothing Found!"); nothingFound.setForeground(Color.GRAY); nothingFound.setHorizontalAlignment(SwingConstants.CENTER); nothingFound.setVerticalAlignment(SwingConstants.CENTER); nothingFound.setFont(new Font("Raleway", Font.PLAIN, 14)); nothingFound.setBounds(5, 110, 235, 45); contactListPanel.add(nothingFound); } }catch(SQLException ex){ System.out.println(ex.getMessage()); System.out.println(ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } } // make a call public void makeCall(String contactNumber){ // System.out.println("dialing "+contactName+"..."); PhoneDial panel = new PhoneDial(); panel.setTextFieldText(contactNumber); NewWindowFrame frame = new NewWindowFrame(panel); frame.setVisible(true); ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose(); } // Handle ActionListener events public void actionPerformed(ActionEvent e){ if( e.getSource() == homeBtn ){ // Go to home screen HomeScreen panel = new HomeScreen(); NewWindowFrame frame = new NewWindowFrame(panel); frame.setVisible(true); ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose(); } if( e.getSource() == clearBtn ){ // Go to home screen MyDatabaseManager db = new MyDatabaseManager(); if(db.clearCallLog()){ // refresh page CallLogs panel = new CallLogs(); NewWindowFrame frame = new NewWindowFrame(panel); frame.setVisible(true); ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose(); } } }// <-- end actionPerformed // Handle KeyListener events public void keyTyped(KeyEvent e){ // code... }// <-- end keyTyped public void keyPressed(KeyEvent e){ // code... }// <-- end keyPressed public void keyReleased(KeyEvent e){ // code... }// <-- end keyReleased // Change current page public void changeCurrentPage(String target){ if(target == "dial"){ // go to dial page PhoneDial panel = new PhoneDial(); NewWindowFrame frame = new NewWindowFrame(panel); frame.setVisible(true); ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose(); } else if(target == "contacts"){ // go to contacts page ContactsPage panel = new ContactsPage(); NewWindowFrame frame = new NewWindowFrame(panel); frame.setVisible(true); ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose(); } else if(target == "logs"){ // go to call logs page CallLogs panel = new CallLogs(); NewWindowFrame frame = new NewWindowFrame(panel); frame.setVisible(true); ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose(); } } }
theLivin/phone-simulator
CallLogs.java
3,233
// Control how events are added; make sure listeners are added only once
line_comment
en
false
2,886
15
3,233
15
3,484
15
3,233
15
4,117
16
false
false
false
false
false
true
233109_23
package vrml.node; import java.util.Hashtable; import vrml.*; // // This is the general Script class, to be subclassed by all scripts. // Note that the provided methods allow the script author to explicitly // throw tailored exceptions in case something goes wrong in the // script. // public abstract class Script extends vrml.BaseNode { Hashtable fields; Hashtable fieldkinds; Hashtable fieldtypes; public Script() { fields = new Hashtable(); fieldkinds = new Hashtable(); fieldtypes = new Hashtable(); } public void add_field(String kind, String type, String name, Field f) { fields.put(name,f); fieldkinds.put(name,kind); fieldtypes.put(name,type); } public String get_field_type(String name) { return (String)fieldtypes.get(name); } // This method is called before any event is generated public void initialize() { } // Get a Field by name. // Throws an InvalidFieldException if fieldName isn't a valid // field name for a node of this type. protected final Field getField(String fieldName) { return (Field)fields.get(fieldName); } // Get an EventOut by name. // Throws an InvalidEventOutException if eventOutName isn't a valid // eventOut name for a node of this type. // spec: protected public final Field getEventOut(String eventOutName) { return (Field)fields.get(eventOutName); } // Get an EventIn by name. // Throws an InvalidEventInException if eventInName isn't a valid // eventIn name for a node of this type. protected final Field getEventIn(String eventInName) { return (Field)fields.get(eventInName); } // processEvents() is called automatically when the script receives // some set of events. It shall not be called directly except by its subclass. // count indicates the number of events delivered. public void processEvents(int count, Event events[]) { } // processEvent() is called automatically when the script receives // an event. public void processEvent(Event event) { } // eventsProcessed() is called after every invocation of processEvents(). public void eventsProcessed() { } // shutdown() is called when this Script node is deleted. public void shutdown() { } public String toString() { return ""; } // This overrides a method in Object }
gitpan/FreeWRL
java/Script.java
578
// shutdown() is called when this Script node is deleted.
line_comment
en
false
533
12
577
12
622
12
578
12
663
13
false
false
false
false
false
true
234087_1
import java.util.ArrayList; public class Lighting { //direction that the light faces. public Vector3 lightDirection; //how bright should the illuminated side of meshes be? public double lightIntensity; //how dark should the unilluminated side of meshes be? public double shadowIntensity; public Lighting(Vector3 lightDirectionIn, double lightIntensityIn, double shadowIntensityIn) { lightDirection = lightDirectionIn; lightIntensity = lightIntensityIn; shadowIntensity = shadowIntensityIn; } //goes through the specified meshes and updates all their lighting's public void update(ArrayList<Mesh> meshes) { for (int i = 0; i < meshes.size(); i++) meshes.get(i).calculateLighting(this); } }
trrt-good/FlightSimulator
Lighting.java
179
//how bright should the illuminated side of meshes be?
line_comment
en
false
169
11
179
12
198
11
179
12
234
14
false
false
false
false
false
true
234105_5
import java.awt.event.KeyEvent; import javax.media.opengl.GL2; import javax.media.opengl.glu.GLU; import com.jogamp.opengl.util.gl2.GLUT; import framework.JOGLFrame; import framework.Scene; import framework.ShaderProgram; /** * Display a simple scene to demonstrate OpenGL. * * @author Robert C. Duvall */ public class Shader extends Scene { private static final String SHADERS_DIR = "/shaders/"; private static final String[] SHADERS = { "fixed", "diffuse", "gouraud", "gooch", "pulse" }; private float[] myLightPos = { 0, 1, 1, 1 }; // animation state private float myTime; private float myAngle; private boolean isShaderOn; private String myShaderFile; private ShaderProgram myShader; /** * Create the scene with the given arguments. */ public Shader (String[] args) { super("Shader example"); myTime = 0; myAngle = 0; isShaderOn = true; myShaderFile = args.length > 0 ? args[0] : "fixed"; } /** * Initialize general OpenGL values once (in place of constructor). */ @Override public void init (GL2 gl, GLU glu, GLUT glut) { // load shaders from disk ONCE myShader = makeShader(gl, myShaderFile); } /** * Draw all of the objects to display. */ @Override public void display (GL2 gl, GLU glu, GLUT glut) { // usually not necessary myShader = makeShader(gl, myShaderFile); gl.glRotatef(myAngle, 0, 1, 0); if (isShaderOn) { myShader.bind(gl); { glut.glutSolidTeapot(1); } myShader.unbind(gl); } else { gl.glColor3d(1, 0, 1); glut.glutSolidTeapot(1); } } /** * Set the camera's view of the scene. */ @Override public void setCamera (GL2 gl, GLU glu, GLUT glut) { glu.gluLookAt(0, 1, 5, // from position 0, 0, 0, // to position 0, 1, 0); // up direction } /** * Establish the lights in the scene. */ public void setLighting (GL2 gl, GLU glu, GLUT glut) { gl.glEnable(GL2.GL_LIGHTING); gl.glEnable(GL2.GL_LIGHT0); gl.glShadeModel(GL2.GL_SMOOTH); gl.glEnable(GL2.GL_COLOR_MATERIAL); // position light and make it a spotlight gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, myLightPos, 0); } /** * Animate the scene by changing its state slightly. */ @Override public void animate (GL2 gl, GLU glu, GLUT glut) { myAngle += 4; myTime += 1.0f / JOGLFrame.FPS; myShader.bind(gl); { // animate shader values if (myShaderFile == "pulse") { myShader.setUniform(gl, "time", new float[] { myTime }, 1); } } myShader.unbind(gl); } /** * Called when any key is pressed within the canvas. */ @Override public void keyReleased (int keyCode) { switch (keyCode) { // turn light on/off case KeyEvent.VK_S: isShaderOn = ! isShaderOn; break; case KeyEvent.VK_1: case KeyEvent.VK_2: case KeyEvent.VK_3: case KeyEvent.VK_4: case KeyEvent.VK_5: myShaderFile = SHADERS[keyCode - KeyEvent.VK_1]; break; } } // create a program from the corresponding vertex and fragment shaders private ShaderProgram makeShader (GL2 gl, String filename) { ShaderProgram result = new ShaderProgram(); result.attachVertexShader(gl, SHADERS_DIR+filename+".vert"); result.attachFragmentShader(gl, SHADERS_DIR+filename+".frag"); result.link(gl); return result; } // allow program to be run from here public static void main (String[] args) { new JOGLFrame(new Shader(args)); } }
duke-compsci344-spring2015/lab_opengl
src/Shader.java
1,101
/** * Draw all of the objects to display. */
block_comment
en
false
1,004
13
1,101
13
1,180
15
1,101
13
1,329
15
false
false
false
false
false
true
234116_1
public class Floor extends Thing { private double floorHeight; private Color dark, bright; private Color specularLight; public Floor(Color dark, Color bright, double floorHeight, Color specularLight) { this.dark = dark; this.bright = bright; this.floorHeight = floorHeight; this.specularLight = specularLight; } public boolean hasLighting() { return true; } public Color getSpecularWeight() {// what does specular light need to be? return specularLight; } public void makeColorProportional(double size) { // keeps the original colors proportional to what you chose, // and prepares them for recieving diffuse lighting and shadows dark.changeColor(dark.getRed() * size, dark.getGreen() * size, dark.getBlue() * size); bright.changeColor(bright.getRed() * size, bright.getGreen() * size, bright.getBlue() * size); } public Point getNormal(Point spot) { return new Point(0.0, 1.0, 0.0); } public Color getAmbient(Point p) { double cD = 4; double x = p.getX(); double z = p.getZ(); x = x % cD; z = z % cD; if (z > -1 && z <= 2) { if (x >= 0 && x <= 2) { return dark; } if (x >= 2 && x < 4) { return bright; } if (x < 0 && x >= -2) { return bright; } if (x <= -2 && x > -4) { return dark; } } if (z >= 2 && z < 4) { if (x >= 0 && x <= 2) { return bright; } if (x >= 2 && x < 4) { return dark; } if (x < 0 && x >= -2) { return dark; } if (x <= -2 && x > -4) { return bright; } } return new Color(255, 25, 25);// you should never see this color } public Intersection getIntersection(Point start, Point end) { double distance = (floorHeight - start.getY()) / (end.getY() - start.getY()); if (Math.abs(end.getX() - start.getY()) < this.MIN) { return new Intersection(60 + 1, null, null); } if (distance < MIN) { return new Intersection(60 + 1, null, null); } double x = start.getX() * (1.0 - distance) + end.getX() * distance; double y = floorHeight; double z = start.getZ() * (1.0 - distance) + end.getZ() * distance; return new Intersection(distance, new Point(x, y, z), this); } public boolean hasDiffuse() { return true; } public Color getDiffuse(Point p) { return getAmbient(p); } }
edgartheunready/raytracer
Floor.java
727
// keeps the original colors proportional to what you chose,
line_comment
en
false
694
12
727
13
828
11
727
13
872
11
false
false
false
false
false
true
234120_27
package edu.mit.blocks.codeblockutil; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import javax.swing.JButton; import javax.swing.SwingUtilities; /** * A CButton is a swing-compatible widget that allows clients * to display an oval button with an optional text. * * To add a particular action to this widget, users should invoke * this.addCButtonListener( new CButtonListener()); */ public class CButton extends JButton implements MouseListener { private static final long serialVersionUID = 328149080228L; /** blur lighting of this button */ static float[] BLUR = {0.10f, 0.10f, 0.10f, 0.10f, 0.30f, 0.10f, 0.10f, 0.10f, 0.10f}; /** the inset of this button */ static final int INSET = 3; /** The highlighting inset */ static final int HIGHLIGHT_INSET = 2; /** Focus Flag: true iff mouse is hovering over button */ boolean focus = false; /** Press Flag: true iff button was pressed but has not been released */ boolean pressed = false; /** Selected Flag: true iff button was toggled to selected */ boolean selected = false; /** Color of this button when not pressed */ Color buttonColor; /** Color of this button when pressed */ Color selectedColor; /** Color of the foreground when not hovered */ Color foregroundColor = Color.white; /** Color of the foreground whe hovered */ Color hoveredColor = Color.red; /** * Creates a button with text and black buttonColor, and * white slectedColor * @param text */ public CButton(String text) { this(new Color(30, 30, 30), Color.gray, text); } /** * Create a button with text; * @param buttonColor - color when not pressed down * @param selectedColor - color when pressed down but not released yet * @param text - textual label of this * * @requires buttonColor, selectedColor, text != null * @effects constructs new CButton */ public CButton(Color buttonColor, Color selectedColor, String text) { super(); this.setOpaque(false); this.buttonColor = buttonColor; this.selectedColor = selectedColor; this.setText(text); this.setFont(new Font("Ariel", Font.BOLD, 16)); this.addMouseListener(this); this.setPreferredSize(new Dimension(80, 25)); this.setCursor(new Cursor(Cursor.HAND_CURSOR)); } /** * Dynamically changes the coloring of the buttons when * pressed or not pressed. * * @param buttonColor * @param selectedColor * * @requires buttonColor, selectedColor != null * @modifies this.buttonColor && this.seletedColor * @effects change button coloring to match to inputs */ public void setLighting(Color buttonColor, Color selectedColor) { this.buttonColor = buttonColor; this.selectedColor = selectedColor; } public void setTextLighting(Color foregroundColor, Color hoveredColor) { this.foregroundColor = foregroundColor; this.hoveredColor = hoveredColor; } /** * @modifies this.selected * @effects toggles selcted flag to valeu of selected */ public void toggleSelected(boolean selected) { this.selected = selected; this.repaint(); } ///////////////////////////////////////////////////////////////////////// //Methods below this line should not be //modified or overriden and affects the Rendering of this button. /////////////////////// /** * Prevents textual label from display out of the bounds * of the this oval shaped button's edges */ @Override public Insets getInsets() { //top, left, bottom, right return new Insets(0, this.getHeight() / 2, 0, this.getHeight() / 2); } /** * re paints this */ @Override public void paint(Graphics g) { //super.paint(g); //selected color Color backgroundColor; if (this.pressed || this.selected) { backgroundColor = this.selectedColor; } else { backgroundColor = this.buttonColor; } // Set up graphics and buffer Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); BufferedImage buffer = GraphicsManager.gc.createCompatibleImage(this.getWidth(), this.getHeight(), Transparency.TRANSLUCENT); Graphics2D gb = buffer.createGraphics(); gb.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Set up first layer int buttonHeight = this.getHeight() - (INSET * 2); int buttonWidth = this.getWidth() - (INSET * 2); int arc = buttonHeight; Color topColoring = backgroundColor.darker(); Color bottomColoring = backgroundColor.darker(); gb.setPaint(new GradientPaint(0, INSET, topColoring, 0, buttonHeight, bottomColoring, false)); // Paint the first layer gb.fillRoundRect(INSET, INSET, buttonWidth, buttonHeight, arc, arc); gb.setColor(Color.darkGray); gb.drawRoundRect(INSET, INSET, buttonWidth, buttonHeight, arc, arc); // set up paint data fields for second layer int highlightHeight = buttonHeight - (HIGHLIGHT_INSET * 2); int highlightWidth = buttonWidth - (HIGHLIGHT_INSET * 2); int highlightArc = highlightHeight; topColoring = backgroundColor.brighter().brighter().brighter().brighter(); bottomColoring = backgroundColor.brighter().brighter().brighter().brighter(); // Paint the second layer gb.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .8f)); gb.setPaint(new GradientPaint(0, INSET + HIGHLIGHT_INSET, topColoring, 0, INSET + HIGHLIGHT_INSET + (highlightHeight / 2), backgroundColor.brighter(), false)); gb.setClip(new RoundRectangle2D.Float(INSET + HIGHLIGHT_INSET, INSET + HIGHLIGHT_INSET, highlightWidth, highlightHeight / 2, highlightHeight / 3, highlightHeight / 3)); gb.fillRoundRect(INSET + HIGHLIGHT_INSET, INSET + HIGHLIGHT_INSET, highlightWidth, highlightHeight, highlightArc, highlightArc); // Blur ConvolveOp blurOp = new ConvolveOp(new Kernel(3, 3, BLUR)); BufferedImage blurredImage = blurOp.filter(buffer, null); // Draw button g2.drawImage(blurredImage, 0, 0, null); // Draw the text (if any) if (this.getText() != null) { if (this.focus) { g2.setColor(hoveredColor); } else { g2.setColor(foregroundColor); } Font font = g2.getFont().deriveFont((float) (((float) buttonHeight) * .6)); g2.setFont(font); FontMetrics metrics = g2.getFontMetrics(); Rectangle2D textBounds = metrics.getStringBounds(this.getText(), g2); float x = (float) ((this.getWidth() / 2) - (textBounds.getWidth() / 2)); float y = (float) ((this.getHeight() / 2) + (textBounds.getHeight() / 2)) - metrics.getDescent(); g2.drawString(this.getText(), x, y); } } ////////////////////// //Mouse Listeners ////////////////////// @Override public void addMouseListener(MouseListener l) { super.addMouseListener(l); } @Override public void mouseEntered(MouseEvent e) { this.focus = true; repaint(); } @Override public void mouseExited(MouseEvent e) { this.focus = false; repaint(); } @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { this.pressed = true; } repaint(); } @Override public void mouseReleased(MouseEvent e) { this.pressed = false; repaint(); } @Override public void mouseClicked(MouseEvent e) { } }
laurentschall/openblocks
src/main/java/edu/mit/blocks/codeblockutil/CButton.java
2,198
// set up paint data fields for second layer
line_comment
en
false
1,957
10
2,198
10
2,429
10
2,198
10
2,709
10
false
false
false
false
false
true
234459_6
package Model; /** * * @author Jonathan */ public class Review { private String idReview; private int useful; private int Funny; private int Rating; private String Comment; private String Status; private String ReportDetails; private String reviewer; private String images; private String review; public Review() { } public Review(String idReview, int useful, int Funny, int Rating, String Comment, String Status, String ReportDetails) { this.idReview = idReview; this.useful = useful; this.Funny = Funny; this.Rating = Rating; this.Comment = Comment; this.Status = Status; this.ReportDetails = ReportDetails; } /** * @return the idReview */ public String getIdReview() { return idReview; } /** * @param idReview the idReview to set */ public void setIdReview(String idReview) { this.idReview = idReview; } /** * @return the useful */ public int getUseful() { return useful; } /** * @param useful the useful to set */ public void setUseful(int useful) { this.useful = useful; } /** * @return the Funny */ public int getFunny() { return Funny; } /** * @param Funny the Funny to set */ public void setFunny(int Funny) { this.Funny = Funny; } /** * @return the Rating */ public int getRating() { return Rating; } /** * @param Rating the Rating to set */ public void setRating(int Rating) { this.Rating = Rating; } /** * @return the Comment */ public String getComment() { return Comment; } /** * @param Comment the Comment to set */ public void setComment(String Comment) { this.Comment = Comment; } /** * @return the Status */ public String getStatus() { return Status; } /** * @param Status the Status to set */ public void setStatus(String Status) { this.Status = Status; } /** * @return the ReportDetails */ public String getReportDetails() { return ReportDetails; } /** * @param ReportDetails the ReportDetails to set */ public void setReportDetails(String ReportDetails) { this.ReportDetails = ReportDetails; } /** * @return the reviewer */ public String getReviewer() { return reviewer; } /** * @param reviewer the reviewer to set */ public void setReviewer(String reviewer) { this.reviewer = reviewer; } /** * @return the images */ public String getImages() { return images; } /** * @param images the images to set */ public void setImages(String images) { this.images = images; } /** * @return the review */ public String getReview() { return review; } /** * @param review the review to set */ public void setReview(String review) { this.review = review; } }
getEat/getEatCode
GetEat/Review.java
749
/** * @param Funny the Funny to set */
block_comment
en
false
725
13
749
14
947
15
749
14
1,030
18
false
false
false
false
false
true
235025_2
/* * Copyright (C) 2014 Alfons Wirtz * website www.freerouting.net * * 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 at <http://www.gnu.org/licenses/> * for more details. */ package board; import geometry.planar.TileShape; import java.util.Set; /** * * Functionality required for items, which can be * electrical connected to other items. * * @author Alfons Wirtz */ public interface Connectable { /** * Returns true if this item belongs to the net with number p_net_no. */ public boolean contains_net(int p_net_no); /** * Returns true if the net number array of this and p_net_no_arr have a common * number. */ public boolean shares_net_no(int [] p_net_no_arr); /** * Returns a list of all connectable items overlapping * and sharing a net with this item. */ Set<Item> get_all_contacts(); /** * Returns a list of all connectable items overlapping with * this item on the input layer and sharing a net with this item. */ Set<Item> get_all_contacts(int p_layer ); /** * Returns the list of all contacts of a connectable item * located at defined connection points. * Connection points of traces are there endpoints, connection * points of drill_items there center points, and connection * points of conduction areas are points on there border. */ Set<Item> get_normal_contacts(); /** * Returns all connectable items of the net with number p_net_no, which can be reached recursively * from this item via normal contacts. * if (p_net_no <= 0, the net number is ignored. */ Set<Item> get_connected_set(int p_net_no); /** * Returns for each convex shape of a connectable item * the subshape of points, where traces can be connected to that item. */ TileShape get_trace_connection_shape(ShapeSearchTree p_tree, int p_index); }
nikropht/FreeRouting
board/Connectable.java
620
/** * Returns true if this item belongs to the net with number p_net_no. */
block_comment
en
false
554
20
620
22
657
24
620
22
712
24
false
false
false
false
false
true
235157_3
// Pyramid.java import java.util.Scanner; public class Pyramid extends Shape implements Volume { private double baseLength; private double baseWidth; private double height; @Override public double calculateShape() { // Surface area of a pyramid return baseLength * baseWidth + 0.5 * baseLength * Math.sqrt(Math.pow(baseWidth / 2, 2) + Math.pow(height, 2)) + 0.5 * baseWidth * Math.sqrt(Math.pow(baseLength / 2, 2) + Math.pow(height, 2)); } @Override public double calculatePerimeter() { // Perimeter calculation for a 3D shape is not applicable return 0; } @Override public double calculateVolume() { return (1.0 / 3.0) * baseLength * baseWidth * height; } // Function to get input from the user public void getInput() { Scanner scanner = new Scanner(System.in); System.out.print("Enter the base length of the pyramid: "); this.baseLength = scanner.nextDouble(); System.out.print("Enter the base width of the pyramid: "); this.baseWidth = scanner.nextDouble(); System.out.print("Enter the height of the pyramid: "); this.height = scanner.nextDouble(); } }
samisafk/PIJ
Assignment 5/Pyramid.java
320
// Function to get input from the user
line_comment
en
false
283
8
320
8
335
8
320
8
365
8
false
false
false
false
false
true
235890_0
/** * Theatre class holds all database information * initialize on programming start up * * Singleton design to ensure only instance */ import java.util.*; public class Theatre { private static Theatre theatre; //showtime has time/name/screen private List<Movie> movies = new ArrayList<Movie>(); //order has orderid/ticketid/movie name/seat number/showtime time private List<Order> orders = new ArrayList<Order>(); private List<DiscountCode> discounts = new ArrayList<DiscountCode>(); private UserController loginserver; /** *deafult ctor */ public Theatre() { } /** * add items to run time arrays */ public void addMovie(Movie newMovie) {movies.add(newMovie);} public void addOrder(Order newOrder) {orders.add(newOrder);} public void addDiscount(DiscountCode newDiscount) {discounts.add(newDiscount);} /** *remove items from dynamic arrays */ public void removeOrder(int orderID) { for(int i = 0; i < orders.size(); i++) { if(orderID == orders.get(i).getOrderID()) { updateSeatmap(orders.get(i)); orders.remove(i); } } } public void removeDiscount(int discountCode) { for(int i = 0; i < discounts.size(); i++) { if(discountCode == discounts.get(i).getCode()) { discounts.remove(i); } } } /** * find items in dynamic arrays */ public Order findOrder(int orderID, String email) { for(int i = 0; i < orders.size(); i++) { if(orderID == orders.get(i).getOrderID() && email == orders.get(i).getEmail()) { return orders.get(i); } } return null; } public DiscountCode findDiscount(int discountCode) { for(int i = 0; i < discounts.size(); i++) { if(discountCode == discounts.get(i).getCode()) { return discounts.get(i); } } return null; } public Showtime findShowTime(int ID) { for(int i = 0; i < movies.size(); i++) { Movie checkMovie = movies.get(i); for(int j = 0; j < checkMovie.getShowtimes().size(); j++) { Showtime checkShowtime = checkMovie.getShowtime(j); if(checkShowtime.getID() == ID) { return checkShowtime; } } } return null; } /** *Singleton ctor */ private Theatre(int testIntRemoveLater) { MovieDatabase theatredb = new MovieDatabase(); movies = theatredb.readMovies(); orders = theatredb.readOrders(); discounts = theatredb.readDiscountCodes(); theatredb.setMaxOrderID(); theatredb.setMaxTicketID(); theatredb.setMaxShowtimeID(); theatredb.setMaxCodeCounter(); loginserver = UserController.getLoginInstance(); } //getters public static Theatre getTheatre() { if (theatre == null) { theatre = new Theatre(); } return theatre; } public List<Movie> getReleasedMovies(){ ArrayList<Movie> released = new ArrayList<Movie>(); for (Movie m : this.movies){ if(m.isReleased()){ released.add(m); } } return released; } public List<Movie> getEarlyMovies(){ ArrayList<Movie> early = new ArrayList<Movie>(); for(Movie m : this.movies){ if(m.isEarly()){ early.add(m); } } return early; } /** * Updated seatmap after order cancellation * */ public void updateSeatmap(Order order){ Movie movie = null; Showtime st = null; for(int i = 0; i < movies.size(); i++){ if(movies.get(i).getTitle().equals(order.getTickets().get(0).getMovieName())){ movie = movies.get(i); break; } } for(int i = 0; i < movie.getShowtimes().size(); i++){ if(order.getTickets().get(0).getshowtimeID() == movie.getShowtime(i).getID()){ st = movie.getShowtime(i); break; } } for(int i = 0; i < order.getTickets().size(); i++){ st.getSeats().cancelSeats(order.getTickets().get(i).getSeatColumn(), order.getTickets().get(i).getSeatRow()); } } }
Jgerbrandt/ENSF-480-Final-Project
Theatre.java
1,223
/** * Theatre class holds all database information * initialize on programming start up * * Singleton design to ensure only instance */
block_comment
en
false
1,028
26
1,223
35
1,310
31
1,223
35
1,529
34
false
false
false
false
false
true
237688_0
import java.util.Scanner; public class Nuclear{ public static boolean no_decay(double chance_of_decay){ return ( Math.random() > chance_of_decay); //This method will return "true" if the isotope survives and "false if it decays. //Decay occurs if the random number 0 to 1 is greater than chance. //The input "chance" is the probability of decay per iteration } public static void main(String[] args){ Scanner scan = new Scanner(System.in); int N; //set the initial number of atoms System.out.println( "input N, the initial number of atoms."); N = scan.nextInt(); int survive; // this is a temporary variable to count the number of survivors per iteration double prob; // this is the chance of decay process happening for an atom each iteration System.out.println( "input P, the probability of decay."); prob = scan.nextDouble(); int steps=0; StdDraw.setXscale( 0. , 8.0 / prob); StdDraw.setYscale(0. , (float) N ); while(N>0){ System.out.print( N + " "); StdDraw.point((double) steps , (float) N ); survive = 0; steps++; for(int i=0; i<N; i++){ if( no_decay( prob) ){ survive++; } } StdDraw.line( steps -1,N,steps,survive); N=survive; } System.out.print( "0"+ "\nThe number of time steps was " + steps + "\n"); } }
TaeyoungLeeJack/decay_sim
Nuclear.java
393
//This method will return "true" if the isotope survives and "false if it decays.
line_comment
en
false
363
21
393
22
439
19
393
22
466
23
false
false
false
false
false
true
237878_0
package cp213; import java.awt.Font; import java.math.*; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; /** * Stores a HashMap of MenuItem objects and the quantity of each MenuItem * ordered. Each MenuItem may appear only once in the HashMap. * * @author Vicky Sekhon * @author Abdul-Rahman Mawlood-Yunis * @author David Brown * @version 2023-09-06 */ public class Order implements Printable { public static final BigDecimal TAX_RATE = new BigDecimal(0.13); private static final String itemFormat = "%-20s %s @ $ %.2f = $ %.2f %n"; // your code here // create hash map (holds item and quantity) HashMap<MenuItem, Integer> items = new HashMap<>(); /** * Increments the quantity of a particular MenuItem in an Order with a new * quantity. If the MenuItem is not in the order, it is added. * * @param item The MenuItem to purchase - the HashMap key. * @param quantity The number of the MenuItem to purchase - the HashMap value. */ public void add(final MenuItem item, final int quantity) { // your code here // check if item already exists in order if (items.containsKey(item)) { this.update(item, quantity); } else { // quantity is greater than 0 if (quantity > 0) { items.put(item, quantity); // quantity is 0 } else { items.remove(item); } } } /** * Removes an item from an order entirely. * * @param item The MenuItem to completely remove. */ public void removeAll(final MenuItem item) { items.remove(item); } /** * Calculates the total value of all MenuItems and their quantities in the * HashMap. * * @return the total price for the MenuItems ordered. */ public BigDecimal getSubTotal() { // your code here BigDecimal subTotal = BigDecimal.ZERO; // iterate through the hash map for (Map.Entry<MenuItem, Integer> entry : items.entrySet()) { // run "get" to find the item name and based on that, do menuitem.getPrice() BigDecimal itemPrice = entry.getKey().getPrice(); // run "get" to find the item quantity int quantity = entry.getValue(); // multiply price x quantity and add it the running total subTotal = subTotal.add(itemPrice.multiply(BigDecimal.valueOf(quantity))); } return subTotal; } /** * Calculates and returns the total taxes to apply to the subtotal of all * MenuItems in the order. Tax rate is TAX_RATE. * * @return total taxes on all MenuItems */ public BigDecimal getTaxes() { // your code here BigDecimal tax = BigDecimal.ZERO; MathContext m = new MathContext(2); tax = this.getSubTotal().multiply(TAX_RATE).round(m); return tax; } /** * Calculates and returns the total price of all MenuItems order, including tax. * * @return total price */ public BigDecimal getTotal() { // your code here BigDecimal subTot = BigDecimal.ZERO; subTot = this.getSubTotal().add(this.getTaxes()); return subTot; } /* * Implements the Printable interface print method. Prints lines to a Graphics2D * object using the drawString method. Prints the current contents of the Order. */ @Override public int print(final Graphics graphics, final PageFormat pageFormat, final int pageIndex) throws PrinterException { int result = PAGE_EXISTS; if (pageIndex == 0) { final Graphics2D g2d = (Graphics2D) graphics; g2d.setFont(new Font("MONOSPACED", Font.PLAIN, 12)); g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); // Now we perform our rendering final String[] lines = this.toString().split("\n"); int y = 100; final int inc = 12; for (final String line : lines) { g2d.drawString(line, 100, y); y += inc; } } else { result = NO_SUCH_PAGE; } return result; } /** * Returns a String version of a receipt for all the MenuItems in the order. */ @Override public String toString() { // your code here String format = ""; for (Map.Entry<MenuItem, Integer> entry : items.entrySet()) { MenuItem menuItem = entry.getKey(); int quantity = entry.getValue(); String name = entry.getKey().getName(); BigDecimal price = entry.getKey().getPrice(); BigDecimal totalPrice = menuItem.getPrice().multiply(BigDecimal.valueOf(quantity)); // return formatted output containing details about customer order format += String.format(itemFormat, name, quantity, price, totalPrice); } // create payment section format += String.format("Subtotal: $%6.2f %n", this.getSubTotal()); format += String.format("Taxes: $%6.2f %n", this.getTaxes()); format += String.format("Total: $%6.2f %n", this.getTotal()); return format; } /** * Replaces the quantity of a particular MenuItem in an Order with a new * quantity. If the MenuItem is not in the order, it is added. If quantity is 0 * or negative, the MenuItem is removed from the Order. * * @param item The MenuItem to update * @param quantity The quantity to apply to item */ public void update(final MenuItem item, final int quantity) { // your code here if (quantity > 0) { int currentItemQuantity = items.get(item); // update quantity items.put(item, currentItemQuantity+quantity); } else { // remove item from hashmap items.remove(item); } } }
VickySekhon/cp213
GUI/Order.java
1,531
/** * Stores a HashMap of MenuItem objects and the quantity of each MenuItem * ordered. Each MenuItem may appear only once in the HashMap. * * @author Vicky Sekhon * @author Abdul-Rahman Mawlood-Yunis * @author David Brown * @version 2023-09-06 */
block_comment
en
false
1,387
73
1,531
81
1,677
74
1,531
81
1,829
86
false
false
false
false
false
true
238107_0
import java.io.*; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; import java.util.concurrent.Callable; public class CriminalData { Connection connection; public CriminalData(Connection connection){ this.connection = connection; } private void display(){ System.out.println("1. Add criminal Record "); System.out.println("2. Fetch Information of criminal"); System.out.println("3. Go back to main dashboard"); } private void fetchCriminalRecord(String cid){ // fetch information from table using connection try{ Statement stmt = connection.createStatement(); System.out.println("Fetching records with condition..."); String sql = "SELECT * FROM criminal WHERE criminal_id = '" + cid + "'"; ResultSet rs = stmt.executeQuery(sql); rs = stmt.executeQuery(sql); while(rs.next()){ //Display values System.out.print("ID: " + rs.getString("criminal_id")); System.out.print(", First Name: " + rs.getString("first_name")); System.out.print(", Last Name: " + rs.getString("last_name")); System.out.print(", Gender: " + rs.getString("gender")); System.out.print(", Age: " + rs.getString("age")); System.out.print(", Address: " + rs.getString("criminal_address")); System.out.println(", District: " + rs.getString("district")); } rs.close(); } catch(SQLException e){ System.err.println(e.getMessage()); } return; } private void addCriminalRecord(){ // add criminal Information in Criminal Table using Connection // add case information in Cases Table // use attributes for taking input Scanner sc = new Scanner(System.in); System.out.println("Enter Criminal ID :"); String criminal_id = sc.nextLine(); System.out.println("Enter First name :"); String first_name = sc.nextLine(); System.out.println("Enter Last name :"); String last_name = sc.nextLine(); System.out.println("Enter gender (M/F) :"); String gender = sc.nextLine(); System.out.println("Enter age :"); int age = sc.nextInt(); sc.nextLine(); System.out.println("Enter Criminal Address :"); String criminal_address = sc.nextLine(); System.out.println("Enter District :"); String district = sc.nextLine(); System.out.println("Enter Jail ID :"); int jailid = sc.nextInt(); System.out.println("Enter Case ID :"); int caseid = sc.nextInt(); System.out.println("Enter the suspect ID :"); int suspect_id = sc.nextInt(); try{ System.out.println("Inserting records into the table..."); String sql = "{CALL add_criminal(?,?,?,?,?,?,?,?,?)}"; CallableStatement cs = connection.prepareCall(sql); cs.setString(1, criminal_id); cs.setString(2, first_name); cs.setString(3, last_name); cs.setString(4, gender); cs.setInt(5, age); cs.setString(6, criminal_address); cs.setString(7, district); cs.setInt(8, caseid); cs.setInt(9, suspect_id); cs.execute(); sql = "{CALL add_jailLog(?,?)}"; cs = connection.prepareCall(sql); cs.setInt(1, jailid); cs.setString(2, criminal_id); cs.execute(); System.out.println("Inserted record into the table..."); } catch(SQLException e){ System.err.println(e.getMessage()); } // sc.close(); return; // officer-in-charge must exist // case must be filed already // verdict in courtHearing must be } public void runClass(){ Scanner cin = new Scanner(System.in); while(true){ display(); int option = cin.nextInt(); cin.nextLine(); if(option == 1){ addCriminalRecord(); }else if(option == 2){ System.out.println("Enter criminal id : "); // cin.nextLine(); String criminal_id = cin.nextLine(); fetchCriminalRecord(criminal_id); }else if(option == 3){ System.out.println("Going back to Main dashboard!!"); break; }else{ System.out.println("Wrong option selected"); } } // cin.close(); } }
AdiG-iitrpr/CriminalRecordManagementSystem
java/src/CriminalData.java
1,149
// fetch information from table using connection
line_comment
en
false
927
8
1,149
8
1,192
8
1,149
8
1,310
8
false
false
false
false
false
true
238456_10
package clone.gene; import java.util.ArrayList; import java.util.Random; public class Projectv0 { private Random rand = new Random(); private ArrayList<Entity> generation = new ArrayList<>(); private ArrayList<ArrayList<Entity>> entities = new ArrayList<>(); private final int MUTFREQ = 20; // mutation frequency, the lower, the more frequent public void start() { Entity LUCA = new Entity(1, 1); //last universal common ancestor generation.add(LUCA); entities.add(generation); } public void procreate() { Entity d1; // daughter Entity d2; generation = new ArrayList<>(); for (Entity e : entities.get(entities.size() - 1)) { // last generation if (!e.isSexuallyReproducing()) { d1 = new Entity(e.getSequence()); d2 = new Entity(e.getSequence()); d1.mutate((generation.size() + 1) * MUTFREQ); // with each generation, entities become better at not mutating d2.mutate((generation.size() + 1) * MUTFREQ); if(d1.isViable()){ generation.add(d1); } if(d2.isViable()){ generation.add(d2); } } else { // mate(e, findMate(e)); } } entities.add(generation); } private Entity findMate(Entity e) { return null; } public Entity mate(Entity parent1, Entity parent2) { return null; } public void display(){ for(int i = 0; i < entities.size(); i++){ System.out.println("Generation " + (i + 1) + ":"); for(Entity e : entities.get(i)){ e.display(); } } } public static void main(String[] args) { Projectv0 p = new Projectv0(); p.start(); for(int i = 0; i < 4; i++){ p.procreate(); } p.display(); //DNA dna = new DNA(1, 1); //dna.addChromosome(); //dna.addPloid(); //dna.display(); } } class Entity { private Random rand = new Random(); private final int CHROMSMOD = 2; // chromosome number increase frequency modifier (1/x) private final int PLOIDMOD = 3; //ploidy number increase frequency modifier (1/x) public Entity(int chromosomes, int homologuous) { if (chromosomes == 0 || homologuous == 0) { throw new IllegalArgumentException("Cannot have 0 chromosomes"); } dna = new DNA(chromosomes, homologuous); this.chromosomes = chromosomes; this.homologuous = homologuous; setReproduction(); } public boolean isViable() { if(dna.getGeneNo() > 0){ return true; } else { return false; } } public void mutate() { if(rand.nextBoolean()){ dna.mutateAdd(); } if(rand.nextBoolean()){ dna.mutateDelete(); } set(); } public void mutate(int freq) { if(rand.nextBoolean()){ dna.mutateAdd(freq); } if(rand.nextBoolean()){ dna.mutateDelete(freq); } if(rand.nextInt(CHROMSMOD * freq * dna.size()) == 0){ //less and less frequent dna.addChromosome(); } if(rand.nextInt(PLOIDMOD * freq * dna.ploidy()) == 0){ dna.addPloid(); } set(); } public void display() { dna.display(); } public Entity(ArrayList<ArrayList<ArrayList<Character>>> sequence) { dna = new DNA(sequence); } private void setReproduction() { if (homologuous == 1 && chromosomes == 1) { // prokaryotes divide sexualReproduction = false; } else { sexualReproduction = true; } } public boolean isSexuallyReproducing() { return sexualReproduction; } public void setSexualReproduction(boolean sexualReproduction) { this.sexualReproduction = sexualReproduction; } public int getChromosomes() { return chromosomes; } public int getHomologuous() { return homologuous; } public void set(){ dna.set(); } public ArrayList<ArrayList<ArrayList<Character>>> getSequence() { return dna.getSequence(); } private DNA dna; private boolean sexualReproduction; private int chromosomes; private int homologuous; }
Rallade/geneclone
src/clone/gene/Projectv0.java
1,273
// chromosome number increase frequency modifier (1/x)
line_comment
en
false
1,030
10
1,273
11
1,212
11
1,273
11
1,510
14
false
false
false
false
false
true
239679_12
package Model; /** * Supplied class Part.java */ /** * * @author Michael Brown */ public abstract class Part { private int id; private String name; private double price; private int stock; private int min; private int max; public Part(int id, String name, double price, int stock, int min, int max) { this.id = id; this.name = name; this.price = price; this.stock = stock; this.min = min; this.max = max; } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the price */ public double getPrice() { return price; } /** * @param price the price to set */ public void setPrice(double price) { this.price = price; } /** * @return the stock */ public int getStock() { return stock; } /** * @param stock the stock to set */ public void setStock(int stock) { this.stock = stock; } /** * @return the min */ public int getMin() { return min; } /** * @param min the min to set */ public void setMin(int min) { this.min = min; } /** * @return the max */ public int getMax() { return max; } /** * @param max the max to set */ public void setMax(int max) { this.max = max; } }
mabrownjr/WGU-C482
Model/Part.java
463
/** * @return the max */
block_comment
en
false
441
10
463
9
586
12
463
9
612
13
false
false
false
false
false
true
239759_0
package ast; import compiler.Failure; /** Represents a linked list of location environments, with each entry * documenting the location of a particular variable in memory. */ public abstract class LocEnv { protected String name; private LocEnv next; /** Default constructor. */ public LocEnv(String name, LocEnv next) { this.name = name; this.next = next; } /** Return the variable name for this environment entry. */ public String getName() { return name; } /** Return the tail of this environment. */ public LocEnv next() { return next; } /** Search this environment for a the occurence of a given variable. * We assume that a previous static analysis has already identified * and eliminate references to unbound variables. */ public LocEnv find(String name) { for (LocEnv env=this; env!=null; env=env.next) { if (name.equals(env.name)) { return env; } } throw new Error("Could not find environment entry for " + name); } /** Return a string that describes the location associated with * this enviroment entry. */ public abstract String loc32(Assembly a); }
dcobbley/CS322AsmGen
ast/LocEnv.java
283
/** Represents a linked list of location environments, with each entry * documenting the location of a particular variable in memory. */
block_comment
en
false
266
26
283
28
310
28
283
28
322
30
false
false
false
false
false
true
240228_29
package application.offer; import java.io.Serializable; import java.time.LocalDate; import java.util.*; import application.App; import application.opinion.*; import application.users.RegisteredUser; import exceptions.*; import es.uam.eps.padsof.telecard.*; /** * This class stores the basic data needed for an Offer. It is abstract, as it * is used to create HolidayOffer and LivingOffer * * @author Miguel Arconada ([email protected]) y Alberto * Gonzalez ([email protected]) * */ public abstract class Offer implements Serializable{ /** * ID needed for serialization */ private static final long serialVersionUID = -8222183165622361142L; /** * Starting date of the offer */ private LocalDate startingDate; /** * Price of the offer */ private Double price; /** * Deposit to be paid for the offer */ private Double deposit; /** * Description of the offer */ private String description; /** * Status in which the offer is */ private OfferStatus status; /** * House in which the offer takes place */ private House offeredHouse; /** * All the opinions about the offer */ private List<Opinion> opinions; /** * List of users that cannot book this offer, because they did not pay the reservation within 5 days */ private List<RegisteredUser> restrictedUsers; /** * Constructor of the class Offer * * @param startingDate Starting date of the offer * @param price Price of the offer * @param deposit Deposit to be paid for the offer * @param description Description of the offer * @param offeredHouse House in which the offer takes place */ public Offer(LocalDate startingDate, Double price, Double deposit, String description, House offeredHouse) { this.startingDate = startingDate; this.price = price; this.deposit = deposit; this.description = description; this.status = OfferStatus.PENDING_FOR_APPROVAL; this.offeredHouse = offeredHouse; this.opinions = new ArrayList<Opinion>(); this.restrictedUsers = new ArrayList<RegisteredUser>(); } /** * Getter method for the offeredHouse attribute * * @return House of the offer */ public House getHouse() { return this.offeredHouse; } /** * Getter method for the status attribute * * @return Status of the offer */ public OfferStatus getStatus() { return this.status; } /** * Getter method for the startingDate attribute * * @return Starting date of the offer */ public LocalDate getDate() { return this.startingDate; } /** * Getter method for all the comments * @return List of comments */ public List<Opinion> getComments() { List<Opinion> aux = new ArrayList<Opinion>(); for(Opinion o: opinions) { if (o.getClass() == Comment.class) { aux.add(o); } } return aux; } /** * Getter method for the description attribute * * @return Description of the offer */ public String getDescription() { return description; } /** * Getter method for the replies attribute * * @return Opinions of the offer */ public List<Opinion> getOpinions() { return this.opinions; } /** * Getter method for the restrictedUsers attribute * @return List of restricted users */ public List<RegisteredUser> getRestrictedUsers() { return restrictedUsers; } /** * Method used to modify the starting date of the offer * * @param startingDate New starting date of the offer * @throws NotTheOwnerException When the user trying to modify the offer is not the owner of the house * @throws InvalidOfferStatusException When you try to modify a offer that is not pending for changes */ public void modifyOffer(LocalDate startingDate) throws InvalidOfferStatusException, NotTheOwnerException{ if(!this.status.equals(OfferStatus.PENDING_FOR_CHANGES)) { throw new InvalidOfferStatusException(this.status, "modifyOffer"); } else if(!App.getLoggedUser().equals(this.offeredHouse.getHost())) { throw new NotTheOwnerException(App.getLoggedUser()); } else { this.startingDate = startingDate; } } /** * Method used to modify the price and deposit of the offer * * @param price New price of the offer * @param deposit New deposit of the offer * @throws NotTheOwnerException When the user trying to modify the offer is not the owner of the house * @throws InvalidOfferStatusException When you try to modify a offer that is not pending for changes */ public void modifyOffer(Double price, Double deposit) throws InvalidOfferStatusException, NotTheOwnerException { if(!this.status.equals(OfferStatus.PENDING_FOR_CHANGES)) { throw new InvalidOfferStatusException(this.status, "modifyOffer"); } else if(!App.getLoggedUser().equals(this.offeredHouse.getHost())) { throw new NotTheOwnerException(App.getLoggedUser()); } else { this.price = price; this.deposit = deposit; } } /** * Method used to modify the description date of the offer * * @param description New description of the offer * @throws NotTheOwnerException When the user trying to modify the offer is not the owner of the house * @throws InvalidOfferStatusException When you try to modify a offer that is not pending for changes */ public void modifyOffer(String description) throws InvalidOfferStatusException, NotTheOwnerException { if(!this.status.equals(OfferStatus.PENDING_FOR_CHANGES)) { throw new InvalidOfferStatusException(this.status, "modifyOffer"); } else if(!App.getLoggedUser().equals(this.offeredHouse.getHost())) { throw new NotTheOwnerException(App.getLoggedUser()); } else { this.description = description; } } /** * Method used to modify the status of the offer * * @param status New status of the offer */ public void modifyOffer(OfferStatus status){ this.status = status; } /** * Method used to pay for an offer * * @throws NoUserLoggedException When no user is logged in the app * @throws CouldNotPayHostException When the system could not pay the host * @throws InvalidCardNumberException When the card number of the guest is not 16 digits long */ public void payOffer() throws NoUserLoggedException, CouldNotPayHostException, InvalidCardNumberException { Double amount = this.getAmount(); String subject = "------------"; RegisteredUser user = App.getLoggedUser(); if (user == null) { throw new NoUserLoggedException(); } String ccard = user.getCreditCard(); try { TeleChargeAndPaySystem.charge(ccard, subject, amount); } catch (InvalidCardNumberException e) { throw e; } catch (FailedInternetConnectionException e) { System.out.println(e); } catch (OrderRejectedException e) { System.out.println(e); } modifyOffer(OfferStatus.PAID); this.payHost(); } /** * Method used to pay the host what has been paid by the client minus the system * fees * * @throws CouldNotPayHostException When the app could not pay the host (invalid card number) */ public abstract void payHost() throws CouldNotPayHostException; /** * Method used to add an opinion about the offer * * @param opinion Comment about the offer * @throws NoUserLoggedException When a non-logged user tries to comment an offer */ public void rateOffer(String opinion) throws NoUserLoggedException { Opinion o = new Comment(opinion); if(App.getLoggedUser() == null) { throw new NoUserLoggedException(); } this.opinions.add(o); } /** * Method used to add a rating to the offer * * @param rating Rating of the offer * @throws NoUserLoggedException When a non-logged user tries to rate a offer */ public void rateOffer(Double rating) throws NoUserLoggedException { Opinion o = new Rating(rating); if(App.getLoggedUser() == null) { throw new NoUserLoggedException(); } this.opinions.add(o); } /** * Method that calculates the average rating of the offer * * @return The average rating of the offer. Calculated from the rating. */ public Double getAvgRating() { Double rating = 0.0; int amount = 0; for (Opinion o : this.opinions) { if (o.getClass() == Rating.class) { rating += ((Rating) o).getRating(); amount++; } } if(amount == 0) { return 0.0; } return rating / amount; } /** * Method that calculates the amount to be paid * * @return Amount to be paid */ public Double getAmount() { return this.price + this.deposit; } /** * Method that returns the type of the offer. It is abstract as an Offer has no * type unless it is from a subclass * * @return Type of the offer */ public abstract OfferType getType(); @Override /** * Method that returns all the information stored in an object of the class * Offer in a printable and readable format. It prints the data in common * amongst all the types of offers * * @return Information stored in the Offer in a printable format */ public String toString() { String string = ""; string += "Offer for the house in " + this.getHouse().getZipCode() + " (" + this.getHouse().getCity() + ")"; string += "\n Description: " + this.description; string += "\nStatus: " + this.status; string += "\nPrice: " + this.price; string += "\nDeposit: " + this.deposit; string += "\nStarting date: " + this.startingDate; return string; } }
miguelarman/PADSOF_2018
Assignment3/src/application/offer/Offer.java
2,584
/** * Method that returns all the information stored in an object of the class * Offer in a printable and readable format. It prints the data in common * amongst all the types of offers * * @return Information stored in the Offer in a printable format */
block_comment
en
false
2,375
62
2,584
60
2,734
64
2,584
60
3,155
68
false
false
false
false
false
true
240625_1
package edu.hawaii.ics621; import java.util.ArrayList; import java.util.List; import java.util.Random; import edu.hawaii.ics621.algorithms.KMeans; public class Main { public static final int INPUT_SIZE = 1000; public static final int CLUSTERS = 5; /** * @param args */ public static void main(String[] args) { // Generate a list of items. List<DoublePoint> inputs = new ArrayList<DoublePoint>(); Random generator = new Random(); for (int i = 0; i < 100; i++) { inputs.add(new DoublePoint(generator.nextDouble(), generator.nextDouble())); } KMeans clusterer = new KMeans(); System.out.println("Clustering items"); List<DoublePoint> results = clusterer.cluster(inputs, CLUSTERS); DoublePoint point; for (int i = 0; i < results.size(); i++) { point = results.get(i); System.out.println("Cluster " + (i + 1) + ": " + point.toString()); } } }
keokilee/kmeans-hadoop
src/edu/hawaii/ics621/Main.java
281
// Generate a list of items.
line_comment
en
false
242
7
281
7
298
7
281
7
322
8
false
false
false
false
false
true
241647_3
import java.util.Scanner; /** * * @author */ public class TennisKata { private int player1Points = 0; private int player2Points = 0; private final int FOUR = 4; private final int THREE = 3; private final int TWO = 2; private final int ONE = 1; private final String PLAYER_1 = "Player 1"; private final String PLAYER_2 = "Player 2"; private Scanner scanner; public static void main(String args[]) { TennisKata kata = new TennisKata(); kata.getPlayerPoints(); System.out.println(kata.processPlayerPoints()); } /** * Takes input points for Player 1 and Player 2. */ private void getPlayerPoints() { scanner = new Scanner(System.in); getPlayer1Points(); getPlayer2Points(); } /** * Takes and validates input for Player 1 points. */ private void getPlayer1Points() { try { System.out.println("Enter player 1 points:"); player1Points = Integer.parseInt(scanner.next()); } catch (NumberFormatException e) { System.out.println("Please enter valid points"); getPlayer1Points(); } } /** * Takes and validates input for Player 2 points. */ private void getPlayer2Points() { try { System.out.println("Enter player 2 points:"); player2Points = Integer.parseInt(scanner.next()); } catch (NumberFormatException e) { System.out.println("Please enter valid points"); getPlayer2Points(); } } /** * Processes the points depending upon conditions. * * @return String value stating the result. */ private String processPlayerPoints() { String result = getWinnerIfAvailable(); if (result != null) { return (result + " wins"); } result = getDeuceIfAvailable(); if (result != null) { return result; } result = getAdvantagePlayerIfAvailable(); if (result != null) { return (result + " has advantage"); } if (arePointsEqual()) { return (getPointsValue(player1Points) + " all"); } return (getPointsValue(player1Points) + "," + getPointsValue(player2Points)); } /** * Returns winner player. If a player has at least 4 points and leads by at * least 2 points then he is the winner. * * @return winner player. */ private String getWinnerIfAvailable() { if ((player1Points >= FOUR) && (player1Points >= (player2Points + TWO))) { return PLAYER_1; } if ((player2Points >= FOUR) && (player2Points >= (player1Points + TWO))) { return PLAYER_2; } return null; } /** * Returns player with advantage. If both player has at least 3 points and a * player is leading with 1 point then that player has advantage. * * @return player with advantage. */ private String getAdvantagePlayerIfAvailable() { if (player1Points >= THREE && player2Points >= THREE) { if (player1Points == player2Points + ONE) { return PLAYER_1; } if (player2Points == player1Points + ONE) { return PLAYER_2; } } return null; } /** * Returns deuce if both players have at least 3 points and have same points * * @return deuce based on condition. */ private String getDeuceIfAvailable() { if (player1Points >= THREE && arePointsEqual()) { return "Deuce"; } return null; } /** * Returns true if both players have same points. * * @return true if both players have same points. */ private boolean arePointsEqual() { return player1Points == player2Points; } /** * Returns points value in Tennis terminology. * * @param points * @return points value in tennis terminology. */ private String getPointsValue(int points) { switch (points) { case 0: return "Love"; case ONE: return "Fifteen"; case TWO: return "Thirty"; case THREE: return "Forty"; default: System.out.println("Entered value is not legal."); } return null; } }
onkariwaligunje/2019_DEV_018
TennisKata.java
1,047
/** * Takes and validates input for Player 2 points. */
block_comment
en
false
976
15
1,047
15
1,179
17
1,047
15
1,282
20
false
false
false
false
false
true
243916_5
import java.util.Arrays; /** * The Straight Class is a subclass of the Hand Class and implements Hand_Interface. * It implements isValid() and getType() and overrides getTopCard() method from the Hand Class. * * @author BHATIA Divtej Singh ( UID : 3035832438 ) * */ public class Straight extends Hand implements Hand_Interface{ // Default Serial Version ID private static final long serialVersionUID = 1L; /** * Constructor for Straight Type. * * @param player The specified CardGamePlayer object * @param cards The specified list of cards (CardList object) */ public Straight(CardGamePlayer player, CardList cards) { super(player, cards); } /** * A method for retrieving the top card of this hand. * * @return Card object which is the Top Card of the given Hand */ public Card getTopCard() { // Storing the ranks of all cards in an array int[] ranks = new int[5]; for (int i = 0 ; i < 5; i ++) { int k = this.getCard(i).getRank(); if (k == 0) { // Case of Ace ranks[i] = 13; //second highest rank } else if (k == 1 ) {// Case of 2 ranks[i] = 14; //highest rank } else { ranks[i] = k; } } // Finding highest rank int highest_rank = ranks[0]; for (int i = 0 ;i < 5; i ++) { // Looping the ranks array if (ranks[i] > highest_rank) { highest_rank = ranks[i]; } } // Return Card with highest rank for (int i = 0 ; i < 5 ; i ++) { if (highest_rank == ranks[i]) { return (this.getCard(i)); } } return null; } /** * This method is implemented from the Hand_Interface * * @return True is the given hand is a Valid straight, False of it is not A striaght type. * */ public boolean isValid() { // All straights should be made of 5 cards. if (this.size() != 5) { return false; } // Storing the ranks of all cards in an array int[] ranks = new int[5]; for (int i = 0 ; i < 5; i ++) { int k = this.getCard(i).getRank(); if (k == 0) { // Case of Ace ranks[i] = 13; //second highest rank } else if (k == 1 ) {// Case of 2 ranks[i] = 14; //highest rank } else { ranks[i] = k; } } //ranks stores all //sorting ranks array Arrays.sort(ranks); for(int i = 1 ; i < 5; i ++) { if(ranks[i] != ranks[i-1] + 1) { // successive rank should be current rank + 1 return false ; } } return true; } /** * This method is implemented from the Hand_Interface * * @return String Containing the type of hand. * */ public String getType() { return new String("Straight"); } }
BhatiaDivtej/BigTwo-A-Network-Card-Game
Straight.java
877
// Case of Ace
line_comment
en
false
817
4
877
5
912
4
877
5
1,079
5
false
false
false
false
false
true
244231_3
//Raja Hammad Mehmood // This program runs the Pig game. import java.util.Scanner; public class Pig { public static void main ( String[] args ) { Scanner scanner = new Scanner(System.in); System.out.println("enter how many players you want to play with"); int players= scanner.nextInt();// number of players while(players <2) { // checking in valid number System.out.println("enter at least 2 players"); players= scanner.nextInt(); } scanner.nextLine(); int[] noofplayers = new int[players];// array for the number of players int[] sum = new int[players];// array for sum of scores int roll; boolean flag =false; boolean condition=true; String opinion; for (int x=0;; x++) { //runs for every player (x is the loop controlling variable) condition=true; if (x==(players)) { // goes back to the first player if the final player has done the turn x=0; } while (condition=true) { System.out.println("player "+(x+1)+" do you want to roll?"); opinion=scanner.nextLine();//saves if user wants to roll again or not if (opinion.equalsIgnoreCase("yes")) { roll=(int)(Math.random()*6)+1; System.out.println("player "+(x+1)+" your roll is "+roll); if (roll==1) { System.out.println("end of turn as you rolled 1"); break; } else { sum[x]=sum[x]+roll; if (sum[x]>=100) { System.out.println("player "+ (x+1) + " wins with "+ sum[x] + " points !"); flag=true; break; } } System.out.println("Current scores:"); for (int i=0; i<noofplayers.length ; i++) { System.out.println("player "+ (i+1)+" :" + sum[i]); } } else { System.out.println("end of turn"); break; } } if (flag==true) { break; } } } }
rajahammad086/Lab5
Pig.java
520
// checking in valid number
line_comment
en
false
473
5
520
5
558
5
520
5
650
5
false
false
false
false
false
true
245362_1
/** A non-equilibrium Rock-Paper-Scissors player. * * @author RR */ public class MixedBot implements RoShamBot { /** Returns an action according to the mixed strategy (0.5, 0.5, 0.0). * * @param lastOpponentMove the action that was played by the opponent on * the last round (this is disregarded). * @return the next action to play. */ public Action getNextMove(Action lastOpponentMove) { double coinFlip = Math.random(); if (coinFlip <= 0.5) return Action.ROCK; else return Action.PAPER; } }
alhart2015/RockPaperScissors
MixedBot.java
163
/** Returns an action according to the mixed strategy (0.5, 0.5, 0.0). * * @param lastOpponentMove the action that was played by the opponent on * the last round (this is disregarded). * @return the next action to play. */
block_comment
en
false
158
69
163
68
172
71
163
68
199
77
false
false
false
false
false
true
245963_3
public class User { private String username; private String acctType; private double credits; public String getUsername() { return username; } public String getAcctType() { return acctType; } public double getCredits() { return credits; } public void setCredits(double credits) { this.credits = credits; } public User(){} public User(String uName, String aType, double creds){ this.username = uName; this.acctType = aType; this.credits = creds; } /** * parse input string to create user object * @param input: String * @return : User object */ public User(String input){ // parse line from file into object // of form UUUUUUUUUUUUUUU_TT_CCCCCCCCC // get rid of spaces on right this.username = input.substring(0, 15).trim(); this.acctType = input.substring(16, 18); this.credits = Double.parseDouble(input.substring(19)); } /** * format object into for appropriate for writing to fileuserName * @param : None * @return : String representation of User to be written to file */ public String stringify(){ return (String.format("%-15s", this.username) + ' ' + this.acctType + ' ' + String.format("%09.2f", this.credits)); } }
aleemalibhai/Auction_App_Backend
src/User.java
337
// get rid of spaces on right
line_comment
en
false
328
7
337
7
378
7
337
7
420
7
false
false
false
false
false
true
246698_1
import java.io.File; import java.io.IOException; import java.util.InputMismatchException; import java.util.Locale; import java.util.Scanner; import java.io.FileWriter; import java.io.PrintWriter; public class CloudData { Vector[][][] advection; // in-plane regular grid of wind vectors, that evolve over time float[][][] convection; // vertical air movement strength, that evolves over time int[][][] classification; // cloud type per grid point, evolving over time int dimx, dimy, dimt; // data dimensions Vector averageWind = new Vector(); // overall number of elements in the timeline grids int dim() { return dimt * dimx * dimy; } // convert linear position into 3D location in simulation grid void locate(int pos, int[] ind) { ind[0] = (int) pos / (dimx * dimy); // t ind[1] = (pos % (dimx * dimy)) / dimy; // x ind[2] = pos % (dimy); // y } void classify() { for (int t = 0; t < dimt; t++) { for (int x = 0; x < dimx; x++) { for (int y = 0; y < dimy; y++) { float avex=0; float avey=0; int dividor = 0; //go through all 8 surrounding elements for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { //if element is less than 0 or more than dimension ignore it if (!((x+i) < 0) && !((x+i) > dimx-1)) { if(!((y+j) < 0) && !((y+j) > dimy-1)){ avex += advection[t][x + i][y + j].x; avey += advection[t][x + i][y + j].y; dividor++; //add to averages and keep track of number of elements added } } } } //calculate actual averages avex=avex/dividor; avey=avey/dividor; //find magnitude double ave_magnitude = Math.sqrt(avex*avex + avey*avey); //add to classification using criteria if(Math.abs(convection[t][x][y])>ave_magnitude) { classification[t][x][y]=0; } else if(ave_magnitude>0.2 && (ave_magnitude >= Math.abs(convection[t][x][y]))) { classification[t][x][y]=1; } else { classification[t][x][y]=2; } } } } } void findAve() { averageWind = new Vector(); for (int t = 0; t < dimt; t++){ for (int x = 0; x < dimx; x++){ for (int y = 0; y < dimy; y++) { averageWind.x += advection[t][x][y].x; averageWind.y += advection[t][x][y].y; } } } averageWind.x = averageWind.x/dim(); averageWind.y = averageWind.y/dim(); } // read cloud simulation data from file void readData(String fileName){ try{ Scanner sc = new Scanner(new File(fileName), "UTF-8"); // input grid dimensions and simulation duration in timesteps dimt = sc.nextInt(); dimx = sc.nextInt(); dimy = sc.nextInt(); //System.out.println(dimt+" "+dimx + " "+dimy); // initialize and load advection (wind direction and strength) and convection advection = new Vector[dimt][dimx][dimy]; convection = new float[dimt][dimx][dimy]; for(int t = 0; t < dimt; t++) for(int x = 0; x < dimx; x++) for(int y = 0; y < dimy; y++){ advection[t][x][y] = new Vector(); advection[t][x][y].x = Float.parseFloat(sc.next()); advection[t][x][y].y = Float.parseFloat(sc.next()); convection[t][x][y] = Float.parseFloat(sc.next()); //System.out.println(advection[t][x][y].x+" "+advection[t][x][y].y + " "+convection[t][x][y]); } classification = new int[dimt][dimx][dimy]; sc.close(); } catch (IOException e){ System.out.println("Unable to open input file "+fileName); e.printStackTrace(); } catch (InputMismatchException e){ System.out.println("Malformed input file "+fileName); e.printStackTrace(); } } // write classification output to file void writeData(String fileName, Vector wind){ try{ FileWriter fileWriter = new FileWriter(fileName); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.printf("%d %d %d\n", dimt, dimx, dimy); printWriter.printf(Locale.US,"%f %f\n", wind.x, wind.y); for(int t = 0; t < dimt; t++){ for(int x = 0; x < dimx; x++){ for(int y = 0; y < dimy; y++){ printWriter.printf("%d ", classification[t][x][y]); } } printWriter.printf("\n"); } printWriter.close(); } catch (IOException e){ System.out.println("Unable to open output file "+fileName); e.printStackTrace(); } } }
Lawrence-Godfrey/Weather-Prediction-using-threading
src/CloudData.java
1,540
// vertical air movement strength, that evolves over time
line_comment
en
false
1,346
11
1,540
13
1,586
11
1,540
13
2,036
12
false
false
false
false
false
true
247603_3
package chapter_fifteen.samples; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.shape.Polygon; import javafx.scene.Group; import javafx.scene.layout.BorderPane; import javafx.scene.input.*; import javafx.geometry.Point2D; import java.util.*; /** * Listing 15.19 USMap.java */ public class USMap extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { MapPane map = new MapPane(); Scene scene = new Scene(map, 1200, 800); primaryStage.setTitle("USMap"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage map.setOnKeyPressed(e -> { if (e.getCode() == KeyCode.UP) { map.enlarge(); // Enlarge the map } else if (e.getCode() == KeyCode.DOWN) { map.shrink(); // SHrink the map } }); map.requestFocus(); } class MapPane extends BorderPane { private Group group = new Group(); MapPane() { // Load coordinates from a file ArrayList<ArrayList<Point2D>> points = getPoints(); // Add points to the polygon list for (int i = 0; i < points.size(); i++) { Polygon polygon = new Polygon(); // Add points to the polygon list for (int j = 0; j < points.get(i).size(); j++) polygon.getPoints().addAll(points.get(i).get(j).getX(), -points.get(i).get(j).getY()); polygon.setFill(Color.WHITE); polygon.setStroke(Color.BLACK); polygon.setStrokeWidth(1 / 14.0); polygon.setOnMouseClicked(e -> { if (e.getButton() == MouseButton.PRIMARY) { polygon.setFill(Color.RED); } else if (e.getButton() == MouseButton.SECONDARY) { polygon.setFill(Color.BLUE); } else { polygon.setFill(Color.WHITE); } }); group.getChildren().add(polygon); } group.setScaleX(14); group.setScaleY(14); this.setCenter(group); } public void enlarge() { group.setScaleX(1.1 * group.getScaleX()); group.setScaleY(1.1 * group.getScaleY()); } public void shrink() { group.setScaleX(0.9 * group.getScaleX()); group.setScaleY(0.9 * group.getScaleY()); } private ArrayList<ArrayList<Point2D>> getPoints() { ArrayList<ArrayList<Point2D>> points = new ArrayList<>(); try (Scanner input = new Scanner(new java.net.URL( "https://liveexample.pearsoncmg.com/data/usmap.txt") .openStream())) { while (input.hasNext()) { String s = input.nextLine(); if (Character.isAlphabetic(s.charAt(0))) { points.add(new ArrayList<>()); // For a new state } else { Scanner scanAString = new Scanner(s); // Scan one point double y = scanAString.nextDouble(); double x = scanAString.nextDouble(); points.get(points.size() - 1).add(new Point2D(x, y)); } } } catch (Exception ex) { ex.printStackTrace(); } return points; } } }
sharaf-qeshta/Introduction-to-Java-Programming-and-Data-Structures-Comprehensive-Version-Eleventh-Edition-Global-
Chapter_15/samples/USMap.java
898
// Place the scene in the stage
line_comment
en
false
765
7
898
7
973
7
898
7
1,087
7
false
false
false
false
false
true
247676_1
package sample; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.scene.layout.HBox; import javafx.scene.layout.BorderPane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; public class ControlCircle extends Application { private CirclePane circlePane = new CirclePane(); @Override // Override the start method in the Application class public void start(Stage primaryStage) { // Hold two buttons in an HBox HBox hBox = new HBox(); hBox.setSpacing(10); hBox.setAlignment(Pos.CENTER); Button btEnlarge = new Button("Enlarge"); Button btShrink = new Button("Shrink"); hBox.getChildren().add(btEnlarge); hBox.getChildren().add(btShrink); // Create and register the handler btEnlarge.setOnAction(new EnlargeHandler()); BorderPane borderPane = new BorderPane(); borderPane.setCenter(circlePane); borderPane.setBottom(hBox); BorderPane.setAlignment(hBox, Pos.CENTER); // Create a scene and place it in the stage Scene scene = new Scene(borderPane, 200, 150); primaryStage.setTitle("ControlCircle"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } class EnlargeHandler implements EventHandler<ActionEvent> { @Override // Override the handle method public void handle(ActionEvent e) { circlePane.enlarge(); } } /** * The main method is only needed for the IDE with limited * JavaFX support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } class CirclePane extends StackPane { private Circle circle = new Circle(50); public CirclePane() { getChildren().add(circle); circle.setStroke(Color.BLACK); circle.setFill(Color.WHITE); } public void enlarge() { circle.setRadius(circle.getRadius() + 2); } public void shrink() { circle.setRadius(circle.getRadius() > 2 ? circle.getRadius() - 2 : circle.getRadius()); } }
ashishrsai/Intermediate-Programming-Lab-Solutions
Week 9/ControlCircle.java
590
// Hold two buttons in an HBox
line_comment
en
false
497
8
590
8
621
8
590
8
684
8
false
false
false
false
false
true
248009_0
public class square extends rectangle { // method specific to our square shape public double measure; public square(double measure) { super(measure, measure); } public int getSides() { sides = 4; return sides; } }
kaneclev/CS219
square.java
70
// method specific to our square shape
line_comment
en
false
59
7
70
7
76
7
70
7
87
7
false
false
false
false
false
true
248577_7
import java.util.*; public abstract class FSA implements Decider { /* * A Finite State Automaton (FSA) is a kind of decider. * Its input is always a string, and it either accepts or rejects that string. * We're making this an abstract class for now (where not all parts are defined) * because there are many different kinds of finite state automata. So far we've * only looked at the simplest kind, but we'll be looking at more complex ones for * the next homework assignment. */ public Set<String> states; // Q public Map<Tuple,String> delta; // \delta, this map's keys are state/character pairs, the values are states. public String start; // q_0 public Set<String> finals; // F public Set<Character> alphabet; // \Sigma public boolean decide(String s){ // run the machine on the string and accept/reject it. boolean accept = reset(); accept = finals.contains(start); for(int i = 0; i < s.length(); i++){ accept = step(s.charAt(i)); } reset() return accept; } public abstract boolean step(char c); // advance one transition public abstract boolean reset(); // return to start state to begin another input public abstract void toDot(); // give a dot representation of the automaton for visualization. };
zb3qk/CompTheoryHW3
Java/FSA.java
321
// advance one transition
line_comment
en
false
297
4
321
4
336
4
321
4
353
4
false
false
false
false
false
true
3668_0
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; class Result { /* * Complete the 'diagonalDifference' function below. * * The function is expected to return an INTEGER. * The function accepts 2D_INTEGER_ARRAY arr as parameter. */ public static int diagonalDifference(List<List<Integer>> arr) { int a = 0, b = 0; for(int i = 0; i < arr.size(); i++){ for(int j = 0; j < arr.get(i).size(); j++){ if(i == j){ a += arr.get(i).get(j); } if((i + j) == (arr.size() - 1)){ b += arr.get(i).get(j); } } } return (a > b) ? a - b : b - a; } } public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int n = Integer.parseInt(bufferedReader.readLine().trim()); List<List<Integer>> arr = new ArrayList<>(); IntStream.range(0, n).forEach(i -> { try { arr.add( Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")) .map(Integer::parseInt) .collect(toList()) ); } catch (IOException ex) { throw new RuntimeException(ex); } }); int result = Result.diagonalDifference(arr); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); bufferedReader.close(); bufferedWriter.close(); } }
Mjp777/JAVA-WITH-OOPS
Diagonal Difference.java
489
/* * Complete the 'diagonalDifference' function below. * * The function is expected to return an INTEGER. * The function accepts 2D_INTEGER_ARRAY arr as parameter. */
block_comment
en
false
400
42
489
43
525
48
489
43
582
56
false
false
false
false
false
true
237696_2
/* * Copyright (C) 2014 Brian L. Browning * * This file is part of Beagle * * Beagle 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. * * Beagle is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package main; import beagleutil.Samples; import blbutil.FileIterator; import blbutil.InputIterator; import blbutil.StringUtil; import java.io.File; import java.util.Arrays; /** * <p>Class {@code NuclearFamilies} stores parent-offspring relationships * in a list of samples. In particular, class {@code NuclearFamilies} * stores a list of the single individuals in the list of samples, * a list of the parent-offspring duos in the list of samples, and a list of * the parent-offspring trios in the list of samples. A single individual is * an individuals without a parent or offspring in the list of samples. * </p> * Instances of class {@code NuclearFamilies} are immutable. * * @author Brian L. Browning {@code <[email protected]>} */ public class NuclearFamilies { private final File pedFile; private final Samples samples; private final int[] single; private final int[] duoOffspring; private final int[] trioOffspring; private final int[] mother; private final int[] father; /** * Constructs a new {@code NuclearFamilies} instance. * * @param samples the list of samples. * @param pedFile a linkage-format pedigree file, or {@code null} * if no pedigree relationships are known. A pedigree file must have * at least 4 white-space delimited columns. The first column of the * pedigree file (family ID) is ignored. The second, third, and fourth * columns are the individual's ID, father's ID, and mother's ID * respectively. * * @throws NullPointerException if {@code samples==null}. * @throws IllegalArgumentException if a pedigree file is specified, * and it has a non-blank line with less than 4 white-space delimited fields. * @throws IllegalArgumentException if a pedigree file is specified, * and it has duplicate individual identifiers in the second white-space * delimited column. */ public NuclearFamilies(Samples samples, File pedFile) { this.pedFile = pedFile; this.samples = samples; this.father = new int[samples.nSamples()]; this.mother = new int[samples.nSamples()]; boolean[] isParent = new boolean[samples.nSamples()]; Arrays.fill(father, -1); Arrays.fill(mother, -1); if (pedFile != null) { identifyParents(samples, pedFile, isParent, father, mother); } int[] cnts = counts(isParent, father, mother); this.single = new int[cnts[0]]; this.duoOffspring = new int[cnts[1]]; this.trioOffspring = new int[cnts[2]]; fillArrays(samples, isParent, father, mother, single, duoOffspring, trioOffspring); } private int[] counts(boolean[] isParent, int[] fathers, int[] mothers) { assert isParent.length==fathers.length; assert isParent.length==mothers.length; int[] cnts = new int[3]; for (int j=0; j<isParent.length; ++j) { int nParents = 0; if (fathers[j] >= 0) { ++nParents; } if (mothers[j] >= 0) { ++nParents; } if (nParents==0) { if (isParent[j]==false) { ++cnts[0]; // increment single count, cnts[0] } } else { // increment duo count, cnts[1], or trio count, cnt[2] ++cnts[nParents]; } } return cnts; } private static void identifyParents(Samples samples, File pedFile, boolean[] isParent, int[] father, int[] mother) { String MISSING_PARENT = "0"; boolean[] idHasBeenProcessed = new boolean[samples.nSamples()]; try (FileIterator<String> pedIt=InputIterator.fromGzipFile(pedFile)) { while (pedIt.hasNext()) { String line = pedIt.next().trim(); if (line.length() > 0) { String[] fields = getPedFields(line); String offspringId = fields[1]; String fatherId = fields[2]; String motherId = fields[3]; int offspring = samples.index(offspringId); if (offspring != -1) { if (idHasBeenProcessed[offspring]) { String s = "duplicate sample in pedigree file: " + offspringId; throw new IllegalArgumentException(s); } else { idHasBeenProcessed[offspring] = true; } if (fatherId.equals(MISSING_PARENT)==false) { int sampleIndex = samples.index(fatherId); if (sampleIndex != -1) { isParent[sampleIndex] = true; father[offspring] = sampleIndex; } } if (motherId.equals(MISSING_PARENT)==false) { int sampleIndex = samples.index(motherId); if (sampleIndex != -1) { isParent[sampleIndex] = true; mother[offspring] = sampleIndex; } } } } } } } private static String[] getPedFields(String line) { String[] fields = StringUtil.getFields(line, 5); if (fields.length < 4) { String s = "invalid line in ped file: " + line; throw new IllegalArgumentException(s); } return fields; } private static void fillArrays(Samples samples, boolean[] isParent, int[] father, int[] mother, int[] single, int[] duoOffspring, int[] trioOffspring) { int singleIndex = 0; int duoIndex = 0; int trioIndex = 0; for (int j=0, n=samples.nSamples(); j<n; ++j) { int nParents = nParents(j, father, mother); switch (nParents) { case 0: if (isParent[j]==false) { single[singleIndex++] = j; } break; case 1: duoOffspring[duoIndex++] = j; break; case 2: trioOffspring[trioIndex++] = j; break; default: assert false; } }; assert singleIndex==single.length; assert duoIndex==duoOffspring.length; assert trioIndex==trioOffspring.length; } private static int nParents(int index, int[] father, int[] mother) { int cnt = 0; if (father[index]>=0) { ++cnt; } if (mother[index]>=0) { ++cnt; } return cnt; } /** * Returns the list of samples. * @return the list of samples. */ public Samples samples() { return samples; } /** * Returns the number of samples. * @return the number of samples. */ public int nSamples() { return samples.nSamples(); } /** * Returns the pedigree file, or returns {@code null} if no * pedigree file was specified. * @return the pedigree file, or {@code null} if no pedigree * file was specified. */ public File pedFile() { return pedFile; } /** * Returns the number of single individuals in the list of samples. * A single individual has no parent or offspring in the list of samples. * @return the number of single individuals in the sample. */ public int nSingles() { return single.length; } /** * Returns the number of parent-offspring duos in the list of samples. * The offspring of a parent-offspring duo has only one parent * in the sample. * @return the number of parent-offspring duos in the list of samples. */ public int nDuos() { return duoOffspring.length; } /** * Returns the number of parent-offspring trios in the list of samples. * The offspring of a parent-offspring trio has two parents * in the sample. * @return the number of parent-offspring trios in the list of samples. */ public int nTrios() { return trioOffspring.length; } /** * Returns the sample index of the specified single individual. * A single individual has no first-degree relative in the list of * samples. * @param index the index of a single individual. * @return the sample index of the specified single individual. * @throws IndexOutOfBoundsException if * {@code index<0 || index>=this.nSingles()}. */ public int single(int index) { return single[index]; } /** * Returns the sample index of the parent of the specified * parent-offspring duo. * @param index the index of a parent-offspring duo. * @return the sample index of the parent of the specified * parent-offspring duo. * @throws IndexOutOfBoundsException if * {@code index<0 || index>=this.nDuos()}. */ public int duoParent(int index) { int offspring = duoOffspring[index]; if (father[offspring]>=0) { return father[offspring]; } else { assert mother[offspring]>=0; return mother[offspring]; } } /** * Returns the sample index of the offspring of the specified * parent-offspring duo. * @param index the index of a parent-offspring duo. * @return the sample index of the offspring of the specified * parent-offspring duo. * @throws IndexOutOfBoundsException if * {@code index<0 || index>=this.nDuos()}. */ public int duoOffspring(int index) { return duoOffspring[index]; } /** * Returns the sample index of the father of the specified * parent-offspring trio. * @param index the index of a parent-offspring trio. * @return the sample index of the father of the specified * parent-offspring trio. * @throws IndexOutOfBoundsException if * {@code index<0 || index>=this.nTrios()}. */ public int trioFather(int index) { return father[trioOffspring[index]]; } /** * Returns the sample index of the mother of the specified * parent-offspring trio. * @param index the index of a parent-offspring trio. * @return the sample index of the mother of the specified * parent-offspring trio. * @throws IndexOutOfBoundsException if * {@code index<0 || index>=this.nTrios()}. */ public int trioMother(int index) { return mother[trioOffspring[index]]; } /** * Returns the sample index of the offspring of the specified * parent-offspring trio. * @param index the index of a parent-offspring trio. * @return the sample index of the offspring of the specified * parent-offspring trio. * @throws IndexOutOfBoundsException if * {@code index<0 || index>=this.nTrios()}. */ public int trioOffspring(int index) { return trioOffspring[index]; } /** * Returns the sample index of the father of the specified sample, * or returns {@code -1} if the father is unknown or is not present * in the list of samples. * @param sample a sample index. * @return the sample index of the father of the specified sample, * or returns {@code -1} if the father is unknown or is not present in * the list of samples. * @throws IndexOutOfBoundsException if * {@code sample<0 || sample>=this.nSamples()()}. */ public int father(int sample) { return father[sample]; } /** * Returns the sample index of the mother of the specified sample, * or returns {@code -1} if the mother is unknown or is not present * in the list of samples. * @param sample a sample index. * @return the sample index of the mother of the specified sample, * or returns {@code -1} if the mother is unknown or is not present * in the list of samples. * @throws IndexOutOfBoundsException if * {@code sample<0 || sample>=this.nSamples()()}. */ public int mother(int sample) { return mother[sample]; } }
tfwillems/PhasedBEAGLE
main/NuclearFamilies.java
3,156
/** * Constructs a new {@code NuclearFamilies} instance. * * @param samples the list of samples. * @param pedFile a linkage-format pedigree file, or {@code null} * if no pedigree relationships are known. A pedigree file must have * at least 4 white-space delimited columns. The first column of the * pedigree file (family ID) is ignored. The second, third, and fourth * columns are the individual's ID, father's ID, and mother's ID * respectively. * * @throws NullPointerException if {@code samples==null}. * @throws IllegalArgumentException if a pedigree file is specified, * and it has a non-blank line with less than 4 white-space delimited fields. * @throws IllegalArgumentException if a pedigree file is specified, * and it has duplicate individual identifiers in the second white-space * delimited column. */
block_comment
en
false
2,948
198
3,156
211
3,361
219
3,156
211
3,707
246
true
true
true
true
true
false
81148_0
class Bill { static String item[]; static String qnty[]; static String unit[]; static int price_per_unit[]; static int count; static String pat_name; static String pat_add; static String pat_pin; static String pat_phone; static int pat_age; static int pat_gen; /** * use to initialize all class variable *( This method should call once at the time of whole program execution. ) */ static void init() { item=new String[100]; qnty=new String[100]; unit=new String[100]; price_per_unit=new int[100]; } /** * TO add a bill item name and its quantity,unit,and price per unit * which are provide as parameter from calling method. */ static void addItem(String itm,String qty,String unt,int price) { item[count]=itm; qnty[count]=qty; unit[count]=unt; price_per_unit[count]=price; count++; } static void add_patient_dtls(String pname,int age,int gen, String add,String pin,String ph){ pat_name=pname; pat_age=age; pat_gen=gen; pat_add=add; pat_pin=pin; pat_phone=ph; } /** * Use to repeat a character(from argument) t time and return created string. */ static String repeat(char c,int t) { String s=""; for(int i=1;i<=t;i++) s+=c; return s; } /** * Use to make string specified string size */ static String print(String s,int size,char align) { int d=size-s.length(); if(align=='R' || align=='r') s=repeat(' ',d)+s; else if(align=='L' || align=='l') s+=repeat(' ',d); else { s=repeat(' ',d-(d/2))+s; s+=repeat(' ',(d/2)); } return s; } /** * to show final bill */ static void showBill() { System.out.println("\f*************************************************************************************************"); System.out.println("* SERVICES FOR *"); System.out.println("**************************************CITY HOSPITAL**********************************************"); System.out.println("* GOD BLESS YOU *"); System.out.println("*************************************************************************************************"); System.out.println("Patient Name:"+pat_name+" Age:"+pat_age+" Gender:"+((pat_gen==1)?"Male":"Female")); System.out.println("Address:"+pat_add+" Pin:"+pat_pin); System.out.println("Mobile:"+pat_phone); int total=0; System.out.println(repeat('=',95)); System.out.println(print("Description",50,'M')+" || "+print("Days/Hrs",10,'M')+" || "+print("Service Code",14,'M')+" || "+print("Price",9,'M')); System.out.println(repeat('=',95)); for(int i=0;i<count;i++) { System.out.println(print(item[i],50,'L')+" || "+print(qnty[i],9,'M')+" || "+print(unit[i],13,'L')+" || "+print(price_per_unit[i]+" /-",9,'R')); total+=(price_per_unit[i]); } System.out.println(repeat('=',95)); System.out.println(print("Total",85,'M')+print(Integer.toString(total)+" /-",10,'R')); System.out.println(repeat('=',95)); } }
Sandip-Basak/Hospital-Billing-System
Bill.java
910
/** * use to initialize all class variable *( This method should call once at the time of whole program execution. ) */
block_comment
en
false
794
29
910
28
1,012
32
910
28
1,080
33
false
false
false
false
false
true
102228_1
/* * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must 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. */ import java.util.Arrays; import java.util.Random; public class Streams { static final double EMPLOYMENT_RATIO = 0.5; static final int MAX_AGE = 100; static final int MAX_SALARY = 200_000; public static void main(String[] args) { int iterations; int dataLength; try { iterations = Integer.valueOf(args[0]); dataLength = Integer.valueOf(args[1]); } catch (Throwable ex) { System.out.println("expected 2 integer arguments: number of iterations, length of data array"); return; } /* Create data set with a deterministic random seed. */ Random random = new Random(42); Person[] persons = new Person[dataLength]; for (int i = 0; i < dataLength; i++) { persons[i] = new Person( random.nextDouble() >= EMPLOYMENT_RATIO ? Employment.EMPLOYED : Employment.UNEMPLOYED, random.nextInt(MAX_SALARY), random.nextInt(MAX_AGE)); } long totalTime = 0; for (int i = 1; i <= 20; i++) { long startTime = System.currentTimeMillis(); long checksum = benchmark(iterations, persons); long iterationTime = System.currentTimeMillis() - startTime; totalTime += iterationTime; System.out.println("Iteration " + i + " finished in " + iterationTime + " milliseconds with checksum " + Long.toHexString(checksum)); } System.out.println("TOTAL time: " + totalTime); } static long benchmark(int iterations, Person[] persons) { long checksum = 1; for (int i = 0; i < iterations; ++i) { double result = getValue(persons); checksum = checksum * 31 + (long) result; } return checksum; } /* * The actual stream expression that we want to benchmark. */ public static double getValue(Person[] persons) { return Arrays.stream(persons) .filter(p -> p.getEmployment() == Employment.EMPLOYED) .filter(p -> p.getSalary() > 100_000) .mapToInt(Person::getAge) .filter(age -> age >= 40).average() .getAsDouble(); } } enum Employment { EMPLOYED, UNEMPLOYED } class Person { private final Employment employment; private final int age; private final int salary; public Person(Employment employment, int height, int age) { this.employment = employment; this.salary = height; this.age = age; } public int getSalary() { return salary; } public int getAge() { return age; } public Employment getEmployment() { return employment; } }
graalvm/graalvm-demos
streams/Streams.java
1,229
/* Create data set with a deterministic random seed. */
block_comment
en
false
1,060
11
1,229
11
1,201
11
1,229
11
1,511
12
false
false
false
false
false
true
167403_1
import java.util.*; import java.util.concurrent.locks.ReentrantReadWriteLock; public class Status { private final ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock(); private final Map<String,TransferWorker> requestsSent = new HashMap<>(); //associates the name of the file, with the TransferWorker that sent a request private final Map<String,TransferWorker> requestsReceived = new HashMap<>(); //associates the name of the file, with the TransferWorker that will handle the request received private final Deque<String> filesToBeSent;//stores the name of the files that need to be sent public Status (Collection<String> filesToBeSent){ this.filesToBeSent = new ArrayDeque<>(filesToBeSent); } public void addRequestSent(String filename, TransferWorker worker){ try { rwlock.writeLock().lock(); requestsSent.put(filename,worker); } finally { rwlock.writeLock().unlock(); } } public void addRequestReceived(String filename, TransferWorker worker){ try { rwlock.writeLock().lock(); requestsReceived.put(filename,worker); } finally { rwlock.writeLock().unlock(); } } public String pollNextFile(){ try { rwlock.writeLock().lock(); return filesToBeSent.poll(); } finally { rwlock.writeLock().unlock(); } } public Collection<TransferWorker> getRequestsSent(){ try { rwlock.readLock().lock(); return new ArrayList<>(requestsSent.values()); } finally { rwlock.readLock().unlock(); } } public Collection<TransferWorker> getRequestsReceived(){ try { rwlock.readLock().lock(); return new ArrayList<>(requestsReceived.values()); } finally { rwlock.readLock().unlock(); } } public Collection<String> getFilesToBeSent(){ try { rwlock.readLock().lock(); return new ArrayList<>(filesToBeSent); } finally { rwlock.readLock().unlock(); } } public boolean wasRequestReceived(String filename){ try { rwlock.readLock().lock(); return requestsReceived.containsKey(filename); } finally { rwlock.readLock().unlock(); } } public boolean wasRequestSent(String filename){ try { rwlock.readLock().lock(); return requestsSent.containsKey(filename); } finally { rwlock.readLock().unlock(); } } }
GoncaloPereiraFigueiredoFerreira/TP2-CC-2021
src/Status.java
555
//associates the name of the file, with the TransferWorker that will handle the request received
line_comment
en
false
519
20
555
20
637
20
555
20
719
20
false
false
false
false
false
true