method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
550c811f-4337-4669-abab-5b97c1a8b8b8
0
public void exceptionalMethod() { throw new TestException(); }
d10c2c10-682e-43a3-9a52-89abd63eac25
1
public String updateOffline(Product p) { try { String sql = "UPDATE stock SET productName = ?, count = ?, price = ?, feature = ? where productId = "+p.getpId(); PreparedStatement ps = StatusController.connection.prepareStatement(sql); ps.setString(1, p.getpName()); ps.setInt(2, p.getAmount()); ps.setDouble(3, p.getPrice()); ps.setString(4, p.getpFeature()); //ps.setQueryTimeout(5); //ps.executeUpdate(); //ps.close(); return ps.toString(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; }
e829a34c-0a2e-43d0-be65-17731ad5ac8e
4
public int logIn(String username, String password) { try { String host = "localhost"; socket = new Socket(host, 2001); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); } catch (IOException ex) { Logger.getLogger(ServerCommunicator.class.getName()).log(Level.SEVERE, null, ex); } try { out.println("LOGIN"); if(in.readLine().startsWith("Ok")){ out.println(username); if(in.readLine().startsWith("Ok")){ out.println(password); response = Integer.parseInt(in.readLine()); } else{ System.out.println("Bad response from server."); } } else{ System.out.println("Bad response from server."); } } catch (IOException ex) { Logger.getLogger(ServerCommunicator.class.getName()).log(Level.SEVERE, null, ex); } return response; }
2fa6d097-37ee-40a0-aef0-6f3816a182e1
7
public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null) return q == null; if (q == null) return p == null; TreeIterator ip = new TreeIterator(p); TreeIterator iq = new TreeIterator(q); while (ip.hasNext() && iq.hasNext()) { if (!equalNode(ip.next(), iq.next())) return false; } if (ip.hasNext() || iq.hasNext()) return false; return true; }
5a0491df-fdea-45c5-8e42-c2ce1ab97304
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AdjacencyListElement other = (AdjacencyListElement) obj; if (target == null) { if (other.target != null) return false; } else if (!target.equals(other.target)) return false; if (weight != other.weight) return false; return true; }
484a0145-8e29-4a05-8e6a-38ce26c9f573
3
public List<ObjectiveObj> getObjectiveTable(PreparedStatement pre) { List<ObjectiveObj> items = new LinkedList<ObjectiveObj>(); try { ResultSet rs = pre.executeQuery(); if (rs != null) { while (rs.next()) { ObjectiveObj item = new ObjectiveObj(); item.setObjId(rs.getInt("obj_id")); item.setObjName(rs.getString("obj_name")); items.add(item); } } } catch (Exception ex) { ex.printStackTrace(); } return items; }
b314c762-63a2-4a16-bd4d-9476b92acadd
5
public ArrayList<Copy> getAllCopies(){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ArrayList<Copy> copyList = new ArrayList<Copy>(); try { Statement stmnt = conn.createStatement(); String sql = "SELECT * FROM Copies"; ResultSet res = stmnt.executeQuery(sql); while(res.next()) { copy = new Copy(res.getInt("copy_id"), res.getInt("book_id"), res.getInt("edition"), res.getBoolean("lendable")); copyList.add(copy); } } catch(SQLException e) { System.out.println(e); } return copyList; }
cb33621f-bd8f-4ace-8359-dfd73b44d415
7
protected JPopupMenu createPopupMenu(boolean properties, boolean save, boolean print, boolean zoom) { JPopupMenu result = new JPopupMenu("Chart:"); boolean separator = false; if (properties) { JMenuItem propertiesItem = new JMenuItem( localizationResources.getString("Properties...")); propertiesItem.setActionCommand(PROPERTIES_COMMAND); propertiesItem.addActionListener(this); result.add(propertiesItem); separator = true; } if (save) { if (separator) { result.addSeparator(); separator = false; } JMenuItem saveItem = new JMenuItem( localizationResources.getString("Save_as...")); saveItem.setActionCommand(SAVE_COMMAND); saveItem.addActionListener(this); result.add(saveItem); separator = true; } if (print) { if (separator) { result.addSeparator(); separator = false; } JMenuItem printItem = new JMenuItem( localizationResources.getString("Print...")); printItem.setActionCommand(PRINT_COMMAND); printItem.addActionListener(this); result.add(printItem); separator = true; } if (zoom) { if (separator) { result.addSeparator(); separator = false; } JMenu zoomInMenu = new JMenu( localizationResources.getString("Zoom_In")); this.zoomInBothMenuItem = new JMenuItem( localizationResources.getString("All_Axes")); this.zoomInBothMenuItem.setActionCommand(ZOOM_IN_BOTH_COMMAND); this.zoomInBothMenuItem.addActionListener(this); zoomInMenu.add(this.zoomInBothMenuItem); zoomInMenu.addSeparator(); this.zoomInDomainMenuItem = new JMenuItem( localizationResources.getString("Domain_Axis")); this.zoomInDomainMenuItem.setActionCommand(ZOOM_IN_DOMAIN_COMMAND); this.zoomInDomainMenuItem.addActionListener(this); zoomInMenu.add(this.zoomInDomainMenuItem); this.zoomInRangeMenuItem = new JMenuItem( localizationResources.getString("Range_Axis")); this.zoomInRangeMenuItem.setActionCommand(ZOOM_IN_RANGE_COMMAND); this.zoomInRangeMenuItem.addActionListener(this); zoomInMenu.add(this.zoomInRangeMenuItem); result.add(zoomInMenu); JMenu zoomOutMenu = new JMenu( localizationResources.getString("Zoom_Out")); this.zoomOutBothMenuItem = new JMenuItem( localizationResources.getString("All_Axes")); this.zoomOutBothMenuItem.setActionCommand(ZOOM_OUT_BOTH_COMMAND); this.zoomOutBothMenuItem.addActionListener(this); zoomOutMenu.add(this.zoomOutBothMenuItem); zoomOutMenu.addSeparator(); this.zoomOutDomainMenuItem = new JMenuItem( localizationResources.getString("Domain_Axis")); this.zoomOutDomainMenuItem.setActionCommand( ZOOM_OUT_DOMAIN_COMMAND); this.zoomOutDomainMenuItem.addActionListener(this); zoomOutMenu.add(this.zoomOutDomainMenuItem); this.zoomOutRangeMenuItem = new JMenuItem( localizationResources.getString("Range_Axis")); this.zoomOutRangeMenuItem.setActionCommand(ZOOM_OUT_RANGE_COMMAND); this.zoomOutRangeMenuItem.addActionListener(this); zoomOutMenu.add(this.zoomOutRangeMenuItem); result.add(zoomOutMenu); JMenu autoRangeMenu = new JMenu( localizationResources.getString("Auto_Range")); this.zoomResetBothMenuItem = new JMenuItem( localizationResources.getString("All_Axes")); this.zoomResetBothMenuItem.setActionCommand( ZOOM_RESET_BOTH_COMMAND); this.zoomResetBothMenuItem.addActionListener(this); autoRangeMenu.add(this.zoomResetBothMenuItem); autoRangeMenu.addSeparator(); this.zoomResetDomainMenuItem = new JMenuItem( localizationResources.getString("Domain_Axis")); this.zoomResetDomainMenuItem.setActionCommand( ZOOM_RESET_DOMAIN_COMMAND); this.zoomResetDomainMenuItem.addActionListener(this); autoRangeMenu.add(this.zoomResetDomainMenuItem); this.zoomResetRangeMenuItem = new JMenuItem( localizationResources.getString("Range_Axis")); this.zoomResetRangeMenuItem.setActionCommand( ZOOM_RESET_RANGE_COMMAND); this.zoomResetRangeMenuItem.addActionListener(this); autoRangeMenu.add(this.zoomResetRangeMenuItem); result.addSeparator(); result.add(autoRangeMenu); } return result; }
25881960-b21d-42ff-9757-3dc8f3f40eb6
1
@Test public void resolve() { BigDecimal n1=new BigDecimal(1); BigDecimal n2=new BigDecimal(1); BigDecimal num=new BigDecimal(3); int count=2; while(num.toString().length()<1000){ count++; num=n2.add(n1); n1=n2; n2=num; } print(count); }
523113dd-4640-4c17-9f73-753dfec7e8b4
0
public void setNameFromTextField() { firstNameText.setText((Name.getInstance().getFirstName())); middleNameText.setText((Name.getInstance().getMiddleName())); lastNameText.setText((Name.getInstance().getLastName())); }
71d42186-677a-4ac6-9dc2-7e1fe2befcd0
4
public List<Double> getDoubleListFromString(String xArg) { if (xArg == null || xArg.equalsIgnoreCase("")) return null; List<Double> d = new ArrayList<Double>(); char[] c = xArg.toCharArray(); int lastPos = 0; for (int i = 0; i < c.length; i++) { if (c[i] == ',') { d.add(Double.valueOf(returnMergedCharacters(lastPos, i, c))); lastPos = i + 1; } } //Add final double. d.add(Double.valueOf(returnMergedCharacters(lastPos, c.length, c))); return d; }
42456ce8-1586-4b46-a595-bc795cb218d8
2
private boolean has6Neighbors(PieceCoordinate butterflyPos) { int neighbors = 0; Iterator<Entry<PieceCoordinate, HantoPiece>> pieces = board.entrySet().iterator(); PieceCoordinate next; while(pieces.hasNext()) { Entry<PieceCoordinate, HantoPiece> entry = pieces.next(); next = entry.getKey(); if (next.isAdjacentTo(butterflyPos)) neighbors++; } return neighbors == 6; }
179dd8d9-ecd8-46f1-b1f7-b98c809aabaf
1
public static BufferedImage loadImage(String path){ try { return ImageIO.read(new FileInputStream("res/" + path + ".png")); } catch (IOException e) { e.printStackTrace(); } return null; }
5e283e1b-83d8-4c91-bc82-dc97a0ea493f
5
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SanitizeEvent other = (SanitizeEvent) obj; if (!Objects.equals(this.streamName, other.streamName)) { return false; } if (!Objects.equals(this.sanitizedEventId, other.sanitizedEventId)) { return false; } return true; }
bacd689d-00cc-49e9-8740-00343468a79d
1
public void submitMode(boolean isSubmitMode) { if (isSubmitMode) { submissionPane.setViewportView(new SubmitView(this)); } else { submissionPane.setViewportView(submissionView); } }
bb606329-06b3-470d-b5a7-f4017c899fb2
7
private void getResponseBipolarList() { titleDLM.removeAllElements(); bipolarQuestionList = bipolarQuestion.getResponseBipolarList(fileName, publicFileName, counterTeamType); if (bipolarQuestionList.size() != 0) { for (int i = 0; i < bipolarQuestionList.size(); i++) { titleDLM.addElement(bipolarQuestionList.get(i).getTitle()); } titleJlst.setSelectedIndex(0); if (!(bipolarQuestionList.get(0).getDescription() == null || bipolarQuestionList.get(0).getDescription().equals("null"))) { descriptionJtxa.setText(bipolarQuestionList.get(0).getDescription()); } // Exists patent claim bipolarQuestionCurrent = bipolarQuestionList.get(0); if (bipolarQuestionCurrent.getBipolarQuestionParent() != null) { parentContentJlbl.setText(bipolarQuestionCurrent.getBipolarQuestionParent().getTitle()); // Store parent title parentIdJlbl.setText(bipolarQuestionCurrent.getBipolarQuestionParent().getId()); // Store Parent id } else { parentContentJlbl.setText("None"); } dialogContentJlbl.setText(bipolarQuestionCurrent.getDialogState()); playerContentJlbl.setText(bipolarQuestionCurrent.getName()); if (bipolarQuestionCurrent.getName().equals(userLogin.getName()) && bipolarQuestionCurrent.getDialogState().equals("Private")) { editDetailsJbtn.setEnabled(true); deleteActionJbtn.setEnabled(true); } else { editDetailsJbtn.setEnabled(false); deleteActionJbtn.setEnabled(false); } } }
00fee885-628c-4e28-b4da-be347fecc5a9
7
private Class _clazz(Class clazz){ switch(clazz.getName()){ case "boolean": return java.lang.Boolean.class; case "int": return java.lang.Integer.class; case "float": return java.lang.Float.class; case "double": return java.lang.Double.class; case "long": return java.lang.Long.class; case "byte" : return java.lang.Byte.class; case "char": return java.lang.Character.class; default : return clazz; } }
3dca291d-3a1d-48c1-95db-d5e1536f70b1
6
private boolean compruebaImpactoMisil(Nave jugador){ for (int i=0;i<sprites.size();i++) if (sprites.get(i).getClass()==Misil.class) { Misil laserEnemigo=(Misil)sprites.get(i); if ((laserEnemigo.getX()>jugador.getX() && laserEnemigo.getX()+laserEnemigo.getWidth()<jugador.getX()+jugador.getWidth()) && (laserEnemigo.getY()<jugador.getY()+jugador.getHeight() && laserEnemigo.getY()>jugador.getY())) return false; } return true; }
b75a042e-3a46-4f58-a086-1995b05596ea
8
private void updateClaim(boolean choice1) { switch (claim.getStatus()) { case UnRanked: claim.rank(choice1 ? Claim.Rank.Complex : Claim.Rank.Simple); JOptionPane.showMessageDialog(form, "The claim has been ranked " + (choice1 ? Claim.Rank.Complex : Claim.Rank.Simple)); break; case Ranked: claim.setStatus(choice1 ? Claim.Status.Confirmed : Claim.Status.Declined); if(choice1) { String billingInfo = AutomaticCustomerEmulator.sendForm(); storage.addPayment(claim.getCustomerId(), claim.getId(), claim.getDamageCost(), billingInfo); } else AutomaticCustomerEmulator.sendMail("Your claim was denied"); JOptionPane.showMessageDialog(form, "The claim has been " + (choice1 ? "confirmed" : "declined")); break; default: return; } storage.updateClaim(claim); if (listener != null) { listener.actionPerformed(new ActionEvent(this, 0, null)); } }
943159d5-e526-4522-b5d9-3d86be79e4a2
4
public BrickBreaker() { panel = new BrickBreakerPanel(); //build the frame and attach everything to it. frame = new GameFrame( "Brickbreaker by Jeremy", GAMEHEIGHT, GAMEWIDTH, new BrickBreakerMenu( GAMEWIDTH + BrickBreakerPanel.PANELWIDTH, BrickBreakerMenu.MENUHEIGHT, this), panel, this); gameActive = false; gameTimer = new Timer(); // This section creates all of the default game objects which includes // bricks and a paddle. // Use absolute positioning for the game objects this.setLayout(null); //make a paddle paddle = new Paddle(); add(paddle); paddle.repaint(); //make the bricks bricks = new LinkedList<Brick>(); for (int row = 0; row < BRICKROWS; row++) { for (int col = 0; col < BRICKCOLS; col++) { bricks.add(new Brick(col * Brick.BRICKWIDTH, row * Brick.BRICKHEIGHT + BRICKHEADSPACE, Color.RED)); } } for (Brick x:bricks) { add(x); x.repaint(); } balls = new LinkedList<Ball>(); // Set up the mouse listener to place the game ball. The on-click sets // the ball's location and starts the game this.addMouseListener( new MouseListener() { public void mouseClicked(final MouseEvent arg0) { return; } public void mouseEntered(final MouseEvent arg0) { return; } public void mouseExited(final MouseEvent arg0) { return; } public void mousePressed(final MouseEvent arg0) { if (arg0.getButton() != MouseEvent.BUTTON1) { return; //only care about button 1 } // create the new ball at the click location. Ball newBall = new Ball(arg0.getX() - Ball.DEFAULTRADIUS, arg0.getY() - Ball.DEFAULTRADIUS, Ball.DEFAULTRADIUS); balls.add(newBall); add(newBall); newBall.repaint(); startGame(); } public void mouseReleased(final MouseEvent arg0) { return; } } ); }
3f4d5ecd-7ec4-4d1d-8aba-9bcabf03aca5
8
public void testContext() { int min = -80; int max = 80; int size = max - min; for (double v : new double[] { -15D, -10D, -5D, 5D, 15D }) { double[] table = new double[2]; char[][] data = new char[size][size]; int i = 0; int j = 0; for (double x = min; x < max; x++, i++) { j = 0; for (double y = min; y < max; y++, j++) { double vv = this.cm.evaluate(x, y, 1D); data[i][j] = (vv < 0 ? '.' : ' '); } } ConicContext ctx = new ConicContext(); double[] p = new double[2]; int t = QuadricSection.section(this.cm, v, min, max, table); for (int z = 0; z < t; z++) { double d = Math.floor(table[z]); data[(int) (d - min)][(int) (v - min)] = '*'; ctx.initialize(this.cm, d, v, min, max, min, max); for (int tm = 0; tm < 30; tm++) { ctx.getCurrentInnerPoint(p); data[(int) (p[0] - min)][(int) (p[1] - min)] = '+'; ctx.getCurrentOuterPoint(p); data[(int) (p[0] - min)][(int) (p[1] - min)] = '@'; ctx.next(); } } for (j = 0; j < size; j++) { for (i = 0; i < size; i++) { System.out.print(data[i][j]); } System.out.println(); } } assertTrue(true); }
6d5a4467-8664-4e98-aed6-4cc7045af8fc
8
public void update() { if (walking) animSprite.update(); else animSprite.setFrame(0); if (fireRate > 0) fireRate--; double xa = 0, ya = 0; double speed = 1.0; if (input.up) { ya -= speed; animSprite = up; } else if (input.down) { ya += speed; animSprite = down; } if (input.left) { xa -= speed; animSprite = left; } else if (input.right) { xa += speed; animSprite = right; } if (xa != 0 || ya != 0) { move(xa, ya); walking = true; } else { walking = false; } clear(); updateShooting(); }
16bdd834-eca6-4d18-afeb-88770bf94ea9
2
public static String getSuffixWithDot(String s){ if(s == null || s.isEmpty()){ return null; } int lastDotIndex = s.lastIndexOf("."); int length = s.length(); String suffix = s.substring(lastDotIndex, length); return suffix; }
afdd34cc-a621-4958-99ee-3f2ff6a84b00
4
public void run() { try { Synthesizer synthesizer = MidiSystem.getSynthesizer(); synthesizer.open(); MidiChannel channel = synthesizer.getChannels()[0]; while (true) { if (play == true) { channel.programChange(instType); channel.noteOn(pitch, velocity); pause = 350; play = false; } try { Thread.sleep(pause); } catch (InterruptedException e) { } finally { channel.noteOff(pitch); } pause = 0; } } catch (MidiUnavailableException e) { e.printStackTrace(); } }
9c9cc191-ff26-4f0e-b53f-8850bf669c5a
0
public int getPort() { return port; }
eb75f3fd-012c-4cc2-838f-1a64a5417ba5
1
protected String getTag() { return newArray ? "new[]" : "new"; }
5d8f4d39-a8d8-4cc7-a9b9-839d56599fc5
1
public boolean containsNode(String idRef) { return terminals.containsKey(idRef) || nonterminals.containsKey(idRef); }
777c399c-c8e1-4f48-91ec-9f616b8e4afc
9
public void run() { /* forall v in V doe label(v) <- EMPTY; * for i<-n downto 1 do * let v be an unnumbered vertex with largest label; * number(v); * forall unnumbered neighbours of v do * label(w) <- label(w) + {i} */ NVertexOrder<D> order = new NVertexOrder<D>(); int bestUpperBound = Integer.MAX_VALUE; for( int startVertex=0; startVertex<graph.getNumberOfVertices(); ++startVertex ){ for(NVertex<LBFSData> v : graph){ v.data.visited = false; v.data.labels.clear(); order.order.clear(); } //Set start vertex NVertex<LBFSData> first = graph.getVertex(startVertex); //Update his neigbours updateNeigbours(first, graph.getNumberOfVertices() ); //Add the first vertex to the permutation order.order.add( first.data.getOriginal() ); //for i <- n downto 1 do for( int i=graph.getNumberOfVertices()-1; i>0; --i ){ NVertex<LBFSData> biggest = null; // Vertex with highest label for(int j=0; j<graph.getNumberOfVertices(); ++j) { NVertex<LBFSData> v = graph.getVertex(j); //Only look at vertices that aren't numbered if( ! v.data.visited ) { //Set the first vertex as the init vertex if( biggest==null ) { biggest = v; } else if( lexBigger( v.data.labels, biggest.data.labels ) ) { biggest = v; } } } //Update the neighbours of the selected vertex if( biggest!=null ) { updateNeigbours(biggest, i ); order.order.add( biggest.data.getOriginal() ); } } //Reverse the list Collections.reverse(order.order); //Create the treedecomposition to get the upperbound PermutationToTreeDecomposition<D> pttd = new PermutationToTreeDecomposition<D>(order); pttd.setInput(originalGraph); pttd.run(); int newUpper = pttd.getUpperBound(); if( bestUpperBound > newUpper) { vertexOrder = new NVertexOrder<D>(order); bestUpperBound = newUpper; } } upperbound = bestUpperBound; }
a28b852e-1b6d-4d87-a686-60582e51227c
0
public void setNext(Items next) { this.next = next; }
943938b2-7477-4890-b342-b9ecda398e46
5
public Player getNextLocatorPlayer(){ ArrayList<Player> onlineFriends = getOnlineFriends(); if(onlineFriends.size() == 0) return null; int index = 0; if(playerLocator != null){ Player currLocator = Bukkit.getPlayerExact(playerLocator); System.out.print("1"); if(currLocator != null && onlineFriends.contains(currLocator)){ index = onlineFriends.indexOf(currLocator) + 1; if(index >= onlineFriends.size()) index = 0; } } System.out.print(index); return onlineFriends.get(index); }
64cc0e67-31f3-49da-99c3-698558d6cc3a
8
protected void handleExpandStateChanged() { if (isExpanded()) { if (scrollpane.getParent() != this) add(scrollpane); } else { if (scrollpane.getParent() == this) remove(scrollpane); // collapse all pinnable palette stack children that aren't pinned for (Iterator iterator = getContentPane().getChildren().iterator(); iterator .hasNext();) { Object child = iterator.next(); if (child instanceof PinnablePaletteStackFigure && !((PinnablePaletteStackFigure) child).isPinnedOpen()) { ((PinnablePaletteStackFigure) child).setExpanded(false); } } } if (pinFigure != null) { pinFigure.setVisible(isExpanded() && showPin); } }
6c8ec12c-feda-4bdc-b059-19d2f823436f
3
private void paintNaves(Graphics2D g2d){ int nNaves = juego.getnNaves(); List<Nave> nav=naves; List<Nave> list = (nNaves==2) ? nav : nav.subList(0, 1); for (Nave n : list) { if(n.isVivo()) n.paint(g2d); } }
b4769592-9df0-4527-98d8-7fc104e707ce
7
public void setZeroes(int[][] matrix) { boolean[] row = new boolean[matrix.length]; boolean[] col = new boolean[matrix[0].length]; for(int i=0; i<matrix.length; i++) { for(int j=0; j<matrix[i].length; j++) { if(matrix[i][j] ==0) { row[i] = true; col[j] = true; } } } for(int i=0; i<matrix.length; i++) { for(int j=0; j<matrix[i].length; j++) { if(row[i] || col[j]) matrix[i][j]=0; } } }
771a7c62-f0e0-465a-9cee-726e149d8922
2
public static boolean commitToFile(ArrayList<Employee> employees, String filePath) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); Document employeeDoc; DocumentBuilder docBuilder = dbFactory.newDocumentBuilder(); employeeDoc = docBuilder.newDocument(); Element rootElement = employeeDoc.createElement("Company"); final int count = employees.size(); for (int i = 0; i < count; ++i) { final Employee employee = employees.get(i); Element employeeElement = employeeDoc.createElement("Employee"); Element firstNameElement = employeeDoc.createElement("FirstName"); firstNameElement.setTextContent(employee.getFirstName()); Element lastNameElement = employeeDoc.createElement("LastName"); lastNameElement.setTextContent(employee.getLastName()); Element hoursWorkedElement = employeeDoc.createElement("HoursWorked"); hoursWorkedElement.setTextContent(Integer.toString(employee.getHours())); Element payRateElement = employeeDoc.createElement("PayRate"); payRateElement.setTextContent(Double.toString(employee.getPayRate())); employeeElement.appendChild(firstNameElement); employeeElement.appendChild(lastNameElement); employeeElement.appendChild(hoursWorkedElement); employeeElement.appendChild(payRateElement); rootElement.appendChild(employeeElement); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(rootElement); StreamResult result = new StreamResult(new File(filePath)); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(source, result); } catch (Exception e) { return false; } return true; }
9a574749-d964-49e1-9a1a-667f3165cf4c
0
public void mouseDragged(MouseEvent e) { //System.out.println("============= mouseDragged ============"); moveCamera(e); }
50786d44-e673-47fb-8d6b-df1f0591da8b
0
private static void init(){ // создание и заполнение списка list.add(new Cube(3,0,0)); list.add(new Orb(1,2,5,5)); list.add(new Tetrahedron(1,2,3,12)); list.add(new Cylinder(1,1,5)); //list.add(new Cube(2,0,0)); // list.add(new Orb(3,4,1,0)); // list.add(new Tetrahedron(3,2,6,18)); // list.add(new Cylinder(2,7,5)); // list.add(new Cube(5,0,0)); // list.add(new Orb(1,1,4,3)); }
8fb139a2-8350-46c4-811c-c416027b4800
6
public void renderHUD(Box2D bounds) { super.renderHUD(bounds) ; if (selection.selected() != null) { camera.setLockOffset(infoArea.xdim() / -2, 0) ; } else { camera.setLockOffset(0, 0) ; } camera.updateCamera() ; if (currentPanel != newPanel) { beginPanelFade() ; if (currentPanel != null) currentPanel.detach() ; if (newPanel != null) newPanel.attachTo(infoArea) ; currentPanel = newPanel ; } if (capturePanel) { panelFade = UINode.copyPixels(infoArea.trueBounds(), panelFade) ; capturePanel = false ; } final float TRANSITION_TIME = 0.33f ; float fade = System.currentTimeMillis() - panelInceptTime ; fade = (fade / 1000f) / TRANSITION_TIME ; if (fade <= 1) { GL11.glColor4f(1, 1, 1, 1 - fade) ; UINode.drawPixels(infoArea.trueBounds(), panelFade) ; } }
06eee5ea-1d23-4b54-94f4-bfcc1b4bbca6
5
public final void processFFT(double pitchShift, double[] gFFTworksp) { int k, qpd, index; double real, imag, magn, phase, tmp; double[] gAnaMagn = this.gAnaMagn; double[] gAnaFreq = this.gAnaFreq; double[] gSynMagn = this.gSynMagn; double[] gSynFreq = this.gSynFreq; /* this is the analysis step */ for (k = 0; k <= fftFrameSize2; k++) { /* de-interlace FFT buffer */ real = gFFTworksp[2*k]; imag = gFFTworksp[2*k+1]; /* compute magnitude and phase */ magn = 2.*Math.sqrt(real*real + imag*imag); phase = Math.atan2(imag,real); /* compute phase difference */ tmp = phase - gLastPhase[k]; gLastPhase[k] = phase; /* subtract expected phase difference */ tmp -= (double)k*expct; /* map delta phase into +/- Pi interval */ qpd = (int)(tmp/M_PI); if (qpd >= 0) qpd += qpd&1; else qpd -= qpd&1; tmp -= M_PI*(double)qpd; /* get deviation from bin frequency from the +/- Pi interval */ tmp = osamp*tmp/(2.*M_PI); /* compute the k-th partials' true frequency */ tmp = (double)k*freqPerBin + tmp*freqPerBin; /* store magnitude and true frequency in analysis arrays */ gAnaMagn[k] = magn; gAnaFreq[k] = tmp; } /* ***************** PROCESSING ******************* */ /* this does the actual pitch shifting */ Arrays.fill(gSynMagn, 0); Arrays.fill(gSynFreq, 0); //int fftFrameSize2_1 = fftFrameSize2 - 1; for (k = 0; k <= fftFrameSize2; k++) { index = (int)(k/pitchShift); //double scale = k/pitchShift - index; if (index <= fftFrameSize2) { //if (index <= fftFrameSize2_1) { gSynMagn[k] += gAnaMagn[index]; //gSynMagn[k] += gAnaMagn[index]*(1-scale) + gAnaMagn[index]*scale; gSynFreq[k] = gAnaFreq[index] * pitchShift; } } /* ***************** SYNTHESIS ******************* */ /* this is the synthesis step */ for (k = 0; k <= fftFrameSize2; k++) { /* get magnitude and true frequency from synthesis arrays */ magn = gSynMagn[k]; tmp = gSynFreq[k]; /* subtract bin mid frequency */ tmp -= (double)k*freqPerBin; /* get bin deviation from freq deviation */ tmp /= freqPerBin; /* take osamp into account */ tmp = 2.*M_PI*tmp/osamp; /* add the overlap phase advance back in */ tmp += (double)k*expct; /* accumulate delta phase to get bin phase */ gSumPhase[k] += tmp; phase = gSumPhase[k]; /* get real and imag part and re-interleave */ gFFTworksp[2*k] = magn*Math.cos(phase); gFFTworksp[2*k+1] = magn*Math.sin(phase); /* long s_index = ((long)(phase*ffactor)) % table_len; if(s_index < 0) s_index += table_len; gFFTworksp[2*k] = magn*costable[(int)s_index]; gFFTworksp[2*k] = magn*sintable[(int)s_index]; */ } }
48e8552d-7f71-480c-a136-e87ebc7ccd27
7
private static void printHubDetails (int indent, Device dev) { try { Hub h = new Hub (dev); int ports = h.getNumPorts (); boolean indicator = h.isIndicator (); indentLine (indent, (h.isRootHub () ? "Root " : "") + "Hub, " + ports + " ports" ); indentLine (indent, "overcurrent protection: " + h.getOverCurrentMode () ); indentLine (indent, "power switching: " + h.getPowerSwitchingMode () ); if (indicator) indentLine (indent, "has port indicator LEDs"); if (h.isCompound ()) indentLine (indent, "part of a compound device"); // not showing POTPGT, or hub's own current draw indent -= 4; indentLine (indent, ""); for (int i = 1; i <= ports; i++) { Device child = dev.getChild (i); if (child == null) continue; indentLine (indent, "<!-- Port " + i + (h.isRemovable (i) ? "" : " is built-in.") + " -->"); printDevice (indent, child); } } catch (IOException e) { e.printStackTrace (System.out); } }
6a91a8d5-000a-49d0-9e7f-18be08cc9427
3
public ParticleGenerator(Class<? extends T> impl, actor.interfaces.Movable source) { try { ctor = impl.getConstructor(); } catch (SecurityException e) { e.printStackTrace(); return; } catch (NoSuchMethodException e) { e.printStackTrace(); return; } this.source = source; intensity = 1; }
ee034fb8-6ad5-4a14-a70f-94abf7012fe7
4
public void downloadJarFromJenkins(String urlPrefix, String localPath) { InputStream input = null; FileOutputStream writeFile = null; try { String path = getJenkinsRelativePath(urlPrefix); URL url = new URL(urlPrefix+"lastStableBuild/artifact/"+path); System.out.println(url); URLConnection connection = url.openConnection(); int fileLength = connection.getContentLength(); if (fileLength == -1) { System.out.println("Invalide URL or file."); return; } input = connection.getInputStream(); String fileName = url.getFile().substring(url.getFile().lastIndexOf('/') + 1); writeFile = new FileOutputStream(localPath+'/'+fileName); byte[] buffer = new byte[1024]; int read; int bytesDownloaded = 0; setProgress(0); while ((read = input.read(buffer)) > 0) { writeFile.write(buffer, 0, read); bytesDownloaded += read; setProgress((int) ((float)bytesDownloaded/fileLength*100)); } writeFile.flush(); } catch (IOException e) { System.out.println("Error while trying to download the file."); e.printStackTrace(); } finally { try { writeFile.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } } }
19a68011-1e51-4ae9-94be-20f3dcf52fd8
6
private Node merge(Node startLeft, int leftLength, Node startRight, int rightLength) { int leftCounter = 0; Node leftCursor = startLeft; int rightCounter = 0; Node rightCursor = startRight; Node startCursor = null; Node mergeCursor = null; int totalLength = leftLength + rightLength; for (int i = 0; i < totalLength; i++) { if (leftCounter < leftLength && (rightCounter >= rightLength || leftCursor.data.compareTo(rightCursor.data) <= 0)) { if (startCursor == null){ mergeCursor = leftCursor; startCursor = mergeCursor; } else { mergeCursor.next = leftCursor; mergeCursor = leftCursor; } leftCursor = leftCursor.next; leftCounter++; } else { if (startCursor == null) { mergeCursor = rightCursor; startCursor = mergeCursor; } else { mergeCursor.next = rightCursor; mergeCursor = rightCursor; } rightCursor = rightCursor.next; rightCounter++; } } mergeCursor.next = null; // unlink the last node to avoid cycles return startCursor; }
c25a356a-a88f-4c27-88f3-352ed1a716d0
5
public double pow2(double x, int n){ // deal with negativity separately if(n == Integer.MIN_VALUE) return 1.0/(pow2(x, n+1) * pow2(x, -1)); if(n < 0) return 1.0 / pow2(x, -n); // can not handle the case where n = MIN_VALUE if(n == 1) return x; if(n == 0) return 1.0; double y = pow2(x, n / 2); if(n % 2 == 0) { return y*y; }else{ return y * y * x; } }
e0ae2f33-cf46-4ff1-9fdb-aab1374ba9bb
1
public void updateUniforms(Matrix4f worldMatrix, Matrix4f projectedMatrix, Material material) { if(material.getTexture() != null) material.getTexture().bind(); else RenderUtil.unbindTextures(); setUniform("transform", projectedMatrix); setUniform("color", material.getColor()); }
13c3a5d6-cf08-4f29-8fce-58992c79c94f
2
public void enable() throws IOException { // This has to be synchronized or it can collide with the check in the task. synchronized (optOutLock) { // Check if the server owner has already set opt-out, if not, set it. if (isOptOut()) { configuration.set("opt-out", false); configuration.save(configurationFile); } // Enable Task, if it is not running if (task == null) { start(); } } }
15e4cb79-9432-4cc0-82da-18262bb905b7
2
private void Equipa2_RadioButtonItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_Equipa2_RadioButtonItemStateChanged if(Equipa2_RadioButton.isSelected()) Jogador_ComboBox.setEnabled(true); if(Equipa2_RadioButton.isSelected()== false) Jogador_ComboBox.setEnabled(false); }//GEN-LAST:event_Equipa2_RadioButtonItemStateChanged
af032b44-4eb9-4f19-ba52-aaf58c901dc8
7
@SuppressWarnings("unchecked") private<PType extends IPerformances> List<GenericTestResults<Double, CTDiscreteNode, ICTClassifier<Double,CTDiscreteNode>, PType>> executeTests( List<ITestFactory<Double, CTDiscreteNode, ICTClassifier<Double,CTDiscreteNode>, PType>> testFactories, List<ITrajectory<Double>> dataset, ICTClassifier<Double,CTDiscreteNode> baseNBModel) { this.verbosePrint("Execute tests:\n"); // Inizialization Set<String> classStates = new TreeSet<String>(); for( int i = 0; i < baseNBModel.getClassNode().getStatesNumber(); ++i) classStates.add( baseNBModel.getClassNode().getStateName(i)); List<GenericTestResults<Double, CTDiscreteNode, ICTClassifier<Double,CTDiscreteNode>, PType>> resultsList = new Vector<GenericTestResults<Double, CTDiscreteNode, ICTClassifier<Double,CTDiscreteNode>, PType>>(this.modelToTest.size()); // Tests for( int i = 0; i < this.modelToTest.size(); ++i) { String[] modelData = this.modelToTest.get(i); String modelName = "M" + i + "_" + modelData[0] + (modelData.length > 5 ? modelData[5] + "-" + modelData[6] : ""); this.verbosePrint("\t. model " + modelName + "\n"); // Test execution this.verbosePrint("\t. test running\n"); ITestResults<Double,CTDiscreteNode,ICTClassifier<Double,CTDiscreteNode>,PType> result = testFactories.get(i).newTest(modelName, baseNBModel, dataset); resultsList.add( (GenericTestResults<Double, CTDiscreteNode, ICTClassifier<Double,CTDiscreteNode>, PType>) result); // Result printing this.verbosePrint("\t. result printing\n"); try { if( this.cvValidation != null) printTestResults(this.resultsPath, (GenericTestResults<Double, CTDiscreteNode, ICTClassifier<Double,CTDiscreteNode>, MicroMacroClassificationPerformances<Double, ClassificationStandardPerformances<Double>>>) result, classStates, baseNBModel.getClassNode().getName(), this.confidenceLevel, dataset.size(), this.testName, this.cvValidation.getKFolds()); else if( this.hoValidation != null) printTestResults(this.resultsPath, (GenericTestResults<Double, CTDiscreteNode, ICTClassifier<Double,CTDiscreteNode>, ClassificationStandardPerformances<Double>>) result, classStates, baseNBModel.getClassNode().getName(), this.confidenceLevel, dataset.size(), this.testName); else if( this.clusteringValidation != null) printTestResults(this.resultsPath, (GenericTestResults<Double, CTDiscreteNode, ICTClassifier<Double,CTDiscreteNode>, ClusteringExternalPerformances<Double>>) result, classStates, baseNBModel.getClassNode().getName(), dataset.size(), this.testName, this.testType.equals("hard")); }catch(Exception e) { System.err.println("Error during the result printing for model " + modelName + ": " + e); e.printStackTrace(); System.exit(1); } } this.verbosePrint("Execute tests (END)\n"); return resultsList; }
d2490ba4-2fe2-4c2a-957e-a7be10dbda99
2
public void PlayAgain(){ System.out.print("Do you wish to play again? Y or N: "); Scanner input = new Scanner(System.in); String answer = ""; answer ="n";//input.nextLine(); if (answer.equalsIgnoreCase("y")) { input.close(); new Game(); } else if (answer.equalsIgnoreCase("n")) { input.close(); endGame(); } else PlayAgain(); }
82ff5c30-0922-4b3e-a290-3cb29dd9b793
9
public void configureOtherEtcProperties(){ if (getDebug()) System.out.println(getProperties().size()+" property updates found"); for (Map.Entry<String, String> e:getProperties().entrySet()){ File file=new File(getFuseHome(), "etc/"+e.getKey().split("_")[0]+".cfg"); if (!file.exists()) throw new RuntimeException("Unable to find file ["+file.getPath()+"] to apply property update"); String property=e.getKey().split("_")[1]; boolean append=false; if (e.getKey().split("_").length>2) append=e.getKey().split("_")[2].equalsIgnoreCase("append"); // append=Boolean.parseBoolean(e.getKey().split("_")[2]); String newValue=e.getValue(); if (getDebug()) System.out.println("Property update: file=["+file+"], property=["+property+"], value=["+newValue+"], append=["+append+"]"); // make the property change try { if (!file.getCanonicalFile().exists()) throw new RuntimeException("configuration file "+file.getCanonicalPath()+" cannot be found"); org.apache.felix.utils.properties.Properties p=new org.apache.felix.utils.properties.Properties(file); p.save(new File(file.getParentFile(), file.getName()+".bak")); String value=append?p.get(property)+newValue:newValue; if (getDebug()) System.out.println("changing value from ["+p.get(property) +"] to ["+value+"]"); p.setProperty(property, value); p.save(file); } catch (IOException ex) { ex.printStackTrace(); } } }
0c956c53-ac0d-4b73-9cef-813ccc5b3323
7
public String[] mapTypes(String[] types) { String[] newTypes = null; boolean needMapping = false; for (int i = 0; i < types.length; i++) { String type = types[i]; String newType = map(type); if (newType != null && newTypes == null) { newTypes = new String[types.length]; if (i > 0) { System.arraycopy(types, 0, newTypes, 0, i); } needMapping = true; } if (needMapping) { newTypes[i] = newType == null ? type : newType; } } return needMapping ? newTypes : types; }
5be1fec4-6b96-4a3b-9654-2f5c4246a87e
8
public void putAll( Map<? extends Float, ? extends Integer> map ) { Iterator<? extends Entry<? extends Float,? extends Integer>> it = map.entrySet().iterator(); for ( int i = map.size(); i-- > 0; ) { Entry<? extends Float,? extends Integer> e = it.next(); this.put( e.getKey(), e.getValue() ); } }
8894e576-b96d-4b0b-96a3-385de2ed96a6
1
@Override public void restartMachine(IMachine machine) throws InvalidObjectException, ConnectorException { try { CloudStackClient client = ClientLocator.getInstance().getClient(machine.getComputeCenter().getProperties(), controllerServices); client.rebootVirtualMachine(machine.getName()); } catch (Exception e) { throw new ConnectorException("Error Rebooting " + machine.getComputeCenter().getType().getName() + " Instance Id:" + machine.getName() + ". Error:" + e.getMessage(), e); } }
f3d834bb-2306-4103-b065-46a57cbfda35
9
public Interactable.Result keyboardInteraction(Key key) { try { switch(key.getKind()) { case ArrowDown: return Result.NEXT_INTERACTABLE_DOWN; case Tab: case ArrowRight: return Result.NEXT_INTERACTABLE_RIGHT; case ArrowUp: return Result.PREVIOUS_INTERACTABLE_UP; case ReverseTab: case ArrowLeft: return Result.PREVIOUS_INTERACTABLE_LEFT; case Enter: onActivated(); break; default: if(key.getCharacter() == ' ' || key.getCharacter() == 'x') onActivated(); break; } return Result.DO_NOTHING; } finally { invalidate(); } }
87ed6018-0682-4886-8726-b10ed9b0086a
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Hill other = (Hill) obj; if (field == null) { if (other.field != null) return false; } else if (!field.equals(other.field)) return false; return true; }
96fd7db9-5e2f-4e5d-883e-bb88c9bb5ac8
4
private static void populateEntities(World world, String uin, int loops){ TileMap tm = world.tileMap; for(int i = 0; i < loops; i++){ EntityLiving el = (EntityLiving) Entity.createEntityFromUIN(uin, tm, world); int x = new Random().nextInt(tm.getXRows()); int y = new Random().nextInt(tm.getYRows()); if(y+1 < tm.getYRows()) if(world.tileMap.getBlockID(x, y) == 0){ if(world.tileMap.getBlockID(x, y+1) > 0){ el.setPosition(x*32 + 16, y*32 + 16); world.listWithMapObjects.add(el); System.out.println("added pig at " + x + " " + (y)); } } } }
6571a33d-60a6-43ad-b711-51c417902b22
5
protected void restoreButtonBorder(AbstractButton b) { Object cp = b.getClientProperty("paintToolBarBorder"); if ((cp != null) && (cp instanceof Boolean)) { Boolean changeBorder = (Boolean)cp; if (!changeBorder.booleanValue()) { return; } } Border border = (Border) orgBorders.get(b); if (border != null) { if (border instanceof NullBorder) { b.setBorder(null); } else { b.setBorder(border); } } b.setMargin((Insets) orgMargins.get(b)); }
19066e8b-453e-4761-a2f3-a895daff48ea
1
public void setNametextFontsize(int fontsize) { if (fontsize <= 0) { this.nametextFontSize = UIFontInits.NAME.getSize(); } else { this.nametextFontSize = fontsize; } somethingChanged(); }
674bc0b4-bd3e-4619-8864-812c87b4ef47
8
void parseOtherServersList(String list) { // Splitlist String[] temp = list.split(";"); String IP = null; String BindingName = null; int Port = 0; for (int i = 0; i < temp.length; i++) { switch (i % 3) { case 0: IP = temp[i]; // System.out.println("IP: "+IP); break; case 1: BindingName = temp[i]; // System.out.println("Name: "+BindingName); break; case 2: Port = Integer.valueOf(temp[i].trim()); // Creating the server ServerGroup s = new ServerGroup(IP, BindingName, Port); if(!serversRegister.contains(s)) serversRegister.add(s); if (firstExecution) { if (s.bind()) { try { System.out.println("Joining Server Group: "+s); s.rmi.JoinServer(_ip.getHostAddress(), serverRMIPort); s.joined = true; } catch (RemoteException e) { e.printStackTrace(); } } } break; } } mutex.release(); firstExecution = false; }
fdd57b67-8d7a-4e7d-84e5-eec083239646
1
public static void init3dCanvas(int x, int y) { Rasterizer.lineOffsets = new int[y]; for (int i = 0; i < y; i++) { Rasterizer.lineOffsets[i] = x * i; } Rasterizer.centerX = x / 2; Rasterizer.centerY = y / 2; }
dc04a0e8-a613-43a8-bb04-1d18e4e8868e
1
public Declaration(String jsonFile) throws FileNotFoundException, IOException, Exception { String JSONInfo = FileReader.loadFileIntoString(jsonFile, "UTF-8"); json = JSONObject.fromObject(JSONInfo); nomCycle = json.get("cycle").toString(); NumeroPermis = json.get("numero_de_permis").toString(); heuresTransfereesCyclePrecedent = Integer.parseInt(json.get("heures_transferees_du_cycle_precedent").toString()); activitesReconnues = new ArrayList<>(); activitesIgnorees = new ArrayList<>(); activites = new ArrayList<>(); try { cycle = Cycle.getCycleCorrespondant(nomCycle); } catch (Exception ex) { erreurs.add(ex.getMessage()); } }
3e8dbc2a-71bd-42b1-9c0b-b1d9c0efc982
4
public int removeDuplicates(int[] A) { int MAX_REPEAT = 2; if( A.length <= MAX_REPEAT ) return A.length; int p = 0; int r = 1; for( int i = 1; i < A.length; i++ ) { if( A[i] != A[p] ) { A[++p] = A[i]; r = 1; } else { if( r < MAX_REPEAT ) { A[++p] = A[i]; r++; } } } return p + 1; }
d87cd807-f01e-4549-b151-ddd07a0a83f3
3
public void run() { String producedData = ""; try { while (true) { if (producedData.length()>75) break; producedData = new String("Hi! "+producedData); sleep(1000); // It takes a second to obtain data. theBuffer.putLine(producedData); } } catch (Exception e) { // Just let thread terminate (i.e., return from run). } } // run
090ff37a-fd88-49cf-81e5-4f75a348bab4
7
private Object popupCombo(Object combobox) { // combobox bounds relative to the root desktop int combox = 0, comboy = 0, combowidth = 0, comboheight = 0; for (Object comp = combobox; comp != content; comp = getParent(comp)) { Rectangle r = getRectangle(comp, "bounds"); combox += r.x; comboy += r.y; Rectangle view = getRectangle(comp, ":view"); if (view != null) { combox -= view.x; comboy -= view.y; Rectangle port = getRectangle(comp, ":port"); combox += port.x; comboy+= port.y; } if (comp == combobox) { combowidth = r.width; comboheight = r.height; } } // :combolist -> combobox and combobox -> :combolist Object combolist = createImpl(":combolist"); set(combolist, "combobox", combobox); set(combobox, ":combolist", combolist); // add :combolist to the root desktop and set the combobox as popupowner popupowner = combobox; insertItem(content, ":comp", combolist, 0); set(combolist, ":parent", content); // lay out choices verticaly and calculate max width and height sum int pw = 0; int ph = 0; for (Object item = get(combobox, ":comp"); item != null; item = get(item, ":next")) { Dimension d = getSize(item, 8 , 4); setRectangle(item, "bounds", 0, ph, d.width, d.height); pw = Math.max(pw, d.width); ph += d.height; } // set :combolist bounds int listy = 0, listheight = 0; int bellow = getRectangle(content, "bounds").height - comboy - comboheight - 1; if ((ph + 2 > bellow) && (comboy - 1 > bellow)) { // popup above combobox listy = Math.max(0, comboy - 1 - ph - 2); listheight = Math.min(comboy - 1, ph + 2); } else { // popup bellow combobox listy = comboy + comboheight + 1; listheight = Math.min(bellow, ph + 2); } setRectangle(combolist, "bounds", combox, listy, combowidth, listheight); layoutScroll(combolist, pw, ph, 0, 0, 0, 0, true, 0); repaint(combolist); // hover the selected item int selected = getInteger(combobox, "selected", -1); setInside(combolist, (selected != -1) ? getItem(combobox, selected) : null, true); return combolist; }
5e12ed9a-824f-4fcf-ac20-7c8f949ee3a4
7
public static void main(String[] args) { // TODO Auto-generated method stub Class clsObj=null; try{ clsObj = Class.forName("UsingAnnotation"); } catch(ClassNotFoundException cnfe){ cnfe.printStackTrace(); } try { Method mthd = clsObj.getMethod("fun", null); if(mthd.isAnnotationPresent(MyAnnotation.class)) { MyAnnotation myAnnObj = mthd.getAnnotation(MyAnnotation.class); int level = myAnnObj.level(); mthd.invoke(null, null); } } catch (IllegalAccessException e1) { // TODO: handle exception e1.printStackTrace(); } catch (IllegalArgumentException e2) { // TODO: handle exception e2.printStackTrace(); } catch (InvocationTargetException e3) { // TODO: handle exception e3.printStackTrace(); } catch (SecurityException e4) { // TODO: handle exception e4.printStackTrace(); } catch (NoSuchMethodException e5) { // TODO: handle exception e5.printStackTrace(); } }
aa3875e0-d1f8-49c5-b091-a16f0a67f2ac
8
@Override public void analyzeCoverage() { // in this analysis, skip and count the read pair where either read // or mate are flagged as unmapped if (this.getSamRecord().getReadUnmappedFlag() || this.getSamRecord().getMateUnmappedFlag()) { readMateUnmappedCount++; return; } // in this analysis, skip and count the reads located on different // chromosomes // ReferenceIndex seems to be the Index which is 0-based Chromosome // Number if (this.getSamRecord().getReferenceIndex() != this.getSamRecord() .getMateReferenceIndex()) { readMateSplittedChromosome++; return; } // in this analysis, skip and count the pairs where read and mate // have same orientation if (this.getSamRecord().getReadNegativeStrandFlag() && this.getSamRecord().getMateNegativeStrandFlag()) { bothSameOrientated++; return; } if (!this.getSamRecord().getReadNegativeStrandFlag() && !this.getSamRecord().getMateNegativeStrandFlag()) { bothSameOrientated++; return; } // in this analysis, skip and count the read pairs with InsertSize > // 1000 bp if (Math.abs(this.getSamRecord().getInferredInsertSize()) > 10000) { highDistance++; return; } super.analyzeCoverage(); } // end analyzeCoverage()
5d77fc66-2ab4-4d4a-807d-f9d51ff7e917
9
final public SimpleNode Start() throws ParseException { /*@bgen(jjtree) Start */ SimpleNode jjtn000 = new SimpleNode(JJTSTART); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { booleanSentence(); jj_consume_token(0); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetLastToken(getToken(0)); {if (true) return jjtn000;} } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } throw new Error("Missing return statement in function"); }
d7bb4a1f-4787-4c92-b04c-3be3f761dc39
0
public int getMouseX() { return mouseLocation.x; }
939a881b-c870-4bd3-bf12-64dd6a28a4ed
8
static void write(Command cmd, OutputStream out) throws UnsupportedEncodingException, IOException { encode(cmd.getCommand(), out); for (Parameter param : cmd.getParameters()) { encode(String.format("=%s=%s", param.getName(), param.hasValue() ? param.getValue() : ""), out); } String tag = cmd.getTag(); if ((tag != null) && !tag.equals("")) { encode(String.format(".tag=%s", tag), out); } List<String> props = cmd.getProperties(); if (!props.isEmpty()) { StringBuilder buf = new StringBuilder("=.proplist="); for (int i = 0; i < props.size(); ++i) { if (i > 0) { buf.append(","); } buf.append(props.get(i)); } encode(buf.toString(), out); } for (String query : cmd.getQueries()) { encode(query, out); } out.write(0); }
4817f473-3c5a-4eec-a38d-6e41fd50e14d
5
public void begin() { final ObjectInputStream in; final ObjectOutputStream out; try { in = new ObjectInputStream(socket.getInputStream()); out = new ObjectOutputStream(socket.getOutputStream()); Thread input = new Thread() { @Override public void run() { while(true) { readMessage(in); if(kill) return; } } }; input.setDaemon(true); input.start(); Thread output = new Thread() { @Override public void run() { while(true) { writeMessages(out); if(kill) return; } } }; output.setDaemon(true); output.start(); } catch (IOException e) { kill(); } }
688fbffb-c266-40e5-bf79-7b7978a2d7f0
5
private void checkAttribute() { ExpressionDecomposer ed=new ExpressionDecomposer(); //check select Iterator<Expression> s=select.iterator(); while(s.hasNext()) { ArrayList<String> selectAttrs=ed.getIdentifiers(s.next()); Iterator<String> selectIterator=selectAttrs.iterator(); while(selectIterator.hasNext()) { attributesInTable(selectIterator.next(),"select clause"); } } //check where if(where!=null) { ArrayList<String> whereAttrs=ed.getIdentifiers(where); Iterator<String> whereIterator=whereAttrs.iterator(); while(whereIterator.hasNext()) { attributesInTable(whereIterator.next(),"where clause"); } } //check group if(group!=null) { attributesInTable(group,"aggregation"); } }
02aef370-d73d-4514-8821-265228536325
2
@Override public boolean removeLockByResources(Set<String> resources) { boolean thereturn = false; for (String resource : resources) thereturn = removeLockByResource(resource) || thereturn; return thereturn; }
5fe5075d-e89f-4574-b7f0-2b316c2f8f55
5
public boolean checkForBookIssuedOrNot(IssueBookVO issueBookVO) throws LibraryManagementException { boolean returnValue = true; ConnectionFactory connectionFactory = new ConnectionFactory(); Connection connection; try { connection = connectionFactory.getConnection(); } catch (LibraryManagementException e) { throw e; } PreparedStatement preparedStatement = null; ResultSet resultSet; try { preparedStatement = connection .prepareStatement("select * from ISSUE_BOOK where BOOK_ID = ?" + " and RECEIVE_DATE is null"); preparedStatement.setString(1, issueBookVO.getBookID()); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { returnValue = false; throw new LibraryManagementException( ExceptionCategory.BOOK_ALREADY_ISSUED); } } catch (SQLException e) { throw new LibraryManagementException(ExceptionCategory.SYSTEM); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { throw new LibraryManagementException( ExceptionCategory.SYSTEM); } } connectionFactory.closeConnection(connection); } return returnValue; }
02aa2864-c85b-4199-a59f-7ad39c04cbc0
4
private void checkForRemovedMarkers() { markersToRemove.clear(); for (Node node : pane.getChildren()) { if (node instanceof Marker) { if (getSkinnable().getMarkers().keySet().contains(node)) continue; node.setManaged(false); node.removeEventHandler(MouseEvent.MOUSE_PRESSED, mouseEventHandler); node.removeEventHandler(MouseEvent.MOUSE_DRAGGED, mouseEventHandler); node.removeEventHandler(MouseEvent.MOUSE_RELEASED, mouseEventHandler); node.removeEventHandler(TouchEvent.TOUCH_PRESSED, touchEventHandler); node.removeEventHandler(TouchEvent.TOUCH_MOVED, touchEventHandler); node.removeEventHandler(TouchEvent.TOUCH_RELEASED, touchEventHandler); markersToRemove.add(node); } } for (Node node : markersToRemove) pane.getChildren().remove(node); }
5e122e53-6631-43d7-af2e-23151613255f
8
public static void start() { System.out.println("MAYBE IT WORKS?"); try { try { new ServerClassLoader(). //ServerRestarter.class.getClassLoader(). loadClass("server.Server").getConstructor(int.class).newInstance(port); return; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } new Server(port); } catch (IOException e) { e.printStackTrace(); } }
94de4be7-d8a0-4f10-b90c-cfa8c72c0a45
2
@Override public void Parse(Session Session, EventRequest Request) { if (Session.GrabActor().Frozen) { return; } int X = Request.PopInt(); int Y = Request.PopInt(); Session.GrabActor().GoalPosition = new Position(X, Y, Session.GrabActor().CurrentPosition.Z); if (Session.GrabActor().IsMoving) { Session.GrabActor().NeedsPathChange = true; } }
f411f8b8-7f7d-4c8d-9a45-19e59b9a6beb
9
static void sortWith0(int[] a, int fromIndex, int toIndex, IntComparator cmp) { final int length = toIndex - fromIndex + 1; if (length < 2) return; if (length == 2) { if (cmp.gt(a[fromIndex], a[toIndex])) { int x = a[fromIndex]; a[fromIndex] = a[toIndex]; a[toIndex] = x; } return; } // FIXME bad performance final int pivot = a[fromIndex]; int p1 = 0; int p2 = 0; int[] a1 = new int[length]; int[] a2 = new int[length]; for (int i = fromIndex + 1; i <= toIndex; i++) { final int v = a[i]; if (cmp.lt(v, pivot)) a1[p1++] = v; else a2[p2++] = v; } int p = fromIndex; for (int i = 0; i < p1; i++) a[p++] = a1[i]; a[p++] = pivot; for (int i = 0; i < p2; i++) a[p++] = a2[i]; if (p1 > 0) sortWith0(a, fromIndex, fromIndex + p1 - 1, cmp); if (p2 > 0) sortWith0(a, fromIndex + p1 + 1, toIndex, cmp); }
fb0570da-a2fd-49c7-9e91-96e2518b059f
6
private void validate() throws RrdException { boolean ok = true; if(timestamps.length != values.length || timestamps.length < 2) { ok = false; } for(int i = 0; i < timestamps.length - 1 && ok; i++) { if(timestamps[i] >= timestamps[i + 1]) { ok = false; } } if(!ok) { throw new RrdException("Invalid plottable data supplied"); } }
cfb3416b-d1c8-41c0-9043-74d1a46ef4f9
5
public Archive(File file) throws IOException { // Initialize this.file = file; files = new HashMap<String, ArchiveFile>(); if (!file.exists()) return; // Open the file to read RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "r"); // Read the header int filecnt = changeEndianness(raf.readInt()); List<Integer> offsets = new ArrayList<Integer>(); // Read the offsets for (int i = 0; i < filecnt; i++) { int offset = changeEndianness(raf.readInt()); if (offset == 0) { break; } offsets.add(offset); } // Read the file entries for (int i = 0; i < offsets.size(); i++) { raf.seek(offsets.get(i)); ArchiveFile f = new ArchiveFile(); f.size = changeEndianness(raf.readInt()); int pathsize = changeEndianness(raf.readInt()); byte[] path = new byte[pathsize]; raf.read(path); f.filename = new String(path); f.offset = offsets.get(i) + 8 + pathsize; files.put(f.filename, f); } } finally { if (raf != null) { raf.close(); } } }
616861d5-d72c-41d5-8bb0-ba5b7bd461de
3
@Override public boolean store() throws SQLException{ if(super.store()== false){ return false; } else if(super.getID()==-1) { return false; } SQLiteJDBC db = new SQLiteJDBC(); String sql = String.format( "INSERT INTO customers (user_id,gender,dob,trn,phone)" + "VALUES ('%d','%s','%s','%s','%s');", super.getID(), this.gender, (new SimpleDateFormat("dd-MM-yyyy")).format(this.dob), this.trn, this.phone ); if(db.updateQuery(sql)>0){ db.close(); return true; } else{ db.close(); return false; } }
7d10f17a-9304-4b21-8a84-a2f9554187dc
4
public static PrivateKey getPrivateKey(String pem) throws IOException, GeneralSecurityException { PrivateKey key = null; byte[] bytes = getFragmentOfPEM(pem, RSA_PRIVATE_KEY_PEM_HEADER, RSA_PRIVATE_KEY_PEM_FOOTER); String rsa = new String(bytes); String split[] = rsa.split("-----"); rsa = split[2]; ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence .fromByteArray(Base64.decode(rsa.getBytes())); Enumeration<?> e = primitive.getObjects(); BigInteger v = ((DERInteger) e.nextElement()).getValue(); int version = v.intValue(); if (version != 0 && version != 1) { throw new IllegalArgumentException( "wrong version for RSA private key"); } /** * In fact only modulus and private exponent are in use. */ BigInteger modulus = ((DERInteger) e.nextElement()).getValue(); BigInteger publicExponent = ((DERInteger) e.nextElement()) .getValue(); BigInteger privateExponent = ((DERInteger) e.nextElement()) .getValue(); BigInteger prime1 = ((DERInteger) e.nextElement()).getValue(); BigInteger prime2 = ((DERInteger) e.nextElement()).getValue(); BigInteger exponent1 = ((DERInteger) e.nextElement()).getValue(); BigInteger exponent2 = ((DERInteger) e.nextElement()).getValue(); BigInteger coefficient = ((DERInteger) e.nextElement()).getValue(); RSAPrivateKeySpec rsaPrivKeySpec = new RSAPrivateKeySpec(modulus, privateExponent); try{ KeyFactory kf = KeyFactory.getInstance("RSA"); key = kf.generatePrivate(rsaPrivKeySpec); }catch(GeneralSecurityException e1){ throw e1; } return key; }
89a1af35-f471-45b6-a4c3-2e3792ef3a9c
5
public ObjectDefinition method580() { int i = -1; if (varbitFileId != -1) { VarBit varBit = VarBit.cache[varbitFileId]; int j = varBit.configId; int k = varBit.anInt649; int l = varBit.anInt650; int i1 = Client.anIntArray1232[l - k]; i = ObjectDefinition.client.configStates[j] >> k & i1; } else if (anInt749 != -1) { i = ObjectDefinition.client.configStates[anInt749]; } if (i < 0 || i >= childIds.length || childIds[i] == -1) { return null; } else { return ObjectDefinition.forId(childIds[i]); } }
f705de00-f4ad-4a04-837e-ef5450f71d00
2
@Override public boolean evaluate(T t) { if(firstSearchString.evaluate(t) || secondSearchString.evaluate(t)){ return true; } else{ return false; } }
a5bcf1f1-e17c-4410-a4b6-08d205082794
5
public boolean actionDisinfest(Actor actor, Crop crop) { final Item seed = actor.gear.bestSample( Item.asMatch(SAMPLES, crop.species), 0.1f ) ; int success = seed != null ? 2 : 0 ; if (actor.traits.test(CULTIVATION, MODERATE_DC, 1)) success++ ; if (actor.traits.test(CHEMISTRY , ROUTINE_DC , 1)) success++ ; if (Rand.index(5) <= success) { crop.infested = false ; if (seed != null) actor.gear.removeItem(seed) ; } return true ; }
473f7569-2648-416e-b252-84e4bff8b71b
0
public static void main(String[] args) { /* * try { // Set cross-platform Java L&F (also called "Metal") * //UIManager * .setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); * UIManager. * setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); * } catch (UnsupportedLookAndFeelException e) { // handle exception } * catch (ClassNotFoundException e) { // handle exception } catch * (InstantiationException e) { // handle exception } catch * (IllegalAccessException e) { // handle exception } */ BDApplication modeleApp = new BDApplication(); VueApplication vueApp = new VueApplication("GED - Projet ISTY", modeleApp); /* * ControleurApplication controleurApp = new ControleurApplication( * modeleApp, vueApp); */ ControleurApplication controleurApp = new ControleurApplication( modeleApp, vueApp); }
ce3ec1bf-bbbb-4aea-a484-90db9562ecfe
7
private ListNode insertIntoSortedList(ListNode target, ListNode source){ //initialize if(target == null){ target = new ListNode(source.val); }else{ ListNode p = target; //if source is the smallest one. if (target.val > source.val) { target = new ListNode(source.val); target.next = p; }else{ while(p != null){ ListNode pNext = p.next; //the last node in the list if(pNext == null){ if(p.val < source.val){ p.next = new ListNode(source.val); }else{ ListNode element = new ListNode(p.val); p.val = source.val; p.next = element; } }else if(p.val <= source.val && source.val < pNext.val){ ListNode element = new ListNode(source.val); p.next = element; element.next = pNext; break; } p = pNext; } } } return target; }
354e97bb-7e97-4f03-ab70-3b7165684ef6
7
@Override protected ERGameEvent readEventStream(InputStream inputStream) throws IOException { ObjectInputStream ois = new ObjectInputStream(inputStream); switch(ois.readInt()){ case (ERGameEvent.EVENT_MESSAGE_C): return ERGameEvent.EventMessageClient(ois.readUTF()); case (ERGameEvent.EVENT_MESSAGE): return ERGameEvent.EventMessage( ois.readUTF(), ois.readUTF()); case (ERGameEvent.EVENT_UPDATE_C): return ERGameEvent.EventUpdateClient( ois.readFloat(), ois.readFloat() ); case (ERGameEvent.EVENT_UPDATE): return ERGameEvent.EventUpdate( ois.readInt(), ois.readFloat(), ois.readFloat(), ois.readFloat(), ois.readFloat() ); case (ERGameEvent.EVENT_DESTROY): return ERGameEvent.EventDestroy( ois.readInt() ); case (ERGameEvent.EVENT_INTERACT_C): return ERGameEvent.EventInteractClient( ois.readInt() ); case (ERGameEvent.EVENT_INTERACT): return ERGameEvent.EventInteract( ois.readInt(), ois.readInt() ); default: return null; } }
23b8ce7e-7aad-4a01-aaf0-69fe8e75e4ae
9
public static void main(String[] args) { int startPort = 8000; int endPort = 8001; int TIMESPAN = 10; String serverIp = "localhost"; String output = "y"; for (int i = 0; i < args.length - 1; i++) { if (args[i].equals("-sp")) { startPort = Integer.parseInt(args[i + 1]); } if (args[i].equals("-ep")) { endPort = Integer.parseInt(args[i + 1]); } if (args[i].equals("-t")) { TIMESPAN = Integer.parseInt(args[i + 1]); } if (args[i].equals("-ip")) { serverIp = args[i + 1]; } if (args[i].equals("-o")) { output = args[i + 1]; } } Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, TIMESPAN); int counter = 0; String PingMe[] = new String[endPort - startPort]; // int INTERVALL = 60000; //Multiple Server auf versch. IPs/Ports for (int i = startPort; i < endPort; i++) { PingMe[i - startPort] = "http://" + serverIp + ":" + i + "/xmlrpc"; } // TODO: Multiple Server auf einem Port String Servers[] = new String[] { "MyXmlRpcServer" }; AdminServer adminServer = new AdminServer(PingMe, Servers); //While TIMESPAN count RPC Calls while (Calendar.getInstance().getTimeInMillis() < cal.getTimeInMillis()) { adminServer.startClients(); if (output.equals("y")) adminServer.terminalOutput(); // try { // Thread.sleep(INTERVALL); // } catch (InterruptedException e) { // e.printStackTrace(); // } counter++; } System.out.println("RPC Calls in " + TIMESPAN + " seconds:\t" + counter); }
c66f6d5d-0ce7-4445-97db-85325fba3b4b
0
public boolean getJumpKeyPressed() { return jumpKeyPressed; }
b3293b81-640b-46bc-81f3-57a797e23f5f
0
public void setZ(int z) { this.z = z; }
b288b356-8205-45b9-b829-07e6270e1d45
3
public void stop() { if (!loading()) { // Make sure there is a sequencer: if (sequencer == null) return; try { // stop playback: sequencer.stop(); // rewind to the beginning: sequencer.setMicrosecondPosition(0); // No need to listen any more: sequencer.removeMetaEventListener(this); } catch (Exception e) { errorMessage("Exception in method 'stop'"); printStackTrace(e); SoundSystemException sse = new SoundSystemException( e.getMessage()); SoundSystem.setException(sse); } } }
2da4a376-ca86-4c9c-a2dc-57888fe1a1d8
2
public static String byteToHexString(byte[] data) { // convert the byte to hex format method 2 StringBuffer hexString = new StringBuffer(); for (int i = 0; i < data.length; i++) { String hex = Integer.toHexString(0xff & data[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
7e0dca14-6562-4c46-98c6-02be3b5c4a48
9
private static Path processPath(final List<String> PATH_LIST, final PathReader READER) { final Path PATH = new Path(); PATH.setFillRule(FillRule.EVEN_ODD); while (!PATH_LIST.isEmpty()) { if ("M".equals(READER.read())) { PATH.getElements().add(new MoveTo(READER.nextX(), READER.nextY())); } else if ("L".equals(READER.read())) { PATH.getElements().add(new LineTo(READER.nextX(), READER.nextY())); } else if ("C".equals(READER.read())) { PATH.getElements().add(new CubicCurveTo(READER.nextX(), READER.nextY(), READER.nextX(), READER.nextY(), READER.nextX(), READER.nextY())); } else if ("Q".equals(READER.read())) { PATH.getElements().add(new QuadCurveTo(READER.nextX(), READER.nextY(), READER.nextX(), READER.nextY())); } else if ("H".equals(READER.read())) { PATH.getElements().add(new HLineTo(READER.nextX())); } else if ("L".equals(READER.read())) { PATH.getElements().add(new VLineTo(READER.nextY())); } else if ("A".equals(READER.read())) { PATH.getElements().add(new ArcTo(READER.nextX(), READER.nextY(), 0, READER.nextX(), READER.nextY(), false, false)); } else if ("Z".equals(READER.read())) { PATH.getElements().add(new ClosePath()); } } return PATH; }
b4315476-c31f-43ab-98c8-6d167cce7fd4
7
public static void main(String[] args) { // Load the project properties Properties properties = new Properties(); try { properties.load(new FileInputStream("src/main/resources/threadedMerge.properties")); } catch (IOException e) { System.out.println("Error: could not locate properties file"); } NPROD = Integer.parseInt((String)properties.get("NPROD")); NCONS = Integer.parseInt((String)properties.get("NCONS")); /* * SERIAL APPROACH */ // Read input List<Integer> inputSerial = new ArrayList<Integer>(); try { String currentInput; BufferedReader br = new BufferedReader(new FileReader("test.txt")); while ((currentInput = br.readLine()) != null) { inputSerial.add(Integer.parseInt(currentInput)); } } catch (IOException e) { System.out.println("Error: input file not found"); } // Sort the input Integer[] inputSerialArray = inputSerial.toArray(new Integer[inputSerial.size()]); MergeSort m = new MergeSort(); long startTime = System.nanoTime(); m.sort(inputSerialArray); // Determine how long the search took long endTime = System.nanoTime(); long duration = endTime - startTime; System.out.println("Serial sort executed in " + duration/(1000000000.0) + " seconds"); // Write the output to file try { BufferedWriter outputWriter = new BufferedWriter(new FileWriter("outSerial.txt")); for (int i = 0; i < inputSerialArray.length; i++) { outputWriter.write(Integer.toString(inputSerialArray[i])); outputWriter.newLine(); } outputWriter.flush(); outputWriter.close(); } catch (IOException e) { System.out.println("Error: write error"); } /* * THREADED APPROACH */ MergeHelper helper = new MergeHelper(); // Single producer to read input and write output List <MergeProducer> producers = new ArrayList<MergeProducer>(); for (int i=0; i < NPROD; i++) { producers.add(new MergeProducer(helper, i)); producers.get(i).start(); } List <MergeConsumer> consumers = new ArrayList<MergeConsumer>(); for (int i=0; i < NCONS; i++) { consumers.add(new MergeConsumer(helper, i)); consumers.get(i).start(); } }
c988d162-9079-4488-9ff7-1f40e67b8888
1
public List<Element> getElementsOnGrid() { final List<Element> elements = new ArrayList<Element>(); for (Square square : squares.values()) elements.addAll(square.getElements()); return elements; }
e25f8bae-c6c7-47a1-80ee-a255a7c996ed
9
@Override public void init (AbstractQueue<QueueElement> queue, Properties props) throws MalformedURLException, ParserConfigurationException, TransformerConfigurationException { this.queue = queue; this.props = props; String strInputURL = System.getProperty("ncmInputURL"); if (strInputURL == null) { logger.severe("System property ncmInputURL not set."); System.exit(1); } else { url = new URL(strInputURL); } // Check filter. String strFilter = props.getProperty("filter"); if (strFilter != null) { filterFile = new File(strFilter); if (!filterFile.exists()) { throw new RuntimeException(filterFile.getPath() + ": does not exist."); } else if (!filterFile.isFile()) { throw new RuntimeException(filterFile.getPath() + ": is not a file."); } if (!filterFile.canRead()) { throw new RuntimeException(filterFile.getPath() + ": is not readable."); } } else { logger.config("No filter stylesheet configured."); } // Check stylesheet. String strTransform = props.getProperty("transform"); if (strTransform != null) { transformFile = new File(strTransform); if (!transformFile.exists()) { throw new RuntimeException(transformFile.getPath() + ": does not exist."); } else if (!transformFile.isFile()) { throw new RuntimeException(transformFile.getPath() + ": is not a file."); } if (!transformFile.canRead()) { throw new RuntimeException(transformFile.getPath() + ": is not readable."); } } else { logger.config("No transform stylesheet configured."); } bDebug = props.getProperty("debug", "false").equalsIgnoreCase("true"); // Prepare a document builder. docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(true); docBuilder = docBuilderFactory.newDocumentBuilder(); transformerFactory = TransformerFactory.newInstance(); // Prepare a transfomer. transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.STANDALONE, "no"); transformer.setOutputProperty("{http://xml.apache.org/xsl}indent-amount", "4"); logger.fine("Using class " + docBuilderFactory.getClass().getCanonicalName() + " as DocumentBuilderFactory."); logger.fine("Using class " + transformerFactory.getClass().getCanonicalName() + " as TransformerFactory."); }
c1343184-5bc8-4eb3-8fcd-11bafa726330
4
@Override public boolean execute(AdrundaalGods plugin, CommandSender sender, String... args) { // Grab the argument, if any. String arg1 = (args.length > 0 ? args[0] : ""); if(arg1.isEmpty()) { plugin.reloadConfigs(); plugin.reloadDataFiles(); Messenger.sendMessage(sender, ChatColor.GRAY+"All files reloaded"); return true; } if(arg1.equalsIgnoreCase("config")) { plugin.reloadConfigs(); Messenger.sendMessage(sender, ChatColor.GRAY+"Configs reloaded"); return true; } else if(arg1.equalsIgnoreCase("data")) { plugin.reloadDataFiles(); Messenger.sendMessage(sender, ChatColor.GRAY+"Data files reloaded"); return true; } else return false; }
aef73deb-91dc-4695-8c55-269f7d7755a6
5
public void personDetailsForm() { super.personDetailsForm(); // If fields not empty if (name != null && address != null && email != null && contactNumber != null) { // Edit mode selected if (editMode) { driver.getPersonDB().changePersonDetails(person, name, email, contactNumber, address, 0, null, null, null); setTextField(getIndex(driver.getPersonDB().getCustomerList()), driver.getPersonDB() .getCustomerList()); valid = true; } // Adding a new customer else { valid = true; driver.getPersonDB().createNewPerson(person, name, email, contactNumber, address, 0, null, null, null); setTextField(driver.getPersonDB().getCustomerList().size() - 1, driver .getPersonDB().getCustomerList()); } // Set enabled status of buttons deletePersonButton.setEnabled(true); newPersonButton.setEnabled(true); editPersonButton.setEnabled(true); // Set visibility of buttons editPersonButton.setVisible(true); submitButton.setVisible(false); cancelButton.setVisible(false); cancelEditButton.setVisible(false); newPersonButton.setVisible(true); } else { JOptionPane.showMessageDialog(null, "" + errorMessage); } // Reset the view revalidate(); repaint(); }
332b1194-1028-420c-b07b-0efccc8acec3
0
public Air() { super(Color.white, false); }
a9f9d66d-a9af-4557-8a9e-6628f5492fb0
5
public void testCompare2Spreadsheets( WorkBookHandle bk1, WorkBookHandle bk2 ) throws Exception { WorkSheetHandle[] s1 = bk1.getWorkSheets(); WorkSheetHandle[] s2 = bk2.getWorkSheets(); if( s1.length != s2.length ) { log.info( "These Workbooks do not have the same sheet count. Original: " + s1.length + " vs. Compard:" + s2.length ); } List matchedSheets = new Vector(); // iterate the original and match sheets for( int x = 0; x < s1.length; x++ ) { try { if( s1[x].getSheetName().equals( s2[x].getSheetName() ) ) { matchedSheets.add( s1[x] ); } } catch( Exception xe ) { ; } } Iterator it = matchedSheets.iterator(); while( it.hasNext() ) { WorkSheetHandle s1x = (WorkSheetHandle) it.next(); WorkSheetHandle s2x = bk2.getWorkSheet( s1x.getSheetName() ); // get all the cells, and compare them CellHandle[] c1x = s1x.getCells(); CellHandle[] c2x = s2x.getCells(); System.out.println( getCellText( c1x ) ); System.out.println( getCellText( c2x ) ); } }
e4e038a5-b41f-452e-942d-12d4b5a25bc1
7
private void readGrid() throws FileNotFoundException, IllegalArgumentException, ArrayIndexOutOfBoundsException{ boardReader = new Scanner(startBoard); String row = ""; int rowCount = 0; while (boardReader.hasNext()) { row = boardReader.next(); rowCount++; } boardReader = new Scanner(startBoard); gridOut = new Cell[rowCount][row.length()]; for (int i = 0; i < rowCount; i++) { row = boardReader.next(); for (int j=0; j < row.length(); j++) { if (row.charAt(j)=='X') { gridOut[i][j] = new Cell(true); } else if (row.charAt(j)=='O') { gridOut[i][j] = new Cell(false); } else { throw new IllegalArgumentException(); } } } for (Cell[] checkRow : gridOut) { if ((checkRow.length)!=gridOut[0].length) throw new ArrayIndexOutOfBoundsException(); } }