method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
2517a2b1-6806-40f8-8abc-060f6882e278
1
public static void main(String[] args) { long start_time = System.currentTimeMillis(); CountingWords cw = new CountingWords(); LoadTexts texts = new LoadTexts(); Iterator<String> iter = texts.iterator(); Map<String, Integer> stat = cw.getStatistic(iter.next()); Set<String> res_list = cw.getWords(stat); while (iter.hasNext()) { stat = cw.getStatistic(iter.next()); res_list.retainAll(cw.getWords(stat)); } WriteToFile.write(res_list); long end_time = System.currentTimeMillis(); System.out.println("End, time: " + (end_time - start_time)); }
093b7a20-6ddb-4491-85c5-5bd5bb994246
9
public static void main(String[] argv) throws Exception { KeyFactory factory = KeyFactoryImpl.getInstance(); KeyPair dsa = factory.generateDSA(512); KeyPair rsa = factory.generateRSA(1024); SecureRandom r = new SecureRandom(); String key = "374A2BD6D85F5FAA0B6FE06D2F4D8C240DAD83EA345EC1922553F40FEDCC3071DBF946FB454FF56BA7FAAD4A1C4163F57D220CAE6628BA767BE8C9E8B38A6AD91CC990A3AC230981A3D2CBC7E0355178871C50D5AAFB800FAC8965D1F9A9C2DD10DDE8A5CA01005991388068AFED7B0F0A097C38756FC48B38D5A390F43F9097B722CCE5506445A3412713293E99D414AB65D80FA9376DD4D8542B77A70A0A0DE4E16E8A5E718F05F6AD08A7EFA2CA0F5F93F3D90F5B6D0B81D133E6B59DE889"; for (int i = 0; i < 30; i ++) { KeyPair dhA = KeyFactoryImpl.getInstance().generateDHPublic(3); long total = 0; long time = System.nanoTime(); KeyPair dhB = KeyFactoryImpl.getInstance().generateDHPublic(3); /* System.out.println(Helpers .toHexString(dhA.getPublic().getEncoded(), "")); System.out.println(Helpers.toHexString(dhA.getPrivate().getEncoded(), "")); System.out.println(Helpers .toHexString(dhB.getPublic().getEncoded(), "")); System.out.println(Helpers.toHexString(dhB.getPrivate().getEncoded(), "")); */ // byte[] dhApub = ((DHPublicKey) dhA.getPublic()).getY().toByteArray(); // byte[] dhBpub = ((DHPublicKey) dhB.getPublic()).getY().toByteArray(); DHParameters dhParameters = DHParameters.getParams(3); PublicKey restoreApub = KeyFactoryImpl.getInstance().generateDHPublic( Helpers.hexStringToByteArray(key), dhParameters.getP().toByteArray(), dhParameters.getG().toByteArray()); /* System.out.println("ORIGINAL KEY A : " + Helpers.toHexString(((DHPublicKey) dhA.getPublic()).getY() .toByteArray(), "")); System.out.println("RESTORED KEY A : " + Helpers.toHexString(((DHPublicKey) restoreApub).getY() .toByteArray(), "")); System.out.println("ORIGINAL KEY N : " + Helpers.toHexString(((DHPublicKey) dhB.getPublic()).getY() .toByteArray(), "")); System.out.println("RESTORED KEY N : " + Helpers.toHexString(((DHPublicKey) restoreBpub).getY() .toByteArray(), "")); */ time = System.nanoTime(); byte[] dhsN = factory.generateDHSecret(restoreApub, dhB.getPrivate()); time = System.nanoTime() -time; System.out.print(time + "\n" ); } /* try { if (dhsA == null) System.out.println("key is null"); else System.out.println("key lengths : " + dhsA.length + " and " + dhsN.length); // System.out.println(getHexString(dhsA.getEncoded())); } catch (Exception e) { System.out.println(e.getMessage()); } */ SecretKey desKey = factory.generateDES(112); SecretKey sha1Key = factory.generateSHA1(160); SecretKey md5Key = factory.generateMD5(112); byte[] ciphertext; DESCrypto desAlgo = new DESCrypto(desKey); ciphertext = desAlgo.encrypt("test".getBytes()); //System.out.println("length " + ciphertext.length); //System.out.println(new String(desAlgo.decrypt(ciphertext, desAlgo // .getIV()))); RSACrypto rsaAlgo = new RSACrypto(rsa.getPublic(), rsa.getPrivate()); //ciphertext = rsaAlgo.encrypt("test".getBytes()); System.out.println(new String(rsaAlgo.decrypt(ciphertext))); SecretKey aesKey = factory.generateAES(128); AESCrypto aesAlgo = new AESCrypto(aesKey); ciphertext = aesAlgo.encrypt("test".getBytes()); System.out.println("length " + ciphertext.length); System.out.println(new String(aesAlgo.decrypt(ciphertext, aesAlgo .getIV()))); HMACSHA1Digest sha1Algo = new HMACSHA1Digest(sha1Key); byte[] sig = sha1Algo.digest("test".getBytes()); if (sha1Algo.verify(sig, "test".getBytes())) System.out.println("HMAC verified successfully"); else System.out.println("verified unsuccessfully"); DSASignature dsaAlgo = new DSASignature(); byte[] data = new byte[416]; sig = dsaAlgo.sign(data, dsa.getPrivate()); if (dsaAlgo.verify(sig, data, dsa.getPublic())) System.out.println("DSA verified successfully"); else System.out.println("DSA verified unsuccessfully"); RSASignature rsaSigAlgo = new RSASignature(); sig = rsaSigAlgo.sign("test".getBytes(), rsa.getPrivate()); if (rsaSigAlgo.verify(sig, "test2".getBytes(), rsa.getPublic())) System.out.println("RSA verified successfully"); else System.out.println("RSA verified unsuccessfully"); HMACMD5Digest md5Algo = new HMACMD5Digest(md5Key); sig = md5Algo.digest("test".getBytes()); if (md5Algo.verify(sig, "testdas".getBytes())) System.out.println("HMACMD5 verified successfully"); else System.out.println("HMACMD5 verified unsuccessfully"); SHA1Digest sha1md = new SHA1Digest(); byte[] md = sha1md.digest("test".getBytes()); if (sha1md.verify(md, "test".getBytes())) System.out.println("SHA1 matches"); File dsaPubFile = new File("/home/dieman/workspace/cutehip/dsa.pub"); File rsaPubFile = new File("/home/dieman/workspace/cutehip/rsa.pub"); File dsaPrivFile = new File("/home/dieman/workspace/cutehip/dsa.priv"); File rsaPrivFile = new File("/home/dieman/workspace/cutehip/rsa.priv"); factory.saveToFile(dsa.getPublic(), dsaPubFile); factory.saveToFile(rsa.getPublic(), rsaPubFile); factory.saveToFile(dsa.getPrivate(), dsaPrivFile); factory.saveToFile(rsa.getPrivate(), rsaPrivFile); Key dsaPubLoad = factory.loadFromFile(dsaPubFile, KeyFactoryImpl.DSA_KEY, true); Key rsaPubLoad = factory.loadFromFile(rsaPubFile, KeyFactoryImpl.RSA_KEY, true); Key dsaPrivLoad = factory.loadFromFile(dsaPrivFile, KeyFactoryImpl.DSA_KEY, false); Key rsaPrivLoad = factory.loadFromFile(rsaPrivFile, KeyFactoryImpl.RSA_KEY, false); HostIdentity hi = new HostIdentity(rsa.getPublic().getEncoded(), HostIdentity.RSASHA1, (short) 0, (byte) 3); HostIdentityTag hit = new HostIdentityTag(hi); System.out.println("HIT as IPv6 address : " + hit.getAsAddress().getHostAddress()); byte[] i = new byte[8]; SecureRandom rand = new SecureRandom(); rand.nextBytes(i); Puzzle puzzle = new Puzzle(i, null, hit.getAsBytes(), hit.getAsBytes(), 40); if (Puzzle.solve(puzzle, 1000 * 30)) { System.out.println("Puzzle soved"); if (Arrays.equals(i, puzzle.getRandom())) { if (Puzzle.verify(puzzle)) System.out.println("Puzzle verified"); } else { System.out.println("Random values differ"); } } }
bf2e9eab-8028-44e1-913e-05da1aceea80
7
public boolean puraTiedosto() throws FileNotFoundException, IOException, ClassNotFoundException { FileInputStream fis = new FileInputStream(lahde); BufferedInputStream bis = new BufferedInputStream(fis); byte[] luetutKoodiTavut = new byte[purkuBlokkiKoko]; //FileInputStream fis2 = new FileInputStream(lahde.getAbsolutePath()+ ".ser"); ObjectInputStream ois = new ObjectInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(kohde)); koodistaMerkki = (HajautusTaulukko)ois.readObject(); Long kohdePituus = (Long)ois.readObject(); System.out.println("Puretaan " + kohdePituus + " tavua dataa..."); StringBuilder lohkonKoodiMerkit = new StringBuilder(); int tavujaLuettu = 0; long tavujaKirjoitettu = 0; StringBuilder lohkonSelkoTeksti; StringBuilder nykyisenMerkinKoodi = new StringBuilder(); // Luetaan pakattua dataa tiedostosta lohkon koon verran kerrallaan while ((tavujaLuettu = bis.read(luetutKoodiTavut))>0) { lohkonSelkoTeksti = new StringBuilder(); lohkonKoodiMerkit = nykyisenMerkinKoodi; nykyisenMerkinKoodi = new StringBuilder(); //Kydn lohkon jokainen tavu lpi for (int i = 0; i < tavujaLuettu; i++) { // kydn jokaisen tavun jokainen bitti lpi, ja listn puskuriin for (int j = 7; j>=0; j--) { if ((luetutKoodiTavut[i] & (1 << j)) != 0) lohkonKoodiMerkit.append("1"); else lohkonKoodiMerkit.append("0"); } } char[] lohkonKoodiMerkitTaulukko = lohkonKoodiMerkit.toString().toCharArray(); for (int k = 0; k<lohkonKoodiMerkitTaulukko.length; k++) { if (tavujaKirjoitettu < kohdePituus) { nykyisenMerkinKoodi.append(lohkonKoodiMerkitTaulukko[k]); Object o = koodistaMerkki.annaArvo(nykyisenMerkinKoodi.toString()); if (o != null) { lohkonSelkoTeksti.append(o.toString()); nykyisenMerkinKoodi = new StringBuilder(); tavujaKirjoitettu++; } } } bos.write(lohkonSelkoTeksti.toString().getBytes()); } bos.flush(); bis.close(); fis.close(); bos.close(); return false; }
5c90bf43-f860-41a2-8a5f-5dec051b9c36
4
public static boolean testMagic(String pathName) throws IOException { // Open the file BufferedReader reader = new BufferedReader(new FileReader(pathName)); boolean isMagic = true; int lastSum = -1; // For each line in the file ... String line; while ((line = reader.readLine()) != null) { // ... sum each row of numbers String[] parts = line.split("\t"); int sum = 0; for (String part : parts) { sum += Integer.parseInt(part); } if (lastSum == -1) { // If this is the first row, remember the sum lastSum = sum; } else if (lastSum != sum) { // if the sums don't match, it isn't magic, so stop reading isMagic = false; break; } } reader.close(); return isMagic; }
8fc63dc9-eacc-4bcd-9508-69b3995e433e
8
public static Name getName(String noteName) { noteName = noteName.toUpperCase(); if (!(noteName.matches(NOTE_NAME_PATTERN))) { throw new IllegalArgumentException("Invalid note name!"); } switch (noteName) { case "C": return Name.C; case "D": return Name.D; case "E": return Name.E; case "F": return Name.F; case "G": return Name.G; case "A": return Name.A; case "B": return Name.B; default: return null; } }
85282ff4-13a3-486c-994b-b7ab4c381c95
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(MedicineInsert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MedicineInsert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MedicineInsert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MedicineInsert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { MedicineInsert dialog = new MedicineInsert(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
ba9a6245-5795-4863-a875-f77015bf0083
9
public DailyAirtimeSettings(java.awt.Frame parent, boolean modal, boolean sun, boolean mon, boolean tue, boolean wed, boolean thu, boolean fri, boolean sat) { super(parent, modal); this.setIconImage(new ImageIcon(getClass().getResource( "ShowClockWindowLogo.png")).getImage()); /* * daily_selections.txt saves the values selected the last time the Daily *Airtime Settings dialog was opened. */ File f = new File("daily_selections.txt"); //check if the values for daily airtimes settings have previously been set by user if(f.exists()) { //get the values from daily_selections.txt and set them in our variables try { try (Scanner scan = new Scanner(new File("daily_selections.txt"))) { sunStartHour = Integer.parseInt(scan.nextLine()); sunEndHour = Integer.parseInt(scan.nextLine()); sunStartMinute = Integer.parseInt(scan.nextLine()); sunEndMinute = Integer.parseInt(scan.nextLine()); sunStartValue1 = scan.nextLine(); sunStartValue2 = scan.nextLine(); sunEndValue1 = scan.nextLine(); sunEndValue2 = scan.nextLine(); monStartHour = Integer.parseInt(scan.nextLine()); monEndHour = Integer.parseInt(scan.nextLine()); monStartMinute = Integer.parseInt(scan.nextLine()); monEndMinute = Integer.parseInt(scan.nextLine()); monStartValue1 = scan.nextLine(); monStartValue2 = scan.nextLine(); monEndValue1 = scan.nextLine(); monEndValue2 = scan.nextLine(); tueStartHour = Integer.parseInt(scan.nextLine()); tueEndHour = Integer.parseInt(scan.nextLine()); tueStartMinute = Integer.parseInt(scan.nextLine()); tueEndMinute = Integer.parseInt(scan.nextLine()); tueStartValue1 = scan.nextLine(); tueStartValue2 = scan.nextLine(); tueEndValue1 = scan.nextLine(); tueEndValue2 = scan.nextLine(); wedStartHour = Integer.parseInt(scan.nextLine()); wedEndHour = Integer.parseInt(scan.nextLine()); wedStartMinute = Integer.parseInt(scan.nextLine()); wedEndMinute = Integer.parseInt(scan.nextLine()); wedStartValue1 = scan.nextLine(); wedStartValue2 = scan.nextLine(); wedEndValue1 = scan.nextLine(); wedEndValue2 = scan.nextLine(); thuStartHour = Integer.parseInt(scan.nextLine()); thuEndHour = Integer.parseInt(scan.nextLine()); thuStartMinute = Integer.parseInt(scan.nextLine()); thuEndMinute = Integer.parseInt(scan.nextLine()); thuStartValue1 = scan.nextLine(); thuStartValue2 = scan.nextLine(); thuEndValue1 = scan.nextLine(); thuEndValue2 = scan.nextLine(); friStartHour = Integer.parseInt(scan.nextLine()); friEndHour = Integer.parseInt(scan.nextLine()); friStartMinute = Integer.parseInt(scan.nextLine()); friEndMinute = Integer.parseInt(scan.nextLine()); friStartValue1 = scan.nextLine(); friStartValue2 = scan.nextLine(); friEndValue1 = scan.nextLine(); friEndValue2 = scan.nextLine(); satStartHour = Integer.parseInt(scan.nextLine()); satEndHour = Integer.parseInt(scan.nextLine()); satStartMinute = Integer.parseInt(scan.nextLine()); satEndMinute = Integer.parseInt(scan.nextLine()); satStartValue1 = scan.nextLine(); satStartValue2 = scan.nextLine(); satEndValue1 = scan.nextLine(); satEndValue2 = scan.nextLine(); } }catch (IOException ex) { Logger.getLogger(ShowtimeSettings.class.getName()).log(Level.SEVERE, null, ex); } } initComponents(); this.sun = sun; this.mon = mon; this.tue = tue; this.wed = wed; this.thu = thu; this.fri = fri; this.sat = sat; //enable showtime setting options for each day that was selected if(sun) { sunEndAmPm.setEnabled(true); sunEndColon.setEnabled(true); sunEndHourSpinner.setEnabled(true); sunEndLabel.setEnabled(true); sunEndMinuteSpinner.setEnabled(true); sunStartAmPm.setEnabled(true); sunStartColon.setEnabled(true); sunStartHourSpinner.setEnabled(true); sunStartLabel.setEnabled(true); sunStartMinuteSpinner.setEnabled(true); sundayLabel.setEnabled(true); } if(mon) { monEndAmPm.setEnabled(true); monEndColon.setEnabled(true); monEndHourSpinner.setEnabled(true); monEndLabel.setEnabled(true); monEndMinuteSpinner.setEnabled(true); monStartAmPm.setEnabled(true); monStartColon.setEnabled(true); monStartHourSpinner.setEnabled(true); monStartLabel.setEnabled(true); monStartMinuteSpinner.setEnabled(true); mondayLabel.setEnabled(true); } if(tue) { tueEndAmPm.setEnabled(true); tueEndColon.setEnabled(true); tueEndHourSpinner.setEnabled(true); tueEndLabel.setEnabled(true); tueEndMinuteSpinner.setEnabled(true); tueStartAmPm.setEnabled(true); tueStartColon.setEnabled(true); tueStartHourSpinner.setEnabled(true); tueStartLabel.setEnabled(true); tueStartMinuteSpinner.setEnabled(true); tuesdayLabel.setEnabled(true); } if(wed) { wedEndAmPm.setEnabled(true); wedEndColon.setEnabled(true); wedEndHourSpinner.setEnabled(true); wedEndLabel.setEnabled(true); wedEndMinuteSpinner.setEnabled(true); wedStartAmPm.setEnabled(true); wedStartColon.setEnabled(true); wedStartHourSpinner.setEnabled(true); wedStartLabel.setEnabled(true); wedStartMinuteSpinner.setEnabled(true); wednesdayLabel.setEnabled(true); } if(thu) { thuEndAmPm.setEnabled(true); thuEndColon.setEnabled(true); thuEndHourSpinner.setEnabled(true); thuEndLabel.setEnabled(true); thuEndMinuteSpinner.setEnabled(true); thuStartAmPm.setEnabled(true); thuStartColon.setEnabled(true); thuStartHourSpinner.setEnabled(true); thuStartLabel.setEnabled(true); thuStartMinuteSpinner.setEnabled(true); thursdayLabel.setEnabled(true); } if(fri) { friEndAmPm.setEnabled(true); friEndColon.setEnabled(true); friEndHourSpinner.setEnabled(true); friEndLabel.setEnabled(true); friEndMinuteSpinner.setEnabled(true); friStartAmPm.setEnabled(true); friStartColon.setEnabled(true); friStartHourSpinner.setEnabled(true); friStartLabel.setEnabled(true); friStartMinuteSpinner.setEnabled(true); fridayLabel.setEnabled(true); } if(sat) { satEndAmPm.setEnabled(true); satEndColon.setEnabled(true); satEndHourSpinner.setEnabled(true); satEndLabel.setEnabled(true); satEndMinuteSpinner.setEnabled(true); satStartAmPm.setEnabled(true); satStartColon.setEnabled(true); satStartHourSpinner.setEnabled(true); satStartLabel.setEnabled(true); satStartMinuteSpinner.setEnabled(true); saturdayLabel.setEnabled(true); } }
e2e6fe60-a119-4f80-b546-f32d7e93f2e4
0
private void createDummyTravelTrips() { TravelTrip temp = new TravelTrip(); temp.setCountry("Pakistan"); temp.setCity("Lahore"); temp.setFromDate("19/06/2012"); temp.setToDate("27/06/2012"); temp.setBusiness(false); //travelTripDao.register(temp); travelTripService.addTravelTrip(temp); }
e9088026-0042-4a95-9551-7241483a13c6
5
public ComparatorTreeNode(SingleTreeNode oldNode, SingleTreeNode newNode){ this.oldNode = oldNode; this.newNode = newNode; if (oldNode != null && newNode != null) comparatorNodeTableModel = new ComparatorNodeTableModel(oldNode.getNodeTableModel(), newNode.getNodeTableModel()); if (oldNode == null) color = addedColor; else if (newNode == null) color = removedColor; else if (comparatorNodeTableModel.getRowCount() > 0) color = modifiedColor; else color = Color.black; }
a9c9c637-8f3f-471f-9eff-595133eb29e7
3
public static void isBoardLegal(String board, int dimension) { if (Objects.isNull(board) || board.isEmpty() || board.length() % dimension != 0) { throw new IllegalStateException("There is something wrong with your board"); } }
ecf49a15-9bba-40b1-9a11-5e906e0b98bf
1
public Tileset(){ try { tileset = ImageIO.read(new File("F:\\DerWorkspace\\Zombie\\src\\Tileset.png")); } catch (IOException e) { e.printStackTrace(); } tilesetLaden(tileset); }
85dd3698-8caf-4865-a92f-f614e47d585f
2
public int setTypeCompte(String typeCompte) { if(typeCompte.equalsIgnoreCase("solde") || typeCompte.equalsIgnoreCase("abonnement")){ this.typeCompte = typeCompte.toLowerCase(); return 0; } else{ return -1; } }
33dbe4ef-52a3-4372-bd3d-1d98647875b6
0
public Boolean getSuccess() { return success; }
660d0350-c281-4c1c-b014-803bf8aefe82
6
public static int getMaxStones(int currRow, int currCol, int[][] inputArr) { int max = 0; try { int v1 = inputArr[currRow-1][currCol - 1]; max = v1 > max ? v1 : max; } catch (Exception e) { } try { int v1 = inputArr[currRow-1][currCol]; max = v1 > max ? v1 : max; } catch (Exception e) { } try { int v1 = inputArr[currRow-1][currCol + 1]; max = v1 > max ? v1 : max; } catch (Exception e) { } return max; }
03ca70c3-f6ff-4ec2-975c-20dd9dd61bd2
9
public boolean isValidSwap(int x, int y, SwapDirection swapDirection) { if(x < 0 || y < 0) return false; if(this.isPositionAvailable(x, y)) /* No square for swap here. */ return false; int newX = x; int newY = y; newX += (swapDirection == SwapDirection.RIGHT) ? 1 : 0; newX += (swapDirection == SwapDirection.LEFT) ? -1 : 0; newY += (swapDirection == SwapDirection.DOWN) ? 1 : 0; newY += (swapDirection == SwapDirection.UP) ? -1 : 0; if(newX < 0 || newY < 0) return false; boolean foundSquareForSwap = !this.isPositionAvailable(newX, newY); return foundSquareForSwap; }
7b4d0384-2ef2-494f-8b5d-896643b7e106
6
protected void updateClassPath(File dir) throws Exception { URL[] urls = new URL[this.urlList.length]; for (int i = 0; i < this.urlList.length; i++) { urls[i] = new File(dir, getJarName(this.urlList[i])).toURI().toURL(); } if (classLoader == null) { classLoader = new URLClassLoader(urls) { protected PermissionCollection getPermissions(CodeSource codesource) { PermissionCollection perms = null; try { Method method = SecureClassLoader.class.getDeclaredMethod("getPermissions", new Class[] { CodeSource.class }); method.setAccessible(true); perms = (PermissionCollection)method.invoke(getClass().getClassLoader(), new Object[] { codesource }); String host = "www.minecraft.net"; if ((host != null) && (host.length() > 0)) perms.add(new SocketPermission(host, "connect,accept")); else { codesource.getLocation().getProtocol().equals("file"); } perms.add(new FilePermission("<<ALL FILES>>", "read")); } catch (Exception e) { e.printStackTrace(); } return perms; } }; } String path = dir.getAbsolutePath(); if (!path.endsWith(File.separator)) { path = path + File.separator; } unloadNatives(path); System.setProperty("org.lwjgl.librarypath", path + "natives"); System.setProperty("net.java.games.input.librarypath", path + "natives"); natives_loaded = true; }
76b51218-e0f3-4408-b05d-792585081147
2
public AbstractInsnNode[] find(String regex) { try { Matcher regexMatcher = Pattern.compile(processRegex(regex), Pattern.MULTILINE).matcher(representation); if (regexMatcher.find()) return makeResult(regexMatcher.start(), regexMatcher.end()); } catch (PatternSyntaxException ex) { ex.printStackTrace(); } return new AbstractInsnNode[0]; }
d5eadfbb-6eab-4f85-8507-2c4efda36bf1
5
private void createAdvancedContent(String serie, String[] albums, int id) throws IOException { Logger.getLogger(ReportGenerator.class.getName()).entering(ReportGenerator.class.getName(), "createAdvancedContent", new Object[] {serie, albums, id}); BufferedWriter comicFile; comicFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(reportFolder + "Comic" + id + ".html"), "UTF-8")); createHeader(comicFile); StringBuilder content = new StringBuilder(); content = content.append(System.getProperty("line.separator")).append(" <div id=\"listing\">"); content = content.append(System.getProperty("line.separator")).append(" <table align=\"center\" cellspacing=\"0\">"); content = content.append(System.getProperty("line.separator")).append(" <thead>"); content = content.append(System.getProperty("line.separator")).append(" <td colspan=\"2\">").append(serie).append(" (").append(albums.length).append(" ").append(resourceBundle.getString("nbrOfAlbums.text")).append(") - <a href=\"index.html\">Menu</a></td>"); content = content.append(System.getProperty("line.separator")).append(" </thead>"); content = content.append(System.getProperty("line.separator")).append(" <tbody>"); for (int i = 0; i < albums.length; i++) { if (cancelAsked) { return; } if (i != 0) { createThumbnail(serie, albums[i], id, i); } if (i%2 == 0) { if (i != 0) { content = content.append(System.getProperty("line.separator")).append(" </tr>"); } content = content.append(System.getProperty("line.separator")).append(" <tr class=\"pair\">"); } else { content = content.append(System.getProperty("line.separator")).append(" </tr>"); content = content.append(System.getProperty("line.separator")).append(" <tr class=\"impair\">"); } content = content.append(System.getProperty("line.separator")).append(" <td class=\"thumbnail\"><img src=\"thumbnails/Comic").append(id).append("-").append(i).append(".png\" alt=\"").append(albums[i]).append("\" /></td>"); content = content.append(System.getProperty("line.separator")).append(" <td>").append(albums[i]).append("</td>"); setProgress(++nbrOfProcessedAlbums * 100 / nbrOfAlbums); publish(MessageFormat.format(resourceBundle.getString("simpleListingGen.text"), serie, albums[i])); } content = content.append(System.getProperty("line.separator")).append(" </tr>"); content = content.append(System.getProperty("line.separator")).append(" </tbody>"); content = content.append(System.getProperty("line.separator")).append(" <tfoot>"); content = content.append(System.getProperty("line.separator")).append(" <td colspan=\"2\">Copyright &copy; Inervo</td>"); content = content.append(System.getProperty("line.separator")).append(" </tfoot>"); content = content.append(System.getProperty("line.separator")).append(" </table>"); content = content.append(System.getProperty("line.separator")).append(" </div>"); content = content.append(System.getProperty("line.separator")).append(" </div>"); comicFile.write(content.toString()); comicFile.newLine(); createSimpleFooter(comicFile); comicFile.close(); Logger.getLogger(ReportGenerator.class.getName()).exiting(ReportGenerator.class.getName(), "createAdvancedContent"); }
d7c6fbee-ed3b-4fbd-8a3a-9ecb4dc3b694
4
public Object clone() { //MERLIN MERLIN MERLIN MERLIN MERLIN// TuringMachine a = new TuringMachine(this.tapes()); a.setEnvironmentFrame(this.getEnvironmentFrame()); HashMap<TMState, TMState> map = new HashMap<TMState, TMState>(); // Old states to new states. for (Object o: states){ // System.out.println(o.getClass().getName()); TMState tms = (TMState)o; TMState ntms = new TMState(tms);//I could write a clone for that TM too, I suppose, but there's nothing wrong with a nice C++ style copy constructor ntms.setAutomaton(a); //recognize thine new master, after the convenience of the copy constructor, lest there be great many bugs. ntms.setLabel(tms.getLabel()); ntms.setName(tms.getName()); map.put(tms, ntms); a.addState(ntms); //using OBJECT equality, and OBJECT hashcode, which is fine here because we want to know if the objects are literally the same (which they should be) } for (Object o: finalStates){ TMState tms = (TMState) o; a.addFinalState(map.get(tms)); } a.setInitialState((TMState) map.get((TMState) getInitialState())); for (Object o: states){ TMState tms = (TMState)o; Transition[] ts = getTransitionsFromState(tms); TMState from = map.get(tms); for (int i = 0; i < ts.length; i++) { TMState to = map.get(ts[i].getToState()); Transition toBeAdded = (Transition)ts[i].clone(); toBeAdded.setFromState(from); toBeAdded.setToState(to); // a.addTransition(ts[i].copy(from, to)); a.addTransition(toBeAdded); } } return a; }
30e2c58b-c8bf-4f42-87a0-e9f07e6fa959
3
public boolean isLawful(){ switch(this){ case LAWFUL_GOOD: case LAWFUL_NEUTRAL: case LAWFUL_EVIL: return true; default: return false; } }
a4f98ebe-226b-4424-825b-36fea19da703
8
public static boolean isBinarySearchTree(TreeNode rootNode) { if(rootNode == null) { return true; } TreeNode leftSubTree = rootNode.getLeft(); TreeNode rightSubTree = rootNode.getRight(); boolean leftResult = isBinarySearchTree(leftSubTree); boolean rightResult = isBinarySearchTree(rightSubTree); if (leftSubTree != null) leftMax = (leftSubTree.getKey() > leftMax) ? leftSubTree.getKey() : leftMax; if (rightSubTree != null) rightMin = (rightSubTree.getKey() < rightMin) ? rightSubTree.getKey() : rightMin; return leftResult && rightResult && (rootNode.getKey() >= leftMax && rootNode.getKey() <= rightMin); }
b07d146b-45a8-4aae-8711-5aa247d63644
2
public int[] getHashBuckets(String key) { return Filter.getHashBuckets(key, hashCount, buckets()); }
fa6659b2-3e52-4ca5-bf73-25e46cc8b543
1
private final void reliableExecution(PlanObject plan) throws FatalError, RestartLater { try { plan.run(); } catch (JSONException e) { Output.println(plan.getName() + " hat einen unbehandelbaren Fehler erzeugt.", 0); } }
fcb5b0a6-fcd5-43fb-9710-73794dab1fbb
7
public static Map imageTagsFromFile(String fileName) { Map imagesTags = new HashMap(); /* Set path to file */ String filepath = System.getProperty("user.dir"); filepath = filepath + "/src/statsemdistance/res/" + fileName; BufferedReader br = null; String line; String split = ","; try { br = new BufferedReader(new FileReader(filepath)); while ((line = br.readLine()) != null) { /* Create an array with the strings of every line */ String[] words = line.split(split); for (int i = 0; i < words.length; i++) { words[i] = words[i].replace(" \"", "").replace("\"", ""); } /* add the key and create internal list */ imagesTags.put(words[0], new ArrayList()); /* Go through the internal list and add all the tags */ List internal = (ArrayList) imagesTags.get(words[0]); for (int i = 1; i < words.length; i++) { /* Key already exists for the image; Search for tag in the internal list and add it */ internal.add(words[i]); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("Reading done"); return imagesTags; }
974362d5-1d10-488f-91a7-b558033cdfcb
2
public static void main(String[] args) { /* program to print the pattern 1 12 123 1234 */ for (int i=3;i<=10;i++) { for (int j=1;j<=i;j++) System.out.print(j); System.out.println(""); } }
378ba437-9dc7-4076-8967-26fed335aa7e
0
public void setVelocityY(float dy) { this.dy = dy; }
ff029151-9365-4702-be97-8576ab73eed7
0
public static void main(String[] args) { HashMap map = new HashMap(); map.put("a","zhangsan"); map.put("b","lisi"); map.put("c","wangwu"); map.put("a","zhaoliu"); System.out.println(map); String value = (String)map.get("b"); System.out.println(value); System.out.println("------------"); String value1 = (String)map.get("d"); System.out.println(value1); System.out.println("------------"); }
99dca2a0-1a50-43b9-bada-6b295f420461
2
public static Connection getConexion(){ try{ Class.forName("com.mysql.jdbc.Driver"); if(conex==null){ conex = DriverManager.getConnection(url,usuario,clave); }else{ conex = null; } }catch(ClassNotFoundException | SQLException e){ JOptionPane.showMessageDialog(null, e); } return conex; }
a223b12a-4cb1-4155-8123-405c04ddcb6d
0
static void w(Lethal l) { l.kill(); }
fa779ca8-4b8c-459f-b23a-27d16ab163eb
0
public int getPoints() { return points; }
9e411658-519e-492c-a7ae-65a654793299
8
public static void findNumbersWithThreeDifferentDigits(int[] sourceNumbers) { int digit1, digit2, digit3; print("Все трехзначные числа, в десятичной записи которых нет одинаковых цифр: "); for (int sourceNumber : sourceNumbers) { digit1 = sourceNumber / 100; digit2 = sourceNumber / 10 % 10; digit3 = sourceNumber % 10; // Ищем трехзначные числа if ((sourceNumber >= 100 && sourceNumber <= 999) || (sourceNumber <= -100 && sourceNumber >= -999)) { if ((digit1 != digit2) && (digit2 != digit3) && (digit1 != digit3)) { print(sourceNumber + ", "); } } } println(); }
3270b03c-e436-485d-bfc3-7c91de4b9c82
1
private static Field getLabelField(final String name) { try { Field f = Label.class.getDeclaredField(name); f.setAccessible(true); return f; } catch (NoSuchFieldException e) { return null; } }
ba411fbd-5f43-4399-9c58-3c72b638bdaa
6
private Record searchingFile(final String data, final String mark) throws IOException { BufferedReader br = new BufferedReader(new FileReader(file)); try { String line; while ((line = br.readLine()) != null) { String recformat =""; StringTokenizer str = new StringTokenizer(line,","); while (str.hasMoreTokens()) { recformat += str.nextToken()+" "; } Record rec = new Record(recformat); if (rec.phone.equals(data) && mark.equals("phone")) { return rec; } if (rec.name.equals(data) && mark.equals("name")) { return rec; } } return null; } finally { br.close(); } }
59371398-8b7c-4cc7-9d2f-4d5cdb4f8c25
5
public String getColumnName(int column) { String name = "??"; switch (column) { case 0: name = "Source"; break; case 1: name = "Destination"; break; case 2: name = "FileModel name"; break; case 3: name = "Progress"; break; case 4: name = "Status"; break; } return name; }
01238a80-089a-4edc-935f-46c4bb29b452
3
@Override public void paintComponent (Graphics g) { champion.getIcon().paintIcon (this, g, 1, 1); if ((isHovered) && BORDER_HIGHLIGHTED != null) g.drawImage (BORDER_HIGHLIGHTED, 0, 0, null); else if (BORDER != null) g.drawImage (BORDER, 0, 0, null); }
aa324753-eec5-4288-9651-8609c4b5beb7
7
DrawFile createImage(Entity entity, FileFormatOption option) throws IOException { final double dpiFactor = diagram.getDpiFactor(option); if (entity.getType() == EntityType.NOTE) { return createImageForNote(entity.getDisplay2(), entity.getSpecificBackColor(), option, entity.getParent()); } if (entity.getType() == EntityType.ACTOR) { return createImageForActor(entity, dpiFactor); } if (entity.getType() == EntityType.CIRCLE_INTERFACE) { return createImageForCircleInterface(entity, dpiFactor); } if (entity.getType() == EntityType.ABSTRACT_CLASS || entity.getType() == EntityType.CLASS || entity.getType() == EntityType.ENUM || entity.getType() == EntityType.INTERFACE) { return createImageForCircleCharacter(entity, dpiFactor); } return null; }
8222d655-3178-4068-b9ca-fc55bde1c084
4
public String bottomUp() { Cluster c = new Cluster(); double minDistance, daux = 0; int c1 = 0, c2 = 0, numIteracionesQueFaltan = this.instances.numInstances(); int iteraciones = numIteracionesQueFaltan; System.out.println("Iteracion 1 de " + iteraciones + "."); ClusterList updatingClusterList = this.beginBottomUp(); String resultado = "A distancia 0, " + updatingClusterList.toString() + "\n"; while (numIteracionesQueFaltan > 1) { // Sabemos que empezamos desde el numero total de clusters iniciales hasta quedarnos con uno unico. System.out.println("Iteracion " + (iteraciones - numIteracionesQueFaltan + 2) + " de " + iteraciones + "."); minDistance = 1.0/0.0; // Infinito. for (int i = 0; i < updatingClusterList.size(); i++) { // Comprobamos cada cluster... c = updatingClusterList.get(i); for (int j = i + 1; j < updatingClusterList.size(); j++) { // ...con el resto de clusters que quedan por comprobar. daux = this.link.calculateClusterDistance(c, updatingClusterList.get(j)); // Calculamos la distancia entre clusters. if (daux < minDistance) { // Comprobamos si es la menor. De serlo, la guardamos. minDistance = daux; c1 = i; // Guardamos la posicion del primer cluster. c2 = j; // Guardamos la posicion del segundo cluster. } } } updatingClusterList.get(c1).merge(updatingClusterList.get(c2)); // Unimos los dos clusters mas cercanos entre si. updatingClusterList.remove(c2); // Eliminamos el cluster que hemos introducido en el otro. numIteracionesQueFaltan--; // Un cluster menos en la lista. resultado += "A distancia " + minDistance + ", " + updatingClusterList.toString() + "\n"; } return resultado; }
e778e095-97d3-46a0-a21c-3fc052b33fd0
9
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("landen", landService.findAll()); List<String> fouten = new ArrayList<>(); if(!(request.getParameterMap().isEmpty())){ Land land = null; try{ long landNr = Long.parseLong(request.getParameter("landNr")); land = landService.read(landNr); if(land == null){ fouten.add("Land niet gevonden"); } } catch(NumberFormatException ex){ fouten.add("Landnummer moet een getal zijn"); } if(fouten.isEmpty()){ request.setAttribute("land", land); Soort soort = null; if(request.getParameterMap().containsKey("soortNr")){ try{ long soortNr = Long.parseLong(request.getParameter("soortNr")); soort = soortService.read(soortNr); if(soort == null){ fouten.add("soort niet gevonden"); } if(!land.getSoorten().contains(soort)){ fouten.add("deze soort hoort niet bij dit land"); } } catch(NumberFormatException ex){ fouten.add("soortNummer moet een getal zijn"); } if(fouten.isEmpty()){ request.setAttribute("soort", soort); } else{ request.setAttribute("fouten", fouten); } } } else{ request.setAttribute("fouten", fouten); } } request.getRequestDispatcher(SAME_PAGE_VIEW).forward(request, response); }
0ccde472-d720-4a08-aa94-ce3b78bcfa89
0
public static String GetTimeStamp() { String TimeStamp = ""; Calendar now = Calendar.getInstance(); TimeStamp = FormatInt(Integer.toString(now.MONTH + 1)) + FormatInt(Integer.toString(now.DAY_OF_MONTH + 1)) + FormatInt(Integer.toString(now.HOUR_OF_DAY + 1)) + FormatInt(Integer.toString(now.MINUTE + 1)) + FormatInt(Integer.toString(now.SECOND + 1)); return TimeStamp; }
326dc0e4-c9fc-410b-bcdb-df6470d9bf15
2
@Override public boolean offer(RenderItem item) { if (maxSize > 0 && renderList.size() >= maxSize) { return false; } renderList.addLast(item); return true; }
aabd15b5-25a8-45e4-b3c1-1698db1236a3
2
public void addRow(Object... row) { if (row.length != columnNames.size()) { throw new IllegalArgumentException("row data != column count : " + row.length + "!=" + columnNames.size()); } String[] s = new String[columnNames.size() + 1]; s[0] = Integer.toString(rows.size()); for (int i = 1; i < s.length; i++) { s[i] = row[i-1].toString(); } rows.add(s); }
11ffc141-18bb-4c3e-bbde-1ef19fff1ff8
7
private void updateMinMax(float[] magnitudes) { if(minimums == null || maximums == null) initializeMinMax(magnitudes); else if(minimums.length != magnitudes.length || maximums.length != magnitudes.length) initializeMinMax(magnitudes); else for(int i = 0; i < magnitudes.length; ++i) { if(-1*magnitudes[i] < minimums[i]) { minimums[i] = -1*magnitudes[i]; } if(-1*magnitudes[i] > maximums[i]) { maximums[i] = -1*magnitudes[i]; } } }
24af4c1e-e00c-4f07-a312-feda3edf277d
5
protected String nextLine() throws Exception { if (inHandle==null) { throw new Exception("Read Object Be Closed."); } if (!lastIsLine) { if (!inHandle.hasNextLine()) { throw new Exception("Read Error."); } if (!inHandle.nextLine().isEmpty()) { throw new Exception("This mast be empty."); } lastIsLine = true; } if (!inHandle.hasNextLine()) { throw new Exception("Read Error."); } return inHandle.nextLine(); }
5aebeec4-a0ed-4a32-b828-37218c7b32ff
6
public final boolean getBoolean(int index) throws JSONException { Object o = get(index); if (o.equals(Boolean.FALSE) || (o instanceof String && ((String)o).equalsIgnoreCase("false"))) { return false; } else if (o.equals(Boolean.TRUE) || (o instanceof String && ((String)o).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a Boolean."); }
b646882d-715d-4fb9-be36-26b11a1a3354
0
@Override public void focusLost(FocusEvent e) { textArea = (OutlinerCellRendererImpl) e.getComponent(); textArea.hasFocus = false; }
16d669af-27ff-4fa9-8346-279319d37ba6
0
@Override public void setYearsExperience(int yearsExperience) { super.setYearsExperience(yearsExperience); }
68cdaebc-5268-48e0-9235-eb36504ec17b
7
protected boolean tryMove() { boolean collided = false; for(BB bb : level.collidables) { if(bb.intersects(this.x + this.xa, this.y, width, height)) { if(this.xa > 0) { this.x = bb.getX() - width; } else if(this.xa < 0) { this.x = bb.getX() + bb.getWidth(); } this.xa = 0; collided = true; } if(bb.intersects(this.x, this.y + this.ya, width, height)) { if(this.ya > 0) { this.y = bb.getY() - height; onGround = true; } else if(this.ya < 0) { this.y = bb.getY() + bb.getHeight() + 1; } this.ya = 0; collided = true; } } this.x += this.xa; this.y += this.ya; return collided; }
29c80779-4e1f-4e65-8f06-03fad66ebe7d
8
public void setRenderer(int row, int column) { if(column == 0) setHorizontalAlignment(SwingConstants.CENTER); else if (column == 1) { if(dataFormat==ASM_FORMAT) setHorizontalAlignment(SwingConstants.LEFT); else setHorizontalAlignment(SwingConstants.RIGHT); } if (row>contents.size()) return; AsmLine current = contents.getLine(row); /****************/ setToolTipText(""); if (current.label() != null) setToolTipText("("+current.label()+")"); if (current.comment() != null) setToolTipText(getToolTipText() + "\t" + current.comment()); if (getToolTipText().isEmpty()) setToolTipText(null); else setBackground(Color.GREEN); if (row == pointerAddress) setBackground(Color.yellow); /****************/ }
34c9bb76-9634-42e2-9d15-a9bdc22ec9d4
6
static public int convert(int id) { switch (id) { case CRIT_MELEE: case CRIT_RANGE: case CRIT_SPELL: return CRIT; case HASTE_MELEE: case HASTE_SPELL: case HASTE_RANGE: return HASTE; default: return id; } }
086170c3-7783-4e0c-9e28-3cafc90f20b0
1
public void nextTurn() { if (wait == 0) { ++turn; } }
60bd28c8-2094-476e-af30-d47f628c7786
5
public boolean isCheckmated(Color color) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { Piece piece = getPiece(j, i); if (piece instanceof King && piece.getColor() == color) { return piece.getLegalMoves(new Coordinate(j, i), this).isEmpty() && this.findThreatenedSquares(color).contains(new Coordinate(j, i)); } } } return false; }
fd2b094c-c6ab-4277-a99d-ecaf72f9fac5
9
@Override public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); boolean enabled = false; if (command.equals(MAKE_PASS)) { if (this.makePassItem.isSelected()) { enabled = true; } this.menu.setEnabled(enabled); this.logic.setMakePass(enabled); } else if (command.equals(USE_LOWER)) { if (this.lowerItem.isSelected()) { enabled = true; System.out.println(menu.isPopupMenuVisible()); System.out.println(menu.isSelected()); } this.logic.setUseLowerCase(enabled); } else if (command.equals(USE_UPPER)) { if (this.upperItem.isSelected()) { enabled = true; } this.logic.setUseUpperCase(enabled); } else if (command.equals(USE_NUMBER)) { if (this.numberItem.isSelected()) { enabled = true; } this.logic.setUseNumber(enabled); } else if (command.equals(CREATE_PASS)) { this.logic.createAndShowRandomPass(); } }
ca13027b-1e2f-4580-b832-bb8347486953
0
public void setIcfgFactory(BiDirICFGFactory factory) { this.cfgFactory = factory; }
a676071d-2762-4a17-aa3a-07e82f652c93
5
private void processFlameDrawing() { drawingFlames = true; try { long l = System.currentTimeMillis(); int i = 0; int j = 20; while (aBoolean831) { flameCycle++; getFlameOffsets(); getFlameOffsets(); drawFlames(); if (++i > 10) { long l1 = System.currentTimeMillis(); int k = (int) (l1 - l) / 10 - j; j = 40 - k; if (j < 5) { j = 5; } i = 0; l = l1; } try { Thread.sleep(j); } catch (Exception exception) { } } } catch (Exception exception) { } drawingFlames = false; }
5646b3f7-1581-4ebf-abfb-ea333715e091
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(qtrackIntroUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(qtrackIntroUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(qtrackIntroUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(qtrackIntroUI.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 qtrackIntroUI().setVisible(true); } }); }
fc1d1374-e251-4b8b-82c9-8b93aad7eebe
6
private void logCurrentState(final Instruction instr) { if (log.isLoggable(Level.INFO)) { log.info("Current instruction: " + instr + " (line " + instr.getSourceLine() + ")"); log.info("PC: " + programCounter + "\tFP: " + framePointer + "\tHP:" + heapPointer); log.info("Stack contents:"); if(this.stack.size() > 0) { int limit = Math.max(stack.size() - 10, -1); for(int i = stack.size() - 1; i > limit; i--) { log.info(i + ": " + stack.get(i)); } } else { log.info("Stack is empty!"); } log.info("Memory dump:"); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("0x00000001\t"); int i = 0; while (i < MEM_SIZE) { stringBuilder.append("0x"); stringBuilder.append(String.format("%08X", this.memory[i])); stringBuilder.append(" "); i++; if(i < MEM_SIZE && (i % 8) == 0) { log.info(stringBuilder.toString()); stringBuilder = new StringBuilder(); stringBuilder.append("0x"); stringBuilder.append(String.format("%08X", i)); stringBuilder.append("\t"); } } log.info(stringBuilder.toString()); } }
05e5ba1e-97c8-4d62-b23c-6db39d9fcf0d
5
public static void main(String args[]) { //Display a welcome message. System.out.println("Welcome to the Person Tester Application"); System.out.println(); //Create the Scanner object. Scanner sc = new Scanner(System.in); //Continue until choice isn't equal to "Y" or "y". String choice = "y"; while (choice.equalsIgnoreCase("y")) { String personType = Validator.getRequiredString(sc, "Create customer or employee? (c/e): "); System.out.println(); if (personType.equalsIgnoreCase("c") || personType.equalsIgnoreCase("e")) { String firstName = Validator.getRequiredString(sc,"Enter first name: "); String lastName = Validator.getRequiredString(sc, "Enter last name: "); String email = Validator.getRequiredString(sc, "Enter email address: "); if(personType.equalsIgnoreCase("c")) { String custNum = Validator.getRequiredString(sc, "Enter customer number: "); System.out.println(); Customer customer = new Customer(firstName, lastName, email); customer.setFirstName(firstName); customer.setLastName(lastName); customer.setEmail(email); customer.setCustNum(custNum); print(customer); } else if(personType.equalsIgnoreCase("e")) { String ssn = Validator.getRequiredString(sc, "Enter employee Social Security Number: "); System.out.println(); Employee employee = new Employee(firstName, lastName, email); employee.setFirstName(firstName); employee.setLastName(lastName); employee.setEmail(email); employee.setSsn(ssn); print(employee); } } else { System.out.println("Error! Invalid selection. Try again. \n"); continue; } //See if the user wants to continue. choice = Validator.getRequiredString(sc, "Continue? (y/n): "); System.out.println(); } }
9b80e5e9-c1c4-4140-af55-fbd04d9fcd08
1
private boolean deleteEntry() { try { rs.deleteRow(); return true; } catch (SQLException ex) { System.out.println(ex.getMessage()); } return false; }
aa43667a-f47b-4852-bd2b-41ec3c495d4f
2
private Matrix4f getParentMatrix() { if (parent != null && parent.hasChanged()) { parentMatrix = parent.getTransformation(); } return parentMatrix; }
5ded1b3f-55e1-4c62-9a1e-0cd906c6d142
7
public void displayResults(boolean showMismatches,PrintStream out) throws IOException { PrintfFormat fmt = new PrintfFormat("%s %3d %7.2f | %30s | %30s\n"); for (int i=0; i<pairs.length; i++) { if (pairs[i]!=null) { String label = pairs[i].isCorrect() ? "+" : "-"; String aText = (pairs[i].getA()==null) ? "***" : pairs[i].getA().unwrap(); String bText = (pairs[i].getB()==null) ? "***" : pairs[i].getB().unwrap(); if (showMismatches || "+".equals(label)) { out.print( fmt.sprintf( new Object[] { label, new Integer(i+1), new Double(pairs[i].getDistance()), aText, bText })); } } } }
74144a62-0c0f-48f4-b754-3aad42a40f07
7
public Operator(char operator) { switch(operator) { case 41: // ')' stackPrecedence = -1; inputPrecedence = 0; break; case 40: // '(' stackPrecedence = 0; inputPrecedence = 7; break; case 43: // '+' stackPrecedence = 2; inputPrecedence = 1; break; case 45: // '-' stackPrecedence = 2; inputPrecedence = 1; break; case 42: // '*' stackPrecedence = 4; inputPrecedence = 3; break; case 47: // '/' stackPrecedence = 4; inputPrecedence = 3; break; case 94: // '^' stackPrecedence = 6; inputPrecedence = 5; break; } this.operator = operator; }
5f12fc27-783b-498b-84fe-c0b4b06eaadb
1
@Override public void relocate(){ if(isRunning()){ super.relocate(); } }
de1bd413-09a2-400e-93a6-9ea49df92f7d
7
public static void printControlFrame(ControlFrame self, PrintableStringWriter stream) { if (Surrogate.subtypeOfP(Stella_Object.safePrimaryType(self), Logic.SGT_LOGIC_PARALLEL_CONTROL_FRAME)) { { ParallelControlFrame self000 = ((ParallelControlFrame)(self)); stream.print("|PLL-CF|" + ControlFrame.debugFrameId(self000) + "["); } } else { stream.print("|CF|" + ControlFrame.debugFrameId(self) + "["); } if (self.choicePointUnbindingOffset != Stella.NULL_INTEGER) { stream.print(self.choicePointUnbindingOffset); } else { stream.print("_"); } { Object old$Printinframe$000 = Logic.$PRINTINFRAME$.get(); try { Native.setSpecial(Logic.$PRINTINFRAME$, self); { boolean printtimesP = self.allottedClockTicks != Stella.NULL_INTEGER; stream.print(" " + self.state + " " + self.currentStrategy); if (self.up != null) { stream.print(" UP: " + ControlFrame.debugFrameId(self.up)); } else { stream.print(" UP: -"); } if (self.down != null) { stream.print(" DOWN: " + ControlFrame.debugFrameId(self.down)); } else { stream.print(" DOWN: -"); } stream.print(" DEPTH: " + ControlFrame.computeFrameDepth(self)); if (((Description)(KeyValueList.dynamicSlotValue(self.dynamicSlots, Logic.SYM_LOGIC_DESCRIPTION, null))) != null) { stream.print(" DESC: " + ((Description)(KeyValueList.dynamicSlotValue(self.dynamicSlots, Logic.SYM_LOGIC_DESCRIPTION, null)))); } if (printtimesP) { stream.print(" CLOCK: " + ((QueryIterator)(Logic.$QUERYITERATOR$.get())).currentClockTicks + " START: " + self.startingClockTicks + " TICKS: " + self.allottedClockTicks); } stream.print(((self.reversePolarityP ? " ~" : " ")) + self.proposition + "]"); } } finally { Logic.$PRINTINFRAME$.set(old$Printinframe$000); } } }
711c343e-2207-4345-8304-5890f81301e4
8
private void countryClickedSetupMode(Country c) { switch (setupMode) { case 4: if (c.getUnit() == null) { this.addUnit(1, currentArmy(), c); currentArmy().setFreeUnits(currentArmy().getFreeUnits() - 1); incrementTurn(); numTerritoriesClaimed++; if (numTerritoriesClaimed == 42) { enterSetupReinforcement(); } } break; case 5: if (currentArmy() == c.getUnit().getArmy()) { addTroop(c); numSetupTroops--; if (this.turn == numPlayers - 1 && currentArmy().getFreeUnits() == 0) { enterGamePhase(); break; } if (numSetupTroops == 0) { incrementTurn(); numSetupTroops = Math.min(3, currentArmy().getFreeUnits()); } } break; } }
38d4ee7f-c0e4-4ce0-8ca2-e10df20ac1c0
5
public Pays(){ lesDeps = DAO.getLesDeps(); lesSpe = DAO.getLesSpe(); Collection<Medecin> lesMeds = DAO.getLesMeds(); for(Medecin unMed : lesMeds){ for(Departement unDep : lesDeps){ if(unDep.getNum().equals(unMed.getDep())){ unDep.addMedecin(unMed); } } for(Specialite uneSpe : lesSpe){ if(uneSpe.getSpecialite().equals(unMed.getSpe())){ uneSpe.addMed(unMed); } } } }
6c8c6263-f2e5-4648-8cc6-a72d80434ebf
9
@Override public void run() { byte[] buff = new byte[1024 * 8]; BufferedInputStream bufferedInputStream = null; BufferedOutputStream bufferedOutputStream = null; System.err.println("request SERVER <- CLIENT: time:" + System.nanoTime()); try { bufferedInputStream = new BufferedInputStream(socket.getInputStream()); int receiveBufferSize = socket.getReceiveBufferSize(); int read = bufferedInputStream.read(buff); Thread.sleep(300); bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream()); bufferedOutputStream.write(response); bufferedOutputStream.flush(); System.err.println("response SERVER -> CLIENT: time:" + System.nanoTime()); if (bufferedInputStream != null) bufferedInputStream.close(); if (bufferedOutputStream != null) bufferedOutputStream.close(); if (socket != null) socket.close(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }finally { try { if (bufferedInputStream != null) bufferedInputStream.close(); if (bufferedOutputStream != null) bufferedOutputStream.close(); if (socket != null) socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
6e5a3a0d-e7d1-40f5-96d9-8fe55d062be0
2
public boolean isFirstNameChar(int token) { return (isLetter(token) || token == '_' || token == ':'); }
9f606666-b125-4a9e-8dbc-b08438a97b1e
5
public static List<String> getProtectedLines( String fileName ) { List<String> protectedLines = new ArrayList<String>(); File exportFile = new File( fileName ); BufferedReader br = null; try { br = new BufferedReader( new FileReader( exportFile ) ); String line = ""; // find start of protection while ( !line.contains( PROTECTED_CODE ) ) { line = br.readLine(); if ( line == null ) break; } // read next line line = br.readLine(); while ( line != null ) { line = "\n" + line; protectedLines.add( line ); line = br.readLine(); } br.close(); } catch ( FileNotFoundException e ) { // Ignored if file doesn't exist. } catch ( IOException e ) { e.printStackTrace(); } return protectedLines; }
6b3d1355-e178-4eb4-b8e1-6cd383a9df46
7
static public Pkcs12 from(final InputStream input, final char[] password) { notNull(input, "Input"); notNull(password, "Password"); try { final KeyStore p12 = KeyStore.getInstance(KEY_STORE_TYPE, new BouncyCastleProvider()); p12.load(input, password); for (String alias : Collections.list(p12.aliases())) { if (p12.isKeyEntry(alias)) { final Certificate cert = p12.getCertificate(alias); final PrivateKey key = (PrivateKey) p12.getKey(alias, password); if (cert != null && key != null) { return new Pkcs12(cert, key, alias); } } } } catch (IOException e) { if(e.getMessage().toUpperCase().contains("Illegal key size".toUpperCase())) { throw new IllegalArgumentException("Illegal key size found in PKCS12 input. This is usually caused by " + "Java enforcing outdated US export laws. Upgrade to Java 1.7.0_40, change to OpenJDK, or " + "install Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy.", e); } throw new IllegalArgumentException("Unable to read certificate or private key from PKCS12 input", e); } catch (GeneralSecurityException e) { throw new IllegalArgumentException("Unable to unpack certificate or private key from PKCS12 input", e); } throw new IllegalArgumentException("Unable to find certificate and private key in PKCS12 input"); }
c51e9a70-8e90-4198-baed-2792fd140a27
1
@FXML private void noteListClicked(MouseEvent event) { NoteEntity n = noteList.getSelectionModel().getSelectedItem(); if (n != null) { //System.out.println("'click:" + n.getTitle()); } }
acc7bb44-5a77-401f-a9be-3637b86d88dd
8
public int searchAux(int[] A, int target, int low, int high) { //divide into two parts int mid = (low + high) / 2; if (A[mid] == target) { return mid; } if (low > high) { return -1; } //find target in each part if (A[low] <= A[mid]) { if (target >= A[low] && target < A[mid]) { return searchAux(A, target, low, mid - 1); } else { return searchAux(A, target, mid + 1, high); } } else if (A[mid] <= A[low]) { if (target > A[mid] && target <= A[high]) { return searchAux(A, target, mid + 1, high); } else { return searchAux(A, target, low, mid - 1); } } return -1; }
2f52b9e7-82c5-4669-a25f-b05922d40376
8
private static boolean scanAdjNodes(int scanX, int scanY) { // Variables that store coordinates of surrounding nodes int xLower = scanX - 1; int yLower = scanY - 1; int xHigher = scanX + 1; int yHigher = scanY + 1 ; if (x == 0) xLower = x; else if (x == 26) xHigher = x; // Doesn't allow coordinates outside of the edges of the grid if (y == 0) yLower = y; else if (y == 26) yHigher = y; for (int i = xLower; i <= xHigher; i++) { for (int j = yLower; j <= yHigher; j++) { // Stores x,y coordinates if node is set to visible and contains a bala ant if (AntColony.node[i][j].balas != 0 && AntColony.node[i][j].visible == true) { x = i; y = j; return true; } } } return false; // No bala ants in visible adjacent nodes }
3732ab55-0057-4e66-9b7a-2ffacd80338a
1
@Override public void save(YamlPermissionBase holder) throws DataSaveFailedException { holder.save(); try { yamlConfiguration.save(file); } catch (IOException ex) { throw new DataSaveFailedException(ex); } }
b0ae5153-3701-424f-948b-6af86b91cc38
3
private void guiSetupByState() { b.removeAll(); switch(state) { case 0: { b.add(clazzString); b.add(enterButton); } case 1: { b.add(constructors); b.add(enterButton); } case 2: { b.add(paraScroll); b.add(enterButton); } } pack(); }
ad06ed6d-560f-4aa6-be5b-3d244d6bcbe6
2
public void testGetField_int() { LocalDateTime test = new LocalDateTime(COPTIC_PARIS); assertSame(COPTIC_UTC.year(), test.getField(0)); assertSame(COPTIC_UTC.monthOfYear(), test.getField(1)); assertSame(COPTIC_UTC.dayOfMonth(), test.getField(2)); assertSame(COPTIC_UTC.millisOfDay(), test.getField(3)); try { test.getField(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getField(3); } catch (IndexOutOfBoundsException ex) {} }
c1205fd9-3614-4597-8c7e-15aa8751d7bf
3
public static void printmenucategoryConsole(String inCategory) { Connection c = null; Statement stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:Restuarant.db"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM MENU;"); while (rs.next()) { String category = rs.getString("category"); String name = rs.getString("name"); String price = rs.getString("price"); if (category.equals(inCategory)) { System.out.println("CATEGORY = " + category); System.out.println("NAME = " + name); System.out.println("PRICE = " + price); System.out.println("---------------------"); } } rs.close(); stmt.close(); c.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } System.out.println("Operation done successfully"); }
df4fd74b-46cb-41c6-ae2d-357a0ec13613
0
@Test public void testAccumulate() { CircleAccumulator test = new CircleAccumulator(new boolean[][]{ {false, false, true , true , true , false, false}, // Circle with {false, true , false, false, false, true , false}, // Radius 3 and {true , false, false, false, false, false, true }, // Center (3,3) {true , false, false, false, false, false, true }, {true , false, false, false, false, false, true }, {false, true , false, false, false, true , false}, {false, false, true , true , true , false, false}}, 1, 6); test.accumulate(); Set<int[]> temp = test.threshold(16); int[][] result = temp.toArray(new int[temp.size()][3]); System.out.println("Accumulator: " + Arrays.deepToString(test.getAccumulator())); assertEquals("Too many or too few results: " + Arrays.deepToString(result), 1, result.length); assertArrayEquals("Incorrect Result! Actual: " + Arrays.toString(result[0]) + ", Expected: [3, 3, 3]", new int[]{3, 3, 3}, result[0]); }
e4891080-03f5-456e-8f29-9a8ad073ac9c
6
public boolean canShiftRight(){ if(loc1.getColumn() == board.getWidth()-1 || loc2.getColumn() == board.getWidth()-1|| loc3.getColumn() == board.getWidth()-1 || loc4.getColumn() == board.getWidth()-1){ return false; } //gets all of the rightmost locations of the piece ArrayList<Location> rightLocs = getRightLocs(); for(int i = 0; i < rightLocs.size(); i++){ if(board.getValue(rightLocs.get(i).getRow(), rightLocs.get(i).getColumn() + 1) !=0){ return false; } } return true; }
90cbaf68-437a-48e3-a160-54ba0bd982d0
2
protected void createCells(int[][] squares) { cells = new Cell[NCELLS][NCELLS]; for (int row = 0; row < NCELLS; row++) { for (int col = 0; col < NCELLS; col++) { cells[row][col] = new Cell(squares[row][col] == 1); add(cells[row][col]); } } }
80568389-5359-4799-a6d1-5405b3a53166
4
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed if(rec != null && !rec.isVisible()){ lPane.remove(rec); rec = null; } if (rec == null) { rec = new FrmRecebimento(this); Validacoes v = new Validacoes(); v.posicao(this, rec); lPane.add(rec); try { rec.setSelected(true); } catch (PropertyVetoException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); } }else{ rec.toFront(); } }//GEN-LAST:event_jButton2ActionPerformed
777e344f-b1a5-4da1-8177-18537c4a7481
3
public List<Block> getBlocks() { List<Block> blockList = new ArrayList<Block>(); World cuboidWorld = this.getWorld(); for (int x = this.x1; x <= this.x2; x++) { for (int y = this.y1; y <= this.y2; y++) { for (int z = this.z1; z <= this.z2; z++) { blockList.add(cuboidWorld.getBlockAt(x, y, z)); } } } return blockList; }
8a8fdbfe-0598-4c16-8531-3db67a1e6d00
7
@Override protected void connected(Socket socket) { sock = socket; try { sock.setTcpNoDelay(true); try { sock.setTrafficClass(0x10); } catch(SocketException e) { System.out.println("Connection Error! >> " + e.getMessage()); } socketOut = new PrintStream(sock.getOutputStream()); socketIn = sock.getInputStream(); fireConnected(); while (true) { //block until the socket is closed if(!_isConnected) break; } } catch(SocketException e) { System.out.println("Connection Error! >> " + e.getMessage()); } catch(Exception e) { System.out.println("Connection Error! >> " + e.getMessage()); } finally { fireDisconnected(); } try { socket.close(); } catch (Exception e) { System.out.println("Connection Error! >> " + e.getMessage()); } _isConnected=false; try { Thread.sleep(5000); } catch (Exception e) {} }
f4eed2d5-aa56-440e-93ea-9df531f03697
1
public static final String toId(Enum<?> value) { return value.name().toLowerCase().replace('_', ' '); }
011f62dc-4c36-486b-8388-8b6c17a888e9
7
public void testValidEdge3() { try { TreeNode tree = new TreeNode("tree", 2); TreeNode subtree = new TreeNode("spare-subtree"); tree.setBranch(new TreeNode[]{ subtree, new TreeNode("subtree")}); setTree(tree); TreeNode realTree = ((Question1)answer); ((Question1)answer).deleteSubTree(realTree, 1); assertTrue(null, "Your code has incorrectly deleted a leaf node from a 2-branching tree", ((String)(realTree.getData())).equals("tree") && realTree.getBranch().length == 2 && realTree.getBranch()[0] == subtree && realTree.getBranch()[1] == null); } catch(TreeException exn) { fail(exn, "Your code threw a `TreeException`. Possible causes: \n* Remember that the `root` node has a `label`.\n* Maybe you are using your parameters incorrectly?\n* Maybe you are using `==` instead of the `equals` method when testing labels?"); } catch(NullPointerException exn) { fail(exn, "Your code threw an `NullPointerException`. Possible causes: \n* Remember that the `root` node has a `label`.\n* Maybe you are using your node parameter incorrectly?\n* Maybe you have assumed that edge numbering starts at 1?\n* Has your code forgotten to `exclude` the branch array's size as an index value?"); } catch(ArrayIndexOutOfBoundsException exn) { fail(exn, "Your code threw an `ArrayIndexOutOfBoundsException`. Possible causes: \n* Remember that the `root` node has a `label`.\n* Maybe you are using your node parameter incorrectly?\n* Maybe you have assumed that edge numbering starts at 1?\n* Has your code forgotten to `exclude` the branch array's size as an index value?"); } catch(Throwable exn) { fail(exn, "No exception's should be generated, but your code threw: " + exn.getClass().getName()); } // end of try-catch } // end of method testValidEdge3
45aec501-6b68-427a-9a1f-30f3efcba43b
3
private ArrayList<Element> listeDesNoeudsFils(Element e, String name) { ArrayList< Element> listeDesNoeudFils= new ArrayList<Element>(); NodeList listeDeNoeudsXML= e.getChildNodes(); Node noeudXML= null; for (int i=0;i<listeDeNoeudsXML.getLength();i++) { noeudXML= listeDeNoeudsXML.item(i); if (noeudXML.getNodeName().equals(name) && (noeudXML.getNodeType()== Node.ELEMENT_NODE)) { Element child= (Element)noeudXML; listeDesNoeudFils.add(child); } } return listeDesNoeudFils; }
b963c13e-53a1-48d5-a62f-155382d34e25
3
public void setLeft(PExp node) { if(this._left_ != null) { this._left_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._left_ = node; }
1f3afb66-c86c-469e-bbf1-ab910195811c
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UserPO other = (UserPO)obj; if (this.password == null) { if (other.password != null) return false; } else if (!this.password.equals(other.password)) return false; if (this.username == null) { if (other.username != null) return false; } else if (!this.username.equals(other.username)) return false; return true; }
b182820f-9493-45ba-a843-7db56d0e16f9
2
public static String dcnEncode(String string){ char[] replacements = null; int i = 0; int index = 0; replacements = new char[]{0,5,36,96,124,126}; for(i=0;i<replacements.length;i++){ while((index = string.indexOf(replacements[i])) >=0 ){ string = string.substring(0,index) + "/%DCN"+leadz(replacements[i])+"%/" + string.substring(index+1,string.length()); } } return(string); }
37e69989-49d7-4839-88fe-0da3c9eb2ee2
0
public T find(Object id) { return getEntityManager().find(entityClass, id); }
8d632f6b-6f24-4a6c-998c-1efe92442c4c
4
public void refreshPanel() { if (Sessie.getIngelogdeGebruiker().heeftPermissie( PermissieHelper.permissies.get("BEHEERALLEVAKKEN"))) { List<Vak> vakken = Dao.getInstance().getVakken(); vakLijst.clear(); for (Vak vak : vakken) { vakLijst.addElement(vak); } } else if (Sessie.getIngelogdeGebruiker().heeftPermissie( PermissieHelper.permissies.get("BEHEEREIGENVAKKEN"))) { List<Vak> vakken = Dao.getInstance().getVakkenVanDocent( Sessie.getIngelogdeGebruiker().getId()); vakLijst.clear(); for (Vak vak : vakken) { vakLijst.addElement(vak); } } }
70900ddb-e87c-4177-a62b-61f5408de054
5
private void updateFields(Object selectedItem) { for (Team t : c.getTeams()) { if (t.getName().equals(selectedItem.toString())) { avgscore.setText(String.valueOf(t.getAverageScore())); lowscore.setText(String.valueOf(t.getLowscore())); highscore.setText(String.valueOf(t.getHighestScore())); } } boolean set = false; for (Rankbit r : rankbits) { if (selectedItem.toString().equals(r.getTeamnumber())) { set = true; rank.setText(String.valueOf(r.getRank())); sppoints.setText(r.getWPSP()); } } if(!set){ rank.setText("DNQ"); sppoints.setText("DNQ"); } }
82385b9e-584c-4a6b-9174-9ab885db41a6
6
public static void addRecent(File file) { String extension = PathUtils.getExtension(file.getName()); if (Platform.isMacintosh() || Platform.isWindows()) { extension = extension.toLowerCase(); } for (String allowed : FileType.getOpenableExtensions()) { if (allowed.equals(extension)) { if (file.canRead()) { file = PathUtils.getFile(PathUtils.getFullPath(file)); RECENTS.remove(file); RECENTS.add(0, file); if (RECENTS.size() > MAX_RECENTS) { RECENTS.remove(MAX_RECENTS); } } break; } } }
b405286b-2498-4682-8909-83f80dcebbcf
0
private boolean logging_enabled() { synchronized (logging_enabled) { return logging_enabled; } }
e9dd3ba5-147f-4cce-9b81-6ca8cabf4f5f
3
public void buttonP() { if(bChina.contains(Main.mse)) { Main.soundPlayer.menuKlick(); Main.startGame(GameData.createData("China", ""), true); } else if(bMiddleAge.contains(Main.mse)) { Main.soundPlayer.menuKlick(); Main.startGame(GameData.createData("MiddleAge", ""), true); } else if(bModern.contains(Main.mse)) { Main.soundPlayer.menuKlick(); Main.startGame(GameData.createData("Modern", ""), true); } }
833c2f8d-5d2f-4b8a-9b71-0cc03e9ecd09
4
protected void readVvAdd(float[][] a, BitInputStream source, int offset, int length) throws VorbisFormatException, IOException { int i,j;//k;//entry; int chptr=0; int ch=a.length; if(ch==0) { return; } int lim=(offset+length)/ch; for(i=offset/ch;i<lim;){ final float[] ve=valueVector[source.getInt(huffmanRoot)]; for(j=0;j<dimensions;j++){ a[chptr++][i]+=ve[j]; if(chptr==ch){ chptr=0; i++; } } } }
c92feb2e-4c48-422d-b795-6dd29daede7f
8
public List<Token> postProcess(List<Token> tokens) { if (tokens.size() == 0) { return tokens; } List<Token> newTokens = new ArrayList<Token>(); for (int i = 0; i < tokens.size(); i++) { Token token = tokens.get(i); String compoundInfo = this.compoundTable.get(token.getMorpheme().toString()); if (compoundInfo == null) { newTokens.add(token); continue; } StringTokenizer st = new StringTokenizer(compoundInfo); int start = token.getStart(); while (st.hasMoreTokens()) { String termInfo = st.nextToken(); Token newToken = new Token(); String surface = getField(termInfo, 0); newToken.setSurface(surface); StringBuffer partOfSpeech = new StringBuffer(getField(termInfo, 2)); String tmp = getField(termInfo, 3); if (!tmp.equals("*")) { partOfSpeech.append("-").append(tmp); } tmp = getField(termInfo, 4); if (!tmp.equals("*")) { partOfSpeech.append("-").append(tmp); } tmp = getField(termInfo, 5); if (!tmp.equals("*")) { partOfSpeech.append("-").append(tmp); } newToken.getMorpheme().setPartOfSpeech(new String(partOfSpeech)); newToken.getMorpheme().setConjugationalType(getField(termInfo, 6)); newToken.getMorpheme().setConjugationalForm(getField(termInfo, 7)); newToken.getMorpheme().setBasicForm(getField(termInfo, 8)); newToken.getMorpheme().setReadings(Arrays.asList(getField(termInfo, 9))); newToken.getMorpheme().setPronunciations(Arrays.asList(getField(termInfo, 10))); newToken.setCost(token.getCost()); if (getField(termInfo, 11).equals("-")) { newToken.getMorpheme().setAdditionalInformation("p=" + token.getMorpheme().getPartOfSpeech()); } else { newToken.getMorpheme().setAdditionalInformation(getField(termInfo, 11)); } newToken.setLength(surface.length()); newToken.setStart(start); start += surface.length(); newTokens.add(newToken); } } return newTokens; }
82706d3d-3a88-44cd-8780-0dc06169986a
3
private void save_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_save_buttonActionPerformed for (int i = 0; i < rubric_table.getColumnCount(); i++) { try { GradeAccess.enterGrade(studentID, courseID, actName, rubric_table.getModel().getValueAt(i, 0).toString(), Float.parseFloat(rubric_table.getModel().getValueAt(i, 1) .toString())); } catch (NumberFormatException e) { e.printStackTrace(); } catch (SQLException e) { GradeAccess.updateGrade(studentID, courseID, actName, rubric_table.getModel().getValueAt(i, 0).toString(), Float.parseFloat(rubric_table.getModel().getValueAt(i, 1) .toString())); } } setOkToNav(); JOptionPane.showMessageDialog(this,"Grade saved."); }//GEN-LAST:event_save_buttonActionPerformed
cdcbaa0b-8960-4a97-8657-b6e580e4d833
2
public void roll(int pins) { frames[currentIndex].addRoll(pins); if (frames[currentIndex].isFull()) { if (currentIndex != 0) { frames[currentIndex - 1].setNextFrame(frames[currentIndex]); } currentIndex++; } }
9104d6b2-e02b-41ee-a39d-122b0f6b529f
7
public static void hookdr_f77(int n, double x[], double f[], double g[], double a[][], double udiag[], double p[], double xpls[], double fpls[], Uncmin_methods minclass, double sx[], double stepmx[], double steptl[], double dlt[], int iretcd[], boolean mxtake[], double amu[], double dltp[], double phi[], double phip0[], double sc[], double xplsp[], double wrk0[], double epsm, int itncnt[]) { /* Here is a copy of the hookdr FORTRAN documentation: SUBROUTINE HOOKDR(NR,N,X,F,G,A,UDIAG,P,XPLS,FPLS,FCN,SX,STEPMX, + STEPTL,DLT,IRETCD,MXTAKE,AMU,DLTP,PHI,PHIP0, + SC,XPLSP,WRK0,EPSM,ITNCNT,IPR) C C PURPOSE C ------- C FIND A NEXT NEWTON ITERATE (XPLS) BY THE MORE-HEBDON METHOD C C PARAMETERS C ---------- C NR --> ROW DIMENSION OF MATRIX C N --> DIMENSION OF PROBLEM C X(N) --> OLD ITERATE X[K-1] C F --> FUNCTION VALUE AT OLD ITERATE, F(X) C G(N) --> GRADIENT AT OLD ITERATE, G(X), OR APPROXIMATE C A(N,N) --> CHOLESKY DECOMPOSITION OF HESSIAN IN LOWER C TRIANGULAR PART AND DIAGONAL. C HESSIAN IN UPPER TRIANGULAR PART AND UDIAG. C UDIAG(N) --> DIAGONAL OF HESSIAN IN A(.,.) C P(N) --> NEWTON STEP C XPLS(N) <-- NEW ITERATE X[K] C FPLS <-- FUNCTION VALUE AT NEW ITERATE, F(XPLS) C FCN --> NAME OF SUBROUTINE TO EVALUATE FUNCTION C SX(N) --> DIAGONAL SCALING MATRIX FOR X C STEPMX --> MAXIMUM ALLOWABLE STEP SIZE C STEPTL --> RELATIVE STEP SIZE AT WHICH SUCCESSIVE ITERATES C CONSIDERED CLOSE ENOUGH TO TERMINATE ALGORITHM C DLT <--> TRUST REGION RADIUS C IRETCD <-- RETURN CODE C =0 SATISFACTORY XPLS FOUND C =1 FAILED TO FIND SATISFACTORY XPLS SUFFICIENTLY C DISTINCT FROM X C MXTAKE <-- BOOLEAN FLAG INDICATING STEP OF MAXIMUM LENGTH USED C AMU <--> [RETAIN VALUE BETWEEN SUCCESSIVE CALLS] C DLTP <--> [RETAIN VALUE BETWEEN SUCCESSIVE CALLS] C PHI <--> [RETAIN VALUE BETWEEN SUCCESSIVE CALLS] C PHIP0 <--> [RETAIN VALUE BETWEEN SUCCESSIVE CALLS] C SC(N) --> WORKSPACE C XPLSP(N) --> WORKSPACE C WRK0(N) --> WORKSPACE C EPSM --> MACHINE EPSILON C ITNCNT --> ITERATION COUNT C IPR --> DEVICE TO WHICH TO SEND OUTPUT C */ int i,j; boolean fstime[] = new boolean[2]; boolean nwtake[] = new boolean[2]; double tmp,rnwtln,alpha,beta; double fplsp[] = new double[2]; iretcd[1] = 4; fstime[1] = true; tmp = 0.0; for (i = 1; i <= n; i++) { tmp += sx[i]*sx[i]*p[i]*p[i]; } rnwtln = Math.sqrt(tmp); if (itncnt[1] == 1) { amu[1] = 0.0; // IF FIRST ITERATION AND TRUST REGION NOT PROVIDED BY USER, // COMPUTE INITIAL TRUST REGION. if (dlt[1] == -1.0) { alpha = 0.0; for (i = 1; i <= n; i++) { alpha += (g[i]*g[i])/(sx[i]*sx[i]); } beta = 0.0; for (i = 1; i <= n; i++) { tmp = 0.0; for (j = i; j <= n; j++) { tmp += (a[j][i]*g[j])/(sx[j]*sx[j]); } beta += tmp*tmp; } dlt[1] = alpha*Math.sqrt(alpha)/beta; dlt[1] = Math.min(dlt[1],stepmx[1]); } } while (iretcd[1] > 1) { // FIND NEW STEP BY MORE-HEBDON ALGORITHM Uncmin_f77.hookst_f77(n,g,a,udiag,p,sx,rnwtln,dlt, amu,dltp,phi,phip0, fstime,sc,nwtake,wrk0,epsm); dltp[1] = dlt[1]; // CHECK NEW POINT AND UPDATE TRUST REGION Uncmin_f77.tregup_f77(n,x,f,g,a,minclass,sc,sx,nwtake,stepmx, steptl,dlt,iretcd,xplsp,fplsp,xpls,fpls, mxtake,3,udiag); } return; }
de60a550-1e40-451b-b9f2-8cc76a7aa12f
8
private static void dfs(int i, int j, int cost, int time) { if (!inBoard(i, j) || cost >= costs[i][j]) { return; } costs[i][j] = cost; if (board[i][j] == '*') { return; } if (time == k) { return; } dfs(i - 1, j, board[i][j] == 'U' ? cost : cost + 1, time + 1); dfs(i, j - 1, board[i][j] == 'L' ? cost : cost + 1, time + 1); dfs(i + 1, j, board[i][j] == 'D' ? cost : cost + 1, time + 1); dfs(i, j + 1, board[i][j] == 'R' ? cost : cost + 1, time + 1); }