file_id
stringlengths
4
9
content
stringlengths
41
35k
repo
stringlengths
7
113
path
stringlengths
5
90
token_length
int64
15
4.07k
original_comment
stringlengths
3
9.88k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
excluded
bool
2 classes
242518_2
//To change this license header, choose License Headers in Project Properties. //To change this template file, choose Tools | Templates //and open the template in the editor. public class Savings extends Account implements PayInterest{ public Savings(int accNumber, String accHolder, double balance, String branch) { super(accNumber, accHolder, balance, branch); } @Override public void payInterest(double rate){ this.balance+=balance*rate; } }
BakangMonei/BankingSystem
Savings.java
111
//and open the template in the editor.
line_comment
en
true
242865_25
/* Interface Processing's core functions to Erlang Copyright 2013 by J. David Eisenberg Licensed under LGPL version 2.1 (same as Processing's core) */ import com.ericsson.otp.erlang.*; import processing.core.*; import java.awt.BorderLayout; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JFrame; public class ErlProc { OtpSelf self; OtpConnection connection; OtpErlangPid erlPid; String erlNodeName; String erlFunctionName; ProcessingFrame frame; Embedded embed; public ErlProc() { } /** * Read a line from standard input. Output from Erlang may not be * buffered, so I do not want to make a BufferedReader based on System.in. */ private String getLine() { byte[] buf = new byte[256]; int ch = 0; int i = 0; try { ch = System.in.read(); while (ch > 0 && ch != '\n' && i < 256) { if (ch >= 32) // skip control characters { buf[i++] = (byte) ch; } ch = System.in.read(); } } catch (Exception e) { i = 0; // bail; return null string } return new String(buf, 0, i); } /** * Establish a connection with an Erlang node. Start by receiving * the Erlang node's name via the port. */ public void go() { String str; OtpPeer erlangPeer; OtpMsg message; OtpErlangTuple tuple; OtpErlangAtom command; OtpErlangList dimensionList; float [] dimensions; try { OtpErlangObject [] items = new OtpErlangObject[3]; OtpErlangObject obj; /* The Erlang node name comes via the port */ erlNodeName = getLine(); /* Create a connection to Erlang */ self = new OtpSelf("java_process"); erlangPeer = new OtpPeer(erlNodeName); connection = self.connect(erlangPeer); // System.err.println("Connected to " + erlNodeName // + " " + connection + "\r"); /* Send a message to the Erlang process by name; it will have my Pid and node name in it. */ // System.err.println("Java's pid is " + connection.self().pid() + "\r"); items[0] = new OtpErlangAtom("kabuki"); items[1] = connection.self().pid(); items[2] = new OtpErlangString("java_process"); connection.send("hub", new OtpErlangTuple(items)); /* Erlang sends me a message from which I can get its Pid and the sketch dimensions */ message = connection.receiveMsg(); obj = message.getMsg(); // System.err.println("Java gets message " + obj + "\r"); tuple = (OtpErlangTuple) obj; command = (OtpErlangAtom) tuple.elementAt(0); /* And I send back a message to let Erlang know handshaking is finished */ if (command.atomValue().equals("kabuki")) { int width; int height; erlPid = (OtpErlangPid) tuple.elementAt(1); dimensions = getFloatList(tuple.elementAt(2), 2); width = (int) dimensions[0]; height = (int) dimensions[1]; // System.err.println("Java gets Erlang's Pid: " + erlPid + // " Dimensions: " + dimensionList + "\r"); connection.send(erlPid, new OtpErlangAtom("kabuki_complete")); // open the frame, and start the embedded PApplet frame = new ProcessingFrame(connection, width, height); embed = frame.embed; frame.setResizable(true); frame.setSize(width + 20, height + 20); frame.setVisible(true); embed.init(); } else { // System.err.println("Java gets unknown command " + command.atomValue() // + "\r"); } } catch (Exception e) { // System.err.println("ERR" + e); e.printStackTrace(); } } /** * Retrieve a list of floating point numbers from an Erlang list. */ private float[] getFloatList(OtpErlangObject obj, int maxItems) { float[] result = null; /* Erlang represents a list of integers < 255 as a string. If I get a string, I have to convert each of those integers to a float. */ if (OtpErlangString.class.isInstance(obj)) { String str = ((OtpErlangString) obj).stringValue(); int[] codePoints = OtpErlangString.stringToCodePoints(str); result = new float[str.length()]; for (int i = 0; i < Math.min(maxItems, str.length()); i++) { result[i] = codePoints[i]; } } else if (OtpErlangList.class.isInstance(obj)) // normal Erlang list { OtpErlangList list = (OtpErlangList) obj; int nItems = Math.min(maxItems, list.arity()); result = new float[nItems]; /* Coerce doubles and integers into floats. An OtpErlangFloat is a subclass of OtpErlangDouble, and an OtpErlangInt is a subclass of OtpErlangLong, so that's all I have to check for. */ for (int i = 0; i < nItems; i++) { try { if (OtpErlangDouble.class.isInstance(list.elementAt(i))) { result[i] = ((OtpErlangDouble) list.elementAt(i)).floatValue(); } else if (OtpErlangLong.class.isInstance(list.elementAt(i))) { result[i] = ((OtpErlangLong) list.elementAt(i)).intValue(); } else { result[i] = 0.0F; // if I can't figure out what it is, bail out. } } catch (Exception e) { e.printStackTrace(System.err); result[i] = 0.0F; // likewise if coercion fails } } } return result; } /** * Accept messages from Erlang to draw to the sketch. This is where * all the work really happens. */ private void executeDrawingCommands(OtpErlangList drawingList) { boolean exit = false; OtpErlangTuple tuple; String command; float[] coords; int nItems = drawingList.arity(); for (int i = nItems -1 ; i >= 0; i--) { tuple = (OtpErlangTuple) drawingList.elementAt(i); command = ((OtpErlangAtom) tuple.elementAt(0)).atomValue(); // System.err.println("Executing: " + command + "\r"); if (command.equals("redraw")) { embed.redraw(); embed.noLoop(); } else if (command.equals("noLoop")) { embed.noLoop(); } else if (command.equals("fill")) { doFill(tuple.elementAt(1)); } else if (command.equals("noFill")) { embed.noFill(); } else if (command.equals("stroke")) { doStroke(tuple.elementAt(1)); } else if (command.equals("nostroke")) { embed.noStroke(); } else if (command.equals("background")) { doBackground(tuple.elementAt(1)); } else if (command.equals("line")) { coords = getFloatList(tuple.elementAt(1), 4); if (coords.length == 4) { embed.line(coords[0], coords[1], coords[2], coords[3]); } } else if (command.equals("rect")) { coords = getFloatList(tuple.elementAt(1), 4); if (coords.length == 4) { embed.rect(coords[0], coords[1], coords[2], coords[3]); } } else if (command.equals("ellipse")) { coords = getFloatList(tuple.elementAt(1), 4); if (coords.length == 4) { embed.ellipse(coords[0], coords[1], coords[2], coords[3]); } } else if (command.equals("triangle")) { coords = getFloatList(tuple.elementAt(1), 6); if (coords.length == 6) { embed.triangle(coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]); } } else if (command.equals("quad")) { coords = getFloatList(tuple.elementAt(1), 8); if (coords.length == 8) { embed.quad(coords[0], coords[1], coords[2], coords[3], coords[4], coords[5], coords[6], coords[7]); } } } } private void doFill(OtpErlangObject params) { float[] values = getFloatList(params, 4); switch (values.length) { case 1: embed.fill(values[0]); break; case 2: embed.fill(values[0], values[1]); break; case 3: embed.fill(values[0], values[1], values[2]); break; case 4: embed.fill(values[0], values[1], values[2], values[3]); break; default: break; } } private void doBackground(OtpErlangObject params) { float[] values = getFloatList(params, 4); switch (values.length) { case 1: embed.background(values[0]); break; case 2: embed.background(values[0], values[1]); break; case 3: embed.background(values[0], values[1], values[2]); break; case 4: embed.background(values[0], values[1], values[2], values[3]); break; default: break; } } private void doStroke(OtpErlangObject params) { float[] values = getFloatList(params, 4); switch (values.length) { case 1: embed.stroke(values[0]); break; case 2: embed.stroke(values[0], values[1]); break; case 3: embed.stroke(values[0], values[1], values[2]); break; case 4: embed.stroke(values[0], values[1], values[2], values[3]); break; default: break; } } class Embedded extends PApplet { OtpErlangObject obj; OtpErlangList drawingList; OtpConnection connection; int width; int height; public Embedded(OtpConnection connection, int width, int height) { super(); this.connection = connection; this.width = width; this.height = height; } private OtpErlangTuple createTuple(String atom, int value) { OtpErlangObject[] elements = new OtpErlangObject[2]; elements[0] = new OtpErlangAtom(atom); elements[1] = new OtpErlangFloat(value); return new OtpErlangTuple(elements); } private OtpErlangTuple getEnvironment() { OtpErlangTuple [] items = new OtpErlangTuple[8]; OtpErlangObject [] elements = new OtpErlangObject[2]; OtpErlangTuple result; items[0] = createTuple("mouseX", this.mouseX); items[1] = createTuple("mouseY", this.mouseY); items[2] = createTuple("pmouseX", this.pmouseX); items[3] = createTuple("pmouseY", this.pmouseY); elements[0] = new OtpErlangAtom("mousePressed"); elements[1] = new OtpErlangBoolean(this.mousePressed); items[4] = new OtpErlangTuple(elements); elements[0] = new OtpErlangAtom("mouseButton"); if (this.mouseButton == PApplet.LEFT) { elements[1] = new OtpErlangAtom("left"); } else if (this.mouseButton == PApplet.RIGHT) { elements[1] = new OtpErlangAtom("right"); } else if (this.mouseButton == PApplet.CENTER) { elements[1] = new OtpErlangAtom("center"); } else { elements[1] = new OtpErlangAtom("none"); } items[5] = new OtpErlangTuple(elements); items[6] = createTuple("width", this.width); items[7] = createTuple("height", this.height); elements[0] = new OtpErlangAtom("environment"); elements[1] = new OtpErlangList(items); result = new OtpErlangTuple(elements); return(result); } public void setup() { OtpErlangAtom atom; OtpErlangTuple tuple; size(width, height); try { // System.err.println("Java is sending environment\r"); connection.send(erlPid, getEnvironment()); atom = (OtpErlangAtom) connection.receiveMsg().getMsg(); if (atom.atomValue().equals("ok")) { connection.send(erlPid, new OtpErlangAtom("setup")); tuple = (OtpErlangTuple) connection.receiveMsg().getMsg(); // System.err.println("Java told: " + // ((OtpErlangAtom) tuple.elementAt(0)).atomValue() + "\r"); executeDrawingCommands((OtpErlangList) tuple.elementAt(1)); } } catch (Exception e) { // System.err.println("Cannot setup.\r"); e.printStackTrace(System.err); System.exit(1); } } public void draw() { OtpErlangAtom atom; OtpErlangTuple tuple; try { connection.send(erlPid, getEnvironment()); atom = (OtpErlangAtom) connection.receiveMsg().getMsg(); if (atom.atomValue().equals("ok")) { connection.send(erlPid, new OtpErlangAtom("draw")); tuple = (OtpErlangTuple) connection.receiveMsg().getMsg(); // System.err.println("Java told: " + // ((OtpErlangAtom) tuple.elementAt(0)).atomValue() + "\r"); executeDrawingCommands((OtpErlangList) tuple.elementAt(1)); } } catch (Exception e) { // System.err.println("Cannot draw.\r"); e.printStackTrace(System.err); System.exit(1); } } } class ProcessingFrame extends JFrame { public Embedded embed; public ProcessingFrame(OtpConnection connection, int width, int height) { super("Processing from Erlang"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); Embedded embed = new Embedded(connection, width, height); add(embed, BorderLayout.CENTER); this.embed = embed; } } public static void main(String [] args) { ErlProc app = new ErlProc(); app.go(); } }
jdeisenberg/elixir-proc
ErlProc.java
3,782
// likewise if coercion fails
line_comment
en
true
243141_1
public class Item { private String name; private String model; private double estimatedValue; private boolean toReturn; private int availableQuantity; // Constructor public Item(String name, String model, double estimatedValue, boolean toReturn, int availableQuantity) { this.name = name; this.model = model; this.estimatedValue = estimatedValue; this.toReturn = toReturn; this.availableQuantity = availableQuantity; } // Getter and setter methods for all attributes public String getName() { return name; } public void setName(String name) { this.name = name; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public double getEstimatedValue() { return estimatedValue; } public void setEstimatedValue(double estimatedValue) { this.estimatedValue = estimatedValue; } public boolean isToReturn() { return toReturn; } public void setToReturn(boolean toReturn) { this.toReturn = toReturn; } public int getAvailableQuantity() { return availableQuantity; } public void setAvailableQuantity(int availableQuantity) { this.availableQuantity = availableQuantity; } }
mubashirhussainshah/Java-Lab-Inventory-Management-Application
Item.java
291
// Getter and setter methods for all attributes
line_comment
en
true
243158_15
public class Main { public static void A_star(int[][] graph, int start, int end) { int V = graph.length; // the set of nodes already evaluated Set<Integer> closedSet = new HashSet<>(); // the set of currently discovered nodes that are already evaluated // initially only the start node is known. Set<Integer> openSet = new HashSet<>(); openSet.add(start); // the most efficient previous step, i.e. the parent node int[] cameFrom = new int[V]; for (int i = 0; i < V; i++) cameFrom[i] = i; // for each node, the cost of getting from start node to that node int[] gScore = new int[V]; Arrays.fill(gScore, Integer.MAX_VALUE); gScore[start] = 0; // fScore = gScore + hScore // hScore is the estimated cost to move from that node to the end // The value is partly known, partly heuristic int[] fScore = new int[V]; Arrays.fill(fScore, Integer.MAX_VALUE); // 3 ways to calculate "h" // 1. Euclidean Distance (Exact Heuristics) // when there are no blocked cells/obstacles // h = sqrt ( (current_cell.x – goal.x)2 + (current_cell.y – goal.y)2 ) // 2.1 Manhattan Distance (Approximation Heuristics) // When we are allowed to move only in four directions only // h = abs (current_cell.x – goal.x) + abs (current_cell.y – goal.y) // 2.2 Diagonal Distance (Approximation Heuristics) // When we are allowed to move 8 directions only // h = max { abs(current_cell.x – goal.x), abs(current_cell.y – goal.y) } fScore[start] = hScore(start, end); while (!openSet.isEmpty()) { int cur = minF(openSet, fScore, V); // reach the end point if (cur == end) { constructPath(cameFrom, cur, start); } // current node has been evaluated openSet.remove(cur); closedSet.add(cur); for (int v = 0; v < V; v++) { // for each neighbor of cur // not a neighbor, undirected graph if (graph[cur][v] == 0) continue; // has been evaluated if (closedSet.contains(v)) continue; // the dist from start to the neighbor int tmp_gScore = gScore[cur] + graph[cur][v]; if (!openSet.contains(v)) openSet.add(v); // Discover a new node else if (tmp_gScore >= gScore[v]) continue; // this is not a better path // else, this is a better path cameFrom[v] = cur; gScore[v] = tmp_gScore; fScore[v] = gScore[v] + hScore(v, end); } } } private static int hScore(int start, int end) { // here we use Manhattan dist return 2 * Math.abs(end - start); } private static int minF(Set<Integer> openSet, int[] fScore, int V) { int minVal = Integer.MAX_VALUE, idx = -1; for (int i = 0; i < V; i++) { if (openSet.contains(i) && fScore[i] < minVal) { minVal = fScore[i]; idx = i; } } return idx; } private static void constructPath(int[] cameFrom, int cur, int start) { // construct path LinkedList<Integer> finalPath = new LinkedList<>(); finalPath.addFirst(cur + 1); while (true) { cur = cameFrom[cur]; finalPath.addFirst(cur + 1); if (cur == start) break; } System.out.print(finalPath); System.out.println(); } public static void main(String[] args) { int graph[][] = { {0,0,0,1,0}, {0,0,0,1,1}, {0,0,0,0,1}, {1,1,0,0,1}, {0,1,1,1,0}, }; A_star(graph, 0, 2); } }
zhugejunwei/Algorithms-in-Java-Swift-CPP
A* Algorithm.java
1,067
// 2.2 Diagonal Distance (Approximation Heuristics)
line_comment
en
true
243357_30
/* * @file Entity.java * * @brief Implementa a interface GameObject para objetos moveis no jogo (= entidade) * * @author Alexandre Marques Carrer <alexandrecarrer@usp.br> * @author Felipe Bagni <febagni@usp.br> * @author Gabriel Yugo Kishida <gabriel.kishida@usp.br> * @author Gustavo Azevedo Correa <guazco@usp.br> * * @date 06/2020 * */ import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public abstract class Entity implements GameObject { protected int x; //coordenada x da entidade na matriz do mapa protected int y; //coordenada y da entidade na matriz do mapa protected MapID id; //identidade do objeto protected GameObject[][] map; //matriz dos objetos do mapa protected int direction; //direcao da entidade protected int frame; //frame da animacao do sprite da entidade protected BufferedImage sprite; //sprite da entidade protected final int animationSlowness = 6; //fator da velocidade da animacao protected int realX, realY; //coordenadas do sprite da entidade na tela protected int speedX, speedY; //velocidades nos eixos cartesianos do sprite na tela protected int xLength, yLength; //tamanho da matriz nos eixos protected String spritePath; // Caminho dos sprites dos objetos protected int lastDirection = KeyEvent.VK_LEFT; // Ultima dire��o da entidade protected static int step = 2; /* * @brief Setters e Getters para algumas caracteristicas */ public void setRealX(int x) {realX = x;} public void setRealY(int y) {realY = y;} public int getRealX() {return realX;} public int getRealY() {return realY;} public static void setStep(int newStep) {step = newStep;} public void setSpritePath (String spritePath) { this.spritePath = spritePath; } public void setMap(GameObject[][] map2) { this.map = map2; xLength = map2.length; yLength = map2[0].length; } @Override public int getX() {return (realX+(squareSize/2))/squareSize;} @Override public int getY() {return (realY+(squareSize/2))/squareSize;} @Override public MapID getID() {return id;} @Override public void setX(int x) {this.x = x;} @Override public void setY(int y) {this.y = y;} @Override public void setID(MapID id) {this.id = id;} /* * @brief Verifica se o objeto na posicao x, y == parede */ protected boolean isNotAWall(int x, int y) { return map[x][y].getID() != MapID.Wall; } public abstract GameObject clone(); /* * @brief Funcoes booleanas que verificam a posicao relativa do sprite em comparacao com o centro de seu bloco no eixo X */ protected boolean centeredOnX() {return realX - getX()*squareSize == 0;} protected boolean higherThanCenterOnX() {return realX - getX()*squareSize > 0;} protected boolean lowerThanCenterOnX() {return realX - getX()*squareSize < 0;} /* * @brief Funcoes booleanas que verificam a posicao relativa do sprite em comparacao com o centro de seu bloco no eixo Y */ protected boolean centeredOnY() {return realY - getY()*squareSize == 0;} protected boolean higherThanCenterOnY() {return realY - getY()*squareSize > 0;} protected boolean lowerThanCenterOnY() {return realY - getY()*squareSize < 0;} /* * @brief Verifica se o sprite esta na borda do mapa */ protected boolean isOnEdge() { if (speedX != 0 && (getX() == xLength -1 || getX() == 0)) return true; //se a entidade esta se movendo no eixo x e esta em seus extremos else if (speedY != 0 && (getY() == yLength -1 || getY() == 0)) return true; //se a entidade esta se movendo no eixo y e esta em seus extremos else return false; } /* * @brief Verifica se a entidade está parada */ protected boolean isStopped() { return (speedX == 0 && speedY == 0); } /* * @brief Verifica se a entidade pode se mover na direcao indicada * * @param direction Direcao da entidade * * @return Se pode ou nao seguir */ protected boolean canGo(String direction) { if (direction == "up") { if (isOnEdge()) return ( isNotAWall(xLength-1, getY()) || !centeredOnX()); return (isNotAWall(getX()-1, getY()) || !centeredOnX()); } else if (direction == "down") { if (isOnEdge()) return (isNotAWall(0, getY()) || !centeredOnX()); return (isNotAWall(getX()+1, getY()) || !centeredOnX()); } else if (direction == "left"){ if (isOnEdge()) return (isNotAWall(getX(), yLength-1) || !centeredOnY()); return (isNotAWall(getX(), getY()-1) || !centeredOnY()); } else if (direction == "right") { if (isOnEdge()) return (isNotAWall(getX(), 0) || !centeredOnY()); return (isNotAWall(getX(), getY()+1) || !centeredOnY()); } return false; } /* * @brief Verifica se a entidade esta andando no eixo y e tem que parar */ boolean hasToStopY() { return (!canGo("right") && speedY > 0) || (!canGo("left") && speedY < 0); } /* * @brief Verifica se a entidade esta andando no eixo x e tem que parar */ boolean hasToStopX() { return ((!canGo("down") && speedX > 0) || (!canGo("up") && speedX < 0)); } /* * @brief Setter da velocidade da entidade em ambos os eixos */ void setSpeed(int speedX, int speedY) { this.speedX = speedX; this.speedY = speedY; } /* * @brief Atualiza posicao do pacman corrigindo se ele sai do mapa */ void updateMovement() { realX += speedX; realY += speedY; if(getX() <= 0 && speedX < 0 && (lowerThanCenterOnX())) realX = (xLength - 1)*squareSize; else if(getX() >= xLength - 1 && speedX > 0 && (higherThanCenterOnX())) realX = 0; if(getY() <= 0 && speedY < 0 && (lowerThanCenterOnY())) realY = (yLength - 1)*squareSize; else if(getY() >= yLength - 1 && speedY > 0 && (higherThanCenterOnY())) realY = 0; } /* * @brief Atualiza o valor da velocidade do pacman */ void updateSpeed() { switch (direction) { case KeyEvent.VK_UP: moveUp(); break; case KeyEvent.VK_DOWN: moveDown(); break; case KeyEvent.VK_LEFT: moveLeft(); break; case KeyEvent.VK_RIGHT: moveRight(); break; } } /* * @brief Movimento da entidade para cima */ void moveUp() { if(!centeredOnY()) return; if (canGo("up")) setSpeed(-step, 0); else if (hasToStopY()) setSpeed(0, 0); else setSpeed(0, speedY); } /* * @brief Movimento da entidade para baixo */ void moveDown() { if(!centeredOnY()) return; if (canGo("down")) setSpeed(step, 0); else if (hasToStopY()) setSpeed(0, 0); else setSpeed(0, speedY); } /* * @brief Movimento da entidade para a esquerda */ void moveLeft() { if(!centeredOnX()) return; if (canGo("left")) setSpeed(0, -step); else if (hasToStopX()) setSpeed(0, 0); else setSpeed(speedX, 0); } /* * @brief Movimento da entidade para a direita */ void moveRight() { if(!centeredOnX()) return; if (canGo("right")) setSpeed(0, step); else if (hasToStopX()) setSpeed(0, 0); else setSpeed(speedX, 0); } @Override public abstract void tick(); /* * @brief m�todo que atualiza a anima��o da entidade */ void updateAnimation() { frame++; if(frame>5*animationSlowness) frame = 0; } /* * @brief m�todo que especifica como deve ser renderizado as entidades */ @Override public void render(Graphics graphic) { int animationDirection; if(speedX > 0) animationDirection = KeyEvent.VK_DOWN; else if(speedX < 0) animationDirection = KeyEvent.VK_UP; else if(speedY > 0) animationDirection = KeyEvent.VK_RIGHT; else if(speedY < 0) animationDirection = KeyEvent.VK_LEFT; else animationDirection = lastDirection; graphic.drawImage(sprite.getSubimage((frame/(2*animationSlowness))*30, (animationDirection - 37)*30, 28, 28) , realY+2, realX+2, null); lastDirection = animationDirection; } /* * @brief m�todo que atualiza a o sprite da entidade baseado no look-and-feel */ public void updateSprite() { try { this.sprite = ImageIO.read(new File(SpritesManager.getFolder() + this.spritePath)); } catch (IOException e) { e.printStackTrace(); } } }
febagni/project-pacman
src/Entity.java
2,741
/* * @brief Movimento da entidade para a esquerda */
block_comment
en
true
243476_13
import java.awt.desktop.SystemSleepEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.ArrayList; import java.lang.Thread ; enum Status{ NOT_STARTED, CONTINUE, ENDED } public class Game { private String currentWord ; private String displayedWord ; private String inputFileName ; ArrayList<String> words ; Status gameStatus ; Scanner scanner ; Player player ; public Game(){ gameStatus = Status.NOT_STARTED ; words = new ArrayList<>() ; inputFileName = "words.txt" ; scanner = new Scanner(System.in) ; getWords(); } /* Setters */ public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } private void setCurrentWord( String s){ currentWord = s ; } private void setDisplayedWord( String s){ displayedWord = s ; } public void setGameStatus( Status st){ gameStatus = st ; } /* Getters */ public Status getGameStatus() { return gameStatus; } public String getCurrentWord() { return currentWord; } public String getDisplayedWord() { return displayedWord; } private void getWords(){ String filePath = inputFileName; try { // Create a File object representing the file File file = new File(filePath); // Create a Scanner object to read from the file Scanner sc = new Scanner(file); // Read and process each line of the file while (sc.hasNextLine()) { String line = sc.nextLine(); words.add(line) ; } } catch (FileNotFoundException e) { // Handle file not found exception System.out.println( e.getMessage() ); } } public Boolean pickRandomWordFromWordList(){ int numberOfWords = words.size(); if( numberOfWords == 0) return false ; int randomIndex = (int) (Math.random()*numberOfWords); setCurrentWord( words.get(randomIndex) ); // erase word from word list words.remove(randomIndex) ; return true; } public void addPlayer(String name){ player = new Player(name) ; } public void takeGuessFromPlayer(){ System.out.println("Enter your guess ... "); String guess = scanner.nextLine() ; char gs = guess.charAt(0) ; player.setGuess(gs); } public void printPlayerStatus(){ // Clear the console System.out.print("\033[H\033[2J"); System.out.flush(); System.out.println("Your word " + displayedWord); System.out.println("Your health " + player.getHealth() ); System.out.println("Your current score " + player.getNumberOfKnownWords() ); } public boolean isEnded(){ return gameStatus == Status.ENDED ; } public void draw(){ int health = player.getHealth() ; if( health <= 4 ){ drawRope() ; } if( health <= 3 ){ drawHead(); } if( health <= 2 ){ drawArms() ; } if( health <= 1 ){ drawBody() ; } if( health <= 0 ){ drawFoot() ; } } private void drawRope(){ System.out.println("**************************************"); System.out.println(" | "); System.out.println(" | "); System.out.println(" ----- "); } private void drawHead (){ System.out.println(" O "); } private void drawArms(){ // put one extra backslash to escape special character property of it in java System.out.println(" /|\\ "); } private void drawBody(){ System.out.println(" | "); } private void drawFoot (){ System.out.println(" / \\ "); } public void playGame(){ pickRandomWordFromWordList() ; int wordSize = currentWord.length() ; String buffer = "" ; // Make displayed word same length with currentWord but all chars replaced by '_' for(int i = 0 ; i<wordSize ; i++){ buffer = buffer + "_" ; } displayedWord = buffer ; while( !isEnded() ){ printPlayerStatus(); draw(); while(true){ try{ takeGuessFromPlayer(); break; } catch (Exception e){ System.out.println("You didn't enter any guess!!ç"); } } boolean charFound = false ; boolean alreadyGuessed = false ; String bufferDisplayed = "" ; // check if current guess is in the displayed words for(int i = 0 ; i< currentWord.length() ; i++ ){ if(player.getGuess() == displayedWord.charAt(i) ){ alreadyGuessed = true ; break; } } // Update displayed word according to player's guess. for(int i = 0 ; i< currentWord.length() ; i++ ){ if( currentWord.charAt(i) == player.getGuess() ){ charFound = true ; wordSize -- ; bufferDisplayed += player.getGuess() ; } else{ bufferDisplayed += displayedWord.charAt(i) ; } } // change displayed word setDisplayedWord(bufferDisplayed); if(!charFound || alreadyGuessed){ player.setHealth( player.getHealth()-1 ); } // Determine WIN LOSE or CONTINUE // CASE: LOSE if( player.isDead() ){ setGameStatus(Status.ENDED); System.out.println("You have lost the game " + player.getName()+ " :/") ; System.out.println("As total you have guessed "+ player.getNumberOfKnownWords() +" words correctly"); System.out.println("The word to be guessed was : " + currentWord) ; try { Thread.sleep( 3* 1000); } catch (InterruptedException ie) { System.out.println("Sleep interrupted"); ie.printStackTrace(); } continue; } if( wordSize == 0 ){ player.setNumberOfKnownWords( player.getNumberOfKnownWords()+1 ); printPlayerStatus() ; draw() ; System.out.println("You guessed the word correctly "); // Case : No words left to be guessed if(!pickRandomWordFromWordList()){ System.out.println("You have guessed all the words correctly"); System.out.println("As total you have guessed " + player.getNumberOfKnownWords() + " words correctly"); System.out.println("---------------Game Ended---------------"); System.out.println("****************************************"); try { Thread.sleep( 3* 1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } setGameStatus(Status.ENDED) ; continue ; } // Case : There are words to be guessed else{ printPlayerStatus(); draw() ; player.setGuess('*'); System.out.println("Next word is loading..."); setDisplayedWord(""); // Maybe we should implement other game logic here other than calling same function recursively. try { Thread.sleep( 3* 1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } playGame() ; return ; } } setGameStatus(Status.CONTINUE); } } }
omer-faruk-erdem/Hangman_Game
Game.java
1,749
// Determine WIN LOSE or CONTINUE
line_comment
en
true
243726_0
/*Concepts implemented: * 1. swing and awt for GUI. * 2. Classes and objects * 3. Constructor, Anonymous class * 4. static, final and access modifiers. * 5. File Handling * 6. Exception Handling * 7. Interfaces, method overriding (Runtime Polymorphism). * 8. Encapsulation,Multithreading (basic) * 9. Important keywords like this,final etc. * 10.Garbage collection and finalize. */ import javax.swing.UIManager; public class Main{ public static void main(String args[]) { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel"); new TextEditor(); } catch(Exception e) { System.out.println(e); } } }
sreshtha10/TextEditor
src/Main.java
215
/*Concepts implemented: * 1. swing and awt for GUI. * 2. Classes and objects * 3. Constructor, Anonymous class * 4. static, final and access modifiers. * 5. File Handling * 6. Exception Handling * 7. Interfaces, method overriding (Runtime Polymorphism). * 8. Encapsulation,Multithreading (basic) * 9. Important keywords like this,final etc. * 10.Garbage collection and finalize. */
block_comment
en
true
243910_8
import java.util.*; import java.util.function.Predicate; public class Rule implements Node { private final int HAND_SIZE = 5; private final int FLUSH_SCORE; private final int STRAIGHT_SCORE; private final PokerSquaresPointSystem system; private Node leftChild; private Node rightChild; private Node parent; private Random randomGenerator; private boolean row; private int rc; private int pointThresh; private Integer id; private String ruleType; public Rule(PokerSquaresPointSystem system, Integer id) { this.id = id; this.system = system; FLUSH_SCORE = system.getHandScore(PokerHand.FLUSH); STRAIGHT_SCORE = system.getHandScore(PokerHand.STRAIGHT); int[] scores = system.getScoreTable(); Arrays.sort(scores); // threshold is the median score pointThresh = scores[scores.length/4]; randomGenerator = new Random(); // determine if checking row or column boolean randBool = randomGenerator.nextBoolean(); row = randBool; // which row or column to check int randInt = randomGenerator.nextInt(5); rc = randInt; ruleType = decideType(); } /** * @return A String that determines the type of this rule. */ private String decideType() { int method = randomGenerator.nextInt(3) + 1; String label; switch (method) { case 1: label = "place in hand"; break; case 2: label = "straight"; break; case 3: label = "flush"; break; default: throw new IllegalStateException( "Invalid integer: not in 0-3 (Rule)"); } return label; } /** * {@inheritDoc} */ public void setRight(Node right) { this.rightChild = right; this.rightChild.setParent(this); } /** * {@inheritDoc} */ public void setLeft(Node left) { this.leftChild = left; this.leftChild.setParent(this); } /** * {@inheritDoc} */ public Node getParent() { return this.parent; } /** * {@inheritDoc} */ public void setParent(Node parent) { this.parent = parent; } /** * {@inheritDoc} */ public Integer getID() { return id; } /** * @return A String that represents the function or value of this node. */ public String getLabel() { String rowOrCol = row ? "row" : "column"; String rcnum = Integer.toString(rc); String label = "Check for " + ruleType + " in the " + rowOrCol + " ranked " + rcnum; return label; } /** * Counts the cards in the row/column that fit a certain criterion * @return A list of counts sorted by the criterion in rows/columns. */ private int[][] countCards(Card[][] grid, Predicate<Card> filter) { int[][] counts = new int[5][2]; // make the second entry in each count the row/col number for (int i = 1; i < 5; i++) { counts[i][1] = i; } // count the number of entries in each row/col if (row) { // row for (int row = 0; row < 5; row++) { for (int col = 0; col < 5; col++) { if (filter.test(grid[row][col])) { counts[row][0]++; } } } } else { // column for (int row = 0; row < 5; row++) { for (int col = 0; col < 5; col++) { if (filter.test(grid[col][row])) { counts[row][0]++; } } } } // compares 2 dimensional int arrays Arrays.sort(counts, new Comparator<int[]>() { @Override public int compare(final int[] item1, final int[] item2) { // randomize if the values are the same if (item2[0] - item1[0] == 0) { return randomGenerator.nextBoolean() ? 1 : -1; } // otherwise, return the normal comparator return item2[0] - item1[0]; } }); return counts; } /** * Checks a given row number, places the card somewhere in the row, * and then checks what kind of hand it gives, and returns the value of * the hand. * @return A boolean, indicating which direction to move in the tree. */ private boolean checkRow(Card[][] grid, Card curCard) { // choose which row we'll place the card into Predicate<Card> isCard = (Card card) -> card != null; int[][] preferenceList = countCards(grid, isCard); // make sure there aren't too many cards in a hand int temprc = rc; int rowChoice = preferenceList[temprc][1]; while (preferenceList[temprc][0] >= HAND_SIZE) { temprc = (temprc + 1) % HAND_SIZE; rowChoice = preferenceList[temprc][1]; if (temprc == rc) break; } Card[] potentialHand = grid[rowChoice].clone(); int handLength = preferenceList[temprc][0]; potentialHand[handLength] = curCard; int handScore = system.getHandScore(potentialHand); int suitScore = suitCheck(potentialHand); int seqScore = seqCheck(potentialHand); if (ruleType == "flush") handScore = suitScore; else if (ruleType == "straight") handScore = seqScore; return (handScore > pointThresh); } /** * Checks a given column number, places the card somewhere in the column, * and then checks what kind of hand it gives, and returns the value of * the hand. * @return A boolean, indicating which direction to move in the tree. */ private boolean checkColumn(Card[][] grid, Card curCard) { // find counts for each column Predicate<Card> isCard = (Card card) -> card != null; int[][] preferenceList = countCards(grid, isCard); // find column with appropriate number of cards (< 5) int temprc = rc; int columnChoice = preferenceList[temprc][1]; while (preferenceList[temprc][0] >= HAND_SIZE) { temprc = (temprc + 1) % HAND_SIZE; columnChoice = preferenceList[temprc][1]; if (temprc == rc) break; } Card[] potentialHand = new Card[5]; int handLength = preferenceList[temprc][0]; for (int i = 0; i < potentialHand.length; i++) { potentialHand[i] = grid[columnChoice][i]; } potentialHand[handLength] = curCard; int handScore = system.getHandScore(potentialHand); int suitScore = suitCheck(potentialHand); int seqScore = seqCheck(potentialHand); if (ruleType == "flush") handScore = suitScore; else if (ruleType == "straight") handScore = seqScore; return (handScore > pointThresh); } /** * Checks for groups of suits in the hand, and then * determines whether there is a flush. If there is a * partial flush, scales down the score. * @return A score for the hand based on flush potential. */ private int suitCheck(Card[] hand) { int[] suitCount = new int[HAND_SIZE]; for (int i = 0; i < HAND_SIZE; i++) { suitCount[i] = 0; } int maxSuit = 0; for (int i = 0; i < HAND_SIZE; i++) { if (hand[i] != null) { int suit = hand[i].getSuit(); suitCount[suit]++; if (suitCount[suit] > maxSuit) maxSuit = suitCount[suit]; } } if (maxSuit == HAND_SIZE) { return FLUSH_SCORE; } else { return (FLUSH_SCORE/(HAND_SIZE-maxSuit)); } } /** * Checks for sequences in the given hand and returns * the score for the straight, and if the sequence is partial, * returns a scale down value for the score. * @return A score for the hand based on straight potential. */ private int seqCheck(Card[] hand) { int[] ranks = new int[HAND_SIZE]; for (int i = 0; i < HAND_SIZE; i++) { if (hand[i] == null) { ranks[i] = 0; } else { ranks[i] = hand[i].getRank(); } } Arrays.sort(ranks); int first = 0; int seqCount = 0; for (int i = 0; i < HAND_SIZE; i++) { if (ranks[i] != 0) { if (first == 0) { first = ranks[i]; } if (ranks[i] - first < 5) { seqCount++; } } } if (seqCount == HAND_SIZE) { return STRAIGHT_SCORE; } else { return (STRAIGHT_SCORE/(HAND_SIZE - seqCount)); } } /** * Evaluates the node at this level and returns one of the child nodes. * @return A boolean, indicating which direction to move in the tree. */ public int[] evaluate(Card[][] grid, Card curCard) { boolean direction = row ? checkRow(grid, curCard) : checkColumn(grid, curCard); return direction ? rightChild.evaluate(grid, curCard) : leftChild.evaluate(grid, curCard); } /** * {@inheritDoc} */ public Node getLeftChild() { return leftChild; } /** * {@inheritDoc} */ public Node getRightChild() { return rightChild; } /** * {@inheritDoc} */ public Object clone() throws CloneNotSupportedException { return super.clone(); } }
chetaldrich/pokersquares
src/Rule.java
2,387
/** * {@inheritDoc} */
block_comment
en
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
243932_0
/* * Boolean Or on double values. * */ import org.jgap.*; import org.jgap.gp.*; import org.jgap.gp.impl.*; import org.jgap.util.*; /** * The boolean or operation on double values. * * @author Hakan Kjellerstrand */ public class OrD extends MathCommand implements IMutateable, ICloneable { public OrD(final GPConfiguration a_conf) throws InvalidConfigurationException { super(a_conf, 2, CommandGene.DoubleClass); } public CommandGene applyMutation(int index, double a_percentage) throws InvalidConfigurationException { CommandGene mutant; if (a_percentage < 0.5d) { mutant = new XorD(getGPConfiguration()); } else { mutant = new AndD(getGPConfiguration()); } return mutant; } public String toString() { return "&1 || &2"; } /** * @return textual name of this command * * @author Hakan Kjellerstrand */ public String getName() { return "OrD"; } public double execute_double(ProgramChromosome c, int n, Object[] args) { double d1 = c.execute_double(n, 0, args); double d2 = c.execute_double(n, 1, args); boolean b1 = true; boolean b2 = true; if (d1 < 1.0d) { b1 = false; } if (d2 < 1.0d) { b2 = false; } if (b1 | b2) { return 1.0d; } return 0.0d; } /** * Clones the object. Simple and straight forward implementation here. * * @return cloned instance of this object * * @author Hakan Kjellerstrand */ public Object clone() { try { OrD result = new OrD(getGPConfiguration()); return result; } catch (Exception ex) { throw new CloneException(ex); } } }
hakank/hakank
jgap/OrD.java
503
/* * Boolean Or on double values. * */
block_comment
en
true
244136_2
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class Report */ public class Report extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Report() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath()); response.setContentType("text/html"); request.getRequestDispatcher("include.jsp").include(request, response); PrintWriter pr=response.getWriter(); HttpSession session=request.getSession(); /*String id1=(String) session.getAttribute("username"); String id2=(String) session.getAttribute("password"); LoginDAO ld=new LoginDAO(); ArrayList a1=ld.income(id1,id2); Iterator itr=a1.iterator(); itr.hasNext(); ReportPoso rp=(ReportPoso) itr.next(); float inc=rp.getSum(); ArrayList a2=ld.expense(id1, id2); Iterator it=a2.iterator(); it.hasNext(); ReportPoso rpt=(ReportPoso) it.next(); float exp=rpt.getSum(); float rem=inc-exp; pr.println("<html><body><table border><th>Remaining</th>"); pr.println("<tr><td>Income</td><td>"+inc+"</td></tr>"); pr.println("<tr><td>Remaining</td><td>"+rem+"</td></tr>"); pr.println("<tr><td>Expense</td><td>"+exp+"</td></tr>"); pr.println("<tr></tr><tr><td>Balance</td><td>"+rem+"</td></tr>"); pr.println("</table></body></html>"); */ } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
BhushanKumarSingh/Money-Maneger
Report.java
626
// TODO Auto-generated constructor stub
line_comment
en
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
244314_0
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { static long flippingBits(long N) { long l=(long)Math.pow(2,32)-1; return l^N; // Complete this function } public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int a0 = 0; a0 < T; a0++){ long N = in.nextLong(); long result = flippingBits(N); System.out.println(result); } in.close(); } }
Aabhas99/HackerRank-Solution-To-Algorithms
Interview Preparation Kit/Miscellaneous/Flipping bits.java
168
// Complete this function
line_comment
en
true
244598_0
package TJU; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; /*- * @author Mazen Magdy * -We need to "match" the maximum amount of cows to food and drinks. So we can build a graph where * each drink, food, cow is a vertex. Food is connected to a cow with capacity 1, and a cow is connected to drink * with capacity 1. Moreover a cow has vertex capacity 1. The Maximum Flow in this graph is the answer. */ public class TJU_2823_Dining { static final int oo = 1 << 27; static int V, s, t; static ArrayList<Integer>[] g; static int[][] res; static int[] p; static void addEdge(int u, int v, int cap) { g[u].add(v); g[v].add(u); res[u][v] = cap; } static int edmondKarp() { int mf = 0; p = new int[V]; while (true) { Queue<Integer> q = new LinkedList<Integer>(); q.add(s); Arrays.fill(p, -1); p[s] = s; while (!q.isEmpty()) { int u = q.poll(); // System.err.println(u); if (u == t) break; for (int v : g[u]) { // System.err.println(u + " " + v + " " + res[u][v]); if (p[v] == -1 && res[u][v] > 0) { p[v] = u; q.add(v); } } } if (p[t] == -1) break; mf += augment(t, oo); } return mf; } static int augment(int v, int flow) { if (v == s) return flow; flow = augment(p[v], Math.min(flow, res[p[v]][v])); res[p[v]][v] -= flow; res[v][p[v]] += flow; return flow; } public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(System.in); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(), F = sc.nextInt(), D = sc.nextInt(); V = (N << 1) + F + D + 2; s = V - 2; t = V - 1; g = new ArrayList[V]; for (int i = 0; i < V; i++) g[i] = new ArrayList<Integer>(); res = new int[V][V]; for (int cow = 0; cow < N; cow++) { int f = sc.nextInt(); int d = sc.nextInt(); for (int j = 0; j < f; j++) { int v = sc.nextInt() - 1; addEdge(v, F + cow, 1); } addEdge(F + cow, F + N + cow, 1); for (int j = 0; j < d; j++) { int v = sc.nextInt() - 1; addEdge(F + N + cow, v + F + (N << 1), 1); } } for (int i = 0; i < F; i++) addEdge(s, i, 1); for (int i = F + (N << 1); i < F + (N << 1) + D; i++) addEdge(i, t, 1); // System.err.println(Arrays.toString(g)); out.println(edmondKarp()); out.flush(); out.close(); } static class MyScanner { StringTokenizer st; BufferedReader br; public MyScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public MyScanner(String filename) throws IOException { br = new BufferedReader(new FileReader(new File(filename))); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
TheRealImaginary/CompetitiveProgramming
TJU/TJU_2823_Dining.java
1,279
/*- * @author Mazen Magdy * -We need to "match" the maximum amount of cows to food and drinks. So we can build a graph where * each drink, food, cow is a vertex. Food is connected to a cow with capacity 1, and a cow is connected to drink * with capacity 1. Moreover a cow has vertex capacity 1. The Maximum Flow in this graph is the answer. */
block_comment
en
true
244641_0
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Pouya */ public class DiningTest { public static void main(String[] args){ Chopstick CH = new Chopstick(); new Philosopher(CH).start(); new Philosopher(CH).start(); new Philosopher(CH).start(); new Philosopher(CH).start(); new Philosopher(CH).start(); } }
pouyarz/Multithreading--Dining-Philosophers-problem-solution-with-Java
DiningTest.java
143
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */
block_comment
en
true
244870_61
/* * Event Platform Client (EPC) * * _/\/\/\/\/\/\________________________________________/\/\_____ * _/\____________/\/\__/\/\____/\/\/\____/\/\/\/\____/\/\/\/\/\_ * _/\/\/\/\/\____/\/\__/\/\__/\/\/\/\/\__/\/\__/\/\____/\/\_____ * _/\/\____________/\/\/\____/\/\________/\/\__/\/\____/\/\_____ * _/\/\/\/\/\/\______/\________/\/\/\/\__/\/\__/\/\____/\/\/\___ * ______________________________________________________________ * ___/\/\/\/\/\__/\/\____/\/\______________________________/\/\_____ * _/\/\__________/\/\______________/\/\/\____/\/\/\/\____/\/\/\/\/\_ * _/\/\__________/\/\____/\/\____/\/\/\/\/\__/\/\__/\/\____/\/\_____ * _/\/\__________/\/\____/\/\____/\/\________/\/\__/\/\____/\/\_____ * ___/\/\/\/\/\__/\/\/\__/\/\/\____/\/\/\/\__/\/\__/\/\____/\/\/\___ * __________________________________________________________________ * * DESCRIPTION * Collects events in an input buffer, adds some metadata, places them * in an ouput buffer where they are periodically bursted to a remote * endpoint via HTTP POST. * * Designed for use with Wikipedia Android application producing events to * the EventGate intake service. * * AUTHORS * Jason Linehan <jlinehan@wikimedia.org> * Mikhail Popov <mpopov@wikimedia.org> * * LICENSE NOTICE * Copyright 2019 Wikimedia Foundation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import org.json.JSONObject; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Scanner; import java.util.Timer; import java.util.TimerTask; import java.util.List; public class EPC { /** * OutputBuffer: buffers events in a queue prior to transmission * * Static class * * Transmission is via HTTP POST. * Transmissions are not sent at a uniform offset but are shaped into * 'bursts' using a combination of queue size and debounce time. * * These concentrate requests (and hence, theoretically, radio awake state) * so as not to contribute to battery drain. */ private static class OutputBuffer { /* * When an item is added to QUEUE, wait this many ms before sending. * * If another item is added to QUEUE during this time, reset the * countdown. */ private static int WAIT_MS = 2000; /* * When QUEUE.size() exceeds this value TIMER becomes non-interruptable. */ private static int WAIT_ITEMS = 10; /* * When ENABLED is false, items can be enqueued but not dequeued. * Timers will not be set for enqueued items. * QUEUE may grow beyond WAIT_ITEMS. */ private static boolean ENABLED = true; /* * IMPLEMENTATION NOTE: QUEUE is a linked list of two-element arrays of * strings. * * The two strings in each array item are the two arguments of the * send() or schedule() method. */ private static LinkedList<String[]> QUEUE = new LinkedList(); /* * IMPLEMENTATION NOTE: Java Timer will provide the desired asynchronous * countdown after a new item is added to QUEUE. */ private static Timer TIMER; /* * IMPLEMENTATION NOTE: Java abstract TimerTask class requires a run() * method be defined. * * The run() method is called when the Timer expires. */ private static class Task extends TimerTask { public void run() { send_all_scheduled(); } } /** * Dequeue and call send() on all scheduled items. */ public static void send_all_scheduled() { if (TIMER != null) { TIMER.cancel(); } if (ENABLED == true) { /* * All items on QUEUE are permanently removed. */ String[] item = new String[2]; while ((item = QUEUE.poll()) != null) { /* * Failure of send() will result in data loss. * (Fire-and-forget) */ send(item[0], item[1]); } } else { /* * Do nothing; the data is still in the queue and will be sent * after we are enabled again. */ } } /** * Schedule a request to be sent. * * @param url destination of the HTTP POST request * @param body body of the HTTP POST request */ public static void schedule(String url, String body) { /* * The actual item enqueued is an array of length 2 holding the two * arguments. */ String[] item = {url, body}; /* * Item is enqueued whether or not sending is enabled. */ QUEUE.add(item); if (ENABLED == true) { if (QUEUE.size() >= WAIT_ITEMS) { /* * >= because while sending is disabled, any number of items * could be added to QUEUE without it emptying. */ send_all_scheduled(); } else { /* * The arrival of a new item interrupts the timer and resets * the countdown. */ if (TIMER != null) { TIMER.cancel(); } TIMER = new Timer(); TIMER.schedule(new Task(), WAIT_MS); } } } /** * Attempt to send a request with the given url and body. * * @param url destination of the HTTP POST request * @param body body of the HTTP POST request */ public static void send(String url, String body) { if (ENABLED == true) { /* * Attempt to transmit the given body to the given url via HTTP * POST. */ try { Integration.http_post(url, body); } catch (Exception e) { /* * FIXME: How to handle? */ } } else { /* * Do nothing (transmission is disabled; items remain in QUEUE) */ } } /** * Enable sending */ public static void enable_sending() { ENABLED = true; /* * Try immediately to send any enqueued items. Otherwise another * item must be enqueued before sending is triggered. */ send_all_scheduled(); } /** * Disable sending */ public static void disable_sending() { ENABLED = false; } } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /** * AssociationController: provides associative identifiers and manage their * persistence * * Static class * * Identifiers correspond to various scopes e.g. 'pageview', 'session', * 'activity', and 'device'. */ private static class AssociationController { private static String PAGEVIEW_ID = null; private static String SESSION_ID = null; /** * Generate a pageview identifier. * * @return pageview ID * * The identifier is a string of 20 zero-padded hexadecimal digits * representing a uniformly random 80-bit integer. */ public static String pageview_id() { if (PAGEVIEW_ID == null) { PAGEVIEW_ID = Integration.generate_id(); } return PAGEVIEW_ID; } /** * Generate a session identifier. * * @return session ID * * The identifier is a string of 20 zero-padded hexadecimal digits * representing a uniformly random 80-bit integer. */ public static String session_id() { if (SESSION_ID == null) { /* * If there is no runtime value for SESSION_ID, try to load a * value from persistent store. */ SESSION_ID = Integration.get_persistent("sid"); if (SESSION_ID == null) { /* * If there is no value in the persistent store, generate a * new value for SESSION_ID, and write the update to the * persistent store. */ SESSION_ID = Integration.generate_id(); Integration.set_persistent("sid", SESSION_ID); } } return SESSION_ID; } /** * Unset the session. */ public static void begin_new_session() { /* * Clear runtime and persisted value for SESSION_ID. */ SESSION_ID = null; Integration.del_persistent("sid"); /* * A session refresh implies a pageview refresh, so clear runtime * value of PAGEVIEW_ID. */ PAGEVIEW_ID = null; } } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /** * SamplingController: computes various sampling functions on the client * * Static class * * Sampling is based on associative identifiers, each of which have a * well-defined scope, and sampling config, which each stream provides as * part of its configuration. */ private static class SamplingController { /** * Compute a boolean function on a random identifier. * * @param token string of random hexadecimal digits * @param config sampling config from stream configuration * @return true if in sample or false otherwise */ public static boolean in_sample(String token, JSONObject config) { if (!config.has("rate")) { return true; /* True by default */ } return true; /* FIXME */ } } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /** * The static public API allows callers to configure streams and log events. */ /* * CONFIG is the shared store of stream configuration data. Stream * configuration is looked up by the name of the stream. */ private static JSONObject CONFIG = new JSONObject(); /* * COPIED maps stream names to lists of stream names. Stream name 'x' will * be mapped to an array of stream names matching 'x.*'. */ private static Map<String, List<String>> COPIED = new HashMap<String, List<String>>(); /* * The constructor is private, so instantiation of the EPC class is * impossible. */ private void EPC() { } /** * Add configuration to the shared CONFIG object. * * @param config stream configuration to be loaded into memory */ public static void configure(String config) { /* * FIXME: in production this can't be so simple? */ CONFIG = new JSONObject(config); COPIED.clear(); for (Object xx : CONFIG.keySet()) { String x = (String)xx; COPIED.put(x, new LinkedList<String>()); for (Object yy : CONFIG.keySet()) { String y = (String)yy; if (y.startsWith(x + ".")) { COPIED.get(x).add(y); } } } /* TODO: Try inputbuffer flush here */ } /** * Log an event according to the given stream's configuration. * * @param stream name of the stream to send @object to * @param arg sequence of key, value pairs, or single JSONObject */ public static void log(String stream, Object... arg) throws RuntimeException { JSONObject data; if (!(arg[0] instanceof JSONObject)) { /* * The 'meta' field is reserved. Altering its value will result in * undefined behavior. An event's timestamp shall be recorded at the * moment of its first receipt. Subsequent invocations shall not * alter the timestamp value. */ String dt = Integration.generate_iso_8601_timestamp(); JSONObject meta = new JSONObject(); meta.put("dt", dt); /* * IMPLEMENTATION NOTE: The log() method can be called multiple * times on the same data. The first time it is called, the data * will be presented as a variadic argument list. In all subsequent * calls, it will be presented as a single JSONObject. This branch * triggers on the first call, and this is where we wrap the * argument list into a JSONObject. */ data = new JSONObject(); for (int i = 0; i < arg.length; i += 2) { try { data.put(arg[i].toString(), arg[i + 1]); } catch (Exception e) { /* arg[i+1] not JSON-compatible type */ throw new RuntimeException(e); } } data.put("meta", meta); } else { data = (JSONObject)arg[0]; } if (!CONFIG.has(stream)) { /* * If specified stream is not yet configured, event is discarded. */ return; } for (String copied_stream : COPIED.get(stream)) { /* * Invocation on a stream 'x' shall result in invocation on any * configured stream matching 'x.*', with a copy of the event. * * An event's copy shall have timestamp equal to that of the * original, regardless of when the copy is created. * * No information besides the original event data and the original * timestamp shall pass between stream 'x' and 'x.*'. */ log(copied_stream, data); } if (Integration.client_cannot_be_tracked()) { /* * If the specified stream is not configured as private, it shall * receive no events when the client has signaled that they shall * not be tracked. */ return; } if (!CONFIG.getJSONObject(stream).has("scope")) { /* * TODO: need to finalize in stream spec */ /* * If the specified stream is not configured with a 'scope' * attribute, it is assigned to the 'pageview' scope for * compatibility with other EPC implementations. App-specific * stream configs should specify 'device' or 'session' scopes only * and explicitly, as 'pageview' scope is mainly relevant to web. */ CONFIG.getJSONObject(stream).put("scope", "pageview"); } /* * The source of randomness for sampling shall be the identifier * corresponding to the stream's configured scope. */ String scope_id; if (CONFIG.getJSONObject(stream).getString("scope").equals("session")) { scope_id = AssociationController.session_id(); } else { scope_id = AssociationController.pageview_id(); } if (SamplingController.in_sample(scope_id, CONFIG.getJSONObject(stream).getJSONObject("sample"))) { /* * An event shall be processed only if the sampling controller * computes true on the identifier corresponding to the stream's * configured scope. */ /* * Retreive the meta field in order to add information besides the * 'dt' field. */ JSONObject meta = data.getJSONObject("meta"); /* * meta.id is optional and should only be done in case the client is * known to send duplicates of events, otherwise we don't need to * make the payload any heavier than it already is */ meta.put("id", Integration.generate_uuid_v4()); meta.put("stream", stream); data.put("meta", meta); /* * Add other root-level information */ data.put("$schema", CONFIG.getJSONObject(stream).getString("$schema")); data.put("pageview_id", AssociationController.pageview_id()); data.put("session_id", AssociationController.session_id()); data.put("device_id", Integration.get_device_id()); if (CONFIG.getJSONObject(stream).has("destination")) { /* * FIXME: replace with a call to Log.d for production (or * abstract away to Integration?) */ System.out.print("\nScheduling event to be sent to stream '" + stream + "'"); System.out.print(" with data: " + data.toString(2) + "\n"); /* * Schedule the event for transmission. */ OutputBuffer.schedule(CONFIG.getJSONObject(stream).getString("destination"), data.toString()); } } } }
linehan/wmf-epc
src/java/EPC.java
4,010
/* * Schedule the event for transmission. */
block_comment
en
false
244884_3
/* A common anti-pattern is mocking a type you do not own, because their behavior often changes and is beyond your control. One solution is to create a light weight wrapper around external lib/types. However, if your wrapper just forwards data without transforming input/output, then the wrapper and the mock of it has little sense to exist,i.e., the abstraction is redundant. You should use normal integration testing */ class Sample{ public void ex() { //verify simple invocation on mock mockedList.size(); verify(mockedList).size(); //verify an interaction has not occurred List<String> mockedList = mock(MyList.class); mockedList.size(); verify(mockedList, never()).clear(); //verify number of interactions with mock mockedList.size(); verify(mockedList, times(1)).size(); //use spy to mock only those methods of a real object that we want to } }
HaonanXu/notes
java/mockito.java
209
//verify number of interactions with mock
line_comment
en
true
244986_0
package cs1302.api; import javafx.geometry.Pos; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.control.TextField; import javafx.scene.control.Button; import javafx.scene.text.Text; import javafx.scene.control.ScrollPane; import javafx.scene.control.Label; import javafx.geometry.Insets; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.layout.Priority; /** * A custom component that takes user input for a song's artist and title and displays the lyrics. */ public class CityData extends VBox { HBox searchBox; Label stateLabel; Label cityLabel; TextField stateField; TextField cityField; Button button; HBox messageBox; Text message; ScrollPane scrollpane; Text text; /** Constructs an {@code CityData} object. */ public CityData() { super(); searchBox = new HBox(8); stateLabel = new Label("State:"); cityLabel = new Label("City:"); stateField = new TextField("ga"); cityField = new TextField("atlanta"); button = new Button("Search"); message = new Text("Type in a US city and its state (abbreviated), then click the button."); messageBox = new HBox(); messageBox.setPadding(new Insets(10,0,10,0)); scrollpane = new ScrollPane(); scrollpane.setPadding(new Insets(10)); text = new Text(); this.getChildren().addAll(searchBox, messageBox, scrollpane); searchBox.getChildren().addAll(cityLabel, cityField, stateLabel, stateField, button); searchBox.setAlignment(Pos.CENTER_LEFT); HBox.setHgrow(stateLabel, Priority.ALWAYS); HBox.setHgrow(cityLabel, Priority.ALWAYS); messageBox.getChildren().add(message); scrollpane.setContent(text); scrollpane.setPrefHeight(450); scrollpane.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS); } // CityData() } // CityData
nicolechung01/City-Zip-Weather
api/CityData.java
505
/** * A custom component that takes user input for a song's artist and title and displays the lyrics. */
block_comment
en
true
245227_5
// 14.5 Tell me something about Object Reflection in java. // Answer: // 1. class type, constructor, member method, these are a few characteristics of a class // 2. the Object Reflection is a collection of tool classes, it is able to handle the situation when you know you want certain behavior, but don't know exactly what type of class you need. // 3. Unlike generics, it mainly deal with member methods and constructors, while generics focus more about data. // 4. you may get a specific constructor, a member method with customized constraints. public class TestJava { public static void main(String[] args) { return; } }
jiguang123/Big-Data-Learning-Note
07_数据结构与算法/Cracking-the-Coding-Interview/p14-5.java
155
// 4. you may get a specific constructor, a member method with customized constraints.
line_comment
en
true
245280_9
package challenge2; /** * SLCC Programming Club - Coding Challenge 2 * October 5, 2022 * * This week's coding challenges feature common interview questions that require recursion. * Implement the methods below based off of the instructions provided in the doc comments. * * For an added challenge, try writing out your code before using your computer. Type it into * your computer only when you're ready to verify your code works! * * @author ... * */ public class Challenge2 { /** * Creates a new string by removing any instance of the character 'x' from a * provided String. * * Warm up by coding this iteratively or recursively. * * EXAMPLES: * warmUp("axbxcxd") → "abcd" * warmUp("xxx a xxx") → " a " * * @param str string to modify * @return string with x's removed */ public String warmUp(String str) { return ""; //TODO } /** * Reverses a given string. * * EXAMPLES: * reverse("hello") → "olleh" * reverse("extraordinary") → "yranidroartxe" * * @param str string to reverse * @return reversed string */ public String reverse (String str) { return ""; //TODO } /** * Determines the sum of two given numbers without using any arithmetic operators. * * EXAMPLES: * sum(12,15) → 27 * sum(20, 3) → 23 * * @param first first number * @param second second number * @return sum of the two numbers */ public static int sum(int first, int second) { return 0; //TODO } /** * ULTIMATE CHALLENGE: * * Returns the longest substring present in the provided Strings. Empty Strings are * valid. * * EXAMPLES: * longestSubstring("Fresh","Press") → "res" * longestSubstring("solution","action") → "tion" * * @param a first string * @param b second string * @return longest substring */ public String longestSubstring(String first, String second) { return ""; //TODO } /** =================================================================================== * TEST CLIENT * =================================================================================== */ public static void main(String[] args) { // TODO Auto-generated method stub } }
SLCCProgrammingClub/ClubChallenges
Challenge2.java
584
/** =================================================================================== * TEST CLIENT * =================================================================================== */
block_comment
en
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
245367_0
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package remix; import java.util.Scanner; /** * * @author Akarsh */ public class Remix { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner sc=new Scanner(System.in); String s=sc.next(); s=s.replace("WUB", " "); System.out.println(s.trim()); } }
Mit-Ak/Competitive-Programming
Remix.java
155
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */
block_comment
en
true
245527_0
/*Question #2b Mohith Nagendra 3/9/2022*/ public class Disk { private Point center; private double radius; public Disk(Point c, double r){ center = c; radius = r; } }
mohithn04/APCompSci
Disk.java
66
/*Question #2b Mohith Nagendra 3/9/2022*/
block_comment
en
true
245548_97
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class Kernel { // Interrupt requests public final static int INTERRUPT_SOFTWARE = 1; // System calls public final static int INTERRUPT_DISK = 2; // Disk interrupts public final static int INTERRUPT_IO = 3; // Other I/O interrupts // System calls public final static int BOOT = 0; // SysLib.boot( ) public final static int EXEC = 1; // SysLib.exec(String args[]) public final static int WAIT = 2; // SysLib.join( ) public final static int EXIT = 3; // SysLib.exit( ) public final static int SLEEP = 4; // SysLib.sleep(int milliseconds) public final static int RAWREAD = 5; // SysLib.rawread(int blk, byte b[]) public final static int RAWWRITE= 6; // SysLib.rawwrite(int blk, byte b[]) public final static int SYNC = 7; // SysLib.sync( ) public final static int READ = 8; // SysLib.cin( ) public final static int WRITE = 9; // SysLib.cout( ) and SysLib.cerr( ) // System calls to be added in Assignment 4 public final static int CREAD = 10; // SysLib.cread(int blk, byte b[]) public final static int CWRITE = 11; // SysLib.cwrite(int blk, byte b[]) public final static int CSYNC = 12; // SysLib.csync( ) public final static int CFLUSH = 13; // SysLib.cflush( ) // System calls to be added in Project public final static int OPEN = 14; // SysLib.open( String fileName ) public final static int CLOSE = 15; // SysLib.close( int fd ) public final static int SIZE = 16; // SysLib.size( int fd ) public final static int SEEK = 17; // SysLib.seek( int fd, int offest, // int whence ) public final static int FORMAT = 18; // SysLib.format( int files ) public final static int DELETE = 19; // SysLib.delete( String fileName ) // Predefined file descriptors public final static int STDIN = 0; public final static int STDOUT = 1; public final static int STDERR = 2; // Return values public final static int OK = 0; public final static int ERROR = -1; // System thread references private static Scheduler scheduler; private static Disk disk; private static Cache cache; // Synchronized Queues private static SyncQueue waitQueue; // for threads to wait for their child private static SyncQueue ioQueue; // I/O queue private final static int COND_DISK_REQ = 1; // wait condition private final static int COND_DISK_FIN = 2; // wait condition // Standard input private static BufferedReader input = new BufferedReader( new InputStreamReader( System.in ) ); // The heart of Kernel public static int interrupt( int irq, int cmd, int param, Object args ) { TCB myTcb; switch( irq ) { case INTERRUPT_SOFTWARE: // System calls switch( cmd ) { case BOOT: // instantiate and start a scheduler scheduler = new Scheduler( ); scheduler.start( ); // instantiate and start a disk disk = new Disk( 1000 ); disk.start( ); // instantiate a cache memory cache = new Cache( disk.blockSize, 10 ); // instantiate synchronized queues ioQueue = new SyncQueue( ); waitQueue = new SyncQueue( scheduler.getMaxThreads( ) ); return OK; case EXEC: return sysExec( ( String[] )args ); case WAIT: if ( ( myTcb = scheduler.getMyTcb( ) ) != null ) { int myTid = myTcb.getTid( ); // get my thread ID return waitQueue.enqueueAndSleep( myTid ); //wait on my tid // woken up by my child thread } return ERROR; case EXIT: if ( ( myTcb = scheduler.getMyTcb( ) ) != null ) { int myPid = myTcb.getPid( ); // get my parent ID int myTid = myTcb.getTid( ); // get my ID if ( myPid != -1 ) { // wake up a thread waiting on my parent ID waitQueue.dequeueAndWakeup( myPid, myTid ); // I'm terminated! scheduler.deleteThread( ); return OK; } } return ERROR; case SLEEP: // sleep a given period of milliseconds scheduler.sleepThread( param ); // param = milliseconds return OK; case RAWREAD: // read a block of data from disk while ( disk.read( param, ( byte[] )args ) == false ) ioQueue.enqueueAndSleep( COND_DISK_REQ ); while ( disk.testAndResetReady( ) == false ) ioQueue.enqueueAndSleep( COND_DISK_FIN ); // it's possible that a thread waiting to make a request was released by the disk, // but then promptly looped back, found the buffer wasn't available for sending (bufferReady == true) // and then went back to sleep Kernel.ioQueue.dequeueAndWakeup(Kernel.COND_DISK_REQ); // now you can access data in buffer return OK; case RAWWRITE: // write a block of data to disk while ( disk.write( param, ( byte[] )args ) == false ) ioQueue.enqueueAndSleep( COND_DISK_REQ ); while ( disk.testAndResetReady( ) == false ) ioQueue.enqueueAndSleep( COND_DISK_FIN ); // it's possible that a thread waiting to make a request was released by the disk, // but then promptly looped back, found the buffer wasn't available for sending (bufferReady == true) // and then went back to sleep Kernel.ioQueue.dequeueAndWakeup(Kernel.COND_DISK_REQ); return OK; case SYNC: // synchronize disk data to a real file while ( disk.sync( ) == false ) ioQueue.enqueueAndSleep( COND_DISK_REQ ); while ( disk.testAndResetReady( ) == false ) ioQueue.enqueueAndSleep( COND_DISK_FIN ); // it's possible that a thread waiting to make a request was released by the disk, // but then promptly looped back, found the buffer wasn't available for sending (bufferReady == true) // and then went back to sleep Kernel.ioQueue.dequeueAndWakeup(Kernel.COND_DISK_REQ); return OK; case READ: switch ( param ) { case STDIN: try { String s = input.readLine(); // read a keyboard input if ( s == null ) { return ERROR; } // prepare a read buffer StringBuffer buf = ( StringBuffer )args; // append the keyboard intput to this read buffer buf.append( s ); // return the number of chars read from keyboard return s.length( ); } catch ( IOException e ) { System.out.println( e ); return ERROR; } case STDOUT: case STDERR: System.out.println("threadOS: caused read errors"); return ERROR; } // return FileSystem.read( param, byte args[] ); return ERROR; case WRITE: switch ( param ) { case STDIN: System.out.println("threadOS: cannot write to System.in"); return ERROR; case STDOUT: System.out.print( (String)args ); break; case STDERR: System.err.print( (String)args ); break; } return OK; case CREAD: // to be implemented in assignment 4 return cache.read( param, ( byte[] )args ) ? OK : ERROR; case CWRITE: // to be implemented in assignment 4 return cache.write( param, ( byte[] )args ) ? OK : ERROR; case CSYNC: // to be implemented in assignment 4 cache.sync( ); return OK; case CFLUSH: // to be implemented in assignment 4 cache.flush( ); return OK; case OPEN: // to be implemented in project return OK; case CLOSE: // to be implemented in project return OK; case SIZE: // to be implemented in project return OK; case SEEK: // to be implemented in project return OK; case FORMAT: // to be implemented in project return OK; case DELETE: // to be implemented in project return OK; } return ERROR; case INTERRUPT_DISK: // Disk interrupts // wake up the thread waiting for a service completion ioQueue.dequeueAndWakeup( COND_DISK_FIN ); // wake up the thread waiting for a request acceptance // ioQueue.dequeueAndWakeup(COND_DISK_REQ); return OK; case INTERRUPT_IO: // other I/O interrupts (not implemented) return OK; } return OK; } // Spawning a new thread private static int sysExec( String args[] ) { String thrName = args[0]; // args[0] has a thread name Object thrObj = null; try { //get the user thread class from its name Class thrClass = Class.forName( thrName ); if ( args.length == 1 ) // no arguments thrObj = thrClass.newInstance( ); // instantiate this class obj else { // some arguments // copy all arguments into thrArgs[] and make a new constructor // argument object from thrArgs[] String thrArgs[] = new String[ args.length - 1 ]; for ( int i = 1; i < args.length; i++ ) thrArgs[i - 1] = args[i]; Object[] constructorArgs = new Object[] { thrArgs }; // locate this class object's constructors Constructor thrConst = thrClass.getConstructor( new Class[] {String[].class} ); // instantiate this class object by calling this constructor // with arguments thrObj = thrConst.newInstance( constructorArgs ); } // instantiate a new thread of this object Thread t = new Thread( (Runnable)thrObj ); // add this thread into scheduler's circular list. TCB newTcb = scheduler.addThread( t ); return ( newTcb != null ) ? newTcb.getTid( ) : ERROR; } catch ( ClassNotFoundException e ) { System.out.println( e ); return ERROR; } catch ( NoSuchMethodException e ) { System.out.println( e ); return ERROR; } catch ( InstantiationException e ) { System.out.println( e ); return ERROR; } catch ( IllegalAccessException e ) { System.out.println( e ); return ERROR; } catch ( InvocationTargetException e ) { System.out.println( e ); return ERROR; } } }
hyeonhong/CSS-430
Paging/src/Kernel.java
2,613
// add this thread into scheduler's circular list.
line_comment
en
true
245572_0
class Disk { static final int NUM_SECTORS = 1024; StringBuffer sectors[] = new StringBuffer[NUM_SECTORS]; int size = 0; // only 1 can write to Disk void write(int sector, StringBuffer data){ sectors[sector] = new StringBuffer(data); } void read(int sector, StringBuffer data){ data.setLength(0); data.append(sectors[sector]); } }
kwchiao/MCSOS
Disk.java
107
// only 1 can write to Disk
line_comment
en
true
245891_0
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.Color; public class Credits extends Buttons { public Credits() { setImage(new GreenfootImage("Credits", 50, Color.BLUE, null)); } public void act() { setImage(new GreenfootImage("Credits", 50, Color.BLUE, Color.WHITE)); getImage().setTransparency(220); if (getWorld() instanceof Intro) { if (Greenfoot.getMouseInfo() != null){ if (Greenfoot.getMouseInfo().getX() >= 385 && Greenfoot.getMouseInfo().getX() <= 515 && Greenfoot.getMouseInfo().getY() >= 430 && Greenfoot.getMouseInfo().getY() <= 490) { setImage(new GreenfootImage("Credits", 50, Color.RED, Color.WHITE)); getImage().setTransparency(220); } } if (Greenfoot.mouseClicked(this)) { Greenfoot.setWorld(new Cred()); } } } }
cpcsc/snowboarding
Credits.java
266
// (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
line_comment
en
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
246002_0
package phys; // TODO(pablo): clearly need to generalize to multi-dimensional space. public abstract class Force { public void apply(Space2D before, Space2D after) { int radius = before.getRadius(); for (int x = 0; x < radius; x++) { for (int y = 0; y < radius; y++) { apply(radius, before, after, x, y); } } } public abstract void apply(int radius, Space2D before, Space2D after, int x, int y); }
pablo-mayrgundter/freality
phys/Force.java
132
// TODO(pablo): clearly need to generalize to multi-dimensional space.
line_comment
en
true
246362_1
/* * Mr Ajay Sharma is working woth words. He found that few words in the langugage have same meaning. Such words are given as a list of pairs as mappedpairs[], where mappedpairs[i] = [word1, word2] indicates that word1 and word2 are the words with same meaning. He is given phrase, and he wants to apply all the mappedpairs[] on the phrase. Your task is to help Mr.Ajay Sharma to find and return all possible Mapped Phrases generated after applying all the mapped words, and print them in lexicographical order. Input Format: ------------- Line-1: An integer N, number of mapped pairs. Next N lines: Two space separated words, mappedpair[]. Last Line: A line of words, the phrase. Output Format: -------------- Print the list of mapped phrases in sorted order. Sample Input-1: --------------- 3 hi hello sweet sugar candy chocolate hi sam! ram has a sugar candy Sample Output-1: ---------------- [hello sam! he has sugar candy, hello sam! he has sugar chocolate, hello sam! he has sweet candy, hello sam! he has sweet chocolate, hi sam! he has sugar candy, hi sam! he has sugar chocolate, hi sam! he has sweet candy, hi sam! he has sweet chocolate] Sample Input-2: --------------- 2 hi hey hey hello hi how are you Sample Output-2: ---------------- [hello how are you, hey how are you, hi how are you] */ /* * Mr Ajay Sharma is working woth words. * He found that few words in the langugage have same meaning. * Such words are given as a list of pairs as mappedpairs[], * where mappedpairs[i] = [word1, word2] indicates that word1 and word2 are * the words with same meaning. * * He is given phrase, and he wants to apply all the mappedpairs[] on the * phrase. * * Your task is to help Mr.Ajay Sharma to find and return all possible * Mapped Phrases generated after applying all the mapped words, * and print them in lexicographical order. * * * Input Format: * ------------- * Line-1: An integer N, number of mapped pairs. * Next N lines: Two space separated words, mappedpair[]. * Last Line: A line of words, the phrase. * * Output Format: * -------------- * Print the list of mapped phrases in sorted order. * * * Sample Input-1: * --------------- * 3 * hi hello * sweet sugar * candy chocolate * hi sam! ram has a sugar candy * * Sample Output-1: * ---------------- * [hello sam! he has sugar candy, hello sam! he has sugar chocolate, * hello sam! he has sweet candy, hello sam! he has sweet chocolate, * hi sam! he has sugar candy, hi sam! he has sugar chocolate, * hi sam! he has sweet candy, hi sam! he has sweet chocolate] * * * * Sample Input-2: * --------------- * 2 * hi hey * hey hello * hi how are you * * Sample Output-2: * ---------------- * [hello how are you, hey how are you, hi how are you] * * #include<bits/stdc++.h> * using namespace std; * * class UnionFind { * vector<int> id; * public: * UnionFind(int N) : id(N) { * iota(begin(id), end(id), 0); * } * int find(int a) { * return id[a] == a ? a : (id[a] = find(id[a])); * } * void connect(int a, int b) { * id[find(a)] = find(b); * } * }; * * int main(){ * int n; * cin>>n; * vector<vector<string>> A(n,vector<string>(2,"")); * for(int i=0;i<n;i++){ * cin>>A[i][0]>>A[i][1]; * } * cin.ignore(); * string s; * getline(cin,s); * istringstream ss(s); * string word; * vector<string> v, tmp, ans; * while (ss >> word) v.push_back(word); * int id = 0; * unordered_map<string, int> index; * unordered_map<int, string> rindex; * for (auto &syn : A) { * if (index.count(syn[0]) == 0) { * index[syn[0]] = id; * rindex[id] = syn[0]; * ++id; * } * if (index.count(syn[1]) == 0) { * index[syn[1]] = id; * rindex[id] = syn[1]; * ++id; * } * } * UnionFind uf(index.size()); * for (auto &syn : A) { * uf.connect(index[syn[0]], index[syn[1]]); * } * unordered_map<int, set<string>> m; * for (int i = 0; i < index.size(); ++i) { * m[uf.find(i)].insert(rindex[i]); * } * function<void(int)> dfs = [&](int i) { * if (i == v.size()) { * string t; * for (auto &w : tmp) { * if (t.size()) t += ' '; * t += w; * } * ans.push_back(t); * return; * } * if (index.count(v[i])) { * for (auto &syn : m[uf.find(index[v[i]])]) { * tmp.push_back(syn); * dfs(i + 1); * tmp.pop_back(); * } * } else { * tmp.push_back(v[i]); * dfs(i + 1); * tmp.pop_back(); * } * }; * dfs(0); * for(auto it:ans){ * cout<<it<<' '; * } * return 0; * } */ import java.util.*; /** * d55p3 */ public class d55p3 { // converting the above code to java }
adityachintala/Elite-Questions
Java/D55/d55p3.java
1,592
/* * Mr Ajay Sharma is working woth words. * He found that few words in the langugage have same meaning. * Such words are given as a list of pairs as mappedpairs[], * where mappedpairs[i] = [word1, word2] indicates that word1 and word2 are * the words with same meaning. * * He is given phrase, and he wants to apply all the mappedpairs[] on the * phrase. * * Your task is to help Mr.Ajay Sharma to find and return all possible * Mapped Phrases generated after applying all the mapped words, * and print them in lexicographical order. * * * Input Format: * ------------- * Line-1: An integer N, number of mapped pairs. * Next N lines: Two space separated words, mappedpair[]. * Last Line: A line of words, the phrase. * * Output Format: * -------------- * Print the list of mapped phrases in sorted order. * * * Sample Input-1: * --------------- * 3 * hi hello * sweet sugar * candy chocolate * hi sam! ram has a sugar candy * * Sample Output-1: * ---------------- * [hello sam! he has sugar candy, hello sam! he has sugar chocolate, * hello sam! he has sweet candy, hello sam! he has sweet chocolate, * hi sam! he has sugar candy, hi sam! he has sugar chocolate, * hi sam! he has sweet candy, hi sam! he has sweet chocolate] * * * * Sample Input-2: * --------------- * 2 * hi hey * hey hello * hi how are you * * Sample Output-2: * ---------------- * [hello how are you, hey how are you, hi how are you] * * #include<bits/stdc++.h> * using namespace std; * * class UnionFind { * vector<int> id; * public: * UnionFind(int N) : id(N) { * iota(begin(id), end(id), 0); * } * int find(int a) { * return id[a] == a ? a : (id[a] = find(id[a])); * } * void connect(int a, int b) { * id[find(a)] = find(b); * } * }; * * int main(){ * int n; * cin>>n; * vector<vector<string>> A(n,vector<string>(2,"")); * for(int i=0;i<n;i++){ * cin>>A[i][0]>>A[i][1]; * } * cin.ignore(); * string s; * getline(cin,s); * istringstream ss(s); * string word; * vector<string> v, tmp, ans; * while (ss >> word) v.push_back(word); * int id = 0; * unordered_map<string, int> index; * unordered_map<int, string> rindex; * for (auto &syn : A) { * if (index.count(syn[0]) == 0) { * index[syn[0]] = id; * rindex[id] = syn[0]; * ++id; * } * if (index.count(syn[1]) == 0) { * index[syn[1]] = id; * rindex[id] = syn[1]; * ++id; * } * } * UnionFind uf(index.size()); * for (auto &syn : A) { * uf.connect(index[syn[0]], index[syn[1]]); * } * unordered_map<int, set<string>> m; * for (int i = 0; i < index.size(); ++i) { * m[uf.find(i)].insert(rindex[i]); * } * function<void(int)> dfs = [&](int i) { * if (i == v.size()) { * string t; * for (auto &w : tmp) { * if (t.size()) t += ' '; * t += w; * } * ans.push_back(t); * return; * } * if (index.count(v[i])) { * for (auto &syn : m[uf.find(index[v[i]])]) { * tmp.push_back(syn); * dfs(i + 1); * tmp.pop_back(); * } * } else { * tmp.push_back(v[i]); * dfs(i + 1); * tmp.pop_back(); * } * }; * dfs(0); * for(auto it:ans){ * cout<<it<<' '; * } * return 0; * } */
block_comment
en
true
246378_2
import java.util.*; import java.lang.reflect.Method; import soot.*; import soot.options.*; import soot.toolkits.graph.*; import soot.toolkits.scalar.*; import soot.baf.*; import soot.jimple.*; public class Taint { public static void main(String[] args) { PackManager.v().getPack("jtp").add(new Transform("jtp.myTransform", new BodyTransformer() { protected void internalTransform(Body body, String phase, Map options) { new TaintAnalysisWrapper(new ExceptionalUnitGraph(body)); } })); soot.Main.main(args); } } class TaintAnalysisWrapper { public TaintAnalysisWrapper(UnitGraph graph) { TaintAnalysis analysis = new TaintAnalysis(graph); if(analysis.taintedSinks.size() > 0) { G.v().out.print("FAILURE: "); G.v().out.println(analysis.taintedSinks); } } } interface GetUseBoxes { public List<ValueBox> getUseBoxes(); } class TaintAnalysis extends ForwardFlowAnalysis<Unit, Set<Value>> { public Map<Unit, Set<Set<Value>>> taintedSinks; public TaintAnalysis(UnitGraph graph) { super(graph); taintedSinks = new HashMap(); doAnalysis(); } protected Set<Value> newInitialFlow() { return new HashSet(); } protected Set<Value> entryInitialFlow() { return new HashSet(); } protected void copy(Set<Value> src, Set<Value> dest) { dest.removeAll(dest); dest.addAll(src); } // Called after if/else blocks, with the result of the analysis from both // branches. protected void merge(Set<Value> in1, Set<Value> in2, Set<Value> out) { out.removeAll(out); out.addAll(in1); out.addAll(in2); } protected void flowThrough(Set<Value> in, Unit node, Set<Value> out) { Set<Value> filteredIn = stillTaintedValues(in, node); Set<Value> newOut = newTaintedValues(filteredIn, node); out.removeAll(out); out.addAll(filteredIn); out.addAll(newOut); System.out.println(in); System.out.println(node); if(isTaintedPublicSink(node, in)) { if(!taintedSinks.containsKey(node)) taintedSinks.put(node, new HashSet()); taintedSinks.get(node).add(in); } } protected Set<Value> stillTaintedValues(Set<Value> in, Unit node) { return in; } // It would be sweet if java had a way to duck type, but it doesn't so we have to do this. protected boolean containsValues(Collection<Value> vs, Object s) { for(Value v : vs) if(containsValue(v, s)) return true; return false; } protected boolean containsValue(Value v, Object s) { try { // I'm so sorry. Method m = s.getClass().getMethod("getUseBoxes"); for(ValueBox b : (Collection<ValueBox>) m.invoke(s)) if(b.getValue().equals(v)) return true; return false; } catch(Exception e) { return false; } } protected Set<Value> newTaintedValues(Set<Value> in, Unit node) { Set<Value> out = new HashSet(); if(containsValues(in, node)) { if(node instanceof AssignStmt) { out.add(((AssignStmt) node).getLeftOpBox().getValue()); } else if(node instanceof IfStmt) { IfStmt i = (IfStmt) node; if(i.getTarget() instanceof AssignStmt) out.add(((AssignStmt) i.getTarget()).getLeftOpBox().getValue()); } } else if(node instanceof AssignStmt) { AssignStmt assn = (AssignStmt) node; if(isPrivateSource(assn.getRightOpBox().getValue())) out.add(assn.getLeftOpBox().getValue()); } return out; } protected boolean isPrivateSource(Value u) { if(u instanceof VirtualInvokeExpr) { VirtualInvokeExpr e = (VirtualInvokeExpr) u; SootMethod m = e.getMethod(); if(m.getName().equals("readLine") && m.getDeclaringClass().getName().equals("java.io.Console")) return true; } return false; } protected boolean isTaintedPublicSink(Unit u, Set<Value> in) { if(u instanceof InvokeStmt) { InvokeExpr e = ((InvokeStmt) u).getInvokeExpr(); SootMethod m = e.getMethod(); if(m.getName().equals("println") && m.getDeclaringClass().getName().equals("java.io.PrintStream") && containsValues(in, e)) return true; } return false; } }
brucespang/taint-analysis
src/Taint.java
1,260
// It would be sweet if java had a way to duck type, but it doesn't so we have to do this.
line_comment
en
true
246575_2
package com.mapreduce; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; public class Wordcount { //This is the method for defining the MapReduce Driver public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { //Creates conf object which loads all the configuration parameters Configuration conf = new Configuration(); String otherArgs[] = new GenericOptionsParser(conf, args).getRemainingArgs(); Job job = new Job(conf, "Simple Wordcount job"); job.setJarByClass(Wordcount.class); //To set Mapper,Reduce and combiner classes job.setMapperClass(MyMapper.class); job.setCombinerClass(MyReducer.class); job.setReducerClass(MyReducer.class); //Output Key-Value data types Type job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); //To inform input output Formats to MapReduce Program job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); //Inform input and output File or Directory locations FileInputFormat.addInputPath(job, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); //Inform the job termination criteria System.exit(job.waitForCompletion(true) ? 0 : 1); } public static class MyMapper extends Mapper<LongWritable, Text, Text, IntWritable> { Text kword = new Text(); IntWritable vword = new IntWritable(); public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] tokens = line.split(" "); for (String token : tokens) { kword.set(token); vword.set(1); context.write(kword, vword); } } } public static class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for(IntWritable value : values) { sum = sum + value.get(); } context.write(key, new IntWritable(sum)); } } }
ActivecubesSolutions/cloudera-connector
Wordcount.java
797
//To set Mapper,Reduce and combiner classes
line_comment
en
true
246685_6
package operator.gene; import gene.Gene; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import ncbi.CachedPubmedAbstractDB; import ncbi.GeneInfoDB; import ncbi.GenePubMedDB; import ncbi.PubMedRecord; import operator.OperationFailedException; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import pipeline.Pipeline; import pipeline.PipelineObject; import buffer.TextBuffer; /** * Annotates variants with the PUBMED_SCORE property, which is computed by looking at pubmed abstracts * stored in a CachedPubmedAbstractDB * * @author brendan * */ public class PubmedRanker extends AbstractGeneAnnotator { //String constants for some XML properties we may use public static final String DISABLE_CACHE_WRITES = "disable.cache.writes"; public static final String GENE_INFO_PATH = "gene.info.path"; public static final String PUBMED_PATH = "pubmed.path"; public static final String NO_DOWNLOADS = "no.downloads"; CachedPubmedAbstractDB abstractDB = null; //DB for abstracts that we query GenePubMedDB geneToPubmed = null; //Look up pub med id's associated with a certain gene GeneInfoDB geneInfo = null; //Look up gene IDs for gene symbols TextBuffer termsFile = null; //Stores key terms we use to score pub med records (abstracts) Map<String, Integer> rankingMap = null; private boolean disableCacheWrites = false; //Disable writing of new variants to cache, useful if we have multiple instances running private int examined = 0; private int scored = 0; /** * If true, we write some progress indicators to system.out * @return */ protected boolean displayProgress() { return true; } public void performOperation() throws OperationFailedException { String disableStr = properties.get(DISABLE_CACHE_WRITES); if (disableStr != null) { Boolean disable = Boolean.parseBoolean(disableStr); disableCacheWrites = disable; } try { if (abstractDB == null) { String pathToPubmedDB = System.getProperty("user.home") + "/resources/gene2pubmed_human"; String pubmedAttr = this.getAttribute(PUBMED_PATH); if (pubmedAttr != null) { pathToPubmedDB = pubmedAttr; } abstractDB = CachedPubmedAbstractDB.getDB(pathToPubmedDB); String dlAttr = this.getAttribute(NO_DOWNLOADS); if (dlAttr != null) { Logger.getLogger(Pipeline.primaryLoggerName).info("Abstract ranker is setting prohibit downloads to : " + dlAttr); Boolean prohibitDLs = Boolean.parseBoolean(dlAttr); abstractDB.setProhibitNewDownloads(prohibitDLs); } } } catch (IOException e) { throw new IllegalStateException("IO error reading cached abstract db : " + e.getMessage()); } //Actually annotate the genes super.performOperation(); //Write map back to file when were done if (abstractDB != null && abstractDB.getMapSize() > 500) { try { abstractDB.writeMapToFile(); } catch (IOException e) { //Probably not a big deal, some abstracts won't get cached e.printStackTrace(); } } Logger.getLogger(Pipeline.primaryLoggerName).info(this.getObjectLabel() + " found " + scored + " hits in " + examined + " total genes"); } @Override public void annotateGene(Gene gene) { if (rankingMap == null) { try { buildRankingMap(); } catch (IOException e) { throw new IllegalStateException("IO error reading pubmed terms file : " + e.getMessage()); } } if (geneInfo == null) { try { String geneInfoPath = GeneInfoDB.defaultDBPath; String geneInfoAttr = this.getAttribute(GENE_INFO_PATH); if (geneInfoAttr != null) { geneInfoPath = geneInfoAttr; } geneInfo = GeneInfoDB.getDB(); if (geneInfo == null) geneInfo = new GeneInfoDB(new File(geneInfoPath)); } catch (IOException e) { throw new IllegalStateException("Error opening gene info file : " + e.getMessage()); } } String geneName = gene.getName(); if (geneName == null || geneName.startsWith("HLA-") || geneName.startsWith("MUC")) { return; } if (geneToPubmed == null) { try { String pubmedPath = System.getProperty("user.home") + "/resources/gene2pubmed_human"; String pubmedAttr = this.getAttribute(PUBMED_PATH); if (pubmedAttr != null) { pubmedPath = pubmedAttr; } geneToPubmed = GenePubMedDB.getDB(new File(pubmedPath)); } catch (IOException e) { throw new IllegalStateException("Error opening gene2pubmed file : " + e.getMessage()); } } String idStr = geneInfo.idForSymbolOrSynonym(geneName); if (idStr == null) { if (geneName.length() < 8) { if (! (geneName.startsWith("C") && geneName.contains("orf"))) System.err.println("Could not find gene id for symbol: " + geneName); } return; } Integer geneID = Integer.parseInt( idStr ); List<Integer> pubmedIDs = geneToPubmed.getPubMedIDsForGene(geneID); if (pubmedIDs == null) { //System.out.println("Found 0 ids for gene : " + geneName); return; } //Grab in batches of 500 if there are more than 500 List<PubMedRecord> records = new ArrayList<PubMedRecord>(Math.min(pubmedIDs.size(), 512)); int start = 0; int end = 500; while(start < pubmedIDs.size()) { //System.out.println("Fetching records from " + start + " to " + Math.min(pubmedIDs.size(), end) + " of " + pubmedIDs.size() + " total requested"); List<PubMedRecord> subrec = abstractDB.getRecordForIDs(pubmedIDs.subList(start, Math.min(pubmedIDs.size(), end)), disableCacheWrites); records.addAll(subrec); start = end; end += 500; } this.getPipelineOwner().fireMessage("Examining " + records.size() + " abstracts for gene : " + geneName); //System.out.println("Found " + records.size() + " records for " + pubmedIDs.size() + " ids for for gene : " + geneName); //We take the *maximum* score found among all abstracts int recordListSize = 10; List<ScoredRecord> scoredRecs = new ArrayList<ScoredRecord>(recordListSize); //Double maxScore = 0.0; //String maxHit = "-"; for(PubMedRecord rec : records) { if (rec != null) { Double abstractScore = computeScore( rec ); if (abstractScore > 0) { ScoredRecord sRec = new ScoredRecord(); sRec.score = abstractScore; sRec.rec = rec; scoredRecs.add(sRec); Collections.sort(scoredRecs, new ScoreComparator()); while (scoredRecs.size() > recordListSize) { scoredRecs.remove(scoredRecs.size()-1); } } } } examined++; Double finalScore = 0.0; if (scoredRecs.size() > 0) { for(int i=0; i<scoredRecs.size(); i++) { double weight = Math.exp(-0.25 * i); double rawScore = scoredRecs.get(i).score; double modScore = weight*rawScore; finalScore += modScore; } } if (finalScore > 0) scored++; gene.addProperty(Gene.PUBMED_SCORE, finalScore); if (scoredRecs.size() > 0) { PubMedRecord rec = scoredRecs.get(0).rec; String maxHit = rec.getTitle() + "," + rec.getCitation(); gene.addAnnotation(Gene.PUBMED_HIT, maxHit); } } /** * Compute a score * @param rec * @return */ private Double computeScore(PubMedRecord rec) { String title = rec.getTitle(); String abs = rec.getAbstract(); if (title != null) title = title.toLowerCase(); if (abs != null) abs = abs.toLowerCase(); double score = 0; for(String term : rankingMap.keySet()) { if (title != null && title.contains(term)) { score += 2.0*rankingMap.get(term); } if (abs != null && abs.contains(term)) { score += rankingMap.get(term); } } //Discount older papers Double mod = 1.0; Integer year = rec.getYear(); if (year != null) { int age = Calendar.getInstance().get(Calendar.YEAR) - year; if (age > 8) mod = 0.75; if (age > 12) { mod = 0.5; } } score *= mod; return score; } private void buildRankingMap() throws IOException { rankingMap = new HashMap<String, Integer>(); BufferedReader reader = new BufferedReader(new FileReader(termsFile.getAbsolutePath())); String line = reader.readLine(); while(line != null) { if (line.trim().length()==0 || line.startsWith("#")) { line = reader.readLine(); continue; } String[] toks = line.split("\t"); if (toks.length != 2) { System.err.println("Warning : could not parse line for pubmed key terms : " + line); line = reader.readLine(); continue; } Integer score = Integer.parseInt(toks[1].trim()); if (toks[0].trim().length()<2) { System.err.println("Warning : could not parse line for pubmed key terms : " + line); line = reader.readLine(); continue; } //System.err.println("Ranking map adding term: " + toks[0].trim().toLowerCase() + " score:" + score); rankingMap.put(toks[0].trim().toLowerCase(), score); line = reader.readLine(); } } public void initialize(NodeList children) { super.initialize(children); for(int i=0; i<children.getLength(); i++) { Node iChild = children.item(i); if (iChild.getNodeType() == Node.ELEMENT_NODE) { PipelineObject obj = getObjectFromHandler(iChild.getNodeName()); if (obj instanceof TextBuffer) { termsFile = (TextBuffer)obj; } } } } class ScoredRecord { PubMedRecord rec; double score; } class ScoreComparator implements Comparator<ScoredRecord> { @Override public int compare(ScoredRecord arg0, ScoredRecord arg1) { if (arg0.score == arg1.score) return 0; if (arg0.score < arg1.score) return 1; else return -1; } } }
brendanofallon/Pipeline
src/operator/gene/PubmedRanker.java
3,056
//Disable writing of new variants to cache, useful if we have multiple instances running
line_comment
en
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
246754_0
import SentiGraph.Graph; import java.io.*; import java.util.*; /** * Created with IntelliJ IDEA. * User: dave * Date: 23/02/14 * Time: 11:59 * To change this template use File | Settings | File Templates. */ public class Resource { public String Path; public HashMap<String,Integer> Frecuency; public HashMap<String,ArrayList<String>> Link; private BufferedWriter _writerFrec; private BufferedWriter _writerLink; public Resource(String path) throws IOException { Path = path; Frecuency = new HashMap<String, Integer>(); Link = new HashMap<String, ArrayList<String>>(); _writerFrec = new BufferedWriter(new FileWriter(Path+".frec")); _writerLink = new BufferedWriter(new FileWriter(Path+".link")); } public Integer Increment(String Lemma){ if(Frecuency.containsKey(Lemma)) return Frecuency.put(Lemma,Frecuency.get(Lemma)+1); Link.put(Lemma,new ArrayList<String>()); return Frecuency.put(Lemma,1); } public boolean AddLink(String Lemma, String other){ return Link.get(Lemma).add(other); } public void Save() throws IOException { for (String key:Frecuency.keySet()) _writerFrec.write(String.format("%1$s:%2$s\r\n",key,Frecuency.get(key))); _writerFrec.close(); for (String key:Link.keySet()){ _writerLink.write(String.format("%1$s:",key)); for (String val:Link.get(key)) _writerLink.write(String.format("%1$s;",val)); _writerLink.write("\r\n"); } _writerLink.close(); } public Graph getGraph() { Graph graph = new Graph(0); for (String s:Frecuency.keySet()) graph.AddNode(s); for (String s:Frecuency.keySet()) for (String ss:Link.get(s)) graph.AddEdge(s,ss,1); return graph; } }
cuza/SemEval_2014_OSX
src/Resource.java
541
/** * Created with IntelliJ IDEA. * User: dave * Date: 23/02/14 * Time: 11:59 * To change this template use File | Settings | File Templates. */
block_comment
en
true
246808_0
/* * TEALsim - MIT TEAL Project * Copyright (c) 2004 The Massachusetts Institute of Technology. All rights reserved. * Please see license.txt in top level directory for full license. * * http://icampus.mit.edu/teal/TEALsim * * $Id: Graph.java,v 1.9 2009/04/24 19:35:52 pbailey Exp $ * */ package teal.plot; import java.util.*; import teal.core.TUpdatable; import teal.sim.TSimElement; import tealsim.gamification.GamificationAgent; public class Graph extends teal.plot.ptolemy.Plot implements TUpdatable, TSimElement { private static final long serialVersionUID = 3761131530906252082L; protected Collection<PlotItem> plotItems; protected GamificationAgent gamification; public Graph() { super(); plotItems = new ArrayList<PlotItem> (); } public synchronized void addPlotItem(PlotItem pi) { if (!plotItems.contains(pi)) { plotItems.add(pi); } } public synchronized void removePlotItem(PlotItem pi) { if (plotItems.contains(pi)) { plotItems.remove(pi); } } public void update() { Iterator it = plotItems.iterator(); while (it.hasNext()) { PlotItem pi = (PlotItem) it.next(); pi.doPlot(this); } repaint(); Thread.yield(); } }
JoeyPrink/TEALsim
src/teal/plot/Graph.java
393
/* * TEALsim - MIT TEAL Project * Copyright (c) 2004 The Massachusetts Institute of Technology. All rights reserved. * Please see license.txt in top level directory for full license. * * http://icampus.mit.edu/teal/TEALsim * * $Id: Graph.java,v 1.9 2009/04/24 19:35:52 pbailey Exp $ * */
block_comment
en
true
246834_2
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:mccallum@cs.umass.edu">mccallum@cs.umass.edu</a> */ package mstparser; import java.util.ArrayList; import java.util.HashMap; import java.io.*; import java.util.Iterator; public class Alphabet implements Serializable { public gnu.trove.TObjectIntHashMap map; public int numEntries; public gnu.trove.TIntObjectHashMap featureMap; // public HashMap<Integer, String> featureMap; boolean growthStopped = false; public Alphabet (int capacity) { this.map = new gnu.trove.TObjectIntHashMap (capacity); this.featureMap = new gnu.trove.TIntObjectHashMap(); this.featureMap.clear(); //this.map.setDefaultValue(-1); numEntries = 0; } public Alphabet () { this (10000); } /** Return -1 if entry isn't present. */ public int lookupIndex (Object entry) { if (entry == null) { throw new IllegalArgumentException ("Can't lookup \"null\" in an Alphabet."); } int ret = map.get(entry); if (ret == -1 && !growthStopped) { ret = numEntries; map.put (entry, ret); featureMap.put(ret, (String)entry); numEntries++; } return ret; } public Object[] toArray () { return map.keys(); } public boolean contains (Object entry) { return map.contains (entry); } public int size () { return numEntries; } public void stopGrowth () { growthStopped = true; map.compact(); } public void allowGrowth () { growthStopped = false; } public boolean growthStopped () { return growthStopped; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeInt (numEntries); out.writeObject(map); out.writeObject(featureMap); out.writeBoolean (growthStopped); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); numEntries = in.readInt(); map = (gnu.trove.TObjectIntHashMap)in.readObject(); System.out.println("map: " + map.size()); featureMap = (gnu.trove.TIntObjectHashMap)in.readObject(); System.out.println("feature map: " + featureMap.size()); // if (featureMap.size() > 10000) { // for (int i=10; i<20; i++) // System.err.println(featureMap.get(i)); // } growthStopped = in.readBoolean(); } }
intfloat/TextLevelDiscourseParser
mstparser/Alphabet.java
871
// public HashMap<Integer, String> featureMap;
line_comment
en
true
246972_45
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package domain; import java.util.ArrayList; /** * * @author diego vega rodriguez B78225 * */ public class CleanCode { //Los nombres de los metodos deben contener un verbo los de las variables deben ser un sustantivo //Ejemplo 1 //Use Intention-Revealing Names Pag.18 //El nombre de la variable o el metodo debe de responder al porque de su existencia y al para que se va usar public int divide() { int resultado = 0; //incorrecto int n = 30; int d = 2; //correcto int numero = 30; int divisor = 2; return resultado = (numero / divisor); } //Ejemplo 2 //Avoid Disinformation Pag.19 //si se esta hablando de varios objetos del mismo tipo en un arreglo como por ejemplo un arreglo con razas de perros //no es necesario pornerle listDogRaces con ponerle dogRaces es suficiente ya que podria crear un mal entendido al no ser una lista public void readDogRaces() { //incorrecto String[] listDogRaces = new String[3]; //correcto String[] dogRaces = new String[3]; for (int i = 0; i < 10; i++) { System.out.println(dogRaces[i]); } } //Ejemplo 3 //Use Pronounceable Names Pag.21 //No usar abreviaciones ya que son poco informativas //No usar variables muy similares ya que puede ser confuso public int calculaSueldo() { int resultado = 0; //incorrecto int sph = 9000; int h = 8; //correcto int sueldoPorHora = 9000; int horas = 8; return resultado = sueldoPorHora * horas; } //Ejemplo 4 //Avoid Encodings Pag.23 // si la variable se va a usar varias veces en el metodo es preferible ponerle un nombre que sea facil de buscar ya que //algunas veces es dificil localizar la variable entre lineas y peor si hay alguna con un nombre similar por lo que seria //mejor usar nombre de variables capaces de diferenciar de la una a la otra public double calculateAverageHoursPerWeek() { double averageHours = 0; //incorrecto int extraHours = 6; int lunchHours = 2; int h = 8; int days = 6; int hoursWeek = 0; //correcto int extraHoursPerWeek = 6; int lunchHoursPerDay = 2; int hoursPerWeek = 0; int DAYS_PER_WEEK = 6; int hours = 8; hoursPerWeek = ((hours + extraHoursPerWeek) * DAYS_PER_WEEK) - (lunchHoursPerDay * DAYS_PER_WEEK); averageHours = (hoursPerWeek / DAYS_PER_WEEK) * 100; return averageHours; } //Ejemplo 5 //Member Prefixes Pag.24 //no es necesario utilizar prefijos en los nombres de las claces o variables, ya deben de ser lo suficientemente sencillas para no tener que utilizarlos public class player { //incorrecto String p_name; String p_description; String t_name; //correcto String PlayerName; String description; String teamName; void setDescription(String PlayerName, String description, String teamName) { this.PlayerName = PlayerName; this.description = description; this.teamName = teamName; } } //Ejemplo 6 // se debe identar bien para llevar un mayor orden y para que otra persona pueda entener mejor nuestro codigo //incorrecto public void identingBad() { int id = 12; String name = "Diego"; String apellido = "Vega"; int edad = 22; } //correcto public void identingGood() { int id = 12; String name = "Diego"; String apellido = "Vega"; int edad = 22; } //Ejemplo 7 //Do one thing Pag.35 //No utilizar un metodo para dos diferenres propositos //incorrect public double[] calculateAverageHoursPerWeekFillArray(double averageHours, int extraHoursPerWeek, int lunchHoursPerDay, int hoursPerWeek, int DAYS_PER_WEEK, int hours) { double[] averageHoursArray = new double[6]; hoursPerWeek = ((hours + extraHoursPerWeek) * DAYS_PER_WEEK) - (lunchHoursPerDay * DAYS_PER_WEEK); averageHours = (hoursPerWeek / DAYS_PER_WEEK) * 100; for (int i = 0; i < averageHoursArray.length; i++) { averageHoursArray[i] = averageHours; } return averageHoursArray; } //correct public void calculateAverageHoursPerWeek(double averageHours, int extraHoursPerWeek, int lunchHoursPerDay, int hoursPerWeek, int DAYS_PER_WEEK, int hours) { hoursPerWeek = ((hours + extraHoursPerWeek) * DAYS_PER_WEEK) - (lunchHoursPerDay * DAYS_PER_WEEK); averageHours = (hoursPerWeek / DAYS_PER_WEEK) * 100; fillArrayPerAverageHoursPerWeek(averageHours); } public double[] fillArrayPerAverageHoursPerWeek(double averageHours) { double[] averageHoursArray = new double[6]; for (int i = 0; i < averageHoursArray.length; i++) { averageHoursArray[i] = averageHours; } return averageHoursArray; } //Ejemplo 8 //Use Descriptive Names Pag.39 //usar nombres que que describan bien la funcion no importa que tan largo sea el nombre public void fill() { } public void fillArrayOfCitiesNames() { } //Ejemplo 9 //Argument Objects Pag.43 //Intentar usar mas argumentos de lo necesario //incorrect public void addEmployee(String name, String firstName, String lastName, int id) { } //correct public void addEmployee(String fulltName, int id) { } //Ejemplo 10 //Structured Programming Pag.48 //cada funcion debetener una salida por lo tanto debe de tener un retun al menos en un ciclo //por lo que no se debe usar break ni continue //incorrecto public int devuelveUltimoDigito(int numero) { //incorrecto while (true) { numero = numero/10; if (numero < 10) { break; } } //correcto while (true) { numero = numero/10; if (numero < 10) { return numero; } } } }
UCR-Paraiso-Lenguajes/Lenguajes-1-12019
Tarea_2/CleanCode.txt
1,748
//Argument Objects Pag.43
line_comment
en
true
247061_10
/* *@author Chau Siu Hong 20186650 */ /*date created 24/12/2023 */ import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; public class Reminder { //method public static void Reminder(){ try{ JFrame frame = new JFrame(); frame.setSize(350,300); frame.setLocation(500,300); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);// It is necessary /*Create a Panel*/ JPanel panel = new JPanel();//It create a Panel frame.add(panel); // Add the panel ReminderP(panel); // Design the Panel + use the method frame.setVisible(true); }catch(Exception e){} } public static void ReminderP(JPanel panel){ panel.setLayout(null); //create bookmark //label JLabel bookmarkLabel = new JLabel("Please input your study plan"); bookmarkLabel.setBounds(50,20,200,25); panel.add(bookmarkLabel); JLabel contentLabel = new JLabel("Content:"); contentLabel.setBounds(50,50,100,25); panel.add(contentLabel); JLabel exptimeLabel = new JLabel("Expected time:"); exptimeLabel.setBounds(50,80,100,25); panel.add(exptimeLabel); JLabel expYLabel = new JLabel("(yyyy)"); expYLabel.setBounds(140, 100, 30, 25); panel.add(expYLabel); JLabel expMLabel = new JLabel("(m/mm)"); expMLabel.setBounds(190,100,40,25); panel.add(expMLabel); JLabel expDLabel = new JLabel("(d/dd)"); expDLabel.setBounds(245,100,40,25); panel.add(expDLabel); JLabel slash1 = new JLabel("/"); slash1.setBounds(180,80,20,25); panel.add(slash1); JLabel slash2 = new JLabel("/"); slash2.setBounds(235,80,20,25); panel.add(slash2); //textbox to input JTextField content = new JTextField(20); content.setBounds(100,50,100,25); panel.add(content); JTextField expyear = new JTextField(20); expyear.setBounds(140,80,40,25); panel.add(expyear); JTextField expmonth = new JTextField(20); expmonth.setBounds(190,80,40,25); panel.add(expmonth); JTextField expdate = new JTextField(20); expdate.setBounds(240,80,40,25); panel.add(expdate); //button to create JButton Create = new JButton("Create"); Create.setBounds(100,160,100,25); Create.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event){ try{ String c = content.getText(); String y = expyear.getText(); String m = expmonth.getText(); String d = expdate.getText(); if ((c.isEmpty()) && (y.isEmpty()) && (m.isEmpty()) && (d.isEmpty())){ JOptionPane.showMessageDialog(null,"Invalid input!Please input again!"); }else{ String text = content.getText() + "," + expyear.getText() + "/" + expmonth.getText() + "/" + expdate.getText(); Storage.TextFileInput("reminder.txt", text); JOptionPane.showMessageDialog(null,"You create a bookmark Successfully!"); String count = Storage.TextFileRead("RCount.txt"); //Read the number from the RCount.txt int n = Integer.parseInt(count); n = n + 1; Storage.TextFileDelete("RCount.txt"); // Delete the old file Storage.TextFileInput("RCount.txt",Integer.toString(n)); } }catch(Exception e){} } }); panel.add(Create); } public static String[] CheckBookmark() { //check the created bookmarks(read the file) ArrayList<String> AList = new ArrayList<String>(); // arraylist try{ BufferedReader bufferReader = new BufferedReader(new FileReader("reminder.txt")); // while loop to read file as string lines, until end (null string) String strLine; while ((strLine = bufferReader.readLine()) != null) { // read a line AList.add(strLine); // add read string line data to arraylist } bufferReader.close(); //close the stream } catch (IOException ioE){ } // Convert ArrayList to String array return AList.toArray(new String[AList.size()]); } public static void main(String[] args){ Reminder(); } }
HKU-Space-Engineering/Group
Reminder.java
1,184
//textbox to input
line_comment
en
true
247187_0
/*Here are the changes made: Fixed the import statements. Corrected the main method's parameter declaration from public static void main(Strings[] args) to public static void main(String[] args). Corrected the array declaration from int Associate[] ass = int Associate[5]; to Associate[] ass = new Associate[5];. Corrected the data type for String from string in both the Associate class and the main method. Fixed the missing semicolons in various places. Corrected the getExp method in the Associate class from getExp(int exp) to setExp(int exp) for setting the exp field. */ import java.util.Arrays; import java.util.Scanner; public class Solution { public static void main(String[] args) { Associate[] ass = new Associate[5]; Scanner sc = new Scanner(System.in); for (int i = 0; i < 5; ++i) { ass[i] = new Associate(sc.nextInt(), sc.next(), sc.next(), sc.nextInt()); } String searchTech = sc.next(); sc.close(); Associate[] result = method1(ass, searchTech); for (int i = 0; i < result.length; i++) { System.out.println(result[i].getId()); } } public static Associate[] method1(Associate[] ass, String searchTech) { Associate[] arr1 = new Associate[0]; for (int i = 0; i < ass.length; i++) { if (ass[i].getTech().equals(searchTech) && ass[i].getExp() % 5 == 0) { arr1 = Arrays.copyOf(arr1, arr1.length + 1); arr1[arr1.length - 1] = ass[i]; } } return arr1; } } class Associate { private int id; private int exp; private String name; private String tech; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTech() { return tech; } public void setTech(String tech) { this.tech = tech; } public int getExp() { return exp; } public void setExp(int exp) { this.exp = exp; } public Associate(int id, String name, String tech, int exp) { this.id = id; this.name = name; this.tech = tech; this.exp = exp; } }
ANUNAY-NALAM/Code_in_Java
pra1.java
644
/*Here are the changes made: Fixed the import statements. Corrected the main method's parameter declaration from public static void main(Strings[] args) to public static void main(String[] args). Corrected the array declaration from int Associate[] ass = int Associate[5]; to Associate[] ass = new Associate[5];. Corrected the data type for String from string in both the Associate class and the main method. Fixed the missing semicolons in various places. Corrected the getExp method in the Associate class from getExp(int exp) to setExp(int exp) for setting the exp field. */
block_comment
en
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
247608_1
/* created to test ActionListener */ package Java_Problems; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * * @author tph */ public class Control_Circle extends JFrame{ private JButton b1=new JButton("Enlarge"); private JButton b2=new JButton("Shrink"); Circle c=new Circle(); public Control_Circle() { JPanel p=new JPanel(); p.add(b1); p.add(b2); this.add(c,BorderLayout.CENTER); this.add(p,BorderLayout.SOUTH); b1.addActionListener(new EnlargeListener()); b2.addActionListener(new ShrinkListener()); } public static void main(String[] args) { JFrame frame=new Control_Circle(); frame.setTitle("Controlling Circle's size"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500,500); frame.setLocationRelativeTo(null); frame.setVisible(true); } class EnlargeListener implements ActionListener //Must have class in order to write Action Event { public void actionPerformed(ActionEvent e) { c.enlarge(); } } class ShrinkListener implements ActionListener { public void actionPerformed(ActionEvent e) { c.shrink(); } } class Circle extends JPanel { private int radius=5; protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawOval((getWidth()/2)-radius, (getHeight()/2)-radius, 2*radius, 2*radius); } public void enlarge() { radius+=10; repaint(); } public void shrink() { radius-=10; repaint(); } } }
thapyayhmuTP/Java_Problems
Control_Circle.java
423
/** * * @author tph */
block_comment
en
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
247832_5
package javabot.RaynorsRaiders; import java.util.LinkedList; import javabot.JNIBWAPI; import javabot.types.*; import javabot.types.UnitType.UnitTypes; import javabot.util.*; import javabot.model.*; public class CoreReactive extends RRAITemplate { //Data structs LinkedList<BuildAlert> core_econ_buildAlerts; int defcon, agressiveCountdown; public enum BuildAlert { NO_MINERALS, NO_GAS, NO_ROOM, NO_WORKERS }; /* Here is our constructor */ public CoreReactive() { core_econ_buildAlerts = new LinkedList<BuildAlert>(); } /* This is to be run during setup, currently its a basic loadout of units to create */ public void setup() { //System.out.println("CoreReactive Online"); } public void startUp() { agressiveCountdown = baby.campaign; } /* This is to be run frequently, and is the quick-decider for things such as resources */ public void checkUp() { if (agressiveCountdown-- >= 0) { if(defcon-- <= 0) { if (baby.genomeSetting.defensiveness > (int) (Math.random() * 100)) { Unit targetUnit = bwapi.getUnit(info.scouter.getNearestUnit(UnitTypes.Protoss_Zealot.ordinal(), builder.homePositionX, builder.homePositionY)); military.unitOperation(20, targetUnit.getX(), targetUnit.getY()); } defcon = baby.genomeSetting.bloodFrequency * 5; } } } public void debug() { // Need to put core Reactive debug here } public void econ_sendBuildAlert(BuildAlert alert) { core_econ_buildAlerts.add(alert); } public LinkedList<Unit> gen_findUnits(UnitTypes input) { LinkedList<Unit> listToBuild = new LinkedList<Unit>(); UnitType searchFor = bwapi.getUnitType(input.ordinal()); for(Unit unit : bwapi.getMyUnits()) { if(unit.getTypeID() == searchFor.getWhatBuildID()) { listToBuild.add(unit); } } return listToBuild; } public Region gen_findClosestRegion(Integer d_x, Integer d_y) { Region winningRegion = null; Double distanceFromWinning; Double distanceFromWorking; for (Region workingRegion : bwapi.getMap().getRegions()) { if (winningRegion != null) { distanceFromWinning = Math.sqrt( Math.pow(Math.abs(d_x - winningRegion.getCenterX()), 2) + Math.pow(Math.abs(d_y - winningRegion.getCenterY()), 2) ); distanceFromWorking = Math.sqrt( Math.pow(Math.abs(d_x - workingRegion.getCenterX()), 2) + Math.pow(Math.abs(d_y - workingRegion.getCenterY()), 2) ); if (distanceFromWorking < distanceFromWinning) { winningRegion = workingRegion; } } else { winningRegion = workingRegion; } } return winningRegion; } }
nclarke/RaynorsRaiders
CoreReactive.java
871
// Need to put core Reactive debug here
line_comment
en
true
247875_19
package data; import java.awt.Point; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import java.util.Vector; import macro.LogoutException; import memo.InternalMemo; import memo.MemoProcessor; import party.SocialMacro; import window.HaltThread; import window.PWindow; import window.WindowThread; import arena.Arena; import combat.CombatStyle; import combat.Healer; import combat.SpellInstance; import control.Computer; import control.MustaphaMond; import control.Network; import control.ProfileStatus; import control.TimeLog; public class Profile implements Comparable<Profile> { static final String PROFILE_DIR = "profile/"; public static String dir() { return PROFILE_DIR; } //Maintains a list of all local profiles read from file static final ArrayList<Profile> localProfiles = new ArrayList<Profile>(); public static ArrayList<Profile> getLocalProfiles(Config config) { if(localProfiles.isEmpty()) { String s = PROFILE_DIR + config.getComputer()+"/"; for(File f : new File(s).listFiles()) { localProfiles.add(new Profile(f)); } } return localProfiles; } private static final int VERSION = 7; private String name; public String getName() { return name; } private String poeName; public String getPoeName() { return poeName; } //Log in information private String email; public String getEmail() { return email; } private String password; public String getPassword() { return password; } //Character class private CombatStyle combatStyle; public CombatStyle getCombatStyle() { return combatStyle; } //When logged in, which character position it is in on the list (0-offset) private int indexOnList; public int getIndexOnList() { return indexOnList; } //Character level private int level; public int getLevel() { return level; } private Point twilightSellPoint; public Point getTwilightSellPoint() { return twilightSellPoint; } //What potions this character holds (only type is significant) private static final int NUM_POTIONS = 5; public int getNumPotions() { return NUM_POTIONS; } private Potion[] potions = new Potion[NUM_POTIONS]; public Potion getPotions(int index) { return potions[index]; } public void usePotion(PWindow window, Potion p) { Potion.usePotion(window, potions, p); } public void useHealingPotion(PWindow window) { Potion.useHealingPotion(window, potions); } public void useManaPotion(PWindow window) { Potion.useManaPotion(window, potions); } /** * * Returns the indices of all potions of a certain type * * @param type * @return */ public ArrayList<Integer> getPotions(Potion type) { ArrayList<Integer> matchingPots = new ArrayList<Integer>(); for(int a = 0; a < potions.length; a++) { if(potions[a] == type) { matchingPots.add(a + 1); } } return matchingPots; } private int healingHealth; public int getHealingHealth() { return healingHealth; } private int criticalHealth; public int getCriticalHealth() { return criticalHealth; } private static final long NO_START = -1L; private long startTime = NO_START; //since it has yet to start private static final long MAX_PLAYTIME_PER_DAY = 1000 * 60 * 60 * 12; //Change to 6 later public boolean isAvailable() { System.out.println("Status for "+name+" is "+status); return status == ProfileStatus.IDLE; } /** @return : Time the profile has been active */ public long sessionTime() { return startTime == NO_START ? 0 : System.currentTimeMillis() - startTime; } private EventLog eventLog = new EventLog(); public void logsOut(Config config) { eventLog.addEvent(EventType.LOGOUT); if(eventLog.numberOfEvents(EventType.LOGOUT, 5 * 60 * 1000) > 15) { System.err.println("Logging out Frequently"); config.emailNotification("Logging Out Frequently"); } } private ProfileStatus status = ProfileStatus.IDLE; public ProfileStatus getStatus() { return status; } public void setStatus(ProfileStatus status) { this.status = status; } private Computer comp = null; public Computer getComputer() { return comp; } //what computer this is running on, if any public void setComputer(Computer comp) { this.comp = comp; } //Lower number is higher priority to run private int priority; public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } //could use a more robust api public static void savePriorities(Network network) { try { BufferedWriter buff = new BufferedWriter(new FileWriter(MustaphaMond.getPrioritiesFile())); Vector<Profile> profiles = network.getProfiles(); Collections.sort(profiles); for(Profile prof : profiles) { buff.write(prof.name); buff.newLine(); } buff.close(); } catch(IOException e) { } } private ArrayList<InternalMemo> memos = new ArrayList<InternalMemo>(); public void receiveMemo(InternalMemo im) { memos.add(im); } public void processMemos(Network network, PWindow window) { for(InternalMemo memo : memos) { MemoProcessor.process(network, window, this, memo); } memos.clear(); } private Profile friend = null; public void setFriend(Profile friend) { System.out.println("Setting friend of "+name+" to "+friend.name); this.friend = friend; } public Profile getFriend() { return friend; } public String getDescription() { if(friend != null) { return "(Partied With: "+friend+")"; } return ""; } public void reparty(PWindow window) { if(friend != null) { SocialMacro.inviteToParty(window, friend); } } /* //Used for determining whether this character should go into the portal (as a waiter) private boolean portalOpen = false; public void markPortalOpen() { portalOpen = true; } public void markPortalClosed() { portalOpen = false; } public boolean isPortalOpen() { return portalOpen; } */ /** Clears out all existing arenas and replaces it with this one */ public void changeArena(final Arena arena) { arenas.clear(); arenas.add(arena); } //What Arenas this character is allowed to have access to private ArrayList<Arena> arenas = new ArrayList<Arena>(); private boolean hasMana = false; public void foundManaBar() { hasMana = true; } public boolean hasMana() { return hasMana; } /** * * Gets an available arena based on when it was last visited * If no arenas are available, it will hang until there is one available * * @return */ public Arena getAvailableArena() { int rndIndex = new Random().nextInt(arenas.size()); return arenas.get(rndIndex); } @Override public String toString() { return name; } public boolean fight(PWindow window, Arena arena, WindowThread thread, Healer healer) throws LogoutException, HaltThread { return combatStyle.fight(window, arena, thread, healer); } public void useAuras(PWindow window) { combatStyle.useAuras(window); } /* public void turnOffAuras(PWindow window) { combatStyle.turnOffAuras(window); } */ public void pickUpItems(PWindow window, WindowThread thread, Healer healer) throws LogoutException, HaltThread { combatStyle.pickUpItems(window, thread, healer); } public void shootEverywhere(PWindow window, Healer healer) throws LogoutException { combatStyle.shootEverywhere(window, healer); } public void castDecoyTotem(PWindow window) { combatStyle.castDecoyTotem(window); } public void castAttackTotem(PWindow window) { combatStyle.castAttackTotem(window); } public boolean castPortal(PWindow window) { return combatStyle.castPortal(window); } public double attack(PWindow window, Point p) { return combatStyle.attack(window, p); } //Loads a profile from the file public Profile(File f) { readName(f); //based on filename Queue<String> lines = new LinkedList<String>(); Data.readLines(f, lines); readVersion(f, lines); readPoeName(lines); readLoginInfo(lines); //email and password readIndexOnList(lines); readLevel(lines); readPotions(lines); ArrayList<SpellInstance> spells = new ArrayList<SpellInstance>(); readSpells(lines, spells); readClass(lines, spells); readArenas(lines); readHealing(lines); readTwilightSellPoint(lines); //readHome(lines); //unused at the moment } private void readName(File f) { name = f.getName().split("\\.")[0]; } private void readPoeName(Queue<String> lines) { poeName = lines.poll(); } //Each read method dequeues as it processes private void readVersion(File f, Queue<String> lines) { //# int version = Integer.parseInt(lines.poll()); if(version != VERSION) { System.err.println("File "+f.getName()+" is of version "+version+". Update to Version "+VERSION+"."); System.exit(1); } } private void readLoginInfo(Queue<String> lines) { email = lines.poll(); password = lines.poll(); } private void readClass(Queue<String> lines, ArrayList<SpellInstance> spells) { combatStyle = CombatStyle.fromString(lines.poll(), spells); } private void readIndexOnList(Queue<String> lines) { //# indexOnList = Integer.parseInt(lines.poll()); } private void readLevel(Queue<String> lines) { //# level = Integer.parseInt(lines.poll()); } private void readPotions(Queue<String> lines) { //{Potion}, {Potion}, etc. String[] potions = lines.poll().split(","); for(int a = 0; a < NUM_POTIONS; a++) { this.potions[a] = Potion.fromString(potions[a]); } } private void readSpells(Queue<String> lines, ArrayList<SpellInstance> spells) { //Spell:Key:Freq, (decimal) //Spell:Key:Freq, //... //Spell:Key:Freq; boolean isTerminal = false; while(!isTerminal) { String line = lines.poll(); isTerminal = line.endsWith(";"); line = line.substring(0, line.length() - 1); //cut off last character String[] components = line.split(":"); for(int a = 0; a < components.length; a++) { components[a] = components[a].trim(); } if(components[0].endsWith("+")) //Marks it to use { components[0] = components[0].substring(0, components[0].length() - 1); spells.add(new SpellInstance(components)); } } } private void readArenas(Queue<String> lines) { //#represents level of difficulty, 0-2 //Arena#, //Arena#, //... //Arena#; while(true) { String line = lines.poll(); boolean isTerminal = line.endsWith(";"); line = line.substring(0, line.length() - 1); //cut off last character arenas.add(Arena.fromString(line)); //assume we have yet to visit each location if(isTerminal) break; } } private void readHealing(Queue<String> lines) { //# Healing followed by Critical (Lower is more health) //# //# healingHealth = Integer.parseInt(lines.poll()); criticalHealth = Integer.parseInt(lines.poll()); } private void readTwilightSellPoint(Queue<String> lines) { //# Healing followed by Critical (Lower is more health) //# //# twilightSellPoint = new Point(PWindow.getWidth() / 2, Integer.parseInt(lines.poll())); } @Override public int compareTo(Profile otherProfile) { return (priority - otherProfile.priority); } }
seokhohong/PathOfExile
src/data/Profile.java
3,516
//based on filename
line_comment
en
false
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
248191_0
import java.io.Serializable; import java.util.List; public class Token implements Serializable { String request; Integer sender; Integer receiver; @Override public String toString() { return request; } public void setReceiver(Integer receiver) { this.receiver = receiver; } public void setSender(Integer sender) { this.sender = sender; } class Join extends Token { final int port; public Join(int port){ this.port = port; this.request = joinRequest(port); } private String joinRequest(int port) { StringBuilder req = new StringBuilder(); req.append("JOIN ").append(port); return req.toString(); } } class Details extends Token { final List<Integer> ports; // List of port number (aka. identifiers) public Details(List<Integer> ports){ this.ports = ports; this.request = detailsRequest(ports); } private String detailsRequest(List<Integer> ports) { StringBuilder req = new StringBuilder(); req.append("DETAILS "); ports.forEach(p -> req.append(p).append(" ")); return req.toString(); } } class VoteOptions extends Token { final List<String> voteOptions; // List of voting options for the consensus protocol VoteOptions(List<String> voteOptions) { this.voteOptions = voteOptions; this.request = voteOptionsRequest(voteOptions); } private String voteOptionsRequest(List<String> voteOptions) { StringBuilder req = new StringBuilder(); req.append("VOTE_OPTIONS "); voteOptions.forEach(v -> req.append(v).append(" ")); return req.toString(); } } class Votes extends Token { final List<SingleVote> votes; Votes(List<SingleVote> votes) { this.votes = votes; this.request = voteRequest(votes); } private String voteRequest(List<SingleVote> votes) { StringBuilder req = new StringBuilder(); req.append("VOTE "); //VOTE port i vote 1 port 2 vote 2 ...port n vote n votes.forEach(vote -> req.append(vote.getParticipantPort()).append(" ").append(vote.getVote()).append(" ")); return req.toString(); } } class Outcome extends Token { final String outcome; final List<Integer> participants; Outcome(String outcome, List<Integer> participants) { this.outcome = outcome; this.participants = participants; this.request = outcomeRequest(outcome, participants); } //OUTCOME A 12346 12347 12348 private String outcomeRequest(String outcome, List<Integer> participants) { StringBuilder req = new StringBuilder(); req.append("OUTCOME ").append(outcome).append(" "); participants.forEach(p -> req.append(p).append(" ")); return req.toString(); } } public static void sleep(long millis){ try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } public static void log(Object o){ System.out.println(o.toString()); } } class SingleVote implements Serializable { private final int participantPort; private final String vote; public SingleVote(int participantPort, String vote) { this.participantPort = participantPort; this.vote = vote; } public int getParticipantPort() { return participantPort; } public String getVote() { return vote; } @Override public String toString() { return "<" + participantPort + ", " + vote + ">"; } }
ejupialked/consensus-protocol
src/Token.java
845
// List of port number (aka. identifiers)
line_comment
en
true
248410_0
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Models; /** * * @author m4rkm3n */ public class Bills { private int bill_id; private int bill_cid; private int bill_num; private String issuedate; private String duedate; private int unit_cost; private int total_cost; private int units_consumed; private int after_due_date; private String bill_status; private int fc_surcharge; private int ptv_fee; private int gst; private int electricity_duty; public int getBill_id() { return bill_id; } public void setBill_id(int bill_id) { this.bill_id = bill_id; } public int getBill_cid() { return bill_cid; } public void setBill_cid(int bill_cid) { this.bill_cid = bill_cid; } public int getBill_num() { return bill_num; } public void setBill_num(int bill_num) { this.bill_num = bill_num; } public String getIssuedate() { return issuedate; } public void setIssuedate(String issuedate) { this.issuedate = issuedate; } public String getDuedate() { return duedate; } public void setDuedate(String duedate) { this.duedate = duedate; } public int getUnit_cost() { return unit_cost; } public void setUnit_cost(int unit_cost) { this.unit_cost = unit_cost; } public int getTotal_cost() { return total_cost; } public void setTotal_cost(int total_cost) { this.total_cost = total_cost; } public int getUnits_consumed() { return units_consumed; } public void setUnits_consumed(int units_consumed) { this.units_consumed = units_consumed; } public int getAfter_due_date() { return after_due_date; } public void setAfter_due_date(int after_due_date) { this.after_due_date = after_due_date; } public String getBill_status() { return bill_status; } public void setBill_status(String bill_status) { this.bill_status = bill_status; } public int getFc_surcharge() { return fc_surcharge; } public void setFc_surcharge(int fc_surcharge) { this.fc_surcharge = fc_surcharge; } public int getPtv_fee() { return ptv_fee; } public void setPtv_fee(int ptv_fee) { this.ptv_fee = ptv_fee; } public int getGst() { return gst; } public void setGst(int gst) { this.gst = gst; } public int getElectricity_duty() { return electricity_duty; } public void setElectricity_duty(int electricity_duty) { this.electricity_duty = electricity_duty; } }
OsamaMahmood/BillManagementSystem
src/Models/Bills.java
802
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */
block_comment
en
true
248463_1
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DAO; import DTO.CategoryDTO; import java.io.FileNotFoundException; import java.util.List; import mapper.CategoryMapper; /** * * @author Thuan Vo */ public class CategoryDAO extends AbstractDAO<CategoryDTO> { public CategoryDTO getByIdDuty(int id_duty) { CategoryDAO category = new CategoryDAO(); String sql = "SELECT * FROM `danhmuc` WHERE id_duty = ?"; List<CategoryDTO> temp = category.query(sql, new CategoryMapper(), id_duty); CategoryDTO result = temp.get(0); return result; } public Integer save(CategoryDTO category) throws FileNotFoundException { StringBuilder sql = new StringBuilder("INSERT INTO danhmuc(id_duty,name,image,image_hover"); sql.append(" VALUES(?, ?, ?, ?)"); return insert(sql.toString(), category.getId_duty(), category.getName(), category.getImage(), category.getImage_hover()); } public List<CategoryDTO> findAll() { String sql = "select * from danhmuc"; return query(sql, new CategoryMapper()); } public void delete(int idCategory) throws FileNotFoundException { String sql = "DELETE FROM danhmuc WHERE id_duty = ? "; update(sql, idCategory); } public void update(CategoryDTO category) throws FileNotFoundException { StringBuilder sql = new StringBuilder("UPDATE danhmuc SET name = ? , image = ? , image_hover = ?"); sql.append("WHERE id_duty = ?"); update(sql.toString(), category.getName(), category.getImage(), category.getImage_hover(), category.getId_duty()); } }
VoNhu2901/java-swing-project
src/DAO/CategoryDAO.java
421
/** * * @author Thuan Vo */
block_comment
en
true
248545_0
package utils; import java.util.ArrayList; import java.util.List; /** * Optimized Que list * I might have misread the source code for Stack, but it looked like calling "pop" had an array copy operation * I could probably find a proper collection but I'm lazy and this worked */ public class Q<T> { private List<T> backbone = new ArrayList<T>(); private int length = 0; public void add(T toAdd) { if (length >= backbone.size()) { backbone.add(toAdd); } else { backbone.set(length, toAdd); } length++; } public int size() { return length; } public T pop() { return backbone.get(--length); } }
dragon1672/pente
src/utils/Q.java
187
/** * Optimized Que list * I might have misread the source code for Stack, but it looked like calling "pop" had an array copy operation * I could probably find a proper collection but I'm lazy and this worked */
block_comment
en
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
249237_2
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Scanner; import java.util.Set; class Flight implements Comparable<Flight> { public int flightID; public String from; public String to; public Date date; public Set<Passenger> passengers = new HashSet<>(); public Flight(int flightID, String from, String to, Date date) { this.flightID = flightID; this.from = from; this.to = to; this.date = date; } public int compareTo(Flight other) { // Sort flights by date ascending return this.date.compareTo(other.date); } public boolean equals(Flight other) { return (this.flightID == other.flightID); } } class Date implements Comparable<Date> { public int year; public int month; public int day; public Date(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public int compareTo(Date other) { // Sort by year then month then day ascending if (this.year != other.year) { return (this.year - other.year); } if (this.month != other.month) { return (this.month - other.month); } return (this.day - other.day); } } class Passenger implements Comparable<Passenger> { public int passengerID; public String firstName; public String lastName; public Set<Flight> flights = new HashSet<>(); public Passenger(int passengerID, String firstName, String lastName) { this.passengerID = passengerID; this.firstName = firstName; this.lastName = lastName; } public int compareTo(Passenger other) { // Sort passengers by number of flights ascending return (this.flights.size() - other.flights.size()); } } class PassengerRun implements Comparable<PassengerRun> { public int passengerID; public int longestRun; public PassengerRun(int passengerID, int longestRun) { this.passengerID = passengerID; this.longestRun = longestRun; } public int compareTo(PassengerRun other) { // Sorts passenger runs by longest run ascending return (this.longestRun - other.longestRun); } } class PassengerPair implements Comparable<PassengerPair> { public int passengerIDA; public int passengerIDB; public int numberOfFlights; public PassengerPair(int passengerIDA, int passengerIDB, int numberOfFlights) { this.passengerIDA = passengerIDA; this.passengerIDB = passengerIDB; this.numberOfFlights = numberOfFlights; } public int compareTo(PassengerPair other) { // Sorts passenger pairs by number of flights shared ascending return (this.numberOfFlights - other.numberOfFlights); } } public class FlightData { private static String passengerFilename = "passengers.csv"; private static String flightDataFilename = "flightData.csv"; private static String question1Filename = "javaQuestion1.csv"; private static String question2Filename = "javaQuestion2.csv"; private static String question3Filename = "javaQuestion3.csv"; private static String question4Filename = "javaQuestion4.csv"; private static String question5Filename = "javaQuestion5.csv"; public static void main(String[] args) { Map<Integer, Passenger> passengers = getPassengers(passengerFilename); Map<Integer, Flight> flights = getFlights(flightDataFilename); getPassengersOfEachFlight(passengers, flights, flightDataFilename); getTotalFlightsForEachMonth(passengers, flights, question1Filename); getMostFrequentFlyers(passengers, flights, 100, question2Filename); getPassengerRuns(passengers, flights, "uk", question3Filename); getPassengersWithSharedFlights(passengers, flights, 3, question4Filename); } public static Map<Integer, Passenger> getPassengers(String filename) { // Returns a map of (passengerID, passenger) pairs // from the given input filename Map<Integer, Passenger> passengers = new HashMap<>(); try { Scanner scanner = new Scanner(new File(filename)); // Read header scanner.nextLine(); while (scanner.hasNextLine()) { // Read passenger line String[] passenger = scanner.nextLine().split(","); int passengerID = Integer.parseInt(passenger[0]); String firstName = passenger[1]; String lastName = passenger[2]; passengers.put(passengerID, new Passenger(passengerID, firstName, lastName)); } } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); } return passengers; } public static Map<Integer, Flight> getFlights(String filename) { // Returns a map of (flightID, flight) pairs // from the given input filename Map<Integer, Flight> flights = new HashMap<>(); try { Scanner scanner = new Scanner(new File(filename)); // Read header scanner.nextLine(); while (scanner.hasNextLine()) { // Read flight line String[] flight = scanner.nextLine().split(","); int passengerID = Integer.parseInt(flight[0]); int flightID = Integer.parseInt(flight[1]); String from = flight[2]; String to = flight[3]; String[] date = flight[4].split("-"); int year = Integer.parseInt(date[0]); int month = Integer.parseInt(date[1]); int day = Integer.parseInt(date[2]); flights.put(flightID, new Flight(flightID, from, to, new Date(year, month, day))); } scanner.close(); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); } return flights; } public static void getPassengersOfEachFlight( Map<Integer, Passenger> passengers, Map<Integer, Flight> flights, String filename) { // Creates a set of passengers that travelled on // each flight, as well as a set of flights that // each passenger travelled on try { Scanner scanner = new Scanner(new File(filename)); // Read header scanner.nextLine(); while (scanner.hasNextLine()) { // Read flight line String[] flight = scanner.nextLine().split(","); int passengerID = Integer.parseInt(flight[0]); int flightID = Integer.parseInt(flight[1]); // Update the relevant passenger passengers.get(passengerID).flights .add(flights.get(flightID)); // Update the relevant flight flights.get(flightID).passengers .add(passengers.get(passengerID)); } scanner.close(); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); } } public static void getTotalFlightsForEachMonth( Map<Integer, Passenger> passengers, Map<Integer, Flight> flights, String filename) { // Outputs the total flights for each month // to the given output filename int[] monthNumberOfFlights = new int[12]; for (Integer flightID : flights.keySet()) { int month = flights.get(flightID).date.month; monthNumberOfFlights[month - 1]++; } try { PrintWriter writer = new PrintWriter(new File(filename)); String header = "month,numberOfFlights"; writer.println(header); for (int i = 0; i < monthNumberOfFlights.length; i++) { // Write line int month = i + 1; String line = month + "," + monthNumberOfFlights[i]; writer.println(line); } writer.close(); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); } } public static void getMostFrequentFlyers( Map<Integer, Passenger> passengers, Map<Integer, Flight> flights, int k, String filename) { // Outputs the k most frequent flyers // to the given output filename // Create min heap of at most k elements PriorityQueue<Passenger> bestPassengers = new PriorityQueue<>(); for (Passenger passenger : passengers.values()) { bestPassengers.add(passenger); // Ensure min heap has at most k elements if (bestPassengers.size() > k) { // Remove the (k + 1)th most frequent passenger bestPassengers.poll(); } } // Extract the passengers in ascending order List<Passenger> outputPassengers = new ArrayList<>(); while (!bestPassengers.isEmpty()) { outputPassengers.add(bestPassengers.poll()); } Collections.reverse(outputPassengers); // Output the top k passengers in order of // number of flights descending try { PrintWriter writer = new PrintWriter(new File(filename)); String header = "passengerId,numberOfFlights," + "firstName,lastName"; writer.println(header); for (Passenger passenger : outputPassengers) { // Write line String line = passenger.passengerID + "," + passenger.flights.size() + "," + passenger.firstName + "," + passenger.lastName; writer.println(line); } writer.close(); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); } } public static void getPassengerRuns( Map<Integer, Passenger> passengers, Map<Integer, Flight> flights, String runEnd, String filename) { // Outputs the longest runs for each passenger // given a location runEnd // to the given output filename List<PassengerRun> passengerRuns = new ArrayList<>(); for (int passengerID : passengers.keySet()) { // Create a list of flights sortable by date List<Flight> passengerFlights = new ArrayList<>(passengers.get(passengerID).flights); int longestRun = getLongestRun(passengerFlights, runEnd); passengerRuns.add(new PassengerRun(passengerID, longestRun)); } // Sort passenger runs by longest run descending Collections.sort(passengerRuns); Collections.reverse(passengerRuns); // Output passenger runs try { PrintWriter writer = new PrintWriter(new File(filename)); String header = "passengerId,longestRun"; writer.println(header); for (PassengerRun passengerRun : passengerRuns) { // Write line String line = passengerRun.passengerID + "," + passengerRun.longestRun; writer.println(line); } writer.close(); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); } } public static int getLongestRun(List<Flight> passengerFlights, String runEnd) { // Returns the longest run // given a list of passenger flights // and a location runEnd // Sort passenger flights by date ascending Collections.sort(passengerFlights); int longestRun = 0; int currentRun = 0; if (!passengerFlights.get(0).from.equals(runEnd)) { // Start at first location longestRun++; currentRun++; } for (Flight flight : passengerFlights) { if (flight.to.equals(runEnd)) { // End of current run currentRun = 0; continue; } // Extend current run currentRun++; longestRun = Math.max(longestRun, currentRun); } return longestRun; } public static void getPassengersWithSharedFlights( Map<Integer, Passenger> passengers, Map<Integer, Flight> flights, int k, String filename) { // Outputs the passenger pairs sharing > k flights // to the given output filename // passengerPairIDNumberOfFlights is a set of // (passengerPairID, numberOfFlights) pairs Map<String, Integer> passengerPairIDNumberOfFlights = new HashMap<>(); for (int passengerIDA : passengers.keySet()) { for (int passengerIDB : passengers.keySet()) { if (passengerIDA >= passengerIDB) { // Same passenger is both parts of the pair // Ensures passenger A has a lower ID than // passenger B to avoid double counting continue; } // Create the ID representing the pair String passengerPairID = passengerIDA + "&" + passengerIDB; // Get number of shared flights int numberOfFlights = 0; for (Flight flightA : passengers.get(passengerIDA) .flights) { if (passengers.get(passengerIDB).flights .contains(flightA)) { // Current flight is shared numberOfFlights++; } } passengerPairIDNumberOfFlights.put(passengerPairID, numberOfFlights); } } List<PassengerPair> passengerPairs = new ArrayList<>(); for (String passengerPairID : passengerPairIDNumberOfFlights.keySet()) { // Create a list of passenger pairs sortable // by number of flights shared String[] passengerIDs = passengerPairID.split("&"); int passengerIDA = Integer.parseInt(passengerIDs[0]); int passengerIDB = Integer.parseInt(passengerIDs[1]); int numberOfFlights = passengerPairIDNumberOfFlights .get(passengerPairID); passengerPairs.add(new PassengerPair(passengerIDA, passengerIDB, numberOfFlights)); } Collections.sort(passengerPairs); Collections.reverse(passengerPairs); // Output passenger pairs try { PrintWriter writer = new PrintWriter(new File(filename)); String header = "passenger1Id,passenger2Id," + "numberOfFlightsTogether"; writer.println(header); for (PassengerPair passengerPair : passengerPairs) { if (passengerPair.numberOfFlights <= k) { // Number of flights shared must be more than k continue; } // Write line String line = passengerPair.passengerIDA + "," + passengerPair.passengerIDB + "," + passengerPair.numberOfFlights; writer.println(line); } writer.close(); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); } } }
mkhilari/Quantexa-Flight-Data-Assignment
FlightData.java
3,480
// Sort passengers by number of flights ascending
line_comment
en
false
249294_0
package com.seu.domian; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @ClassName Experts * @Description TODO * @Author 吴宇航 * @Date 2018/9/2 20:59 * @Version 1.0 **/ @Data @Entity public class Experts { @Id @GeneratedValue private Integer id; private String name; private String phone; private String email; }
cckmit/dpDisputeSys
src/main/java/com/seu/domian/Experts.java
136
/** * @ClassName Experts * @Description TODO * @Author 吴宇航 * @Date 2018/9/2 20:59 * @Version 1.0 **/
block_comment
en
true
249304_3
/* * Copyright 2002-2019 Drew Noakes and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ package com.drew.imaging; import com.drew.lang.annotations.NotNull; import com.drew.lang.annotations.Nullable; /** * Enumeration of supported file types. * * MIME Type Source: https://www.freeformatter.com/mime-types-list.html * https://www.iana.org/assignments/media-types/media-types.xhtml */ public enum FileType { Unknown("Unknown", "Unknown", null), Jpeg("JPEG", "Joint Photographic Experts Group", "image/jpeg", "jpg", "jpeg", "jpe"), Tiff("TIFF", "Tagged Image File Format", "image/tiff", "tiff", "tif"), Psd("PSD", "Photoshop Document", "image/vnd.adobe.photoshop", "psd"), Png("PNG", "Portable Network Graphics", "image/png", "png"), Bmp("BMP", "Device Independent Bitmap", "image/bmp", "bmp"), Gif("GIF", "Graphics Interchange Format", "image/gif", "gif"), Ico("ICO", "Windows Icon", "image/x-icon", "ico"), Pcx("PCX", "PiCture eXchange", "image/x-pcx", "pcx"), Riff("RIFF", "Resource Interchange File Format", null), Wav("WAV", "Waveform Audio File Format", "audio/vnd.wave", "wav", "wave"), Avi("AVI", "Audio Video Interleaved", "video/vnd.avi", "avi"), WebP("WebP", "WebP", "image/webp", "webp"), QuickTime("MOV", "QuickTime Movie", "video/quicktime", "mov", "qt"), Mp4("MP4", "MPEG-4 Part 14", "video/mp4", "mp4", "m4a", "m4p", "m4b", "m4r", "m4v"), Heif("HEIF", "High Efficiency Image File Format", "image/heif", "heif", "heic"), Avif("AVIF", "AV1 Image File Format", "image/avif", "avif"), Eps("EPS", "Encapsulated PostScript", "application/postscript", "eps", "epsf", "epsi"), Mp3("MP3", "MPEG Audio Layer III", "audio/mpeg", "mp3"), /** Sony camera raw. */ Arw("ARW", "Sony Camera Raw", null, "arw"), /** Canon camera raw, version 1. */ Crw("CRW", "Canon Camera Raw", null, "crw"), /** Canon camera raw, version 2. */ Cr2("CR2", "Canon Camera Raw", null, "cr2"), /** Nikon camera raw. */ Nef("NEF", "Nikon Camera Raw", null, "nef"), /** Olympus camera raw. */ Orf("ORF", "Olympus Camera Raw", null, "orf"), /** FujiFilm camera raw. */ Raf("RAF", "FujiFilm Camera Raw", null, "raf"), /** Panasonic camera raw. */ Rw2("RW2", "Panasonic Camera Raw", null, "rw2"), /** Canon camera raw (version 3). Shared by CR3 (image) and CRM (video). */ Crx("CRX", "Canon Camera Raw", null, "cr3", "crm"), // Only file detection Aac("AAC", "Advanced Audio Coding", "audio/aac", "m4a"), Asf("ASF", "Advanced Systems Format", "video/x-ms-asf", "asf", "wma", "wmv"), Cfbf("CFBF", "Compound File Binary Format", null, (String[])null), Flv("FLV", "Flash Video", "video/x-flv", ".flv", ".f4v,"), Indd("INDD", "INDesign Document", "application/octet-stream", ".indd"), Mxf("MXF", "Material Exchange Format", "application/mxf", "mxf"), Pdf("PDF", "Portable Document Format", "application/pdf", "pdf"), Qxp("QXP", "Quark XPress Document", null, "qzp", "qxd"), Ram("RAM", "RealAudio", "audio/vnd.rn-realaudio", "aac", "ra"), Rtf("RTF", "Rich Text Format", "application/rtf", "rtf"), Sit("SIT", "Stuffit Archive", "application/x-stuffit", "sit"), Sitx("SITX", "Stuffit X Archive", "application/x-stuffitx", "sitx"), Swf("SWF", "Small Web Format", "application/vnd.adobe.flash-movie", "swf"), Vob("VOB", "Video Object", "video/dvd", ".vob"), Zip("ZIP", "ZIP Archive", "application/zip", ".zip", ".zipx"); @NotNull private final String _name; @NotNull private final String _longName; @Nullable private final String _mimeType; private final String[] _extensions; FileType(@NotNull String name, @NotNull String longName, @Nullable String mimeType, String... extensions) { _name = name; _longName = longName; _mimeType = mimeType; _extensions = extensions; } @NotNull public String getName() { return _name; } @NotNull public String getLongName() { return _longName; } @Nullable public String getMimeType() { return _mimeType; } @Nullable public String getCommonExtension() { return (_extensions == null || _extensions.length == 0) ? null : _extensions[0]; } @Nullable public String[] getAllExtensions() { return _extensions; } }
drewnoakes/metadata-extractor
Source/com/drew/imaging/FileType.java
1,597
/** Canon camera raw, version 1. */
block_comment
en
true
249763_0
import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.io.SyndFeedInput; import com.sun.syndication.io.XmlReader; import java.net.URL; import java.util.Random; public class NewsPoster implements Runnable{ private long timeStart; public NewsPoster(){ this.timeStart = System.currentTimeMillis(); } public void postNews() { try { String[] cities = {"quebec", "toronto", "warsaw", "amsterdam", "rotterdam", "riga", "oslo", "stockholm", "prague", "sydney", "london", "berlin", "beijing", "delhi", "tokyo", "california", "iowa", "zurich", "geneva"}; var random = new Random(); URL feedSource = new URL("https://news.google.com/news/rss/headlines/section/geo/" + cities[random.nextInt(cities.length - 1)]); SyndFeedInput input = new SyndFeedInput(); SyndFeed feed = input.build(new XmlReader(feedSource)); for (var o : feed.getEntries()) { SyndEntry entry = (SyndEntry) o; var tweeter = new Tweeter(); tweeter.setTweet(entry.getTitle() + " " + entry.getLink()); tweeter.postTweet(); break; } } catch (Exception e) { e.printStackTrace(); System.err.println(e); } } @Override public void run() { while(true) { if (System.currentTimeMillis() - timeStart > 60000) { var newsPoster = new NewsPoster(); newsPoster.postNews(); timeStart = System.currentTimeMillis(); } } } }
assemblu/TwitterBot
src/NewsPoster.java
459
//news.google.com/news/rss/headlines/section/geo/" + cities[random.nextInt(cities.length - 1)]);
line_comment
en
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
11160_0
/** * Program to print the day on the 13th of every month in a year if year and day on the 1st of January are given */ import java.io.*; class Q3 { int noOfDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; static String Day[]={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"}; String Month[]={"January","February","March","April","May","June","July","August","September","October","November","December"}; static int year; Q3() { year=2018; } void prog(int d) { int y=365; int dayOfMonth=1; int dayOfWeek=d; int month=0; if (year%100!=0 && year%4==0) {noOfDays[1]++;y++;} else if (y%400==0){noOfDays[1]++;y++;} System.out.println("Month\t\tThirteenth"); for(int i=1;i<=y; i++) { if (month==12)break; dayOfMonth++; dayOfWeek++; if(Day.length==dayOfWeek) { dayOfWeek=0; } if (dayOfMonth>noOfDays[month]) { month++; dayOfMonth=1; } if(dayOfMonth==13) { System.out.println(Month[month]+"\t\t"+Day[dayOfWeek]); } } } public static void main() throws IOException { BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); System.out.print("Enter year = "); year = Integer.parseInt (br.readLine()); System.out.print("Enter day on 1st Jan = "); String d = br.readLine(); int D=0; for(int i=0;i<=6;i++) { if(Day[i].equalsIgnoreCase(d))D=i; } Q3 obj = new Q3(); obj.prog(D); } }
adityaoberai/ISC-2018-Computer-Science-Project
Q3.java
513
/** * Program to print the day on the 13th of every month in a year if year and day on the 1st of January are given */
block_comment
en
true
57391_0
/* * Copyright © 1996-2009 Bart Massey * ALL RIGHTS RESERVED * [This program is licensed under the "MIT License"] * Please see the file COPYING in the source * distribution of this software for license terms. */ import java.awt.*; public class Digits extends Canvas { private int ndigits; private int value = 0; private boolean has_value = false; private Font digit_font; private static Font default_digit_font = null; private static int default_pointsize = -1; private boolean greyed = false; public static int defaultPointsize() { if (default_pointsize < 0) { Font f = (new Label("x")).getFont(); if (f == null) throw new AWTError("No label font"); else default_pointsize = f.getSize(); } return default_pointsize; } private static Font find_font() { if (default_digit_font == null) { int size = 14; try { size = defaultPointsize(); } catch (AWTError e) { // do nothing } default_digit_font = new Font("Courier", Font.PLAIN, size); } return default_digit_font; } public Digits(int n, Font f) { if (n <= 0) throw new IllegalArgumentException("Too few digits"); ndigits = n; digit_font = f; } public Digits(int n) { this(n, find_font()); } public Dimension minimumSize() { FontMetrics fm = getFontMetrics(digit_font); int w = ndigits * fm.getMaxAdvance(); return new Dimension(w, fm.getHeight()); } public Dimension preferredSize() { return minimumSize(); } public void paint(Graphics g) { if (!has_value) return; Dimension s = size(); Dimension m = minimumSize(); if (greyed) { Color old = g.getColor(); g.setColor(Color.gray); g.fillRect(0, 0, s.width, s.height); g.setColor(old); } if (s.width < m.width || s.height < m.height) { if (s.width > 5) g.drawLine(5, s.height / 2, s.width - 5, s.height / 2); return; } g.setFont(digit_font); String vs = Integer.toString(value); char ch[] = new char[ndigits]; for (int i = 0; i < ndigits; i++) ch[i] = 0; if (vs.length() > ndigits) vs = vs.substring(vs.length() - ndigits); for (int i = 0; i < vs.length(); i++) ch[i + ndigits - vs.length()] = vs.charAt(i); FontMetrics fm = g.getFontMetrics(); int y = s.height - fm.getDescent() - fm.getLeading(); int x = s.width; for (int i = 0; i < ndigits; i++) { int j = ndigits - i - 1; x -= fm.charWidth(ch[j]); g.drawChars(ch, j, 1, x, y); } } public Font getFont() { return digit_font; } public void setFont(Font f) { digit_font = f; repaint(); } public void setValue(int v) { has_value = true; value = v; repaint(); } // Should throw a subclass of RuntimeException public int getValue() { if (!has_value) throw new AWTError("Attempted to get non-existent digits"); return value; } public boolean hasValue() { return has_value; } public void clearValue() { has_value = false; repaint(); } public void setDimmed(boolean greyed) { if (this.greyed != greyed) { this.greyed = greyed; repaint(); } } }
BartMassey/java-yacht
Digits.java
1,026
/* * Copyright © 1996-2009 Bart Massey * ALL RIGHTS RESERVED * [This program is licensed under the "MIT License"] * Please see the file COPYING in the source * distribution of this software for license terms. */
block_comment
en
true
64591_0
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Scanner; // Problem link: https://open.kattis.com/problems/cups public class cups { public static void main(String[] args) { Scanner fs = new Scanner(System.in); int n = fs.nextInt(); fs.nextLine(); ArrayList<Cup> cups = new ArrayList<>(); for (int i = 0; i < n; i++) { char[] s = fs.nextLine().toCharArray(); String temp = "", firstParam = ""; for (int j = 0; j < s.length; j++) { if (firstParam.equals("") && s[j] == ' ') { firstParam = temp; temp = ""; } else { temp += s[j]; } } String secondParam = temp; if (isNumber(firstParam.toCharArray())) { cups.add(new Cup(Integer.parseInt(firstParam) / 2, secondParam)); } else { cups.add(new Cup(Integer.parseInt(secondParam), firstParam)); } } Collections.sort(cups, new Comparator<Cup>() { @Override public int compare(Cup o1, Cup o2) { return Integer.compare(o1.radius, o2.radius); } }); for (Cup cup : cups) { System.out.println(cup.color); } fs.close(); } static boolean isNumber(char[] param) { for (int i = 0; i < param.length; i++) { if (param[i] < '0' || param[i] > '9') { return false; } } return true; } static class Cup { String color; int radius; Cup(int radius, String color) { this.radius = radius; this.color = color; } } }
mgalang229/Kattis-Training
cups.java
511
// Problem link: https://open.kattis.com/problems/cups
line_comment
en
true
67533_0
/****************************************************************************** Online Java Compiler. Code, Compile, Run and Debug java program online. Write your code in this editor and press "Run" button to execute it. *******************************************************************************/ public class Film { private int id; private String name; private String genre; private int duration; private int year; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } }
NiNglos/FA_JAVA
Java/Main.java
209
/****************************************************************************** Online Java Compiler. Code, Compile, Run and Debug java program online. Write your code in this editor and press "Run" button to execute it. *******************************************************************************/
block_comment
en
true
129483_0
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; /** * See * <a href="https://www.urionlinejudge.com.br/judge/en/problems/view/1763">Santa's * Translator</a> * * @author Brian Yeicol Restrepo Tangarife */ public class URI1763SantasTranslator { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { String country; while ((country = in.readLine()) != null) { switch (country) { case "estados-unidos": case "inglaterra": case "australia": case "antardida": case "canada": out.println("Merry Christmas!"); break; case "espanha": case "argentina": case "chile": case "mexico": out.println("Feliz Navidad!"); break; case "brasil": case "portugal": out.println("Feliz Natal!"); break; case "italia": case "libia": out.println("Buon Natale!"); break; case "siria": case "marrocos": out.println("Milad Mubarak!"); break; case "austria": out.println("Frohe Weihnacht!"); break; case "grecia": out.println("Kala Christougena!"); break; case "suecia": out.println("God Jul!"); break; case "turquia": out.println("Mutlu Noeller"); break; case "japao": out.println("Merii Kurisumasu!"); break; case "alemanha": out.println("Frohliche Weihnachten!"); break; case "belgica": out.println("Zalig Kerstfeest!"); break; case "coreia": out.println("Chuk Sung Tan!"); break; case "irlanda": out.println("Nollaig Shona Dhuit!"); break; default: out.println("--- NOT FOUND ---"); break; } } out.close(); } }
yeicol/URI
URI1763SantasTranslator.java
641
/** * See * <a href="https://www.urionlinejudge.com.br/judge/en/problems/view/1763">Santa's * Translator</a> * * @author Brian Yeicol Restrepo Tangarife */
block_comment
en
true
156066_1
import java.util.ArrayList; import java.util.TreeMap; import java.util.Set; import java.util.Map; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.io.FileWriter; import java.io.PrintWriter; import java.io.BufferedWriter; public class Tester { private ArrayList< Party > parties; private TreeMap < Client, Party > games; private File clientsInfo; private Scanner clientsScanner; private BufferedWriter writer; public Tester() { parties = new ArrayList<>(); games = new TreeMap<>(); clientsInfo = new File("./clients_info.txt"); try { writer = new BufferedWriter(new FileWriter("./output.txt")); clientsScanner = new Scanner(clientsInfo); } catch (Exception ex) { ex.printStackTrace(); } clientsScanner.useDelimiter("\n"); initParties(); initClients(); } private void initParties() { // ArrayList < Client > clients = Server.getClientsWhoHaveMessages(); for (int i = 0; i < 10; i++) { parties.add(new Party(i)); } } private void initClients() { /* party index client id client ip client port */ while (clientsScanner.hasNextLine()) { int partyInd = clientsScanner.nextInt(); clientsScanner.nextLine(); Client client = new Client(); client.read(clientsScanner); games.put(client, parties.get(partyInd)); } } public void test() { for (Map.Entry<Client, Party> entry : games.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } Scanner input = new Scanner(System.in); input.useDelimiter("\n"); // ENTER FIRST CLIENT System.out.println("\nPlease enter the client info to be searched:"); int id = input.nextInt(); input.nextLine(); String ip = input.nextLine(); int port = input.nextInt(); Client toSearchClient = new Client(id, ip, port); if (games.containsKey(toSearchClient)) { System.out.println("\nKey was found!"); System.out.println(games.get(toSearchClient)); } else { System.out.println("\nKey was not found!"); } System.out.println("\nHere are all the keys:"); write("After search:"); for (Client c : games.keySet()) { System.out.println(c); write(c.toString()); } // ENTER SECOND CLIENT System.out.println("\nPlease enter the client info to be deleted:"); id = input.nextInt(); input.nextLine(); ip = input.nextLine(); port = input.nextInt(); toSearchClient = new Client(id, ip, port); if (games.containsKey(toSearchClient)) { System.out.println("\nKey was found!"); games.remove(toSearchClient); } else { System.out.println("\nKey was not found!"); } System.out.println("\nHere are all the keys:"); write("\nAfter deletion:"); for (Client c : games.keySet()) { System.out.println(c); write(c.toString()); } try { writer.close(); } catch (Exception ex) { ex.printStackTrace(); } } private void write(String what) { try { writer.write(what); writer.write("\n"); } catch (Exception ex) { ex.printStackTrace(); } } }
Arvolear/University
Java/Indiv3/Tester.java
982
/* party index client id client ip client port */
block_comment
en
true
176789_1
/* Complete the countApplesAndOranges function in the editor below. It should print the number of apples and oranges that land on Sam's house, each on a separate line. countApplesAndOranges has the following parameter(s): s: integer, starting point of Sam's house location. t: integer, ending location of Sam's house location. a: integer, location of the Apple tree. b: integer, location of the Orange tree. apples: integer array, distances at which each apple falls from the tree. oranges: integer array, distances at which each orange falls from the tree. Input Format The first line contains two space-separated integers denoting the respective values of and . The second line contains two space-separated integers denoting the respective values of and . The third line contains two space-separated integers denoting the respective values of and . The fourth line contains space-separated integers denoting the respective distances that each apple falls from point . The fifth line contains space-separated integers denoting the respective distances that each orange falls from point . Constraints Output Format Print two integers on two different lines: The first integer: the number of apples that fall on Sam's house. The second integer: the number of oranges that fall on Sam's house. Sample Input 0 7 11 5 15 3 2 -2 2 1 5 -6 Sample Output 0 1 1 Solution - */ import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; class Result { /* * Complete the 'countApplesAndOranges' function below. * * The function accepts following parameters: * 1. INTEGER s * 2. INTEGER t * 3. INTEGER a * 4. INTEGER b * 5. INTEGER_ARRAY apples * 6. INTEGER_ARRAY oranges */ public static void countApplesAndOranges(int s, int t, int a, int b, List<Integer> apples, List<Integer> oranges) { // Write your code here int count_apple = 0; int count_orange = 0; for(int i : apples){ if(i + a >= s && i + a <= t){ count_apple++; } } for(int i : oranges){ if(i + a >= s && i + a <= t){ count_orange++; } } System.out.println(count_apple); System.out.println(count_orange); } } public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" "); int s = Integer.parseInt(firstMultipleInput[0]); int t = Integer.parseInt(firstMultipleInput[1]); String[] secondMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" "); int a = Integer.parseInt(secondMultipleInput[0]); int b = Integer.parseInt(secondMultipleInput[1]); String[] thirdMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" "); int m = Integer.parseInt(thirdMultipleInput[0]); int n = Integer.parseInt(thirdMultipleInput[1]); String[] applesTemp = bufferedReader.readLine().replaceAll("\\s+$", "").split(" "); List<Integer> apples = new ArrayList<>(); for (int i = 0; i < m; i++) { int applesItem = Integer.parseInt(applesTemp[i]); apples.add(applesItem); } String[] orangesTemp = bufferedReader.readLine().replaceAll("\\s+$", "").split(" "); List<Integer> oranges = new ArrayList<>(); for (int i = 0; i < n; i++) { int orangesItem = Integer.parseInt(orangesTemp[i]); oranges.add(orangesItem); } Result.countApplesAndOranges(s, t, a, b, apples, oranges); bufferedReader.close(); } }
jvedsaqib/100daysofcodechallenge
day22.java
994
/* * Complete the 'countApplesAndOranges' function below. * * The function accepts following parameters: * 1. INTEGER s * 2. INTEGER t * 3. INTEGER a * 4. INTEGER b * 5. INTEGER_ARRAY apples * 6. INTEGER_ARRAY oranges */
block_comment
en
true
179820_0
/*- * Copyright (c) 2009, A P Francisco * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ public class DisjointSet { private int size; private int[] pi; private int[] rank; public DisjointSet(int n) { size = n + 1; pi = new int[size]; rank = new int[size]; for (int i = 0; i < size; i++) { rank[i] = 1; pi[i] = i; } } public int findSet(int i) { if (i < 0 || i >= size) return -1; for (; i != pi[i]; i = pi[i]) pi[i] = pi[pi[i]]; return i; } public boolean sameSet(int i, int j) { return findSet(i) == findSet(j); } public void unionSet(int i, int j) { if (i < 0 || j < 0 || i >= size || j >= size) return; int iRoot = findSet(i); int jRoot = findSet(j); if (iRoot == jRoot) return; if (rank[iRoot] > rank[jRoot]) { pi[jRoot] = iRoot; rank[iRoot] += rank[jRoot]; } else if (rank[iRoot] < rank[jRoot]) { pi[iRoot] = jRoot; rank[jRoot] += rank[iRoot]; } else { pi[iRoot] = jRoot; rank[jRoot] += rank[iRoot]; } } public int getRank(int i) { return rank[i]; } }
RicardoBrancas/CRC_1
java/DisjointSet.java
605
/*- * Copyright (c) 2009, A P Francisco * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
block_comment
en
true
204905_1
import java.io.*; import java.util.*; class MemoryBlock { // hardcoded values if the user does not want to enter the values; int[] memory = new int [100] ; boolean[] free ; int[] processes; int[] frag ; int n; int divs = memory.length; Scanner s = new Scanner(System.in); void welcomeMessage() { System.out.println("\n\tWelcome to The Memory Allocation Simulator"); memoryInput(); System.out.print("Enter the number of processes : "); n = s.nextInt(); processInput(); boolean run=true; while(run){ choice(); for(int i = 0; i < divs; ++i) { free[i] = true; frag[i] = 0; } } } void processInput() { for(int i=0;i<n; i++){ System.out.print("\nEnter the size of the process that needs to be added : "); processes[i] = s.nextInt(); } } void memoryInput() { // re-initialising the data if user wants to enter the data; memory = new int[100]; free = new boolean[100]; frag = new int [100]; processes = new int [100]; System.out.print("\nEnter the number of Memory Blocks: "); divs = s.nextInt(); for(int i = 0; i < divs; ++i) { System.out.print("\nEnter the Memory Block on Position " + (i + 1) + ": "); memory[i] = s.nextInt(); free[i] = true; frag[i] = 0; } } void choice() { System.out.print("\nEnter the Algorithm for Memory Allocation: \n"); System.out.print("[1] First Fit\n"); System.out.print("[2] Best Fit\n"); System.out.print("[3] Worst Fit\n"); System.out.print("[4] Exit\n"); System.out.print("Enter a number (1-4): "); int fitType = s.nextInt(); for(int i=0;i<n;i++){ switch(fitType) { case 1: firstFit(i); break; case 2: bestFit(i); break; case 3: worstFit(i); break; case 4: System.exit(0); default: System.out.println("\nPlease enter a number between 1 and 4.\n"); }} } void firstFit(int pn) { int ans = -1; for(int i = 0; i < divs; i++) { if(free[i] && processes[pn] <= memory[i]) { free[i]=false; frag[i]=memory[i]-processes[pn]; ans = i; break; } } if(pn==n-1) printTable(ans); } void bestFit(int pn) { int ans = -1, curr = 1000000; for(int i = 0; i < divs; i++) { if(free[i] && processes[pn] <= memory[i]) { if(memory[i] - processes[pn] < curr) { curr = memory[i] - processes[pn]; ans = i; } } } free[ans]=false; frag[ans]=memory[ans]-processes[pn]; if(pn==n-1) printTable(ans); } void worstFit(int pn) { int ans = -1, curr = 0; for(int i = 0; i < divs; i++) { if(free[i] && processes[pn] <= memory[i]) { if(memory[i] - processes[pn] > curr) { curr = memory[i] - processes[pn]; ans = i; } } } if(ans!=-1) { free[ans]=false; frag[ans]=memory[ans]-processes[pn]; } if(pn==n-1) printTable(ans); } void printTable(int pos) { System.out.print("+---------------------------------------------------------------------------------------------+\n"); System.out.print("|\tNo.\tMemory \t\t Status \t Process \t\tInternal Fragmentation|\n"); System.out.print("+---------------------------------------------------------------------------------------------+\n"); int j = 1, ok = 0; int pnum=0; for (int i = 0; i < divs; i++) { System.out.print("|\t" + (i + 1) + " \t " + memory[i] + " \t\t " + ((!free[i]) ? "F \t\t" : "NF ") + " " + ((free[i])? "\t\t\t":("Process " + (++pnum))) + "\t\t\t"+(((frag[i])==0)? "":frag[i])+"\t\t|"); System.out.println(' '); } System.out.print("+---------------------------------------------------------------------------------------------+\n"); } } class resall { public static void main(String args[]) throws IOException { MemoryBlock m = new MemoryBlock(); m.welcomeMessage(); } }
AdityaT-19/OSPROJ
resall.java
1,271
// re-initialising the data if user wants to enter the data;
line_comment
en
true
206412_1
import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; @DatabaseTable(tableName = "jobs") public class Job { @DatabaseField(generatedId=true) private int id; @DatabaseField private int user_id; @DatabaseField private int project_id; @DatabaseField private String tid; @DatabaseField private String job_type; @DatabaseField private String job_data; @DatabaseField private int run_every; @DatabaseField private int last_run; // last time run (in seconds since epoch) @DatabaseField private int max_runtimes; @DatabaseField private int run_times; @DatabaseField private String status; @DatabaseField private boolean paused; @DatabaseField private String run_in_background; public Job() { // ORMLite needs a no-arg constructor } public Job(int userId, int projectId, String tid, String jobType, String jobData, int runEvery, int lastRun, int maxRunTimes, int runTimes, boolean paused, String runInBackground) { //this.id = id; this.user_id = userId; this.project_id = projectId; this.tid = tid; this.job_type = jobType; this.job_data = jobData; this.run_every = runEvery; this.last_run = lastRun; this.max_runtimes = maxRunTimes; this.run_times = runTimes; this.paused = paused; this.run_in_background = runInBackground; } public int getJobId() { return id; } public String getJobType() { return job_type; } public int getUserId() { return user_id; } public int getProjectId() { return project_id; } public String getJobData() { return job_data; } public int getRunTimes() { return run_times; } public void setRunTimes(int runTimes) { this.run_times = runTimes; } public int getMaxRunTimes() { return max_runtimes; } public int getRunEvery() { return run_every; } public boolean getPaused() { return paused; } // what the fuck is going on here with ormlite? boolean values were being set to false automatically, and the string comes back as "t" or "f" instead of full boolean string public String getRunInBackground() { return Boolean.toString(run_in_background.equals("t")); } public void setStatus(String status) { this.status = status; } public int getLastRun() { return last_run; } public void setLastRun(int lastRun) { this.last_run = lastRun; } public String getStatus() { return this.status; } }
lynch-a/hackmaster9000
HackJob/Job.java
710
// ORMLite needs a no-arg constructor
line_comment
en
true
231208_0
public class findleaders { public static void leaders(int[] input) { /* Your class should be named Solution * Don't write main(). * Don't read input, it is passed as function argument. * Print output and don't return it. * Taking input is handled automatically. */ int n = input.length; int [] leader = new int [n]; int lc =0; int max = input[n-1]; leader[lc++]= max; for(int i =n-2; i>=2; i--){ if(input[i]>= max){ max = input[i]; leader[lc++]=max; } } for(int i = 0; i<lc;i++){ System.out.print(leader[i]+" "); } } public static void main(String[] args) { int arr[]= {1,3,5,6,7,3}; leaders(arr); } }
nishthaaggarwal15/Leaning-java
src/findleaders.java
228
/* Your class should be named Solution * Don't write main(). * Don't read input, it is passed as function argument. * Print output and don't return it. * Taking input is handled automatically. */
block_comment
en
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 <browning@uw.edu>} */ 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
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
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
65511_1
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.CRServo; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.hardware.Gamepad; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.util.ElapsedTime; import com.qualcomm.robotcore.util.Range; import org.firstinspires.ftc.robotcore.external.Telemetry; import com.stormbots.MiniPID; // dumb "pid" that tries to keep the orientation stable // uses the integrated imu public class Pid implements Runnable{ Telemetry t; HardwareMap hwmap; MotorIO motorIO; bno055driver d; MiniPID pidctrl = new MiniPID(2, 0.0, 7); double rawAngle = 0; boolean kys_signal = false; double target = 0; double angleComp = Math.toRadians(180); double[] vec = {0, 0}; boolean enabled = false; public void setTarget(){ this.target = Math.toRadians(d.getAngles()[0]); } public void kys(){ kys_signal = true; } public Pid(Telemetry t, HardwareMap hwmap, MotorIO motorIO){ this.t = t; this.hwmap = hwmap; this.motorIO = motorIO; d = new bno055driver("imu", this.hwmap); } public void enable(){ this.enabled=true; } public void disable(){ this.enabled=false; } public double getAngle(){ return this.rawAngle; } @Override public void run(){ while(!kys_signal){ if(this.enabled){ double rawAngle = Math.toRadians(d.getAngles()[0]); double diff; if(Math.abs(rawAngle - target) > Math.PI){ if(rawAngle<target){ diff = (Math.PI-rawAngle - target); } else{ diff = -(Math.PI-rawAngle - target); } } else{ diff = rawAngle - target; } if(Math.abs(diff)>0.08){ motorIO.setRotation(diff); } else{ motorIO.setRotation(0.0); } } else{ motorIO.setRotation(0.0); } } } }
otaniemenlukio/First-Global-2019
Pid.java
663
// uses the integrated imu
line_comment
en
true
67253_0
/* * Decompiled with CFR 0.152. * * Could not load the following classes: * net.minecraft.client.gui.ScaledResolution */ import i.gishreloaded.deadcode.managers.ShaderManager; import i.gishreloaded.deadcode.utils.visual.RenderUtils; import i.gishreloaded.deadcode.wrappers.Wrapper; import net.minecraft.client.gui.ScaledResolution; public class ai { public static final int a = 20; public d b; public int c; public int d; public String e; public String f; public int g; public int h; public boolean i; public long j; public double k; public long l; public double m; public ai(String string, String string2, int n2, int n3, double d2) { this.e = string; this.f = string2; this.g = n2; this.h = n3; this.b = new d(d2, 1.0); this.a(); } public void a(float f2, float f3) { if (this.c == 0) { this.c = Wrapper.INSTANCE.i().a(this.e); } if (this.d == 0) { this.d = Wrapper.INSTANCE.p().a(this.f); } int n2 = 20; int n3 = n2 / 4; float f4 = (float)this.b.b(); int n4 = er.b(aX.f, f4 / 1.5f); int n5 = er.b(this.g, f4); int n6 = er.b(this.h, f4); if (RenderUtils.a()) { ShaderManager.b().a(f2 - (float)this.c - (float)(n3 * 2), f3, f2, f3 + 20.0f, 16.0f, 3, n4); ShaderManager.b().a(f2 - (float)this.c - (float)n2 - (float)this.d - (float)n3, f3, f2 - (float)this.c - (float)n2 + (float)n3, f3 + 20.0f, 14.0f, 3, n4); } RenderUtils.a(f2, (double)f3, (double)(f2 - (float)this.c - (float)(n3 * 2)), (double)(f3 + 20.0f), n4); RenderUtils.a(f2 - (float)this.c - (float)n2 + (float)n3, (double)f3, (double)(f2 - (float)this.c - (float)n2 - (float)this.d - (float)n3), (double)(f3 + 20.0f), n4); Wrapper.INSTANCE.i().a(this.e, f2 - (float)this.c - (float)n3, f3 + 4.0f, n5); Wrapper.INSTANCE.p().a(this.f, f2 - (float)this.c - (float)n2 - (float)this.d, f3 + 7.0f, n6); this.b.a(false); this.i = (double)f4 <= 0.1; } public void a() { long l2 = System.currentTimeMillis(); ScaledResolution scaledResolution = new ScaledResolution(Wrapper.INSTANCE.getMinecraft()); this.k = scaledResolution.getScaledWidth(); this.m = -20.0; this.j = l2; this.l = l2; } }
n3xtbyte/deadcode-source
ai.java
906
/* * Decompiled with CFR 0.152. * * Could not load the following classes: * net.minecraft.client.gui.ScaledResolution */
block_comment
en
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
232713_0
public class Workshop2 { public static void main(String[] args) { class Complex { private double r; private double i; String number; public Complex(double real, double imaginary) { r = real; i = imaginary; } public Complex() { r = 0; i = 0; } public void setReal(double real) { r = real; } public void setImaginary(double imaginary) { i = imaginary; } public double getReal() { return r; } public double getImaginary() { return i; } public String toString() { String fullString; if (i > 0) { fullString = r + "+" + i + "i"; } else if (i < 0) { fullString = Double.toString(r) + Double.toString(i) + "i"; } else { //imaginary component = 0 fullString = Double.toString(r); } return fullString; } } Complex obj = new Complex(); obj.setReal(666.86); obj.setImaginary(-21.86); System.out.println(obj.getReal()); System.out.println(obj.getImaginary()); System.out.println(obj.toString()); } }
osbetel/CS-142-Coursework-2015
src/Workshop2.java
318
//imaginary component = 0
line_comment
en
true