method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
22f72b6d-b6a9-4d65-ae56-d6eb837a30a5
8
public void merge(int[] myList, int low1, int mid, int low2, int high) { /* check if stopButton has been selected */ if(stopFlag == true) { return; } /* create a temp array to hold the sorted ints, initialize iterators etc. */ int[] tempArray = new int[(mid - low1) + (high - low2) + 2]; int s1 = low1; /* starting point for lower half */ int s2 = low2; /* starting point for upper half */ int d = 0; /* index for tempArray */ int k = 0; while(s1 <= mid && s2 <= high) /* while elements remaining in BOTH halves */ { /* compare one element from lower half with one element from upper half; * put the smaller of the two ints into tempArray */ if(myList[s1] < myList[s2]) { tempArray[d++] = myList[s1++]; } else { tempArray[d++] = myList[s2++]; } }//end while(s1 <= mid && s2 <= high) /* at this point, either s1 has reached mid or s2 has reached high (ie one of the * two halves is exhausted), so copy whatever is left of the array half (that * hasn't been exhausted) into tempArray */ /* copy over remaining elements in lower half of array if s1 isnt already at mid */ while(s1 <= mid) { tempArray[d++] = myList[s1++]; } /* copy over remaining elements in upper half of array if s2 isnt already at high */ while(s2 <= high) { tempArray[d++] = myList[s2++]; } /* copy merge-sorted tempArray over to myList */ for(k = 0, s1 = low1; s1 <= high; s1++, k++) { myList[s1] = tempArray[k]; repaint(); try { sortThread.sleep(getMsSleepDuration()); } catch(InterruptedException e) { System.out.println("Error: sleep interrupted" + e); } }//end for loop }//end merge()
ed4f3308-ff84-436b-86d4-d12c96d782e5
4
public void movimiento(){ while(carro.getCaminoEnSeguimiento().darPrimerNodo()!=null) { if(carro.evaluarSiguienteMovimiento()){ try { sleep(movingTime); } catch (InterruptedException e) { e.printStackTrace(); } carro.avanzarEnCamino(); } else { try { sleep(waitingTime); } catch (InterruptedException e) { e.printStackTrace(); } } } }
e1cd1dc9-1326-46f1-bf53-9be4e3c73bad
3
public Object getValueAt(int row, int col) { if (row > -1 && col > -1 && data != null) { return data[row][col]; } else { return null; } }
580fb6d2-3d7e-41d4-a1cd-fa17e9d6d06c
3
public static void main(String[] args) { try { Socket sk = new Socket("192.168.1.220",9090); sk.getOutputStream().write("GET /echo HTTP/1.1\r\n".getBytes("utf-8")); sk.getOutputStream().write("Upgrade: websocket\r\n".getBytes("utf-8")); sk.getOutputStream().write("Connection: Upgrade\r\n".getBytes("utf-8")); sk.getOutputStream().write("Host: 192.168.1.220:9090\r\n".getBytes("utf-8")); sk.getOutputStream().write("Origin: null\r\n".getBytes("utf-8")); sk.getOutputStream().write("Sec-WebSocket-Key: tO03f6yG86XB6K2k0UEfRg==\r\n".getBytes("utf-8")); sk.getOutputStream().write("Sec-WebSocket-Version: 13\r\n".getBytes("utf-8")); sk.getOutputStream().write("Sec-WebSocket-Extensions: x-webkit-deflate-frame\r\n\r\n".getBytes("utf-8")); sk.getOutputStream().flush(); Thread.currentThread().sleep(200); createInputMonitorThread(sk.getInputStream(),sk.getOutputStream()); /*GET /echo HTTP/1.1 Upgrade: websocket Connection: Upgrade Host: 192.168.1.220:9090 Origin: null Sec-WebSocket-Key: tO03f6yG86XB6K2k0UEfRg== Sec-WebSocket-Version: 13 Sec-WebSocket-Extensions: x-webkit-deflate-frame*/ } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
8f803041-25c2-4322-b38e-6971f4dd1af5
3
private static ArrayList<Double> loadFunctionData( String filename ){ ArrayList<Double> fnData = new ArrayList<Double>(); try { java.io.InputStream in = Wavelet.class.getResourceAsStream(filename); CSVReader reader = new CSVReader(new InputStreamReader(in)); List<String[]> myEntries = reader.readAll(); for(int i = 0; i < myEntries.size(); i++) { String[] content = myEntries.get(i); for(int j = 0; j< content.length; j++) { fnData.add( Double.parseDouble( content[j]) ); } } reader.close(); } catch(Exception ex){} return fnData; }// end loadFunctionData method.
30f03f6e-3761-4e9c-8a91-937584506a63
1
public String getData() { if (data == null) return null; return data.toString(); }
3ba52e67-7faa-47ba-85ab-4e88b56c1bb7
3
@Override public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { return motherLangWordList.get(rowIndex); } if (columnIndex == 1) { return translationList.get(rowIndex); } if (columnIndex == 2) { return idList.get(rowIndex); } else { return "0"; } }
8ada5606-0b74-485d-8999-5a1b776bbc0b
4
public static void main(String args[]){ int i=0; int j=0; for(i=1;i<10;i++){ for(j=1;j<10;j++){ totalarray[i][j] = cross; } } for(i=1;i<4;i++){ for(j=1;j<4;j++){ subarray(i,j); } } finalwin = checkarray(bigarraydecision,zero); finalwin = checkarray(bigarraydecision,cross); System.out.print(finalwin); }
654cc7f5-007e-4782-88c3-b834fa4afcbc
8
public static <T> T fromJson(final String inJson, Class<T> objClass) { try { boolean errorFound = false; // if API returned errors or warnings if (GsonErrors.class.isAssignableFrom(objClass)) { GsonErrors gsonErrors = gson.fromJson(inJson, GsonErrors.class); if (gsonErrors != null) { // print errors if (gsonErrors.getErrors() != null) { errorFound = true; Logging.error("The API returned the following error(s): "); for (String error : gsonErrors.getErrors()) { Logging.error(error); } } // print warnings if (gsonErrors.getWarnings() != null) { errorFound = true; Logging.warn("The API returned the following warning(s): "); for (String warning : gsonErrors.getWarnings()) { Logging.warn(warning); } } if (errorFound) return null; } } T resultObj = gson.fromJson(inJson, objClass); return resultObj; } catch (Exception e) { return null; } }
592b7838-3582-4276-805a-62d8dde08e56
8
protected List<Exit> findExits(Modifiable M,XMLTag piece, Map<String,Object> defined, BuildCallback callBack) throws CMException { try { final List<Exit> V = new Vector<Exit>(); final String tagName="EXIT"; final List<XMLLibrary.XMLTag> choices = getAllChoices(null,null,null,tagName, piece, defined,true); if((choices==null)||(choices.size()==0)) return V; for(int c=0;c<choices.size();c++) { final XMLTag valPiece = choices.get(c); if(valPiece.parms().containsKey("VALIDATE") && !testCondition(M,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined)) continue; if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR)) Log.debugOut("MUDPercolator","Build Exit: "+CMStrings.limit(valPiece.value(),80)+"..."); defineReward(M,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true); final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_"); final Exit E=buildExit(valPiece,defined); if(callBack != null) callBack.willBuild(E, valPiece); V.add(E); clearNewlyDefined(defined, definedSet, tagName+"_"); } return V; } catch(PostProcessException pe) { throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe); } }
c6e77843-c22a-4b1d-a31d-95e3777bdcd7
4
public static void main(String[] args) { // Initialization Deck playDeck = new Deck(); playDeck.shuffle(); Hand playerHand = new Hand(); playerHand.drawNewHand(playDeck); Hand computerHand = new Hand(); computerHand.drawNewHand(playDeck); // Playing the game playerHand.evaluate(); int[] playerScore = playerHand.getEvaluation(); computerHand.evaluate(); int[] computerScore = computerHand.getEvaluation(); int[] genList = { 0, 1, 2, 3 }; for (int num : genList) { if (playerScore[num] > computerScore[num]) { System.out.println("Win"); break; } else if (playerScore[num] < computerScore[num]) { System.out.println("Lose"); break; } else if (num == 3){ System.out.println("Draw"); break; } } System.out.println(playerScore[0]+ " " +playerScore[1]+ " " +playerScore[2]+ " " +playerScore[3]); System.out.println(computerScore[0] + " " + computerScore[1] + " " + computerScore[2] + " " + computerScore[3]); }
8acf0cfe-de7d-4599-a473-91c87f0ba194
4
@Override public void run() { Object value = null; RoomInfo roomInfo; String resultString; try { oIn = new ObjectInputStream(new BufferedInputStream( socket.getInputStream())); value = oIn.readObject(); try { roomInfo = getByEvent((String) value); if(roomInfo!=null) { resultString = roomInfo.toJSONObject().toJSONString(); System.out.println(TAG+" normal return: "+resultString); } else { resultString = ""; System.out.println(TAG+" error? or isStarted false "); } oOut = new ObjectOutputStream(new BufferedOutputStream( socket.getOutputStream())); oOut.writeObject(resultString); oOut.flush(); System.out.println("success"); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (IOException e) { } catch (ClassNotFoundException e) { } finally { freeResources(socket, oIn, oOut); } }
2dff91ce-02fc-4fd4-8be3-0b9e3971c509
2
public static <T, E> T getKeyByValue(Map<T, E> map, E value) { for (Map.Entry<T, E> entry : map.entrySet()) { if (value.equals(entry.getValue())) { return entry.getKey(); } } return null; }
7a18d780-22a9-4fd2-af50-aa837c6635dc
5
@Override public boolean equals(Object obj) { if (obj instanceof BulkItem) { BulkContainer objBulk = (BulkContainer) obj; if (objBulk.food == this.food && objBulk.amount == this.amount && objBulk.unit == this.unit && objBulk.container == this.container) return true; else return false; }//if else return false; }//equals(Object obj)
8553deb0-90f8-4160-8f3f-c99bfeaf3d05
5
public void keyReleased(KeyEvent evt){ switch(evt.getKeyCode()){ case KeyEvent.VK_W: upPress = 0; break; case KeyEvent.VK_S: downPress = 0; break; case KeyEvent.VK_A: leftPress = 0; break; case KeyEvent.VK_D: rightPress = 0; break; case KeyEvent.VK_I: doPath = false; break; } }
09863ab0-4cdc-4507-9c53-885db253784e
3
public TeaNode getNode(String[] valuesCombination) { String[] strValues = new String[2]; strValues[0] = valuesCombination[0]; strValues[1] = valuesCombination[2]; Double sugar = valuesCombination[1] == null ? 0 : Double.parseDouble(valuesCombination[1]); for (TeaNode node : this.nodes()) { if(ArrayUtils.isEquals(node.valuesCombination, valuesCombination)) { return node; } } return null; }
5407c070-a12f-42c2-88bb-9d3af8b94e92
7
private static boolean backrefMatcher(REGlobalData gData, int parenIndex, char[] chars, int end) { int len; int i; int parenContent = gData.parens_index(parenIndex); if (parenContent == -1) return true; len = gData.parens_length(parenIndex); if ((gData.cp + len) > end) return false; if ((gData.regexp.flags & JSREG_FOLD) != 0) { for (i = 0; i < len; i++) { if (upcase(chars[parenContent + i]) != upcase(chars[gData.cp + i])) return false; } } else { for (i = 0; i < len; i++) { if (chars[parenContent + i] != chars[gData.cp + i]) return false; } } gData.cp += len; return true; }
0a69e7bb-092c-4ae4-9afb-f070acbf8259
2
public List<infoNode> getInfo() { ArrayList<infoNode> info = new ArrayList<infoNode>(); NodeList infoNodes = node.getChildNodes(); for (int i = 0; i < infoNodes.getLength(); i++) { Node node = infoNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { infoNode infoNode = new infoNode(node); info.add(infoNode); } } return info; }
b87e26d6-9457-40ae-ba77-19d0ffaf26f3
7
private boolean initialize() { CommPortIdentifier portID = null; Enumeration ports = CommPortIdentifier.getPortIdentifiers(); System.out.println("Trying ports:"); while(portID == null && ports.hasMoreElements()) { CommPortIdentifier testPort = (CommPortIdentifier) ports.nextElement(); System.out.println(" " + testPort.getName()); if(testPort.getName().startsWith(portName)) { try { serialPort = (SerialPort) testPort.open(programName, 1000); portID = testPort; System.out.println("Connected on " + portID.getName()); break; } catch(PortInUseException e) { System.out.println(e); } } } if(portID == null || serialPort == null) { System.out.println("Could not connect to Arduino!"); return false; } try { serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); Thread.sleep(2000); return true; } catch(Exception e) { System.out.println(e); } return false; }
f4ae39ed-584f-4bdb-8de8-29379738bf4b
3
public void report_error(String message, Object info) { StringBuffer m = new StringBuffer("Error"); if (info instanceof java_cup.runtime.Symbol) { java_cup.runtime.Symbol s = ((java_cup.runtime.Symbol) info); if (s.left >= 0) { m.append(" in line "+(s.left+1)); if (s.right >= 0) m.append(", column "+(s.right+1)); } } m.append(" : "+message); System.err.println(m); }
167bf9d7-7935-4fc7-92c0-65aebe64e1a0
3
private void makePacks(List<Card> cardList) { for (Card.Suit suit : Card.Suit.values()) { //No kings. for (int i = 0; i < Card.Rank.values().length - 1; i++) { cardList.add(new Card(suit, Card.Rank.values()[i], true)); } //No kings or aces. for (int i = 1; i < Card.Rank.values().length - 1; i++) { cardList.add(new Card(suit, Card.Rank.values()[i], true)); } } }
b99a72b7-8610-4677-b71b-363072528e2d
7
private void jBt_IngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBt_IngresarActionPerformed // TODO add your handling code here: ButtonModel bm = this.bGr_Motivo.getSelection(); if(bm!=null){ if(this.jRb_Archivo1.isSelected()) // Si es ingreso manual, pasa a la pantalla solicitando los datos { panelSuperior(getPanelInterno2()); }else { boolean ok =false; if(this.jRb_Archivo.isSelected()) { try { File archivo = fileChooser.abrirArchivo(); if(archivo!=null){ Utilitario.mensajeProcedimientoCorrecto("Se realizo el ingreso de las caravanas correctamente", "Ingreso de Caravanas"); //this.dispose(); ok = true; } } catch (InputMismatchException e) { Utilitario.mensajeError("Archivo seleccionado no pudo ser encontrado.", "ERROR"); }catch (Exception exc){ Utilitario.mensajeError(exc.toString(),"ERROR"); } } if(ok){ getPanelIngresoD().actualizar(); panelSuperior(getPanelIngresoD());; } } }else{ Utilitario.mensajeError("Debe seleccionar un motivo.", "ERROR"); } }//GEN-LAST:event_jBt_IngresarActionPerformed
bf4388df-6c57-4566-8485-ea1c1739cc55
3
private void paintOnScreen() { try { graphics = buffer.getDrawGraphics(); graphics.drawImage( bi, 0, 0, null ); if( !buffer.contentsLost() ) buffer.show(); Thread.yield(); // Let the OS have a little time... } finally { // release resources if( graphics != null ) graphics.dispose(); if( g2d != null ) g2d.dispose(); } }
9cf13000-8296-4b7b-a50b-150e3cbac583
4
@Override public void collideWith(Element e) { if (e instanceof PlayerCTF) { final PlayerCTF playerEntered = (PlayerCTF) e; // You have to enter your own StartingPosition if (player.equals(playerEntered)) { final PlayerFlag inventoryFlag = playerEntered.getInventory().findFlag(); if (inventoryFlag != null) { // The flag you bring in has to be of an other player if (!inventoryFlag.getPlayer().equals(player)) { getGrid().addElementToPosition(inventoryFlag, inventoryFlag.getPlayerInfo().getBeginPosition()); playerEntered.addCapturedPlayerFlag(inventoryFlag.getPlayerInfo()); playerEntered.getInventory().remove(inventoryFlag); } } } } }
e08bd7c0-aaf8-4f70-9fa9-5eae1a1dfe82
1
public boolean matchesAndOneAbove(Card other) { return (other.getSuit() == this.suit && this.rank.ordinal() == other.getRank().ordinal() + 1); }
87de58c0-5476-4c0a-b371-d2ac3f98a92c
7
public boolean SurviveVisions(int[] inTargets, byte[] inVisions){ // returns true if this set of visions is compatible // with this GameState. In the boolean array, 1 means innocent, 2 means wolf, 0 means no target. boolean output = true; for(int n = 0; n < NumPlayers; n++){ if(this.playerTest(n+1) == 2){ if(inTargets[n] == 0) return true; // No vision was had, therefore no conflict. output = ((playerTest(inTargets[n]) <= (-3)) || (playerTest(inTargets[n]) >= 3)); // output is now // true if the Seer saw a wolf. output = (((inVisions[n] == 2) && output) || ((inVisions[n] == 1) && !output)); } } return output; }
e57b4c47-fdaa-4a7d-b8b8-725bf4aa19ec
5
private void preprocessDataTwo(double commonError){ // Check row and column lengths this.numberOfRows = this.values.length; this.numberOfColumns = this.values[0].length; for(int i=1; i<this.numberOfRows; i++){ if(this.values[i].length!=this.numberOfColumns)throw new IllegalArgumentException("All rows of the value matrix must be of the same length"); } this.diagonalLength = this.numberOfRows; if(this.numberOfRows>this.numberOfColumns)this.diagonalLength = this.numberOfColumns; // Fill errors matrix this.errors = new double[this.numberOfRows][this.numberOfColumns]; for(int i=0; i<this.numberOfRows; i++){ for(int j=0; j<this.numberOfColumns; j++){ this.errors[i][j] = commonError*commonError; } } }
b96bd4c8-065a-4fc6-8c8a-1664ef07c097
9
SlotAction parseSlotAction (Model model, Set<String> variables) throws Exception { String operator = ""; if (t.getToken().equals("-") || t.getToken().equals("<") || t.getToken().equals(">") || t.getToken().equals("<=") || t.getToken().equals(">=")) { operator = t.getToken(); t.advance(); } Symbol slot = Symbol.get (operator+t.getToken()); if (slot.isVariable() && !variables.contains(slot.getString())) model.recordWarning ("variable '" + slot.getString() + "' is not set", t); t.advance(); Symbol value = Symbol.get (t.getToken()); if (value.isVariable() && !variables.contains(value.getString())) model.recordWarning ("variable '" + value.getString() + "' is not set", t); t.advance(); return new SlotAction (model, slot, value); }
89088105-3067-4e02-a192-f0447b1db7a2
7
public void generate(int files, int payments) { int x; int y; int total = 0; try { DocumentBuilderFactory docFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); for (x = 0; x < files; x++) { Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("PAYMENTS"); doc.appendChild(rootElement); for (y = 0; y < payments; y++) { ++total; String payer = "payer" + total; String recipient = "recipient" + total; String details = "details" + total; Element payment = doc.createElement("payment"); rootElement.appendChild(payment); switch (y % 3) { case 0: addPhysicalElements(doc, payment, payer, "physical_payer"); addPhysicalElements(doc, payment, recipient, "physical_recipient"); addDetailsElements(doc, payment, details); break; case 1: addLegalElements(doc, payment, payer, "legal_payer"); addLegalElements(doc, payment, recipient, "legal_recipient"); addDetailsElements(doc, payment, details); break; case 2: addPhysicalElements(doc, payment, payer, "physical_payer"); addLegalElements(doc, payment, recipient, "legal_recipient"); addDetailsElements(doc, payment, details); } } TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); String fileFullPath = GENERATE_PATH + x + ".xml"; StreamResult result = new StreamResult(new File(fileFullPath)); transformer.transform(source, result); logger.debug("File {} successfully generated!", fileFullPath); } } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } }
beb362d6-9941-4a4a-a18a-8d15621d1c7e
0
public int GetTravelTime() { //return the travel time return this.offBusTicks - this.onBusTicks; }
3a3698e8-d4b2-49f3-8a8a-786f63002283
7
public void disconnect() { try { if(sInput != null) sInput.close(); } catch(Exception e) {} // not much else I can do try { if(sOutput != null) sOutput.close(); } catch(Exception e) {} // not much else I can do try{ if(socket != null) socket.close(); } catch(Exception e) {} // not much else I can do // inform the GUI if(cg != null) cg.connectionFailed(); }
7640ffde-d054-45cd-96fa-bc16bae097cc
2
protected boolean canHaveAsElement(Position pos, Element elem) { return elem != null && pos != null && grid.getElementsOnPosition(pos).isEmpty(); }
6b066ea2-1b65-408f-9a47-e00f8f2756ad
4
public static double binaryShannonEntropyDit(double p) { if (p > 1.0) throw new IllegalArgumentException("The probabiliy, " + p + ", must be less than or equal to 1"); if (p < 0.0) throw new IllegalArgumentException("The probabiliy, " + p + ", must be greater than or equal to 0"); double entropy = 0.0D; if (p > 0.0D && p < 1.0D) { entropy = -p * Math.log10(p) - (1 - p) * Math.log10(1 - p); } return entropy; }
df7a066c-dfc2-4767-91c2-2cf5d6e33266
6
protected void avoid(mxCellState edge, mxCellState vertex) { mxIGraphModel model = graph.getModel(); Rectangle labRect = edge.getLabelBounds().getRectangle(); Rectangle vRect = vertex.getRectangle(); if (labRect.intersects(vRect)) { int dy1 = -labRect.y - labRect.height + vRect.y; int dy2 = -labRect.y + vRect.y + vRect.height; int dy = (Math.abs(dy1) < Math.abs(dy2)) ? dy1 : dy2; int dx1 = -labRect.x - labRect.width + vRect.x; int dx2 = -labRect.x + vRect.x + vRect.width; int dx = (Math.abs(dx1) < Math.abs(dx2)) ? dx1 : dx2; if (Math.abs(dx) < Math.abs(dy)) { dy = 0; } else { dx = 0; } mxGeometry g = model.getGeometry(edge.getCell()); if (g != null) { g = (mxGeometry) g.clone(); if (g.getOffset() != null) { g.getOffset().setX(g.getOffset().getX() + dx); g.getOffset().setY(g.getOffset().getY() + dy); } else { g.setOffset(new mxPoint(dx, dy)); } model.setGeometry(edge.getCell(), g); } } }
23dd34ad-123b-428a-a112-814ffa6473e3
0
public State getState() { return state; }
880b8764-fb04-47ac-9b05-5580e6c4dab1
5
public void draw(Graphics2D g) { int w = getWidth(); int h = getHeight(); RoundRectangle2D box = new RoundRectangle2D.Float( 0, 0, w, h, 20, 20); g.setColor(background); g.fill(box); GradientPaint paint; /* GradientPaint paint = new GradientPaint( 0, 0, Color.DARK_GRAY, 0, h, Color.LIGHT_GRAY); g.setPaint(paint); */ int bx = (int)getBallX(); int by = (int)getBallY(); int bw = (int)getBallWidth(); int minX = (int)getBallX(this.min); int maxX = (int)getBallX(this.max); g.setColor(isEnabled() ? Color.GRAY : background); g.setStroke(new BasicStroke(1.5f)); g.drawLine(minX, by, maxX, by); g.drawLine(maxX + (int)getMargin(), 0, maxX + (int)getMargin(), h); g.setColor(isEnabled() ? Color.LIGHT_GRAY : background); g.setStroke(new BasicStroke(1.5f)); g.draw(box); // Draw ticks //g.drawLine(minX, by - bw/4, minX, by + bw/4); //g.drawLine(maxX, by - bw/4, maxX, by + bw/4); Ellipse2D ball = new Ellipse2D.Double( bx - bw/2, by - bw/2, bw, bw); g.setColor(isEnabled() ? Color.GRAY : background); g.fill(ball); int y1 = by - bw/2; int y2 = down? by + bw * 2 : by + bw/2; if (isEnabled()) { paint = new GradientPaint( 0, y1, new Color(0xddffffff, true), 0, y2, new Color(0x00ffffff, true)); g.setPaint(paint); g.fill(ball); paint = new GradientPaint( 0, by - bw/2, Color.LIGHT_GRAY, 0, by + bw/2, Color.BLACK); g.setPaint(paint); g.draw(ball); } g.setColor(Color.LIGHT_GRAY); g.setFont(font); String s = decimalValue.format(value) + unit; g.drawString(s, w - getGutter() + 5, h - 17); g.setFont(new Font(null, 0, 14)); g.drawString(getText(), minX, h - 4); }
fe319c99-5c8f-4786-a11d-594e31bcdff7
5
@Override public String get(long i) { if (ptr != 0) { short strLen = stringLengths.getShort(i); if (strLen < 0) return null; long offset = sizeof * i * maxStringLength * CHARSET_SIZE; for (int j = 0; j < strLen; j++) { byteArray[j] = Utilities.UNSAFE.getByte(ptr + offset + sizeof * j); } try { return new String(byteArray, 0, strLen, CHARSET); } catch (UnsupportedEncodingException ex) { return null; } } else { if (isConstant()) { return data[0]; } else { return data[(int) i]; } } }
08200660-2ac9-4a46-b000-854a3bddaffb
5
public void sortBySuit() { // Sorts the cards in the vHand so that cards of the same suit are // grouped together, and within a suit the cards are sorted by value. // Note that aces are considered to have the lowest value, 1. Vector vNewHand = new Vector(); while (vHand.size() > 0) { int pos = 0; // Position of minimal card. Card c = (Card)vHand.elementAt(0); // Minumal card. for (int i = 1; i < vHand.size(); i++) { Card c1 = (Card)vHand.elementAt(i); if ( c1.getSuit() < c.getSuit() || (c1.getSuit() == c.getSuit() && c1.getValue() < c.getValue()) ) { pos = i; c = c1; } } vHand.removeElementAt(pos); vNewHand.addElement(c); } vHand = vNewHand; }
1c5bbdb7-9d6b-4f52-89e9-58ad851c78ca
4
public static void main(String[] args) { ArrayList<Commands> inputCommands; ArrayList<Commands> outputCommands; ArrayList<Commands> sorted; Scanner inputText = new Scanner(System.in); String text; String path = ""; System.out.println("Enter path-name or leave blank for a sample text: "); boolean check = false; while(check == false){ text = inputText.nextLine(); if(text.equals("")){ path = "src\\Files\\sample.txt"; break; } else { path = text; } if(!Units.CheckGetCommandList(path)){ break; } System.out.println("Not a valid path, enter path-name or leave blank for a sample text: "); } inputCommands = FileReader.getCommandList(path); outputCommands = Logic.formatCommandList(inputCommands); sorted = Logic.Sort(outputCommands); //Prints everything with a dynamic length String format = "%1$-9s %2$-20s %3$-19s %4$-1s"; System.out.format(format,"Command:","Source path:","Target path:","Catalog:"); System.out.print("\n"); for (Commands print : sorted) { System.out.format(format, print.getCommand() , print.getPath() , print.getMovePath() , print.getCatalog() + "\n"); } }
07df19ce-1709-42ca-b15e-3c4491ea05c5
8
public String getRecommendListForPreferentialAttachment() { String recommend = ""; try { Class.forName("com.mysql.jdbc.Driver"); connect = DriverManager.getConnection("jdbc:mysql://localhost/NETWORK_TEST?" + "user=root&password=root"); connect.setAutoCommit(false); statement = connect.createStatement(); for (String node : this.nodeList) { String sql = "select d2.node as recommend, (d1.degree * d2.degree) as score " + "from (select START_NODE as node, count(*) as degree from network_test." + this.table + " where START_NODE = '" + node + "'" + ") as d1, (select START_NODE as node, count(*) as degree from network_test." + this.table + " group by START_NODE) as d2 where d1.node <> d2.node " + "and (d1.node, d2.node) not in (select * from network_test." + this.table + ") order by score desc limit 10"; resultSet = statement.executeQuery(sql); recommend += node + ":"; while (resultSet.next()) { String recommendNode = resultSet.getString("Recommend"); recommend += recommendNode + ","; } recommend += "\n"; } connect.commit(); statement.close(); connect.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { try { if(statement!=null) statement.close(); } catch(SQLException se2) { }// nothing we can do try{ if(connect!=null) connect.close(); } catch(SQLException se) { se.printStackTrace(); } } return recommend; }
2d1484ed-d879-4432-83b0-c38276a0fbd7
3
public Route geefRoute(Knooppunt start, Knooppunt stop) throws IllegalArgumentException { if(knooppuntOpMuur(stop) == true || knooppuntOpMuur(start) == true) throw new IllegalArgumentException("start en/of stop mogen niet op een muur vallen"); if (start.equals(stop)) { Route routeNaarZelfdePunt = new Route(); routeNaarZelfdePunt.appendKnooppunt(start); routeNaarZelfdePunt.appendKnooppunt(stop); return routeNaarZelfdePunt; } RouteMetaData bezochtevelden[][] = new RouteMetaData[this.speelveld.length][this.speelveld[0].length]; bezoekVeld(start, bezochtevelden, null, 0); printBezochteVelden(bezochtevelden); return contrueerRoute(bezochtevelden, stop); }
da652ec3-f87a-4800-8da4-c9ab2619fd15
5
private boolean cargarProductosVendidos(int idVenta, LinkedList<Pair> productos, LinkedList<BigDecimal> preciosFinales) { boolean resultOp = true; Iterator itr = productos.iterator(); Articulo prod; Pair par; BigDecimal cant; Venta v = Venta.findById(idVenta); if (v.getBoolean("pago")) { Iterator itr2 = preciosFinales.iterator(); while (itr.hasNext()) { par = (Pair) itr.next(); //saco el par de la lista BigDecimal precioFinal = (BigDecimal) itr2.next(); prod = (Articulo) par.first(); //saco el producto del par cant = ((BigDecimal) par.second()).setScale(2, RoundingMode.CEILING);//saco la cantidad del par ArticulosVentas prodVendido = ArticulosVentas.create("venta_id", idVenta, "articulo_id", prod.get("id"), "cantidad", cant, "precio_final", precioFinal); resultOp = resultOp && prodVendido.saveIt(); } } else { while (itr.hasNext()) { par = (Pair) itr.next(); //saco el par de la lista prod = (Articulo) par.first(); //saco el producto del par cant = ((BigDecimal) par.second()).setScale(2, RoundingMode.CEILING);//saco la cantidad del par ArticulosVentas prodVendido = ArticulosVentas.create("venta_id", idVenta, "articulo_id", prod.get("id"), "cantidad", cant); resultOp = resultOp && prodVendido.saveIt(); } } return resultOp; }
a3a5df9e-d28b-476f-bfe1-0828f242a2ea
8
public boolean mousedown(Coord c, int button) { if (folded) { if (!c.isect(Coord.z, isz.add(cl.sz()))) return false; if (c.isect(Coord.z.add(cl.sz()), isz)) return true; } if (awnd != null) awnd.setfocus(awnd); else parent.setfocus(this); raise(); if (super.mousedown(c, button)) return (true); if (!c.isect(Coord.z, sz)) return (false); if (button == 1) { ui.grabmouse(this); doff = c; if (c.isect(new Coord(sz.x - gzsz.x, 0), gzsz)) rsm = true; else dm = true; } return (true); }
548aee4c-a2d7-42a2-afdc-a74531998442
4
public static void closeDB() { try { if (connection != null) { connection.close(); } if (statement != null) { statement.close(); } if (rs != null) { rs.close(); } } catch (Exception e) { e.printStackTrace(); } }
9b922529-460a-4d9a-89a7-fdffdee40760
8
protected void gmcpSaySend(String sayName, MOB mob, Environmental target, CMMsg msg) { if((mob.session()!=null)&&(mob.session().getClientTelnetMode(Session.TELNET_GMCP))) { mob.session().sendGMCPEvent("comm.channel", "{\"chan\":\""+sayName+"\",\"msg\":\""+ MiniJSON.toJSONString(CMLib.coffeeFilter().fullOutFilter(null, mob, mob, target, null, CMStrings.removeColors(msg.sourceMessage()), false)) +"\",\"player\":\""+mob.name()+"\"}"); } final Room R=mob.location(); if(R!=null) for(int i=0;i<R.numInhabitants();i++) { final MOB M=R.fetchInhabitant(i); if((M!=null)&&(M!=msg.source())&&(M.session()!=null)&&(M.session().getClientTelnetMode(Session.TELNET_GMCP))) { M.session().sendGMCPEvent("comm.channel", "{\"chan\":\""+sayName+"\",\"msg\":\""+ MiniJSON.toJSONString(CMLib.coffeeFilter().fullOutFilter(null, M, mob, target, null, CMStrings.removeColors(msg.othersMessage()), false)) +"\",\"player\":\""+mob.name()+"\"}"); } } }
c24f237a-453c-401b-84e4-148a2bc9a9f1
8
private static Relationshiptype setBeanProperties(ResultSet resultset) { Relationshiptype relationshiptype = new Relationshiptype(); try { relationshiptype.setId(resultset.getInt("id")); relationshiptype.setName_a_b(resultset.getString("name_a_b")); relationshiptype.setLabel_a_b(resultset.getString("label_a_b")); relationshiptype.setName_b_a(resultset.getString("name_b_a")); relationshiptype.setLabel_b_a(resultset.getString("label_b_a")); relationshiptype.setDescription(resultset.getString("description")); String contact_type_a = resultset.getString("contact_type_a"); if (contact_type_a.equals("Individual")) { relationshiptype.setContact_type_a(Relationshiptype.Enum_contact_type.INDIVIDUAL); } if (contact_type_a.equals("Organization")) { relationshiptype.setContact_type_a(Relationshiptype.Enum_contact_type.ORGANIZATION); } if (contact_type_a.equals("Household")) { relationshiptype.setContact_type_a(Relationshiptype.Enum_contact_type.HOUSEHOLD); } String contact_type_b = resultset.getString("contact_type_b"); if (contact_type_b.equals("Individual")) { relationshiptype.setContact_type_b(Relationshiptype.Enum_contact_type.INDIVIDUAL); } if (contact_type_b.equals("Organization")) { relationshiptype.setContact_type_b(Relationshiptype.Enum_contact_type.ORGANIZATION); } if (contact_type_b.equals("Household")) { relationshiptype.setContact_type_b(Relationshiptype.Enum_contact_type.HOUSEHOLD); } relationshiptype.setContact_sub_type_a(resultset.getString("contact_sub_type_a")); relationshiptype.setContact_sub_type_b(resultset.getString("contact_sub_type_b")); relationshiptype.setIs_reserved(resultset.getBoolean("is_reserved")); relationshiptype.setIs_active(resultset.getBoolean("is_active")); return relationshiptype; } catch (SQLException ex) { Logger.getLogger(RelationshiptypeController.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (Exception e) { Logger.getLogger(RelationshiptypeController.class.getName()).log(Level.SEVERE, null, e); return null; } }
124edb82-46c2-47fd-9e06-1fcb76816b6e
5
@Override public Extension[] getChildren() { NodeList children = configEntry.getChildNodes(); if(children != null) { Extension[] res = new Extension[children.getLength()]; int newIndex = 0; for(int i = 0; i < children.getLength(); i++) { Node entry = children.item(i); // make sure that it is not a pure text entry if(entry.hasAttributes() || entry.hasChildNodes()) { res[newIndex] = new XMLExtension(entry); newIndex++; } } // did we omit some entries? Resize array. if(newIndex != children.getLength()) { res = Arrays.copyOf(res, newIndex); } return res; } return null; }
9ec432a7-3698-4b7c-98f3-6038e1267d0b
8
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int t = 1; t <= T; t++) { int N = sc.nextInt(); int[] arr = new int[N]; for (int i = 0; i < N; i++) { arr[i] = sc.nextInt(); } int min = N, ind = arr[0]; for (int i = 0; i < N; i++) { int a = 0, b = 0; for (int j = 0; j < N; j++) { if (i == j) { continue; } if (arr[j] < arr[i]) { a++; } if (arr[j] > arr[i]) { b++; } } if (Math.abs(a - b) < min) { min = Math.abs(a - b); ind = arr[i]; } } System.out.println("Case " + t + ": " + ind); } }
ad225496-ff3e-4987-be78-86f331c4b4c3
2
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dir == null) ? 0 : dir.hashCode()); result = prime * result + ((hexLoc == null) ? 0 : hexLoc.hashCode()); return result; }
32e1683d-8624-4854-8247-bcf3f916f910
6
@Override public boolean halt(Event lastEvent, OurSim ourSim) { boolean halt = true; List<Job> finishedJobsList = new LinkedList<Job>(); for (ActiveEntity entity : ourSim.getGrid().getAllObjects()) { if (entity instanceof Broker) { Broker broker = (Broker) entity; List<Job> jobs = broker.getJobs(); int currentlyFinished = 0; for (Job job : jobs) { if (job.getState().equals(ExecutionState.FINISHED)) { currentlyFinished++; finishedJobsList.add(job); } } halt &= currentlyFinished >= finishedJobs; } } if (halt) { for (Job job : finishedJobsList) { System.out.println(job.getEndTime()); } } return halt; }
5666e055-baba-442a-8ff3-0d4f6e00d2b9
5
public void declareWinner() { int white, black; white = black = 0; String string; for(int i = 0 ; i < board_row; i++) { for(int j = 0; j < board_col; j++) { ChipColor color = board_array[i][j].getChipColor(); if(color == ChipColor.WHITE) white++; else if(color == ChipColor.BLACK) black++; } } if(white > black) this.winner_string = "You win"; else this.winner_string = "You lose"; this.winner = true; this.repaint(); }
dd9e3478-1e9b-4ccf-9f0e-610f3ee387a4
1
public void save() throws IOException { JSONObject json = new JSONObject(); json.put("startYear", startDate.getYear()); json.put("startMonth", startDate.getMonth()); json.put("startDay", startDate.getDay()); json.put("username", username); json.put("displayName", displayName); json.put("isRightHanded", isRightHanded); json.put("favoriteDiscName", favoriteDiscName); json.put("favoriteCourseName", favoriteCourseName); json.put("gamesPlayed", gamesPlayed); json.put("holesInOne", holesInOne); json.put("albatrosses", albatrosses); json.put("eagles", eagles); json.put("birdies", birdies); json.put("pars", pars); json.put("bogeys", bogeys); json.put("doubleBogeys", doubleBogeys); json.put("tripleBogeys", tripleBogeys); json.put("worstHole", worstHole); json.put("lifetimeThrows", lifetimeThrows); json.put("lifetimeOverUnder", lifetimeOverUnder); try { File file = new File("profiles/" + username + ".json"); FileWriter fw = new FileWriter(file.getAbsolutePath()); fw.write(json.toString()); fw.close(); } catch (IOException ex) { Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex); } saveDiscs(); }
e71a7e0b-1320-4d20-87df-61a454d0b7ce
6
public boolean getBoolean(String key) throws JSONException { Object object = this.get(key); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object) .equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object) .equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); }
78e14ddb-1373-457c-a52c-9a5e8cbf4782
3
@Override public void paintComponent(Graphics g) { super.paintComponent(g); if(string != null) { for(int i=0;i<string.length;i++) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); FontRenderContext frc = g2.getFontRenderContext(); LineMetrics lm = font.getLineMetrics(string[i], frc); float width = (float) font.getStringBounds(string[i], frc).getWidth(); float height = lm.getAscent() + lm.getDescent(); nextX += width; nextY = height*lines + 14; float x; float y; if(getX()+nextX > getX()+getWidth()-4) { lines++; x = 4; y = nextY + height; nextX = width + 4; nextY = height*lines + 14; } else { x = nextX - width; y = nextY; } g2.setColor(color[i]); g2.drawString(string[i], x, y); } nextX = 4; nextY = 4; lines = 0; } }
e8e53820-43bf-4ec1-a42c-4d603987a586
0
public Object getInternal() { return internal; }
6197774b-4c44-4615-8676-23063731fd15
9
private String readByteArray() { StringBuffer buf = new StringBuffer(); int count = 0; char w = (char) 0; // read individual bytes and format into a character array while ((loc < stream.length) && (stream[loc] != '>')) { char c = (char) stream[loc]; byte b = (byte) 0; if (c >= '0' && c <= '9') { b = (byte) (c - '0'); } else if (c >= 'a' && c <= 'f') { b = (byte) (10 + (c - 'a')); } else if (c >= 'A' && c <= 'F') { b = (byte) (10 + (c - 'A')); } else { loc++; continue; } // calculate where in the current byte this character goes int offset = 1 - (count % 2); w |= (0xf & b) << (offset * 4); // increment to the next char if we've written four bytes if (offset == 0) { buf.append(w); w = (char) 0; } count++; loc++; } // ignore trailing '>' loc++; return buf.toString(); }
455eb04c-8a53-4440-ab3d-e65bec9d9581
5
private void AITurn() throws CloneNotSupportedException { Coordinates toHit = new Coordinates(); do { // first time hit any ship if (strategie == null && lastAttackResult == true) { strategie = new AttackStrategie(lastAttack); toHit = strategie.getNextAttack(lastAttackResult); } // go on with strategie ;) else if (strategie != null) { toHit = strategie.getNextAttack(lastAttackResult); // to do chech if allready in hit fields if (toHit == null) { strategie = null; toHit = getRandomCoordinates(); } } else { toHit = getRandomCoordinates(); } } while (alreadyHit.contains(toHit)); alreadyHit.add(toHit); // to do // hit field with coordinates lastAttack = toHit; Message<Coordinates> hitMessage = new MessageFactory<Coordinates>().createMessage(eMessageType.attack, toHit); // game game.handleOponentMessage(hitMessage); }
4c0cabc7-4f2d-4f05-8199-380e6ee65492
1
public String convert(HashMap<String, Integer> dv) { // El mensaje debe ser en la forma IP:costo para cada elemento del dv en vez del espacio como separador del vector StringBuilder result = new StringBuilder(); result.append("From:"); result.append(Setup.ROUTER_NAME); result.append("\n"); result.append("Type:DV\n"); result.append("Len:"); result.append(dv.size()); result.append("\n"); for(String name : dv.keySet()) { int costo = dv.get(name); result.append(name); result.append(":"); result.append(costo); result.append("\n"); } return result.toString(); }
dd673224-90cc-4b61-aa4a-2f6ef1b91341
6
public void monitorFileModify(Path file) { try { if(file.startsWith(sourceDir) && !Files.isDirectory(file)){ Path subPath = sourceDir.relativize(file); for(Path targetDir : targetDirs){ Path newPath = targetDir.resolve(subPath); if(!newPath.toFile().exists() || !FileUtils.contentEquals(newPath.toFile(),file.toFile())){ Files.createDirectories(newPath.getParent()); logger.info("cp "+file.toString()+" "+newPath.toString()); new File(newPath.toString()).setWritable(true); Files.copy(file, newPath, REPLACE_EXISTING); } } } } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage()); } }
96869205-b5a2-4bb9-bb5a-9474fc15d7d0
1
public void setDescriptor(String desc) { if (!desc.equals(getDescriptor())) descriptor = constPool.addUtf8Info(desc); }
aaf5fe16-436b-4293-950d-dd729cd9fe58
7
@Override public JSONObject addPUserPollActivity(String userId, String name, String option) throws JSONException { boolean isSuccess=false; JSONObject mainobj=new JSONObject(); try { pm = PMF.get().getPersistenceManager(); Query query = pm.newQuery(Poll.class, ":p.contains(pollName)"); List<Poll> result = (List<Poll>) query.execute(name); if (result != null) if (result.size() > 0) { result.get(0).addCount(option); } } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage()); mainobj.put("Response", "Error"); return mainobj; } //Now adding user attempted status to User DB try { pm = PMF.get().getPersistenceManager(); Query query = pm.newQuery(User.class, ":p.contains(userId)"); List<User>result = (List<User>) query.execute(userId); if(result!=null) if(result.size()>0) { isSuccess=result.get(0).addUserPollActivity(name); if(isSuccess) { mainobj=getPollStatus(name); } else { mainobj.put("Response", "Error"); } } pm.close(); } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage()); mainobj.put("Response", "Error"); return mainobj; } return mainobj; }
e57e7f68-413c-4445-b977-83205d9128ea
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; MInterface other = (MInterface) obj; if (operations == null) { if (other.operations != null) return false; } else if (!operations.containsAll(other.operations) || !other.operations.containsAll(operations)) // any order return false; if (pub != other.pub) return false; return true; }
966c13bd-5eaa-45ec-bdca-669f76bdddff
9
public String getSchemeSpecificPart() { StringBuffer schemespec = new StringBuffer(); if (m_userinfo != null || m_host != null || m_port != -1) { schemespec.append("//"); //$NON-NLS-1$ } if (m_userinfo != null) { schemespec.append(m_userinfo); schemespec.append('@'); } if (m_host != null) { schemespec.append(m_host); } if (m_port != -1) { schemespec.append(':'); schemespec.append(m_port); } if (m_path != null) { schemespec.append( (m_path)); } if (m_queryString != null) { schemespec.append('?'); schemespec.append(m_queryString); } if (m_fragment != null) { schemespec.append('#'); schemespec.append(m_fragment); } return schemespec.toString(); }
352837e5-8af5-4a1c-a51b-621c739c947f
9
private void export() { if(modelCompareShipping == null) return; Integer columnCount = jTableReport.getColumnCount() == 0 ? 1 : jTableReport.getColumnCount(); Integer rowCount = jTableReport.getRowCount() + 5; Object[][] data = new Object[rowCount][columnCount]; StringBuilder line = new StringBuilder(); if(jComboBoxRegion.getSelectedIndex() == 0) { List<Agent> selectedAgent = modelSelectedAgent.getList(); line.append("Клиенты: "); for(Agent agent : selectedAgent) { line.append(agent.getId() + "; "); } } else { line.append("Регион: " + jComboBoxRegion.getSelectedItem().toString()); if(jRadioButtonRegionPrice.isSelected()){ line.append(" Региональный прайс: " + ((RegionPrice) jComboBoxRegionPrice.getSelectedItem()).toString()); }else if(jRadioButtonGroupPrice.isSelected()){ line.append(" Групповой прайс: " + ((GroupPrice) jComboBoxGroupPrice.getSelectedItem()).toString()); }else{ line.append(" Все:"); } } String first = "Период 1: с " + new SimpleDateFormat(Application.TABLE_DATE).format(jXDatePickerFirstStart.getDate()) + " по " + new SimpleDateFormat(Application.TABLE_DATE).format(jXDatePickerFirstEnd.getDate()); String second = "Период 2: с " + new SimpleDateFormat(Application.TABLE_DATE).format(jXDatePickerSecondStart.getDate()) + " по " + new SimpleDateFormat(Application.TABLE_DATE).format(jXDatePickerSecondEnd.getDate()); data[0][0] = line.toString(); data[1][0] = first; data[2][0] = second; JTableHeader[] headers = new JTableHeader[columnCount]; for(int i = 0; i < columnCount; i++) { JTableHeader header = jTableReport.getTableHeader(); data[4][i] = header.getColumnModel().getColumn(i).getHeaderValue(); } for(int i = 0; i < rowCount - 5; i++) { for(int j = 0; j < columnCount; j++) { data[i + 5][j] = jTableReport.getValueAt(i, j); } } data[1][11] = "=SUBTOTAL(9,L7:L" + rowCount + ")"; data[2][11] = "=SUBTOTAL(3,L7:L" + rowCount + ")"; data[1][12] = "=SUBTOTAL(9,M7:M" + rowCount + ")"; data[2][12] = "=SUBTOTAL(3,M7:M" + rowCount + ")"; data[1][13] = "=P3*100/(P3-R3)-100"; data[1][14] = "=Q3*100/(Q3-S3)-100"; data[1][15] = "=SUBTOTAL(9,P7:P" + rowCount + ")"; data[1][16] = "=SUBTOTAL(9,Q7:Q" + rowCount + ")"; data[1][17] = "=SUBTOTAL(9,R7:R" + rowCount + ")"; data[1][18] = "=SUBTOTAL(9,S7:S" + rowCount + ")"; data[1][19] = "=SUBTOTAL(9,T7:T" + rowCount + ")"; data[1][20] = "=SUBTOTAL(9,U7:U" + rowCount + ")"; ServiceApplication.openOpenSaveJDialogXLS(this, data); }
7b47c578-5adc-4d23-bf09-a9eff34abadc
0
public String getAddressDetail() { StringBuilder addressDetail = new StringBuilder(); addressDetail.append(getStreetName() + "\n" + getCityName() + ", " + getStateName() + "\n" + getCountry() + "\nPin: " + getZipCode()); return addressDetail.toString(); }
0732985e-1b96-4359-b03b-1cacbab3b3d2
6
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); fillFibo(45); int testCases = Integer.parseInt(in.readLine().trim()); for (int t = 0; t < testCases; t++) { int n = Integer.parseInt(in.readLine().trim()); int prev = -1, p; while (n != 0) { p = bs(n); for (int i = p + 1; prev != -1 && i < prev; i++) out.append('0'); out.append('1'); n -= fibo[p]; prev = p; } for (int i = 1; prev != -1 && i < prev; i++) out.append('0'); out.append('\n'); } System.out.print(out); }
9d0c1c48-0307-4e11-8584-7014612b485c
1
public static Packet01JSON decode(byte[] data) throws IOException { ByteArrayInputStream stream = new ByteArrayInputStream(data); try { stream.reset(); return new Packet01JSON(mapper.readValue(stream, Map.class)); } catch (Exception e) { System.out.println("odd, unknown error"); e.printStackTrace(); } return null; }
38c2fdab-5446-4cfd-b2fe-37415f143a2a
5
public void run() { try { Telnet.writeLine(cs, "<fggreen> >>> Welcome to AdaMUD <<< <reset>"); Telnet.flushInput(cs); while((player = s.getPlayerDB().login(cs, s)) == null); player.look(); while (true) { System.out.println("Waiting for message"); String message = Telnet.readLine(cs).trim(); if(message == null) { //Disconnected break; } if(message.equals("bye")) { Telnet.writeLine(cs, "Goodbye!"); break; } parseCommand(message); } cs.close(); } catch (IOException e) { System.out.println("Client error: " + e); } finally { s.getPlayerDB().remove(player); s.remove(cs); } }
ee14d1c3-78cf-4672-ba95-ce8f08a7f107
3
public static int uniforme(double... probas) { // TODO à revoir double p = rand.nextDouble(); // System.out.println("p : " + p); boolean stop = false; int i = 0; double proba = 0; while (!stop && i < probas.length) { // System.out.println("i : " + i); proba += probas[i]; // System.out.println("proba : "+proba); if (p < proba) { stop = true; } i++; } return i - 1; }
a2cd5444-e5ff-4b56-89cf-f168aaf0a485
3
public short deinitialize() { exit.set(true); // Stop the packet sniffing MsgAnalyzerCmnDef.WriteDebugSyslog("De-initialize the SerialReceiver object\n"); short ret = serial_receiver.deinitialize(); if (MsgAnalyzerCmnDef.CheckFailure(ret)) return ret; // Notify the worker thread of analyzing serial data to die... // t.interrupt(); MsgAnalyzerCmnDef.WriteDebugSyslog("Notify the worker thread of analyzing the serial data it's going to die..."); synchronized(this) { notify(); } MsgAnalyzerCmnDef.WriteDebugSyslog("Wait for the worker thread of analyzing serial data's death..."); try { //wait till this thread dies t.join(); // System.out.println("The worker thread of receiving serial data is dead"); MsgAnalyzerCmnDef.WriteDebugSyslog("Wait for the worker thread of analyzing serial data's death Successfully !!!"); } catch (InterruptedException e) { MsgAnalyzerCmnDef.WriteDebugSyslog("The analyzing serial data worker thread throws a InterruptedException..."); } catch(Exception e) { MsgAnalyzerCmnDef.WriteErrorSyslog("Error occur while waiting for death of analyzing serial data worker thread, due to: " + e.toString()); } return ret; }
56f1f144-b108-4943-bcb4-59a40100f4f9
5
public int Problem41() { for (int n=9;n>=1;n--) { int[] digits = new int[n]; for (int i=0;i<digits.length;i++) { digits[i]=i+1; } int result=-1; do { if(Utility.isPrime(Utility.toInteger(digits))) { result = Utility.toInteger(digits); } }while (Utility.nextPermutation(digits)); if (result!=-1) { return result; } } throw new RuntimeException("Not Found"); }
c0e70e8d-0df4-4bb7-8413-971d0527e8e3
2
private Cmds getCommand(String message) { int begin = message.indexOf(' ') + 1; int end = message.indexOf(' ', begin); if(end == NOT_FOUND) end = message.length(); String cmd = message.substring(begin, end).toUpperCase(); try { return Cmds.valueOf(cmd); } catch (IllegalArgumentException iae) { return Cmds.INVALID; } }
4c3d18fc-a989-4350-8ade-df3728540792
8
private void assignGamePoints() { // Get our card points and game value. int curCardPoints = countCardPoints(declarerIndex); int curGameValue = gameValue(); // Grab our player and tricks won pile for them. PlayerInfo player = players[declarerIndex]; Pile pile = player.getTricksWonPile(); // There are 4 possible win conditions: boolean wonGame = false; if (gameType.getGameType() == GameTypeOptions.GameType.Null) { // If it's null, and declarer won no tricks. wonGame = pile.getNumCards() == 0; } else if (gameType.getSchwarz()) { // If schwarz and declarer won all tricks. wonGame = (pile.getNumCards() == 30); } else if (gameType.getSchneider()) { // If schneider and declarer won at-least 90 card points. wonGame = (curCardPoints >= 90 && curGameValue >= highestBid); } else { // If any other case, declarer must've won over 60 points. wonGame = (curCardPoints > 60 && curGameValue >= highestBid); } // If we won the game, add to score, otherwise subtract String tempParts = this.players[(declarerIndex)].getPlayer().getClass().getName().replaceAll("skatgame.", ""); if(wonGame) { player.setGameScore(player.getGameScore() + curGameValue); this.roundStats.log("The " + tempParts + " has won " + curGameValue + " points this round.", this.indentationLevel); } else { player.setGameScore(player.getGameScore() - (2 * curGameValue)); this.roundStats.log("The " + tempParts +" has lost " + (2 * curGameValue) + " points this round.", this.indentationLevel); } // Let our players know the round stats (we used to not have rounds, so this was called game stats, whoops..) int[] endGameScores = new int[PLAYER_COUNT]; for(int i = 0; i < endGameScores.length; i++) endGameScores[i] = this.players[i].getGameScore(); for(PlayerInfo playerInfo : this.players) playerInfo.getPlayer().endGameInfo(wonGame, endGameScores); }
adf9b02c-d4fe-4da8-b2e3-e7227be839e9
6
public static boolean isValid(MouseEvent e, Canvas c, Palette pal) { if (pal != null && pal.getSelectedColor(e.getButton()) == null) return false; Point p = e.getPoint(); if (p.x < 0 || p.y < 0) return false; Dimension d = c.getImageSize(); if (p.x >= d.width || p.y >= d.height) return false; return true; }
3f12c3d5-21d4-46a8-b24c-f085ff82c9d8
1
private VappClient createVApp(IControllerServices controllerServices, String vCloudUrl, String username, String password, String orgName, String vdcName, String vAppName, String catalogName, String templateName, String network) throws ConnectorException { VappClient vCloudApp = new VappClient(controllerServices); try { // logging in String loginResponse = vCloudApp.login(vCloudUrl, username, orgName, password); // getting org links Document doc = RestClient.stringToXmlDocument(loginResponse); String allOrgsLink = doc.getElementsByTagName(Constants.LINK).item(0).getAttributes().getNamedItem(Constants.HREF).getTextContent().trim(); // //needs to be removed in case createVdc needs to be removed String adminLink = doc.getElementsByTagName(Constants.LINK).item(1).getAttributes().getNamedItem(Constants.HREF).getTextContent().trim(); String orgLink = vCloudApp.retrieveOrg(allOrgsLink, orgName); // To instantiate a vApp template you need the vDc on which the vApp is going to be deployed and the object // references for the catalog in which the vApp template will be entered. String vdcLink = vCloudApp.findVdc(orgLink, vdcName); String catalogLink = vCloudApp.findCatalog(orgLink, catalogName); String templateLink = vCloudApp.retrieveTemplate(catalogLink, templateName); String response = vCloudApp.newvAppFromTemplate(vAppName, templateLink, catalogLink, vdcLink, network); String vAppLink = vCloudApp.retrieveVappLink(response); vCloudApp.setvAppLink(vAppLink); } catch (Exception e) { throw new ConnectorException(e); } return vCloudApp; }
b4659d75-e296-4b2d-a758-6cd15767bf41
0
@Override public void loadRcon() throws DataLoadFailedException { Map<String, Object> data = getData("server", "name", "rcon"); load(PermissionType.RCON, "rcon", data); }
441dfbf3-0206-4d49-ad42-abd3fd5c3738
2
public final synchronized void close(){ if(fileFound){ try{ input.close(); }catch(java.io.IOException e){ System.out.println(e); } } }
42254c1b-2448-4083-b3f0-98c64e4461cb
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(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GUI.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 GUI().setVisible(true); } }); }
908f2815-6c66-422d-a63e-a7ec36545781
5
/* */ public void checkFire() /* */ { /* 114 */ for (int i = 0; i < Core.barricades.size(); i++) { /* 115 */ Barricade b = (Barricade)Core.barricades.get(i); /* 116 */ if (this.hitCheck.intersects(b.getBox())) { /* 117 */ this.autoFire = false; /* */ } /* */ } /* 120 */ for (int i = 0; i < Core.enemies.size(); i++) { /* 121 */ EnemyRifle e = (EnemyRifle)Core.enemies.get(i); /* 122 */ if ((this.hitCheck.intersects(e.collision)) && (e != this)) /* 123 */ this.autoFire = false; /* */ } /* */ }
5ac075d6-dca3-4a96-8922-0f3c7cad258b
4
public static ArrayList<Model3D> clone(ArrayList<Model3D> l) { ArrayList<Model3D> models = new ArrayList<Model3D>(); Model3D model; for (Model3D m : l) { model = new Model3D(); for (Face f : m.getFaces()) { model.getFaces().add(new Face(new Point(f.p1.x, f.p1.y, f.p1.z), new Point(f.p2.x, f.p2.y, f.p2.z), new Point(f.p3.x, f.p3.y, f.p3.z))); } for (Segment s : m.getSegments()) { model.getSegments().add(new Segment(new Point(s.p1.x, s.p1.y, s.p1.z), new Point(s.p2.x, s.p2.y, s.p2.z))); } for (Point p : m.getPoints()) { model.getPoints().add(new Point(p.x, p.y, p.z)); } model.setDecalageX(m.getDecalageX()); model.setDecalageY(m.getDecalageY()); model.setNom(m.getNom()); models.add(model); } return models; }
fe3d8265-fd41-425d-bf0b-fb040bf5dbd6
2
static List<Language> getLanguages(Path languageProperties) throws IOException { if (!FileUtil.control(languageProperties)) { throw new IOException(); } if (languages == null) { readLanguageProperties(languageProperties); } return languages; }
5d94d710-7c38-4351-ac9e-f019bc7b15d2
7
public void applyUpdate(Contact update) { if (update == null) return; if (update.getId() != 0 && update.getId() != this.getId() ) throw new IllegalArgumentException("Update contact must have same id as contact to update"); // Since title is used to display contacts, don't allow empty title if (! isEmpty( update.getTitle()) ) this.setTitle(update.getTitle()); // empty nickname is ok // other attributes: allow an empty string as a way of deleting an attribute in update (this is hacky) if (update.getName() != null ) this.setName(update.getName()); else this.setName(""); if (update.getEmail() != null) this.setEmail(update.getEmail()); else this.setEmail(""); if (update.getPhoneNumber() != null ) this.setPhoneNumber(update.getPhoneNumber()); else this.setPhoneNumber(""); }
29770267-dd95-4985-bb80-79e75fa28426
5
int skipCommentsAndQuotes(char[] expressionChars, int position) { String[] startSkip = getStartSkip(); for (int i = 0; i < startSkip.length; i++) { // 判断表达是否和注释的起始标识匹配 if (expressionChars[position] == startSkip[i].charAt(0)) { boolean match = true; for (int j = 1; j < startSkip[i].length(); j++) { if (!(expressionChars[position + j] == startSkip[i].charAt(j))) { match = false; break; } } // 如果匹配需要返回跳过后的表达式位置 if (match) { return endIndexOfCommentsAndQuotes(expressionChars, i, position); } } } return position; }
b359c438-3f91-4de4-b558-47b109daf10c
9
protected synchronized void refreshDicWords(String dicPath) { int index = dicPath.lastIndexOf(".dic"); String dicName = dicPath.substring(0, index); if (allWords != null) { try { Map/* <String, Set<String>> */temp = FileWordsReader .readWords(dicHome + dicPath, charsetName); allWords.put(dicName, temp.values().iterator().next()); } catch (FileNotFoundException e) { // 如果源文件已经被删除了,则表示该字典不要了 allWords.remove(dicName); } catch (IOException e) { throw toRuntimeException(e); } if (!isSkipForVacabulary(dicName)) { this.vocabularyDictionary = null; } // 如果来的是noiseWord if (isNoiseWordDicFile(dicName)) { this.noiseWordsDictionary = null; // noiseWord和vocabulary有关,所以需要更新vocabulary this.vocabularyDictionary = null; } // 如果来的是noiseCharactors else if (isNoiseCharactorDicFile(dicName)) { this.noiseCharactorsDictionary = null; // noiseCharactorsDictionary和vocabulary有关,所以需要更新vocabulary this.vocabularyDictionary = null; } // 如果来的是单元 else if (isUnitDicFile(dicName)) { this.unitsDictionary = null; } // 如果来的是亚洲人人姓氏 else if (isConfucianFamilyNameDicFile(dicName)) { this.confucianFamilyNamesDictionary = null; } // 如果来的是以字母,数字等组合类语言为开头的词汇 else if (isLantinFollowedByCjkDicFile(dicName)) { this.combinatoricsDictionary = null; } } }
4e54782c-519a-47c3-a8c9-63f02d62caee
8
@Override public void process(WatchedEvent event) { System.out.println("[" + Thread.currentThread() + "event : " + event); switch (event.getType()) { case None: switch (event.getState()) { case Disconnected: case Expired: System.out.println("[" + Thread.currentThread() + "Session has expired"); synchronized (lock) { dead = true; lock.notifyAll(); } break; case SyncConnected: System.out.println("[" + Thread.currentThread() + "Connected to the server"); synchronized (lock) { dead = false; lock.notifyAll(); // populateView(); } break; } zk.register(this); break; case NodeCreated: System.out.println("Node " + event.getPath() + " created"); // FLE+ // nodeDataChanged(event.getPath()); break; case NodeChildrenChanged: System.out.println("Children changed for node " + event.getPath()); populateChildren(event.getPath()); break; case NodeDeleted: System.out.println("Node " + event.getPath() + " deleted"); nodeDeleted(event.getPath()); break; case NodeDataChanged: System.out.println("Data changed for node " + event.getPath()); nodeDataChanged(event.getPath()); break; } }
076e789f-e3a0-4f62-ac8a-32d8ff401354
0
public void mouseReleased(MouseEvent event) { adapter.mouseReleased(event); }
40ade1b7-0d9b-474e-af0c-957ce8777539
3
public static DatarateProperty createSoftRequirement(int bandwidthKBitSec, double percentageMinimalRequired) { if(percentageMinimalRequired > 1) percentageMinimalRequired = 1.0d; if(percentageMinimalRequired < 0) percentageMinimalRequired = 0; // do we require 100% of requested at minimum? if(percentageMinimalRequired >= (1.0d -EPS)) { // a very hard soft requirement ;-) return new DatarateProperty(bandwidthKBitSec, Limit.MIN); } else { /* * Depending on the maximum and the percentage of minimal acceptable * of that data rate, we calculate a new expectation value and variance * for a normal distribution, which represents that requirement. */ double DStrich = ((1.0d +percentageMinimalRequired)/2.0d) *bandwidthKBitSec; double sigma = (DStrich -(percentageMinimalRequired *bandwidthKBitSec)) /3.0d; return new DatarateProperty((int)Math.round(DStrich), sigma*sigma, Limit.MIN); } }
c6c40703-bf7d-49c1-ac94-65a8df230df2
6
private double getHeightScalingConstant(){ double s = 0.0; if(!maxWeightMap.isEmpty() && !davidAvgGVC){ for(Map.Entry<String, Double> entry : maxWeightMap.entrySet()){ s += entry.getValue(); } } else if (!averageAttributeWeights.isEmpty() && davidAvgGVC) { for (Map.Entry<String, Double> entry : averageAttributeWeights.entrySet()) { s += entry.getValue(); } } return s; }
54b21990-bb20-4e55-a002-b4d5ddfec36e
5
public Collection<ProvinciaDTO> buscarPorDepartamento (int iddepa) { Connection con = null; PreparedStatement pstm = null; ResultSet rs = null; try { con = UConnection.getConnection(); String sql = "SELECT p.* " + "FROM ubprovincia p " + "WHERE p.IdDepa = ?"; pstm = con.prepareStatement(sql); pstm.setInt(1, iddepa); rs = pstm.executeQuery(); Vector<ProvinciaDTO> ret = new Vector<ProvinciaDTO>(); ProvinciaDTO dto = null; while(rs.next()) { dto = new ProvinciaDTO(); dto.setIdprov(rs.getInt("IdProv")); dto.setProvincia(rs.getString("provincia")); dto.setIddepa(rs.getInt("IdDepa")); ret.add(dto); } return ret; } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } finally { try { if ( rs != null) rs.close(); if (pstm != null) pstm.close(); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } }
6acb70f4-f32f-4a38-ae5e-adf69c14236d
1
public void Display_store() { final Iterator iter = IndStore.values().iterator(); while (iter.hasNext()) { final Swizzler indswz = (Swizzler) iter.next(); System.out.println("\nIV: " + indswz.ind_var() + " tgt: " + indswz.target() + "\narray: " + indswz.array() + " init: " + indswz.init_val() + " end: " + indswz.end_val()); } }
fe410b6a-591b-4251-94b8-99b8439efc3b
5
@EventHandler(priority=EventPriority.LOWEST) public void onPlayerInteract(final PlayerInteractEvent event) { if(isPlaying.contains(event.getPlayer().getName())) { if(event.getPlayer().getItemInHand() != null) { if(event.getPlayer().getItemInHand().getType().equals(Material.MUSHROOM_SOUP)) { if(event.getPlayer().getHealth() >= 20D) { event.setCancelled(true); return; } else { if((event.getPlayer().getHealth() + 7) > 20D) { event.getPlayer().setHealth(20D); } else { event.getPlayer().setHealth(event.getPlayer().getHealth()+7); } event.getPlayer().getInventory().getItemInHand().setType(Material.BOWL); return; } } } } }
2ec76d68-46f5-4825-b840-66861d10c9c1
1
public void eatMeat(int meat) { this.meat -= meat; if (this.meat <= 0) { this.timeOfInertion = 0; } }
a57e0bbc-6c8e-4cbf-a0d2-f2140daaa6ba
3
private int jjMoveStringLiteralDfa23_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjMoveNfa_0(0, 22); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return jjMoveNfa_0(0, 22); } switch(curChar) { case 45: return jjMoveStringLiteralDfa24_0(active0, 0xfffe00000000000L); default : break; } return jjMoveNfa_0(0, 23); }
4080b403-3f90-476e-bdca-b8bc4d1e07ff
4
public boolean tablanvan(){ if(hovaakar1>-1 && hovaakar2>-1 && hovaakar1<8 && hovaakar2<8) return true; else { logger.info("A lépés nem a táblán van!"); return false; } }
16103abb-f716-4524-9048-2724847aef5d
2
@Override protected void updateShareRate(Share share) { List<Long> history = historyData.get(share.name); if(history != null && flag < history.size()){ share.setActualSharePrice(history.get(flag)); }else{ flag = 1; } }
3e05858e-5137-4caf-81eb-483ae4ae9c65
0
@Test public void delMinReturnsCorrectValueAfterSingleInsert() { h.insert(v); assertEquals(v, h.delMin()); }
b0b11984-3423-430b-9392-10c65b6da7e3
4
public String getToken() { cadtmp = null; for (int x = this.getBegin(); x < this.getCad().length(); x++) { chartmp = this.getCad().charAt(x); this.setBegin(x); if (chartmp != ' ') { if (Pattern.matches(this.getMatchValue(), chartmp + "")) { cadtmp = cadtmp + chartmp; if (this.getMatchValue().equals(this.getMatchOperacion())) { this.setBegin(x + 1); // ListToken.add(new Nodo(cadtmp, this.getMatchName(this.getMatchValue()))); return cadtmp; } } else { // if (!cadtmp.equals("")) { //// ListToken.add(new Nodo(cadtmp, this.getMatchName(this.getMatchValue()))); // } this.changeMatchValue(chartmp); return cadtmp; } } else { // if (!cadtmp.equals("")) { //// ListToken.add(new Nodo(cadtmp, this.getMatchName(this.getMatchValue()))); // } this.setBegin(x + 1); return cadtmp; } } // if (!cadtmp.equals("")) { //// ListToken.add(new Nodo(cadtmp, this.getMatchName(this.getMatchValue()))); // } this.setHaveToken(false); return cadtmp; }
abd6d65c-816c-4983-a890-3c5880c4daab
3
private static byte[][] ShiftRows(byte[][] state) { byte[] t = new byte[4]; for (int r = 1; r < 4; r++) { for (int c = 0; c < Nb; c++) t[c] = state[r][(c + r) % Nb]; for (int c = 0; c < Nb; c++) state[r][c] = t[c]; } return state; }
6d5d3de8-1955-46bd-8347-232bf6856a46
1
public void setUse(String ID, boolean use) { int row = getIndex(ID); if (row == -1) return; rows.get(row)[USE] = new Boolean(use); }
3cc9b928-e88c-40cb-9802-67114e9688d5
8
public static Graph randomTree4() { int depth = 6; Graph graph = new Graph(depth * 100, depth * 50); int a = 0; int b = 1; int c = 0; graph.addVertex(new Vertex(c++, 25, 25 + 25 * (depth - 1))); for (int i = 1; i < depth; i++) { for (int j = 0; j <= i; j++) { graph.addVertex(new Vertex(c++, 25 + 50 * i, 25 + 25 * (depth - i - 1) + 50 * j)); } graph.addEdge(b, a); for (int j = b + 1; j < c - 1; j++) { if (Math.random() < 0.5) graph.addEdge(j, a + j - b); else graph.addEdge(j, a + j - b - 1); } graph.addEdge(c - 1, a + c - b - 2); a = b; b = c; } for (int i = depth; i < 2 * depth + 1; i++) { for (int j = 0; j <= 2 * depth - i - 2; j++) { graph.addVertex(new Vertex(c++, 25 + 50 * i, 75 + 25 * (i - depth - 1) + 50 * j)); } for (int j = b; j < c; j++) { if (Math.random() < 0.5) graph.addEdge(j, a + j - b + 1); else graph.addEdge(j, a + j - b); } a = b; b = c; } return graph; }