method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
e0ac918d-aff8-4028-9a70-67f738c56f5c
5
public static void saveRegion( Region region, File dir ) { File f = new File( dir, String.format( "r%d %d %d.gven.dat", region.x, region.y, region.z ) ); if ( !createFile( f ) ) { return; } Chunk[] chunks = region.getChunks(); int[][] chunkCoords = new int[ chunks.length ][ 3 ]; byte[][] voxels = new byte[ chunks.length ][ chunks[ 0 ].getVoxels().length ]; for ( int i = 0; i < chunks.length; i++ ) { chunkCoords[ i ][ 0 ] = chunks[ i ].x; chunkCoords[ i ][ 1 ] = chunks[ i ].y; chunkCoords[ i ][ 2 ] = chunks[ i ].z; for ( int j = 0; j < voxels[ i ].length; j++ ) { voxels[ i ][ j ] = chunks[ i ].getVoxels()[ j ]; } } try { DataOutputStream dos = new DataOutputStream( new FileOutputStream( f ) ); // schedule writes for each chunk for ( int i = 0; i < chunks.length; i++ ) { Scheduler.enqueueEvent( "writeChunk", RegionIO.class, dos, chunkCoords[ i ], voxels[ i ] ); } // scheduler the closing of the stream after all the writes Scheduler.enqueueEvent( "close", dos ); // closes the stream after everything has been written } catch ( Exception e ) { Lumberjack.throwable( "RegSave", e ); } }
ec1f3262-3ab6-4265-b136-9edfc23e9ae0
3
Transcript createTranscript(Gene gene, String trId) { int start = gene.getStart(), end = gene.getEnd(); Transcript tr = new Transcript(gene, gene.getStart(), gene.getEnd(), gene.getStrand(), "transcript_" + trId); tr.setProteinCoding(true); add(tr); // Add exons int numEx = Math.max(random.nextInt(maxExons), 1); for (int ne = 0; ne < numEx; ne++) { // Non-overlapping exons int size = tr.size() / numEx; start = tr.getStart() + size * ne + random.nextInt(size / 2); end = start + random.nextInt(size / 2); Exon exon = new Exon(tr, start, end, gene.getStrand(), "exon_" + trId + "_" + ne, ne + 1); // Set exon sequence String seq = chromoSequence.substring(start, end + 1); if (exon.isStrandMinus()) seq = GprSeq.reverseWc(seq); // Reverse strand? => reverse complement of the sequence exon.setSequence(seq); add(exon); } // Add UTRs if (addUtrs) createUtrs(tr); tr.adjust(); tr.rankExons(); return tr; }
7b3abd49-7595-472c-82d6-2ad797e6ab9f
3
private Cipher createAndInitialiseContentCipher( ByteBuffer encrypted, byte[] decryptionKeyBytes) throws PDFParseException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { final Cipher cipher; if (encryptionAlgorithm.isRC4()) { cipher = Cipher.getInstance(CIPHER_RC4); cipher.init(Cipher.DECRYPT_MODE, createRC4Key(decryptionKeyBytes)); } else if (encryptionAlgorithm.isAES()) { cipher = createAESCipher(); final byte[] initialisationVector = new byte[16]; if (encrypted.remaining() >= initialisationVector.length) { encrypted.get(initialisationVector); } else { throw new PDFParseException( "AES encrypted stream too short - " + "no room for initialisation vector"); } final SecretKeySpec aesKey = new SecretKeySpec(decryptionKeyBytes, KEY_AES); final IvParameterSpec aesIv = new IvParameterSpec(initialisationVector); cipher.init(Cipher.DECRYPT_MODE, aesKey, aesIv); } else { throw new PDFParseException( "Internal error - unhandled cipher type: " + encryptionAlgorithm); } return cipher; }
370cf007-fb08-494a-8b1c-e322c0546523
4
private void getKeys() { try { generatedKeys = (List<KeyPair>)((new ObjectInputStream(new FileInputStream(SCRATCH_PATH))).readObject()); } catch( Exception e ) { System.err.println("couldn't get scratch keys: " + e.toString()); System.out.println("generating keys..."); CryptoUtils c = new CryptoUtils(); generatedKeys = new LinkedList<KeyPair>(); for( int i=0; i<200; i++ ) { if( (i%100) == 0 ) { System.out.println("done " + i); } generatedKeys.add(c.getPair()); } System.out.println("done, writing..."); try { (new ObjectOutputStream(new FileOutputStream(SCRATCH_PATH))).writeObject(generatedKeys); } catch (Exception e2 ) { e.printStackTrace(); } System.out.println("done"); } }
4757e924-ca8b-42e2-a471-2ac89bf24353
6
public void downloadVideo(String ytLink){ final String[] args = new String[]{"youtube-dl.exe","-c", ytLink}; final String vidString = ytLink.substring(ytLink.indexOf("watch?v=")+8); try { youtubeProc = Runtime.getRuntime().exec(args); downloadThread = new Thread(){ public void run(){ BufferedReader input = new BufferedReader(new InputStreamReader(youtubeProc.getInputStream())); String line=""; try { while ((line=input.readLine())!=null){ log(line); if ((line.contains ("[youtube:channel]")) || (line.contains("Downloading video #"))){ log("Couldn't find a good video. Manually put in youtube link."); log("Args: "+args.toString()); log("vidString: "+vidString); break; } } } catch (IOException e) { e.printStackTrace(); } if (!isCancelled){ log("Converting"); setOpenVideoButtonEnabled(true); convertVideoToMp3(vidString); } } }; downloadThread.start(); } catch (IOException e1) { e1.printStackTrace(); SongDownloader.messageBox("You need youtube-dl.exe in the same folder as the program to run this."); } }
c2fd846a-e089-4d10-9953-b8bbba49848d
5
@EventHandler(priority = EventPriority.LOWEST) public void onPlayerRespawn(PlayerRespawnEvent e){ File fichier_language = new File(OneInTheChamber.instance.getDataFolder() + File.separator + "Language.yml"); final FileConfiguration Language = YamlConfiguration.loadConfiguration(fichier_language); final String PartiePerdue = UtilChatColor.colorizeString(Language.getString("Language.Arena.Player_lost")); final Player player = e.getPlayer(); if(ArenaManager.getArenaManager().isInArena(player)){ final Arena arena = ArenaManager.getArenaManager().getArenaByPlayer(player); if(arena.getStatus() == Status.INGAME){ final PlayerArena pa = PlayerArena.getPlayerArenaByPlayer(player); new BukkitRunnable() { @Override public void run() { if(pa.getLives() < 1){ String JoueurAPerdu = UtilChatColor.colorizeString(Language.getString("Language.Arena.Broadcast_player_lost")).replaceAll("%player", player.getName()); arena.removePlayer(player, PartiePerdue, JoueurAPerdu); }else{ Random rand = new Random(); int nbAlea = rand.nextInt(arena.getSpawnsLocations().size()); pa.getPlayer().teleport(arena.getSpawnsLocations().get(nbAlea)); pa.loadGameInventory(); pa.getArena().updateScores(); } } }.runTaskLater(OneInTheChamber.instance, 1L); }else if(arena.getStatus() == Status.STARTING || arena.getStatus() == Status.JOINABLE){ new BukkitRunnable() { @Override public void run() { player.teleport(arena.getStartLocation()); } }.runTaskLater(OneInTheChamber.instance, 1L); } } }
b8b1507c-aa75-4e3b-873c-7c21de9883fb
2
public boolean remove(Class<?> type) { T removed = provided.remove(type); if (removed != null) { provided.values().removeAll(Arrays.asList(removed)); return true; } return false; }
e0cc425a-a730-42e0-a28f-ede0e7d6f3ab
8
private Polygon rectangleShadow(int x, int y, int shapeX, int shapeY, int width, int height) { int[] xPoints = {0, 0, 0, 0, 0}; int[] yPoints = {0, 0, 0, 0, 0}; //Left side of screen if (x > shapeX + width) { //top if (y > shapeY + height) { xPoints = new int[] {shapeX, shapeX, shapeX + width, shapeX + width - (x - (shapeX + width))*10, shapeX - (x - shapeX)*10}; yPoints = new int[] {shapeY + height, shapeY, shapeY, shapeY - (y - shapeY)*10, shapeY + height - (y - (shapeY + height))*10}; } //bottom else if (y < shapeY) { xPoints = new int[] {shapeX, shapeX, shapeX + width, shapeX + width - (x - (shapeX + width))*10, shapeX - (x - shapeX)*10}; yPoints = new int[] {shapeY, shapeY + height, shapeY + height, shapeY + height - (y - (shapeY + height))*10, shapeY - (y - shapeY)*10}; } //left else { xPoints = new int[]{shapeX + width, shapeX, shapeX, shapeX + width, shapeX + width - (x - (shapeX + width))*10, shapeX + width - (x - (shapeX + width))*10}; yPoints = new int[]{shapeY + height, shapeY + height, shapeY, shapeY, shapeY - (y - shapeY)*10, shapeY + height - (y - (shapeY + height))*10}; } } //Right side of screen else if (x < shapeX) { //top if (y > shapeY + height) { xPoints = new int[] {shapeX, shapeX + width, shapeX + width, shapeX + width - (x - (shapeX + width))*10, shapeX - (x - shapeX)*10}; yPoints = new int[] {shapeY, shapeY, shapeY + height, shapeY + height - (y - (shapeY + height))*10, shapeY - (y - shapeY)*10}; } //bottom else if (y < shapeY) { xPoints = new int[] {shapeX + width, shapeX + width, shapeX, shapeX - (x - (shapeX))*10, shapeX + width - (x - (shapeX + width))*10}; yPoints = new int[] {shapeY, shapeY + height, shapeY + height, shapeY + height - (y - (shapeY + height))*10, shapeY - (y - shapeY)*10}; } //Right else { xPoints = new int[]{shapeX, shapeX + width, shapeX + width, shapeX, shapeX - (x - shapeX)*10, shapeX - (x - shapeX)*10}; yPoints = new int[]{shapeY, shapeY, shapeY + height, shapeY + height, shapeY + height - (y - (shapeY + height))*10, shapeY - (y - (shapeY))*10}; } } //middle else{ if(y > shapeY + height){ xPoints = new int[]{shapeX, shapeX, shapeX + width, shapeX + width, shapeX + width - (x - (shapeX + width))*10, shapeX - (x - shapeX)*10}; yPoints = new int[]{shapeY + height, shapeY, shapeY, shapeY + height, shapeY + height - (y - (shapeY + height))*10, shapeY + height- (y - (shapeY + height))*10}; } else if(y < shapeY){ xPoints = new int[]{shapeX, shapeX, shapeX + width, shapeX + width, shapeX + width - (x - (shapeX + width))*10, shapeX - (x - shapeX)*10}; yPoints = new int[]{shapeY, shapeY + height, shapeY + height, shapeY, shapeY - (y - shapeY)*10, shapeY - (y - shapeY)*10}; } } return new Polygon(xPoints, yPoints, xPoints.length); }
d75dc2ed-c8e6-410d-85d2-f76a9ab3f1b3
9
private boolean HandleMiscCommand(String s) { if (s.equals("i") || s.equals("inventory")) { if (! inventory.isEmpty()) { String invStr = inventory.toString(); invStr = invStr.split("\\[")[1]; invStr = invStr.split("\\]")[0]; System.out.println("inventory: " + invStr); } else { System.out.println("inventory empty"); } return true; } else if (s.equals("h") || s.equals("help")) { System.out.println("The following commands are available:"); System.out.println("n, s, e, w"); System.out.println("look"); System.out.println("inventory, i"); System.out.println("take (item)"); System.out.println("read (item)"); System.out.println("drop (item)"); System.out.println("turn on (item)"); System.out.println("put (item) in (container)"); System.out.println("attack (creature) with (item)"); System.out.println("open (container)"); System.out.println("open exit"); return true; } else if (s.equals("look")) { if (currentRoom.GetItems().isEmpty() && currentRoom.GetCreatures().isEmpty() && currentRoom.GetContainers().isEmpty()) { System.out.println("The room is empty."); } else { System.out.print("you see a "); PrintCurrentRoomItems(); PrintCurrentRoomContainers(); PrintCurrentRoomCreatures(); System.out.println(""); } return true; } else { System.out.println("Bad command"); return false; } }
d7696800-ac4c-475a-9a44-31b1609becd3
3
@Override public void execute(CommandSender arg0, String[] arg1) { if (!arg0.hasPermission("BungeeSuite.admin")) { arg0.sendMessage(plugin.NO_PERMISSION); return; } if (arg1.length == 1) { if (arg1[0].equalsIgnoreCase("reload")) { plugin.reload(); arg0.sendMessage("All configs for BungeeSuite reloaded"); } } }
5d119956-064f-40fd-8b48-ee93496e7768
8
public void afficherPiece(Piece piece, JPanel panel) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { panel.getComponent(i + j * 4).setBackground(Color.DARK_GRAY); } } if (piece != null) { int positiony = 0; int positionx = 0; if (piece.getLongueur() < 3) { positiony = 1; } if (piece.getLargeur() < 3) { positionx = 1; } for (int y = 0; y < piece.getLongueur(); y++) { for (int x = 0; x < piece.getLargeur(); x++) { if (piece.getMatrice()[y][x] == null) { panel.getComponent(x + positionx + (y + positiony) * 4).setBackground(Color.DARK_GRAY); } else { panel.getComponent(x + positionx + (y + positiony) * 4).setBackground(piece.getMatrice()[y][x].getCouleur()); } } } } }
bdc59219-4478-4e11-8c37-7934619cb99b
2
public Main () { int nCounters = 3; YourMonitor mon = new YourMonitor(nCounters); DisplayHandler disp = new DisplayHandler(mon); ClerkHandler[] clerk = new ClerkHandler[nCounters]; for (int i=0; i<nCounters; i++) clerk[i] = new ClerkHandler(mon, i); CustomerHandler dispenser = new CustomerHandler(mon); disp.start(); for (int i=0; i<nCounters; i++) clerk[i].start(); dispenser.start(); System.out.println("\n\n"+"Main: Threads are running ..."); }
c79ac8b8-3bca-44fc-b53f-c63c8046a6b0
9
public static void main(String[] args) throws IOException { BufferedReader in; StringBuilder out = new StringBuilder(); File f = new File("entrada"); if (f.exists()) { in = new BufferedReader(new FileReader(f)); } else in = new BufferedReader(new InputStreamReader(System.in)); int HPy, ATKy, DEFy, HPm, ATKm, DEFm; int priceH, priceA, priceD; int d[]; int temp; int minPrice = Integer.MAX_VALUE; int hitM; int hitY; d = readInts(in.readLine()); HPy = d[0]; ATKy = d[1]; DEFy = d[2]; d = readInts(in.readLine()); HPm = d[0]; ATKm = d[1]; DEFm = d[2]; d = readInts(in.readLine()); priceH = d[0]; priceA = d[1]; priceD = d[2]; for (int hp = 0; hp <= 1000; hp++) { for (int atk = 0; atk <= 1000; atk++) { for (int def = 0; def <= 1000; def++) { temp = hp * priceH + atk * priceA + def * priceD; if (temp > minPrice) break; if (temp < minPrice) { if (DEFy + def >= ATKm) hitM = Integer.MAX_VALUE; else hitM = (int) Math.ceil((HPy + hp) * 1.0 / (ATKm - (DEFy + def))); if (DEFm >= ATKy + atk) hitY = Integer.MAX_VALUE; else hitY = (int) Math.ceil(HPm * 1.0 / ((ATKy + atk) - DEFm)); if (hitM > hitY) { minPrice = temp; } } } } } System.out.println(minPrice); }
aea08bb6-bd61-49a6-b580-ba8afaa9c60b
3
public void visitPhiCatchStmt(final PhiCatchStmt stmt) { if (stmt.target() != null) { stmt.target().visit(this); } print(" := Phi-Catch("); final Iterator e = stmt.operands().iterator(); while (e.hasNext()) { final Expr operand = (Expr) e.next(); operand.visit(this); if (e.hasNext()) { print(", "); } } println(")"); }
79c4a72e-bf84-4be7-9fe3-b5c33e4698e9
6
private String constructTagAttributesQuery(String regExp, String qualification, String[][] values) { String selectqry = ""; String columnName = ""; if (qualification.equalsIgnoreCase("Tags")) { selectqry = " SELECT TAG_ENTITY_UUID FROM TAGS" + " WHERE UPPER(TAG_NAME)"; columnName = "UPPER(TAG_NAME)"; } else { selectqry = " SELECT ATTRIBUTE_ORGANIZATIONAL_UUID" + " FROM attributes WHERE UPPER(ATTRIBUTE_VALUE)"; columnName = "UPPER(ATTRIBUTE_VALUE)"; } String qry = selectqry; int groups = values.length; for (int i = 0; i < groups; i++) { int numValues = values[i].length; if (regExp.equalsIgnoreCase("on")) { qry += " ~* ?"; for (int j = 1; j < numValues; j++) qry += " OR " + columnName + " ~* ?"; } else { qry += " IN (?"; for (int j = 1; j < numValues; j++) qry += ",?"; qry += ")"; } if (i != groups - 1) qry += " INTERSECT " + selectqry; } return qry; }
08e6fc68-206e-445d-8d41-75c7fd8a30fb
1
@Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; }
70e7d38d-e0d9-45e4-a87c-e415fad4c5dc
6
private <T> ArrayList<Method> findTestMethods(T object, String testname) { Method[] allMethods = findAllMethods(object.getClass()); ArrayList<Method> allNamed = new ArrayList<Method>(); Class<?>[] testerParam = new Class[] { this.getClass() }; // make a list of all methods with the given name for (Method method : allMethods) { if (method.getName().startsWith("test") && this.matchParams(method.getParameterTypes(), testerParam)) { allNamed.add(method); Reflector.ensureIsAccessible(method); } else if (method.getAnnotation(TestMethod.class) != null) { allNamed.add(method); Reflector.ensureIsAccessible(method); } } if (allNamed.size() > 0) { // found test methods that matched the given parameter list testname = testname + "Found " + allNamed.size() + " test methods"; return allNamed; } // no test methods that matched the given parameter list else { testname = testname + "\nNo method with the name test..." + " found in the class " + object.getClass().getName() + "\n"; return null; } }
458e0679-3711-4e0d-88c6-eb9938a762cf
5
private void subdivide(EChannel cod_info) { int scfb_anz = 0; if ( bigvalues_region == 0) { /* no big_values region */ cod_info.region0_count = 0; cod_info.region1_count = 0; } else { if ( cod_info.window_switching_flag == 0 ) { int index0, index1; /* Calculate scfb_anz */ while (scalefac_band_long[scfb_anz] < bigvalues_region) scfb_anz++; /* assert (scfb_anz < 23); */ index0 = (cod_info.region0_count = subdv_table[scfb_anz][0]) + 1; index1 = (cod_info.region1_count = subdv_table[scfb_anz][1]) + 1; cod_info.address1 = scalefac_band_long[index0]; cod_info.address2 = scalefac_band_long[index0 + index1]; cod_info.address3 = bigvalues_region; } else { if ( (cod_info.block_type == 2) && (cod_info.mixed_block_flag == 0) ) { cod_info.region0_count = 8; cod_info.region1_count = 12; cod_info.address1 = 36; } else { cod_info.region0_count = 7; cod_info.region1_count = 13; cod_info.address1 = scalefac_band_long[ cod_info.region0_count + 1 ]; } cod_info.address2 = bigvalues_region; cod_info.address3 = 0; } } }
afcb36b2-0214-42a7-b351-4732d7d5ab5a
3
public ArrayList<String> parseTemplate(ArrayList<String> data,ArrayList<String> expressions){ int position; ArrayList<String> newTemplate = new ArrayList<String>(); for(String line : template){ for(int i = 0; i < data.size();i++){ String temp = expressions.get(i); // Get expression position = line.indexOf(temp); // get position of expression if(position != -1){ // Replace replacement expression with data line = line.substring(0, position + temp.length() - replacement.length()) + data.get(i) + line.substring(position + temp.length()); } } // After replacing all content, add changed row to array newTemplate.add(line); } return newTemplate; }
164ac95e-c1c5-45c6-804c-c03c5f35a5a9
4
public void upgrade() { if(canUpgrade) { ArrayList<Object> deedNames = new ArrayList<Object>(); for (int i = 0; i < deeds.size(); i++) { Property prop = deeds.get(i); if (prop instanceof Street) deedNames.add(prop.name); } String[] names = deedNames.toArray(new String[deedNames.size()]); String s = (String)JOptionPane.showInputDialog(null, "Which property do you want to upgrade?", "Property Upgrade", JOptionPane.QUESTION_MESSAGE, null, names, names[0] ); if (s != null) { int result = Arrays.asList(names).indexOf(s); Street choice = (Street)deeds.get(result); choice.upgradeStreet(this); } } }
457806cd-67e5-4b9b-8808-0fe66aeca92a
3
@Override public void keyTyped(KeyEvent e) { /* * if (keys.contains(KeyEvent.VK_COMMA) && speed - 50 >= 1) { * timer.cancel(); speed -= 50; setTimers(); } if * (keys.contains(KeyEvent.VK_PERIOD)) { timer.cancel(); speed += 50; * setTimers(); } */ if (keys.contains(KeyEvent.VK_ESCAPE)) { if (state == 0) { state = 1; } else if (state == 1) { state = 0; } } }
cbd587e7-73fd-460a-a081-a930e4f62304
0
public void decoder(int[] octets_data){ }
5fb3b7fa-d3b0-43b1-ba07-6becb6be8425
8
public Path shortestPath(int x1, int y1, int x2, int y2){ if(x1<0 || x2<0 || y1<0 || y2<0 || x1>(width-1) || x2>(width-1) || y1>(height-1) || y2>(height-1)){ return null; } PathFinder pf = new AStar(this.graph,this); return pf.shortestPath(this.grid.get(new Coordinate(x1,y1)), this.grid.get(new Coordinate(x2,y2))); }
e977eae0-e8d3-4589-b1f0-92d1efa073d9
0
public int getSeconds() { return (int) (this.numSamples / this.sampleRateHz); }
790aba3b-245c-41a8-b307-6d0c71e41b34
2
protected void play(InputStream in, AudioDevice dev) throws JavaLayerException { stopPlayer(); if (in!=null && dev!=null) { player = new Player(in, dev); playerThread = createPlayerThread(); playerThread.start(); } }
14af3dfd-262a-4a21-a0f8-f5d2f5c09abf
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(StringParameterWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(StringParameterWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(StringParameterWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(StringParameterWindow.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 StringParameterWindow().setVisible(true); } }); }
cd523c58-1a83-4722-b67b-a879e3547ee8
2
public double[] subarray_as_magnitude_of_Phasor(int start, int end){ if(end>=this.length)throw new IllegalArgumentException("end, " + end + ", is greater than the highest index, " + (this.length-1)); Phasor[] pp = this.getArray_as_Phasor(); double[] magn = new double[end-start+1]; for(int i=start; i<=end; i++)magn[i-start] = pp[i].getMagnitude(); return magn; }
d7b134e1-e3a2-49ee-9a5c-50e4e44380c0
5
public String toString() { Set<Product> set = deals_list.keySet(); Iterator<Product> i = set.iterator(); String list = ""; String message; while (i.hasNext()) { Product p = i.next(); Deal d = deals_list.get(p); if (p instanceof UnitProduct && d instanceof ItemPromo) { message = ("Buy " + d.getDealCondition() + " " + p.getProductName() + " get one free!\n"); list += message; } if ((p instanceof WeighableProduct | p instanceof UnitProduct) && d instanceof ItemDiscount) { message = ("Get " + d.getDealCondition() + "% off " + p.getProductName() + "!\n"); list += message; } } return list; }
7fb173fd-dc8b-4682-88c2-8c65861f81d9
5
public static Map<Integer, Map<Integer, Pearson>> getAllPearson(UserPreferences[] UP, double minPearson) { Map<Integer, Map<Integer, Pearson>> pearsons = new TreeMap<Integer, Map<Integer, Pearson>>(); for (int i = 0; i < UP.length; i++) { for (int j = i + 1; j < UP.length; j++) { Pearson p = new Pearson(UP[i], UP[j]); if (p.pearson >= minPearson || p.pearson <= (-minPearson)) { Map<Integer, Pearson> map; if (pearsons.containsKey(p.userId1)) { map = pearsons.get(p.userId1); } else { map = new TreeMap<Integer, Pearson>(); pearsons.put(p.userId1, map); } map.put(p.userId2, p); } } } return pearsons; }
f05977a4-0435-49c2-a98a-fa1598704a1d
4
private void updateGegnerPanels(JPanel spielFeld) { List<JPanel> panels = new ArrayList<JPanel>(); for (int i = 9; i >= 0; i--) { for (int j = 0; j < 10; j++) { JPanel panel = new JPanel(); if (gegner.getSpielfeld().getElements()[j][i] .getZustandsIndex() == 2) { panel.setBackground(new FreiZustand(null).getElementColor()); } else { panel.setBackground(gegner.getSpielfeld().getElements()[j][i] .getElementColor()); } panels.add(panel); } } spielFeld_Gegner.removeAll(); for (JPanel jPanel : panels) { spielFeld.add(jPanel); } }
8375713e-598c-4602-81d2-54ffc675969f
7
private Method findSupertypeMethod(Object o, String methodName, Class<?>[] types) { Method matchingMethod = null; Method[] methods = o.getClass().getDeclaredMethods(); methodloop: for (Method method : methods) { if (methodName.equals(method.getName())) { Class<?>[] params = method.getParameterTypes(); if (params.length == types.length) { for (int i = 0; i < params.length; i++) { // Check if param is supertype of arg in the same position if (!params[i].isAssignableFrom(types[i])) { break methodloop; } } } // If we reach here, then all params and args were compatible matchingMethod = method; break; } } return matchingMethod; }
a04ac88e-c57d-4284-8d31-1861ec74919e
1
public Polygon getPolygon() { Polygon polygon = new Polygon(); for(Point P : vertices) { polygon.addPoint(P.ix, P.iy); } return polygon; }
335b32dd-36b2-4dc1-ae2e-dd72a89dbf93
9
public void start() { synchronized (this) { if (ps != null) { ps.destroy(); ps = null; } running = true; Thread t = new Thread(new Runnable() { @Override public void run() { String[] cmd; if (from.endsWith("TVCardTC4000SD")) { cmd = new String[] { "/usr/local/bin/ffmpeg", "-deinterlace", "-f", "video4linux", "-i", "/dev/pci_tv", "-f", "alsa", "-i", "hw:1,0", to }; } else { cmd = new String[] { "/usr/local/bin/ffmpeg", "-deinterlace", "-i", from, to }; } try { while (running == true) { ps = Runtime.getRuntime().exec(cmd); BufferedReader br = new BufferedReader( new InputStreamReader(ps.getErrorStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } ps.waitFor(); Thread.sleep(1000); } ps = null; } catch (Exception e) { e.printStackTrace(); } finally { running = false; if (ps != null) { ps.destroy(); ps = null; } } } }); t.start(); while (running == true && ps == null) { try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } } }
e0c2fa38-b799-4f5b-aa2c-cddd41ba5deb
1
private DocumentBuilder getDocumentBuilder() throws ParserConfigurationException { if(documentBuilder==null) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setErrorHandler(getErrorHandler()); documentBuilder.setEntityResolver(getEntityResolver()); } return documentBuilder; }
7261b520-29db-4113-ba10-582ff72a77e8
2
void obfuscatePasswd(String passwd, byte[] obfuscated) { for (int i = 0; i < 8; i++) { if (i < passwd.length()) obfuscated[i] = (byte)passwd.charAt(i); else obfuscated[i] = 0; } DesCipher des = new DesCipher(obfuscationKey); des.encrypt(obfuscated, 0, obfuscated, 0); }
847fa496-4fc2-47db-ba7f-2247dd563e6f
8
public void print(int mm,int yy){ if(mm<0||mm>11) throw new IllegalArgumentException("Month "+mm+" bad, must be 0-11."); System.out.print(months[mm]); System.out.print(" "); System.out.println(yy); System.out.println("Su Mo Tu We Th Fr Sa"); GregorianCalendar calendar=new GregorianCalendar(yy,mm,1); int leadGap=calendar.get(Calendar.DAY_OF_WEEK)-1; int daysInMonth=dom[mm]; if(calendar.isLeapYear(calendar.get(Calendar.YEAR))&&mm==1){ daysInMonth=daysInMonth+1; } for(int i=0;i<leadGap;i++) System.out.print(" "); for(int i=1;i<=daysInMonth;i++){ if(i<10) System.out.print(" "); System.out.print(i); if((leadGap+i)%7==0) System.out.println(); else System.out.print(" "); } }
8ac92172-f573-48eb-bfae-a365f7afed84
5
public Dialog(int rows,int columns,final Matrix m){ super("matrix input"); final JTextField field[][] = new JTextField[rows][columns]; try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { } setSize(400, 400); Container c = getContentPane(); JPanel centerPanel = new JPanel(new GridLayout(rows, columns)); int i=0; int j=0; for (i=0; i<rows; i++){ for (j=0; j<columns; j++){ field[i][j]=new JTextField(5); centerPanel.add(field[i][j]); } } centerPanel.setBorder(BorderFactory.createEtchedBorder()); JButton btn = new JButton("Save"); c.add(centerPanel, BorderLayout.CENTER); c.add(btn, BorderLayout.SOUTH); btn.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { int i=0; int j=0; for (i=0; i<m.rows; i++){ for (j=0; j<m.columns; j++){ m.set(i + 1, j + 1, Double.parseDouble(field[i][j].getText())); //field[i][j].requestFocus(); } } m.printConsole(); } }); WindowListener wndCloser = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; addWindowListener(wndCloser); setVisible(true); }
2df2f69d-976b-480d-b66a-4dc5549134e1
0
public int getHP() { return hp; }
e6153051-f842-432c-b81c-b4cc0b43759d
9
public static void main(String [] args){ String usage = "java mobilemedia.startMobileMediaServer --hostName <String> --portNum <String> --archName <String>\n"; String hostName=null,portNum=null; String archName=null; for(int i=0; i < args.length; i++){ if(args[i].equals("--hostName")){ hostName = args[++i]; } else if(args[i].equals("--portNum")){ portNum= args[++i]; } else if(args[i].equals("--archName")){ archName = args[++i]; } } if(archName == null || hostName == null || portNum == null){ System.err.println(usage); System.exit(1); } FIFOScheduler sched = new FIFOScheduler(100); Scaffold s = new Scaffold(); RRobinDispatcher disp = new RRobinDispatcher(sched, 10); s.dispatcher=disp; s.scheduler=sched; BasicC2Topology c2Topology = new BasicC2Topology(); Architecture arch = new Architecture(archName, c2Topology); arch.scaffold=s; Vector profServerList = new Vector(); profServerList.addElement("urn:glide:prism:MediaProfileServer"); QueryServer theQueryServer = new QueryServer("urn:glide:prism:MediaQueryServer",profServerList); theQueryServer.scaffold = s; ProfileServer theProfileServer = null; try{ theProfileServer = new ProfileServer("urn:glide:prism:MediaProfileServer","mobilemedia.profile.handlers.MP3FileStoreProfileHandler;"); } catch(Exception e){ System.err.println(e.getMessage()); e.printStackTrace(); } theProfileServer.scaffold = s; ProductServer theProductServer = null; try{ theProductServer = new ProductServer("urn:glide:prism:MediaProductServer","mobilemedia.product.handlers.MP3FileStoreProductHandler"); } catch(Exception e){ System.err.println(e.getMessage()); e.printStackTrace(); } theProductServer.scaffold = s; //make the connectors now C2BasicHandler bbc=new Prism.handler.C2BasicHandler(); Connector serverConn = new Connector("urn:glide:prism:ServerConn", bbc); serverConn.scaffold =s; C2BasicHandler bbc2=new Prism.handler.C2BasicHandler(); Connector QueryConn = new Connector("urn:glide:prism:QueryConn", bbc2); QueryConn.scaffold =s; //let's add the ports Port mediaProductServerReplyPort=new Port(PrismConstants.REPLY,theProductServer); theProductServer.addPort(mediaProductServerReplyPort); mediaProductServerReplyPort.scaffold = s; Port mediaProfileServerReplyPort=new Port(PrismConstants.REPLY,theProfileServer); theProfileServer.addPort(mediaProfileServerReplyPort); mediaProfileServerReplyPort.scaffold = s; Port serverConnProductRequestPort=new Port(PrismConstants.REQUEST,serverConn); serverConn.addPort(serverConnProductRequestPort); serverConnProductRequestPort.scaffold = s; Port serverConnProfileRequestPort=new Port(PrismConstants.REQUEST,serverConn); serverConn.addPort(serverConnProfileRequestPort); serverConnProfileRequestPort.scaffold = s; Port serverConnReplyPort=new Port(PrismConstants.REPLY,serverConn); serverConn.addPort(serverConnReplyPort); serverConnReplyPort.scaffold = s; Port queryServerRequestPort=new Port(PrismConstants.REQUEST,theQueryServer); theQueryServer.addPort(queryServerRequestPort); queryServerRequestPort.scaffold = s; Port queryServerReplyPort=new Port(PrismConstants.REPLY,theQueryServer); theQueryServer.addPort(queryServerReplyPort); queryServerReplyPort.scaffold = s; Port QueryConnRequestPort=new Port(PrismConstants.REQUEST,QueryConn); QueryConn.addPort(QueryConnRequestPort); QueryConnRequestPort.scaffold = s; arch.weld(mediaProductServerReplyPort,serverConnProductRequestPort); arch.weld(mediaProfileServerReplyPort,serverConnProfileRequestPort); arch.weld(serverConnReplyPort,queryServerRequestPort); arch.weld(queryServerReplyPort,QueryConnRequestPort); ExtensiblePort QueryConnSocketReplyPort = new ExtensiblePort(PrismConstants.REPLY, QueryConn); SocketDistribution sd=new SocketDistribution(QueryConnSocketReplyPort, Integer.parseInt(portNum)); QueryConnSocketReplyPort.addDistributionModule(sd); QueryConnSocketReplyPort.scaffold = s; QueryConn.addPort(QueryConnSocketReplyPort); arch.add(QueryConnSocketReplyPort); arch.add(theQueryServer); arch.add(theProfileServer); arch.add(theProductServer); arch.add(QueryConn); arch.add(serverConn); disp.start(); arch.start(); }
ce63521f-418b-4808-aacc-023c9b4c6678
1
@Override public void mouseExited(MouseEvent e) { if(selection != -1) { setSelection(selection); } e.consume(); }
85373772-a516-46e0-bc4c-cb9bc67134b2
6
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.translate(200,200); GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); for(int x = 0; x >-100; x--) { for(int y = -100; y < 0; y++) { if(x == 0) { path.moveTo(0, -100); } else { path.lineTo(x, y); } } } for(int x = -100; x <0; x++) { for(int y = 0; y > -100; y--) { if(x == -100) { path.moveTo(-100,0); } else { path.lineTo(x, y); } } } path.closePath(); Color color = new Color(0f,0.5f,0.125f); g2.setColor(color); g2.draw(path); }
de8cf5bf-ebf1-456b-9fce-a7693adc82fb
7
void updateDisplay() { long now = System.currentTimeMillis(); // current time in ms long elapsed = now - lastUpdate; // ms elapsed since last update remaining -= elapsed; // adjust remaining time lastUpdate = now; // remember this update time // Convert remaining milliseconds to mm:ss format and display if (remaining <= 0) { remaining = 0; //roundLength; } int hours = (int) remaining / 60000 / 60; int minutes = (int) (remaining / 60000) % 60; int seconds = (int) ((remaining % 60000) / 1000); String days = ""; if(hours >= 24) { days = (hours / 24) + ((hours/24==1) ? " Day, " : " Days - "); hours = hours % 24; } GUI.setTimer(curRound, days + format.format(hours) + ":" + format.format(minutes) + ":" + format.format(seconds), totalRnd); //This changes the color of the timer when the time is less than 10 seconds if (seconds <=10 && minutes == 1 && hours == 1){ if ((seconds % 2) == 0) GUI.flashTimer(1); else GUI.flashTimer(0); } else GUI.flashTimer(2); // If we've completed the countdown beep and display new page GUI.setBank(operator.getBank().getAdjustedBalance()); }
1f7e503c-98c9-490f-a985-b2da0d6bc9eb
2
public boolean equals(Object o) { if (o instanceof Map.Entry) { Map.Entry e = (Map.Entry) o; return key.equals(e.getKey()) && value.equals(e.getValue()); } return false; }
97609672-68b2-4af0-928a-3f2cd272ac1c
5
@Override public void draw(Graphics2D g) { setMapPosition(); if(jiggle){ tracker ++; if(tracker < 2) xmap +=4; else if(tracker < 4) xmap-=4; else { jiggle = false; tracker = 0; } } if (facingRight) g.drawImage(getAnimation().getImage(), (int) ((xScreen + xmap) - (width / 2)), (int) ((yScreen + ymap) - (height / 2)), null); else g.drawImage(getAnimation().getImage(), (int) (((xScreen + xmap) - (width / 2)) + width), (int) ((yScreen + ymap) - (height / 2)), -width, height, null); if (getWorld().showBB) { g.setColor(Color.WHITE); g.draw(getRectangle()); } }
d183409d-a4cd-4763-bdfa-e4d976a0d072
7
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(target==mob) { mob.tell(L("You already know your own alignment!.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> peer(s) into the eyes of <T-NAMESELF>.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); mob.tell(mob,target,null,L("<T-NAME> seem(s) like <T-HE-SHE> is @x1.",CMLib.flags().getAlignmentName(target).toLowerCase())); } } else beneficialWordsFizzle(mob,target,auto?"":L("<S-NAME> peer(s) into the eyes of <T-NAMESELF>, but then blink(s).")); // return whether it worked return success; }
24d7574a-ebad-4ad7-b0cc-1f2d72ca1ed7
0
public DrawableItem getDitem() { return ditem; }
0b73bfd0-5090-4cc5-80dc-f61b1ed76d21
5
private static void run() throws InterruptedException { while (!finished) { Display.update(); if (Display.isCloseRequested()) { finished = true; } else if (Display.isActive()) { Display.sync(FRAMERATE); render(); } else { // The window is not in the foreground, so we can allow other stuff to run and // infrequently update Thread.sleep(100); if (Display.isVisible() || Display.isDirty()) { render(); } } } }
caa7f0fb-831f-4a2d-8ef4-3b0c103e941c
8
private static void addFiles(File file, List<String> result, File reference) { if (file == null || !file.exists() || !file.isDirectory()) { return; } for (File child : file.listFiles()) { if (child.isDirectory()) { addFiles(child, result, reference); } else { String path = null; while (child != null && !child.equals(reference)) { if (path != null) { path = child.getName() + "/" + path; } else { path = child.getName(); } child = child.getParentFile(); } result.add(path); } } }
39d62620-80b8-4832-bbf5-f45d5ecf7447
0
public static void main(String[] args){ int h; System.out.println(); }
d0b0979e-a455-42ad-8e80-1b004f0a378e
9
@Override public String rawReviewsData(int pageNum) { HttpPost httppost = null; String responseBody = ""; try { StringBuffer sb = new StringBuffer(postURL); sb.append("id="+ID) .append("/page="+pageNum) .append("/xml"); ResponseHandler<String> responseHandler = new ResponseHandler<String>(){ @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if(status >= 200 && status <300){ HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity,"UTF-8") : null; }else{ throw new ClientProtocolException("Unexpected response status: " + status); } } }; if(useProxy){ String pacUrl = iphoneParams.getProperty("PROXY_PAC"); //px = ProxyUtil.getProxyInfoFromPAC(pacUrl, sb.toString()); String username = iphoneParams.getProperty("PROXY_USER"); String password = iphoneParams.getProperty("PROXY_PASSWORD"); String proxyIp = iphoneParams.getProperty("PROXY_IP"); int proxyPort = Integer.valueOf(iphoneParams.getProperty("PROXY_PORT")); if(sb.toString().startsWith("http://")){ sb = sb.delete(0, 7); }else if(sb.toString().startsWith("https://")){ sb = sb.delete(0, 8); } HttpHost target = new HttpHost(sb.toString(), 80, "http"); HttpHost proxy = new HttpHost(proxyIp, proxyPort); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(proxyIp, proxyPort), new UsernamePasswordCredentials(username, password)); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider).build(); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); int startIndexOfRelativeAddress = sb.indexOf("/"); HttpGet httpget = new HttpGet(sb.substring(startIndexOfRelativeAddress)); httpget.setConfig(config); // httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); System.out.println("Executing request with Proxy " + httpget.getRequestLine() + " to " + target + " via " + proxy); responseBody = httpclient.execute(target, httpget, responseHandler); }else{ HttpClient httpClient = new DefaultHttpClient(); httppost = new HttpPost(sb.toString()); System.out.println("executing request "+httppost.getURI()); responseBody = httpClient.execute(httppost, responseHandler); } //handle json // System.out.println("---------------------------------"); // System.out.println(responseBody); // System.out.println("---------------------------------"); return responseBody; } catch (Exception e) { if(e instanceof ClientProtocolException){ System.out.println(e.getMessage() +" : End Page"); }else{ e.printStackTrace(); } }finally{ if(httppost != null){ httppost.releaseConnection(); } } return ""; }
08d6cc95-6093-4877-a1ba-8a244aa8fe7d
4
private static void generateMainPanel() { // main panel layout GridLayout mainPanelGrid = new GridLayout(1, 2); mainPanel.setLayout(mainPanelGrid); // generating data source data = new DataRetriever(); initMap(data); // map initialization // Flights and crews flightList = new JList(data.generateFlights()); flightList.setBorder(generateBorder("Flights")); crewList = new JList(data.generateCrews()); crewList.setBorder(generateBorder("Crews")); // listener to match flight-crew flightList.addListSelectionListener(new FlightListener()); // for multiple selection and deselection crewList.setSelectionModel(new DefaultListSelectionModel() { private int firstIndex = -1; private int lastIndex = -1; public void setSelectionInterval(int indice1, int indice2) { if (firstIndex == indice1 && lastIndex == indice2) { if (getValueIsAdjusting()) { setValueIsAdjusting(false); setSelection(indice1, indice2); } } else { firstIndex = indice1; lastIndex = indice2; setValueIsAdjusting(false); setSelection(indice1, indice2); } } private void setSelection(int indice1, int indice2) { if (super.isSelectedIndex(indice1)) { super.removeSelectionInterval(indice1, indice2); Set<Crew> tempCrewRemoveSet = new HashSet<Crew>(crewList.getSelectedValuesList()); map.put(flightList.getSelectedValue().toString(),tempCrewRemoveSet); } else { super.addSelectionInterval(indice1, indice2); Set<Crew> tempCrewSet = new HashSet<Crew>(crewList.getSelectedValuesList()); map.put(flightList.getSelectedValue().toString(),tempCrewSet); } } }); mainPanel.add(flightList); mainPanel.add(crewList); }
1d4514e9-a5c6-409b-a097-90f4337f0eca
7
public boolean addObject(int x, int y, int width, int length, int height) { if ((x - width) > 0 || (x + width) < map.length || (y - length) > 0 || (y + length) < map[0].length) { for (int i = x - (width / 2); i < x + (width / 2); i++) { for (int j = y - (length / 2); j < y + (length / 2); j++) { try{ this.map[i][j] = height; }catch(Exception e){ System.err.println("Object is outside this map."); } } } return true; } return false; }
c4c7ebbf-c8c0-4bcd-bc22-ed8b1e25a8a7
9
public void setChecked(boolean checked) { Object newValue = null; // For backward compatibility, if the style is not // set yet, then convert it to a toggle button. if (value == null || value == VAL_TOGGLE_BTN_ON || value == VAL_TOGGLE_BTN_OFF) { newValue = checked ? VAL_TOGGLE_BTN_ON : VAL_TOGGLE_BTN_OFF; } else if (value == VAL_RADIO_BTN_ON || value == VAL_RADIO_BTN_OFF) { newValue = checked ? VAL_RADIO_BTN_ON : VAL_RADIO_BTN_OFF; } else { // Some other style already, so do nothing. return; } if (newValue != value) { value = newValue; if (checked) { firePropertyChange(CHECKED, Boolean.FALSE, Boolean.TRUE); } else { firePropertyChange(CHECKED, Boolean.TRUE, Boolean.FALSE); } } }
54a30bf4-b799-407c-aa8a-1ceffedd3dd8
3
public void setRight(PExpLogica node) { if(this._right_ != null) { this._right_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._right_ = node; }
00429d4d-fdcc-48e3-9c19-739dcd18601e
7
public DoubledDigraph<SugiyamaNode<V>,SugiyamaArc<V,E>> createLayoutGraph(Digraph<V,E> graph, DigraphLayoutDimensionProvider<V> dimensions, Digraph<V,?> feedback, int horizontalSpacing) { DoubledDigraph<SugiyamaNode<V>,SugiyamaArc<V,E>> result = DoubledDigraphAdapter.getAdapterFactory(factory).create(); Map<V,SugiyamaNode<V>> map = new HashMap<V, SugiyamaNode<V>>(); // create nodes for (V vertex : graph.vertices()) { SugiyamaNode<V> node = new SugiyamaNode<V>(vertex, dimensions.getDimension(vertex), horizontalSpacing); map.put(vertex, node); result.add(node); } // create arcs for (V source : graph.vertices()) { for (V target : graph.targets(source)) { SugiyamaNode<V> s = map.get(source); SugiyamaNode<V> t = map.get(target); E e = graph.get(source, target); if (feedback.contains(source, target)) { if (graph.contains(target, source)) { result.put(t, s, new SugiyamaArc<V,E>(t, s, e, graph.get(target, source))); } else { result.put(t, s, new SugiyamaArc<V,E>(t, s, true, e)); } } else if (!graph.contains(target, source)) { result.put(s, t, new SugiyamaArc<V,E>(s, t, false, e)); } } } assert Digraphs.isAcyclic(result); computeNodeLayers(result); return result; }
ac1b8ab8-1fdc-4921-a285-2ebdf5a0c800
9
protected void syncActivation(float[] activeNumbers) { //todo: refactor (it can become faster and easier) HashSet<Model> activeModel2 = new HashSet<>(); activeModels.clear(); if (activeNumbers[0] >= 0) { int speed = 0; int ls = 0; for (Model model : models) { if (model.getIsComplex()) { ComplexModel c = (ComplexModel) model; for (int i = 0; i < c.getSize(); i++) { if (speed == (int) activeNumbers[ls]) { ls++; activeModel2.add(c.getModel(i)); if (ls >= activeNumbers.length) break; } speed++; } } else { if (speed == (int) activeNumbers[ls]) { ls++; activeModel2.add(model); if (ls >= activeNumbers.length) break; } speed++; } if (ls >= activeNumbers.length) break; } } activeModels =activeModel2; }
f41d6d77-998f-43e2-a710-1411a7d40680
8
public void SetParameter(String head, String unit, String digital, String analog, float xfrom, float xto, float x) { Header = head; if (Header.length()==0) WHeader=false; else WHeader=true; Unit = unit; if (digital.equals("false")==true) WDigital=false; else WDigital=true; if (analog.equals("false")==true) WAnalog=false; else WAnalog=true; XMin = xfrom; XMax = xto; XNew = x; XOld = XNew; CHANGED=true; //Recalculation if (WHeader==true) {Hhe = Mhe / 6;} // height of the header else Hhe=0; if (WDigital==true) {Dhe = Mhe / 6;} // height of the digital instrument else Dhe = 0; if (WAnalog==true) {Ahe = Mhe - Hhe - Dhe;} // height of the analog instrument else { Ahe = 0; if (WDigital==true) { if (WHeader == true) {Hhe = Mhe /3; Dhe = Mhe - Hhe; }// DIGITAL with header else {Hhe = 0; Dhe = Mhe; }// DIGITAL without header }// WITHOUT ANA else // only header (!!!) {Hhe = Mhe; } } // repaint(); } // End of SetParameter
53c593b6-7367-4e24-8408-06d436ac433c
2
private void reduce(){ int[] primeNumbers = getPrimeNumbers(); for (int primeNumber: primeNumbers){ while (isReducible(primeNumber)){ numerator /= primeNumber; denominator /= primeNumber; } } }
8308e0dc-b469-4ef6-a851-93d52fc52242
2
public Object opt(int index) { return (index < 0 || index >= length()) ? null : this.myArrayList.get(index); }
c275e33f-ddda-4bb8-94ae-daf103c3956e
2
private int inserir (Endereco e){ int status = -1; Connection con = null; PreparedStatement pstm = null; try{ con = ConnectionFactory.getConnection(); pstm = con.prepareStatement(INSERT, Statement.RETURN_GENERATED_KEYS); pstm.setString(1, e.getEstado()); pstm.setString(2, e.getCidade()); pstm.setString(3, e.getBairro()); pstm.setString(4, e.getRua()); pstm.setString(5, e.getComplemento()); pstm.setInt(6, e.getNumero()); pstm.execute(); try(ResultSet rs = pstm.getGeneratedKeys()){ rs.next(); status = rs.getInt(1); } } catch (Exception ex){ JOptionPane.showMessageDialog(null, "Erro ao inserir endereço: " + ex.getMessage()); } finally{ try{ ConnectionFactory.closeConnection(con, pstm); } catch(Exception ex){ JOptionPane.showMessageDialog(null, "Erro ao fechar conexão: " + ex.getMessage()); } } return status; }
7f9ded5e-1f7e-403a-87f0-f36a504dc55f
2
private boolean isValidPixel(int pixel) { if (pixel >= 0 && pixel < pixels.length) return true; return false; }
04c08461-130e-4758-881e-4a0ccb90c971
1
private PublicKey byteArrayToPublicKey(byte[] tmp) { PublicKey pubK = null; ByteArrayInputStream bis = new ByteArrayInputStream(tmp); ObjectInput in; try { in = new ObjectInputStream(bis); pubK = (PublicKey) in.readObject(); bis.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } return pubK; }
e0beafc3-b803-4c69-b492-efdcc5711f3a
8
final public void Class_name() throws ParseException { /*@bgen(jjtree) Class_name */ SimpleNode jjtn000 = new SimpleNode(JJTCLASS_NAME); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { Identifier(); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } }
2abfe9d4-9c41-422c-892a-df011035e126
5
public double computeSimilarity(Map<Integer, Double> a, Map<Integer, Double> b) throws Exception { double result = 0.0; // compute inner product of a and b double sum = 0.0; for (int keya : a.keySet()){ if (b.containsKey(keya)){ sum += a.get(keya) * b.get(keya); } } if (sum != 0.0){ // compute norm of vector a double diva = 0.0; for (int key : a.keySet()) diva += a.get(key) * a.get(key); diva = Math.sqrt(diva); // compute norm of vector b double divb = 0.0; for (int key : b.keySet()) divb += b.get(key) * b.get(key); divb = Math.sqrt(divb); result = sum / (diva * divb); } return result; }
f6afc6a9-d5c1-4c95-8bcd-c39f77a57356
9
private static void render(String s) { if (s.equals("{")) { buf_.append("\n"); indent(); buf_.append(s); _n_ = _n_ + 2; buf_.append("\n"); indent(); } else if (s.equals("(") || s.equals("[")) buf_.append(s); else if (s.equals(")") || s.equals("]")) { backup(); buf_.append(s); buf_.append(" "); } else if (s.equals("}")) { _n_ = _n_ - 2; backup(); backup(); buf_.append(s); buf_.append("\n"); indent(); } else if (s.equals(",")) { backup(); buf_.append(s); buf_.append(" "); } else if (s.equals(";")) { backup(); buf_.append(s); buf_.append("\n"); indent(); } else if (s.equals("")) return; else { buf_.append(s); buf_.append(" "); } }
f91553a6-162c-453c-89eb-21e02a96d1a7
9
public static void gerenciarCarros() { int opcao; String chassi, cor, modelo, placa; float diaria; int ano; ArrayList<Carro> carros; while (true) { opcao = menu.menuCarros(); switch (opcao) { case 1: System.out.print("Digite o chassi :"); chassi = menu.scan.next(); System.out.print("Digite a diária :"); diaria = menu.scan.nextFloat(); Carro carro = new Carro(chassi, diaria); loja.adcionarCarro(carro); break; case 2: System.out.print("Digite o chassi :"); chassi = menu.scan.next(); try { loja.existeCarro(chassi); loja.removerCarro(chassi); } catch (NaoEncontradoException ex) { System.out.println(ex + ": Carro"); } break; case 3: System.out.print("Digite o chassi :"); chassi = menu.scan.next(); try { loja.existeCarro(chassi); System.out.print("Digite o chassi :"); chassi = menu.scan.next(); System.out.print("Digite o modelo :"); modelo = menu.scan.next(); System.out.print("Digite a cor :"); cor = menu.scan.next(); System.out.print("Digite a placa :"); placa = menu.scan.next(); System.out.print("Digite a diaria :"); diaria = menu.scan.nextFloat(); System.out.print("Digite o ano :"); ano = menu.scan.nextInt(); loja.editarCarro(chassi, diaria, cor, modelo, placa, ano); } catch (NaoEncontradoException ex) { System.out.println(ex + ": Carro"); } break; case 4: carros = loja.getCarros(); for (Carro c : carros) { System.out.println("Chassi: " + c.getChassi()); System.out.println("Diaria: " + c.getDiaria()); System.out.println("Alugado: " + c.isAlugado()); System.out.println("Modelo: " + c.getModelo()); System.out.println("Cor: " + c.getCor()); System.out.println("Placa: " + c.getPlaca()); System.out.println("Ano: " + c.getAno()); } break; case 5: return; } } }
611081e2-1a13-43bd-aed8-e6c446b95a9d
3
protected void skipAttributes(DataInputStream input) throws IOException { int count = input.readUnsignedShort(); for (int i = 0; i < count; i++) { input.readUnsignedShort(); // the name index long length = input.readInt(); while (length > 0) { long skipped = input.skip(length); if (skipped == 0) throw new EOFException("Can't skip. EOF?"); length -= skipped; } } }
ef1f70c1-ff9e-4398-936d-121dc4e04960
3
public void close() { try { if ((this.connect != null) && (!this.connect.isClosed())) { this.connect.close(); } } catch (SQLException ex) { System.out.println("Error: " + ex); } }
656e081e-ca1b-444a-9204-4b5b25cf0a93
2
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); String msj_exito = "El movimiento por \" <causa_movimiento> \" se realizó correctamente"; String msj_error = "Error al realizar el movimiento por \" <causa_movimiento> \""; HttpSession sesion = request.getSession(true); String tipo_sesion = (String) sesion.getAttribute("identidad"); try (PrintWriter out = response.getWriter()) { String busqueda = request.getParameter("equipo"); if (busqueda == null) { String mov = request.getParameter("movimiento"); if (realizaMovimiento(request)) { msj_exito = msj_exito.replace("<causa_movimiento>", mov); response.sendRedirect(tipo_sesion + ".jsp?mensaje=" + URLEncoder.encode(msj_exito, "UTF-8") + "&exito=true"); } else { msj_error = msj_error.replace("<causa_movimiento>", mov); response.sendRedirect(tipo_sesion + ".jsp?mensaje=" + URLEncoder.encode(msj_error, "UTF-8") + "&exito=false"); } } else { out.print(generaTabla(busqueda)); } } }
c47b59a4-24ab-4a8d-957e-02bdd34fb1ad
6
public Tr(HtmlMidNode parent, HtmlAttributeToken[] attrs){ super(parent, attrs); for(HtmlAttributeToken attr:attrs){ String v = attr.getAttrValue(); switch(attr.getAttrName()){ case "align": align = Align.parse(this, v); break; case "bgcolor": bgcolor = Bgcolor.parse(this, v); break; case "char": charr = Char.parse(this, v); break; case "charoff": charoff = Charoff.parse(this, v); break; case "valign": valign = Valign.parse(this, v); break; } } }
f542d922-d635-4884-89a5-930cde3af462
5
private final void parseDoctype() throws IOException { int nesting = 1; while (true) { switch (read()) { case -1: fail(UNEXPECTED_EOF); break; case '<': nesting++; break; case '>': if (--nesting == 0) { return; } break; default: break; } } }
608fbcc3-c616-4b4f-bcb8-b4d0b782901d
4
public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || this.length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; }
c2a74d3d-0d27-49de-b1e2-1465afcd612e
9
protected void keyTyped(char par1, int par2) { field_73905_m = false; if (par2 == 15) { completePlayerName(); } else { field_73897_d = false; } if (par2 == 1) { mc.displayGuiScreen(null); } else if (par2 == 28) { String s = inputField.getText().trim(); if (s.length() > 0) { mc.ingameGUI.func_73827_b().func_73767_b(s); if (!mc.handleClientCommand(s)) { mc.field_71439_g.sendChatMessage(s); } } mc.displayGuiScreen(null); } else if (par2 == 200) { getSentHistory(-1); } else if (par2 == 208) { getSentHistory(1); } else if (par2 == 201) { mc.ingameGUI.func_73827_b().func_73758_b(19); } else if (par2 == 209) { mc.ingameGUI.func_73827_b().func_73758_b(-19); } else { inputField.textboxKeyTyped(par1, par2); } }
17e750c7-46b1-4b0c-b208-7b285dec0796
5
public void faltaEnvido(boolean envido, boolean envidoEnvido, boolean realEnvido, Humano jugadorH, Contador contador, boolean mentir){ System.out.println("\n"+this.getNombre()+": Falta Envido"); //condicional para ver si el humano quiere if(jugadorH.cantoFaltaEnvido()){ System.out.println(jugadorH.getNombre()+": Quiero"); int puntosMaquina = this.puntosMano(); int puntosHumano = jugadorH.obtenerPutnos(); System.out.println("\n"+this.getNombre()+": "+puntosMaquina+" puntos."); System.out.println(jugadorH.getNombre()+": "+puntosHumano+" puntos."); //Verifico si el humano no canto mal los puntos if(!(puntosHumano==-1)){ if(puntosMaquina<puntosHumano){ contador.sumarFaltaEnvido(jugadorH); }else if(puntosMaquina>puntosHumano){ contador.sumarFaltaEnvido(this); }else{ if(this.isMano()){ contador.sumarFaltaEnvido(this); }else{ contador.sumarFaltaEnvido(jugadorH); } } }else{ System.out.println("Error "+jugadorH.getNombre()+". Puntos mal cantados, rabón perdido."); contador.sumarPuntos(this, 2); contador.sumarFaltaEnvido(this); this.setManoGanada(2); } }else{ System.out.println(jugadorH.getNombre()+": No Quiero"); contador.sumarPuntos(this, contador.faltaEnvidoNoQuerida(envido, envidoEnvido, realEnvido)); } }
a5038647-4972-431a-8f0b-4dad8940a778
5
private boolean findUnexploredCellWithDist(int rowCount, int colCount) { boolean foundMin = false; for(int rowID = 0;rowID < rowCount ; rowID++){ for(int colID = 0;colID < colCount;colID++){ for(int drcID = OREIT_MIN;drcID <= OREIT_MAX;drcID ++){ if(!explored[rowID][colID][drcID] && distance[rowID][colID][drcID] < minDist){ minRowID = rowID; minColID = colID; minDrcID = drcID; minDist = distance[rowID][colID][drcID]; foundMin = true; } }//END of loop on orientation }// END of loop on columns }//End of loop on rows return foundMin; }
df14836d-30e5-405b-896a-b885187f1bb7
4
public static void validateCity(City city) throws TechnicalException { if (city == null) { throw new TechnicalException(MSG_ERR_NULL_ENTITY); } if ( ! isStringValid(city.getName(), NAME_SIZE)) { throw new TechnicalException(NAME_ERROR_MSG); } if ( ! isStringValid(city.getPicture(), PICTURE_SIZE)) { throw new TechnicalException(PICTURE_ERROR_MSG); } if ( ! isSelectedElem(city.getCountry().getIdCountry())) { throw new TechnicalException(SELECT_COUNTRY_ERROR_MSG); } }
06d36e71-97b0-4a3e-a8af-e9fa27708201
1
private int[] createBowl(int [] platter) { int[] bowl = new int[NUM_FRUITS]; int sz = 0; while (sz < bowlsize) { // pick a fruit according to current fruit distribution int fruit = pickFruit(platter); int c = 1 + random.nextInt(3); c = Math.min(c, bowlsize - sz); c = Math.min(c, platter[fruit]); bowl[fruit] += c; sz += c; } return bowl; }
3cbebacd-85d6-4fbb-91ff-5ddfef9c5892
5
private static int compareIp(final InetAddress adr1, final InetAddress adr2) { byte[] ba1 = adr1.getAddress(); byte[] ba2 = adr2.getAddress(); // general ordering: ipv4 before ipv6 if (ba1.length < ba2.length) { return -1; } if (ba1.length > ba2.length) { return 1; } // we have 2 ips of the same type, so we have to compare each byte for (int i = 0; i < ba1.length; i++) { int b1 = unsignedByteToInt(ba1[i]); int b2 = unsignedByteToInt(ba2[i]); if (b1 == b2) { continue; } if (b1 < b2) { return -1; } else { return 1; } } return 0; }
697590ba-a102-48d6-9f61-71022a0a9596
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(Mod.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Mod.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Mod.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Mod.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 Mod().setVisible(true); } }); }
afe2455e-f89d-41cc-bceb-fceab69bca8f
1
@Test(expected = IllegalArgumentException.class) public void testPickUpActionTestInventoryFull() throws InvalidActionException { // Max size of inventory is 6 for (int i = 0; i < 6; i++) player.getInventory().add(new LightGrenade(grid)); player.incrementActionsWithMaxActions(); final LightGrenade item = new LightGrenade(grid); grid.addElementToPosition(item, new Position(1, 1)); item.pickUp(player); }
7a32ab32-2986-4094-a433-1647d8bc2948
4
public SpriteSheet(String path) { BufferedImage image = null; try { image = ImageIO.read(this.getClass().getResourceAsStream(path)); } catch (IOException e) { e.printStackTrace(); } if (image == null) { return; } this.path = path; this.width = image.getWidth(); this.height = image.getHeight(); pixels = image.getRGB(0, 0, width, height, null, 0, width); for (int i = 0; i < pixels.length; i++) { pixels[i] = (pixels[i] & 0xff) / 64; } for (int i = 0; i < 8; i++) { System.out.println(pixels[i]); } }
2bb4059e-460b-4df3-9275-6248c67a1cad
2
public void calculateDeltaFunctionValuesForOutputNeuron(double teachingInput) { myDelta = 0.0; if (this.neuronType != ENeuronType.Output) throw new UnsupportedOperationException( "This function is only for the use with Output-Neurons! This is a " + this.neuronType.toString()); myDelta = teachingInput - this.activationValue; for (Axon ax : this.incomingDendrites) { ax.getSource().addDeltaValue(myDelta * ax.getWeight()); } }
4e9b4d47-db7b-4b14-9e98-fa682e07944d
7
private static void identifySeparator(File fname) { separators.put(",", new int[2]); separators.put(";", new int[2]); separators.put(":", new int[2]); separators.put("|", new int[2]); separators.put("\t", new int[2]); separators.put(" ", new int[2]); java.io.BufferedReader fin; try { fin = new java.io.BufferedReader(new java.io.FileReader(fname)); String record; int n = 0; while ((record = fin.readLine()) != null) { record = compressBlanks(record); if (record.length() == 0) continue; countSeparators(record); deleteInvalidSeparators(n); n++; if (n > 100 || separators.size() == 0) break; } if (separators.size() == 0) { if (n == 1) { separator = ""; nCols = 1; } } else { Object[] keys = separators.keySet().toArray(); separator = (String) keys[0]; nCols = 1 + ((int[]) separators.get(separator))[1]; } fin.close(); } catch (java.io.IOException ie) { System.err.println("I/O exception in computeVariableTypes"); } }
90ea8831-1242-4081-933d-818dee09c6bb
3
public void writeBooleanArray(boolean[] v) throws IOException { final int size = v.length; final int byteCount = NBTInputStream.ceilDiv(size, 8); final byte[] data = new byte[byteCount]; this.writeInt(size); for (int boolIndex = 0, byteIndex = 0, bitIndex = 7; boolIndex < size; boolIndex++) { if (v[boolIndex]) { data[byteIndex] |= 1 << bitIndex; } --bitIndex; if (bitIndex < 0) { byteIndex++; bitIndex = 7; } } this.out.write(data); this.incCount(byteCount); }
c4c7dfc5-569c-4202-9aaf-75e66e141a78
3
public SingleTreeNode uct(StateObservationMulti state) { SingleTreeNode selected = null; double bestValue = -Double.MAX_VALUE; for (SingleTreeNode child : this.children) { double hvVal = child.totValue; double childValue = hvVal / (child.nVisits + this.epsilon); childValue = Utils.normalise(childValue, bounds[0], bounds[1]); //System.out.println("norm child value: " + childValue); double uctValue = childValue + K * Math.sqrt(Math.log(this.nVisits + 1) / (child.nVisits + this.epsilon)); uctValue = Utils.noise(uctValue, this.epsilon, this.m_rnd.nextDouble()); //break ties randomly // small sampleRandom numbers: break ties in unexpanded nodes if (uctValue > bestValue) { selected = child; bestValue = uctValue; } } if (selected == null) { throw new RuntimeException("Warning! returning null: " + bestValue + " : " + this.children.length + " " + + bounds[0] + " " + bounds[1]); } //Roll the state: //need to provide actions for all players to advance the forward model Types.ACTIONS[] acts = new Types.ACTIONS[no_players]; //set this agent's action acts[id] = actions[id][selected.childIdx]; //get actions available to the opponent and assume they will do a random action Types.ACTIONS[] oppActions = actions[oppID]; acts[oppID] = oppActions[new Random().nextInt(oppActions.length)]; state.advance(acts); return selected; }
1986d586-e3a3-49d9-bfba-1dc4db11f768
9
protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) { Color backColor = tabPane.getBackgroundAt(tabIndex); if (!(backColor instanceof UIResource)) { super.paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect, isSelected); return; } g.setFont(font); View v = getTextViewForTab(tabIndex); if (v != null) { // html Graphics2D g2D = (Graphics2D) g; Object savedRenderingHint = null; if (AbstractLookAndFeel.getTheme().isTextAntiAliasingOn()) { savedRenderingHint = g2D.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AbstractLookAndFeel.getTheme().getTextAntiAliasingHint()); } v.paint(g, textRect); if (AbstractLookAndFeel.getTheme().isTextAntiAliasingOn()) { g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, savedRenderingHint); } } else { // plain text int mnemIndex = -1; if (JTattooUtilities.getJavaVersion() >= 1.4) { mnemIndex = tabPane.getDisplayedMnemonicIndexAt(tabIndex); } Graphics2D g2D = (Graphics2D) g; Composite composite = g2D.getComposite(); AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f); g2D.setComposite(alpha); Color fc = tabPane.getForegroundAt(tabIndex); if (isSelected) { fc = AbstractLookAndFeel.getTheme().getTabSelectionForegroundColor(); } if (!tabPane.isEnabled() || !tabPane.isEnabledAt(tabIndex)) { fc = AbstractLookAndFeel.getTheme().getDisabledForegroundColor(); } if (ColorHelper.getGrayValue(fc) > 128) { g2D.setColor(Color.black); } else { g2D.setColor(Color.white); } JTattooUtilities.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex, textRect.x + 1, textRect.y + 1 + metrics.getAscent()); g2D.setComposite(composite); g2D.setColor(fc); JTattooUtilities.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent()); } }
b2ca7e8a-151e-4b9b-926a-0ec5dcf5f10c
8
public void updatePosition() { if (xPos < xDestination) xPos++; else if (xPos > xDestination) xPos--; if (yPos < yDestination) yPos++; else if (yPos > yDestination) yPos--; if(xPos == xDestination && yPos == yDestination) { switch(mCommand) { case goToPosition: { mCommand = EnumCommand.noCommand; mAgent.msgAnimationAtPosition(); break; } case leaveMarket: { mCommand = EnumCommand.noCommand; mAgent.msgAnimationLeftMarket(); break; } default: break; } } }
3181e507-8f53-446e-af93-cd0845933a53
9
public void toDot(String filename) { System.out.println("Writing " + filename); BufferedWriter w = null; try { FileWriter fstream = new FileWriter(filename); w = new BufferedWriter(fstream); w.write("digraph G {\n"); // nodes for (PDAState s : states) { String id = Util.dotId(s); if (id.length() > 200) { id = Util.dotId(s.id); } w.write("" + s.id + " [label=" + id + (s.rejects ? ", color=red" : "") + ", shape=box];\n"); // shift edges for (Entry<Symbol, PDAState> e2 : s.shifts.entrySet()) { w.write("" + s.id + " -> " + e2.getValue().id + " [label=" + Util.dotId(e2.getKey()) + "];\n"); } // goto edges for (Entry<R, PDAState> e2 : s.gotos.entrySet()) { w.write("" + s.id + " -> " + e2.getValue().id + " [label=" + "R" + s.id /*Util.dotId(e2.getKey())*/ + "];\n"); } if (s.rejectState != null) { w.write("" + s.id + " -> " + s.rejectState.id + " [color=red];\n"); } } w.write("}\n"); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } finally { if (w != null) { try { w.close(); } catch (IOException e) { } } } }
a85409ea-e058-458c-a1a4-6af8ff00a677
2
public double standardDeviation_as_Complex_ConjugateCalcn() { boolean hold = Stat.nFactorOptionS; if (nFactorReset) { if (nFactorOptionI) { Stat.nFactorOptionS = true; } else { Stat.nFactorOptionS = false; } } Complex[] cc = this.getArray_as_Complex(); double variance = Stat.varianceConjugateCalcn(cc); Stat.nFactorOptionS = hold; return Math.sqrt(variance); }
71678e77-e569-4b51-b6e6-76781561de7e
5
public static boolean readUserSelectedFile() { if (fileDialog == null) fileDialog = new JFileChooser(); fileDialog.setDialogTitle("Select File for Input"); int option = fileDialog.showOpenDialog(null); if (option != JFileChooser.APPROVE_OPTION) return false; File selectedFile = fileDialog.getSelectedFile(); BufferedReader newin; try { newin = new BufferedReader( new FileReader(selectedFile) ); } catch (Exception e) { throw new IllegalArgumentException("Can't open file \"" + selectedFile.getName() + "\" for input.\n" + "(Error :" + e + ")"); } if (!readingStandardInput) { // close current file try { in.close(); } catch (Exception e) { } } emptyBuffer(); // Added November 2007 in = newin; inputFileName = selectedFile.getName(); readingStandardInput = false; inputErrorCount = 0; return true; }
219e9310-78b0-4859-8551-3cac19ea6092
8
public static synchronized JMenu createFileMenu(){ JMenu fileMenu = new JMenu("File"); // Open File JMenuItem item = MenuBarUtils.createItem("Open", "open.png", new ActionListener() { public void actionPerformed(ActionEvent e) { FileSummary fileSummary = FileUtils.openFile(); if (fileSummary != null) { // Once a new file is opened - set the ActionToolbar to end state RecognizerActionToolbar.getInstance().setResetState(); // Adjust the text window in order to reflect the loaded file TextWindow.getInstance().setTitle(fileSummary.getFileName()); // Replace the digits for its equivalent digits TextWindow.getInstance().setText(FileUtils.replaceDigitsForText(fileSummary.getFileData().toString())); TextWindow.getInstance().setWidth(fileSummary.getMaximumWidth()); TextWindow.getInstance().update(); // Whenever a file is open update the text to recognize for the LiveRecognizer if (fileSummary.getFileData().toString() != null && !fileSummary.getFileData().toString().trim().isEmpty()) { // Make sure that there's a Sphinx Configuration file if(SpeechManager.getInstance().getSpeechConfiguration() == null){ // Retrieve the configuration from the software.properties file. String languageModel = SpeechManager.getInstance().setAndVerifyLanguageModel( GlobalProperties.getInstance().getProperty("sphinx.languageModel")); // Set up the Grammar Configuration SpeechManager.getInstance().setSpeechConfiguration( GlobalProperties.getInstance().getProperty( "speechManager.speechConfiguration." + languageModel, // Grammar Configuration SpeechManager.GRAMMAR_MODEL)); // Provide a default configuration if the above doesn't work } // The current Sphinx configuration is selected by the Sphinx Configuration Panel 'configuration' drop down // Do not leave the user waiting until the grammar is created SwingUtilities.invokeLater(new Runnable(){ public void run(){ // Allocate Sphinx4 for recognition SpeechManager.getInstance().configureRecognizer(); } }); // Reset the values of the property file ConfigurationWindow.getInstance().resetNumberOfMessagesToBeRepeated(); } else { // Display Error Message stating that the file is empty or there's nothing to recognize JOptionPane.showMessageDialog(null, "File [" + fileSummary.getFileName() + "] is empty!", "SpeechManager Error", JOptionPane.ERROR_MESSAGE); } } } }); item.setMnemonic('O'); item.setAccelerator(KeyStroke.getKeyStroke('O', CTRL_DOWN_MASK)); fileMenu.add(item); // Open Audio File boolean openAudio = GlobalProperties.getInstance().getPropertyAsBoolean("menuBar.openAudio"); if(openAudio){ JMenu audioMenu = MenuBarUtils.createMenu("Play Audio", "electronic-wave.png"); // Play data that is held in the microphone item = MenuBarUtils.createItem("Microphone data", new ActionListener() { public void actionPerformed(ActionEvent e) { // Only allow the user to open the audio file if there's no recording going on if(!SpeechManager.getInstance().isMicrophoneRecording()){ AudioPlayerWindow audioPlayerWindow = new AudioPlayerWindow(TextWindow.getInstance()); audioPlayerWindow.setLastOpenPath(ConfigurationWindow.getInstance().getPathToStoreAudioFile()); // ---------- Will play microphone data ---------- // //Pass the name of the files being read and the microphone data to the audio player gui String recognizerName = SpeechManager.getInstance().getLiveRecognizerName(); audioPlayerWindow.setFullNameOfAudioToPlay(recognizerName != null ? recognizerName : "[No recorded audio to be played]"); audioPlayerWindow.setMicrophoneData(SpeechManager.getInstance().getCompleteMicrophoneAudioStream()); // ---------- Will display visual audio data ---------- // // Pass Sphinx properties to the AudioPlayer - will help retrieving audio information to draw the Audio and Spectrogram panel audioPlayerWindow.setPropertySheet(SpeechManager.getInstance().getPropertySheet()); // Display the audio wave audioPlayerWindow.setDisplayVisualAudio(GlobalProperties.getInstance().getPropertyAsBoolean("audioPlayerWindow.displayVisualAudio")); // Never display the open button - Display the gui audioPlayerWindow.displayAudioPlayerWindowWithOpenButton(false); } } }); item.setMnemonic('M'); item.setToolTipText("Play the last recorded data"); item.setAccelerator(KeyStroke.getKeyStroke('P', CTRL_DOWN_MASK)); audioMenu.add(item); // Search for an audio file and play it item = MenuBarUtils.createItem("Search...", new ActionListener() { public void actionPerformed(ActionEvent e) { // Only allow the user to open the audio file if there's no recording going on if(!SpeechManager.getInstance().isMicrophoneRecording()){ AudioPlayerWindow audioPlayerWindow = new AudioPlayerWindow(TextWindow.getInstance()); audioPlayerWindow.setLastOpenPath(ConfigurationWindow.getInstance().getPathToStoreAudioFile()); // Display the gui audioPlayerWindow.displayAudioPlayerWindowWithOpenButton(); } } }); item.setMnemonic('S'); item.setToolTipText("Only MP3 format is supported!"); item.setAccelerator(KeyStroke.getKeyStroke('F', CTRL_DOWN_MASK)); audioMenu.add(item); fileMenu.add(audioMenu); } // Add Separator fileMenu.addSeparator(); // Set up the Exit button item = MenuBarUtils.createItem("Exit", null, new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); item.setMnemonic('E'); item.setAccelerator(KeyStroke.getKeyStroke('E', CTRL_DOWN_MASK)); fileMenu.add(item); return fileMenu; }
7fe38319-01c0-4c00-a89f-a68c5f71da1d
9
public ArrayList<String> wordBreak(String s, Set<String> dict) { if (s == null || s.length() == 0) { return null; } int len = s.length(); boolean[] t = new boolean[len + 1]; t[0] = true; for (int i = 0; i < len; i++) { if (!t[i]) continue; for (String a : dict) { int length = a.length(); int end = i + length; if (end > len) continue; if (t[end]) continue; if (s.substring(i, end).equals(a)) { t[end] = true; } } } ArrayList<String> result=new ArrayList<String>(); if(!t[len]) return result; dfs(s,t,len,0,result,new StringBuilder(),dict); return result; }
5eefa2d7-a7ba-4deb-b795-9ca590f79a25
9
protected Cursor loadCursor(String address, int x, int y) { if (address == null) return null; File f = null; if (Page.isApplet() || FileUtilities.isRemote(address)) { URL u = null; try { u = new URL(address); } catch (MalformedURLException e) { e.printStackTrace(); return null; } ConnectionManager.sharedInstance().setCheckUpdate(true); try { f = ConnectionManager.sharedInstance().shouldUpdate(u); if (f == null) f = ConnectionManager.sharedInstance().cache(u); } catch (IOException e) { e.printStackTrace(); return null; } } else { f = new File(address); } if (f == null || !f.exists()) { return null; } URL u = null; try { u = f.toURI().toURL(); } catch (MalformedURLException e) { e.printStackTrace(); return null; } return ModelerUtilities.createCursor(u, new Point(x, y), FileUtilities.getFileName(address)); }
d1c56daf-49b0-4d72-a8ae-b4b72a5f5e92
0
public void setTransform(AffineTransform af){ curTransform = af; }
275064f3-894a-4f28-a11f-7dbc06e23a26
4
public static void moveSelectedY(int y) { if (Main.selectedId != -1 && !Main.getSelected().locked) { RSInterface rsi = Main.getInterface(); if (rsi != null) { if (rsi.children != null) { rsi.childY.set(getSelectedIndex(), rsi.childY.get(getSelectedIndex()) + y); } } } }
f6623bcf-d345-4604-bf0f-cea1a0219382
2
public boolean satisfies(ArrayList<Boolean> b) { //since a clause is a disjunction, if one variable is //true, the whole clause is true. for(Variable v: variables) { boolean varBoo = b.get(v.getNumber()-1); //get boolean //for corresponding variable. if(v.getValue(varBoo)) return true; } return false; }
32297c68-5fc3-42b9-a6a3-a892ba089f93
8
@Override public String buscarDocumentoPorFechaVencimiento(String fechaven1, String fechaven2) { ArrayList<Venta> geResult= new ArrayList<Venta>(); ArrayList<Venta> dbVentas = tablaVentas(); String result=""; Date xfechaven1; Date xfechaven2; Date f1; try{ if (fechaven1.equals("") || fechaven2.equals("")){ result="No puede dejar uno de los campos de fecha en blanco"; return result; } else { SimpleDateFormat dformat = new SimpleDateFormat("dd/MM/yyyy"); xfechaven1 = dformat.parse(fechaven1); xfechaven2 = dformat.parse(fechaven2); for (int i = 0; i < dbVentas.size() ; i++){ f1=dformat.parse(dbVentas.get(i).getFechaven()); if((f1.compareTo(xfechaven1))>=0 && (f1.compareTo(xfechaven2))<=0){ geResult.add(dbVentas.get(i)); } } } }catch (NullPointerException e) { result="No hay Ventas entre las fechas proporcionadas"; }catch (ParseException e){ result=e.getMessage(); } if (geResult.size()>0){ result=imprimir(geResult); } else { result="No se ha encontrado ningun registro"; } return result; }
6f426ebd-77b1-44ed-837b-700d97c2e0df
3
@Test public void testPutGetMessagesInOrder() { try { int noOfMessages = 5; final CountDownLatch gate = new CountDownLatch(noOfMessages); final ArrayList<Message> list = new ArrayList<Message>(noOfMessages); for (int i = 0; i < noOfMessages; i++) { Message msg = new MockMessage("TestMessage"); list.add(i, msg); } AsyncMessageConsumer testSubscriber = new MockTopicSubscriber() { int cnt = 0; public void onMessage(Message received) { assertNotNull("Received Null Message", received); assertEquals("Message values are not equal", list.get(cnt), received); cnt++; gate.countDown(); } }; destination.addSubscriber(testSubscriber); for (Message message : list) { destination.put(message); } boolean messageReceived = gate.await(100, TimeUnit.MILLISECONDS); assertTrue("Did not receive message in 100ms", messageReceived); } catch (Throwable e) { fail("Error while putting message in topic" + e.getMessage()); } }
846c2f69-13c7-4fe8-9113-8a53177fdb24
2
public String getFieldrefName(int index) { FieldrefInfo f = (FieldrefInfo)getItem(index); if (f == null) return null; else { NameAndTypeInfo n = (NameAndTypeInfo)getItem(f.nameAndTypeIndex); if(n == null) return null; else return getUtf8Info(n.memberName); } }
454d5894-6af0-418c-81de-88e1a9c1fd36
7
public static void main(String[] args) { Scanner s = new Scanner(System.in); String str; int temp = 0; int last = -1; Boolean consecutive = true; System.out.println("Please enter a string of positve integers."); System.out.println("Please enter '-1' to end and find whether your list was consecutve and increasing."); System.out.print("Please enter your first number: "); while(true){ str = s.nextLine(); temp = Integer.parseInt(str); if(temp == -1){ break; } if(temp < -1){ System.out.print("Please enter positive numbers only: "); return; } if(last == -1){ System.out.print("Next number: "); last = temp; continue; } if(temp - last != 1){ consecutive = false; } last = temp; System.out.print("Next number: "); } if(last == -1){ System.out.println("You didn't add any numbers."); } else{ System.out.println(consecutive ? "Yes" : "No"); } }