text
stringlengths
14
410k
label
int32
0
9
public boolean isDisturbed(Packet p) { Position receiverPos = p.destination.getPosition(); double distanceFromSource = p.origin.getPosition().distanceTo(receiverPos); double poweredDistanceFromSource = Math.pow(distanceFromSource, alpha); double signal = p.intensity/poweredDistanceFromSource; double noise = ambientNoise; for(Packet pack : Runtime.packetsInTheAir) { // iterate over all active packets if(pack == p) { continue; // that's the packet we want } if(pack.origin.ID == p.destination.ID) { // the receiver node of p is sending a packet itself if(!Configuration.canReceiveWhileSending) { return true; } continue; // the interference created from this sender is not considered } // Detect multiple packets that want to arrive in parallel at the same destination. if(!Configuration.canReceiveMultiplePacketsInParallel && pack.destination.ID == p.destination.ID ) { return true; } Position pos = pack.origin.getPosition(); double distance = pos.distanceTo(receiverPos); double poweredDistance = Math.pow(distance, alpha); noise += pack.intensity / poweredDistance; } boolean disturbed = signal < beta * noise; if(LogL.INTERFERENCE_DETAIL) { Global.log.logln("Node "+p.destination.ID+" is checking a packet from "+p.origin.ID); if(disturbed){ Global.log.logln("Dropped the message due to too much interference."); } } return disturbed; }
8
private String getExpressionType(Expr expr){ String type; if (expr instanceof NumberExpr){ type = "Number"; }else if (expr instanceof LiteralExpr){ type = "String"; }else if (expr instanceof FunctionCallExpr){ String fktName = ((FunctionCallExpr) expr).getFunctionName(); if (fktName.equals("true()") || fktName.equals("false()")){ type = "Boolean"; }else{ type = "Unexpected Type"; System.err.println("Die Funktion "+fktName+" ist nicht zugelassen. Es sind nur die Funktionen true() oder false() zugelassen."); System.exit(0); } }else{ //if (expr instanceof Expr) { type = "PathExpression"; } return type; }
5
public int getLoopLength(BrainFuckCode code, boolean forvardSearch){ int loopLenght = 0; int numberOfInnerLoops = 0; int currentPosition = code.getCurrentPosition(); while (currentPosition > 0 && currentPosition < code.getCode().length()){ switch (code.getCode().charAt(currentPosition)){ case BrainFuckConstants.WHILE: numberOfInnerLoops++; break; case BrainFuckConstants.END: numberOfInnerLoops--; break; } loopLenght++; if(numberOfInnerLoops == 0) break; if (forvardSearch) currentPosition ++; else currentPosition --; } return loopLenght - 1; }
6
private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusLost if(!nombreAntiguo.equals(jTextField1.getText())){ int i = JOptionPane.showConfirmDialog(frame, "Seguro que quieres cambiar la descripción de la política: "+nombreAntiguo+ "\npor "+jTextField1.getText()); if(i==0){ for (int j = 0; j < EntityDB.getInstance().getPlanesDeSoporte().size(); j++) { ArrayList p = ((Estructuras.PlanDeSoporte)EntityDB.getInstance().getPlanesDeSoporte().get(j)).getPoliticasQueSoporta(); for (int k = 0; k < p.size(); k++) { if(p.get(k).equals(nombreAntiguo)){ p.set(k, jTextField1.getText()); } } } Stack s = new Stack(); s.push(EntityDB.getInstance().getRoot()); while(s.size() != 0){ Entidad_P p = (Entidad_P)s.pop(); if(p.getNombre().equals(nombreAntiguo)){ p.setNombre(jTextField1.getText()); } for (int j = 0; j < p.getHijas().length; j++) { s.push(p.getHijas()[j]); } } nombreAntiguo = jTextField1.getText(); } } }//GEN-LAST:event_jTextField1FocusLost
8
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Township)) { return false; } Township other = (Township) object; if ((this.townshipID == null && other.townshipID != null) || (this.townshipID != null && !this.townshipID.equals(other.townshipID))) { return false; } return true; }
5
public void calcRow(int step) { int variableCount = Expression.getVariableCount(); String binaryStep = Integer.toBinaryString(step); while (binaryStep.length() < variableCount) { binaryStep = "0" + binaryStep; // " step 2 = '10' but if i have 3 steps i need '010' } List<String> steps = new ArrayList<>(Expression.getFullExpression()); List<Integer> results = new ArrayList<>(); for (int i = 0; i < variableCount; i++) { results.add(Integer.parseInt(Character.toString(binaryStep.charAt(i)))); } for (int i = variableCount; i < steps.size(); i++) { String currentStep = steps.get(i); for (int j = 0; j < variableCount; j++) { currentStep = currentStep.replace(steps.get(j).charAt(0), binaryStep.charAt(j)); } results.add(Integer.parseInt(calcStep(currentStep))); } List<String> stringResults = new ArrayList<>(); for (int r : results) { stringResults.add(Integer.toString(r)); } fullTable.add(stringResults); }
5
public static void unpackConfig(Archive container) { NpcDefinition.buffer = new Stream(container.get("npc.dat")); Stream stream2 = new Stream(container.get("npc.idx")); int totalNPCs = stream2.getUnsignedShort(); NpcDefinition.npcIndices = new int[totalNPCs]; int i = 2; for (int j = 0; j < totalNPCs; j++) { NpcDefinition.npcIndices[j] = i; i += stream2.getUnsignedShort(); } NpcDefinition.cache = new NpcDefinition[20]; for (int k = 0; k < 20; k++) { NpcDefinition.cache[k] = new NpcDefinition(); } }
2
public void refreshTab(int index) { if (index > -1) { if (itemsPrice.size() > 0) priceField.setText(formatter.format(itemsPrice.get(index))); quantityTextField.setText("1"); if (itemsQuantity.size() > 0) { availableQuantityField.setText(Integer.toString(itemsQuantity.get(index))); grandTotalField.setText(formatter.format(grandTotal)); productComboBox.setSelectedIndex(index); if (supplierComboBox.getSelectedIndex() != 0) { supplierIDField.setText(Integer.toString(driver.getPersonDB().getSupplierList() .get((supplierComboBox.getSelectedIndex() - 1)).getId())); } } if(productComboBox.getSelectedItem()!=null) if(driver.getStockDB().getProductByName(productComboBox.getSelectedItem().toString())!=null){ availableQuantityField.setText(""+driver.getStockDB().getProductByName(productComboBox.getSelectedItem().toString()).getQuantity()); priceField.setText(""+driver.getStockDB().getProductByName(productComboBox.getSelectedItem().toString()).getProduct().getSupplierPrice()); } else{ availableQuantityField.setText("0"); priceField.setText("0.00"); } } revalidate(); repaint(); }
6
private boolean checkLapsedMillis() { if (System.currentTimeMillis() - timer > 1000) { return true; } else { return false; } }
1
public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> currentLevelValue = new ArrayList<Integer>(); Stack<TreeNode> currentLevelTree = new Stack<TreeNode>(); Stack<TreeNode> nextLevelTree = new Stack<TreeNode>(); int level = 0; if (root == null) return result; currentLevelTree.push(root); while (!currentLevelTree.isEmpty() || !nextLevelTree.isEmpty()) { level++; currentLevelValue = new ArrayList<Integer>(); while (!currentLevelTree.isEmpty()) { TreeNode currentNode = currentLevelTree.pop(); currentLevelValue.add(currentNode.val); if (level % 2 != 0) { if (currentNode.left != null) { nextLevelTree.push(currentNode.left); } if (currentNode.right != null) { nextLevelTree.push(currentNode.right); } } else { if (currentNode.right != null) { nextLevelTree.push(currentNode.right); } if (currentNode.left != null) { nextLevelTree.push(currentNode.left); } } } result.add(currentLevelValue); currentLevelTree = nextLevelTree; nextLevelTree = new Stack<TreeNode>(); } return result; }
9
private void reload() throws IOException { File f = new File("servers.json"); if(!f.exists()) { writeServers(); System.out.println(Client.instance.translation.translate("file.created", "servers.json")); } servers = new Gson().fromJson(new InputStreamReader(new FileInputStream("servers.json"), Charset.forName("UTF-8")), new TypeToken<List<ServerListEntry>>(){}.getType()); if(!servers.containsAll(ServerListEntry.DEFAULT)) { servers.addAll(0, ServerListEntry.DEFAULT); writeServers(); } adapter = new ListAdapter<ServerListEntry>(servers) { @Override public int getHeight(ServerListEntry element, GuiScrollList parent) { return 100; } @Override public int getWidth(ServerListEntry element, GuiScrollList parent) { return parent.getWidth(); } @Override public Gui get(ServerListEntry element, GuiScrollList parent) { return element.getGui(); } }; serverList = new GuiScrollList(this, adapter, 1, 0, 0); for(ServerListEntry e : servers) e.ping(); controlList.add(serverList); }
3
@Override public void paintShape(mxGraphics2DCanvas canvas, String text, mxCellState state, Map<String, Object> style) { Rectangle rect = state.getLabelBounds().getRectangle(); Graphics2D g = canvas.getGraphics(); if (labelGlyphs == null) { updateLabelBounds(text, style); } if (labelGlyphs != null && (g.getClipBounds() == null || g.getClipBounds().intersects( rect))) { // Creates a temporary graphics instance for drawing this shape float opacity = mxUtils.getFloat(style, mxConstants.STYLE_OPACITY, 100); Graphics2D previousGraphics = g; g = canvas.createTemporaryGraphics(style, opacity, state); Font font = mxUtils.getFont(style, canvas.getScale()); g.setFont(font); Color fontColor = mxUtils.getColor(style, mxConstants.STYLE_FONTCOLOR, Color.black); g.setColor(fontColor); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, FONT_FRACTIONALMETRICS); for (int j = 0; j < labelGlyphs.length; j++) { mxLine parallel = labelGlyphs[j].glyphGeometry; if (labelGlyphs[j].visible && parallel != null && parallel != mxCurve.INVALID_POSITION) { mxPoint parallelEnd = parallel.getEndPoint(); double x = parallelEnd.getX(); double rotation = (Math.atan(parallelEnd.getY() / x)); if (x < 0) { // atan only ranges from -PI/2 to PI/2, have to offset // for negative x values rotation += Math.PI; } final AffineTransform old = g.getTransform(); g.translate(parallel.getX(), parallel.getY()); g.rotate(rotation); Shape letter = labelGlyphs[j].glyphShape; g.fill(letter); g.setTransform(old); } } g.dispose(); g = previousGraphics; } }
9
public boolean carOnLane(Car fCar, Lane lane) { PathIterator p = fCurve.getPathIterator(null); FlatteningPathIterator f = new FlatteningPathIterator(p, reduceCarSpeed(fCar.getSpeed())); while (!f.isDone()) { float[] pts = new float[6]; switch (f.currentSegment(pts)) { case PathIterator.SEG_MOVETO: case PathIterator.SEG_LINETO: Point2D point = new Point2D.Float(pts[0], pts[1]); if (point.distance(fCar.getPosition()) <= 1) { return true; } } f.next(); } return false; }
4
public static void main(String[] arguments) { //ファイルからテキスト群を読み込み ArrayList<String> texts = ForestExample.loadFile(); //読み込んだテキストからブランチを生成 branches = ForestExample.loadBranch(texts); //読み込んだテキストからノード生成 nodes = ForestExample.loadNode(texts,branches); //ルートの設定 roots = ForestExample.loadRoot(nodes); //ツリー ArrayList<Tree> trees = new ArrayList<Tree>(); for(Root aRoot : roots) { trees.add(new Tree(aRoot)); } for(Tree aTree : trees) { HashMap<Integer,Node> children = aTree.createTreeRoot(); if(children != null) { for(Node aNode : children.values()) { ForestExample.createTree(aNode,aTree); } } } for(Tree aTree : trees) { aForest.addTree(aTree); } ForestModel aModel = new ForestModel(aForest,branches); aModel=new ForestModel(aForest,branches); ForestView aView = new ForestView(aModel, new ForestController()); open(aView,aModel); }
5
private void checkFullHouse() { if (getNumberOfSuits(1) == 1 && getNumberOfSuits(2) == 1 && getNumberOfSuits(3) == 1 && getNumberOfSuits(4) == 1) { myEvaluation[0] = 7; myEvaluation[1] = hand[0].getValue(); myEvaluation[2] = hand[4].getValue(); myEvaluation[3] = hand[0].getValue(); } }
4
public static ArrayList<Commands> Sort(ArrayList<Commands> list){ ArrayList<Commands> commands = new ArrayList<>(); for(Commands var1 : list){ if(var1.getCommand().equals("ADD")){ commands.add(var1); } } for(Commands var2 : list){ if(var2.getCommand().equals("MOVE")){ commands.add(var2); } } for(Commands var3 : list){ if(var3.getCommand().equals("DEL")){ commands.add(var3); } } return commands; }
6
boolean isEmpty() { return this.aNotification.size() <= 0; }
0
private void initGUI() { try { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); GroupLayout thisLayout = new GroupLayout((JComponent)getContentPane()); getContentPane().setLayout(thisLayout); this.setTitle("Tile Puzzle Solver"); pack(); this.setSize(894, 442); this.setSize(Toolkit.getDefaultToolkit().getScreenSize()); this.setExtendedState(Frame.MAXIMIZED_BOTH); { jPanel1 = new JPanel(); GroupLayout jPanel1Layout = new GroupLayout((JComponent)jPanel1); jPanel1.setLayout(jPanel1Layout); { progressBar = new JProgressBar(0, 100000); progressBar.setValue(0); progressBar.setStringPainted(true); theApp.setProgressBar(progressBar); } { rotatePieceFlag = new JCheckBox(); rotatePieceFlag.setText("Rotate Pieces?"); } { solutionNumLabel = new JLabel(); solutionNumLabel.setText("0 solutions found"); } { cancelButton = new JButton(); cancelButton.setText("Forget It!"); cancelButton.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent arg0) { theApp.killEverything(); progressBar.setString("Cancelled"); } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } }); } { solveButton = new JButton(); solveButton.setText("Solve"); solveButton.setBounds(23, 45, 86, 23); solveButton.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent arg0) { // Solve the puzzle and display drawCanvas.redrawGrid(600, 600, theApp.getBoard(), drawCanvas.getGraphics()); //drawCanvas.drawSolution(theApp.solve(theApp.getPuzzle())); theApp.solve(theApp.getPuzzle()); //Piece p = theApp.solve(theApp.getPuzzle()).get(0).getPieces().get(0); //Position pos = theApp.solve(theApp.getPuzzle()).get(0).getPositions().get(0); //drawCanvas.outlinePiece(0, 0, 0, 0, p, drawCanvas.getGraphics()); } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } }); } { leftButton = new JButton(); leftButton.setText("<-"); leftButton.setFont(new java.awt.Font("Segoe UI",0,12)); leftButton.setEnabled(false); leftButton.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent arg0) { if(currSol == 1) leftButton.setEnabled(false); if(currSol > 1){ rightButton.setEnabled(true); currSol--; drawCanvas.drawSolution(theApp.getSolution(currSol - 1)); solDisplayLabel.setText(currSol + "/" + totalSol); } } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } }); } { solDisplayLabel = new JLabel(); solDisplayLabel.setText("0/0"); } { rightButton = new JButton(); rightButton.setText("->"); rightButton.setFont(new java.awt.Font("Segoe UI",0,12)); rightButton.setEnabled(false); rightButton.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent arg0) { if(currSol == totalSol) rightButton.setEnabled(false); if(currSol < totalSol){ currSol++; drawCanvas.drawSolution(theApp.getSolution(currSol - 1)); solDisplayLabel.setText(currSol + "/" + totalSol); leftButton.setEnabled(true); } } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } }); } { fileLabel = new JLabel(); fileLabel.setText("No File..."); } { flipPieceFlag = new JCheckBox(); flipPieceFlag.setText("Reflect Pieces?"); } { loadButton = new JButton(); loadButton.setText("Load File"); loadButton.setBounds(23, 17, 86, 23); loadButton.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent arg0) { fileSelectFrame fsFrame = new fileSelectFrame(theApp); if(fsFrame.getFileName().equals("")) { fileLabel.setText("No File..."); }else{ fileLabel.setText(fsFrame.getFileName()); } } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } }); } jPanel1Layout.setHorizontalGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup() .addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(cancelButton, GroupLayout.PREFERRED_SIZE, 116, GroupLayout.PREFERRED_SIZE) .addGap(32)) .addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(solveButton, GroupLayout.PREFERRED_SIZE, 116, GroupLayout.PREFERRED_SIZE) .addGap(32)) .addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(loadButton, GroupLayout.PREFERRED_SIZE, 116, GroupLayout.PREFERRED_SIZE) .addGap(32)) .addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(flipPieceFlag, GroupLayout.PREFERRED_SIZE, 135, GroupLayout.PREFERRED_SIZE) .addGap(13)) .addComponent(progressBar, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(rotatePieceFlag, GroupLayout.PREFERRED_SIZE, 135, GroupLayout.PREFERRED_SIZE) .addGap(13))) .addGroup(jPanel1Layout.createParallelGroup() .addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(leftButton, GroupLayout.PREFERRED_SIZE, 53, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(solDisplayLabel, GroupLayout.PREFERRED_SIZE, 37, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(rightButton, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE) .addGap(0, 52, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(leftButton, solutionNumLabel, LayoutStyle.ComponentPlacement.INDENT) .addGroup(jPanel1Layout.createParallelGroup() .addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(solutionNumLabel, GroupLayout.PREFERRED_SIZE, 177, GroupLayout.PREFERRED_SIZE) .addGap(0, 34, Short.MAX_VALUE)) .addComponent(fileLabel, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 211, GroupLayout.PREFERRED_SIZE))))); jPanel1Layout.setVerticalGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(loadButton, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(fileLabel, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 1, GroupLayout.PREFERRED_SIZE) .addComponent(flipPieceFlag, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(rotatePieceFlag, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 1, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(leftButton, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(solDisplayLabel, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(rightButton, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(solveButton, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(cancelButton, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 1, GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(progressBar, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(solutionNumLabel, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)) .addContainerGap(48, 48)); } { drawCanvas = new Grid(600, 600, new Piece(new Square[1][1])); // Create new Grid and draw } thisLayout.setVerticalGroup(thisLayout.createSequentialGroup() .addContainerGap() .addGroup(thisLayout.createParallelGroup() .addGroup(thisLayout.createSequentialGroup() .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, 227, GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup() .addGap(50) .addComponent(drawCanvas, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(0, 161, Short.MAX_VALUE))) .addContainerGap(165, 165)); thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, 371, GroupLayout.PREFERRED_SIZE) .addGap(131) .addComponent(drawCanvas, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addContainerGap(293, Short.MAX_VALUE)); this.validate(); // Make sure layout is ok } catch (Exception e) { //add your error handling code here e.printStackTrace(); } }
6
private static void createTempJarInner(JarOutputStream out, File f, String base) throws IOException { if (f.isDirectory()) { File[] fl = f.listFiles(); if (base.length() > 0) { base = base + "/"; } for (int i = 0; i < fl.length; i++) { createTempJarInner(out, fl[i], base + fl[i].getName()); } } else { // filter MANIFEST created by M2E eclipse plugin if(base.equalsIgnoreCase("META-INF/MANIFEST.MF")) return; out.putNextEntry(new JarEntry(base)); FileInputStream in = new FileInputStream(f); byte[] buffer = new byte[1024]; int n = in.read(buffer); while (n != -1) { out.write(buffer, 0, n); n = in.read(buffer); } in.close(); } }
5
public boolean isColliding(GameObject obj){ //If the left side of this is to the left right side of obj and the right side of this is to the right of the left side of obj if(position.getComponent(0) < obj.position.getComponent(0) + obj.width && this.position.getComponent(0) + this.width > obj.position.getComponent(0)){ //IF the top of this is higher than the bottom of obj and the bottom of this is further down than the top of obj if(position.getComponent(1) < obj.position.getComponent(1) + obj.height && this.position.getComponent(1) + this.height > obj.position.getComponent(1)){ return true; } } return false; }
4
public static void main(String[] args) { ThreadB threadB = new ThreadB(); for (int i = 0; i < 5; i++) { new Thread(threadB, "线程名称:(" + i + ")").start(); } try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } //返回对当前正在执行的线程对象的引用 Thread threadMain = Thread.currentThread(); System.out.println("这是主线程:"); System.out.println("返回当前线程组中活动线程的数目:" + Thread.activeCount()); System.out.println("主线程的名称:" + threadMain.getName()); System.out.println("返回该线程的标识符:" + threadMain.getId()); System.out.println("返回线程的优先级:" + threadMain.getPriority()); System.out.println("返回线程的状态:" + threadMain.getState()); System.out.println("返回该线程所属的线程组:" + threadMain.getThreadGroup()); System.out.println("测试线程是否为守护线程:" + threadMain.isDaemon()); // try { // Thread.sleep(10000); // } catch (InterruptedException e) { // e.printStackTrace(); // } }
2
public Object getValueAt(int row, int column) { TokenType type = editableStyles[row]; switch(column) { case 0 : String title = type.toString(); return title.charAt(0) + title.substring(1).toLowerCase(); case 1 : return EditorStyles.getForeground(type); case 2 : return EditorStyles.isBold(type); case 3 : return EditorStyles.isItalic(type); case 4 : return EditorStyles.isUnderline(type); default : return null; } }
5
@Override public void operate(Player player, IncomingPacket packet) { switch (packet.getOpcode()) { /* * Enlists a specified player as a friend. */ case 188: long name = packet.getBuffer().getLong(); player.getPrivateMessaging().addFriendToList(name); break; /* * Removes a specified player as a friend. */ case 215: name = packet.getBuffer().getLong(); player.getPrivateMessaging().getFriends().remove(name); break; /* * Enlists a specified player as an ignore. */ case 133: name = packet.getBuffer().getLong(); player.getPrivateMessaging().addIgnoreToList(name); break; /* * Removes a specified player as an ignore. */ case 74: name = packet.getBuffer().getLong(); player.getPrivateMessaging().getIgnores().remove(name); break; /* * Dispatches a private message over the server's network. * This message is broken down into an array of bytes and re-constructed * on the other end. The name is read as a long and run through an algorithm to * reverse obfuscate the actual name context. */ case 126: name = packet.getBuffer().getLong(); int messageSize = packet.getLength() - 8; byte message[] = packet.readBytes(messageSize); player.getPrivateMessaging().sendPrivateMessage(player, name, message, messageSize); break; } }
5
public static void addCard(Map<String, String> user) { cards.put(user.get("userid"), new Card(gamePanel, user)); gamePanel.setSize(gamePanel.getSize()); }
0
public static int findThreeSumClosest(int[] input, int target) { // sort the array first QuickSort.sort(input, 0 , input.length -1); // set the min value int minDiff = Integer.MAX_VALUE; int result = 0; // iterate from left to right for( int i = 0; i< input.length; i++) { //like 3 sum int start = i+1; int end = input.length -1; while(start < end) { int sum = input[i] + input[start] + input[end]; // if sum becomes target return .. nothing can be closer than this if(sum == target) { minDiff = 0; result = target; return result; } else if(sum < target) { // check if difference is smaller than minDiff if(target - sum < minDiff) { // update the minSum minDiff = target - sum; //record the minimum sum result = sum; } start ++; } else { // if sum is greater than target ..update the minDiffernce and result if(sum - target < minDiff) { minDiff = sum - target; result = sum; } end --; } } } return result; }
6
public Boolean isGameWon(){ for(int i=0;i<getX();i++){ for(int u=0;u<getY();u++){ if(this.cells[i][u]==2048){ return true; } } } return false; }
3
public int getAreaSize() { int rval = 0; if (type == TYPE_RECT) { rval = rect.width * rect.height; } else if (type == TYPE_CIRCLE) { rval = (int) ((double)circle_r * (double)circle_r * Math.PI); } else if (type == TYPE_POLY) { rval = getPolygonArea(poly.xpoints, poly.ypoints, poly.npoints); } return rval; }
3
public MC_Location getLocationAtDirection(MC_DirectionNESWUD dir) { MC_Location loc = new MC_Location(this); if(dir == MC_DirectionNESWUD.NORTH) loc.z--; if(dir == MC_DirectionNESWUD.SOUTH) loc.z++; if(dir == MC_DirectionNESWUD.WEST) loc.x--; if(dir == MC_DirectionNESWUD.EAST) loc.x++; if(dir == MC_DirectionNESWUD.UP) loc.y++; if(dir == MC_DirectionNESWUD.DOWN) loc.y--; return loc; }
6
public void testIllegalCharacters() { System.out.println("\nStarting testIllegalCharacters: users"); try { new User("RegularName"); } catch (IllegalArgumentException iae) { fail("iae not expected."); } try { new User("NumbersWithinName3350"); } catch (IllegalArgumentException iae) { fail("iae not expected."); } try { new User("#BestUserNameEver"); fail("iae expected."); } catch (IllegalArgumentException iae) { } try { new User("Hello World"); fail("iae expected."); } catch (IllegalArgumentException iae) { } try { new User("@!#$%^&*(&^%$&*(^%$&%$"); fail("iae expected."); } catch (IllegalArgumentException iae) { } try { User newUser = new User("ThisIsAValidUserName"); newUser.setUserName("#This&ISNOTAVALID"); fail("iae expected."); } catch (IllegalArgumentException iae) { } System.out.println("Finished testIllegalCharacters: users"); }
6
private ByteBuffer connectClient(String username, String address) { ClientConnectionLogRecord record = new ClientConnectionLogRecord( address, SystemEvent.CLIENT_CONNECTION, "Received connection request from " + address + " for client " + username + "."); LOGGER.log(record); Connection conn = null; try { conn = dbConnectionDispatcher.retrieveDatabaseConnection(); Client tmpClient = FetchClient.execute(username, conn); if (tmpClient == null) { int clientId = CreateClient.execute(username, true, conn); client = new Client(clientId, username, true); record = new ClientConnectionLogRecord(address, SystemEvent.CLIENT_CONNECTION, "Created client " + username + " in the database.", record); LOGGER.log(record); } else { if (tmpClient.isClientOnline()) { RequestResponse failureResponse = new RequestResponse( Status.USER_ONLINE); record = new ClientConnectionLogRecord( address, SystemEvent.CLIENT_CONNECTION, "Responded to connection request from " + address + " with failure since the specified client " + "is already online.", record); LOGGER.log(record); return ProtocolMessage.toBytes(failureResponse); } else { client = tmpClient; ChangeClientStatus.execute(username, true, conn); } } connected = true; record = new ClientConnectionLogRecord(address, SystemEvent.CLIENT_CONNECTION, "Connected client " + username + " successfully, request originated from " + address + ".", record); LOGGER.log(record); conn.commit(); RequestResponse successResponse = new RequestResponse( Status.SUCCESS); return ProtocolMessage.toBytes(successResponse); } catch (SQLException e) { LOGGER.log(new ClientConnectionLogRecord(address, SystemEvent.CLIENT_CONNECTION, "Caught exception while trying to connect client from " + address + ".", record, e)); RequestResponse errorResponse = new RequestResponse( Status.EXCEPTION, e.toString()); if (conn != null) try { conn.rollback(); } catch (SQLException e1) { logRollbackException(e1); } return ProtocolMessage.toBytes(errorResponse); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { logCloseException(e); } } } }
7
public JTextField getjTextFieldAdresse() { return jTextFieldAdresse; }
0
private ArrayList<Chord> trackAnalyze(Track track){ ArrayList<Chord> result = new ArrayList<Chord>(); long tick = -1; int t = 0; while(t<track.size()-1){ try{ ShortMessage tmp = (ShortMessage) track.get(t).getMessage(); long newTick = track.get(t).getTick(); if (tmp.getCommand()>=144 && tmp.getCommand()<=159 && newTick != tick){ Chord newChord = new Chord(tick); tick = newTick; newChord.addMessage(tmp); int size = result.size(); if(size != 0){ result.get(size-1).setEnd(tick); } result.add(newChord); }else if (tmp.getCommand()>=144 && tmp.getCommand()<=159 && newTick == tick){ result.get(result.size()-1).addMessage(tmp); } }catch(Exception e){} t++; } return result; }
9
@Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String Name = request.getParameter("Name"); String City = request.getParameter("City"); String Address = request.getParameter("Address"); String Province = request.getParameter("Province"); String Postalcode = request.getParameter("Postalcode"); if(Name.equals("") || City.equals("") || Address.equals("")||Province.equals("")||Postalcode.equals("")) { return mapping.findForward("error"); } else{ model.Player player = new model.Player(Name,Address,City,Province,Postalcode); HttpSession session=request.getSession(); session.setAttribute("player", player); new PlayerService().getplayer(player); return mapping.findForward("sucess");} }
5
private void btnSaveProfilesMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSaveProfilesMousePressed HashMap<String, Profile> profiles = manager.getProfiles(); for (String username : profiles.keySet()) { try { profiles.get(username).save(); } catch (IOException e) { e.printStackTrace(); } } }//GEN-LAST:event_btnSaveProfilesMousePressed
2
public String getMessage() { return "Congrats!"; }
0
public static boolean isBombed(int x, int y, int[][] sea) { return (isHit(x, y, sea) || isMiss(x, y, sea)); }
1
public static Long makeLong( String s) throws Exception { long val =0; if( s.length() > 32) throw new Exception("Can't encode"); for(int x=0; x < s.length(); x++) { char c = s.charAt(x); if( c== 'A') { val =val | ( A_INT << (x*2)); } else if ( c== 'C') { val = val | (C_INT << (x*2) ); } else if ( c== 'G') { val = val | (G_INT << (x*2) ); } else if ( c == 'T') { val = val | (T_INT << (x*2)); } else return null; } return val; }
6
public static byte[] bytesFromValue(final Value value) throws UnsupportedEncodingException { byte[] bytes; switch (value.getType()) { case NIL: bytes = new byte[]{NIL}; break; case BOOLEAN: if (value.getBooleanValue()) { bytes = new byte[]{BOOLEAN, 0x01}; } else { bytes = new byte[]{BOOLEAN, 0x00}; } break; case INTEGER: { final byte[] intBytes = ByteInteger.bytesFromInt(value.getIntegerValue()); bytes = new byte[]{ INTEGER, intBytes[ByteInteger.FIRST_BYTE], intBytes[ByteInteger.SECOND_BYTE], intBytes[ByteInteger.THIRD_BYTE], intBytes[ByteInteger.FOURTH_BYTE], }; break; } case FLOAT: { final byte[] floatBytes = ByteFloat.bytesFromFloat(value.getFloatValue()); bytes = new byte[]{ FLOAT, floatBytes[ByteInteger.FIRST_BYTE], floatBytes[ByteInteger.SECOND_BYTE], floatBytes[ByteInteger.THIRD_BYTE], floatBytes[ByteInteger.FOURTH_BYTE], }; break; } case STRING: { final byte[] stringBytes = ByteString.bytesFromString(value.getStringValue()); bytes = new byte[stringBytes.length + 2]; bytes[0] = STRING; bytes[1] = (byte) stringBytes.length; for (int i = 0; i < stringBytes.length; ++i) { bytes[(i + 2)] = stringBytes[i]; } break; } default: throw new IllegalArgumentException("Unrecognized type byte: " + value.getType() + "!"); } return bytes; }
7
private float normalize(float x) { if (x > 315) return 0; if (x > 225) return 270; if (x > 135) return 180; if (x > 45) return 90; if (x > -45) return 0; if (x > -135) return -90; if (x > -225) return -180; if (x > 315) return -270; return -360; }
8
public int[][] labeling(BufferedImage image){ int label = 0; int width = image.getWidth(); int height = image.getHeight(); labeledImage = new int[height][width]; //start labeling for(int h = 1 ; h < height-1; h++){ for(int w = 1 ; w < width-1; w++){ int pixel = image.getRGB(w,h) & 0xff; if(pixel == BLACK){ int minLabel = getMinLabel(h,w); if(minLabel > 0){ labeledImage[h][w] = minLabel; }else{ label += 1; labeledImage[h][w] = label; } } } } //reset label base on equalivalant for(int h=1;h<height-1;h++){ for(int w=1;w<width-1;w++){ if(equalTable.containsKey(labeledImage[h][w])){ labeledImage[h][w] = findEqualivalant(labeledImage[h][w]); } } } return labeledImage; }
7
private void completeNickname(KeyEvent e) { e.consume(); String text = getText(); if ( text.trim().isEmpty() ) return; AbstractTab activeTab = InputHandler.getActiveTab(); if (activeTab instanceof ChannelTab == false) return; ChannelTab tab = (ChannelTab) activeTab; int position = getCaret().getDot(); int nickStartPos = text.substring(0, position).lastIndexOf(" "); if (nickStartPos == -1) nickStartPos = 0; else nickStartPos++; int nickEndPos = text.indexOf(" ", position); if (nickEndPos == -1) nickEndPos = text.length(); if (nickEndPos < text.length() && text.charAt(nickEndPos) == ':') nickEndPos--; String partialNick = text.substring(nickStartPos, nickEndPos); String completeNickname; if ( tab.contains(partialNick) ) completeNickname = tab.getNickAfter(partialNick); else completeNickname = tab.getCompleteNickname(partialNick); text = text.substring(0, nickStartPos) + completeNickname + text.substring(nickEndPos); setText(text); }
7
@Override public Object getValueAt(int row, int col) { switch (col) { case 0: return this.arrayListSong.get(row).getTitle(); case 1: return this.arrayListSong.get(row).getArtist(); case 2: return this.arrayListSong.get(row).getAlbum(); case 3: return "E"; case 4: return "SU"; case 5: return "I"; case 6: return "N"; case 7: return "S"; default: return null; } }
8
public Command getCommand(String key) { return (Command) commands.get(key); }
0
private void broadenRiver(Tile tile, int broad, int rivnum) { Point[] surrPoints = Utils.getSurroundingPoints(tile.origin); for (Point p : surrPoints) { Tile t = MyzoGEN.getOutput().getTile(p); if (t != null && t.riverID == -1 && t.floor == tile.floor) { t.tile = Tiles.WATER; t.river = true; t.riverID = rivnum; if (broad == 2) { Point[] surrPoints2 = Utils.getSurroundingPoints(p); for (Point p2 : surrPoints2) { Tile t2 = MyzoGEN.getOutput().getTile(p2); if (t2 != null && t2.riverID == -1 && t2.floor == tile.floor) { t2.tile = Tiles.WATER; t2.river = true; t2.riverID = rivnum; } } } } } }
9
@Override public void run() { while (Fenetre._state != StateFen.Level) { // Verifie l'etat du menu toute les demi-seconde try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }
2
final private boolean jj_3R_199() { Token xsp; xsp = jj_scanpos; if (jj_scan_token(113)) { jj_scanpos = xsp; if (jj_scan_token(114)) { jj_scanpos = xsp; if (jj_scan_token(115)) { jj_scanpos = xsp; if (jj_scan_token(116)) { jj_scanpos = xsp; if (jj_scan_token(117)) { jj_scanpos = xsp; if (jj_scan_token(118)) return true; } } } } } if (jj_3R_185()) return true; return false; }
7
private static void writeResampledFile(OtuWrapper wrapper, List<Integer> resampledList, boolean discrete, boolean allSameDepth, int maxIndex, int maxDepth) throws Exception { File outFile = new File( ConfigReader.getBigDataScalingFactorsDir() + File.separator + "risk" + File.separator + "dirk" + File.separator + "resample" + File.separator + "resampled" + (discrete ? "" :"continious") + "_" + (allSameDepth ? "sameDepth" : "") + ".txt" ); System.out.println(outFile.getAbsolutePath()); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); writer.write( "sample" ); for( int x=0; x < wrapper.getOtuNames().size(); x++) writer.write("\t" + wrapper.getOtuNames().get(x)); writer.write("\n"); for( int x=0;x < wrapper.getSampleNames().size(); x++) { int depth = wrapper.getCountsForSample(x); System.out.println( x + " depth= " + depth); writer.write("sample_" + depth); int[] counts = discrete ? resample(wrapper, resampledList, allSameDepth ? maxDepth : depth) : resampleContinious(wrapper, resampledList, x,maxIndex,maxDepth, allSameDepth ); for( int y=0; y < counts.length; y++) writer.write("\t" + counts[y]); writer.write("\n"); writer.flush(); } writer.close(); }
7
public BroadcastMessageParser(byte[] data){ super(data); this.nickLength = data[510]; this.hostLength = data[511]; byte[] tempNickAsBytes = new byte[255]; byte[] tempHostAsBytes = new byte[255]; System.arraycopy(data, 0, tempNickAsBytes, 0, this.nickLength); System.arraycopy(data, 255, tempHostAsBytes, 0, this.hostLength); int i; for(i=0; i < tempNickAsBytes.length; i++){ if(tempNickAsBytes[i] == 0x00){ break; } } int j; for(j=0; j < tempHostAsBytes.length; j++){ if(tempHostAsBytes[j] == 0x00){ break; } } this.nickAsBytes = new byte[i]; this.hostAsBytes = new byte[j]; System.arraycopy(data, 0, this.nickAsBytes, 0, i); System.arraycopy(data, 255, this.hostAsBytes, 0, j); this.nickAsString = new String(this.nickAsBytes); this.hostAsString = new String(this.hostAsBytes); }
4
public static Cons allEquivalentCollections(LogicObject self, boolean reflexiveP) { { Cons equivalents = Cons.consList(Cons.cons(self, Stella.NIL)); List unscannedequivalents = List.list(Cons.cons(self, Stella.NIL)); LogicObject u = null; if (LogicObject.allSupercollections(self).memberP(self)) { loop000 : for (;;) { u = ((LogicObject)(unscannedequivalents.pop())); { LogicObject parent = null; Iterator iter000 = LogicObject.allDirectSupercollections(u, false); while (iter000.nextP()) { parent = ((LogicObject)(iter000.value)); if ((!equivalents.memberP(parent)) && LogicObject.allSupercollections(parent).memberP(u)) { equivalents = Cons.cons(parent, equivalents); unscannedequivalents.push(parent); } } } if (unscannedequivalents.emptyP()) { break loop000; } } } if (reflexiveP) { return (equivalents); } else { return (equivalents.remove(self)); } } }
7
public void sendAttackResult(boolean result) { if (gui != null) { gui.updateState(eBattleFieldMode.Displaying); } Message<Boolean> attackResult = new Message<>(); attackResult.setMessageType(eMessageType.attackResult); attackResult.setDataContainer(result); oponent.sendMessage(attackResult); }
1
* @return Returns true if the the connection between the given terminals * is valid. */ public boolean isValidConnection(Object source, Object target) { return isValidSource(source) && isValidTarget(target) && (isAllowLoops() || source != target); }
3
byte[] expandChunkData(byte[] input, int inputLength, byte[] buffer, PassthroughConnection ptc) { if(buffer.length < inputDataBufferSize + outputDataBufferSize + expandedBufferSize + 320 || inputLength > inputDataBufferSize) { return null; } ptc.inflate.reset(); ptc.inflate.setInput(input, 0, inputLength); int outputOffset = inputDataBufferSize + outputDataBufferSize; int outputLength = expandedBufferSize; int expandedLength = -1; try { expandedLength = ptc.inflate.inflate(buffer, outputOffset, outputLength); } catch (DataFormatException e) { return null; } if(expandedLength != 81920 && expandedLength != 81920 + 320) { return null; } return buffer; }
5
@Override public boolean okMessage(Environmental host, CMMsg msg) { if(((msg.sourceMinor()==CMMsg.TYP_QUIT) ||(msg.sourceMinor()==CMMsg.TYP_SHUTDOWN) ||((msg.targetMinor()==CMMsg.TYP_EXPIRE)&&(msg.target()==oldRoom)) ||(msg.sourceMinor()==CMMsg.TYP_ROOMRESET)) &&(msg.source().location()!=null) &&(msg.source().location().getGridParent()==affected)) { if(oldRoom!=null) oldRoom.bringMobHere(msg.source(),false); if(msg.source()==invoker) unInvoke(); } return super.okMessage(host,msg); }
9
public static void sellItemTester(String name){ if(ItemStorageInventory.create().sellItemfromStorage(name)){ System.out.println("Sell "+ name + " successfully\n"); }else System.out.println("sell "+name+" failed\n"); }
1
@Override public void restoreTemporaryToCurrent(){tmp = new Color(cur.getRGB());}
0
private void getdefaults() { config.options().copyDefaults(true); }
0
private static void getLocations(){ BufferedReader buffer = null; int id = 0; Region region = null; try{ String sCurrentLine; try{ buffer = new BufferedReader (new FileReader("src/Model/Locations.txt")); }catch(FileNotFoundException exc){ exc.printStackTrace(); } while((sCurrentLine = buffer.readLine()) != null){ if(!sCurrentLine.startsWith("\t")){ if(region!=null){ System.out.println(region.toString()); } region = new Region(sCurrentLine, null, 0); }else{ Location location = new Location(sCurrentLine.substring(1, sCurrentLine.length()), null, id++); region.addLocation(location); } } }catch(IOException e){ e.printStackTrace(); }finally{ try { if(buffer != null){ buffer.close(); } }catch(IOException ex){ ex.printStackTrace(); } } }
7
public HTTPResponse generateResponse( ) { try { final DocumentController controller = ControllerFactory.getController( request.getResource().substring(1) ); switch (request.getMethod()) { case GET: return handleGetRequest(controller); case POST: return handlePostRequest(controller); case DELETE: return handleDeleteRequest(controller); default: return new HTTPResponse( HTTPStatus.NOT_ALLOWED, "Method not allowed: " + request.getMethod() ); } } catch (final BadRequestException bre) { return new HTTPResponse( HTTPStatus.BAD_REQ, "Invalid request: " + bre.getMessage() ); } catch (final ControllerNotFoundException cnfe) { return new HTTPResponse( HTTPStatus.NOT_FOUND, "Path not found: /" + cnfe.getController() ); } catch (final DocumentNotFoundException dnfe) { return new HTTPResponse( HTTPStatus.NOT_FOUND, "Document not found: " + dnfe.getUUID() ); } catch (final ServerErrorException see) { return new HTTPResponse( HTTPStatus.INTERNAL_ERR, "Server error: " + see.getMessage() ); } }
7
public static boolean sessionDelete(String sessionID, int versionNum, Server server) { try { DatagramSocket RPCSocket = new DatagramSocket(); RPCSocket.setSoTimeout(1000); String callID = UUID.randomUUID().toString(); // A unique id for this call String tempSend = callID + "^" + SESSIONDELETE_CODE + "^" + sessionID + "^" + versionNum; byte[] outBuffer = marshal(tempSend); DatagramPacket sendPacket = new DatagramPacket(outBuffer, outBuffer.length, server.ip, server.port); RPCSocket.send(sendPacket); // The packet has been sent, now wait for the server to reply byte[] inBuffer = new byte[4096]; DatagramPacket receivedPacket = new DatagramPacket(inBuffer, inBuffer.length); do { receivedPacket.setLength(inBuffer.length); RPCSocket.receive(receivedPacket); } while (!(RPCClient.unmarshal(receivedPacket.getData())).split("\\^")[0].equals(callID)); } catch (SocketException e) { e.printStackTrace(); return false; } catch (UnknownHostException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } // Everything executed without error return true; }
4
private synchronized void recenterMouse() { if (robot != null && comp.isShowing()) { centerLocation.x = comp.getWidth() / 2; centerLocation.y = comp.getHeight() / 2; SwingUtilities.convertPointToScreen(centerLocation, comp); isRecentering = true; robot.mouseMove(centerLocation.x, centerLocation.y); } }
2
@Override public PaintResource get(Widget widget) { final boolean temp = (highlight && widget.isHovered()); return new PaintResource(new GradientPaint(widget.getX(), widget.getY(), (temp) ? primary.brighter() : primary, widget.getX() + ((direction & HORIZONTAL) == HORIZONTAL ? widget.getWidth() : 0), widget.getY() + ((direction & VERTICAL) == VERTICAL ? widget.getHeight() : 0), (temp) ? secondary.brighter() : secondary)); }
5
public int maxProfit(int[] prices) { int max = 0; for(int i =0;i< prices.length-1;i++){ if(prices[i+1]> prices[i]) max += prices[i+1]- prices[i]; } return max; }
2
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(UniFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(UniFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(UniFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(UniFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new UniFrame().setVisible(true); } }); }
6
private void generarOperacionAleatoria(int a, int b, int c) { //En caso de que sea una division y el divisor sea 0, se le asigna un nuevo valor al divisor sin considerar el cero. if (b == 0 && c == 4) { b = Aleatorio(1, 10); } switch (c) { case 1: tareaProceso = a + " + " + b; resultado = a + b; break; case 2: tareaProceso = a + " - " + b; resultado = a - b; break; case 3: tareaProceso = a + " x " + b; resultado = a * b; break; case 4: tareaProceso = a + " / " + b; resultado = ((double) (a) / (double) b); break; } }
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; // Apparently this is bad style, but we need interfaces and classes with // the same name and package to be equal if (getClass().getSuperclass() != obj.getClass().getSuperclass()) return false; AHBObject other = (AHBObject) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (pkg == null) { if (other.pkg != null) return false; } else if (!pkg.equals(other.pkg)) return false; return true; }
9
public static boolean isStringPalindrome(String str){ List<Character> chars = new LinkedList<>(); for (Character item : str.toCharArray()){ chars.add(item); } ListIterator<Character> str1 = chars.listIterator(); ListIterator<Character> str2 = chars.listIterator(chars.size()); while(str1.hasNext() && str2.hasPrevious()){ if(!str1.next().equals(str2.previous())){ return false; } } return true; }
4
int editDistance(String s1, String s2){ if(s1==null && s2==null) return 0; else if(s1==null) return s2.length(); else if(s2==null) return s1.length(); else { int l1 = s1.length(); int l2 = s2.length(); int[][] dp = new int[l1+1][l2+1]; for(int i=0;i<=l1;i++){ for(int j=0;j<=l2;j++){ if(i==0) dp[i][j]=j; else if(j==0) dp[i][j]=i; else if(s1.charAt(i-1)==s2.charAt(j-1)){ dp[i][j] = dp[i-1][j-1]; } else{ dp[i][j]=Math.min(Math.min( dp[i-1][j]+DELETE , //delete s1[i] dp[i][j-1]+INSERT ), //insert s2[j] dp[i-1][j-1]+REPLACE); //replace s1[i] with s2[j]; } } } return dp[l1][l2]; } }
9
public static final ArrayList<SimpleEntry<String, String>> readFile(String filename) { ArrayList<SimpleEntry<String, String>> stringList = new ArrayList<SimpleEntry<String, String>>(); try { FileInputStream input = new FileInputStream(filename); BufferedReader reader = new BufferedReader(new InputStreamReader(new DataInputStream(input))); String line; while ((line = reader.readLine()) != null) { String binaryString = ""; //System.out.println("Line read = " + line); if (line.contains("0x")) { BigInteger value = new BigInteger(line.replace("0x", ""), 16); binaryString = value.toString(2); } else { BigInteger value = new BigInteger(line); binaryString = value.toString(2); } // Add 0 to the begining if the string is less than 32 bit long if (binaryString.length() < 32) { int nbMissingZero = 32 - binaryString.length(); for (int i = 0; i < nbMissingZero; i++) { binaryString = "0" + binaryString; } } assert(binaryString.length() == 32); SimpleEntry<String, String> entry = new SimpleEntry<String, String>(binaryString, line); stringList.add(entry); } reader.close(); } catch (FileNotFoundException e) { System.out.println("Unable to find or open file : " + filename + "\nclosing"); e.printStackTrace(); System.exit(0); } catch (IOException e) { e.printStackTrace(); } return stringList; }
6
private boolean nonZero(Object obj){ if(obj==null) return false; if(obj instanceof Boolean){ return ((Boolean)obj).booleanValue(); } if(obj instanceof Float || obj instanceof Double){ return ((Number)obj).doubleValue()!=0.0; } if(obj instanceof Number){ return ((Number)obj).longValue()!=0; } if(obj instanceof Character){ return ((Character)obj).charValue()!=0; } return true; }
6
protected static Ptg calcSmall( Ptg[] operands ) throws CalculationException { if( operands.length != 2 ) { return new PtgErr( PtgErr.ERROR_VALUE ); } Ptg rng = operands[0]; Ptg[] array = PtgCalculator.getAllComponents( rng ); if( array.length == 0 ) { return new PtgErr( PtgErr.ERROR_NUM ); } int k = new Double( PtgCalculator.getDoubleValueArray( operands[1] )[0] ).intValue(); if( (k <= 0) || (k > array.length) ) { return new PtgErr( PtgErr.ERROR_NUM ); } CompatibleVector sortedValues = new CompatibleVector(); for( Ptg p : array ) { try { Double d = new Double( String.valueOf( p.getValue() ) ); sortedValues.addOrderedDouble( d ); } catch( NumberFormatException e ) { } ; } try { return new PtgNumber( (Double) sortedValues.get( k - 1 ) ); } catch( Exception e ) { return new PtgErr( PtgErr.ERROR_VALUE ); } }
7
public void update(float dt){ if(moving){ if(path!=null) goalPosition = path.getCurrent(); if(goalPosition!=null) { //offset Tile image according to speed? tile.setOffsetX(tile.getOffsetX() + dt); //finished moving? if(true){ if(path!=null){ path.stepIndex(); if(path.completed){ moving = false; goalPosition = null; path = null; } } else { moving = false; goalPosition = null; } } } } }
6
public int Expect(String Data, int NumBytes ) { byte target = 0; int cnt = 0; try { while ((NumBytes--) != 0) { target = file.readByte(); if (target != Data.charAt(cnt++)) return DDC_FILE_ERROR; } } catch (IOException ioe) { return DDC_FILE_ERROR; } return DDC_SUCCESS; }
3
public static ArrayList<Integer> slidingMaximumDqueue(final List<Integer> a, int b) { ArrayList<Integer> result = new ArrayList<Integer>(); Deque<Integer> deque = new ArrayDeque<>(); for (int i = 0; i < b; i++) { while (!deque.isEmpty() && a.get(deque.getLast()) <= a.get(i)) { deque.removeLast(); } deque.addLast(i); } if (a.size() <= b) { result.add(a.get(deque.getFirst())); return result; } System.out.println("queue : " + deque); System.out.println("result : " + result); for (int i = b; i < a.size(); i++) { System.out.println("queue : " + deque); System.out.println("result : " + result); result.add(a.get(deque.getFirst())); while (!deque.isEmpty() && deque.getFirst() <= i - b) { deque.removeFirst(); } while (!deque.isEmpty() && a.get(i) >= a.get(deque.getLast())) { deque.removeLast(); } deque.addLast(i); } result.add(a.get(deque.getFirst())); return result; }
9
private void RemovePlayer(Player player) { if (_fightingPlayers.contains(player)) { _fightingPlayers.remove(player); String message = String.format("Tribute '%s' has been killed", player.getName()); ChatManager.sendMessageToServer("GameMaker", message); } if (_playerSpawns.containsValue(player)) { Location _removeKey = null; for (Iterator<Location> l = _playerSpawns.keySet().iterator(); l .hasNext();) { Location loc = l.next(); if (_playerSpawns.get(loc) == player) { _removeKey = loc; } } if (_removeKey != null) { _playerSpawns.remove(_removeKey); String message = String .format("Tribute '%s' has left their position early and has been terminated", player.getName()); ChatManager.sendMessageToServer("GameMaker", message); } } }
5
public void create(User user) throws RollbackFailureException, Exception { if (user.getArticleList() == null) { user.setArticleList(new ArrayList<Article>()); } EntityManager em = null; try { utx.begin(); em = getEntityManager(); List<Article> attachedArticleList = new ArrayList<Article>(); for (Article articleListArticleToAttach : user.getArticleList()) { articleListArticleToAttach = em.getReference(articleListArticleToAttach.getClass(), articleListArticleToAttach.getArticleID()); attachedArticleList.add(articleListArticleToAttach); } user.setArticleList(attachedArticleList); em.persist(user); for (Article articleListArticle : user.getArticleList()) { User oldAuthorIDOfArticleListArticle = articleListArticle.getAuthorID(); articleListArticle.setAuthorID(user); articleListArticle = em.merge(articleListArticle); if (oldAuthorIDOfArticleListArticle != null) { oldAuthorIDOfArticleListArticle.getArticleList().remove(articleListArticle); oldAuthorIDOfArticleListArticle = em.merge(oldAuthorIDOfArticleListArticle); } } utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception re) { throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); } throw ex; } finally { if (em != null) { em.close(); } } }
7
public void saveIntoXMLFile( String filename ) { try { // set up xml doc factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder(); Document xmlDoc = db.newDocument(); // set up xml builder TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.setOutputProperty( "indent", "yes" ); DOMSource source = new DOMSource(); source.setNode( xmlDoc ); // Transform the word list into a ordered set. Then the output list is ordered. TreeSet< Word > ts = new TreeSet< Word >( wordLib ); for( Word w : ts ) { Element word = xmlDoc.createElement( "word" ); Element english = xmlDoc.createElement( "english" ); english.setTextContent( w.getEnglishContent() ); word.appendChild( english ); Element type = xmlDoc.createElement( "type" ); if( w.getType() == Word.WordType.NORMAL ) { type.setTextContent( "normal" ); } else if( w.getType() == Word.WordType.PERSON_NAME ) { type.setTextContent( "person name" ); } else if( w.getType() == Word.WordType.SPOT_NAME ) { type.setTextContent( "spot name" ); } else { System.out.println( "Unknown word type:" + w.getType().toString() ); System.exit( 0 ); } word.appendChild( type ); Element sentences = xmlDoc.createElement( "sentences" ); for( int i = 0; i < w.getSentences().size(); i++ ) { Element s = xmlDoc.createElement( "sentence" ); s.setTextContent( w.getSentences().get( i ) ); sentences.appendChild( s ); } word.appendChild( sentences ); Element in_time = xmlDoc.createElement( "in_time" ); in_time.setTextContent( w.getIn_time() ); word.appendChild( in_time ); Element last_time = xmlDoc.createElement( "last_time" ); last_time.setTextContent( w.getLast_time() ); word.appendChild( last_time ); Element total_times = xmlDoc.createElement( "total_times" ); total_times.setTextContent( w.getTotal_times() + "" ); word.appendChild( total_times ); Element peak_times = xmlDoc.createElement( "peak_times" ); peak_times.setTextContent( w.getPeak_times() + "" ); word.appendChild( peak_times ); Element article_frequency = xmlDoc.createElement( "article_frequency" ); article_frequency.setTextContent( w.getArticle_frequency() + "" ); word.appendChild( article_frequency ); xmlDoc.appendChild( word ); } StreamResult result = new StreamResult(); result.setOutputStream( new FileOutputStream( filename ) ); t.transform( source, result ); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
9
private void genPositionBloc( int nbPositionBloc ) { PositionBloc position = null; PositionBloc positionNouvelle = null; int numeroVoie = 0; // création manuelle du premier bloc de la voie. if( this.sens == 1 ) { position = new PositionBloc( nom, 2, true ); } else { position = new PositionBloc( nom, 1, true ); } for( int i = 1 ; i <= nbPositionBloc ; i++ ) { numeroVoie = i*2; // numéros de rue pair à droite, et impair à gauche if( this.sens == 1 ) { if( numeroVoie % 2 != 0 ) { numeroVoie = numeroVoie + 1 ; } } else { if( numeroVoie % 2 == 0 ) { numeroVoie = numeroVoie - 1; } } positionNouvelle = new PositionBloc( nom , numeroVoie , false ); position.addSuivant( positionNouvelle ); position = positionNouvelle ; this.blocs.add( position ); } }
5
public void kertausmaatti(){ File kertaustiedosto = kertauspaneeli.hankiTiedosto("Valitse tiedosto"); if (kertaustiedosto != null){ kertausmaatti.setTiedosto(kertaustiedosto); kertausmaatti.haeTunnisteet(); kertauspaneeli.luoTunnisteidenValinta(); CardLayout cd = (CardLayout)paneelikortit.getLayout(); cd.show(paneelikortit, "kertain"); nakyvaKortti = "kertain"; kertausmaatti.talletaAloitusaika(); //vähän epätarkka paikka tallentaa, mutta menköön } }
1
public void printToFile(String filePath) { try { StringBuilder sbOutput = new StringBuilder(); // Output each member of settings. for (Field field : this.getClass().getDeclaredFields()) { String typestr = field.getType().toString().toLowerCase(); if (typestr.endsWith("string") || typestr.endsWith("int") || typestr.endsWith("double") || typestr.endsWith("float") || typestr.endsWith("boolean")) { // We only print the fields with basic types. sbOutput.append(field.getName() + "=" + field.get(this)); sbOutput.append(System.getProperty("line.separator")); } } FileReaderAndWriter.writeFile(filePath, sbOutput.toString()); } catch (Exception ex) { ex.printStackTrace(); } }
7
public void writeCode(Code code) throws IOException { // call putBit() on all bits, from left to right for (int i = code.length() - 1; i >= 0; i--) { putBit(code.getBit(i)); } }
1
public Pair<Symbol, SymbolString> getAmbiguousCore() { AmbNode amb = getMinimalParseTree(); if (amb == null) { String s = "No ambiguity node found for " + top.getRootSymbol() + " : " + top.yield().prettyPrint(); System.out.println(s); //throw new RuntimeException(s); return new Pair<Symbol, SymbolString>(top.getRootSymbol(), top.yield()); } amb.removeNestedAmbiguities(); amb.liftToCharacterClasses(); amb.addPosInfo(0); // remove identical nodes from bottom of all alternatives boolean changed; do { changed = false; Queue<List<ParseTreeNode>> q = new Queue<List<ParseTreeNode>>(); for (int i = 0; i < amb.children.size(); ++i) { List<ParseTreeNode> y = new ArrayList<ParseTreeNode>(); amb.children.get(i).getBottom(y); q.add(y); } Set<ParseTreeNode> remove = new ShareableHashSet<ParseTreeNode>(); List<ParseTreeNode> y = q.get(0); for (ParseTreeNode n : y) { Set<ParseTreeNode> equalNodes = new ShareableHashSet<ParseTreeNode>(); for (int i = 1; i < q.size(); ++i) { for (ParseTreeNode n2 : q.get(i)) { if (n.equalTo(n2) && !remove.contains(n2)) { equalNodes.add(n2); break; } } } if (equalNodes.size() == q.size() - 1) { remove.addAll(equalNodes); remove.add(n); } } amb.removeNodes(remove); changed = remove.size() > 0; } while (changed); amb.reconstructChildren(); return new Pair<Symbol, SymbolString>(amb.getRootSymbol(), amb.yield()); }
9
public void followPlayer(Rachel r){ if(seePlayer(r)){ follow++; } if(follow > 0){ if(r.getY() > getY()){ setDown(true); } else { setDown(false); } if(r.getY() < getY()){ setUp(true); } else { setUp(false); } if(r.getX() < getX()){ setLeft(true); } else { setLeft(false); } if(r.getX() > getX()){ setRight(true); }else { setRight(false); } } }
6
public void maintainDealer() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InterruptedException{ while(true){ Thread.sleep(1);//So that commands don't happen at the same exact time. if(!callsToDealer.isEmpty()){ final ArrayList<Object> methodToRun = callsToDealer.pop(); System.out.println("Processing call: " + methodToRun); final Object[] args = new Object[methodToRun.size()-2]; Class<?>[] typesOfArgs = new Class<?>[methodToRun.size()-2]; for(int i = 2; i < methodToRun.size(); i++){ args[i-2] = methodToRun.get(i); typesOfArgs[i-2] = args[i-2].getClass(); } final Method m = dealer.getClass().getMethod((String)methodToRun.get(1), typesOfArgs); Thread t = new Thread(new Runnable(){ public void run(){ try { m.invoke(dealer, args); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } finishedDealingFor = methodToRun.toString(); } }); t.start(); } } }
8
public void execute() { this.from.removePiece(this.piece); this.to.addPiece(this.piece); this.piece.increaseMoveCount(); }
0
public static String removeAccelerator(String text) { String modifiedText = text; // Search for ~ int location = text.lastIndexOf(CONTROL_2); // If not found then search for hex EE if (location < 0) { location = text.lastIndexOf(CONTROL_1); } // If not found then search for '&' if (location < 0) { location = text.lastIndexOf(CONTROL_3); } if (location >= 0) { modifiedText = text.substring(0, location) + text.substring(location + 1); } return modifiedText; }
3
public static boolean readBoolean() { String token = getNextToken(); boolean bool; try { if (token.toLowerCase().equals("true")) bool = true; else if (token.toLowerCase().equals("false")) bool = false; else { error ("Error reading boolean data, false value returned."); bool = false; } } catch (Exception exception) { error ("Error reading boolean data, false value returned."); bool = false; } return bool; }
3
public static void reset_branch(String num, String filepath, String downloadpath, Scanner scanner){ String line="", result = ""; int item=0; System.out.println("Please choose the reset button's status that you want to test: 1=press, 2=release, 0=return:"); System.out.println("If you choose to test the pressed status, please keep the button pressed before you press 1, until you see the release instruction."); line=scanner.nextLine(); while(!(line.equals("0"))){ while ((!(line.equals("1")))&&(!(line.equals("2")))&&(!(line.equals("0")))){ System.out.println("Error input! "); System.out.println("Please choose the reset button's status that you want to test: 1=press, 2=release, 0=return:"); line=scanner.nextLine(); } if (line.equals("0")){ break; } item = Integer.parseInt(line); switch(item){ case 1: Reset_Press.serialcomm(num); Reset_Press.fileprocess(downloadpath, filepath); break; case 2: Reset_Release.serialcomm(num); Reset_Release.fileprocess(downloadpath, filepath); break; } System.out.println("Please choose the reset button's status that you want to test: 1=press, 2=release, 0=return:"); line=scanner.nextLine(); } }
7
@GET @Path("events/{id}/cars") @Produces({MediaType.APPLICATION_JSON }) public List<Car> getEventCars(@PathParam("id")int idEvent){ System.out.println("Return the cars list of the event selected by the id"); return JpaTest.eventService.getCars(idEvent); }
0
static final int Mix3To1(final int c1, final int c2) { //return (c1*3+c2) >> 2; if (c1 == c2) { return c1; } return ((((c1 & Mask2) * 3 + (c2 & Mask2)) >> 2) & Mask2) | ((((c1 & Mask13) * 3 + (c2 & Mask13)) >> 2) & Mask13) | ((((c1 & Mask4) >> 2) * 3 + ((c2 & Mask4) >> 2)) & Mask4); }
1
public String getAcademicLevel() { return AcademicLevel; }
0
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] split) { boolean r = false; if (sender instanceof Player) { Player player = (Player) sender; if (instance.pex.has(player, "bitreport.report")) { if (split.length > 0) { String data = ""; for (int i = 0; i < split.length; i++) data += " " + split[i]; data = data.trim(); try { // Store player location data String location = player.getLocation().getX() + "," + player.getLocation().getY() + "," + player.getLocation().getZ(); String world = player.getWorld().getName(); // Create query and prepared statement Connection conn = DriverManager.getConnection(url, user, pass); String query = "INSERT INTO `" + reports + "` (`username`, `status`, `data`, `world`, `location`) VALUES (?,?,?,?,?)"; PreparedStatement insert = conn.prepareStatement(query); // Insert the data into the prepared statement insert.setString(1, player.getName()); insert.setInt(2, 0); insert.setString(3, data); insert.setString(4, world); insert.setString(5, location); // Execute the query insert.executeUpdate(); // Get id to send to staff Statement select = conn.createStatement(); ResultSet result = select .executeQuery("SELECT * FROM `" + reports + "` WHERE `data` = '" + data + "'AND `username` = '" + player.getName() + "'"); int id = 0; while (result.next()) { id = result.getInt(1); } // Clean up insert.close(); conn.close(); // Report back to player player.sendMessage(ChatColor.GREEN + "Your ticket has been submitted and should be handled soon."); for (Player p : instance.getServer().getOnlinePlayers()) { if (p.hasPermission("bitreport.claim")) p.sendMessage(ChatColor.RED + "A new ticket (" + ChatColor.YELLOW + "#" + id + ChatColor.RED + ") has been opened by " + player.getName()); } r = true; } catch (SQLException se) { se.printStackTrace(); } } } else { player.sendMessage(ChatColor.YELLOW + "You do not have access to this feature"); r = true; } } if (sender instanceof ConsoleCommandSender) { instance.logInfo("This is an in-game only command."); r = true; } return r; }
9
private boolean isFalseCharacter(char c) { if (c == '(' || c == ')' || c == '1' || c == '0' || c == ' ') return false; for (int i = 0; i < operator.length; i++) { if (c == operator[i]) return false; } return true; }
7
public static boolean ProcessorUpdateList() { File list = FileManager.modList; installedMods = FileManager.installedMods; installedCoreMods = FileManager.installedCoreMods; if (list != null && list.exists()) { try { List<String> mods = FileWriter.readSmallTextFile(FileManager.updaterDir + "/ModList.list"); modProcessList.clear(); for (String mod : mods) { ModInstance modI = ModInstance.convertString(mod); if (modI != null && !modProcessList.contains(modI)) { modProcessList.add(modI); } } for (ModInstance instance : modProcessList) { ListProcessor.processDownlaod(instance); } ListProcessor.cleanModFolder(); debug.add(""); debug.add("All mods updated"); debug.add("TODO::Launch MinecraftLauncher.jar"); return true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.print("Processor can't find list"); debug.add("Updater List not found"); } return false; }
7
private void initComponents() { selectSectionLbl = new JLabel(); selectSectionScrollPanel = new JScrollPane(); selectSectionJTable = new JTable(); selectDirectionLbl = new JLabel(); motherLangTransRadioBtn = new JRadioButton(); transMotherLangRadioButton = new JRadioButton(); backBtn = new JButton(); nextBtn = new JButton(); //======== this ======== setTitle("Learning words - Select section"); setResizable(false); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setAutoRequestFocus(false); Container contentPane = getContentPane(); contentPane.setLayout(null); //---- selectSectionLbl ---- selectSectionLbl.setText("Select section:"); selectSectionLbl.setFont(selectSectionLbl.getFont().deriveFont(selectSectionLbl.getFont().getStyle() | Font.BOLD)); contentPane.add(selectSectionLbl); selectSectionLbl.setBounds(new Rectangle(new Point(15, 5), selectSectionLbl.getPreferredSize())); //======== selectSectionScrollPanel ======== { selectSectionScrollPanel.setViewportView(selectSectionJTable); } final SelectSectionWordsAmountTableModel model = new SelectSectionWordsAmountTableModel(); selectSectionJTable.setModel(model); selectSectionJTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); selectSectionJTable.getColumnModel().getColumn(1).setMaxWidth(0); selectSectionJTable.getColumnModel().getColumn(1).setMinWidth(0); selectSectionJTable.getColumnModel().getColumn(1).setResizable(false); selectSectionJTable.getColumnModel().getColumn(1).setPreferredWidth(0); selectSectionJTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { int row = selectSectionJTable.getSelectedRow(); selectedSectionName = (model.getValueAt(row, 0)).toString(); selectedSectionID = (Integer)(model.getValueAt(row, 1)); if ((Integer)(model.getValueAt(row,2)) > 0) { if (!nextBtn.isEnabled()) { nextBtn.setEnabled(true); } } else { nextBtn.setEnabled(false); } } catch (Exception ex) { ex.printStackTrace(); } } }); contentPane.add(selectSectionScrollPanel); selectSectionScrollPanel.setBounds(10, 30, 430, 219); //---- selectDirectionLbl ---- selectDirectionLbl.setText("Select direction:"); selectDirectionLbl.setFont(new Font("Segoe UI", Font.BOLD, 12)); contentPane.add(selectDirectionLbl); selectDirectionLbl.setBounds(15, 255, 110, 21); //---- motherLangTransRadioBtn ---- motherLangTransRadioBtn.setText("Mother language > Foreign language"); motherLangTransRadioBtn.setSelected(true); contentPane.add(motherLangTransRadioBtn); motherLangTransRadioBtn.setBounds(15, 280, 235, motherLangTransRadioBtn.getPreferredSize().height); motherLangTransRadioBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { selectedDirection = motherLangTransRadioBtn.getName(); } }); motherLangTransRadioBtn.setName("motherLanguageToForeignLanguage"); transMotherLangRadioButton.setName("foreignLanguageToMotherLanguage"); //---- transMotherLangRadioButton ---- transMotherLangRadioButton.setText("Foreign language > Mother language"); transMotherLangRadioButton.setSelected(false); contentPane.add(transMotherLangRadioButton); transMotherLangRadioButton.setBounds(15, 300, 240, transMotherLangRadioButton.getPreferredSize().height); transMotherLangRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { selectedDirection = transMotherLangRadioButton.getName(); } }); //---- backBtn ---- backBtn.setText("Back"); backBtn.setMargin(new Insets(5, 15, 5, 15)); contentPane.add(backBtn); backBtn.setBounds(110, 335, 95, backBtn.getPreferredSize().height); backBtn.addActionListener(new BackButtonListener(this, user)); //---- nextBtn ---- nextBtn.setText("Next"); nextBtn.setMargin(new Insets(5, 15, 5, 15)); contentPane.add(nextBtn); nextBtn.setBounds(10, 335, 95, nextBtn.getPreferredSize().height); nextBtn.setEnabled(false); nextBtn.addActionListener(new NextButtonListener(user, this)); //---- Button Group ---- ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(motherLangTransRadioBtn); buttonGroup.add(transMotherLangRadioButton); contentPane.setPreferredSize(new Dimension(460, 405)); pack(); setLocationRelativeTo(getOwner()); }
3
public boolean win(Value sign) { Boolean win = false; if (sign != Value.empty) { for (int pointer = 0; pointer < EngineField.sizeField; pointer++) { if (checkColumn(pointer, sign)) win = checkColumn(pointer, sign); if (checkLine(pointer, sign)) win = checkLine(pointer, sign); } for (int pointer = 0; pointer < 2; pointer++) { if (checkDiag(pointer, sign)) win = checkDiag(pointer, sign); } } return win; }
6
protected int parseInt(String input) { int i; if (input == null) { i = FAILURE; } else { try { i = Integer.parseInt(input); } catch (NumberFormatException e) { i = FAILURE; } } return i; }
2
public static String quote(String str) { return (str != null ? "'" + str + "'" : null); }
1
public void start(final Stage primaryStage) { try { Context.get().setSingleton(Stage.class, primaryStage); Context.get().setSingleton(Application.class, this); this.application = loadApplicationLoader(); Context.get().setSingleton(ApplicationLoader.class, this.application); this.application.init(primaryStage); final SplashScreen splash = application.getSplashScreen(); if (splash != null) { Context.get().setSingleton(SplashScreen.class, splash); splash.show(); } Thread startup = new Thread() { public void run() { if (splash != null) { splash.updateProgress("Loading Container...", 10); } Container.start(); if (splash != null) { splash.updateProgress("Registering shutdown hook...", 20); } Toolkit.getToolkit().addShutdownHook(new Runnable() { @Override public void run() { Container.stop(); } }); if (splash != null) { splash.updateProgress("Starting UI...", 22); } application.startApplication(); try { sleep(400L); } catch (InterruptedException e) { LOGGER.warn("Startup interrupted.", e); } if (splash != null) { splash.hide(); } } }; startup.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { LOGGER.fatal("Failed to start application.", e); System.exit(-1); } }); startup.start(); } catch (Exception e) { LOGGER.fatal("Failed to start application.", e); System.exit(-1); } }
7
public static void main(String[] args){ HashMap<String, Command> cmds = new HashMap<String, Command>(); cmds.put("ADD", new Add()); cmds.put("DEF", new Define()); cmds.put("DIV", new Div()); cmds.put("MUL", new Mul()); cmds.put("POP", new Pop()); cmds.put("PRN", new Print()); cmds.put("PSH", new Push()); cmds.put("SQR", new Sqrt()); cmds.put("SUB", new Sub()); boolean isInteractive = false;//флаг для интерактивной подсказки if (args.length > 0){ try { input = new Scanner(new FileInputStream(args[0])); System.out.println("Обрабатывается файл " + args[0]); } catch (FileNotFoundException e) { System.out.println("Файл не найден."); System.exit(1); } } else { isInteractive = true; input = new Scanner(System.in); System.out.println("Введите команды, завершая каждую нажатием <Enter>.\nВведите пустую строку для завершения работы."); System.out.print(">>> "); } Stack<Double> stack = new Stack<Double>(); HashMap<String, Double> vars = new HashMap<String, Double>(); while (input.hasNextLine()){ //приглашение, если вводим команды с клавиатуры if (isInteractive){ System.out.print(">>> "); } String cmd = input.nextLine(); String[] splitCmd = cmd.split(" "); //Если в строке содержится комментарий if (splitCmd[0].startsWith("#")){ continue; } try { cmds.get(splitCmd[0].toUpperCase()).execute(stack, vars, splitCmd); } catch (NullPointerException e){ System.out.println("Программа завершена"); System.exit(0); } } System.out.println("Программа завершена"); }
6
private void initialise() throws IOException { // Reads the state of the ContactManager from a CSV File. BufferedReader CSVFile = new BufferedReader(new FileReader(fileName)); String dataRow = CSVFile.readLine(); // System.out.println(dataRow); // Reads each line until the end of the file. while (dataRow != null) { String[] stringArray = dataRow.split(","); // System.out.println(stringArray.toString()); // System.out.println(stringArray[1]); // Checks to see if the line contains a contact or a meeting. int newID = Integer.parseInt(stringArray[1]); if(stringArray[0].equals("contact")) { if(stringArray.length > 3) { loadContact(newID, stringArray[2], stringArray[3]); } else { loadContact(newID, stringArray[2], ""); } } else { // Deserialise the string into a Calendar Object. String[] dateArray = stringArray[2].split("/"); Calendar newDate = new GregorianCalendar(); newDate.set( Integer.parseInt(dateArray[0]), Integer.parseInt(dateArray[1]), Integer.parseInt(dateArray[2]), Integer.parseInt(dateArray[3]), Integer.parseInt(dateArray[4])); // Deserialise the string into a contact set. String[] contactArray = stringArray[3].split("/"); Set<Contact> newContacts = new HashSet<>(); for(String eachIDasString : contactArray) { Contact newContact = getContactFromID(Integer.parseInt(eachIDasString)); newContacts.add(newContact); } if(stringArray[0].equals("meeting")) { loadFutureMeeting(newID, newDate, newContacts); } else if(stringArray[0].equals("pastmeeting")) { loadPastMeeting(newID, newDate, newContacts, stringArray[4]); } } dataRow = CSVFile.readLine(); } CSVFile.close(); }
6