method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
f5ebc531-c088-43a2-bd45-223ca2e01e4d
0
public void writeLine(String text) { write(text + "\n"); }
bb31bffa-6f84-452d-a7fe-626063926570
3
private void parseReference(Element parentNode, String sectionName, int level) throws TemplateException { try { // look for section XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("/grammar/define[@name='" + sectionName + "']", xml, XPathConstants.NODESET); for (int i = 0, len = nodeList.getLength(); i < len; i++) { Node currentNode = nodeList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { parseReportSectionLevel(parentNode, currentNode, CHILD_NORMAL, level + 1); } } } catch (XPathExpressionException e) { throw new TemplateException("XPathExpressionException", e); } }
4c2faf46-a3d6-45c9-b63e-7b668d0e6ba5
1
public void resetIfVersionMisMatch(String module, int version) { if (getVersion(module) != version) { startBatch(); removePreferences(module); setVersion(module, version); endBatch(); } }
5596ba72-e31d-4f86-a0e1-c244e927c80a
9
public boolean isValidTilePlacement(int row, int column, int rotation) { int row2 = board.getAdjacentRow(rotation, row); int column2 = board.getAdjacentColumn(rotation, column); if (!board.isValidHex(row, column) || board.getHex(row, column).getColor() != Board.VACANT || !board.isValidHex(row2, column2) || board.getHex(row2, column2).getColor() != Board.VACANT) { return false; } if (successfulMoves < 2) { // initial placement: verify that this move is adjacent to a corner // hex with no neighbors // does row, column have any corner hex in its neighbors Hex adjacentCornerHex1 = board.getHex(row, column) .adjacentCornerHex(); Hex adjacentCornerHex2 = board.getHex(row2, column2) .adjacentCornerHex(); if ((adjacentCornerHex1 == null || adjacentCornerHex1 .hasAnyNeighbors()) && (adjacentCornerHex2 == null || adjacentCornerHex2 .hasAnyNeighbors())) { return false; } } return true; }
68d8d4e5-9396-4240-ae47-2784d4fa2adb
5
@Action public void run() { int n = Integer.parseInt(jFormattedTextField1.getText()); if (n > 15 || n < 0) { jTable1.setModel(new javax.swing.table.DefaultTableModel()); if (errorReport == null) { JFrame mainFrame = DemoApp.getApplication().getMainFrame(); errorReport = new ErrorReport(mainFrame, false, 3); errorReport.setLocationRelativeTo(mainFrame); } DemoApp.getApplication().show(errorReport); return; } int[][] intM = SJ03.nDivM(n); Integer[][] intR = new Integer[n][n + 2]; int[] intT = SJ03.compute(n); String[] strC = new String[n + 2]; strC[0] = "元数"; strC[1] = "总数"; for (int i = 0; i < n; i++) { strC[i + 2] = (i + 1) + "块"; intR[i][0] = i + 1; intR[i][1] = intT[i + 1]; for (int j = 1; j <= n; j++) { intR[i][j + 1] = intM[i + 1][j]; } } jTable1.setModel(new javax.swing.table.DefaultTableModel( intR, strC)); }
d3b67fc8-d25e-4c78-8826-e8098f3a51b6
4
private static boolean _isTrimable(char c, char[] exceptions) { if ((exceptions != null) && (exceptions.length > 0)) { for (int i = 0; i < exceptions.length; i++) { if (c == exceptions[i]) { return false; } } } return Character.isWhitespace(c); }
e846e897-8169-4e69-9a22-be74c91c46d2
4
public static void main(String[] argsv) { // Setting op a bank. Bank christmasBank = new Bank(); christmasBank.addAccount(new BankAccount(BigInteger.valueOf(100))); christmasBank.addAccount(new BankAccount(BigInteger.valueOf(50), BigInteger.valueOf(-1000))); BankAccount theAccount = new BankAccount(BigInteger.valueOf(-70), BigInteger.valueOf(-1500)); christmasBank.addAccount(theAccount); // Collect and print all accounts with a balance not below 80: Static method Set<BankAccount> accountsPositiveBalance = christmasBank.getAccountsSatisfying (Bank::hasPositiveBalance); System.out.println("Static method"); for (BankAccount account: accountsPositiveBalance) System.out.println(account.getBalance()); System.out.println(); // Collect and print all accounts with a balance not below 80: Instance method via class accountsPositiveBalance = christmasBank.getAccountsSatisfying (BankAccount::hasPositiveBalance); System.out.println("Instance method via class"); for (BankAccount account: accountsPositiveBalance) System.out.println(account.getBalance()); System.out.println(); // Collect and print all accounts with a balance not below 80: Instance method via instance accountsPositiveBalance = christmasBank.getAccountsSatisfying (theAccount::hasHigherBalanceThan); System.out.println("Instance method via instance"); for (BankAccount account: accountsPositiveBalance) System.out.println(account.getBalance()); System.out.println(); // Generate and print duplicate accounts with a balance 10 higher than the original account. Set<BankAccount> newAccounts = christmasBank.getReplacingAccounts (BankAccount::new); System.out.println("Constructor"); for (BankAccount account: newAccounts) System.out.println(account.getBalance()); System.out.println(); }
3735cadf-8815-4c31-a742-3ea146fc5ebb
6
protected SgfInstance constructGame() { SgfInstance game = new SgfInstance(); Move lastMove = game.getRoot(); Stack<Move> parents = new Stack<Move>(); while (index < contents.length()) { char c = getChar(); if (c == '(') { if (parents.size() == 0) { if (nextChar() == ';') { parents.push(lastMove.addProperties(getProperties())); parents.push(lastMove); } else { // should throw parse error } } else { parents.push(lastMove); } } else if (c == ')' ) { lastMove = parents.pop(); } else if (c == ';') { lastMove = lastMove.createChild(getProperties()); //swap moves } else { //throw UnknownTokenException } index++; } return game; }
88fa2617-4c2b-4c0b-9d3e-14bb4e20767c
7
public ConnexionReclassifierRaster(){ arrayy.clear(); geomms.clear(); Connection con = null; try{ Class.forName("org.postgresql.Driver"); con = DriverManager.getConnection("jdbc:postgresql://"+ConnexionBaseDonnees.getHote()+":"+ConnexionBaseDonnees.getPort()+"/"+ConnexionBaseDonnees.getNomBase(),ConnexionBaseDonnees.getUser(),ConnexionBaseDonnees.getPswd()); if (con!=null){ try{ Statement stmt = con.createStatement(); String query = "SELECT r_table_name as tables, r_raster_column as geom FROM raster_columns"; ResultSet rs = stmt.executeQuery(query); if(arrayy.size()==0&&geomms.size()==0){ while (rs.next()) { String tablename = rs.getString("tables"); String geom = rs.getString("geom"); arrayy.add(tablename); geomms.add(geom); } for (String ef:arrayy){ System.out.println("ConnexRaster: "+ef); } } } catch (SQLException s){ System.out.println("SQL Raster statement is not executed!"); } } } catch (Exception b){ b.printStackTrace(); JOptionPane.showMessageDialog(this,"Erreur : "+b,"Titre : exception",JOptionPane.ERROR_MESSAGE); } this.dispose(); this.setVisible(false); FenetreReclassification fenereclass = new FenetreReclassification(); fenereclass.setVisible(true); }
a03360b1-1fb3-44c4-89b3-efca98cc60b4
2
public String toString() { int a = bits; String s = ""; for(int i = 0 ; i < 32 ; i ++){ if((a & 0x1) == 0x1){ s = "1" + s; } else{ s = "0" + s; } a = a >> 1; } return s; }
656c8146-b65c-49d7-87a0-30451124e575
8
@Override protected void paintComponent(Graphics graphics) { super.paintComponent(graphics); //luodaan taustalle mustat neliöt niin että palikan sivut erottuvat graphics.setColor(Color.BLACK); int ykoordinaattiNeliot=0; graphics.fillRect(65, 1, 64, 257); graphics.fillRect(1, 65, 192, 64); // yla int ykoordinaatti = 2; for(int rivi = 0; rivi<3; rivi++){ int xkoordinaatti=66; for(int sarake = 0; sarake<3; sarake++){ graphics.setColor(this.kuutio.mikaVariOnPaikalla(0, rivi, sarake)); graphics.fillRect(xkoordinaatti, ykoordinaatti, 20, 20); xkoordinaatti=xkoordinaatti+21; } ykoordinaatti=ykoordinaatti+21; } ykoordinaatti=ykoordinaatti+1; //vasen, etu, oikea for(int rivi = 0; rivi<3; rivi++){ int xkoordinaatti=2; for(int sivu=1; sivu<4;sivu++){ for(int sarake = 0; sarake<3; sarake++){ graphics.setColor(this.kuutio.mikaVariOnPaikalla(sivu, rivi, sarake)); graphics.fillRect(xkoordinaatti, ykoordinaatti, 20, 20); xkoordinaatti=xkoordinaatti+21; } xkoordinaatti=xkoordinaatti+1; } ykoordinaatti=ykoordinaatti+21; } ykoordinaatti=ykoordinaatti+1; //ala,taka for(int sivu=4; sivu<6; sivu++){ for(int rivi = 0; rivi<3; rivi++){ int xkoordinaatti=66; for(int sarake = 0; sarake<3; sarake++){ graphics.setColor(this.kuutio.mikaVariOnPaikalla(sivu, rivi, sarake)); graphics.fillRect(xkoordinaatti, ykoordinaatti, 20, 20); xkoordinaatti=xkoordinaatti+21; } ykoordinaatti=ykoordinaatti+21; } ykoordinaatti=ykoordinaatti+2; } graphics.setColor(Color.BLACK); graphics.drawString("0", 150, 145); graphics.drawString("1 2 3", 140, 160); graphics.drawString("4", 150, 175); graphics.drawString("5", 150, 190); }
fbbff1c2-36ab-4272-a790-44a2adbce72f
1
private void getIconArt() { try { boxSelectIcon = ImageIO.read(getClass().getResource("icons/I_BoxSelectTool.png")); brushIcon = ImageIO.read(getClass().getResource("icons/I_BrushTool.png")); eraserIcon = ImageIO.read(getClass().getResource("icons/I_EraserTool.png")); lineIcon = ImageIO.read(getClass().getResource("icons/I_LineTool.png")); rectIcon = ImageIO.read(getClass().getResource("icons/I_RectTool.png")); ellipseIcon = ImageIO.read(getClass().getResource("icons/I_EllipseTool.png")); bucketIcon = ImageIO.read(getClass().getResource("icons/I_BucketTool.png")); } catch (IOException ex) { System.out.println("Images not found"); } }
c375a929-fa13-40bd-9c31-2d0a5fa176ee
0
public void setAge(int age) { this.age = age; }
45e3ada6-cf40-47bc-ae7a-c68a398be19f
9
public void setElectionColumns2() { if( chckbxSubstituteColumns.isSelected()) { chckbxSubstituteColumns.doClick(); } for( VTD b : featureCollection.vtds) { b.resetOutcomes(); b.has_election_results = true; } for( VTD f : featureCollection.features) { f.resetOutcomes(); double[] dd = new double[Settings.num_candidates]; for( int i = 0; i < project.election_columns_2.size(); i++) { try { dd[i] = Double.parseDouble(f.properties.get(project.election_columns_2.get(i)).toString().replaceAll(",","")); } catch (Exception ex) { dd[i] = 0; f.properties.put(project.election_columns_2.get(i),"0"); } } while( f.elections.size() < 2) { f.elections.add(new Vector<Election>()); } f.elections.get(1).clear(); for( int j = 0; j < Settings.num_candidates; j++) { Election d = new Election(); //d.ward_id = b.id; d.turnout_probability = 1; d.population = (int) dd[j]; d.vote_prob = new double[Settings.num_candidates]; for( int i = 0; i < d.vote_prob.length; i++) { d.vote_prob[i] = 0; } d.vote_prob[j] = 1; while( f.elections.size() < 2) { f.elections.add(new Vector<Election>()); } f.elections.get(1).add(d); //System.out.println("ward "+b.id+" added demo "+j+" "+d.population); } } featureCollection.ecology.reset(); election_loaded = true; setEnableds(); }
328e4e2b-1d43-465b-9f69-189e07fec104
1
public ResultSet runQuery(String sql) { try { rs = stat.executeQuery(sql); } catch (SQLException ex) { Logger.getLogger(SQLHelper.class.getName()).log(Level.SEVERE, null, ex); } return rs; }
1b763e11-16f5-433b-95ea-8507a83e31cb
1
@Override public boolean unsubscribeObserver(Observer observer) { boolean removed = false; if (readers.contains(observer)) { removed = readers.remove(observer); } return removed; }
291b7e1a-407a-4d90-94dd-a319e1aab284
5
public void actionPerformed(java.awt.event.ActionEvent e) { String command = e.getActionCommand(); if (myButtonListener != null) { if (command.equals("0")) myButtonListener.processButton(0); else if (command.equals("1")) myButtonListener.processButton(1); else if (command.equals("2")) myButtonListener.processButton(2); else if (command.equals("3")) myButtonListener.processButton(3); } }
eef208e8-485c-4b4a-a89b-c2ce650b0f86
8
protected void updateArc() { // arc was fully matched - save it addToPath( arc ); boolean extended = false; if ( arc.to != forbidden ) { ListIterator<Arc> iter = arc.to.outgoingArcs(); while ( iter.hasNext() ) { Arc a = iter.next(); if ( a.versions.intersects(versions) &&a.to.isPrintedOutgoing(a.versions) &&a.versions.nextSetBit(mum.version)!=mum.version &&(!a.isParent()||!a.hasChildInVersion(mum.version)) ) { this.arc = a; this.first = 0; MatchThreadTransposeLeft mttl = new MatchThreadTransposeLeft( this ); mttl.run(); extended |= mttl.first > 0; } } } if ( !extended ) mismatch(); }
38930f01-0b76-4457-8273-f46561b0533a
5
public int[] sortArrayWithHashMaps(int[] arr) { class ArrEl { int value; int freq; int first; @Override public boolean equals(Object o) { return this == o || o instanceof ArrEl && value == ((ArrEl) o).value; } @Override public int hashCode() { return value; } } class ELComparator implements Comparator<ArrEl> { @Override public int compare(ArrEl el1, ArrEl el2) { if (el1.freq > el2.freq) { return -1; } else if (el1.freq < el2.freq) { return 1; } else if (el1.freq == el2.freq && el1.first < el2.first) { return -1; } else { return 1; } } } Map<Integer, ArrEl> els = new HashMap<>(); for(int i = 0; i < arr.length; i++) { ArrEl el; if (els.containsKey(arr[i])) { el = els.get(arr[i]); el.freq = el.freq + 1; } else { el = new ArrEl(); el.first = i; el.freq = 1; el.value = arr[i]; } els.put(arr[i], el); } List<ArrEl> list = new ArrayList<>(); for (Map.Entry<Integer, ArrEl> e : els.entrySet()) { list.add(e.getValue()); } Collections.sort(list, new ELComparator()); int[] quit = new int[arr.length]; int i = 0; for (ArrEl el : list) { for (int j = 0; j < el.freq; j++) { quit[i] = el.value; i++; } } return quit; }
1f071c72-0389-49ae-8b50-cdb2b854ee0d
0
@SuppressWarnings("unchecked") public List<Film> getDostepneFilmy() { return em.createNamedQuery("film.dostepny").getResultList(); }
ded96e98-f7c0-4922-9d1b-be0af5c6b414
5
@Override public void actionPerformed(ActionEvent act) { // if the user presses exit game in the in-game menu if (act.getActionCommand().equals("menuExitGameBtn")) { exitGame(); } // if the user presses help in the in-game menu if (act.getActionCommand().equals("menuHelpBtn")) { JOptionPane.showMessageDialog( this, "Steal as much as you can before the time runs out. Take stolen items to the van to cash them in. Drag items around to interact with them. Right click them to get a description.", "Help ", JOptionPane.INFORMATION_MESSAGE); } // if the user presses resume in the in-game menu if (act.getActionCommand().equals("menuResumeBtn")) { closeIngameMenu(); } // if the user presses exit to menu it ends the current game and returns to the main menu if (act.getActionCommand().equals("menuExitToMenuBtn")) { endGame(); enterMainMenu(); } // if the user presses exit to menu it ends the current game and returns to the main menu if (act.getActionCommand().equals("sendMessage")) { closeChat(); player.sendChatMessage(chatPanel.getText()); this.requestFocus(); } }
593965c8-4845-4768-9a0f-3aa17f7d351c
8
private void getConnection(Element connectElement) { String room1Name=""; String room2Name=""; String exit1=""; String exit2=""; Element el; NodeList nl = connectElement.getElementsByTagName("room1"); if(nl != null && nl.getLength() > 0) { el = (Element)nl.item(0); room1Name=el.getAttribute("name"); nl = el.getElementsByTagName("exit"); if(nl != null && nl.getLength() > 0) { el = (Element)nl.item(0); exit1=el.getAttribute("type"); } } nl = connectElement.getElementsByTagName("room2"); if(nl != null && nl.getLength() > 0) { el = (Element)nl.item(0); room2Name=el.getAttribute("name"); nl = el.getElementsByTagName("exit"); if(nl != null && nl.getLength() > 0) { el = (Element)nl.item(0); exit2=el.getAttribute("type"); } } Room room1=rooms.get(room1Name); Room room2=rooms.get(room2Name); room1.addExit(ExitDirection.parse(exit1),room2); room2.addExit(ExitDirection.parse(exit2),room1); }
0988c44c-5cc2-4acf-81ee-3ec1a24a489d
2
@Override public void run() { for(int i = 0 ; i < 20 ; i ++) { try { Thread.sleep((long)Math.random() * 1000); } catch (InterruptedException e) { e.printStackTrace(); } SampleCalc.increase(); } }
d52279c6-ea8d-4801-af5f-f992c65cfcb2
1
public Element toElement(Ticket ticket) { Element element = new Element("ticket"); try { element.setAttribute("row", Integer.toString(ticket.getPlace().getRow().getNumber())); element.setAttribute("place", Integer.toString(ticket.getPlace().getNumber())); element.setAttribute("price", Double.toString(ticket.getPrice())); } catch (Exception e) { throw new TicketNotFullException("Not full data in ticket."); } return element; }
7a0aabfa-46ab-455b-8f1c-915bd43eeb08
0
public void setTyyppi(EsteenTyyppi tyyppi) { this.tyyppi = tyyppi; }
5770702f-b896-4782-8b05-e6ffee90f1fd
6
@Override protected Class<?> loadClass(String name, boolean resolve) { try { if ("watermelon.sim.Player".equals(name) || "watermelon.sim.seed".equals(name) || "watermelon.sim.Point".equals(name)||"watermelon.sim.Pair".equals(name)) return parent.loadClass(name); else return super.loadClass(name, resolve); } catch (ClassNotFoundException e) { return null; } }
1b8602a4-8e07-4e31-9d43-db910822fbae
8
private void checkCollision() { for (int i = 0; i < collisionRange.size(); i++) { if (getRectangle().intersects(collisionRange.get(i))) { // Kollision Unten if (collisionRange.get(i).getY() > this.getY() && collisionRange.get(i).getY() <= this.getY() + this.getHeight()) { this.jump = false; } // Kollision Oben if (collisionRange.get(i).getY() + collisionRange.get(i).height >= this .getY() && collisionRange.get(i).getY() < this.getY()) { System.out.println("Oben"); } // Kollision Links if (collisionRange.get(i).getX() + collisionRange.get(i).width >= this .getX() && collisionRange.get(i).getX() < this.getX()) { this.setLocation(this.getX() + 10, this.getY()); } } } }
c2bd83a3-9234-4644-8c01-b1dff940242e
3
public final void setLedSize(final double LED_SIZE) { double size = LED_SIZE < 10 ? 10 : (LED_SIZE > 50 ? 50 : LED_SIZE); if (null == ledSize) { _ledSize = size; } else { ledSize.set(size); } }
8cfe7d51-4231-4dad-8972-4f84f9943db7
8
private String possibleTurns(int x, int y) { String turns = ""; if (x > 0) { if (!maze.getTileAt(x - 1, y).equals(ETile.WALL)) { turns += EDirection.LEFT.getSymbol(); } } if (x < maze.getWidth() - 1) { if (!maze.getTileAt(x + 1, y).equals(ETile.WALL)) { turns += EDirection.RIGHT.getSymbol(); } } if (y > 0) { if (!maze.getTileAt(x, y - 1).equals(ETile.WALL)) { turns += EDirection.UP.getSymbol(); } } if (y < maze.getHeight() - 1) { if (!maze.getTileAt(x, y + 1).equals(ETile.WALL)) { turns += EDirection.DOWN.getSymbol(); } } return turns; }
d5d5f8c8-93e6-43e2-bf2c-3a8ef4fcc8a5
1
private int computeExpectation(int[] pref, int[] dist, int nfruits, int bowlsz) { double exp = 0; for (int i = 0; i != 12; ++i) { double p = 1.0 * dist[i] / nfruits; exp += (p * pref[i] * bowlsz); } return (int)exp; }
80e85e2f-796f-444c-9250-1b1741c5bdca
5
public void onBlockRemoval(World var1, int var2, int var3, int var4) { super.onBlockRemoval(var1, var2, var3, var4); if(!var1.multiplayerWorld) { var1.notifyBlocksOfNeighborChange(var2, var3 + 1, var4, this.blockID); var1.notifyBlocksOfNeighborChange(var2, var3 - 1, var4, this.blockID); this.updateAndPropagateCurrentStrength(var1, var2, var3, var4); this.notifyWireNeighborsOfNeighborChange(var1, var2 - 1, var3, var4); this.notifyWireNeighborsOfNeighborChange(var1, var2 + 1, var3, var4); this.notifyWireNeighborsOfNeighborChange(var1, var2, var3, var4 - 1); this.notifyWireNeighborsOfNeighborChange(var1, var2, var3, var4 + 1); if(var1.isBlockNormalCube(var2 - 1, var3, var4)) { this.notifyWireNeighborsOfNeighborChange(var1, var2 - 1, var3 + 1, var4); } else { this.notifyWireNeighborsOfNeighborChange(var1, var2 - 1, var3 - 1, var4); } if(var1.isBlockNormalCube(var2 + 1, var3, var4)) { this.notifyWireNeighborsOfNeighborChange(var1, var2 + 1, var3 + 1, var4); } else { this.notifyWireNeighborsOfNeighborChange(var1, var2 + 1, var3 - 1, var4); } if(var1.isBlockNormalCube(var2, var3, var4 - 1)) { this.notifyWireNeighborsOfNeighborChange(var1, var2, var3 + 1, var4 - 1); } else { this.notifyWireNeighborsOfNeighborChange(var1, var2, var3 - 1, var4 - 1); } if(var1.isBlockNormalCube(var2, var3, var4 + 1)) { this.notifyWireNeighborsOfNeighborChange(var1, var2, var3 + 1, var4 + 1); } else { this.notifyWireNeighborsOfNeighborChange(var1, var2, var3 - 1, var4 + 1); } } }
9d553022-7ec9-4927-8768-fabdff9ca686
3
public static boolean validateWeapon(String weapon){ if(weapon.equals("laser") || weapon.equals("mortar") || weapon.equals("droid")){ return true; } return false; }
3ebd4e56-25a3-45e2-879d-9bbf2cf2f918
9
public void MainClick(int button, int x, int y){ if((x>(width/8*5) && y>height/4*3)) { if(button==0){ System.exit(0); } } // //starting the game //This first section is for AI singleplayer. if((x<(width/4) && y>height/2)) { if(button==0){ IsThereAI = true; Screen=1; } } else if((x<(width/2) && y>height/2)) { if(button==0){ IsThereAI = false; Screen=1; } } }
f8355a4f-91f1-4911-a727-6eb293003262
1
private boolean jj_2_18(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_18(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(17, xla); } }
a9a5cd02-1b25-48c5-b3ea-7e3bcfcbcee3
5
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (root == null){ return result; } ArrayList<ArrayList<Integer>> rLeft = levelOrderBottom(root.left); ArrayList<ArrayList<Integer>> rRight = levelOrderBottom(root.right); if (rLeft.size()>=rRight.size()){ result = rLeft; for (int i = rLeft.size()-rRight.size();i<rLeft.size();i++){ result.get(i).addAll(rRight.get(i-(rLeft.size()-rRight.size()))); } } else { for (int i = 0;i<rRight.size()-rLeft.size();i++){ result.add(rRight.get(i)); } result.addAll(rLeft); for (int i = rRight.size()-rLeft.size();i<rRight.size();i++){ result.get(i).addAll(rRight.get(i)); } } ArrayList<Integer> last = new ArrayList<Integer>(); last.add(root.val); result.add(last); return result; }
7879dcd6-120d-485f-ae1d-1cce825d5783
0
private void sendSensorData() { SmartDashboard.putBoolean("Tomahawk forward?", tomahawk.isForward()); SmartDashboard.putBoolean("Tilter at top?", tilter.isTopLimitTriggered()); SmartDashboard.putNumber("String-pot", tilter.readStringPot()); }
27a1f0de-7c13-4f00-81bc-973d8fbe9de3
2
@Override public Map<String, Object> getAuctionById(String auctionId) { Map<String, Object> auctionMap = new HashMap<String, Object>(); Auction auction = emgr.find(Auction.class, Integer.parseInt(auctionId)); if (auction != null) { String auctionName = auction.getAuctionName(); String auctionDescription = auction.getAuctionDescription(); Calendar currentCal = Calendar.getInstance(); Calendar endCal = Calendar.getInstance(); Time endTime = auction.getEndTime(); System.out.println("END TIME = " + endTime.toString()); Calendar endDateCal = new GregorianCalendar(); endDateCal.setTime(auction.getEndDate()); String[] splitEndTime = endTime.toString().split(":"); endDateCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(splitEndTime[0])); endDateCal.set(Calendar.MINUTE, Integer.parseInt(splitEndTime[1])); endDateCal.set(Calendar.SECOND, Integer.parseInt(splitEndTime[2])); if (currentCal.after(endDateCal)) { System.out.println("EXPIRED!!!!!!!!!!!!!!!!!"); // Set the auction as expired. Auction expiredAuction = emgr.find(Auction.class, Integer.parseInt(auctionId)); short expired = 1; expiredAuction.setAuctionExpired(expired); emgr.persist(expiredAuction); // Obtain the item details Item item = emgr.find(Item.class, auction.getItemId()); String itemName = item.getItemName(); String itemModel = item.getItemModel(); String itemDescription = item.getItemDescription(); auctionMap.put("itemName", itemName); auctionMap.put("itemModel", itemModel); auctionMap.put("itemDescription", itemDescription); auctionMap.put("auctionName", auction.getAuctionName()); auctionMap.put("auctionDescription", auction.getAuctionDescription()); auctionMap.put("auctionId", Integer.toString(auction.getAuctionId())); auctionMap.put("auctionDaysLeft", "-1"); auctionMap.put("auctionTimeLeft", "-1"); auctionMap.put("auctionItemId", auction.getItemId()); auctionMap.put("auctionStartPrice", auction.getStartPrice()); } else { System.out.println("Not yet expired."); int daysBetween = Days.daysBetween(new DateTime(currentCal.getTime()), new DateTime(endDateCal.getTime())).getDays(); // Obtain the time difference and compensate for 1 hour (since the calendar starts at 01:00 and not 00:00) Date dateDiff = new Date(endDateCal.getTime().getTime() - currentCal.getTime().getTime() - 3600000); SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss"); System.out.println("Duration: " + timeFormat.format(dateDiff)); // Obtain the item details Item item = emgr.find(Item.class, auction.getItemId()); String itemName = item.getItemName(); String itemModel = item.getItemModel(); String itemDescription = item.getItemDescription(); auctionMap.put("itemName", itemName); auctionMap.put("itemModel", itemModel); auctionMap.put("itemDescription", itemDescription); auctionMap.put("auctionName", auction.getAuctionName()); auctionMap.put("auctionDescription", auction.getAuctionDescription()); auctionMap.put("auctionId", Integer.toString(auction.getAuctionId())); auctionMap.put("auctionDaysLeft", Integer.toString(daysBetween)); auctionMap.put("auctionTimeLeft", timeFormat.format(dateDiff)); auctionMap.put("auctionItemId", auction.getItemId()); auctionMap.put("auctionStartPrice", auction.getStartPrice()); } } return auctionMap; }
70fdaba2-6934-4e8c-8cde-4908fba7882e
7
@Override public boolean equals(Object obj) { if(obj instanceof ScreenCharacter == false) return false; ScreenCharacter other = ((ScreenCharacter)(obj)); return character == other.getCharacter() && getForegroundColor() == other.getForegroundColor() && getBackgroundColor() == other.getBackgroundColor() && isBold() == other.isBold() && isNegative() == other.isNegative() && isUnderline() == other.isUnderline() && isBlinking() == other.isBlinking(); }
ccfc4b49-1c2d-4aab-aed0-58f27d56e372
2
public boolean hasSameData(ZFrame other) { if (other == null) return false; if (size() == other.size()) { return Arrays.equals(data, other.data); } return false; }
d300425e-20f4-4e35-830b-edbd11dc2c96
7
public static void main(String[] args) { String FileName = args[0]; In in = new In(FileName); int size = in.readInt(); Point Points[] = new Point[size]; for (int i = 0; i < size; i++) { Points[i] = new Point(in.readInt(), in.readInt()); } // read in the input file for (int i = 0; i < size - 3; i++) { for (int j = i + 1; j < size - 2; j++) { for (int m = j + 1; m < size - 1; m++) { for (int n = m + 1; n < size; n++) { if (Points[i].slopeTo(Points[j]) == Points[j].slopeTo(Points[m]) && Points[j].slopeTo(Points[m]) == Points[m].slopeTo(Points[n])) { Point Result[] = { Points[i], Points[j], Points[m], Points[n] }; Arrays.sort(Result); System.out.println(Result[0] + "->" + Result[1] + "->" + Result[2] + "->" + Result[3]); // rescale coordinates and turn on animation mode StdDraw.setXscale(0, 32768); StdDraw.setYscale(0, 32768); StdDraw.setPenRadius(0.01); // make the points a bit larger Result[0].drawTo(Result[3]); } } } } } // find the points in line }
23dbefc0-2236-42c4-bf01-18b60f9b9e3d
3
@Override public boolean undo(CardGame game, CardPanel panel) { Hand hand = game.getHand(); List<List<Card>> board = game.getBoard(); List<Card> fromHandList = hand.getList(); //Must be the last one as was just done Card fromHand = fromHandList.remove(fromHandList.size() - 1); game.getDeck().push(fromHand); if (hand != null && hand.getIndex() != -1) { board.set(hand.getIndex(), hand.getList()); } game.setHand(prevHand); //Nothing there if (prevHand != null) { board.set(prevHand.getIndex(), new CopyOnWriteArrayList<Card>()); } return true; }
3a418be0-86c2-495a-bd59-d5eb1ce3e51c
8
@Test public void FAMasiva() { try { log.debug("Sleeping for "+sleepTime+" secs due to ESPHORA reconnection problem"); int sleepMillis = sleepTime * 1000; Thread.sleep(sleepMillis); log.debug("Generando Lote Facturas A iva discriminado"); List<FA> facturasA = new ArrayList<FA>(); FA fa = new FA(TipoDocumento.CUIT, cuitCliente, TipoConcepto.PRODUCTOS, importe); facturasA.add(fa); FA fa2 = new FA(TipoDocumento.DNI, dniCliente, TipoConcepto.PRODUCTOS, importe); facturasA.add(fa2); FA fa3 = new FA(TipoDocumento.OTRO, null, TipoConcepto.PRODUCTOS, importe); facturasA.add(fa3); EsphoraResponse response = gateway.authorize(TipoComprobante.FACTURA_A, 1, cuitFacturador, facturasA); log.info("ESTADO: "+response.getEstado()); log.info("RESULTADO: "+response.getResultado()); log.info("TOTAL APROVADAS: "+response.getTotalApproved()); for (ComprobanteFiscal cfAccepted : response.getAllApproved()) { log.info("CAE:"+cfAccepted.getCae()+" - "+cfAccepted.getVtoCae()); } log.info("TOTAL RECHAZADAS: "+response.getTotalRejected()); for (ComprobanteFiscal cfRejected : response.getAllRejected()) { List<EsphoraObservacion> obs = cfRejected.getObservaciones(); if(obs!=null){ for (EsphoraObservacion o : obs) { log.error(o.getMessage()); } } } List<EsphoraError> errores = response.getGlobalErrors(); if(errores!=null){ for (EsphoraError error : errores) { log.error(error.getMessage()); } } assertNotNull("La respuesta de es nula", response); assertNull("Se obtovieron errores en la llamada al servicio",errores); } catch (FECAEException e) { log.error("ERROR",e); fail(e.getMessage()); } catch (InterruptedException e) { log.error("ERROR",e); fail(e.getMessage()); } }
e74f358f-9e0f-4123-9592-0be51056f1c8
7
public boolean copy() { LOGGER.info("LogWriter: copying : src=" + this.srcFile.getName() + " -> dest=" + this.destFile.getName()); LOGGER.info("LogWriter: copying : src=" + this.srcFile.getAbsolutePath() + " -> dest=" + this.destFile.getAbsolutePath()); // Reader BufferedInputStream bis = null; BufferedOutputStream bos = null; boolean success = false; try { final FileInputStream fis = new FileInputStream(this.srcFile); bis = new BufferedInputStream(fis, bufferSizeInput); // Writer final FileOutputStream fout = new FileOutputStream(this.destFile); bos = new BufferedOutputStream(fout, bufferSizeOutput); byte [] b = new byte[internalCopyWriteBufferSize]; int noOfBytes = 0; while( (noOfBytes = bis.read(b)) != -1) { bos.write(b, 0, noOfBytes); } success = true; Thread.sleep(80); } catch(final IOException ioe) { ioe.printStackTrace(); } catch(final InterruptedException oo) { oo.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } } // End of the try - catch finally // LOGGER.info("LogWriter: copying : >> Done <<"); return success; }
20e92e8b-59ab-433b-b49c-44eda106fafa
6
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(LibraryGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(LibraryGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(LibraryGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LibraryGUI.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 LibraryGUI().setVisible(true); } }); }
9d62682a-798a-433e-88d2-a1ab39b9e740
1
public static pgrid.service.corba.repair.RepairIssue[] read (org.omg.CORBA.portable.InputStream istream) { pgrid.service.corba.repair.RepairIssue value[] = null; int _len0 = istream.read_long (); value = new pgrid.service.corba.repair.RepairIssue[_len0]; for (int _o1 = 0;_o1 < value.length; ++_o1) value[_o1] = pgrid.service.corba.repair.RepairIssueHelper.read (istream); return value; }
eed7cf63-f484-421c-b669-23d52d6c77b8
8
private void selectionSimulationStep(double[] previous, double[] next, SelectionStrengthModel[] ssm, double time) { boolean fixFlag =true; boolean zeroFlag =true; // lots of class v set from the calling function. for (int d =0; d < ndeme; d++) { if (sizes[d] == PopulationSizeModel.NULL_POPULATION) continue; double x =previous[d]; // assumption double ax =1.0 - x; if (x > 0) zeroFlag =false; if (x < 1.0) fixFlag =false; double sAA =ssm[d].getStrength(1, 1, time); double sAa =ssm[d].getStrength(1, 0, time); double saa =ssm[d].getStrength(0, 0, time); //System.err.println("SAA @ time:"+time+"\t"+sAA+"\t"+sAa+"\t"+saa); //System.err.println("x's:"+x+"\t"+ax); afterSelectionA[d] =x * (1 + ax * sAa + x * sAA); afterSelectiona[d] =ax * (1 + x * sAa + ax * saa); } for (int d =0; d < ndeme; d++) { if (sizes[d] == PopulationSizeModel.NULL_POPULATION) { next[d] =0;// frequencys[d][1][nextGen] =0; // nextFreq[d][0]=0;//frequencys[d][0][nextGen] =0; continue; } // first self migration. double rate =1 - totalMRates[d]; double nA =rate * afterSelectionA[d]; double na =rate * afterSelectiona[d]; //for(int[] dier:migrationDirections) // System.out.println(Arrays.toString(dier)); int[] directions =migrationDirections[d]; double[] rates =migrationRates[d]; for (int count =0; count < directions.length; count++) { int j =directions[count]; rate =rates[count]; //System.err.println("After!"+Arrays.toString(afterSelectionA)+"\t"+j+"\tD:"+Arrays.toString(directions)); nA +=rate * afterSelectionA[j]; na +=rate * afterSelectiona[j]; } // now put it together for xp double xp =(nA * (1 - nu) + mu * na) / (nA + na); // we keep N in the sample for now... int N =(int)Math.ceil( sizes[d].populationSize(time) * 2);// //System.err.println("CallBin "+N+" "+xp+"\t"+sizes[d].populationSize(time)+"\t"+nA+"\t"+na); double f =(double) binomial.generateBinomial(N, xp) / N; //System.err.println("return bin "+f); //what if N is zero! if(N==0){ f=0;//throw new RuntimeException("NaN, PopulationSize is probably zero! "+N); } // update next[d] =f; } }
91c79424-10e6-4509-8dee-93ab4952a37e
5
public Server(ServerDataHandler dataHandler){ this.dataHandler = dataHandler; try{ serverSocket = new ServerSocket(PORT); }catch(IOException ioe){ System.out.println("Could not create server socket on " + HOST + ":" + PORT); System.exit(0); } try { HOST = InetAddress.getLocalHost().getHostAddress(); }catch (Exception e){ HOST = "localhost"; } System.out.println("Server running on " + HOST + ":" + PORT); while(serverOn){ try{ Socket clientSocket = serverSocket.accept(); populateClient(clientSocket); clients.add(clientSocket); System.out.println(clientSocket + " connected to server"); ClientServiceThread cliThread = new ClientServiceThread(clientSocket); cliThread.start(); }catch(IOException ioe){ System.out.println("Exception encountered on connection to socket"); } } try{ serverSocket.close(); System.out.println("Server stopped"); }catch(Exception e){ System.out.println("Problem stopping server socket"); System.exit(0); } }
a8406a10-3dbd-41c3-bf53-05ae4c8b063e
7
private static char[] multiply(char[] number1, char[] number2, boolean minus) { char[] result = new char[] {'0'}; char[] reversedNumber1 = reverse(number1); char[] reversedNumber2 = reverse(number2); for(int i=0;i<reversedNumber2.length;i++) { int num2 = reversedNumber2[i] - '0'; int carry = 0; char[] tmpMultiResult = new char[reversedNumber1.length+1+i]; int j = 0; while(j<i) { tmpMultiResult[j++] = '0'; } for(j=0;j<reversedNumber1.length;j++) { int num1 = reversedNumber1[j] - '0'; int tmpResult = num1*num2+carry; if(tmpResult>=10) { carry = tmpResult/10; tmpResult = tmpResult%10; } else { carry = 0; } tmpMultiResult[j+i] = Integer.toString(tmpResult).charAt(0); } if(carry > 0) { tmpMultiResult[j+i] = Integer.toString(carry).charAt(0);; } result = Add.addInterface(result, reverse(tmpMultiResult)); } if(result.length==1&&result[0]=='0') { return result; } return removeFrontZero(result, minus); }
e633fb12-c29e-4e1f-924f-5a5e850c53e2
5
public static void main(String[] args) { try { for (String[] command : convertMultipleConsoleCommands(args)) { try { Process process = new ProcessBuilder(command).start(); BufferedReader in = new BufferedReader(new InputStreamReader( process.getInputStream())); BufferedReader error = new BufferedReader(new InputStreamReader( process.getErrorStream())); String line; while ((line = in.readLine()) != null) out.println(line); while ((line = error.readLine()) != null) err.println(line); } catch (IOException e) { e.printStackTrace(); } } } catch (InvalidCommandException e) { e.printStackTrace(); } }
0cb3165e-f137-496c-98f4-32ffb16bf157
4
public static String formatMethodName(String s){ if (s.toLowerCase().equals("resume")) return "unpause"; if (s.toLowerCase().equals("quit to menu")) return "quitToMenu"; String r[] = s.split(" "); for(String w : r) w = w.substring(0, 1).toUpperCase() + w.substring(1).toLowerCase(); r[0] = r[0].toLowerCase(); s = ""; for (String w : r) s += w; return s; }
9b0b1e5e-f16d-46b3-8a16-abe230f2ac97
9
public long getDateField(String name) { String val = valueParameters(get(name),null); if (val==null) return -1; if (_dateReceive==null) { _dateReceive=(SimpleDateFormat[])__dateReceiveCache.get(); if (_dateReceive==null) { _dateReceive=(SimpleDateFormat[]) new SimpleDateFormat[__dateReceiveSource.length]; __dateReceiveCache.set(_dateReceive); } } for (int i=0;i<_dateReceive.length;i++) { // clone formatter for thread safety if (_dateReceive[i]==null) _dateReceive[i]=(SimpleDateFormat)__dateReceiveSource[i].clone(); try{ Date date=(Date)_dateReceive[i].parseObject(val); return date.getTime(); } catch(java.lang.Exception e) { LogSupport.ignore(log,e); } } if (val.endsWith(" GMT")) { val=val.substring(0,val.length()-4); for (int i=0;i<_dateReceive.length;i++) { try{ Date date=(Date)_dateReceive[i].parseObject(val); return date.getTime(); } catch(java.lang.Exception e) { LogSupport.ignore(log,e); } } } throw new IllegalArgumentException(val); }
2ac1ded4-7e98-486b-9475-0367c0b41124
2
@Override public void actionPerformed(ActionEvent action) { super.actionPerformed(action); // TODO Auto-generated method stub switch(action.getActionCommand()) { case "clear": //ClearCell(activeX, activeY); break; case "random": RandomAssign(5); repaint(); break; } }
b04667ad-6910-47fe-9424-c28189de254a
7
public static boolean correct(String dni)throws NullPointerException, NumberFormatException, StringIndexOutOfBoundsException,IllegalArgumentException{ boolean valor=false; if(dni.length()==0){ throw new NullPointerException(); } else if(dni.length()!=9){ valor=false; throw new StringIndexOutOfBoundsException(); }else if((dni.charAt(dni.length()-1))<65 ||(dni.charAt(dni.length()-1))>90){ valor=false; throw new IllegalArgumentException(); }else{ int i=0; while(dni.charAt(i)>47 && dni.charAt(i)<58){ i++; } if(i==8){ valor=true; }else{ valor=false; throw new NumberFormatException(); } } return valor; }
0f554a7c-580f-42d5-afcc-ef6d089be4a4
8
public static int[][] unMap(int[] solution) throws FileNotFoundException { if (solution == null) { System.out.println("There is no solution for this puzzle."); return sudokuPuzzle; } // 345 = row 3, column 4, box contains a 5 //variables used for determining row, column, and value int quotient, remainder, row, column, value; //Go through all of the variables. Skip variavles < 111 because they do //not represent valid sudoku variables for (int i = 111; i < solution.length; i++) { //make sure that the variable has only three digits and that the //variable is true. This corresonds to a square on the puzzle: //ex. 345 = row 3, column 4, box contains a 5 if (solution[i] > 0 && i < 1000) { //345 / 100 = 3 (row ) remainder 45 quotient = i / 100; remainder = i % 100; row = quotient; //45 / 10 = 4 (column) remaider 5 (value) quotient = remainder / 10; column = quotient; value = remainder % 10; //need to take into account variables like //110 210 310 .... 201 301 401 //these values can not be used since 0 is not valid sudoku entry if (value != 0 && column != 0) { //place the value into the sudoku puzzle sudokuPuzzle[translate(row)][translate(column)] = value; } } }//end for //once we are done parsing the variables we then need to print the //soduku board String output = ""; for (int i = 1; i <= 9; i++) { for (int j = 1; j <= 9; j++) { output += sudokuPuzzle[translate(i)][translate(j)] + " "; } output += "\n"; } System.out.println(output); return sudokuPuzzle; }
0d4485ab-20ad-4218-b8e3-1b75e4c82d29
3
public void run() { while (iSAlive) { if (!missileQueue.isEmpty()) { notifyMissile(); } else { synchronized (this) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
19d4ffc8-f1f4-4097-9d6d-1f5c2fdf388a
4
private void paivitaMaxY(){ double maxY = Double.NEGATIVE_INFINITY; for (KentallaOlija osa : osat){ if (osa.getMaxY() > maxY){ maxY = osa.getMaxY(); } } if (getSuojakilpi()){ if (getY()+getSuojakilvenHalkaisija()/2 > maxY){ maxY = getY()+getSuojakilvenHalkaisija()/2; } } setMaxY(maxY); }
53c4dae5-62b9-4c96-ace1-de87b751e8a0
1
public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException { // Taking one line at a time and tokenizing the same String line = value.toString(); StringTokenizer tokenizer = new StringTokenizer(line); // Iterating through all the words available in that line and forming the key value pair while (tokenizer.hasMoreTokens()) { word.set(tokenizer.nextToken()); // Sending to output collector which in turn passes the same to reducer output.collect(word, one); } } // end method
f8e61d99-2d51-4db6-b0a6-e7c99da4175e
1
public String getString(int index) throws JSONException { Object object = get(index); return object == JSONObject.NULL ? null : object.toString(); }
bf3174fb-65ad-4bd3-a877-63048491c52e
1
private String nString(String s,int i){ String result=""; for(;i>0;i--){ result += s; //for appending strings } return result; }
e8124a18-2fc5-4d20-ab5c-bde5052fe17f
6
public static Float valueOf(Object o) { if (o == null) { return null; } else if (o instanceof Float) { return (Float)o; } else if (o instanceof Double) { return (Float)o; } else if (o instanceof Byte) { return (float)(Byte)o; } else if (o instanceof Integer) { return (float)(Integer)o; } else if (o instanceof Long) { return (float)(Long)o; } else { return null; } }
74582073-94d7-42ad-a443-d7e02587a53b
6
private void makefile(){ if(pType.getText().length() > 0 && prio.getText().length() == 1 && tot.getText().length() > 0 && prescrArea.getText().length() > 0){ if(notes.getText().equals("") || notes.getText().equals("Inserisci le tue note.")) MainPanel.prescr.setNotes("-"); else MainPanel.prescr.setNotes(notes.getText()); MainPanel.prescr.setPresType(pType.getText()); MainPanel.prescr.setPriority(prio.getText().charAt(0)); MainPanel.prescr.setTotal(Integer.parseInt(tot.getText())); MainPanel.prescr.setPrescriptions(prescrArea.getText()); MainPanel.currEx.deletePrescription(MainPanel.prescr.getTruename()); MainPanel.currEx.sendPrescriptionData(MainPanel.prescr); } else System.out.println("Inserisci i campi giusti"); }
5b222522-d9f8-4c4c-a98c-fa6e48e73aa0
3
void sendByteArray(int pNumBytes, byte[] pBytes) { int checksum = 0; sendHeader(); //send the packet header for(int i=0; i<pNumBytes; i++){ outBuffer[i] = pBytes[i]; checksum += pBytes[i]; } //calculate checksum and put at end of buffer outBuffer[pNumBytes] = (byte)(0x100 - (byte)(checksum & 0xff)); //send packet to remote if (byteOut != null) { try{ byteOut.write(outBuffer, 0 /*offset*/, pNumBytes + 1); byteOut.flush(); } catch (IOException e) { logSevere(e.getMessage() + " - Error: 371"); } } }//end of Remote::sendBytes
c30663c5-cd62-433f-a21a-04d8af7dc57f
4
public void testForInterference() { //check for packets that are interferred //PS: only check the packets for interference that are still alive // dead packets are still "int the air" as the sender does not know that it is disturbed. activePacketsIterator.reset(); while(activePacketsIterator.hasNext()){ Packet pack = activePacketsIterator.next(); if(pack.positiveDelivery){ //test if the packet is disturbed according to the destinations interference model. pack.positiveDelivery = !pack.destination.getInterferenceModel().isDisturbed(pack); } } // and the same for the passive packets passivePacketsIterator.reset(); while(passivePacketsIterator.hasNext()){ Packet pack = passivePacketsIterator.next(); if(pack.positiveDelivery){ //test if the packet is disturbed according to the destinations interference model. pack.positiveDelivery = !pack.destination.getInterferenceModel().isDisturbed(pack); } } }
0d62f8b4-6a8e-4391-8865-fafa7d7a628c
4
public RandomListNode copyRandomList(RandomListNode head) { if(head == null) return null; HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>(); RandomListNode newHead = new RandomListNode(head.label); map.put(head, newHead); RandomListNode original = head; RandomListNode copy = newHead; original = original.next; while(original!=null){ RandomListNode temp = new RandomListNode(original.label); map.put(original, temp); copy.next = temp; copy = temp; original = original.next; } original = head; copy = newHead; while(original!=null){ if(original.random != null){ copy.random = map.get(original.random) ; }else{ copy.random = null; } original = original.next; copy = copy.next; } return newHead; }
13d173b9-214c-4588-ad72-58f1f8994833
7
final void method2633(int i, int i_50_, r var_r, int i_51_) { anInt4120++; r_Sub1 var_r_Sub1 = (r_Sub1) var_r; i_51_ += ((r_Sub1) var_r_Sub1).anInt10474 + 1; i_50_ += 1 + ((r_Sub1) var_r_Sub1).anInt10468; if (i != 287) method2634(-49, -3, 16, -9, -115); int i_52_ = i_50_ + ((Class330) this).anInt4113 * i_51_; int i_53_ = 0; int i_54_ = ((r_Sub1) var_r_Sub1).anInt10467; int i_55_ = ((r_Sub1) var_r_Sub1).anInt10466; int i_56_ = -i_55_ + ((Class330) this).anInt4113; if (i_51_ <= 0) { int i_57_ = -i_51_ + 1; i_52_ += ((Class330) this).anInt4113 * i_57_; i_54_ -= i_57_; i_53_ += i_57_ * i_55_; i_51_ = 1; } int i_58_ = 0; if (anInt4123 <= i_54_ + i_51_) { int i_59_ = -anInt4123 + (i_51_ - -i_54_) + 1; i_54_ -= i_59_; } if (i_50_ <= 0) { int i_60_ = 1 + -i_50_; i_53_ += i_60_; i_56_ += i_60_; i_58_ += i_60_; i_52_ += i_60_; i_50_ = 1; i_55_ -= i_60_; } if ((((Class330) this).anInt4113 ^ 0xffffffff) >= (i_55_ + i_50_ ^ 0xffffffff)) { int i_61_ = 1 + (i_55_ + (i_50_ + -((Class330) this).anInt4113)); i_58_ += i_61_; i_55_ -= i_61_; i_56_ += i_61_; } if (i_55_ > 0 && i_54_ > 0) { Class99.method880(i_55_, ((Class330) this).aByteArray4112, ((r_Sub1) var_r_Sub1).aByteArray10471, i_53_, i + 13593, i_54_, i_52_, i_56_, i_58_); method2634(i_51_, -1, i_50_, i_54_, i_55_); } }
563c0792-f2f6-456b-91ee-b5ec378d9c9a
6
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(ConsulterClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ConsulterClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ConsulterClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ConsulterClient.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 ConsulterClient().setVisible(true); } }); }
55a3b188-7fa1-4525-80ce-d90fe9ecc25e
0
public T get(){ return this.t; }
a3100ffa-fe8a-4290-ab7b-6c2af3e4f672
3
public char nextClean() throws JSONException { for (;;) { char c = next(); if (c == 0 || c > ' ') { return c; } } }
dc4b6d69-a458-42a7-ad75-bd85944d61b3
1
public void write_buffer(int val) { int k = 0; int rc = 0; rc = outWave.WriteData(buffer, bufferp[0]); // REVIEW: handle RiffFile errors. /* for (int j=0;j<bufferp[0];j=j+2) { //myBuffer[0] = (short)(((buffer[j]>>8)&0x000000FF) | ((buffer[j]<<8)&0x0000FF00)); //myBuffer[1] = (short) (((buffer[j+1]>>8)&0x000000FF) | ((buffer[j+1]<<8)&0x0000FF00)); myBuffer[0] = buffer[j]; myBuffer[1] = buffer[j+1]; rc = outWave.WriteData (myBuffer,2); } */ for (int i = 0; i < channels; ++i) bufferp[i] = (short)i; }
d9950ad7-d20c-427a-bcd0-1568b1400c30
9
void input() { Properties prop = new Properties(); FileInputStream in = null; File f = null; File propertiesDir = Initializer.sharedInstance().getPropertyDirectory(); if (propertiesDir != null && propertiesDir.exists()) { f = new File(propertiesDir, "locationhistory.properties"); if (f.exists()) { try { in = new FileInputStream(f); prop.load(in); } catch (IOException e1) { e1.printStackTrace(); } catch (AccessControlException e2) { e2.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { } } } } if (prop.isEmpty()) return; for (int i = prop.size(); i >= 1; i--) { comboBox.addItem(prop.getProperty(new Integer(i).toString())); } }
d4702a54-9191-4c54-8fb9-9eee8dfc2057
7
public static void main(String[] args) { List<Integer> numbers = new ArrayList<Integer>(); Collections.addAll(numbers, new Integer[] {1, 2, 3, 4, 5, 6, 7, 8, 9}); long startTimeMillis = System.currentTimeMillis(); List<Integer> products = new ArrayList<Integer>(); // Code is zero based, so position - 1 for(int position = 0; position < factorial(numbers.size()); position++) { List<Integer> numList = new ArrayList<Integer>(numbers); int curPosition = position; String result = new String(""); for(int i = 0; i < numbers.size(); i++) { double value = factorial(numbers.size() - i) / (numbers.size() - i); result += numList.remove((int)((curPosition) / value)); curPosition %= value; } for(int i = 1; i < result.length() / 2; i++) { for(int j = (result.length() - i) / 2; j >= i; j--) { int a = Integer.valueOf(result.substring(0, i)); int b = Integer.valueOf(result.substring(i, i + j)); int c = Integer.valueOf(result.substring(i + j)); if(a * b == c && !products.contains(c)) products.add(c); } } } int sum = 0; for(Integer product : products) sum += product; System.out.println("Sum: " + sum); System.out.println("Time: " + (System.currentTimeMillis() - startTimeMillis) + " ms"); }
ae2ab417-c152-4a8c-b7ad-dd142b1f4b9c
4
public void setCampus(Campus campus) { if (this.campus != null && this.campus.getDocenten().contains(this)) { this.campus.removeDocent(this); } this.campus = campus; if (campus != null && !campus.getDocenten().contains(this)) { campus.addDocent(this); } }
a017602f-c110-4b77-9f95-db062cae5316
9
@Test public void test() { //Set up connection //MongoHelper.setDB("iCrossFit"); MongoHelper.setDB("iCrossFit"); //Clear out DB MongoHelper.getCollection("gyms").drop(); MongoHelper.getCollection("users").drop(); MongoHelper.getCollection("trainingClasses").drop(); //Set up data objects //Create First Gym Gym gym1 = new Gym(); //Set variables gym1.setAddress(new Address("20 W Main Street", "Wappingers Falls", "NY", "12590")); gym1.setComments("Hottest and greatest!!!"); gym1.setEmail("wfcrossfit@wfcrossfit.com"); gym1.setEquipment("Kettle balls, bench, squat rack"); gym1.setHold(false); gym1.setMaxCapacity(50); gym1.setName("Wappingers Falls Crossfit"); gym1.setNickName("Wappers Crossfit"); gym1.setPhone("8454445555"); gym1.setPrice(95.00); gym1.setWebsite("http://www.wfcrossfit.com"); gym1.getClassIds().add(1); gym1.getClassIds().add(2); gym1.getClassIds().add(3); //Save if(!MongoHelper.save(gym1,"gyms")) { TestHelper.failed("Save gym 1 failed."); } //Report Status System.out.println("\nSuccessfully saved GYM id = " + gym1.getId() + ".\n\n"); //Create second gym Gym gym2 = new Gym(); //Set variables gym2.setAddress(new Address("12 Main Street", "Poughkeepsie", "NY", "12601")); gym2.setComments("Biggest and best in the Hudson Valley!!!"); gym2.setEmail("pokcrossfit@pokcrossfit.com"); gym2.setEquipment("Kettle balls, rope climb, flip tire, bench, squat rack"); gym2.setHold(false); gym2.setMaxCapacity(75); gym2.setName("Poughkeepsie Crossfit"); gym2.setNickName("Pok Crossfit"); gym2.setPhone("8453331111"); gym2.setPrice(105.00); gym2.setWebsite("http://www.pokcrossfit.com"); gym2.getClassIds().add(4); gym2.getClassIds().add(5); //Save if(!MongoHelper.save(gym2,"gyms")) { TestHelper.failed("Save gym 2 failed."); } //Report Status System.out.println("\nSuccessfully saved GYM id = " + gym2.getId() + ".\n\n"); //Create third gym Gym gym3 = new Gym(); //Set variables gym3.setAddress(new Address("891 New York Router 82", "Hopewell Junction", "NY", "12533")); gym3.setComments("New and Improved!!!"); gym3.setEmail("hopewellcrossfit@pokcrossfit.com"); gym3.setEquipment("Kettle balls, rope climb, flip tire, bench, squat rack"); gym3.setHold(false); gym3.setMaxCapacity(75); gym3.setName("Hopewell Junction Crossfit"); gym3.setNickName("Hopewell Crossfit"); gym3.setPhone("8451115555"); gym3.setPrice(95.00); gym3.setWebsite("http://www.hopewellcrossfit.com"); gym3.getClassIds().add(6); gym3.getClassIds().add(7); gym3.getClassIds().add(8); //Save if(!MongoHelper.save(gym3,"gyms")) { TestHelper.failed("Save gym 3 failed."); } //Report Status System.out.println("\nSuccessfully saved GYM id = " + gym3.getId() + ".\n\n"); //Create fourth gym Gym gym4 = new Gym(); //Set variables gym4.setAddress(new Address("100 Lexington Avenue", "New York", "NY", "10016")); gym4.setComments("Student discounts available"); gym4.setEmail("midtown1@NYcrossfit.com"); gym4.setEquipment("rope climb, flip tire, bench, squat rack"); gym4.setHold(false); gym4.setMaxCapacity(23); gym4.setName("Midtown Manhattan Crossfit"); gym4.setNickName("Midtown Crossfit"); gym4.setPhone("6461115212"); gym4.setPrice(105.00); gym4.setWebsite("http://www.midtownNYcrossfit.com"); gym4.getClassIds().add(9); gym4.getClassIds().add(10); gym4.getClassIds().add(11); //Save if(!MongoHelper.save(gym4,"gyms")) { TestHelper.failed("Save gym 4 failed."); } //Report Status System.out.println("\nSuccessfully saved GYM id = " + gym4.getId() + ".\n\n"); User user1 = new User(); User user2 = new User(); User user3 = new User(); User user4 = new User(); User user5 = new User(); user1.setFirstName("Michael"); user1.setLastName("Gildein"); user1.setAddress(new Address("100 iCossFit Way", "Poughkeepsie", "NY", "12603")); user1.setPhone("8454445555"); user1.setClassLevel("Expert"); user1.setUserName("admin"); user1.setPassword("password"); user1.setAdmin(true); user1.setBillingPlan("Annually"); user2.setFirstName("Ron"); user2.setLastName("Coleman"); user2.setAddress(new Address("100 iCossFit Way", "Poughkeepsie", "NY", "12603")); user2.setPhone("8454445556"); user2.setClassLevel("Intermediate"); user2.setUserName("user"); user2.setPassword("password"); user2.setAdmin(false); user2.setBillingPlan("Annually"); user3.setFirstName("Best"); user3.setLastName("Debugger"); user3.setAddress(new Address("100 iCossFit Way", "Poughkeepsie", "NY", "12603")); user3.setPhone("8454445557"); user3.setClassLevel("Advance"); user3.setUserName("debug"); user3.setPassword("password"); user3.setAdmin(true); user3.setBillingPlan("Annually"); user4.setFirstName("Artur"); user4.setLastName("Sahakyan"); user4.setAddress(new Address("100 One Way", "Poughkeepsie", "NY", "12603")); user4.setPhone("8454448888"); user4.setClassLevel("Advance"); user4.setUserName("admin1"); user4.setPassword("password"); user4.setAdmin(true); user4.setBillingPlan("Annually"); user5.setFirstName("Patrick"); user5.setLastName("Collins"); user5.setAddress(new Address("200 Onlybest Way", "Poughkeepsie", "NY", "12603")); user5.setPhone("8454412888"); user5.setClassLevel("Expert"); user5.setUserName("admin2"); user5.setPassword("password"); user5.setAdmin(true); user5.setBillingPlan("Annually"); user1.setPassword(getMD5(user1.getPassword())); if(!MongoHelper.save(user1,"users")) { TestHelper.failed("Save user 1 failed."); } user2.setPassword(getMD5(user2.getPassword())); if(!MongoHelper.save(user2,"users")) { TestHelper.failed("Save user 2 failed."); } user3.setPassword(getMD5(user3.getPassword())); if(!MongoHelper.save(user3,"users")) { TestHelper.failed("Save user 3 failed."); } user4.setPassword(getMD5(user4.getPassword())); if(!MongoHelper.save(user4,"users")) { TestHelper.failed("Save user 4 failed."); } user5.setPassword(getMD5(user5.getPassword())); if(!MongoHelper.save(user5,"users")) { TestHelper.failed("Save user 5 failed."); } //Pass test case TestHelper.passed(); }
accbfb88-d3db-4ffb-98d7-cc9d91d57afa
2
public Estoque Abrir(int id) throws ErroValidacaoException,Exception{ try{ PreparedStatement comando = conexao .getConexao().prepareStatement("SELECT * FROM estoques"); ResultSet consulta = comando.executeQuery(); comando.getConnection().commit(); Estoque tmp = null; if(consulta.first()){ tmp = new Estoque(); tmp.setId(consulta.getInt("id")); tmp.setQuantidade(consulta.getInt("quantidade")); } return tmp; }catch(SQLException ex){ ex.printStackTrace(); return null; } }
cd0de8be-6b94-4a20-979a-bd57e15b70cf
5
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { long firstseen = player.getFirstPlayed(); @SuppressWarnings("static-access") String strDte = plugin.getCurrentDTG(firstseen); sender.sendMessage(ChatColor.GRAY + "You first logged in: " + ChatColor.BLUE + strDte); return true; } if (args.length == 1) { Player targeton = this.plugin.getServer().getPlayer(args[0]); if (targeton == null) { OfflinePlayer target = this.plugin.getServer().getOfflinePlayer(args[0]); long firstseen = target.getFirstPlayed(); if(firstseen == 0) { sender.sendMessage(ChatColor.BLUE + "'" + args[0] + "'" + ChatColor.GRAY + " has not been seen!"); sender.sendMessage(ChatColor.GOLD + "(Must use exact username)"); return true; } else { @SuppressWarnings("static-access") String strDte = plugin.getFriendly(firstseen); sender.sendMessage(ChatColor.BLUE + target.getName() + ChatColor.GRAY + " first logged in: " + ChatColor.BLUE + strDte); return true; } } else { long firstseen = targeton.getFirstPlayed(); @SuppressWarnings("static-access") String strDte = plugin.getCurrentDTG(firstseen); // String strDte = getFriendly(firstseen); sender.sendMessage(ChatColor.BLUE + targeton.getName() + ChatColor.GRAY + " first logged in: " + ChatColor.BLUE + strDte); return true; } } return true; }
40dc53cc-6c82-4e5a-910c-6ba2587be602
6
public ReportHighScoresPanel(FreeColClient freeColClient, GUI gui, String prefix) { super(freeColClient, gui, Messages.message("reportHighScoresAction.name")); // Display Panel reportPanel.removeAll(); List<HighScore> highScores = getController().getHighScores(); reportPanel.setLayout(new MigLayout("wrap 3, gapx 30", "[][][align right]", "")); if (prefix != null) { reportPanel.add(new JLabel(Messages.message(prefix)), "span, wrap 10"); } for (HighScore highScore : highScores) { JLabel scoreValue = new JLabel(String.valueOf(highScore.getScore())); scoreValue.setFont(smallHeaderFont); reportPanel.add(scoreValue); String messageID = null; if (highScore.getIndependenceTurn() > 0) { messageID = "report.highScores.president"; } else { messageID = "report.highScores.governor"; } String country = highScore.getNewLandName(); JLabel headline = localizedLabel(Messages.message(StringTemplate.template(messageID) .addName("%name%", highScore.getPlayerName()) .addName("%nation%", country))); headline.setFont(smallHeaderFont); reportPanel.add(headline, "span, wrap 10"); reportPanel.add(new JLabel(Messages.message("report.highScores.turn")), "skip"); int retirementTurn = highScore.getRetirementTurn(); String retirementTurnStr = (retirementTurn <= 0) ? Messages.message("N/A") : Messages.message(Turn.getLabel(retirementTurn)); reportPanel.add(new JLabel(retirementTurnStr)); reportPanel.add(new JLabel(Messages.message("report.highScores.score")), "skip"); reportPanel.add(new JLabel(String.valueOf(highScore.getScore()))); reportPanel.add(new JLabel(Messages.message("report.highScores.difficulty")), "skip"); reportPanel.add(new JLabel(Messages.message(highScore.getDifficulty()))); reportPanel.add(new JLabel(Messages.message("report.highScores.independence")), "skip"); int independenceTurn = highScore.getIndependenceTurn(); String independence = (independenceTurn <= 0) ? Messages.message("no") : Messages.message(Turn.getLabel(independenceTurn)); reportPanel.add(new JLabel(independence)); reportPanel.add(new JLabel(Messages.message("report.highScores.nation")), "skip"); if (highScore.getIndependenceTurn() > 0) { reportPanel.add(new JLabel(highScore.getNationName())); } else { reportPanel.add(new JLabel(Messages.message(highScore.getOldNationNameKey()))); } reportPanel.add(new JLabel(Messages.message("report.highScores.nationType")), "skip"); reportPanel.add(new JLabel(Messages.message(highScore.getNationTypeID() + ".name"))); reportPanel.add(new JLabel(Messages.message("report.highScores.units")), "skip"); reportPanel.add(new JLabel(String.valueOf(highScore.getUnits()))); reportPanel.add(new JLabel(Messages.message("report.highScores.colonies")), "skip"); reportPanel.add(new JLabel(String.valueOf(highScore.getColonies()))); reportPanel.add(new JLabel(Messages.message("report.highScores.retired")), "skip"); DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT); reportPanel.add(new JLabel(format.format(highScore.getDate())), "wrap 20"); } reportPanel.doLayout(); }
040f661d-1a03-4419-b31b-9400e70637ac
6
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { HttpRequest request = (HttpRequest) e.getMessage(); HttpResponseStatus status = OK; String stringResult; String phpResult; File filePath = new File(getURIRequest(request)); if(filePath.exists()) { //result diambil dari request ke PHP RMI server dahulu stringResult = new PHPSourceParser().getResultRunCompiledPHPCode(getURIRequest(request)); PHPExecEngine phpEngine = new PHPExecEngine() { @Override public void beforeExecute(PHPExecEngine engine) { System.out.println("Before Execute"); } @Override public void afterExecute(PHPExecEngine engine) { System.out.println("After Execute"); } }; //hasilnya baru kemudian dikirim ke client (server PHP), dan diproses oleh // CLI server PHP tersebut, untuk dirender ke view browser phpResult = phpEngine.getResultExec(cliCommand + " \" " + stringResult + " \""); try { phpResult = new AppClient().getResultRMIClient(phpResult); } catch(RemoteException ex) { String stackTrace = ""; for(int i = 1; i < ex.getStackTrace().length; i++) { stackTrace += ex.getStackTrace()[i] + "<br/>"; } phpResult = ResponseConstant.internalServerError("Internal Server Error", stackTrace); } catch(NotBoundException ex) { String stackTrace = ""; for(int i = 1; i < ex.getStackTrace().length; i++) { stackTrace += ex.getStackTrace()[i] + "<br/>"; } phpResult = ResponseConstant.internalServerError("Internal Server Error", stackTrace); } } else { phpResult = ResponseConstant.notFound; } HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status); response.setHeader(CONTENT_TYPE, "text/html; charset=UTF-8"); response.setContent(ChannelBuffers.copiedBuffer(phpResult, CharsetUtil.UTF_8)); Channel ch = e.getChannel(); ChannelFuture writeFuture; writeFuture = ch.write(response); writeFuture.addListener(new ChannelFutureProgressListener() { public void operationComplete(ChannelFuture future) { future.getChannel().close(); } public void operationProgressed(ChannelFuture future, long amount, long current, long total) { System.out.printf(" %d / %d (+%d)%n", current, total, amount); } }); // Decide whether to close the connection or not. if(!isKeepAlive(request)) { // Close the connection when the whole content is written out. writeFuture.addListener(ChannelFutureListener.CLOSE); } }
8dfb6b17-cf72-429c-9aaf-81bb0701eccd
3
public static GameObject getGameObjectFromFile(String filePath) { Document doc = getDoc(filePath); final String type = doc.getDocumentElement().getNodeName(); switch (type) { case "item": return getItem(doc); case "mob": return getMob(doc); case "player": return getPlayer(doc); default: System.out.println("Invalid type in " + filePath + " - " + type); return null; } }
1dbd6630-9560-4c70-ac40-e484e22ea960
8
private boolean verifyChapPassword(String plaintext) throws RadiusException { if (plaintext == null || plaintext.length() == 0) throw new IllegalArgumentException("plaintext must not be empty"); if (chapChallenge == null || chapChallenge.length != 16) throw new RadiusException("CHAP challenge must be 16 bytes"); if (chapPassword == null || chapPassword.length != 17) throw new RadiusException("CHAP password must be 17 bytes"); byte chapIdentifier = chapPassword[0]; MessageDigest md5 = getMd5Digest(); md5.reset(); md5.update(chapIdentifier); md5.update(RadiusUtil.getUtf8Bytes(plaintext)); byte[] chapHash = md5.digest(chapChallenge); // compare for (int i = 0; i < 16; i++) if (chapHash[i] != chapPassword[i + 1]) return false; return true; }
d1676fd7-bdf5-435c-95a3-ca76c227b119
6
public static int longestRepeatingSubstr(String str) { int currLen = 1; int maxLen = 1; int prevIndex = 0; int[] visited = new int[256]; for (int i = 0; i < visited.length; i++) { visited[i] = -1; } visited[str.charAt(0)] = 0; for (int i = 1; i < str.length(); i++) { prevIndex = visited[str.charAt(i)]; if (prevIndex == -1 || i - currLen > prevIndex) { currLen++; } else { if (currLen > maxLen) maxLen = currLen; currLen = i - prevIndex; } visited[str.charAt(i)] = i; } if (currLen > maxLen) maxLen = currLen; return maxLen; }
57d8cde9-a02e-4aac-9250-27d080b59c15
1
@Override public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { List<BankDeposit> deposits = ReaderFactory.getInstance().getStAXReader() .readXML(DataPath.XML_FILE); request.setAttribute("type", ParserType.STAX); request.setAttribute("deposits", deposits); return PageName.DEPOSITS_PAGE; } catch (XMLReaderStAXException ex) { log.error(ex); } return PageName.ERROR_PAGE; }
c759df9e-6a9e-4bdb-9bdf-7d0c89aba6d7
8
public void turnLeft() { assertMe(); if(x == 0 && y == 1) { x = 1; y = 0;} else if(x == 1 && y == 0) { x = 0; y = -1;} else if(x == 0 && y == -1) { x = -1; y = 0;} else if(x == -1 && y == 0) { x = 0; y = 1;} assertMe(); }
5eb40c78-c547-4377-aea2-67bc784b03eb
1
public List<CategoryEnum> getCategorys() { if (categorys.isEmpty()) { categorys.addAll(Arrays.asList(CategoryEnum.values())); } return categorys; }
cd07630f-3159-4408-8003-1cb6175bfd42
2
public void setWidth(int w){ if(w == 0) w = 1; //System.out.println("Setting Width: " + w); for(int i = 0; i < anim.getFrames().size(); i ++){ Image image = ((AnimFrame)anim.getFrames().get(i)).image; image = image.getScaledInstance(w, image.getHeight(null), 0); ((AnimFrame)anim.getFrames().get(i)).image = image; } //anim.setImage(anim.getImage().getScaledInstance(w, anim.getImage().getHeight(null), 0)); }
27e6c277-7b8d-4314-bcb7-2eaaf7ecaee3
8
public Date ceil(Date date, int field) { Calendar cal = Calendar.getInstance(); cal.setTime(date); for (int currentField : fields) { if (currentField > field) { if (currentField == Calendar.DAY_OF_MONTH && (field == Calendar.WEEK_OF_MONTH || field == Calendar.WEEK_OF_YEAR)) { continue; } cal.set(currentField, cal.getActualMaximum(currentField)); } } if (field == Calendar.WEEK_OF_MONTH || field == Calendar.WEEK_OF_YEAR) { if (cal.getFirstDayOfWeek() == Calendar.MONDAY) { cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.add(Calendar.DAY_OF_WEEK, 6); } } return cal.getTime(); }
fc8a6151-dc4d-4fce-8cc3-3eac7050fdc7
5
@Override public MapConnector<String, Integer> forceSynchronization() throws Exception { try (Connection con = getConnectorInfo().getConnection()) { forceClear(); int n = 0; StringBuilder values = new StringBuilder(); String stm; for (String s : getMap().keySet()) { values = values.append("(").append("'").append(s).append("'").append(",").append(getMap().get(s)).append(")"); if (n + 1 != BLOCK_INSERT_COUNT && n + 1 != getMap().size() - 1) { values = values.append(","); } n++; if (n == BLOCK_INSERT_COUNT || n == getMap().size() - 1) { stm = "INSERT INTO " + getConnectorInfo().getTableName() + "(key,value) VALUES " + values.toString() + ";"; try (PreparedStatement prepStm = con.prepareStatement(stm)) { prepStm.execute(); } values = new StringBuilder(); n = 0; } } } return this; }
4affbc4b-504c-4cf5-be1b-fcd8cb990e78
4
public static boolean isAvaible(URLConnection connection) { if(connection instanceof JarURLConnection) return true; if(connection instanceof HttpURLConnection) try { return ((HttpURLConnection) connection).getResponseCode() == HttpURLConnection.HTTP_OK; } catch (IOException e) { e.printStackTrace(); return false; } if(connection instanceof FileURLConnection) return true; return false; }
583b5599-7331-4d46-87d2-e888ee1690b1
9
private boolean verticalMove(int fromY, int toY, int x) { Board board = getBoard(); // define the direction by coordinates boolean isUpDirection = toY >= fromY; // bottom to top if (isUpDirection) { for (int i = fromY; i <= toY; i++) { if (exitFlag || Thread.currentThread().isInterrupted()) return false; // invert cells board.setCell(board.getCell(x, i) == Cell.Empty ? Cell.Full : Cell.Empty, x, i); fireBoardChanged(board); sleep(ANIMATION_DELAY); } // top to bottom } else { for (int i = fromY; i >= toY; i--) { if (exitFlag || Thread.currentThread().isInterrupted()) return false; // invert cells board.setCell(board.getCell(x, i) == Cell.Empty ? Cell.Full : Cell.Empty, x, i); fireBoardChanged(board); sleep(ANIMATION_DELAY); } } return true; }
d7b3a914-3ad6-4386-a1f8-0224aec65662
5
private void removeExternalEntry(TrieEntry<K, V> h) { if (h == root) { throw new IllegalArgumentException("Cannot delete root Entry!"); } else if (!h.isExternalNode()) { throw new IllegalArgumentException(h + " is not an external Entry!"); } TrieEntry<K, V> parent = h.parent; TrieEntry<K, V> child = (h.left == h) ? h.right : h.left; if (parent.left == h) { parent.left = child; } else { parent.right = child; } // either the parent is changing, or the predecessor is changing. if (child.bitIndex > parent.bitIndex) { child.parent = parent; } else { child.predecessor = parent; } }
d6d78476-23f9-4a99-85fd-e10020787e07
7
private String DecisionChart(Packet p) { // check in case it is a login packet being returned if (!Global.gLoggedIn) { return HandlePacketsWhenLoggedOut(p); } else { char destination = 'r'; char source = 'r'; if (p.GetDestination() == Global.gUserID) { destination = 'l'; } if (p.GetSource() == Global.gUserID) { source = 'l'; } if ((source == 'l') & (destination == 'l')) { return LocalToLocal(p); } if ((source == 'l') & (destination == 'r')) { return LocalToRemote(p); } if ((source == 'r') & (destination == 'l')) { return RemoteToLocal(p); } if ((source == 'r') & (destination == 'r')) { return RemoteToRemote(p); } } return "\n\nShouldn\'t see this message\n"; }
8f52a692-668a-4449-a6b3-b17b4975b514
6
private boolean upToDate (File verFile) { String storedVersion = getStoredVersion(verFile).replace(".", ""); int storedVersion_ = -1; if (!storedVersion.isEmpty()) { try { storedVersion_ = Integer.parseInt(storedVersion); } catch (NumberFormatException e) { Logger.logWarn("Automatically fixing malformed version file for " + name, e); storedVersion = ""; } } if (storedVersion.isEmpty() || storedVersion_ != Integer.parseInt(version.replace(".", ""))) { try { if (!verFile.exists()) { verFile.getParentFile().mkdirs(); verFile.createNewFile(); } BufferedWriter out = new BufferedWriter(new FileWriter(verFile)); out.write(version); out.flush(); out.close(); return false; } catch (IOException e) { Logger.logError("Error while checking modpack version", e); return false; } } return true; }
40bcee50-d5cd-441f-b2fa-14995a18d607
5
@Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("New")){ }else if(e.getActionCommand().equals("Add File")){ }else if(e.getActionCommand().equals("Add Folder")){ }else if(e.getActionCommand().equals("Open")){ }else if(e.getActionCommand().equals("Save")){ } }
8f118c0f-70bf-4210-a3f4-473c0c5b2786
8
private void handlePhysicalInteract( PlayerInteractEvent event ) { if ( event.isCancelled() ) return; Location l = event.getClickedBlock().getLocation(); l.setY( l.getY() - 2 ); if ( l.getBlock().getState() instanceof Sign ) { Sign s = (Sign) l.getBlock().getState(); String[] msg = s.getLines(); Boolean oo = false; String ms = ""; for ( String m : msg ) { if ( !m.isEmpty() && m.substring( 0, 1 ).equals( "/" ) ) { Bukkit.dispatchCommand( event.getPlayer(), m.substring( 1 ) ); } else { if ( oo ) { ms += m + " "; } } if ( m.toLowerCase().equals( "[tell]" ) ) { oo = true; } } if ( !ms.isEmpty() ) event.getPlayer().sendMessage( ChatColor.DARK_AQUA + ChatColor.translateAlternateColorCodes( "&".charAt( 0 ), ms ) ); } }
83cb6870-b085-437a-be4b-557915630964
2
public static void unpack(Stream buffer) { Sound.aByteArray327 = new byte[0x6baa8]; Sound.buffer = new Stream(Sound.aByteArray327); Soundtrack.method166(); do { int j = buffer.getUnsignedShort(); if (j == 65535) { return; } Sound.sound[j] = new Sound(); Sound.sound[j].method242(buffer); Sound.anIntArray326[j] = Sound.sound[j].method243(); } while (true); }
0aa01c4b-d93b-42eb-99eb-57a0dcabcfce
8
@Override public Question findOutlier() { //sort the list boolean done = false; int i = 1; while(i < eval.getDatapoints().size() && !done) { done = true;//gets changed IF a swap occurs for(int j = 0; j< eval.getDatapoints().size() - (i); j++) { if(eval.getDatapoints().get(j).getValueY() > eval.getDatapoints().get(j+1).getValueY()) { eval.getDatapoints().add(j, eval.getDatapoints().remove(j+1)); done = false;//a swap happened so we're not done yet } } i++; } double median = ( eval.getDatapoints().get(eval.getDatapoints().size()/2).getValueY() + eval.getDatapoints().get(1 + eval.getDatapoints().size()/2).getValueY() )/2; int q1 = eval.getDatapoints().size()/4; int q3 = 3*(q1); double iqr = eval.getDatapoints().get(q3).getValueY() - eval.getDatapoints().get(q1).getValueY(); String answer = ""; double upperRange = eval.getDatapoints().get(q3).getValueY() + (1.5*iqr); double lowerRange = eval.getDatapoints().get(q1).getValueY() - (1.5*iqr); for(int k = 0; k < eval.getDatapoints().size(); k ++) { //if > q3+1.5*iqr //if < q1-1.5*iqr //its an outlier if( eval.getDatapoints().get(k).getValueY() < lowerRange || eval.getDatapoints().get(k).getValueY() > upperRange) {//this is an outlier answer = answer + " " + eval.getDatapoints().get(k).getValueX().toString(); } } //create a new question object Question newQuestion = new Question("Find any outliers.", 45, "s", 0); if(answer.isEmpty()) { answer = "No Outliers"; } newQuestion.setAnswer(answer); return newQuestion; }
b2dbeee5-4685-44c8-b1f7-9cd56dd297b5
3
public HSQLDBRecordingManager(){ super(); _recordings = new ArrayList<Recording>(); try { Class.forName("org.hsqldb.jdbcDriver"); } catch (ClassNotFoundException ex){ return; } try { conn = DriverManager.getConnection("jdbc:hsqldb:file:" + _DB, "SA", ""); // conn.setAutoCommit(false); if(!this.tablesExist()) this.initialize(); } catch (SQLException sqlx){ LOG.fatal("Fatal error when trying to read local data. The message is " + sqlx.getMessage()); System.exit(-1); } }
b985e567-89e6-4a36-a87d-696d7a46d12e
6
public boolean isColliding(GameObject object2) { if (!this.active || !object2.isActive()) { return false; } int x, y; for (int i = 0; i < object2.drawShape.npoints; i++) { x = object2.drawShape.xpoints[i]; y = object2.drawShape.ypoints[i]; if (this.drawShape.contains(x, y)) { return true; } } for (int i = 0; i < this.drawShape.npoints; i++) { x = this.drawShape.xpoints[i]; y = this.drawShape.ypoints[i]; if (object2.drawShape.contains(x, y)) { return true; } } return false; }
2a58ee77-f8f7-422e-9773-526449413c25
0
@Override public void documentRemoved(DocumentRepositoryEvent e) {}
368d1ed2-c4e0-4229-b241-4dbffa144229
2
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); ejbUsuario=new EjbUsuario(); ejbUsuario.getUsuario().setContrasenia(request.getParameter("password")); if(ejbUsuario.getByPass()==false) { response.sendRedirect("cambiarcontrasenia.jsp"); } else { ejbUsuario.getUsuario().setContrasenia(request.getParameter("newPassword")); boolean resul=ejbUsuario.update(); if(resul==false) { response.sendRedirect("cambiarcontrasenia.jsp"); } else { response.sendRedirect("principal.jsp"); } } }
f3018e56-66b0-4fde-871d-6064caf0a5ef
9
public ClassHolderType getClassHolderType() { if (rawClass == null) { // rawClass == null in the generic case such as T variable; return SINGLE; } else if (Collection.class.isAssignableFrom(rawClass)) { if (typeParams.size() > 0) { ClassHolderType innerType = typeParams.get(0).getClassHolderType(); return innerType == COLLECTION ? MULTI_COLLECTION : innerType == MULTI_COLLECTION ? MULTI_COLLECTION : COLLECTION; } return COLLECTION; } else if (Map.class.isAssignableFrom(rawClass)) { if (typeParams.size() > 1) { ClassHolderType innerType = typeParams.get(1).getClassHolderType(); return innerType == COLLECTION ? MULTI_MAP : innerType == MULTI_COLLECTION ? MULTI_MAP: MAP; } return MAP; } else{ return SINGLE; } }