method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
68c1eda5-ecca-440f-9bb6-8218f067d763
0
private Handshake(ByteBuffer data, ByteBuffer infoHash, ByteBuffer peerId, boolean isObfuscated) { this.data = data; this.infoHash = infoHash; this.peerId = peerId; this.isObfuscated = isObfuscated; }
fc06e8a6-ce1f-4e45-a392-50a96ba6ac22
3
private void setUpListener(final JScrollPane contents) { changeListButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(pageListShowing==true){ setUpButtonImage(changeListButton,"ChangePageButton.png"); pageListShowing=false; listModel.clear(); contentsList.removeAll(); for (Presentation currentPresentation : contentsChapterList) { listModel.addElement(currentPresentation.getTitle()); pageLabel.setText("Choose a chapter:"); } contents.setViewportView(contentsList); } else{ setUpButtonImage(changeListButton,"ChooseChapterButton.png"); pageListShowing=true; listModel.clear(); contentsList.removeAll(); for (Slide currentSlide : contentsSlideList) { listModel.addElement(currentSlide.getSlideID() + ". " + currentSlide.getDescriptor()); pageLabel.setText("Choose a page:"); } contents.setViewportView(contentsList); } } }); }
7f688904-da4b-49f0-bcbd-8640d9bf1cf1
9
private boolean jj_scan_token(int kind) { if (jj_scanpos == jj_lastpos) { jj_la--; if (jj_scanpos.next == null) { jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); } else { jj_lastpos = jj_scanpos = jj_scanpos.next; } } else { jj_scanpos = jj_scanpos.next; } if (jj_rescan) { int i = 0; Token tok = token; while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } if (tok != null) jj_add_error_token(kind, i); } if (jj_scanpos.kind != kind) return true; if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; return false; }
dc3ba016-283a-4f22-bee3-bd4ea86d9e35
8
public Object getValueFor(int[] position, int crosstabDataIndex){ Object result = null; boolean allPositionsAreEqual = true; if(position != null){ //iterate over dataList for (IntermediateTotalInfo totalInfo : totalsDataList) { int[] positionRelativeToHeader = totalInfo.getPositionRelativeToHeader(); if( positionRelativeToHeader != null && positionRelativeToHeader.length == position.length){ allPositionsAreEqual = true; //iterate over positions for (int i = 0; i < positionRelativeToHeader.length && allPositionsAreEqual; i++) { if(positionRelativeToHeader[i] != position[i]){ //if found one position not equal to the header row index then //mark not all positions are equal in order to skip this //IntermediateDataInfo and pass to the next one allPositionsAreEqual = false; } } if(allPositionsAreEqual){ //the first time we find that all positions are equal we exit the //dataInfo loop and return result = totalInfo.getComputedValues()[crosstabDataIndex]; break; } }else{ //if position relative to header is null then //this is a grand total } }//end loop totalsInfo }else{ //we know the last columns are crosstab grand total columns /*int totalsForAllColsIndex = totalsDataList.size()-1; //the total we need it fullIndex - crosstabDataIndex IntermediateTotalInfo totalInfo = totalsDataList.get(totalsForAllColsIndex-(crosstabSize-1)+crosstabDataIndex); result = totalInfo.getComputedValues()[crosstabDataIndex]; */ IntermediateTotalInfo totalInfo = totalsDataList.get(totalsDataList.size()-1); result = totalInfo.getComputedValues()[crosstabDataIndex]; } return result; }
937dd3bf-5867-4f68-93ba-b13c7b32efd0
7
public void paintComponent(Graphics gfx) { super.paintComponent(gfx); Graphics2D g = (Graphics2D) gfx; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setPaint(Color.blue); //Draw all the lines for(int i = 0; i < (items.length); i++){ g.draw(lines[i]); //To make the lines thicker g.drawLine((int)p[i].x - 1, (int)p[i].y, (int)base[i].x - 1, (int)base[i].y); g.drawLine((int)p[i].x - 2, (int)p[i].y, (int)base[i].x - 2, (int)base[i].y); g.drawLine((int)p[i].x + 1, (int)p[i].y, (int)base[i].x + 1, (int)base[i].y); g.drawLine((int)p[i].x + 2, (int)p[i].y, (int)base[i].x + 2, (int)base[i].y); g.drawLine((int)p[i].x - 3, (int)p[i].y, (int)base[i].x - 3, (int)base[i].y); g.drawLine((int)p[i].x + 3, (int)p[i].y, (int)base[i].x + 3, (int)base[i].y); g.drawLine((int)p[i].x - 4, (int)p[i].y, (int)base[i].x - 4, (int)base[i].y); g.drawLine((int)p[i].x + 4, (int)p[i].y, (int)base[i].x + 4, (int)base[i].y); } Shape[] s; s = new Shape[items.length]; String temp; g.setColor(Color.DARK_GRAY); for(int i = 0; i < items.length; i++){ Float test = new Float((205 - p[i].y) / 200); temp = test.toString(); g.drawString(temp.substring(0,3), (p[i].x + 5),p[i].y); s[i] = p[i].getShape(); } g.setColor(Color.red); for(int i = 0; i < items.length; i++){ g.fill(s[i]); } g.setColor(Color.black); for(int i = 0; i < items.length; i++){ g.draw(s[i]); } //Draw the Line axis g.drawLine(50, 5, 50, 205); //y-axis g.drawLine(50, 205, 260, 205); //x-axis //Draw the static labels g.setFont(new Font(null, Font.BOLD, 12)); String utility_label = new String("Utility"); g.drawString(utility_label, 10, 110); String utility_upper_bound = new String("1"); g.drawString(utility_upper_bound, 35, 15); String utility_lower_bound = new String("0"); g.drawString(utility_lower_bound, 35, 205); //Drawing the labels from variables passed g.setFont(new Font(null, Font.BOLD, 13)); g.drawString(attributeName, 150 - 3*attributeName.length() ,240); Incre = 240 / items.length; // This is the variable that calculate how far each point should be. //Labelling different utilities weights = ddomain.getWeights(); for(int i = 0; i < items.length; i++){ if((weights[i] == 0.0) || (weights[i] == 1.0)){ g.setFont(new Font(null, Font.BOLD, 12)); } else{ g.setFont(new Font(null, Font.PLAIN, 12)); } g.drawString(items[i],(((Incre * i) + getSpacing(i) - 3 * (items[i].length()))),220); } //Drawing the Undo and Redo button g.setFont(new Font(null, Font.PLAIN, 12)); g.setColor(Color.RED); g.drawString("UNDO", 2, 255); g.drawString("REDO", 235, 255); }
7dce1bad-f965-4ffc-b3b4-2b649109dbd6
2
public void addFload(int n) { if (n < 4) addOpcode(34 + n); // fload_<n> else if (n < 0x100) { addOpcode(FLOAD); // fload add(n); } else { addOpcode(WIDE); addOpcode(FLOAD); addIndex(n); } }
8cb2a005-4c87-4fee-97b6-47c0811428fd
5
@Test public void canRetrieveCellFromCoordinates() { for (int x = 0, size = sudoku.getGridLength(); x < size; x++) for (int y = 0; y < size; y++) sudoku.setCellValue(x, y, x * 100 + y); for (int i = 0, sudokuSize = sudoku.getSudokuSize(); i < sudokuSize; i++) { for (int j = 0; j < sudokuSize; j++) { int[] cell = sudoku.getGridCell(i, j); assertThat(cell.length).isEqualTo(sudoku.getGridLength()); for (int k = 0; k < sudoku.getGridLength(); k++) assertThat(cell[k]).isEqualTo(sudoku.getCellValue(i * sudokuSize + k % sudokuSize, j * sudokuSize + (int) Math.floor(k / sudokuSize))); } } }
ee131ad1-f7ef-4d3f-b652-a9d47a13d9dc
2
public String getMatchingStartExpression(String text) { String matchedExpression = null; int expressionCount = getExpressionCount(); for (int i = 0; i < expressionCount; i++) { // Look for a matching Expression String currentExpression = getExpression(i); boolean isMatchingExpression = text.startsWith(currentExpression); if (isMatchingExpression) { matchedExpression = currentExpression; break; } } return matchedExpression; }
77780531-40d6-4e7f-993a-4af1b9b72256
7
private boolean sort() { // Obter pontuações String contents = toString(); if(contents == null) return false; String[] scoresArr = contents.split( Util.EOL ); // Array de pontuações int[] scoresVals = new int[ scoresArr.length ]; // Array com valores String[][] scoresNomes = new String[ scoresArr.length ][2]; // Array com valores e nomes // Preencher scoreVals e scoreNomes for(int i=0; i<scoresArr.length; i++) { String[] scoresTemp = scoresArr[i].trim().split("\t"); scoresVals[i] = Util.parseInt( scoresTemp[0] ); // Valor scoresNomes[i][0] = scoresTemp[0]; // Valor scoresNomes[i][1] = scoresTemp[1]; // Nome } // Ordenar scoreVals Arrays.sort( scoresVals ); // Preparar para escrita PrintStream out = FileAcess.toWrite(topScoresFile); if(out == null) return false; // Escrever no ficheiro for(int i=0; i<scoresArr.length; i++) { // Para só escrever até ao máximo de pontuações if( i>=maxTopScores ) break; int pos = scoresArr.length-1-i; // Posição do valor int valor = scoresVals[pos]; // Valor // Encontrar o nome String nome = new String(""); for(int j=0; j<scoresArr.length; j++) { if( scoresNomes[j][0].equals( ""+scoresVals[pos] ) ) { nome = scoresNomes[j][1]; // Nome break; } } out.println(valor+"\t"+nome); // Escrever } // Fechar o ficheiro out.close(); return true; }
c2bbcfe7-5e6f-4433-b058-c38e00045cd0
8
private void compareDistances(int edge) { System.out.println("edge: " + edge); d.msDelay(3000); if (edge == 1) { if (turnLeft()) { Sputnik.robotMap.setPosition(new Node(0, 4)); Sputnik.robotMap.setHeading(1); } else { Sputnik.robotMap.setPosition(new Node(3, 4)); Sputnik.robotMap.setHeading(3); } } else if (edge == 2) { if (turnLeft()) { Sputnik.robotMap.setPosition(new Node(3, 4)); Sputnik.robotMap.setHeading(0); } else { Sputnik.robotMap.setPosition(new Node(3, 0)); Sputnik.robotMap.setHeading(2); } } else if (edge == 3) { if (turnLeft()) { Sputnik.robotMap.setPosition(new Node(3, 0)); Sputnik.robotMap.setHeading(3); } else { Sputnik.robotMap.setPosition(new Node(1, 0)); Sputnik.robotMap.setHeading(1); } } else if (edge == 6) { if (turnLeft()) { Sputnik.robotMap.setPosition(new Node(0, 1)); Sputnik.robotMap.setHeading(2); } else { Sputnik.robotMap.setPosition(new Node(0, 4)); Sputnik.robotMap.setHeading(0); } } // System.out.println("\nPoint: " + Sputnik.opp.getPose().getX() + ", " // + Sputnik.opp.getPose().getY()); System.out.println("\nHead: " + heading); d.msDelay(3000); }
312ddd29-a089-4b4a-b7c5-731adcfcb0aa
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(ProductoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ProductoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ProductoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ProductoGUI.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 ProductoGUI().setVisible(true); } }); }
a07dac05-b528-40bf-840c-0ea76ff2e8c9
8
@Override public Validator<ResourceModel> getValidator() { return new Validator<ResourceModel>() { @Override public Set<ConstraintViolation> validate(ResourceModel item) { Set<ConstraintViolation> constraints = new HashSet<ConstraintViolation>(); Map<String, ResourceParameter> params = item.getParametersMap(); ResourceParameter param = params.get("exoBool"); String value = param.getValue(); if (value == null || value.equals("")) { ConstraintViolation constraint = new ConstraintViolation(); constraint.setMessage("The boolean exoBool must be set."); constraint.setLevel(ConstraintViolationLevel.CRITICAL); constraint.setValueName(param.getName()); constraints.add(constraint); } param = params.get("raCol"); value = param.getValue(); if (value == null || value.equals("")) { ConstraintViolation constraint = new ConstraintViolation(); constraint.setMessage("The attribute for RA must be set."); constraint.setLevel(ConstraintViolationLevel.CRITICAL); constraint.setValueName(param.getName()); constraints.add(constraint); } param = params.get("decCol"); value = param.getValue(); if (value == null || value.equals("")) { ConstraintViolation constraint = new ConstraintViolation(); constraint.setMessage("The attribute for DEC must be set."); constraint.setLevel(ConstraintViolationLevel.CRITICAL); constraint.setValueName(param.getName()); constraints.add(constraint); } param = params.get("corotIdCol"); value = param.getValue(); if (value == null || value.equals("")) { ConstraintViolation constraint = new ConstraintViolation(); constraint.setMessage("The attribute for CorotID must be set."); constraint.setLevel(ConstraintViolationLevel.CRITICAL); constraint.setValueName(param.getName()); constraints.add(constraint); } return constraints; } }; }
b4408432-0d7e-48c4-b61e-d5cbf83beca8
0
@Override public String getHdfs() { //return "hdfs://192.168.178.41:8020"; return "hdfs://192.168.43.180:9000"; }
c6198069-c600-47bb-86b5-bb0aeac92d3b
1
public void visit_ifgt(final Instruction inst) { if (longBranch) { final Label tmp = method.newLabel(); addOpcode(Opcode.opc_ifle); addBranch(tmp); addOpcode(Opcode.opc_goto_w); addLongBranch((Label) inst.operand()); addLabel(tmp); } else { addOpcode(Opcode.opc_ifgt); addBranch((Label) inst.operand()); } stackHeight--; }
04c957ef-85ce-4e97-912f-e7769a0dade0
9
@Override public Object getValueAt(int rowIndex, int columnIndex) { switch(columnIndex) { case 0: return competition.getRaces().get(rowIndex).getNumber(); case 1: return competition.getRaces().get(rowIndex).getJogger().getName(); case 2: return (competition.getStartTime() != null) ? new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(competition.getStartTime()) : "--/--/---- --:--:--"; case 3: return (competition.getRaces().get(rowIndex).getEndTime() != null) ? new SimpleDateFormat("HH:mm:ss").format(competition.getRaces().get(rowIndex).getEndTime()) : "--:--:--"; case 4: return (competition.getStartTime() == null || competition.getRaces().get(rowIndex).getEndTime() == null) ? "--:--:--" : new SimpleDateFormat("HH:mm:ss").format(new Date(competition.getRaces().get(rowIndex).getDuration().getTime() - (1000 * 60 * 60))); default: return "Inconnu"; } }
00347e5b-2850-4407-8a4c-67d7e2caf3c6
9
public int DBCount(String journal, String from, String to) { if(journal==null) return 0; journal = DB.injectionClean(journal); from = DB.injectionClean(from); to = DB.injectionClean(to); synchronized(journal.toUpperCase().intern()) { int ct=0; DBConnection D=null; try { D=DB.DBFetch(); final ResultSet R=D.query("SELECT CMFROM,CMTONM FROM CMJRNL WHERE CMJRNL='"+journal+"'"); if((from==null)&&(to==null)) ct=D.getRecordCount(R); else { while(R.next()) { if(((from==null)||(from.equalsIgnoreCase(DBConnections.getRes(R,"CMFROM")))) &&((to==null)||(to.equalsIgnoreCase(DBConnections.getRes(R,"CMTONM"))))) ct++; } } } catch(final Exception sqle) { Log.errOut("Journal",sqle); } finally { DB.DBDone(D); } return ct; } }
7cf43fc2-053b-4517-b86a-b045a7d42512
4
public static String read(final InputStream is) { final char[] buffer = new char[2048]; final StringBuilder out = new StringBuilder(); try { Reader in = null; try { in = new InputStreamReader(is, "UTF-8"); while (true) { int rsz = in.read(buffer, 0, buffer.length); if (rsz < 0) break; out.append(buffer, 0, rsz); } } finally { if (in != null) { in.close(); } } } catch (IOException ex) { return ""; } return out.toString(); }
21494fcf-18eb-4929-a2bd-33a88a8ed562
3
public boolean generate(World var1, Random var2, int var3, int var4, int var5) { for(int var6 = 0; var6 < 64; ++var6) { int var7 = var3 + var2.nextInt(8) - var2.nextInt(8); int var8 = var4 + var2.nextInt(4) - var2.nextInt(4); int var9 = var5 + var2.nextInt(8) - var2.nextInt(8); if(var1.isAirBlock(var7, var8, var9) && var1.getBlockId(var7, var8 - 1, var9) == Block.netherrack.blockID) { var1.setBlockWithNotify(var7, var8, var9, Block.fire.blockID); } } return true; }
87cb7ca8-e0ac-44a3-91c7-a0c6db9d21ee
2
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); for(int x = 0; x< IConfig.LARGEUR_CARTE;x++ ){ for(int y = 0; y< IConfig.HAUTEUR_CARTE;y++ ){ this.mapGraph[x][y].repaint(); } } }
1590bcbe-db2c-4157-a941-9fb7691ccbd0
4
public static int searchSign(Block block) { Set<BlockFace> signFaces = EnumSet.of(BlockFace.EAST, BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH); for (BlockFace face : signFaces) { Block relativeBlock = block.getRelative(face); if (relativeBlock.getType() == Material.WALL_SIGN) { Sign signstate = (Sign) relativeBlock.getState().getData(); if (signstate.getFacing() == face) { org.bukkit.block.Sign signBlock = (org.bukkit.block.Sign) relativeBlock.getState(); if (signBlock.getLine(0).equals("[Ninja Proof]")){ return Integer.parseInt(signBlock.getLine(2)); } } } } return 0; }
2f0afb77-9ec6-460e-bb12-afceb0e7ffce
6
public boolean controlarRegistros(){ try { r_con.Connection(); ResultSet rs=r_con.Consultar("select pc_fecha_cierre,pc_fecha_impresion_diario,pc_fecha_inicio from parametros_contables"); rs.next(); Fechas fechas=new Fechas(); String fechaCierre=fechas.parseFecha(rs.getDate(1)); String fechaDiario=fechas.parseFecha(rs.getDate(2)); String fechaInicio=fechas.parseFecha(rs.getDate(3)); rs=r_con.Consultar("select distinct(ba_nro_asiento) from borrador_asientos"); while(rs.next()){ int numCuenta=rs.getInt(1); ResultSet rsAux=r_con.Consultar("select * from borrador_asientos,plan_cuentas where ba_nro_cuenta=pc_nro_cuenta and ba_nro_asiento="+numCuenta); BigDecimal d=new BigDecimal(0); BigDecimal h=new BigDecimal(0); while(rsAux.next()){ d=sumarBigDecimal(d+"",rsAux.getFloat("ba_debe")+""); h=sumarBigDecimal(h+"",rsAux.getFloat("ba_haber")+""); if(!fecha.fechaEntreFechas(fecha.convertirBarras(rsAux.getDate("ba_fecha_contabilidad")+""), fechaDiario, fechaCierre)){ System.out.println("Fecha incorrecta "+fecha.convertirBarras(rsAux.getDate("ba_fecha_contabilidad")+" en "+rsAux.getInt("ba_nro_cuenta"))); r_con.cierraConexion(); return false; } if(!rsAux.getBoolean("pc_imputable")){ System.out.println("No es imputable "+rsAux.getInt("ba_nro_cuenta")+" "+numCuenta); r_con.cierraConexion(); return false; } } d=sumarBigDecimal(d+"","-"+h); if(d.floatValue()!=0){ System.out.println("No balancea "+d); r_con.cierraConexion(); return false; } } r_con.cierraConexion(); return true; } catch (SQLException ex) { r_con.cierraConexion(); Logger.getLogger(GUI_Registrar_Asientos.class.getName()).log(Level.SEVERE, null, ex); return false; } }
575c46cf-cd88-46ff-a6e9-399473a2ca15
2
private static void handleAcceptOffer(SerializableAcceptOffer pack) { // send to the seller for which the offer was accepted the confirmation Server.loggerServer.info("[Server] Received accept offer packet"); String seller; List<String> refusedSellers = new ArrayList<String>(); SelectionKey key = Server.registeredUsersChannels.get(pack.commandInfo .get(0)); if (null == key) { Server.loggerServer.error("[Server] Target user doesn't exist"); return; } seller = pack.commandInfo.get(0); // extract the list of sellers to be refused if (1 != pack.commandInfo.size()) { refusedSellers = pack.commandInfo.subList(1, pack.commandInfo.size()); } pack.commandInfo.clear(); pack.commandInfo.add(seller); Server.sendData(key, pack); // to all the other sellers send refuse offer packages sendRefuseOfferPackages(pack.userName, pack.serviceName, refusedSellers); }
08b6197f-7bfe-44c0-ade7-daf0fc93a0f5
0
public static Date getLastDayOfTheMonth(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), lastDay, 0, 0, 0); return calendar.getTime(); }
43f37be6-b676-4f7c-a301-812eb769820f
1
@SuppressWarnings("static-method") protected StdImage getIcon(Row row, Column column, boolean selected, boolean active) { Object data = row.getData(column); return data instanceof StdImage ? (StdImage) data : null; }
91b7f1a0-47df-496d-8462-5b6eedd17b90
3
public LegalMovesIterator(Board b) { switch (b.turn()) { case WHITE: _pieces = b._whiteSetMap.keySet().iterator(); break; case BLACK: _pieces = b._blackSetMap.keySet().iterator(); break; default: break; } directionCount = 0; _b = b; if(!_pieces.hasNext()){ _piece = -1; _move = null; } else { _piece = _pieces.next(); fill(); } }
d200df58-473c-4125-b7a9-d28dce9c86bb
3
@Test public void testFullTextSearch_on_a_field() { ReadResponse resp = factual.fetch(TABLE, new Query().field("name").search("Fried Chicken")); for (String name : resp.mapStrings("name")) { assertTrue(name.toLowerCase().contains("frie") || name.toLowerCase().contains("fry") || name.toLowerCase().contains("chicken")); } }
aaef8b14-a079-4463-a51b-f8ae226b62ab
5
private void save(File file) { BufferedWriter writer = null; try { try { file.getParentFile().mkdir(); file.createNewFile(); writer = new BufferedWriter(new FileWriter(file)); for(int row = 1; row < countRows + 1; row++) { StringBuilder line = new StringBuilder(); for(int col = 0; col < cols.length; col++) { String key = cols[col] + String.valueOf(row); if(table.get(key) == null){ break; } line.append(table.get(key).getResultValue()); line.append(CELL_SEPARATOR); } line.append("\n"); writer.write(line.toString()); } } finally { if(writer != null){ writer.close(); } } } catch (IOException e){ e.printStackTrace(); } }
75888a66-6689-407e-8058-78d3d97348cb
3
public static Config unserialize(){ Config config = null; try { File file = new File(CONFIG_FILE_NAME); if(!file.exists()) return null; FileInputStream fileIn = new FileInputStream(CONFIG_FILE_NAME); ObjectInputStream objectIn = new ObjectInputStream(fileIn); config = (Config) objectIn.readObject(); objectIn.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return config; }
db088144-3b31-425c-99bb-a331851f254f
1
@Override public void actionPerformed(ActionEvent e) { // if we're not in a totally-maximized state // [which would make this all pointless] ... if (!Outliner.desktop.isMaximized()) { // grabaholda the topmost doc OutlinerDocument doc = (OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched(); // see how tall we can get Dimension curAvailSpace = Outliner.desktop.getCurrentAvailableSpace(); double maxHeight = curAvailSpace.getHeight(); // get the doc's current location Point pLocation = doc.getLocation(); // set its top point to the top of the content area pLocation.setLocation(pLocation.getX(), 0); // get the doc's current size Dimension dSize = new Dimension() ; dSize.setSize((int)doc.getSize().getWidth(), (int)maxHeight); // set the doc's new location and size doc.setLocation(pLocation); doc.setSize(dSize); // let the vertical scroll bar adjust for our new size Outliner.jsp.getVerticalScrollBar().revalidate(); } }
cd3ba2b2-afbf-4e38-b3fe-9b8b7f301ae8
0
@Test public void test_something() throws IOException, InterruptedException { final Map<String, String> server_script = new HashMap<String, String>(); server_script.put("foo", "bar"); final int port =9247; StringTrafficker st = new StringTrafficker(port, port, server_script, server_script); st.run(); }
955fa2d9-908f-4ad7-ad0a-7dfa4de6a3ed
6
public void updateUser() { if (id != null) { PreparedStatement st = null; String q = "UPDATE users SET email = ?, first_Name = ?, last_name = ? "; if (!StringUtil.isBlank(password)) { q += ",password = MD5(?)"; } q += "WHERE id = ?"; try { conn = dbconn.getConnection(); conn.setAutoCommit(false); st = conn.prepareStatement(q); st.setString(1, this.email); st.setString(2, this.firstName); st.setString(3, this.lastName); if (!StringUtil.isBlank(password)) { st.setString(4, this.password); st.setInt(5, this.id); } else { st.setInt(4, this.id); } st.executeUpdate(); deleteUserRoles(email, conn); insertUserRoles(email, role, conn); conn.commit(); } catch (SQLException e) { e.printStackTrace(); try { conn.rollback(); } catch (SQLException o) { o.printStackTrace(); } } finally { try { conn.close(); st.close(); } catch (SQLException e) { System.out.println("Unable to close connection"); } } } else { System.out.println("Unable to update user because email is null"); } }
a7cb4403-8c6b-4859-8326-5911f4f2e206
5
public static boolean isInteger(String line){ for(int i = 0; i < line.length(); i++){ char element = line.charAt(i); if(isNumber(element) == false){ if(i == 0 && element == '-' && line.length() > 1){ continue; } return false; } } return true; }
5d8e6f2e-c8cb-4c1c-894c-de0b194659cd
7
public void listInfo(Intersection closest, JTextArea textOutput) { Set<Integer> roadIds = new HashSet(); double lat = closest.getLatitude(); double lon = closest.getLongitude(); ArrayList<String> roadNames = new ArrayList<String>(); for (Segment seg : segments) { if ((seg.getNodeID1().getID() == closest.getID()) || (seg.getNodeID2().getID() == closest.getID())) { roadIds.add(seg.getRoadID()); } } for (Integer i : roadIds) { for (Road road : roads) { if (i == road.getRoadID()) { roadNames.add(road.getLabel() + " " + road.getCity()); } } } textOutput.setText(""); textOutput.append("Info for intersection " + '\n'); textOutput.append("Latitude: " + lat + " Longitude: " + lon + '\n'); textOutput .append("Names of roads connecting to this intersection:" + '\n'); for (String s : roadNames) { textOutput.append(s + '\n'); } }
2c6b2aa6-7d97-4122-a7d2-d8c4b2ce7cb4
0
public int getK() { return k; }
5bfa0022-e238-414f-8360-db46a9f0c11c
9
@Override public boolean execute(MOB mob, List<String> commands, int metaFlags) throws java.io.IOException { if(!CMProps.getBoolVar(CMProps.Bool.EMAILFORWARDING)) { mob.tell(L("This feature is not activated.")); return false; } String parm = (commands.size() > 1) ? CMParms.combine(commands,1) : ""; if((mob.isAttributeSet(MOB.Attrib.AUTOFORWARD) && (parm.length()==0))||(parm.equalsIgnoreCase("ON"))) { mob.setAttribute(MOB.Attrib.AUTOFORWARD,false); mob.tell(L("Autoemail forwarding has been turned on.")); } else if((!mob.isAttributeSet(MOB.Attrib.AUTOFORWARD) && (parm.length()==0))||(parm.equalsIgnoreCase("OFF"))) { mob.setAttribute(MOB.Attrib.AUTOFORWARD,true); mob.tell(L("Autoemail forwarding has been turned off.")); } else if(parm.length() > 0) { mob.tell(L("Illegal @x1 argument: '@x2'. Try ON or OFF, or nothing to toggle.",getAccessWords()[0],parm)); } return false; }
dcc70c27-7a3d-409a-b6d3-984b33f7f2aa
0
public void setMed_depotLegal(String med_depotLegal) { this.med_depotLegal = med_depotLegal; }
7aee55bf-6460-4258-a3f2-e1fdc15bd8aa
9
public PlacesList<Place> placesForUser(int placeType, String woeId, String placeId, String threshold, Date minUploadDate, Date maxUploadDate, Date minTakenDate, Date maxTakenDate) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); PlacesList<Place> placesList = new PlacesList<Place>(); parameters.put("method", METHOD_PLACES_FOR_USER); parameters.put(Flickr.API_KEY, apiKey); parameters.put("place_type", intPlaceTypeToString(placeType)); if (placeId != null) { parameters.put("place_id", placeId); } if (woeId != null) { parameters.put("woe_id", woeId); } if (threshold != null) { parameters.put("threshold", threshold); } if (minUploadDate != null) { parameters.put("min_upload_date", Long.toString(minUploadDate.getTime() / 1000L)); } if (maxUploadDate != null) { parameters.put("max_upload_date", Long.toString(maxUploadDate.getTime() / 1000L)); } if (minTakenDate != null) { parameters.put("min_taken_date", ((DateFormat) SearchParameters.MYSQL_DATE_FORMATS.get()).format(minTakenDate)); } if (maxTakenDate != null) { parameters.put("max_taken_date", ((DateFormat) SearchParameters.MYSQL_DATE_FORMATS.get()).format(maxTakenDate)); } Response response = transportAPI.get(transportAPI.getPath(), parameters, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element placesElement = response.getPayload(); NodeList placesNodes = placesElement.getElementsByTagName("place"); placesList.setPage("1"); placesList.setPages("1"); placesList.setPerPage("" + placesNodes.getLength()); placesList.setTotal("" + placesNodes.getLength()); for (int i = 0; i < placesNodes.getLength(); i++) { Element placeElement = (Element) placesNodes.item(i); placesList.add(parsePlace(placeElement)); } return placesList; }
398ae2df-7967-49ce-a1b3-e7230fb7bcb5
6
public Object clone() { Automaton a; // Try to create a new object. try { // I am a bad person for writing this hack. // if (this instanceof TuringMachine) // a = new TuringMachine(((TuringMachine) this).tapes()); // else a = (Automaton) getClass().newInstance(); } catch (Throwable e) { // Well golly, we're sure screwed now! System.err.println("Warning: clone of automaton failed!"); return null; } a.setEnvironmentFrame(this.getEnvironmentFrame()); // Copy over the states. HashMap map = new HashMap(); // Old states to new states. Iterator it = states.iterator(); while (it.hasNext()) { State state = (State) it.next(); State nstate = new State(state.getID(), new Point(state.getPoint()), a); // copyRelevantDataForBlocks(nstate, state, a); nstate.setLabel(state.getLabel()); nstate.setName(state.getName()); map.put(state, nstate); a.addState(nstate); } // Set special states. it = finalStates.iterator(); while (it.hasNext()) { State state = (State) it.next(); a.addFinalState((State) map.get(state)); } a.setInitialState((State) map.get(getInitialState())); // Copy over the transitions. it = states.iterator(); while (it.hasNext()) { State state = (State) it.next(); Transition[] ts = getTransitionsFromState(state); State from = (State) map.get(state); for (int i = 0; i < ts.length; i++) { State to = (State) map.get(ts[i].getToState()); Transition toBeAdded = (Transition) ts[i].clone(); //call clone instead of copy so that the gui stuff can get appropriately updated toBeAdded.setFromState(from); toBeAdded.setToState(to); // a.addTransition(ts[i].copy(from, to)); a.addTransition(toBeAdded); } } for(int k = 0; k < this.getNotes().size(); k++){ Note curNote = (Note)this.getNotes().get(k); a.addNote(new Note(curNote.getAutoPoint(), curNote.getText())); ((Note)a.getNotes().get(k)).setView(curNote.getView()); //for undo, we must initialize the clone to our view } return a; }
dde77097-eac1-4224-928c-e6b858f25c92
5
public int getHandValue() { int value = 0; for (int i = 0; i < this.hand.size(); i++) { value += this.hand.get(i).getNumValue(); } if(value > 21 && hasAce) { for(int i = 0; i < aceIndex; i++) { value = value - 10; if(value <= 21) break; } } return value; }
16e02010-effa-4e3c-ab7c-5e7a403ed918
8
public static int tipoInterseccion(int u1, int v1, int u2, int v2, int x1, int y1, int x2, int y2) { int res; int a1,a2,b1,b2,c1,c2,dd; double xx,yy; res = -1; // cuando uno de los segmentos es un punto // res := 0 cuando son paralelas pero no colineales (no se intersectan) // res := 1 CUANDO SE INTERSECTAN EN UN PUNTO // res := 2 cuando se intersectan en mas de un punto (sii colineales) // res := 3 cuando cuando son paralelas y colineales (no se intersectan) // res := 4 cuando cuando NOOOOO son paralelas PERO NOOOOOOOOOOOOO SE INTERSECTAN if((! esSegmentoPunto(u1,v1,u2,v2))&&(! esSegmentoPunto(x1,y1,x2,y2))) { //ecuacion general de la recta................................... // ax + by = c //............................................................... // coeficientes de la recta111111111111 a1 = v1-v2; b1 = u2-u1; c1 = (u1*a1)+(v1*b1); // coeficientes de la recta22222222222 a2 = y1-y2; b2 = x2-x1; c2 = (x1*a2)+(y1*b2); // discriminante........................... dd = (a1*b2)-(b1*a2); //analizamos paralelismo......................... if(dd==0) // si son paralelas................. { if(sonIguales(((b1*c2)+0.0),((c1*b2)+0.0))) // si las rectas son colineales......... { res = getTipoInterseccionSegmentColineales(u1,v1,u2,v2,x1,y1,x2,y2); } else res =0; // son paralelas pero no colineales (no se intersectan) } else { // si no son paralelas (sii se intersectan) // encontramos el punto de interseccion (xx,yy) xx = (((c1+0.0)*(b2+0.0))-((b1+0.0)*(c2+0.0)))/(dd + 0.0); yy = (((a1+0.0)*(c2+0.0))-((c1+0.0)*(a2+0.0)))/(dd + 0.0); // el punto tiene que estar dentro de los dominios en 'X' y en 'Y' // en los dos segmentos if((enDom(xx,(u1+0.0),(u2+0.0)))&&(enDom(xx,(x1+0.0),(x2+0.0)))&&(enDom(yy,(v1+0.0),(v2+0.0)))&&(enDom(yy,(y1+0.0),(y2+0.0)))) // si esta en el dominio res = 1; else res = 4; } } return res; }
99312690-239f-49cf-b637-25b0c5721db1
2
public TestDaoGenerator( Table table ) { super( table ); this.daoName = "Test" + table.getDomName() + "Dao"; filePath = "src/test/java/" + packageToPath() + "/dao/" + daoName + ".java"; for( Column col : table.getColumns() ){ if ( col.isKey() ){ param += toJavaCase( table.getDomName() ) + ".get" + toCamelCase(col.getFldName()) + "(), "; } } param = param.substring( 0, param.length() - 2 ); }
78bb0d15-82fe-4a44-8b3a-2a27739ec6bb
1
private void chargerListeLabo() throws DaoException { List<Labo> desLabos = daoLabo.getAll(); getVue().getModeleJComboBoxLabo().removeAllElements(); for (Labo unLabo : desLabos) { getVue().getModeleJComboBoxLabo().addElement(unLabo); } }
0816f247-b1f5-42a4-bfb6-68bfd12c9d8f
7
public EvolvingGraph readEvolvingGraph () throws FileNotFoundException { Schedule sched; String u, v; int source, dest, cost, numsched; int aux = 0; File f = new File (filename); EvolvingGraph graph = new EvolvingGraph(0); graph.setMaxTime(0); Scanner sc = new Scanner (f); sc.nextInt(); int edges = sc.nextInt(); graph = new EvolvingGraph(); while(edges > 0) { u = sc.next(); v = sc.next(); if (!graph.hasNode(u)) graph.addNode(u); source = graph.getNode(u).getId(); if (!graph.hasNode(v)) graph.addNode(v); dest = graph.getNode(v).getId(); cost = sc.nextInt(); numsched = sc.nextInt(); sched = new Schedule(); while(numsched > 0) { if (sc.hasNext("\\[(\\d*),(\\d*)\\[")) { MatchResult m = sc.match(); int begin = Integer.parseInt(m.group(1)); int end = Integer.parseInt(m.group(2)); sched.add(begin, end); sc.next(); numsched--; } else if (sc.hasNextInt()) { aux = sc.nextInt(); sched.add(aux, aux+1); numsched--; } } if (aux > graph.getMaxTime()) graph.setMaxTime(aux); graph.createEdge(source, dest, sched, cost); edges--; } return graph; }
fdf6cf22-7824-47cb-b1f7-d4a58726942c
3
private void buildQueue(LinkedList<BTPosition<T>> ll, ArrayList<BTPosition<T>> al) { BTPosition<T> c; while (!ll.isEmpty()) { c = ll.poll(); if (c.getLeft() != null) ll.add(c.getLeft()); if (c.getRight() != null) ll.add(c.getRight()); al.add(c); } }
7ccd060a-af2d-4377-bf4a-e230160c00cd
1
private Comparator<Row> comparatorFromOrderCriteria(OrderCriteria criteria){ Integer columnIndex = header.findByCellValue(criteria.getColumnName()).getCellIndex(); Comparator<Row> natural = (e1, e2) -> e1.getCellByIndex(columnIndex).getCellValue(). compareTo(e2.getCellByIndex(columnIndex).getCellValue()); Comparator<Row> numeric = (e1, e2) -> Integer.valueOf(e1.getCellByIndex(columnIndex).getCellValue()). compareTo(Integer.valueOf(e2.getCellByIndex(columnIndex).getCellValue())); return criteria.getStrategy() == OrderStrategy.ASC ? natural : numeric; }
31f51313-ec29-4c60-b870-9240d408354e
6
private VillageDoorInfo getVillageDoorAt(int par1, int par2, int par3) { Iterator var4 = this.newDoors.iterator(); VillageDoorInfo var5; do { if (!var4.hasNext()) { var4 = this.villageList.iterator(); VillageDoorInfo var6; do { if (!var4.hasNext()) { return null; } Village var7 = (Village)var4.next(); var6 = var7.getVillageDoorAt(par1, par2, par3); } while (var6 == null); return var6; } var5 = (VillageDoorInfo)var4.next(); } while (var5.posX != par1 || var5.posZ != par3 || Math.abs(var5.posY - par2) > 1); return var5; }
01f9664d-4055-47a9-9844-30092bc3a0d5
2
public DiscoveredClient getClientForUsername(String username) { synchronized(threadLock) { Iterator<DiscoveredClient> it = getClients().iterator(); while ( it.hasNext() ) { DiscoveredClient thisClient = it.next(); if ( thisClient.getUsername().equals(username) ) return thisClient; } } return null; }
dd85cd37-3dca-4b29-8f5e-712fd171c501
7
public static int computeFieldSize(final FieldDescriptorLite<?> descriptor, final Object value) { WireFormat.FieldType type = descriptor.getLiteType(); int number = descriptor.getNumber(); if (descriptor.isRepeated()) { if (descriptor.isPacked()) { int dataSize = 0; for (final Object element : (List<?>)value) { dataSize += computeElementSizeNoTag(type, element); } return dataSize + CodedOutputStream.computeTagSize(number) + CodedOutputStream.computeRawVarint32Size(dataSize); } else { int size = 0; for (final Object element : (List<?>)value) { size += computeElementSize(type, number, element); } return size; } } else { return computeElementSize(type, number, value); } }
8c15355e-f7e2-4623-8b36-31fbe7f1b979
6
public void shoot(){ if(shoot && BulletTimer == 0){ Bullet b = new Bullet(); // Creates a new bullet; b.setBullet(1, 6 + xShip + ship.getWidth() / 8, window.getHeight() - ship.getHeight() / 2); // Sets bullet's Parameters bullets.add(b); // adds to array BulletTimer = attackSpeed; // Time between bullets is 32 * 8 ( thread.sleep) miliseconds = 256ms }else if(BulletTimer >= 1){ BulletTimer--; } for (Bullet b : bullets ){ if (b.isOutsideBounds(b) && b.collides){ bullets.remove(b); } else { b.pointY += b.bulletSpeed * b.direction; } } }
80f0a63f-8ffa-486e-a538-a32329247a1a
1
public static int[] toIntArray(Integer[] data) { int[] result = new int[data.length]; for (int i = 0; i < data.length; i++) { result[i] = data[i].intValue(); } return result; }
2b14707a-ac58-4ad0-917e-f4637cc022f4
2
public void sendEndActions(){ JSONObject o = new JSONObject(); try { o.put("message", "endactions"); sendMessage(o); } catch (JSONException e){} catch (IOException e){ Debug.error("Error writing to graphics: " + e.getMessage()); } }
cf535ae1-cc50-4ce1-850f-d991926aeb6e
3
private void paintScreen() { Graphics g; try { g = this.getGraphics(); if ((g != null) && (dbImage != null)) { g.drawImage(dbImage, 0, 0, null); } // Sync the display on some systems. // (on Linux, this fixes event queue problems) Toolkit.getDefaultToolkit().sync(); g.dispose(); } catch (Exception e) { EIError.debugMsg("Graphics context error: " + e); } }
a9189ce4-2b0e-4f1f-a03a-35f1b3ed60ef
5
private int berekenSchotRichting(double hoekRad, double kracht, double windSnelheid, double zwaartekracht, Orientatie tankRichting){ //testen in welke richting het schot gaat, returnt 0 wanneer rechtop, -1 wanneer links en 1 wanneer rechts if((int)Math.round(Math.pow((kracht * Math.cos(hoekRad) + windSnelheid), 2)) == 0){ //berekent of het schot rechtop gaat return 0; //schot gaat naar boven } else{ // bereken welke richting het schot gaat (gaat er van uit dat je niet naar beneden kan schieten!) double[] richtingTest = new double[3]; for(int i = 0; i <= 2; i++){ richtingTest[i] = berekenY(i-1, hoekRad, kracht, windSnelheid, zwaartekracht); //berekent y van baan op x-positie -1, 0 en 1 } if(richtingTest[0] > richtingTest[1]){ //als y op -1 groter is dan op 1 return -1; //schot gaat naar links } else if (richtingTest[2] > richtingTest[1]){ //als y op 1 groter is dan op -1 return 1; //schot gaat naar rechts } else if(tankRichting == Orientatie.LINKS){ return -1; } else{ return 1; } } }
cb143ed6-f9ef-410f-8865-e7edf945045f
6
@Override public List<Cell> createCells(Line rawLine) { String line = rawLine.getRawLine(); int lengthOfLine = rawLine.numberOfCharakters(); int charaktersRead = 0; while (true) { char workingCharakter = line.charAt(charaktersRead); Symbol symbol = new Symbol(workingCharakter); parserState.setCurrentSymbol(symbol); if (parserState.isSymbolQuoted()) { parserState.setState(State.IN_QUOTES); parserState.incrementQuotes(); int indexInQuotes = charaktersRead + 1; while (parserState.inQuotes()) { StringBuilder builder = new StringBuilder(); char workingCharakterInQuotes = line.charAt(indexInQuotes); Symbol symbolInQuotes = new Symbol(workingCharakterInQuotes); parserState.setCurrentSymbol(symbolInQuotes); if (parserState.isSymbolQuoted()) { parserState.incrementQuotes(); builder.append(workingCharakterInQuotes); } if (!parserState.isSymbolQuoted()) { builder.append(workingCharakterInQuotes); } if (parserState.isAllQuotesEncountered()) { parserState.setState(State.OUTSIDE_QUOTES); indexInQuotes = 0; } indexInQuotes++; } } charaktersRead++; } }
ba811aaa-bf66-4c77-b11d-7cc50049acb8
4
private void calculateNextGeneration() { //// Prepare selection algorithms crossSelector.updateSpeciments(population); transferSelector.updateSpeciments(population); mutationSelector.updateSpeciments(population); //// Reproduce species int speciesToReproduce = (int)(REPRODUCTION_RATE * POPULATION_SIZE); speciesToReproduce &= 0xFFFFFFFE; // Make even number int couplesCount = speciesToReproduce / 2; while (couplesCount > 0) { List<T> parents = new ArrayList<>(2); parents.add(crossSelector.selectSpeciment()); parents.add(crossSelector.selectSpeciment()); List<T> children = crossOperator.cross(parents); for (T child : children) { fitnessEvaluator.evaluateFitness(child); offspring.add(child); } --couplesCount; } //// Transfer species to offspring unchanged int speciesToTransfer = POPULATION_SIZE - speciesToReproduce; while (speciesToTransfer > 0) { T selectedSpeciment = transferSelector.selectSpeciment(); offspring.add(selectedSpeciment); --speciesToTransfer; } //// Mutate offspring int speciesToMutate = (int)(POPULATION_SIZE * MUTATION_RATE); while (speciesToMutate > 0) { T specimentToMutate = mutationSelector.selectSpeciment(); mutationOperator.mutate(specimentToMutate); fitnessEvaluator.evaluateFitness(specimentToMutate); --speciesToMutate; } //// Move to next iteration population.clear(); population = offspring; offspring.clear(); }
3a4712e7-73ad-42f7-bc16-e2fe4cefebfe
7
public static double[][] readTransitionProbHDFS(String directory, int number_reducers, FileSystem fs) { int number_of_lines = findNumberOfLinesHDFS(directory, "transition-r-", number_reducers, fs); double[][] transition_prob = new double[number_of_lines][number_of_lines]; try { for(int i = 0; i<number_reducers; i++){ String file = directory+"transition-r-"+String.format("%05d", i); if(fs.exists(new Path(file))){ BufferedReader bReader = new BufferedReader(new InputStreamReader(fs.open(new Path(file)))); while (bReader.ready()) { String line = bReader.readLine(); line = line.trim(); if (!line.isEmpty()) { String[] split_line = line.split("\\t"); if(split_line.length == number_of_lines+1){ for(int j = 1; j < split_line.length; j++){ transition_prob[Integer.parseInt(split_line[0])][j-1] = Double.parseDouble(split_line[j]); } } else { System.out.println("row and column number are not identical, a square matrix is required though!"); } } } bReader.close(); } } } catch (IOException ioe) { ioe.printStackTrace(); } return transition_prob; }
9c24493f-3136-41ea-8b4c-8208968ae8c6
2
public void removePush() { if (condStack != null) cond = condStack.mergeIntoExpression(cond); thenBlock.removePush(); if (elseBlock != null) elseBlock.removePush(); }
d95fe38c-eb48-4075-acca-6df09546c555
6
public Imagen getImagenMR(int windowCenter, int windowWidth) { Imagen imgObj = new Imagen(); int alto = rasterDicom.getHeight(); int ancho = rasterDicom.getWidth(); int minX = rasterDicom.getMinX(); int minY = rasterDicom.getMinY(); imgObj.setFormato("P2"); imgObj.setM(ancho); imgObj.setN(alto); //imgObj.setNivelIntensidad((int) Math.pow(2, getNumBits()) - 1); imgObj.setNivelIntensidad(255); imgObj.setArchivoImagen(archivoDcm); short matrizGris[][] = new short[alto][ancho]; if(windowCenter == 0){ windowCenter = getWindowCenter(); } if(windowWidth == 0){ windowWidth = getWindowWidth(); } short y; for (int i = minY; i < alto; i++) { for (int j = minX; j < ancho; j++) { short x = (short) rasterDicom.getSample(j, i, 0); //System.out.println(""+x); if(x <= windowCenter - 0.5 - (windowWidth - 1) / 2 ){ y = Ymin; } else if(x > windowCenter - 0.5 + (windowWidth - 1) / 2 ) { y = Ymax; } else { y = (short) ( ( (x - (windowCenter - 0.5) ) / (windowWidth - 1) + 0.5 ) * ( Ymax - Ymin ) + Ymin ); } matrizGris[i][j] = y; } } imgObj.setMatrizGris(matrizGris); return imgObj; }
e0bd5474-2e52-4691-82ee-bca63316b97c
0
private void setColorBenchmarks() { findExtremes(); this.tempRangesHigh = new long[4]; tempRangesHigh[1] = (HIGH_TEMP + MAX_TEMP) >>> 1; // mid-point tempRangesHigh[0] = (HIGH_TEMP + tempRangesHigh[1]) >>> 1; // lower quartile tempRangesHigh[2] = (MAX_TEMP + tempRangesHigh[1]) >>> 1; // upper quartile tempRangesHigh[3] = MAX_TEMP; // roof this.tempRangesLow = new long[4]; tempRangesLow[1] = (LOW_TEMP + MIN_TEMP) >>> 1; // mid-point tempRangesLow[0] = (MIN_TEMP + tempRangesLow[1]) >>> 1; // lower quartile tempRangesLow[2] = (LOW_TEMP + tempRangesLow[1]) >>> 1; // upper quartile tempRangesLow[3] = LOW_TEMP; // roof this.tempRangesMid = new long[4]; tempRangesMid[1] = (LOW_TEMP + HIGH_TEMP) >>> 1; // mid-point tempRangesMid[0] = (LOW_TEMP + tempRangesMid[1]) >>> 1; // lower quartile tempRangesMid[2] = (HIGH_TEMP + tempRangesMid[1]) >>> 1; // upper quartile tempRangesMid[3] = HIGH_TEMP; // roof this.colorRangesHigh = new int[4]; colorRangesHigh[0] = Color.decode("#FF4400").getRGB(); colorRangesHigh[1] = Color.decode("#FF7700").getRGB(); colorRangesHigh[2] = Color.decode("#FF0000").getRGB(); colorRangesHigh[3] = Color.decode("#FF00FF").getRGB(); this.colorRangesLow = new int[4]; colorRangesLow[0] = Color.decode("#0000FF").getRGB(); colorRangesLow[1] = Color.decode("#0044FF").getRGB(); colorRangesLow[2] = Color.decode("#0077FF").getRGB(); colorRangesLow[3] = Color.decode("#004477").getRGB(); this.colorRangesMid = new int[4]; colorRangesMid[0] = Color.decode("#00FFFF").getRGB(); colorRangesMid[1] = Color.decode("#00FF44").getRGB(); colorRangesMid[2] = Color.decode("#00FF00").getRGB(); colorRangesMid[3] = Color.decode("#FFFF00").getRGB(); }
d2f6de45-4fb8-4987-827b-23a91d52d763
3
public static void initializeCoefficients() { N = 0; postProb = 0.0; // Create window to store old samples if (Settings.agingFlag == Settings.windowAge) { oldSamples = new double[Settings.windowSize][2]; } // Set all scaling coefficients to 0 Transform.scalingCoefficients = new double[Transform.scalingTranslates.size()][Transform.scalingTranslates.size()]; if (Settings.waveletFlag) { Transform.psiPsiCoefficients = new ArrayList<double[][]> (); Transform.psiPhiCoefficients = new ArrayList<double[][]> (); Transform.phiPsiCoefficients = new ArrayList<double[][]> (); // Loop through resolutions for (double j = Settings.startLevel; j <= Settings.stopLevel; j++){ int waveInd = (int) Math.floor(j - Settings.startLevel); int jSize = Transform.waveletTranslates.get(waveInd).size(); // Set all wavelet at this resolution coefficients to 0 double[][] thisPsiPsi = new double[jSize][jSize]; double[][] thisPsiPhi = new double[jSize][jSize]; double[][] thisPhiPsi = new double[jSize][jSize]; Transform.psiPsiCoefficients.add(thisPsiPsi); Transform.psiPhiCoefficients.add(thisPsiPhi); Transform.phiPsiCoefficients.add(thisPhiPsi); } } } //end initializeCoefficients
6493a2e2-d336-4415-8b37-9fcebd606451
3
@Override public void run() { while (true) { String message = produce(); try { if (message.contains("Await receipt")) { System.out.println("transfer done"); queue.transfer(message); // blocks if there is no matching take() pending } else { System.out.println("put done"); queue.put(message); // returns immediately if the queue is not full } } catch (InterruptedException e) { e.printStackTrace(); } } }
e74a5b7f-ff18-49ed-8497-f2bff398370b
9
public IPPacket processPacket(IPPacket packet, int direction) { long now = 0; try {now = System.nanoTime();} catch (Exception e) {} if (direction == DIRECTION_IN) { int offset = packet.getIPHeaderByteLength(); int len = packet.getIPPacketLength() - offset; byte[] esp = packet.getDataUnprotected(); int spi = (int)(((esp[offset] & 0xFF) << 24) | ((esp[offset + 1] & 0xFF) << 16) | ((esp[offset + 2] & 0xFF) << 8) | ((esp[offset + 3] & 0xFF))); BeetEntry entry = __inbound.get(String.valueOf(spi)); if (entry == null) return null; byte[] iv = new byte[entry.getCipher().getIVLength()]; int elen = len - ICV_LENGTH - iv.length - ESP_HEADER_LEN; int alen = ICV_LENGTH; System.arraycopy(esp, offset + ESP_HEADER_LEN, iv, 0, iv.length); byte[] cipher = new byte[elen]; byte[] hash = new byte[ICV_LENGTH]; byte [] hash2 = new byte[ICV_LENGTH]; byte[] ivcipher = new byte[iv.length + elen + ESP_HEADER_LEN]; System.arraycopy(esp, offset + ESP_HEADER_LEN + iv.length, cipher, 0, elen); System.arraycopy(esp, offset + ESP_HEADER_LEN + iv.length + cipher.length, hash, 0, alen); System.arraycopy(esp, offset, ivcipher, 0, ivcipher.length); System.arraycopy(entry.getDigest().digest(ivcipher), 0, hash2, 0, ICV_LENGTH); if (!Arrays.areEqual(hash, hash2)) { System.out.println("auth err: ICV does not match"); return null; } byte[] plain = entry.getCipher().decrypt(cipher, iv); int padlen = (plain[plain.length - 2] & 0xFF); int proto = (plain[plain.length - 1] & 0xFF); IPPacket ipv6 = new IPPacket(IPPacket.IP_VERSION6_LEN + (elen - padlen - ESP_TRAILER_LEN)); ipv6.setIPVersion(IPPacket.IP_VERSION6); ipv6.setNextHeader(proto); ipv6.setIPPacketLength((elen - padlen - ESP_TRAILER_LEN)); ipv6.setDestination(entry.getSrc().getAddress()); ipv6.setSource(entry.getDst().getAddress()); byte[] ipv6raw = ipv6.getDataUnprotected(); System.arraycopy(plain, 0, ipv6raw, IPPacket.IP_VERSION6_LEN, (elen - padlen - ESP_TRAILER_LEN)); return ipv6; } else if (direction == DIRECTION_OUT) { byte[] dst6 = new byte[IPPacket.LENGTH_DESTINATION_ADDRESS6]; packet.getDestination(dst6); BeetEntry entry = __outbound.get(Helpers.toHexString(dst6, "")); int elen = packet.getIPPacketLength(); int padlen = 0; int eivlength = entry.getCipher().getIVLength(); byte[] raw = packet.getDataUnprotected(); if (eivlength > 0) { padlen = eivlength - ((elen + 2) % eivlength); } else { padlen = 4 - ((elen + 2) % 4); } byte[] esp = new byte[ESP_HEADER_LEN + elen + eivlength + padlen + ESP_TRAILER_LEN]; esp[0] = (byte) ((entry.getSPI() >> 24) & 0xFF); esp[1] = (byte) ((entry.getSPI() >> 16) & 0xFF); esp[2] = (byte) ((entry.getSPI() >> 8) & 0xFF); esp[3] = (byte) (entry.getSPI() & 0xFF); esp[4] = (byte) ((entry.getSequence() >> 24) & 0xFF); esp[5] = (byte) ((entry.getSequence() >> 16) & 0xFF); esp[6] = (byte) ((entry.getSequence() >> 8) & 0xFF); esp[7] = (byte) (entry.getSequence() & 0xFF); entry.setSequence(entry.getSequence() + 1); byte[] edat = new byte[elen + padlen + ESP_TRAILER_LEN]; System .arraycopy(raw, packet.getIPHeaderByteLength(), edat, 0, elen); edat[elen + padlen] = (byte) (padlen & 0xFF); edat[elen + padlen + 1] = (byte) (packet.getNextHeader() & 0xFF); byte[] enc = entry.getCipher().encrypt(edat); if (eivlength > 0) System.arraycopy(entry.getCipher().getIV(), 0, esp, ESP_HEADER_LEN, eivlength); System.arraycopy(enc, 0, esp, ESP_HEADER_LEN + eivlength, enc.length); byte[] adat = entry.getDigest().digest(esp); IPPacket espPacket = new IPPacket( (entry.getDst() instanceof Inet4Address ? DEFAULT_IPV4_HEADER_LEN : DEFAULT_IPV6_HEADER_LEN) + esp.length + ICV_LENGTH); if (entry.getDst() instanceof Inet4Address) { espPacket.setSource(entry.getSrc().getAddress()); espPacket.setDestination(entry.getDst().getAddress()); espPacket.setIPVersion(IPPacket.IP_VERSION4); espPacket.setIPHeaderLength(DEFAULT_IPV4_HEADER_LEN / 4); espPacket.setTTL(DEFAULT_TTL); espPacket.setProtocol(ESP_PROTO); } else { // TODO IPv6 handler } System.arraycopy(esp, 0, espPacket.getDataUnprotected(), espPacket .getIPHeaderByteLength(), esp.length); System.arraycopy(adat, 0, espPacket.getDataUnprotected(), espPacket .getIPHeaderByteLength() + esp.length, ICV_LENGTH); return espPacket; } return null; }
ac5ff67e-330d-4eb0-83d8-eaf1dfccddad
6
final void method3049(ByteBuffer class348_sub49, int i, int i_0_) { anInt9179++; int i_1_ = i; while_152_: do { do { if (i_1_ != 0) { if ((i_1_ ^ 0xffffffff) != -2) { if ((i_1_ ^ 0xffffffff) == -3) break; break while_152_; } } else { anInt9176 = class348_sub49.getShort(); break while_152_; } anInt9175 = class348_sub49.getShort(); break while_152_; } while (false); ((Class348_Sub40) this).aBoolean7045 = (class348_sub49.getUByte() ^ 0xffffffff) == -2; } while (false); if (i_0_ != 31015) method3049(null, -85, -85); }
a384222e-d62c-4759-9e4b-73d6be6c0d93
2
public boolean isReference() { return !special && (clazz == null || !clazz.isPrimitive()); }
869f5e0f-4c44-43a3-9e6d-b6679253c8a1
9
public void run() { writer.println("PLAY "+name); writer.flush(); while(!socket.isClosed()){ try { String response = reader.readLine(); if(response.equals("WAIT")) System.out.println("Esperando al otro jugador..."); else if(response.startsWith("VERSUS")){ String name = response.substring("VERSUS ".length(), response.length()); System.out.println("Juegas contra "+name); } else if(response.equals("YOUR BET")){ System.out.println("Ya puedes apostar..."); sendMyBet(); } else if(response.equals("WAIT BET")){ System.out.println("Esperando apuesta del contrincante..."); } else if(response.startsWith("BET OF")){ String data[] = response.substring("BET OF ".length(), response.length()).split(" "); System.out.println("Tu contrincante "+data[0]+" apuesta que hay "+data[1]+" monedas..."); } else if(response.startsWith("AND")){ System.out.println(response+" !!!"); System.out.println("Nos vemos!"); socket.close(); }else{ //not checking response to prevent error response handling, default is none wins and close... System.out.println(response); socket.close(); } } catch (IOException e) { if(!socket.isClosed()) e.printStackTrace(); } } }
b000ea16-dc8f-4743-823f-33b189200614
9
public static Factory get(Class<? extends ASTNode> type, Class<?> argType) { if (type == null) { return null; } try { final Method method = type.getMethod(Parser.kFactoryName, new Class<?>[] { argType }); return new Factory() { protected ASTNode make0(Object args) throws Exception { return (ASTNode) method.invoke(null, args); } }; } catch (NoSuchMethodException e) { } catch (SecurityException e) { } try { final Constructor<? extends ASTNode> constructor = type .getConstructor(argType); return new Factory() { protected ASTNode make0(Object args) throws Exception { return constructor.newInstance(args); } }; } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (SecurityException e) { } return null; }
d6518256-ec8d-49f4-b0b9-9449ec57db50
0
public void setFirst(T newValue) { first = newValue; }
8033e333-e10b-4fc8-93ea-5b0309787e09
5
private static boolean getNext( int[] num, int n, int r ) { int target = r - 1; num[target]++; if ( num[target] > ((n - (r - target)) + 1) ) { while ( num[target] > ((n - (r - target))) ) { target--; if (target < 0) { break; } } if ( target < 0 ) { return true; } num[target]++; for ( int i = target + 1; i < num.length; i++ ) { num[i] = num[i - 1] + 1; } } return false; }
a1e9d2af-03db-40d6-a2b0-c4f7d0f58933
7
private void createRandomTestSuite(final int i) { StroopTest stroopTest = stroopTestProvider.getActiveStroopTest(); if (stroopTest != null) { // FIXME send event + add MainWindow where null int choice = JOptionPane.showConfirmDialog(null, "Wenn Sie einen neuen Test anlegen wird der Alte gel"+oe+"scht, " + "wollen Sie den alten Test vorher speichern?", "Test speichern?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.CANCEL_OPTION) return; if (choice == JOptionPane.YES_OPTION) { eventBusService.post(new SaveStroopTestEvent(stroopTest)); } } int amount; switch (i) { case 0 : { amount = new Random().nextInt(120); stroopTest = StroopTestFactory.createPlainColourTest(amount); break; } case 1 : { amount = new Random().nextInt(120); stroopTest = StroopTestFactory.createOneColourTest(amount); break; } case 2 : { amount = new Random().nextInt(250); stroopTest = StroopTestFactory.createMixedColourTest(amount, TestType.TEST_WORD); break; } case 3 : { amount = new Random().nextInt(250); stroopTest = StroopTestFactory.createMixedColourTest(amount, TestType.TEST_COLOUR); break; } } stroopTestProvider.setActiveStroopTest(stroopTest); eventBusService.post(new InfoMessageEvent("Der Test wurde erfolgreich erstellt.")); }
5c8fb126-ceee-4cfc-a971-0a288bb0cb24
1
public void operation() { if (mComponent != null) { mComponent.operation(); } }
ce6915af-4625-4de0-b6d8-e325d8a091ca
8
@Override public void transit(StateMachineEvent<EventType> event) throws InvalidEventException { Future<?> future = threadPoolFacade.process(new FSMTransitionTask(threadPoolFacade, event,true), syncRunnableProducer); try { future.get(); } catch (InterruptedException ex) { threadPoolFacade.setNextThingToProcess(); throw new InvalidEventException("transition processing has been interrupted", ex); } catch (ExecutionException ex) { ex.getCause().printStackTrace(); if (ex.getCause() instanceof InvalidEventException) { throw (InvalidEventException) ex.getCause(); } if (ex == FSMThreadPoolFacade.queueingFailed){ throw new InvalidEventException("events queue is full"); } else if ((ex.getCause() instanceof RuntimeException) && (ex.getCause().getCause() != null) && ex.getCause().getCause() instanceof InvalidEventException) { // FSMWrapperException is wrapped into RuntimeException and ExecutionException // all this because run() is not declared as throwing Exception ... throw (InvalidEventException) (ex.getCause().getCause()); } else { throw new InvalidEventException("exception during processing of the transit", ex); } } }
66a24128-0205-4b66-9438-3b2d960db4cb
9
public ItemType getItemType(TypeHierarchy th) { boolean isSchemaAware = true; try { isSchemaAware = getExecutable().isSchemaAware(); } catch (NullPointerException err) { // ultra-cautious code in case expression container has not been set if (!th.getConfiguration().isLicensedFeature(Configuration.LicenseFeature.SCHEMA_VALIDATION)) { isSchemaAware = false; } } ItemType in = operand.getItemType(th); if (in.isAtomicType()) { return in; } if (in instanceof NodeTest) { if (in instanceof EmptySequenceTest) { return in; } int kinds = ((NodeTest)in).getNodeKindMask(); if (!isSchemaAware) { // Some node-kinds always have a typed value that's a string if ((kinds | STRING_KINDS) == STRING_KINDS) { return BuiltInAtomicType.STRING; } // Some node-kinds are always untyped atomic; some are untypedAtomic provided that the configuration // is untyped if ((kinds | UNTYPED_IF_UNTYPED_KINDS) == UNTYPED_IF_UNTYPED_KINDS) { return BuiltInAtomicType.UNTYPED_ATOMIC; } } else { if ((kinds | UNTYPED_KINDS) == UNTYPED_KINDS) { return BuiltInAtomicType.UNTYPED_ATOMIC; } } return in.getAtomizedItemType(); } return BuiltInAtomicType.ANY_ATOMIC; }
b51d8af2-c008-483b-a79d-84d9e0324e7f
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(membre_supprimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(membre_supprimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(membre_supprimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(membre_supprimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new membre_supprimer().setVisible(true); } }); }
17405ef8-7791-4402-aec9-bb25a40bcc6a
2
@Override public void run() { try { InputStream is = socket.getInputStream(); while (true) { BufferedReader buffer = new BufferedReader(new InputStreamReader(is)); String str = buffer.readLine(); System.out.println("received msg from server:" + str); } } catch (IOException e) { e.printStackTrace(); } }
124f2a23-3a54-454e-8519-93df099165c6
5
public void update(Observable obs, Object arg) { if (obs instanceof WeatherData) { WeatherData weatherData = (WeatherData)obs; float temperature = weatherData.getTemperature(); temperatures.add(temperature); int count = temperatures.size(); if (count == 1) { this.maxTemperature = this.minTemperature = this.avgTemperature = temperature; } else { if (temperature > maxTemperature) { this.maxTemperature = temperature; } else if (temperature < minTemperature) { this.minTemperature = temperature; } float temperatureSum = 0; for (int i = 0; i < count; i++) { temperatureSum += (float)temperatures.get(i); } this.avgTemperature = temperatureSum / count; } display(); } }
7dcc5ee4-697d-4175-a25f-317486a1ca37
3
public void montarJanelaEditar() { tratadorEventosEditar = new TratadorEventosEditar(acessoBanco, this); painelPrincipal = new JPanel(); MigLayout migLayout = new MigLayout("wrap 3"); painelPrincipal.setLayout(migLayout); botoes.add(botaoCancelar); botoes.add(botaoSalvar); try { MaskFormatter maskaraData = new MaskFormatter("##/##/####"); textoDataNascimento = new JFormattedTextField(maskaraData); textoDataNascimento.setColumns(8); } catch (ParseException e) { e.printStackTrace(); } edicao.setFont(new Font("Times New Roman", Font.BOLD, 20)); painelPrincipal.add(edicao, "gaptop 10, spanx 2, wrap"); painelPrincipal.add(nome, "gaptop 10"); painelPrincipal.add(textoNome, "wrap"); painelPrincipal.add(apelido); painelPrincipal.add(textoApelido, "wrap"); painelPrincipal.add(dataNascimento); painelPrincipal.add(textoDataNascimento, "wrap"); painelPrincipal.add(telefoneResidencial); painelPrincipal.add(textoTelRes, "wrap"); painelPrincipal.add(telefoneCelular); painelPrincipal.add(textoTelCel, "wrap"); painelPrincipal.add(cidade); painelPrincipal.add(textoCidade, "wrap"); painelPrincipal.add(estado); painelPrincipal.add(comboEstados, "wrap"); painelPrincipal.add(botoes, "gapleft 70, spanx 2"); // limitando as teclas que podem ser utilizadas em cada campo textoNome.setDocument(new TeclasPermitidasLetras()); textoCidade.setDocument(new TeclasPermitidasLetras()); textoTelCel.setDocument(new TeclasPermitidasNumeros()); textoTelRes.setDocument(new TeclasPermitidasNumeros()); textoNome.setText((String) contato.getNome()); textoApelido.setText((String) contato.getApelido()); textoDataNascimento.setText((String) contato.getDataNascimento()); textoTelRes.setText((String) contato.getTelefoneResidencial()); textoTelCel.setText((String) contato.getTelefoneCelular()); textoCidade.setText((String) contato.getCidade()); int i; for (i = 0; i < estados.length; i++) if (estados[i].equals(contato.getEstado())) break; comboEstados.setSelectedIndex(i); add(painelPrincipal); botaoSalvar.addActionListener(tratadorEventosEditar); botaoCancelar.addActionListener(tratadorEventosEditar); repaint(); setLocationRelativeTo(null); setResizable(false); setModal(true); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); } }); }
23676ce5-e657-4882-8010-23d5f8fbe303
9
public Vector getOddCycle( Bipartition b ) { //For each vertex, traverse the graph until an endpoint is reached or until a cycle is found. //Keep track of the path to the original vertex and the distance. If the distance is odd, print out the //odd cycle. Vector path = new Vector(); for( int i = 0; i < matrix.length; i++ ) { Vector q = new Vector(); //active vertices Vector s = new Vector(); //visited vertices q.add( new Integer( i )); q.add( new Integer( i )); //parent is node i q.add( new Integer( 0 )); //distance from i is zero //Traverse the graph while vertices remain while( !q.isEmpty() ) { //take out the most recent node int cur = ((Integer)q.remove(0)).intValue(); int curPar = ((Integer)q.remove(0)).intValue(); int curDist = ((Integer)q.remove(0)).intValue(); s.add( new Integer( cur )); //this vertex has now been visited s.add( new Integer( curPar )); //Add all neighbours of the current vertex that have not yet been visited //If we find vertex i again, we have found a cycle. //If the distance from i to i is odd, we have an odd cycle for( int j = 0; j < size(); j++ ) { //add a vertex if it is adjacent to the current vertex and has not been visited if( i == j && matrix[i][j] == 1 && curDist % 2 == 0 ) { //odd cycle //note that the distance is to i's parent, so if it's even then the //distance from i to i is odd. //Build the path by taking out successive parents from S. path.add( new Integer( i ) ); //ends at i path.add( new Integer( cur ) ); //next is cur //Move backwards through the parents for( int k = 0; k < curDist; k++ ) { path.add( new Integer( curPar ) ); int next = s.indexOf( new Integer( curPar ) ); curPar = ((Integer)s.get( next + 1 )).intValue(); } //we are done return path; } else if( !s.contains( new Integer( i ) ) && matrix[i][j ] == 1 ) { q.add( new Integer( i ) ); q.add( new Integer( cur ) ); //cur is the parent q.add( new Integer( curDist + 1 ) ); //one farther away from the beginning } } } } return path; }
72da9e04-9dd8-46d7-a10f-c295284b3c7e
3
private void generateIsland(float y, int minSize, int maxSize) { gen = new IslandGenerator(minSize, maxSize, y); gen.start(); while (gen.finishedIsland == null) { lastProgress = new Float(progress); progress = (gen.progress / factor) + progressBefore; if (progress != lastProgress) { try { Game.server.sendPacketToAllClients(new Packet8Attribute("mapeditor_progress_float", progress)); } catch (Exception e) {} } } progressBefore = new Float(progress); }
7eb4c9de-6760-4edb-9669-fa55deac1803
2
public static double commonBaggageWeight( PassengerTrain train ){ double res = 0; for ( RailwayVehicle it : train ){ if ( it instanceof PassengerCar ){ PassengerCar pCar = (PassengerCar)it; res+= pCar.getBaggageWeight(); } } return res; }
e2b21485-9318-4e66-b39a-70cb64a6a162
2
public static Object loadObject(String file_name) { ObjectInputStream ois; try { ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File(file_name)))); Object object = ois.readObject(); ois.close(); return object; } catch (IOException e) { System.err.println("Error loading: " + file_name); } catch (ClassNotFoundException e) { System.err.println("Error loading: " + file_name); } return null; }
1b086f8a-643c-444b-94be-798a0c1c5009
3
public String getSelectedNote() { String selectedNote = null; int row = table.getSelectedRow(); if(row!=-1) { if(table.getValueAt(row, 0)!=null) { selectedNote = table.getValueAt(row, 0).toString(); } if(table.getValueAt(row, 1)!=null) { selectedNote = table.getValueAt(row, 1).toString(); } } else { selectedNote = null; } return selectedNote; }
44eedce6-fb63-4689-844a-3c608b64734a
6
public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; }
5b2fd1c6-6697-4634-9767-58c22066895c
5
public static ArrayList<MediaCopy> searchMediaByID(String ID){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ArrayList<MediaCopy> media = new ArrayList<MediaCopy>(); try { PreparedStatement stmnt = conn.prepareStatement("SELECT * FROM Media m, MediaCopies mc WHERE mc.media_id = m.media_id AND copy_id LIKE ? AND m.media_id = mc.media_id"); stmnt.setString(1, ID + "%"); ResultSet res; res = stmnt.executeQuery(); while(res.next()){ //Date yearEdition, String publicationPlace, String title String genre, String author, String iSBN, String publisher,int MediaID mediaCopy = new MediaCopy(StringDateSwitcher.toDateYear(res.getString("year")), res.getString("place_of_publication"), res.getString("title"), res.getString("genre"), res.getInt("media_id"), res.getString("creator"), res.getString("producer"), res.getString("type"), res.getInt("copy_id"), res.getBoolean("lendable")); media.add(mediaCopy); } } catch(SQLException e){ e.printStackTrace(); } return media; }
cc0fbdea-5bd8-448b-8743-21646e419e4c
6
public static HashMap<String, HashMap<String, Integer>> getMap(String filePath) throws Exception { HashMap<String, HashMap<String, Integer>> map = new HashMap<String, HashMap<String,Integer>>(); BufferedReader reader = filePath.toLowerCase().endsWith("gz") ? new BufferedReader(new InputStreamReader( new GZIPInputStream( new FileInputStream( filePath)))) : new BufferedReader(new FileReader(new File(filePath ))); String nextLine = reader.readLine(); int numDone =0; while(nextLine != null) { StringTokenizer sToken = new StringTokenizer(nextLine, "\t"); String sample = sToken.nextToken(); String taxa= sToken.nextToken(); int count = Integer.parseInt(sToken.nextToken()); if( sToken.hasMoreTokens()) throw new Exception("No"); HashMap<String, Integer> innerMap = map.get(sample); if( innerMap == null) { innerMap = new HashMap<String, Integer>(); map.put(sample, innerMap); } if( innerMap.containsKey(taxa)) throw new Exception("parsing error " + taxa); innerMap.put(taxa, count); nextLine = reader.readLine(); numDone++; if( numDone % 1000000 == 0 ) System.out.println(numDone); } return map; }
1f9e03a3-4123-460a-bf41-2f52f8336156
9
public static File[] filterImagesFromFolder (File[] folder) { List<File> files = new ArrayList<File>(); File[] listOfImages = null; int i=0; try{ for(File file:folder) { if(file.getName().endsWith(".jpg")||file.getName().endsWith(".jpeg")||file.getName().endsWith(".png") || file.getName().endsWith(".JPG")||file.getName().endsWith(".JPEG") || file.getName().endsWith(".PNG")) { files.add(file); } } listOfImages = new File[files.size()]; for(Object object:files) { listOfImages[i] = (File)object; i++; } } catch(Exception e) { e.printStackTrace(); } return listOfImages; }
0cfed858-4c2d-4d19-9c2e-e296c3265cd6
7
private void canSeeNothingAction() { switch (this.getType()) { case "Goalie" : //MP- If you can see the ball, face it if (canSeeBall) { turnTowardBall(); } else if (canSeeOpponentGoal) {//MP- If you can't see the ball, face the opposition turnTowardOpponentGoal(); } else if (canSeeOwnGoal) {//MP- if you can only see your own goal, face the goal, then turn 180 to face opposition turnTowardOwnGoal(); turnOneEighty(); } else {//MP- Last resort, turn and wait for another percept turnNinety(); } break; case "Attacker" : //Attacker, as player sees nothing it will turn 180 finalTurnDirection = 180; break; case "Midfielder": // Players 4/5/6/7/8 turnOneEighty(); // turns agent 180 degrees so that he can hopefully see something to carry out a desirable action break; /**MP- If you can see nothing at all, keep turning until a more useful percept is detected**/ case "Defender" : //MP- Players 9, 10, 11 turnNinety(); //MP- Keep turning until a more useful percept is detected break; default : throw new Error("<<<--- CAN SEE NOTHING ACTION PLAYER NOT FOUND --->>>"); } }
bb44a6b4-2d4c-48c1-85d8-dc8eb52d9207
8
public static BufferedImage applyGaussianBlur(final BufferedImage image, final int filterRadius, final float alphaFactor, final boolean useOriginalImageAsDestination) { if (filterRadius < 1) { throw new IllegalArgumentException("Illegal filter radius: expected to be >= 1, was " + filterRadius); } float[] kernel = new float[2 * filterRadius + 1]; final float sigma = filterRadius / 3f; final float alpha = 2f * sigma * sigma; final float rootAlphaPI = (float) Math.sqrt(alpha * Math.PI); float sum = 0; for (int i = -0; i < kernel.length; i++) { final int d = -((i - filterRadius) * (i - filterRadius)); kernel[i] = (float) (Math.exp(d / alpha) / rootAlphaPI); sum += kernel[i]; } for (int i = 0; i < kernel.length; i++) { kernel[i] /= sum; kernel[i] *= alphaFactor; } final Kernel horizontalKernel = new Kernel(kernel.length, 1, kernel); final Kernel verticalKernel = new Kernel(1, kernel.length, kernel); synchronized (BlurUtils.class) { final int blurredWidth = useOriginalImageAsDestination ? image.getWidth() : image.getWidth() + 4 * filterRadius; final int blurredHeight = useOriginalImageAsDestination ? image.getHeight() : image.getHeight() + 4 * filterRadius; final BufferedImage img0 = ensureBuffer0Capacity(blurredWidth, blurredHeight); final Graphics2D graphics0 = img0.createGraphics(); graphics0.drawImage(image, null, useOriginalImageAsDestination ? 0 : 2 * filterRadius, useOriginalImageAsDestination ? 0 : 2 * filterRadius); graphics0.dispose(); final BufferedImage img1 = ensureBuffer1Capacity(blurredWidth, blurredHeight); final Graphics2D graphics1 = img1.createGraphics(); graphics1.drawImage(img0, new ConvolveOp(horizontalKernel, ConvolveOp.EDGE_NO_OP, null), 0, 0); graphics1.dispose(); BufferedImage destination = useOriginalImageAsDestination ? image : new BufferedImage(blurredWidth, blurredHeight, BufferedImage.TYPE_INT_ARGB); final Graphics2D destGraphics = destination.createGraphics(); destGraphics.drawImage(img1, new ConvolveOp(verticalKernel, ConvolveOp.EDGE_NO_OP, null), 0, 0); destGraphics.dispose(); return destination; } }
382a175a-8cac-4dd4-8dbe-bd67b3341917
1
public Economy getEconomy() { if (econHook == null) { throw new NullPointerException("Economy was called but hasn't been setup!"); } return econHook; }
f585414a-107b-4260-8b9e-bd531bdb907f
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ChunkSQL other = (ChunkSQL) obj; if (worldName == null) { if (other.worldName != null) return false; } else if (!worldName.equals(other.worldName)) return false; if (x != other.x) return false; if (z != other.z) return false; return true; }
e9e08fed-eb47-4bdd-97ee-3eb549b23a76
4
public static ArrayList<Student> chgGradeMenu(ArrayList<Student> inList){ int choice = 0; do { System.out.println("What would you like to do: \n 1) Change Grade \n 2) Switch Classes \n 3) return to main menu"); Scanner userinput = new Scanner(System.in); choice = userinput.nextInt(); if(choice ==1) { inList = gradeChanger(inList); } else if(choice == 2) { inList = ScheduleChanger(inList); } else if (choice == 3) { break; } else { System.out.println("Invalid input"); System.out.println(); } } while (choice != 3); return inList; }
eba293ec-195f-49cb-a5b9-83d1e17014c8
1
public Tile (int id, Sprite[] sprites, int levelColour) { this.tileID = (byte)id; if(tiles[id] != null) {throw new RuntimeException("Duplicate tile id on " + id);} this.sprites = sprites; this.levelColour = levelColour; tiles[id] = this; spriteID = random.nextInt(sprites.length); System.out.println(spriteID); }
4256b6fc-d66b-48b4-915c-137cc649c452
7
public List<ExtendedEntityType> getIndividualMobs() { List<ExtendedEntityType> types = new ArrayList<ExtendedEntityType>(); if (mobMaximums != null) { for (int i = 0; i < mobMaximums.length; ++i) { if (mobMaximums[i] != Short.MAX_VALUE) { types.add(ExtendedEntityType.valueOf(i)); } } } if (dynMobMultis != null) { for (int i = 0; i < dynMobMultis.length; ++i) { if (dynMobMultis[i] == Short.MAX_VALUE) continue; ExtendedEntityType type = ExtendedEntityType.valueOf(i); // Make sure we haven't already added the entity type if (!types.contains(type)) types.add(type); } } return types; }
2d74dbae-3a45-4675-aa7b-c73ca82a9187
4
protected final short get_reduce(int state, int sym) { short tag; short[] row = reduce_tab[state]; /* if we have a null row we go with the default */ if (row == null) return -1; for (int probe = 0; probe < row.length; probe++) { /* is this entry labeled with our Symbol or the default? */ tag = row[probe++]; if (tag == sym || tag == -1) { /* return the next entry */ return row[probe]; } } /* if we run off the end we return the default (error == -1) */ return -1; }
88710b12-4987-4ebb-b550-bacd2848af10
1
private static Object toAnnoType(Annotation anno, ClassPool cp) throws ClassNotFoundException { try { ClassLoader cl = cp.getClassLoader(); return anno.toAnnotationType(cl, cp); } catch (ClassNotFoundException e) { ClassLoader cl2 = cp.getClass().getClassLoader(); return anno.toAnnotationType(cl2, cp); } }
78aa34cc-2d04-48fd-a4c9-c8db72362cf6
8
@Override public void mouseClicked(MouseEvent e) { //Afficher le contenu de la pioche ouverte if ( e.getSource() == this.openPick && tileViewer == null && !this.selected.hasSelection()) { this.tileViewer = this.openPick.viewTiles(); if (this.tileViewer != null) { this.add(tileViewer, 0); this.client.repaint(); } } //Piocher une piece dans la pioche fermee else if ( e.getSource() == this.closePick && !this.closePick.isEmpty() && tileViewer == null) { try { client.sendMessage("PICK"); } catch ( IOException ex) { ex.printStackTrace(); } } }
d16ab5d2-8c38-4b09-83b5-6faf802c715e
2
private void initializeTetrominoes() { tetromino = bag.draw(); next = new LinkedList<>(); for (int i = 0; i < PREVIEW_COUNT; i++) { next.add(bag.draw()); } if (nextTetrominoesChangedListener != null) nextTetrominoesChangedListener.onNextTetrominoesChanged(next); }
64b0246d-8eb2-4b4e-9937-9def24dce3f6
5
public static ArrayList<BookCopy> searchBookByISBN(String iSBN){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ArrayList<BookCopy> books = new ArrayList<BookCopy>(); try { PreparedStatement stmnt = conn.prepareStatement("SELECT * FROM Books a, BookCopies b WHERE iSBN LIKE ? AND a.book_id = b.book_id"); stmnt.setString(1, iSBN + "%"); ResultSet res; res = stmnt.executeQuery(); while(res.next()){ //Date yearEdition, String publicationPlace, String title String genre, String author, String iSBN, String publisher,int bookID bookCopy = new BookCopy(res.getDate("year"),res.getString("place_of_publication"),res.getString("title"),res.getString("genre"),res.getString("author"),res.getString("iSBN"),res.getString("publisher"),res.getInt("book_id"),res.getInt("copy_id"),res.getInt("edition"),res.getBoolean("lendable")); books.add(bookCopy); } } catch(SQLException e){ e.printStackTrace(); } return books; }
40778bd2-7acd-48b7-bb11-04ea12711dda
5
final void method1716(boolean bool) { if (((Class239) this).aClass348_Sub51_3136.method3425(-82)) ((Class239) this).anInt3138 = 0; anInt5904++; if ((((Class348_Sub51) ((Class239) this).aClass348_Sub51_3136) .aClass239_Sub24_7235.method1820(-32350) ^ 0xffffffff) == -1) ((Class239) this).anInt3138 = 0; if (bool != false) method1712(-60, 72); if ((((Class239) this).anInt3138 ^ 0xffffffff) > -1 || ((Class239) this).anInt3138 > 2) ((Class239) this).anInt3138 = method1710(20014); }
e2bd6872-5754-4436-830e-7173d914635a
4
public byte[] readBytesReverse(int amount, ValueType type) { byte[] data = new byte[amount]; int dataPosition = 0; for (int i = buffer.readerIndex() + amount - 1; i >= buffer.readerIndex(); i--) { int value = buffer.getByte(i); switch (type) { case A: value -= 128; break; case C: value = -value; break; case S: value = 128 - value; break; default: break; } data[dataPosition++] = (byte) value; } return data; }
1be3fbf1-a9c2-4c56-bc62-96805bf5d39f
9
@Override public void add(Difference difference) { if(ignorePaths == null) { list.add(difference); } else { String pathA = trimNonXmlElements(difference.getPathA()); String pathB = trimNonXmlElements(difference.getPathB()); if (ignorePaths.contains(pathA) || ignorePaths.contains(pathB)) { // ignorable matched if(ignorePaths.contains(pathA) && ignorePaths.contains(pathB)) { // both sides contains an ignorable difference return; } else if(pathA.length() > 0 && ignorePaths.contains(pathB)) { // B contains ignorable difference = new Difference(difference.getPathA(), null, "Only in: " + getNameA()); list.add(difference); } else if(ignorePaths.contains(pathA) && pathB.length() > 0) { // A contains ignorable difference = new Difference(null, difference.getPathB(), "Only in: " + getNameB()); list.add(difference); } } else { // no ignorable matched list.add(difference); } } }