method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
9c6261c0-4f02-40ad-8637-b61d7a177ca3
4
@Override protected ContentValidator getResponseValidator() { return new ContentValidator() { /** * Validate the document. */ @Override public void validate(Document doc) throws Exception { if(doc != null) { Node payloadNode = Utilities.selectSingleNode(doc, "//dc:Payload/*[1]", XMLLabels.STANDARD_NAMESPACES); if(payloadNode != null && payloadNode.getNodeType() == Node.CDATA_SECTION_NODE) { Document innerDoc = Utilities.parseXml(payloadNode.getTextContent()); if(innerDoc != null) { Utilities.validate(innerDoc); } } } } }; }
9d16f81d-903c-43e4-84c0-17b3cf6ff295
9
@Override public boolean handleEvent(final Event event) { if (event.id != event.ACTION_EVENT) { return super.handleEvent(event); } else if (event.target == buttons.get("On")) { radioControl.turnOn(); return true; } else if (event.target == buttons.get("Off")) { radioControl.turnOff(); return true; } else if (event.target == buttons.get("Reset")) { radioControl.reset(); return true; } else if (event.target == buttons.get("Scan")) { if(scanner.getState() == Thread.State.NEW) { scanner.start(); } else { radioControl.unlock(); } return true; } else if (event.target == buttons.get("SetFav")) { if(favStation.getState() == Thread.State.NEW) favStation.start(); else radioControl.rewrite(); return true; } else if (event.target == buttons.get("TuneFav")) { radioControl.tuneFav(); return true; } else { return super.handleEvent(event); } }
45c8bbd9-7ccd-44c9-add4-4ed30363e64c
4
private void close() throws Exception { try { if (_resultSet != null) { _resultSet.close(); } if (_statement != null) { _statement.close(); } if (_connect != null) { _connect.close(); } } catch (Exception e) { throw e; } } // End close
81e57ef0-c874-46fb-8d4a-301d69b8d526
8
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((answer == null) ? 0 : answer.hashCode()); result = prime * result + ((answerInfo == null) ? 0 : answerInfo.hashCode()); result = prime * result + ((choice == null) ? 0 : choice.hashCode()); result = prime * result + ((frequence == null) ? 0 : frequence.hashCode()); result = prime * result + ((historyDate == null) ? 0 : historyDate.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((question == null) ? 0 : question.hashCode()); result = prime * result + ((taken == null) ? 0 : taken.hashCode()); return result; }
677c086c-ad1c-4fca-9448-26e2a50c8804
0
private List<AnswerCombination> generateAnswerCombinationList() { List<AnswerCombination> combinations = new ArrayList<AnswerCombination>(); combinations.add(generateAnswerCombination(0, 5)); combinations.add(generateAnswerCombination(1, 4)); combinations.add(generateAnswerCombination(2, 1)); combinations.add(generateAnswerCombination(3, 1)); combinations.add(generateAnswerCombination(4, 1)); combinations.add(generateAnswerCombination(2, 1)); combinations.add(generateAnswerCombination(2, 2)); combinations.add(generateAnswerCombination(2, 3)); combinations.add(generateAnswerCombination(3, 2)); combinations.add(generateAnswerCombination(4, 1)); combinations.add(generateAnswerCombination(5, 0)); combinations.add(generateAnswerCombination(0, 0)); return combinations; }
b58e64e2-6bea-4a78-8f61-532420670753
0
public VueApplication(String parT, BDApplication bDApplication) { super(parT); this.bDApplication = bDApplication; initComponents(); // Initialisation des composants setSize(LARG_ECRAN, HAUT_ECRAN); setLocationRelativeTo(null);// centrage de la fenetre principale setResizable(false); // Redimensionnement interdit this.repaint(); pack(); // Redimensionne la fenetre a la taille de son contenu setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); }
51f14228-638d-4297-b250-befd15e5d424
6
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Product product = (Product) o; return id == product.id && number == product.number && !(name != null ? !name.equals(product.name) : product.name != null); }
2f719372-c26b-4d4e-a2a8-a7b7e8b66b00
9
static <T extends Comparable<T>> int comparePossiblyNull(T aThis, T aThat, NullsGo aNullsGo){ int EQUAL = 0; int BEFORE = -1; int AFTER = 1; int result = EQUAL; if(aThis != null && aThat != null){ result = aThis.compareTo(aThat); } else { //at least one reference is null - special handling if(aThis == null && aThat == null) { //not distinguishable, so treat as equal } else if(aThis == null && aThat != null) { result = BEFORE; } else if( aThis != null && aThat == null) { result = AFTER; } if(NullsGo.LAST == aNullsGo){ result = (-1) * result; } } return result; }
dee8c735-c9e8-4fd6-9770-9b298d0081bb
4
public void execute(){ switch(operator) { case eOperator_Plus: this.setResult(lhs.getValue().add(rhs.getValue())); break; case eOperator_Subtract: this.setResult(lhs.getValue().subtract(rhs.getValue())); break; case eOperator_Divide: this.setResult(lhs.getValue().divide(rhs.getValue())); break; case eOperator_Multiply: this.setResult(lhs.getValue().multiply(rhs.getValue())); } }
4fe1696b-784e-4e46-83ad-3692a8841930
7
public static Show<CheckResult> summaryEx(final Show<Arg<?>> sa) { return showS(new F<CheckResult, String>() { public String f(final CheckResult r) { final String s = summary(sa).show(r).toString(); if (r.isProven() || r.isPassed() || r.isExhausted()) return s; else if (r.isFalsified() || r.isPropException() || r.isGenException()) throw new Error(s); else throw decons(r.getClass()); } }); }
22a73963-dede-40b5-8f32-35e03b1e1ddd
4
public static void main(String[] args) { // String path = "/Users/macbookpro/Desktop/save.wav"; // Player pl = new Player(path); // pl.play(path); // try { // Thread.sleep(5000); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // pl.stopPlay(); // pl.play(path); try { Recorder r = new Recorder(); r.start(); Thread.sleep(1000); r.stopRecord(); File f = new File ("D:/test.wav"); VoiceOperator vo = new VoiceOperator(r.getAudio()); // vo.saveToWave(f, r.getAudio()); r.deleteTmpFile(); // the file will be delete when the programm is closed } catch (InterruptedException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Player pl = new Player(r.getAudio()); // pl.play(r.getAudio()); // try { // Thread.sleep(10000); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // r.stopRecord(); // pl.play(r.getAudio()); }
879b32e4-774e-4caa-ba78-ff90f13eab71
9
protected static void parseWallJson(String jsonResponse, String hashKeys, User user, ArrayList<Message> messagesArray) throws IOException, ParseException { JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject)parser.parse(jsonResponse); JSONArray array = (JSONArray)obj.get("response"); String[] tags = hashKeys.split(","); //Start to parse array of wall messages for (int i = 0; i < array.size() - 1; i++) { Message message = new Message(); message.userInfo = user; //In [0] entry it's nothing interesting. Lets start from [1]. obj = (JSONObject)array.get(i + 1); //Checking to text fields and then check if text contain neсessary word. if (((String)obj.get("text")).isEmpty()) { if ((obj.containsKey("copy_text") && !((String)obj.get("copy_text")).isEmpty())) for (String tag : tags) { if (((String)obj.get("copy_text")).contains(tag)) { message.message = (String)obj.get("copy_text"); //VK date is in unixtime format. So lets multiply it by 1000 to get ms. message.date = new Date((Long)obj.get("date") * 1000); messagesArray.add(message); break; } } } else for (String tag : tags) { if (((String)obj.get("text")).contains(tag)) { message.message = (String)obj.get("text"); //VK date is in unixtime format. So lets multiply it by 1000 to get ms. message.date = new Date((Long)obj.get("date") * 1000); messagesArray.add(message); break; } } if (message.message != null) { message.message = message.message.replaceAll("(\\b((https?|ftp|file)://|www|vk\\.cc)[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|])", "<a href=\\\"$1\\\">$1</a>"); message.message = message.message.replaceAll("#\\S*", ""); } } }
119b1bbe-0a46-4c00-9b8c-ed8417f59104
9
private static void processMouseEvents(){ if( Mouse.isButtonDown(0)){ // FX VOLUME if( Mouse.getX() > Game.SCREEN_WIDTH/4 && Mouse.getX() < Game.SCREEN_WIDTH/4*3 && Mouse.getY() > Game.SCREEN_HEIGHT - 166 && Mouse.getY() < Game.SCREEN_HEIGHT - 146){ Options.FXVolume = (float) (Mouse.getX() - Game.SCREEN_WIDTH/4) / (Game.SCREEN_WIDTH/4*2); } // BG VOLUME if( Mouse.getX() > Game.SCREEN_WIDTH/4 && Mouse.getX() < Game.SCREEN_WIDTH/4*3 && Mouse.getY() > Game.SCREEN_HEIGHT - 116 && Mouse.getY() < Game.SCREEN_HEIGHT - 96){ Options.BGVolume = (float) (Mouse.getX() - Game.SCREEN_WIDTH/4) / (Game.SCREEN_WIDTH/4*2); } } }
1db3bef9-8142-458f-afc9-26817657d5ef
4
public int inputSelectedAnswer() { int playerGuess = 0; String choiceS = ""; do { try { System.out.print(UserDialog.ANSWER_PROMPT); Scanner sc = new Scanner(System.in); choiceS = sc.nextLine(); checkInterruptionRequired(choiceS); playerGuess = Integer.parseInt(choiceS); } catch (InputMismatchException ex) { System.out.println(ExceptionMsg.ANS_NUM_TRY); } catch (NumberFormatException ex) { System.out.println(ExceptionMsg.ANS_NUM_TRY); } } while (!answerRangeValidationCheck(playerGuess) || playerGuess == 0); return playerGuess; }
d86e8d65-4c83-4092-9294-0c0f75443821
9
public List<Location> adjacentLocations(Location location) { assert location != null : "Null location passed to adjacentLocations"; // The list of locations to be returned. List<Location> locations = new LinkedList<Location>(); if(location != null) { int row = location.getRow(); int col = location.getCol(); for(int roffset = -1; roffset <= 1; roffset++) { int nextRow = row + roffset; if(nextRow >= 0 && nextRow < depth) { for(int coffset = -1; coffset <= 1; coffset++) { int nextCol = col + coffset; // Exclude invalid locations and the original location. if(nextCol >= 0 && nextCol < width && (roffset != 0 || coffset != 0)) { locations.add(new Location(nextRow, nextCol)); } } } } // Shuffle the list. Several other methods rely on the list // being in a random order. Collections.shuffle(locations, rand); } return locations; }
7a0e025e-a34b-4ff1-85fb-357e33aa29df
1
@Override public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { List<BankDeposit> deposits = ReaderFactory.getInstance() .getSAXReader().readXML(DataPath.XML_FILE); request.setAttribute("type", ParserType.SAX); request.setAttribute("deposits", deposits); return PageName.DEPOSITS_PAGE; } catch (XMLReaderSAXException ex) { log.error(ex); } return PageName.ERROR_PAGE; }
38c5a6e1-f770-4581-8013-e132e5f389ef
6
private void generate_symbols_list() { symbolnames = new ArrayList<>(); if(log_level >= 4) log.log(4, key, "generate_symbols_list called.", "\n"); for (Map.Entry<String, HashMap<String, Variable>> percontext : context_varname_var.entrySet()) { for (Map.Entry<String, Variable> value : percontext.getValue().entrySet()) { symbolnames.add(value.getKey()); } } symbolnames.add("true"); symbolnames.add("TRUE"); symbolnames.add("false"); symbolnames.add("FALSE"); /* now sort the new generated list from long to short, with a dirty inline class ;) */ Collections.sort(symbolnames, new Comparator<String>() { private int alen; private int blen; @Override public int compare(String a, String b) { alen = a.length(); blen = b.length(); if (alen > blen) { return -1; } else if (alen < blen) { return 1; } else { return 0; } } }); if(log_level >= 4) log.log(4, key, "symbols list: ", Arrays.toString(symbolnames.toArray()), "\n"); }
d3564fa6-5db3-4c6a-be21-6f681ca6bfd3
8
private boolean parseOptions(String[] args) { CommandLineParser parser = new GnuParser(); try { CommandLine cl = parser.parse(opts, args); // check for -help if (cl.hasOption("help")) { showUsage(); System.exit(0); } // check for -version if (cl.hasOption("version")) { showVersion(); System.exit(0); } // check for -precision if (cl.hasOption("precision")) { try { precision = Integer.parseInt(cl.getOptionValue("precision")); if (precision<0 || precision>15) throw new NumberFormatException(); } catch(NumberFormatException nfe) { System.err.println("\nprecision must be a positive integer value in the range [0,15]"); return false; } } // make sure at least one file is specified if (cl.getArgs().length == 0) { System.err.println("\nyou must specify at least one file to analyse"); return false; } // grab the filenames collectionFiles = cl.getArgs(); } catch (ParseException e) { System.err.println(""); System.err.println( e.getMessage() ); return false; } return true; }
cb3c8c14-a365-4095-9f8f-556be7e0a24f
8
public void doMove(Move thisMove) { final Piece piece = getPiece(thisMove.getStartX(), thisMove.getStartY()); /* Supprime l'etat de danger */ // TODO VERIFIER SI CES PIECES PEUVENT ETRE EN DANGER PAR UNE AUTRE DE // MES PIECES // Générer tous les coups possibles pour cette pièce ArrayList<Move> moves = piece.generateMovesForThisPiece(this); // Pour chaque mouvement avant le deplacement, trouver si elle mange // quelque chose et la mettre en etat de hors de danger for (final Move move : moves) { final Piece enemyPiece = chessboard[move.getEndY()][move.getEndX()]; if ((enemyPiece != null) && (enemyPiece.isColor() != piece.isColor())) { enemyPiece.noMoreInDanger(); } } // Supprime la pièce qui va ce faire manger de la liste des pieces // (blacks/whites) de sa couleur if (chessboard[thisMove.getEndY()][thisMove.getEndX()] != null) { if (Helper.isColorWhite(piece.isColor())) { blacks.remove(chessboard[thisMove.getEndY()][thisMove.getEndX()]); } else { whites.remove(chessboard[thisMove.getEndY()][thisMove.getEndX()]); } } // Déplacement de la pièce chessboard[thisMove.getEndY()][thisMove.getEndX()] = piece; chessboard[thisMove.getStartY()][thisMove.getStartX()] = null; // Modifie l'etat moved de la pièce piece.setMoved(true); /* Trouvez si maintenant il ya des morceaux en danger */ // Générer tous les coups possibles pour cette pièce moves = piece.generateMovesForThisPiece(this); // For each move find if it eats something for (final Move move : moves) { final Piece enemyPiece = chessboard[move.getEndY()][move.getEndX()]; if ((enemyPiece != null) && (enemyPiece.isColor() != piece.isColor())) { enemyPiece.inDanger(); } } }
1fac622a-0a33-499a-bfa3-42c669ca2d6d
7
public String getWWWAuthenticateHeader(String realm) throws IOException { StringBuilder into = new StringBuilder(); String authScheme = null; if (realm != null) { into.append(" realm=\"").append(OAuth2.percentEncode(realm)).append('"'); } beforeGetParameter(); if (parameters != null) { for (Map.Entry parameter : parameters) { String name = toString(parameter.getKey()); if (name.startsWith("error")) { if (into.length() > 0) into.append(","); into.append(" "); into.append(OAuth2.percentEncode(name)).append("=\""); into.append(OAuth2.percentEncode(toString(parameter.getValue()))).append('"'); }else if(name.startsWith(AUTH_SCHEME)){ authScheme = toString(parameter.getValue()); } } } if(authScheme == null){ // TODO Throw exception } return authScheme + " " + into.toString(); }
316d262a-ce7b-456c-9bb4-10cad09d9364
3
private boolean doesPosNumHaveList(ArrayList<Integer> posNums, ArrayList<ArrayList<ArrayList<Integer>>> posNumsListArray) { boolean dPNHL = false; for(int i=0; i<posNumsListArray.size(); i++) { dPNHL = dPNHL || doesPosNumListMatch(posNums, posNumsListArray.get(i)); } if(!dPNHL) { ArrayList<ArrayList<Integer>> newBucket = new ArrayList<ArrayList<Integer>>(); newBucket.add(posNums); posNumsListArray.add(newBucket); } return dPNHL; }
f58d4ec3-8f59-44c2-8651-4ec680979f65
3
public static Collection<BSPlayer> getPlayersIgnorers(String player) { Collection<BSPlayer> players = new ArrayList<BSPlayer>(); for(BSPlayer p: PlayerManager.getPlayers()){ if(p.hasIgnores()){ if(p.isIgnoring(player)){ players.add(p); } } } return players; }
6622011d-3aa0-4948-ab4a-f980edf24f67
2
private void addAttributesFrom(Map<Object, Object> attributes, String pathBase, String key) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); String path = pathBase + key + "/info.txt"; try { InputStream is = classLoader.getResourceAsStream(path); BufferedReader reader; if(is == null) { reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path)), "ISO-8859-1")); }else{ reader = new BufferedReader(new InputStreamReader(is)); } reader.readLine(); attributes.put(pathBase + key + "/" + key + "_N", reader.readLine()); reader.readLine(); attributes.put(pathBase + key + "/" + key + "_E", reader.readLine()); reader.readLine(); attributes.put(pathBase + key + "/" + key + "_S", reader.readLine()); reader.readLine(); attributes.put(pathBase + key + "/" + key + "_W", reader.readLine()); reader.close(); } catch (IOException exc) { System.out.println("Could not find " + path); } }
40503484-7494-433f-97d4-8dad596d25b3
4
private void summariseFertilities() { final int SS = World.SECTOR_SIZE, SR = world.size / World.SECTOR_SIZE ; fertilityLevels = new float[SR][SR] ; for (Coord c : Visit.grid(0, 0, world.size, world.size, 1)) { final Tile t = world.tileAt(c.x, c.y) ; final Habitat h = t.habitat() ; float f = h.moisture() ; if (! h.pathClear) f = -5 ; if (h == Habitat.CURSED_EARTH) f = -10 ; fertilityLevels[c.x / SS][c.y / SS] += f ; totalFertility += f ; } for (Coord c : Visit.grid(0, 0, SR, SR, 1)) { fertilityLevels[c.x][c.y] /= SS * SS * 10 ; } totalFertility /= world.size * world.size * 10 ; }
19fbfc7a-f9cf-4ff1-a5fb-d61ff0f2a7b6
7
private int jjMoveStringLiteralDfa6_0(long old1, long active1, long old2, long active2) { if (((active1 &= old1) | (active2 &= old2)) == 0L) return jjStartNfa_0(4, 0L, old1, old2); try { curChar = input_stream.readChar(); } catch (IOException e) { jjStopStringLiteralDfa_0(5, 0L, 0L, active2); return 6; } switch (curChar) { case 68: case 100: return jjMoveStringLiteralDfa7_0(active2, 0x20000000L); case 84: case 116: if ((active2 & 0x80000000L) != 0L) return jjStopAtPos(6, 159); break; default : break; } return jjStartNfa_0(5, 0L, 0L, active2); }
5721f7e0-a525-415e-b668-9bee166fa7e7
7
static public void loadToMemory(VMController vmc, File file){ try { Scanner fileScan = new Scanner(new BufferedReader( new FileReader(file))); fileScan.useDelimiter(System.getProperty("line.separator")); String command; int adress = 0; while (fileScan.hasNext()){ command = fileScan.next(); if (command.equalsIgnoreCase("CODE") || command.equalsIgnoreCase("DATA")|| command.isEmpty()){ continue; } else if (command.startsWith("#")){ adress = Integer.parseInt(command.substring(1, 5), 16); continue; } else if (command.length() != 4){ command = String.format("%-4s", command).replace(' ', '0'); } Memory.setMemory(vmc, adress, command); adress++; } } catch (FileNotFoundException ex) { System.err.println(ex); } }
86b4ed98-8259-428f-9eb9-9856a497eafa
6
private void cambiaLabel(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cambiaLabel if (jComboBox1.getSelectedIndex() == 0) { parcheCartel = 0; jLabel3.setText("Precio de salida $:"); jSpinner1.setVisible(false); jLabel6.setVisible(false); } if (jComboBox1.getSelectedIndex() == 2) { parcheCartel = 2; jLabel3.setText("Precio de salida $:"); SpinnerNumberModel modelito = new SpinnerNumberModel(); jSpinner1.setModel(modelito); modelito.setValue(2); modelito.setMinimum(2); jSpinner1.setVisible(true); jLabel6.setVisible(true); } if (jComboBox1.getSelectedIndex() == 1) { parcheCartel = 1; jLabel3.setText("Precio mínimo a vender $"); jSpinner1.setVisible(false); jLabel6.setVisible(false); } if (jComboBox1.getSelectedIndex() == 4) { parcheCartel = 4; jLabel3.setText("Precio $"); jSpinner1.setVisible(false); jLabel6.setVisible(false); } if (jComboBox1.getSelectedIndex() == 3) { if (parcheCartel != 3) { JOptionPane.showMessageDialog(this, "Los compradores seran anónimos"); } parcheCartel = 3; jLabel3.setText("Precio de salida $:"); jSpinner1.setVisible(false); jLabel6.setVisible(false); } }//GEN-LAST:event_cambiaLabel
30c5ee2e-18c4-414a-9a47-5086c576d1cc
0
public QuizDataObject[] createFilledQuizList(int size) { size=3; QuizDataObject [] qDBArray=new QuizDataObject[size]; qDBArray[0]=new QuizDataObject("dsad0",new String[]{""+(1)},""+2,""+0); qDBArray[1]=new QuizDataObject("dsad1",new String[]{""+(1)},""+2,""+(1)); qDBArray[2]=new QuizDataObject("asfs2",new String[]{""+(0)},""+1,""+(2)); //qDBArray[3]=new QuizDataObject("asa3",new String[]{""+(5)},""+2,""+(3)); //qDBArray[4]=new QuizDataObject("aas4",new String[]{""+(3)},"",""+(4)); //qDBArray[5]=new QuizDataObject("ss5",new String[]{""},"",""+(5)); return qDBArray; }
3bc70304-c45b-4697-95c9-ce993a3c94eb
7
public static double calcChiasmaDist(double chromLength) { if (chromLength<=0.500) { return Double.NaN; } if (chromLength>5.0) { return 0.5; } double toler = 0.00001; double lastdiff = mdiff(chromLength,0.5); //first find initial minimum: double m1 = 10.5; while (mdiff(chromLength,m1)<lastdiff) { lastdiff = mdiff(chromLength,m1); m1 += 10.0; } double m2,m3; if (m1==10.5) { m2 = 5.5; m3 = 0.5; } else { m2 = m1 - 10.0; m3 = m1 - 20.0; } while (m1-m3>toler) { if (mdiff(chromLength,m1-0.5*(m1-m2))<mdiff(chromLength,m2)) { m3 = m2; m2 = m1-0.5*(m1-m2); } else if (mdiff(chromLength,m3+0.5*(m2-m3))<mdiff(chromLength,m2)) { m1 = m2; m2 = m3+0.5*(m2-m3); } else { m1 = m1-0.5*(m1-m2); m3 = m3+0.5*(m2-m3); } } return m2; } //calcChiasmaDist
06c3ee2c-adcd-4ed9-9d64-d711f50c33c4
5
static final int method600(byte i, int i_1_, int i_2_) { anInt1115++; int i_3_; if (i_2_ <= 20000) { if (i_2_ <= 10000) { if ((i_2_ ^ 0xffffffff) >= -5001) { Class348_Sub40_Sub12.method3076(0, true); i_3_ = 1; } else { i_3_ = 2; ConnectionMode.method1263(true); } } else { i_3_ = 3; Class47.method447((byte) -59); } } else { Class133.method1140(120); i_3_ = 4; } if ((((Class348_Sub51) BitmapTable.aClass348_Sub51_3959) .aClass239_Sub25_7271.method1829(-32350) ^ 0xffffffff) != (i_1_ ^ 0xffffffff)) { BitmapTable.aClass348_Sub51_3959.method3429((byte) 74, (((Class348_Sub51) (BitmapTable .aClass348_Sub51_3959)) .aClass239_Sub25_7251), i_1_); Class367_Sub10.method3553(false, (byte) 122, i_1_); } if (i >= -20) aClass243_1114 = null; Class14_Sub2.method243(37); return i_3_; }
aedd1e37-7971-459f-a0cf-1f18c3556d92
9
@Override protected void drawSlot(int index, int xPosition, int yPosition, int l, Tessellator tessellator) { int width = 70; int height = 20; xPosition -= 20; boolean flag = _mouseX >= xPosition && _mouseY >= yPosition && _mouseX < xPosition + width && _mouseY < yPosition + height; int k = (flag ? 2 : 1); GL11.glBindTexture(3553 /*GL_TEXTURE_2D*/, mc.renderEngine.getTexture("/gui/gui.png")); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); controls.drawTexturedModalRect(xPosition, yPosition, 0, 46 + k * 20, width / 2, height); controls.drawTexturedModalRect(xPosition + width / 2, yPosition, 200 - width / 2, 46 + k * 20, width / 2, height); controls.drawString(mc.fontRenderer, options.getKeyBindingDescription(index), xPosition + width + 4, yPosition + 6, 0xFFFFFFFF); boolean conflict = false; for (int x = 0; x < options.keyBindings.length; x++) { if (x != index && options.keyBindings[x].keyCode == options.keyBindings[index].keyCode) { conflict = true; break; } } String str = (conflict ? "\247c" : "") + options.getOptionDisplayString(index); str = (index == selected ? "\247f> \247e??? \247f<" : str); controls.drawCenteredString(mc.fontRenderer, str, xPosition + (width / 2), yPosition + (height - 8) / 2, 0xFFFFFFFF); }
8a220979-e373-4f23-8298-4a6cf641f126
5
private static AncestorListener createAncestorListener( JComponent component, final WindowFocusListener windowListener) { final WeakReference<JComponent> weakReference = new WeakReference<JComponent>( component); return new AncestorListener() { public void ancestorAdded(AncestorEvent event) { // TODO if the WeakReference's object is null, remove the // WeakReference as an // TODO AncestorListener. final Window window = weakReference.get() == null ? null : SwingUtilities.getWindowAncestor(weakReference.get()); if (window != null) { window.removeWindowFocusListener(windowListener); window.addWindowFocusListener(windowListener); // notify the listener of the original focus state of the // window, which ensures // that the listener is in sync with the actual window // state. fireInitialFocusEvent(windowListener, window); } } private void fireInitialFocusEvent( WindowFocusListener windowListener, Window window) { Window focusedWindow = FocusManager.getCurrentManager() .getFocusedWindow(); // fire a fake event to the given listener indicating the actual // focus state of the // given window. if (window == focusedWindow) { windowListener.windowGainedFocus(new WindowEvent(window, WindowEvent.WINDOW_GAINED_FOCUS)); } else { windowListener.windowGainedFocus(new WindowEvent(window, WindowEvent.WINDOW_LOST_FOCUS)); } } public void ancestorRemoved(AncestorEvent event) { Window window = weakReference.get() == null ? null : SwingUtilities.getWindowAncestor(weakReference.get()); if (window != null) { window.removeWindowFocusListener(windowListener); } } public void ancestorMoved(AncestorEvent event) { // no implementation. } }; }
b0c025f6-5fbb-4c06-85d0-ca2b239067ee
5
@Test public void test_12_displayOwnGrid(){ Grid gr = new Grid(2); boolean ok = true; Ship s = new Ship ( 2, 0,0,'v'); gr.addShip(s); char[][] board = gr.displayOwnGrid(); char[][] array = new char[2][2]; for ( int i = 0 ; i < 2 ; i++){ for ( int j = 0; j < 2;j++){ array[i][j] = Grid.DEFAULT_CHAR; } } array[0][0] = 'D'; array[1][0] = 'D'; for ( int i = 0 ; i < 2 ; i++){ for ( int j = 0; j < 2;j++){ if(!(board[i][j] == array[i][j])) ok = false; } } assertTrue("It should be true", ok); }
329af103-b297-4756-a083-815a80d4c23f
8
public void acceptDataSet(DataSetEvent e) { if (m_splitThread == null) { final Instances dataSet = new Instances(e.getDataSet()); m_splitThread = new Thread() { public void run() { try { dataSet.randomize(new Random(m_randomSeed)); int trainSize = (int)Math.round(dataSet.numInstances() * m_trainPercentage / 100); int testSize = dataSet.numInstances() - trainSize; Instances train = new Instances(dataSet, 0, trainSize); Instances test = new Instances(dataSet, trainSize, testSize); TrainingSetEvent tse = new TrainingSetEvent(TrainTestSplitMaker.this, train); tse.m_setNumber = 1; tse.m_maxSetNumber = 1; if (m_splitThread != null) { notifyTrainingSetProduced(tse); } // inform all test set listeners TestSetEvent teste = new TestSetEvent(TrainTestSplitMaker.this, test); teste.m_setNumber = 1; teste.m_maxSetNumber = 1; if (m_splitThread != null) { notifyTestSetProduced(teste); } else { if (m_logger != null) { m_logger.logMessage("[TrainTestSplitMaker] " + statusMessagePrefix() + " Split has been canceled!"); m_logger.statusMessage(statusMessagePrefix() + "INTERRUPTED"); } } } catch (Exception ex) { stop(); // stop all processing if (m_logger != null) { m_logger.statusMessage(statusMessagePrefix() + "ERROR (See log for details)"); m_logger.logMessage("[TrainTestSplitMaker] " + statusMessagePrefix() + " problem during split creation. " + ex.getMessage()); } ex.printStackTrace(); } finally { if (isInterrupted()) { if (m_logger != null) { m_logger.logMessage("[TrainTestSplitMaker] " + statusMessagePrefix() + " Split has been canceled!"); m_logger.statusMessage(statusMessagePrefix() + "INTERRUPTED"); } } block(false); } } }; m_splitThread.setPriority(Thread.MIN_PRIORITY); m_splitThread.start(); // if (m_splitThread.isAlive()) { block(true); // } m_splitThread = null; } }
3b81bd1f-247f-4693-98af-392f0e3bd624
2
private Collection<String> getCutSet(Collection<String> networkMembers) { synchronized(keychain) { ArrayList<String> cutSet = new ArrayList<String>(); // networkMembers might be bigger than keychain.keySet() // but lookups are faster in HashMaps than in Collections. for(String s: networkMembers) { if(keychain.containsKey(s)) { cutSet.add(s); } } return cutSet; } }
a76081dd-cd21-4713-af4b-fd9eb389c699
9
@Override public synchronized void broadcastRecieved(Message message) { if (updateTimeStamps(message)) { System.out.println("Message Recieved: " + message.toString()); try { switch (message.getMessageType()) { case ELECTION: startElection(); break; case ELECT: ElectionBroadcast.addElection(message); break; case DECLARE_LEADER: LEADER.setLeader(message); break; case PEER_LOST: //Tell leader to remove ip address from files SHARED_FILES.peerLost(message); break; case FIND_LEADER: //Broadcast request for who is the leader LEADER.broadcastLeader(); break; case REQUEST_SNAPSHOT: // Request snapshot to include requester's IP in message content. //DirectMessage sender Message reply = new Message(MessageType.SUPPLY_TIMESTAMP, message.getSenderIPAddress(), "Supplying Timestamp"); DirectMessage.sendDirectMessage(reply); break; case SUPPLY_TIMESTAMP: break; } } catch (UnknownHostException ex) { Logger.getLogger(PeerNode.class.getName()).log(Level.SEVERE, null, ex); } } else { System.out.println("Message Ignored: " + message.toString()); } }
3f0c833a-35b9-4ebd-9abd-a45a0bbd16e7
2
@Override public String processCommand(String[] arguments) throws SystemCommandException { String guid = facade.getCurrentUserGUID(); if (guid == null) throw new SystemCommandException("No current user set."); String result = "EID\n"; Set<Election> nominations = facade.getNominations(); for (Election nomination: nominations) result+= nomination.getEID()+"\n"; return result; }
e73ef294-aa60-4d61-bd16-1e1d38edc460
8
public static void selectPlanesByFuelConsumption(Airline airline) { logger.info("Starting planes selection... "); while (true) { logger.info(""); logger.info("Enter Fuel Consumption (press space and enter to exit): "); Scanner scanIn = new Scanner(System.in); String s = scanIn.nextLine(); if (" ".equals(s)) break; try { int fuel = 0; try { fuel = Integer.parseInt(s); } catch (Exception e) { throw new WrongInputException(e); } boolean found = false; for (Plane plane : airline.getPlanes()) { if (fuel < plane.getFuelConsumtion()) { found = true; logger.info("Your match is " + plane.getName() + "; fuel consumption: " + plane.getFuelConsumtion()); } } if (!found) { throw new NoFlightFoundException(); } } catch (NoFlightFoundException e) { logger.info("No planes found matching your criteria. Try again."); } catch (WrongInputException e) { logger.error("Incorrect input, try again", e); } } logger.info("Plane selection finished."); }
def7a506-6c0d-478e-8114-8863ff282bec
3
@EventHandler public void onReloadPlayer(PlayerCommandPreprocessEvent e){ if(e.getMessage().equalsIgnoreCase("/reload") && e.getPlayer().isOp()){ for(Player p : Bukkit.getOnlinePlayers()){ p.kickPlayer("[RP] Plugin is reloading!"); } } }
47773a5b-3dca-4938-b394-4ae5bc74295e
1
public static Bank getInstance() { if(bank == null) { bank = new Bank(); System.out.println("Create one Instance !"); } return bank; }
ed85f5da-90a3-4f89-8228-c7fbc3ca1ad1
2
public void testFactory_Zone_int() { GregorianChronology chrono = GregorianChronology.getInstance(TOKYO, 2); assertEquals(TOKYO, chrono.getZone()); assertEquals(2, chrono.getMinimumDaysInFirstWeek()); try { GregorianChronology.getInstance(TOKYO, 0); fail(); } catch (IllegalArgumentException ex) {} try { GregorianChronology.getInstance(TOKYO, 8); fail(); } catch (IllegalArgumentException ex) {} }
c7f91e1b-507f-4b1b-b69d-02b4404d5065
3
public double function( double i ) { switch( type ) { case 1: return function_hill_valley(i); case 2: return function_downhill(i); case 3: return function_stairs(i); default: return 0; } }
c62b54d0-9217-4bca-9901-f4212bd7ddea
5
private void getColumns(File[] folderList) { try { addHeaders(); } catch (WriteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } for (File valuesVersion : folderList) { System.out.println("Parsing xml from " + valuesVersion.getName() + "\n"); if (valuesVersion.isDirectory()) { File stringsDotXml = new File(valuesVersion, "strings.xml"); Document document = Utils.getXmlFromFile(stringsDotXml); NodeList nodes = document.getElementsByTagName("string"); for (int i = 0; i < nodes.getLength(); i++) { Node item = nodes.item(i); String key = "" + item.getAttributes().getNamedItem("name"); // System.out.println(key); // addCell(excellSheet, 0, i + 1, key); addColumn(key); } System.out.println(keysList.size()); // excellFile.write(); } } }
a0f2584f-42c0-411f-a941-6be1d5eebf51
6
public final boolean isSyncMark(int headerstring,int syncmode,int word) { if (syncmode == INITIAL_SYNC) { sync = ((headerstring & 0xFFF00000) == 0xFFF00000); } else { sync = ((headerstring & 0xFFF80C00) == word) && (((headerstring & 0x000000C0) == 0x000000C0) == single_ch_mode); } // filter out invalid sample rate if(sync) if(sync = (((headerstring >>> 10) & 3) != 3)) if(sync = (((headerstring >>> 17) & 3) != 0)) sync = (((headerstring >>> 19) & 3) != 1); if(sync) first_sync = true; return sync; }
01c2d19d-a86a-466b-8265-893c14acf8b0
3
public static DAOFactory getInstance() throws DAOException { Properties properties = new Properties(); String url; String driver; String user; String password; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream fileProperties = classLoader.getResourceAsStream(FILE_PROPERTIES); if (fileProperties == null) { throw new DAOException("Le fichier properties " + FILE_PROPERTIES + " est introuvable."); } try { properties.load(fileProperties); url = properties.getProperty(PROPERTY_URL); driver = properties.getProperty(PROPERTY_DRIVER); user = properties.getProperty(PROPERTY_USER); password = properties.getProperty(PROPERTY_PASS); } catch (IOException e) { throw new DAOException("Impossible de charger le fichier properties " + FILE_PROPERTIES, e); } try { Class.forName(driver); } catch (ClassNotFoundException e) { throw new DAOException("Le driver est introuvable dans le classpath.", e); } /* * Enrégistrement du pool créé dans une variable d'instance via un appel au constructeur de * DAOFactory. */ DAOFactory instance = new DAOFactory(url, user, password); return instance; }
61de2cb7-015c-43a9-bb01-4a84b3aab52d
7
@SuppressWarnings("unchecked") @Test public void testFPL() { SimpleValidator simpleValidator = new SimpleValidator(); DateRangeBean bean; Set<?> validations; for (int minutes = -45; minutes <= (120 * 60); minutes += 5) { bean = new DateRangeBean(); bean.setDate12(util.add(new Date(), Calendar.MINUTE, minutes)); validations = simpleValidator.validate(bean); TestUtil.assertValid((Set<ConstraintViolation<?>>) validations); } for (int minutes = -60; minutes < -45; minutes += 1) { bean = new DateRangeBean(); bean.setDate12(util.add(new Date(), Calendar.MINUTE, minutes)); validations = simpleValidator.validate(bean); TestUtil.assertValid((Set<ConstraintViolation<?>>) validations, "date12"); } for (int minutes = (120 * 60 + 1); minutes < (120 * 60 + 10); minutes += 1) { bean = new DateRangeBean(); bean.setDate12(util.add(new Date(), Calendar.MINUTE, minutes)); validations = simpleValidator.validate(bean); TestUtil.assertValid((Set<ConstraintViolation<?>>) validations, "date12"); } }
bfa012be-bee0-47fa-9219-5824690b13ad
9
public Message dequeueMessage(int reqClientId, int partSenderId, int queueId, boolean peek) throws MessageDequeueException, MessageDequeueQueueDoesNotExistException, MessageDequeueEmptyQueueException, MessageDequeueNotIntendedReceiverException { if (!(queueId == 0 && partSenderId == 0)) { try { CallableStatement callStat = _connection.prepareCall("{ call dequeueMessage(?,?,?,?) }"); callStat.setInt(1, reqClientId); callStat.setInt(2, partSenderId); callStat.setInt(3, queueId); if (peek) { callStat.setInt(4, 1); } callStat.setInt(4, 0); long startTime = System.nanoTime(); ResultSet resSet = callStat.executeQuery(); long stopTime = System.nanoTime(); _EVALLOG6.log(startTime + "," + stopTime + ",DB_QUERY_DEQUEUE"); resSet.next(); // if result set is empty we get an exception Message message = DBModelFactory.createMessage(resSet.getInt(1), resSet.getInt(2), resSet.getInt(3), resSet.getInt(4), resSet.getTimestamp(5), resSet.getString(6)); resSet.close(); callStat.close(); return message; } catch (SQLException e) { if (e.getSQLState().equals("V2007")) { throw new MessageDequeueQueueDoesNotExistException(e); } else if (e.getSQLState().equals("V2008")) { throw new MessageDequeueEmptyQueueException(e); } else if (e.getSQLState().equals("V2009") || e.getSQLState().equals("V2010") || e.getSQLState().equals("V2011")) { throw new MessageDequeueNotIntendedReceiverException(e); } throw new MessageDequeueException(new Exception()); } } else { throw new MessageDequeueException(new Exception()); } }
fc064a98-7e5f-4963-a5cd-f6722acea263
1
private void init(ByteBuffer buffer) { compression = buffer.get() & 0xff; int compressedSize = buffer.getInt(); if (compression == 0) { size = compressedSize; } else { size = buffer.getInt(); } this.buffer = new byte[compressedSize]; buffer.get(this.buffer); }
aa8affe1-e8b8-4f1c-8123-982bff54b901
6
private void checkAllCollsions() { try { for (Projectile pj : projectiles) { pj.update(); for (Player pl : players) { if (!pl.getName().equalsIgnoreCase(pj.getPlayername())) { if (pl.isAlive()) { pj.checkCollision(pl); } } } } } catch (ConcurrentModificationException e) { checkAllCollsions(); } catch (NullPointerException e) { checkAllCollsions(); } }
36aab7db-cc32-4c4f-9fb7-73f70669659a
8
protected void readAutoAffects(MOB mob, Session S, String name) { if(S!=null) { if(CMSecurity.isAllowed(mob, mob.location(),CMSecurity.SecFlag.CMDMOBS)) { if(name.length()>0) { final Physical P=mob.location().fetchFromMOBRoomFavorsItems(mob,null,name,Wearable.FILTER_ANY); if(P==null) S.colorOnlyPrint(L("You don't see @x1 here.",name)); else { if(S==mob.session()) S.colorOnlyPrint(L(" \n\r^!@x1 is affected by: ^?",P.name())); final String msg=getAutoAffects(mob,P); if(msg.length()<5) S.colorOnlyPrintln(L("Nothing!\n\r^N")); else S.colorOnlyPrintln(msg); } return; } } if(S==mob.session()) S.colorOnlyPrint(L(" \n\r^!Your auto-invoked skills are:^?")); final String msg=getAutoAffects(mob,mob); if(msg.length()<5) S.colorOnlyPrintln(L(" Non-existant!\n\r^N")); else S.colorOnlyPrintln(msg); } }
093078d8-7172-457a-b2ed-4a35d326d111
1
@Override public void showMafia(String[] players) { createMafiaList(30, 100); for (String player : players) { defaultPlayersList.addElement(player); } panel.revalidate(); panel.repaint(); }
1af54e22-1f95-402c-917e-9076a17b7c97
1
public JSONArray getJSONArray(String key) throws JSONException { Object object = this.get(key); if (object instanceof JSONArray) { return (JSONArray) object; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); }
8ea858b8-029d-4333-a433-0cfe22d87fab
8
public static void main(String[] args) { FileInputStream fstream; try { fstream = new FileInputStream(new File("oliveOilsTEST.dat")); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; File outfile = new File("oliveOilsTEST.nn"); FileWriter writer = new FileWriter(outfile ,true); Pattern pat = Pattern.compile("(\\d*\\.\\d+) (\\d*\\.\\d+) (\\d*\\.\\d+) (\\d*\\.\\d+) (\\d*\\.\\d+) (\\d*\\.\\d+) (\\d*\\.\\d+) (\\d*\\.\\d+) (\\d) (\\d) (\\d) (\\d) (\\d) (\\d) (\\d) (\\d) (\\d)"); writer.write("G BEGINGROUP OilTest" + System.getProperty("line.separator")); while ((strLine = br.readLine()) != null) { Matcher mat = pat.matcher(strLine); if(mat.find()) { for(int i = 1; i < 18; i++) { if(i == 1) { writer.write("G IN"); } if(i < 9) { writer.write(" " + mat.group(i)); } if (i == 8) { writer.write(System.getProperty("line.separator") + "G OUT"); } if( i > 8) { writer.write(" " + mat.group(i)); } } writer.write(System.getProperty("line.separator")); //System.out.println("found " + mat.groupCount() + " groups"); } } writer.write("G END" + System.getProperty("line.separator")); writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); } }
d1e402f4-d770-4dae-b909-e324282a4936
2
@Override public int compareTo(AstronomicalObject o) { return (this.mass < o.mass) ? -1 : (this.mass > o.mass) ? 1 : 0; }
e057dbbc-8fa4-4276-be0d-593456ce9a02
1
private String loadKeyOfOrientation(String value) { if (orientationMap == null) { orientationMap = new HashMap<String, String>(); orientationMap.put(propertiesLoader.loadProperty(Orientation.EAST.getKey()), Orientation.EAST.getKey()); orientationMap.put(propertiesLoader.loadProperty(Orientation.NORTH.getKey()), Orientation.NORTH.getKey()); orientationMap.put(propertiesLoader.loadProperty(Orientation.SOUTH.getKey()), Orientation.SOUTH.getKey()); orientationMap.put(propertiesLoader.loadProperty(Orientation.WEST.getKey()), Orientation.WEST.getKey()); } return orientationMap.get(value); }
e3bc415f-76d7-4cdf-a74f-bc3ae8e4a3c6
2
public void printGraph() { for (int i = 0; i < this.vertices.size(); i++) { DirectedNode vertex = this.vertices.get(i); String edges = ""; for (int j = 0; j < vertex.edgeNodes.size(); j++) { edges += vertex.edgeNodes.get(j).data + ", "; } System.out.println("Vertex " + vertex.data + " connects with: " + edges); } }
7f582e1e-d194-4ff6-9bee-ccc3f5c1ca40
7
public static Keyword tryRefutationProof(ControlFrame frame) { { ParallelThread parallelthread = ((QueryIterator)(Logic.$QUERYITERATOR$.get())).currentParallelThread; ParallelControlFrame parallelframe = ((ParallelControlFrame)(parallelthread.topControlFrame.up)); if (parallelframe.unboundVariablesP) { return (Logic.KWD_FAILURE); } ParallelControlFrame.enterHypotheticalWorld(parallelframe); try { { boolean negatedtruthvalueP = frame.reversePolarityP; { Proposition prop = null; Cons iter000 = Proposition.inheritAsTopLevelProposition(frame.proposition, null); for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { prop = ((Proposition)(iter000.value)); if ((Stella.$TRACED_KEYWORDS$ != null) && Stella.$TRACED_KEYWORDS$.membP(Logic.KWD_GOAL_TREE)) { { System.out.println(); System.out.println(" Assume that " + prop + " is " + ((negatedtruthvalueP ? "true" : "false")) + "."); } ; } Proposition.recursivelyFastenDownPropositions(prop, false); Proposition.assignTruthValue(prop, (negatedtruthvalueP ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER)); } } } } catch (Clash e000) { return (Logic.KWD_FINAL_SUCCESS); } return (Logic.KWD_FAILURE); } }
00d49b4a-de0b-46c0-bea6-7aece81344bd
8
public boolean equalsTo(WikiTalkPage page) { if (!page.getTitle().equals(pageTitle)) { return false; } if (!page.getPageId().equals(pageId)) { return false; } if (!page.getPageText().equals(pageText)) { return false; } if (!page.getRevisionTimestamp().equals(revisionTimestamp)) { return false; } if (!page.getRevisionId().equals(revisionId)) { return false; } if (!page.getRevisionComment().equals(revisionComment)) { return false; } if (!page.getRevisionContributor().equals(revisionContributor)) { return false; } if (!page.getRevisionContributorId().equals(revisionContributorId)) { return false; } return true; }
4da68819-4f40-4b33-ac91-c0152b75f7a7
3
public void widgetChanged(JComponent widget){ super.widgetChanged(widget); if (widget == sizeControlGroup){ controller.setSize(sizeControlGroup.getCurrentValue()); } if(widget == xControlGroup){ controller.setXposition(xControlGroup.getCurrentValue()); } if (widget == yControlGroup){ controller.setYposition(yControlGroup.getCurrentValue()); } drawPanel.repaint(); }
bbbb654e-0c0c-4925-bf22-82d3ac8d9edc
5
public OMGraphicList createGraphics(OMGraphicList graphics, Map<String, List> routes, String selectedRoute) { graphics.clear(); Stroke stroke = new BasicStroke(2); if(routes != null){ Iterator iterator = routes.keySet().iterator(); while(iterator.hasNext()){ String routeName = (String)iterator.next(); Iterator points = ((List)routes.get(routeName)).iterator(); if(!points.hasNext()) return graphics; RoutePoint point1 = (RoutePoint)points.next(); // OMPoint location = new OMPoint(point1.getLatitude(), point1.getLongitude(), 2); // graphics.addOMGraphic(location); Color trackColor = Color.BLUE; if(routeName.equals(selectedRoute)) trackColor = Color.RED; while(points.hasNext()){ RoutePoint point2 = (RoutePoint)points.next(); // location = new OMPoint(point2.getLatitude(), point2.getLongitude(), 2); OMLine line = createLine(point1.getLatitude(), point1.getLongitude(), point2.getLatitude(), point2.getLongitude(), trackColor); line.setStroke(stroke); graphics.addOMGraphic(line); // graphics.addOMGraphic(location); point1 = point2; } } } return graphics; }
1d635f71-3af5-4551-8073-c8da966caa92
2
public static void main(String[] args) throws FileNotFoundException{ File f = new File("src/Median.txt"); Scanner s = new Scanner(f); while(s.hasNext()){ input.add(s.nextInt()); Collections.sort(input); size = input.size(); if(size%2 == 0){ size = size/2; size--; }else{ size = (size+1)/2; size--; } counter = counter + input.get(size); } System.out.print(counter); }
e5b6f79c-351f-411b-a45b-24c6e170c5f9
8
public int maximalRectangle(char[][] matrix) { int m = matrix.length; if (m < 1) return 0; int n = matrix[0].length; if (n < 1) return 0; int[] H = new int[n]; int[] L = new int[n]; int[] R = new int[n]; for (int i = 0; i < n; i++) R[i] = n; int res = 0; for (int i = 0; i < m; i++) { int left = 0, right = n; for (int j = 0; j < n; ++j) { if (matrix[i][j] == '1') { ++H[j]; L[j] = Math.max(L[j], left); // 和上层一起选出短板 } else { left = j + 1; H[j] = 0; L[j] = 0; } } for (int j = n - 1; j >= 0; j--) { if (matrix[i][j] == '1') { R[j] = Math.min(R[j], right); res = Math.max(res, H[j] * (R[j] - L[j])); // 和上层一起选出短板 } else { right = j; R[j] = n; } } } return res; }
c56376e6-3922-449e-a18a-754a3fcf8be6
3
public void calculateTemp() { if (this.constantTemp) { return; } long result = 0; long tmp = 0; for (int i = 0; i < thermalConstants.length; i++) { for (int j = 0; j < neighbors.size(); j++) { tmp += (neighbors.get(j).getTemp() * (neighbors.get(j).getMetalPercentage(i))); } tmp = ((((long) (thermalConstants[i] * 100)) * tmp) / 100) / neighbors.size(); result += tmp; tmp = 0; } sa.temps[sa.updating][indexI][indexJ] = result; }
173ff380-0b95-4578-9a92-f2df9d86d281
3
@Override public String toString() { if (header.length() <= 0) return ""; // Delete last character, if it's a '\n' or a '\r' for (char c = header.charAt(header.length() - 1); (c == '\n') || (c == '\r'); c = header.charAt(header.length() - 1)) header.deleteCharAt(header.length() - 1); return header.toString(); }
caf0bcb4-7cf6-4827-8c2b-7ebec171fa7f
9
private void rightChoice() { // Controlla se i Tile selezionati rappresentano una mossa valida int X0 = humanStep[0].getx(); int Y0 = humanStep[0].gety(); int X1 = humanStep[1].getx(); int Y1 = humanStep[1].gety(); if(expectedCell()){ //se la mossa e' corretta la eseguo Step temp=null; for(Step temporary:validatedSteps) if(temporary.getEnd().getX() == X1 && temporary.getEnd().getY() == Y1) temp=temporary; executor.execute(board, temp); boardButton[X0][Y0].setPressed(false); lightValidStep(validatedSteps, false); boardButton[X1][Y1].setPressed(false); refresh(false); if(temp.getEatablePawn() > 0 && eatenByHuman<2 ){ refresh(true); eatenByHuman++; humanStep[0]=humanStep[1]; //reset della mossa utente per proseguire con la mangiata consecutiva X0=X1; Y0=Y1; humanStep[1]=null; boardButton[X0][Y0].setPressed(true); //non devo poter spegere questo bottone boardButton[X0][Y0].lock(); forceNextStep=true; validatedSteps= new ValidStepsList(board, X0, Y0); //creo una validStepList vuota Cell thisCell= board.getCell(X0, Y0); validatedSteps.uiValidator(X0, Y0, 0, null, thisCell); //aggiungo le mosse valide alla lista if(!validatedSteps.isEmpty()){ // se posso ancora mangiare lightValidStep(validatedSteps, true); } else{ StartThread(); } } else{ StartThread(); } } else if( board.getCell(X1, Y1).getPawn()==null){ //se non c'e' una pedina spegne il Tile boardButton[X1][Y1].setPressed(false); boardButton[X1][Y1].setBorder(null); humanStep[1]=null; } // se le pedine sono entrambe bianche spegne la prima ed evidenzia la seconda else if ( board.getCell(X1, Y1).getColorPawn() == board.getCell(X0, Y0).getColorPawn() ) { lightValidStep(validatedSteps, false); boardButton[X0][Y0].setPressed(false); humanStep[0] = humanStep[1]; humanStep[1] = null; X0=X1; Y0=Y1; validatedSteps=new ValidStepsList( board, X0, Y0, false); lightValidStep(validatedSteps , true); } }
74924e8e-b4a7-4536-93bd-e86ac8e0f741
9
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; a[0] = 1; a[1] = 2; TreeSet<Integer> occu = new TreeSet<Integer>(); occu.add(3); for (int i = 2; i < n; i++) { for (int j = a[i-1] + 1; j <= 1000; j++) { boolean found = true; for (int k = 0; k < i; k++) { if (occu.contains(j + a[k])) { found = false; break; } } if (found) { a[i] = j; for (int k = 0; k < i; k++) { occu.add(a[i] + a[k]); } break; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.printf("%d ", (i == j ? 0 : a[i] + a[j])); } System.out.println(); } }
31d34e04-927d-417d-95a0-bd8edd6f1c0c
3
private static void readFile() { String readLine = null; try { BufferedReader bufferedReader = new BufferedReader(new FileReader( dataFile)); while ((readLine = bufferedReader.readLine()) != null) { String[] splitContent = readLine.split(" ", 2); if (splitContent.length > 1) events.add(splitContent[1]); else events.add(splitContent[0]); } bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); } }
5eb421da-e3b4-4d43-a72f-107ed2bac033
0
public void setParagraph(String paragraph) { this.paragraph=paragraph; }
8d9ea16c-23eb-476f-ac7e-760d860082b8
5
public Author getAuthor(int id) { Author aut = null; Connection con = null; Statement stmt = null; try { DBconnection dbCon = new DBconnection(); Class.forName(dbCon.getJDBC_DRIVER()); con = DriverManager.getConnection(dbCon.getDATABASE_URL(), dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD()); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select * From author Where aut_id=" + id); if (rs.next()) { aut = new Author(); aut.setId(rs.getInt(1)); aut.setName(rs.getString(2)); } } catch (SQLException | ClassNotFoundException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } } return aut; }
0fed6a82-067b-4640-8523-fc36922bfeb2
0
public void reset() { start(); }
a41972a3-3ea6-4fe7-b85e-a5f1f8245c0b
7
private boolean isIncluded(Color target, Color pixel) { int rT = target.getRed(); int gT = target.getGreen(); int bT = target.getBlue(); int aT = target.getAlpha(); int rP = pixel.getRed(); int gP = pixel.getGreen(); int bP = pixel.getBlue(); int aP = pixel.getAlpha(); return( (rP<=rT) && (rT<=rP) && (gP<=gT) && (gT<=gP) && (bP<=bT) && (bT<=bP) && (aP<=aT) && (aT<=aP) ); }
0ff04434-6760-4db7-9d41-52736463d5c9
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); } }); }
508f1866-510e-4786-96f0-38d68d5bab64
5
public void setSystemConditionToAll(ElementSystem e, Condition l) { if (e == null) throw new NullPointerException("The ElementSystem is null."); if (l == null) throw new NullPointerException("The condition is null."); RETW(defaultEngineLock, () -> { systemConditions.keySet().forEach(p -> { if (p.first.equals(p.last) && (p.first.equals(e.getID()) || p.last.equals(e.getID()))) systemConditions.put(p, l); }); }); }
0afc604e-b248-4eef-b32d-9958e1c68a66
3
private int pickFruit(float[] currentFruits) { // generate a prefix sum float[] prefixsum = new float[NUM_FRUIT_TYPES]; prefixsum[0] = currentFruits[0]; for (int i = 1; i != NUM_FRUIT_TYPES; ++i) { prefixsum[i] = prefixsum[i-1] + currentFruits[i]; } float currentFruitCount = prefixsum[NUM_FRUIT_TYPES - 1]; // roll a dice [0, currentFruitCount) int rnd = random.nextInt((int) currentFruitCount); for (int i = 0; i != NUM_FRUIT_TYPES; ++i) if (rnd < prefixsum[i]) return i; assert false; return -1; }
46bb27d1-6ac0-46e9-b5eb-125f50d22df4
9
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); RequestDispatcher erd = request.getRequestDispatcher("WEB-INF/register_error.jsp"); SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy"); Date from_date; Date to_date; try { from_date = sdf.parse(request.getParameter("from_date")); to_date = sdf.parse(request.getParameter("to_date")); } catch (Exception e) { request.setAttribute("error", "Invalid date values."); erd.forward(request, response); return; } String date_error = CabinetUtils.ValidateBookingDates(from_date, to_date); if(date_error != null) { request.setAttribute("error", date_error); erd.forward(request, response); return; } int cabin_id; try { cabin_id = Integer.parseInt(request.getParameter("cabins")); } catch (NumberFormatException e) { request.setAttribute("error", "No cabin selection."); erd.forward(request, response); return; } if((cabin_id < 1) || (cabin_id > 23)) { request.setAttribute("error", "Invalid cabin selection."); erd.forward(request, response); return; } String email = request.getParameter("email"); if(email == null || email.isEmpty()) { request.setAttribute("error", "Invalid e-mail."); erd.forward(request, response); return; } int booking_id = -1; if(CabinetUtils.BookingCollides(cabin_id, from_date, to_date)) { request.setAttribute("error", "Booking period collides with an existing booking."); erd.forward(request, response); return; } else { Database db = new Database(); Booking booking = new Booking(); booking.setCabin_id(cabin_id); booking.setDate_From(from_date); booking.setDate_To(to_date); booking.setUser_id(email); booking_id = db.addBooking(booking); db.close(); } if(cabin_id < 0) { request.setAttribute("error", "Unknown error booking."); erd.forward(request, response); return; } RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/register_confirmation.jsp"); request.setAttribute("booking_id", booking_id); rd.forward(request, response); return; }
af0db176-2719-441e-8e02-18a7305f03ae
4
public final void startElement( final String ns, final String lName, final String qName, final Attributes list) throws SAXException { // the actual element name is either in lName or qName, depending // on whether the parser is namespace aware String name = lName == null || lName.length() == 0 ? qName : lName; // Compute the current matching rule StringBuffer sb = new StringBuffer(match); if (match.length() > 0) { sb.append('/'); } sb.append(name); match = sb.toString(); // Fire "begin" events for all relevant rules Rule r = (Rule) RULES.match(match); if (r != null) { r.begin(name, list); } }
d5717978-3515-418a-a92c-701e2399e02f
5
private ARObject searchBooking(int resID, int reservID) { ARObject data = null; boolean found = false; try { Iterator it = booking_.iterator(); while ( it.hasNext() ) { data = (ARObject) it.next(); if (data.getReservationID() == reservID && data.getResourceID() == resID) { found = true; break; } } } catch (Exception e) { found = false; System.out.println(super.get_name() + ": Error - can't search reservation booking."); } if (found == false) { data = null; } return data; }
96ec7b7a-6a8f-4a59-b482-0c3b5a2317eb
2
public void openInBrowser(String url) { try { Desktop.getDesktop().browse(new URI(url)); } catch (IOException e) { } catch (URISyntaxException e) { } }
0efd55ac-4c3e-410e-873b-09373bba9d74
3
public void generateMapOutside() { /** * This method is not finished yet. It creates the outline of the map */ for (int i = 1; i <= averageSideWater; i++) { for (int k = 1; k <= i; k++) { for (int l = i; l >= k; l--) { map[i - k][i - l] = Tile.water; } } } }
b7da7025-8c34-471e-8d04-db339adbdaa1
4
public void mousePressed(int button,int x,int y){ click.play(); int i; i = Checkhit(); if(i < 3){ score += 1; if(buttons[i].getOvalHeight() >= buttonPress.getHeight() && buttons[i].getOvalHeight() <= buttonPress.getHeight()+5){ score += 4; } buttons[i].resetOval(); } if(hitBonus()){ score += 20; bonusButton.resetOval(); } }
2038f652-0c5d-454b-9f96-16c5e4e263d8
3
private void func_885_a(int var1, int var2, int var3, int var4) { if(!this.func_886_c(var1, var2, var3, var4)) { for(int var5 = var1; var5 < var3; ++var5) { for(int var6 = var2; var6 < var4; ++var6) { this.imageData[var5 + var6 * this.imageWidth] &= 16777215; } } } }
70efaaf2-9bd8-4025-985e-a6826e7794af
0
public void setName(String name) { this.name = name; }
3186d0c8-5804-49cd-a284-c00bb0c01e9b
2
private final void getMP3Tag(File song) throws MP3Exception, UnsupportedAudioException { try { this.audioFile = AudioFileIO.read(song); this.tag= audioFile.getTag(); // all of these values are just stored in the attributes of this class. this.songTitle= this.tag.getFirstTitle(); this.albumName= this.tag.getFirstAlbum(); this.artistName= this.tag.getFirstArtist(); } catch (CannotReadException e) { throw new UnsupportedAudioException("CannotReadException "+e.getMessage(), e); } catch (Exception e) { throw new MP3Exception("Exception during setMp3Tag"); } }
e364f475-936b-4954-afe8-77882859c652
4
public void setFiglio(Albero<T> a, int pos) { if ((pos >= numMaxFigli) || (pos < 0)) throw new ArrayIndexOutOfBoundsException(); if (a == null) return; if (a.gradoMax() != gradoMax()) throw new AlberiDiversiException(); figli.set(pos, a); a.setPadre(this); a.setPos(pos); }
ac51428e-9407-4481-88f7-61931a48656b
4
public static String[] read(String filetype) { String strFile = filetype; String[] Blah = null; int filelength=0; try { filelength = count(strFile); } catch (IOException e1) { e1.printStackTrace(); } File file = new File(strFile); if (file.exists() == true) { //System.out.println("Loading..."); try{ Scanner Read = new Scanner(file); for(int i=0; i < filelength;i++) { Blah[i] = Read.nextLine(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } else { System.out.println("ERROR! CONFIG FILE MISSING"); } return Blah; }
ffa40106-b28a-4c2e-9fb2-5a4aa4003738
8
public static void main(String... args) throws IOException{ final int WIDTH=1000,HEIGHT=800,OCTAVES=10; final double PERSISTENCE = 0.6; final float WAVELENGTH = 100f; PerlinImage p = new PerlinImage(3, PERSISTENCE, OCTAVES,WAVELENGTH,WIDTH,HEIGHT,1.2); BufferedImage i = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); long start = System.currentTimeMillis(); for(int y=0;y<HEIGHT;y++){ for(int x=0;x<WIDTH;x++){ double b = p.getNoiseAt(x, y); //System.out.println(b); if(b > 0 && b < 1){ i.setRGB(x, y, new Color(0f,b > 0.2 ? (float) b : b > 0.1 ? (float) b*0.5f : 0f ,b <= 0.2 ? 0.7f : b > 0.4 ? (float) 0.5f : 0.0f).getRGB()); } } } System.out.println("Generation completed in " + (System.currentTimeMillis() - start) + " ms"); ImageIO.write(i, "png", new File("/home/george/Desktop/anotherperlin.png")); }
d7b1f97e-bcc2-42b2-bdeb-ed7de400cb28
6
public synchronized BufferedImage optimized( Getter<BufferedImage> imageSource, int w, int h ) throws ResourceNotFound { //if( image.getWidth() == w && image.getHeight() == h ) return image; synchronized(this) { if( scales == null ) scales = new ArrayList<SoftReference<BufferedImage>>(); } synchronized(scales) { for( SoftReference<BufferedImage> scaleRef : scales ) { BufferedImage scale = scaleRef.get(); if( scale != null && scale.getWidth() == w && scale.getHeight() == h ) return scale; } } BufferedImage image = getImage(imageSource); BufferedImage scale = new BufferedImage(w, h, isCompletelyOpaque(imageSource) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D)scale.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.drawImage( image, 0, 0, w, h, 0, 0, image.getWidth(), image.getHeight(), null); synchronized( scales ) { // TODO: fill in one of the empty spaces scales.add(new SoftReference<BufferedImage>(scale)); } return scale; }
34efcfdb-8a08-4afa-b5b1-9deb4100272f
1
public void visitArrayLengthExpr(final ArrayLengthExpr expr) { if (isLeaf(expr.array())) { firstOrder = true; } }
96448271-bc3c-4273-ab28-f58bdac02bce
2
public String peek() { try { // System.out.println("Starting peek..."); if(stack.size() == 0) { // System.out.println("Returned empty string..."); return ""; } // System.out.println("Returned something real..."); return stack.get(stack.size() - 1); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(stack.size()); } return null; }
7a75044f-78e2-49fe-aab5-60560afc9ac8
1
@Override public void paint(Graphics g, JComponent c) { int tabPlacement = tabPane.getTabPlacement(); Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON); Insets insets = c.getInsets(); Dimension size = c.getSize(); if (tabPane.getTabPlacement() == TOP) { g2d.drawImage(tab, insets.left, insets.top, size.width - insets.right - insets.left, calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight), null); } /*System.out.println("Tab Height"+calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight));*/ super.paint(g2d, c); }
88a91160-6ee8-46a5-b3cf-11ef5cbe0239
6
private static void test1() { Trace trace1 = new Trace (1, 2, 1); FESVo.putTrace(trace1); Trace trace2 = new Trace (1, 4, 1); FESVo.putTrace(trace2); Feature feature1 = new Feature (1, 2, 2); feature1.addW(10); FESVo.putHorizon(feature1); Feature feature2 = new Feature (1, 2, 3); FESVo.putHorizon(feature2); Feature feature3 = new Feature (1, 2, 2); feature3.addW(20); FESVo.putHorizon(feature3); for(GeoTag tag : FESVo.DATA.keySet()) { System.out.println(tag); } for(Integer sourceID : FESVo.SOURCE_IDs.keySet()) { System.out.println(sourceID); } System.out.println("w values in (1,2,2)"); for(int w : ((Feature)(FESVo.DATA.get(new GeoTag(1,2,2)))).getAllWs()) { System.out.println(w); } boolean bool1 = FESVo.DATA.containsKey(trace1.geoTag); GeoTag tag = new GeoTag(1, 2, 1); boolean bool3 = tag.equals(trace1.geoTag); boolean bool2 = FESVo.DATA.containsKey(tag); System.out.println("sourceIDs:"); for (int i : FESVo.getSourceIDs()) { System.out.println(i + ": " + FESVo.getDataType(i)); } System.out.println("sourceIDs of type Trace:"); for (int i : FESVo.getSourceIDs(DataType.TRACE)) { System.out.println(i); } System.out.println("sourceIDs of type Horizon:"); for (int i : FESVo.getSourceIDs(DataType.HORIZON)) { System.out.println(i); } FESVo.setMetadata(1, new SeismicMetadata(999, 8, 4, 0, 1000)); System.out.println("Seismic Meta-Data for ID 1: " + FESVo.getMetadata(1)); System.out.println("Seismic Meta-Data for ID 2: " + FESVo.getMetadata(2)); }
a8e3b9e2-a96e-4876-9e15-c91b11478b69
8
private static void removeThreshold(List<String> otuNames, List<List<Double>> dataPointsUnNormalized, double threshold) { List<Boolean> removeList = new ArrayList<Boolean>(); for (int x = 0; x < otuNames.size(); x++) { int sum = 0; for (int y = 0; y < dataPointsUnNormalized.size(); y++) { sum += dataPointsUnNormalized.get(y).get(x); } if (sum <= threshold) removeList.add(true); else removeList.add(false); } for (int y = 0; y < dataPointsUnNormalized.size(); y++) { int x = 0; for (Iterator<Double> i = dataPointsUnNormalized.get(y).iterator(); i .hasNext();) { i.next(); if (removeList.get(x)) i.remove(); x++; } } int x = 0; for (Iterator<String> i = otuNames.iterator(); i.hasNext();) { i.next(); if (removeList.get(x)) i.remove(); x++; } }
22eec063-cbea-4c1c-ae0e-9038e1e1f7c8
2
protected TokenState getNextState() { String[] line = getNextLine(); TokenState state = new TokenState(line[1], line[line.length-1].equals("yes")); for (int i = 2; i < line.length-1; i++) if (!line[i].equals("")) state.addDestination(getHeaderEntry(i), Integer.parseInt(line[i])); return state; }
4336821d-9b5b-4dd6-b938-34d4c06c2997
1
public void updateType() { if (!isVoid()) updateParentType(subExpressions[0].getType()); }
2f3df30f-c0da-490a-950d-44a06d4f1a1e
3
public void SetAveragePersonsWaitTime(Bus currentBus) { /* * Get the bus arrival time, for each person * (Bus 'firstTicks' - passenger 'firstTicks'), sum all difference, * and find the average */ //holds total wait times of persons int totalPassengerWaitTimes = 0; //get the bus stop iterator Iterator iter = busStop.iterator(); //iterate the bus stop while(iter.hasNext()) { //get the person Person per = ((Person)iter.next()); //sum up each person wait time totalPassengerWaitTimes += (currentBus.GetFirstTicks()-per.GetFirstTicks()); //System.out.println("Bus firstTick: "+currentBus.GetFirstTicks()+", Person firstTick: "+per.GetFirstTicks()); } if(Count()>0) { //get the average of wait times int tmpAverage = (totalPassengerWaitTimes / Count()); if(averagePersonsWaitTime != 0) { //accumulate the old and new averages and find the average averagePersonsWaitTime = (averagePersonsWaitTime + tmpAverage)/2; } else { //first average generated averagePersonsWaitTime = tmpAverage; } //System.out.println("Average person wait time: "+averagePersonsWaitTime); } }
4166fcaa-2335-4fff-8138-a147d4c4c496
1
public void setAbstract(final boolean flag) { int mod = methodInfo.modifiers(); if (flag) { mod |= Modifiers.ABSTRACT; } else { mod &= ~Modifiers.ABSTRACT; } methodInfo.setModifiers(mod); this.setDirty(true); }
8f3b64d2-58f2-4a18-8440-4fe41e2b578b
2
public static boolean isValidCardNum(String cardNum) { if (cardNum == null) return false; return cardNum.matches("\\d{16}") && cardNum.length() <= 16; }
c982e94c-c77e-4c89-95ef-26800488551c
6
public void combine(WindowSettings otherSettings) { windowSize = this.windowSize == null ? otherSettings.windowSize : this.windowSize; windowLocation = this.windowLocation == null ? otherSettings.windowLocation : this.windowLocation; horizontalDividerLocation = this.horizontalDividerLocation == 0 ? otherSettings.horizontalDividerLocation : this.horizontalDividerLocation; verticalDividerLocation = this.verticalDividerLocation == 0 ? otherSettings.verticalDividerLocation : this.verticalDividerLocation; selectedEntryTab = this.selectedEntryTab == -1 ? otherSettings.selectedEntryTab : this.selectedEntryTab; selectedExtrasTab = this.selectedExtrasTab == -1 ? otherSettings.selectedExtrasTab : this.selectedExtrasTab; }
cd8bca8c-f0c3-436b-aed0-3df21dcab82e
1
public static boolean verifySign(String certLoc, String signLoc, String file) throws IOException, GeneralSecurityException{ //adapted from http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/security/apisign/examples/VerSig.java @SuppressWarnings("resource") FileInputStream fis = new FileInputStream(certLoc); ByteArrayInputStream bis = null; byte value[] = new byte[fis.available()]; fis.read(value); bis = new ByteArrayInputStream(value); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate)certFactory.generateCertificate(bis); FileInputStream sigfis = new FileInputStream(signLoc); byte[] sigToVerify = new byte[sigfis.available()]; sigfis.read(sigToVerify); sigfis.close(); Signature sig = Signature.getInstance("SHA1withDSA", "SUN"); sig.initVerify(cert.getPublicKey()); FileInputStream datafis = new FileInputStream(file); BufferedInputStream bufin = new BufferedInputStream(datafis); byte[] buffer = new byte[1024]; int len; while (bufin.available() != 0) { len = bufin.read(buffer); sig.update(buffer, 0, len); }; bufin.close(); boolean verifies = sig.verify(sigToVerify); System.out.println("signature verifies: " + verifies); return verifies; }
7121bccf-b961-4205-b702-047d91f3ca08
4
void generarManzana() { boolean valido =true; do{ manzanaX = (int) (Math.random() * ancho); manzanaY = (int) (Math.random() * alto); for(int i = inicioSnake;i< inicioSnake + longSnake;i++){ int pos =i %(ancho*alto); if(manzanaX ==snakeX[i]&& manzanaY==snakeY[pos]){ valido = false; break; } } }while(!valido); }