text
stringlengths
14
410k
label
int32
0
9
public void testValueCollectionToArray() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap<String> raw_map = new TIntObjectHashMap<String>(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map<Integer, String> map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); Collection<String> collection = map.values(); for (int i = 0; i < collection.size(); i++) { assertTrue(collection.contains(vals[i])); } assertFalse(collection.isEmpty()); Object[] values_obj_array = collection.toArray(); int count = 0; Iterator<String> iter = collection.iterator(); while (iter.hasNext()) { String value = iter.next(); assertTrue(collection.contains(value)); assertEquals(values_obj_array[count], value); count++; } //noinspection ToArrayCallWithZeroLengthArrayArgument String[] values_array = collection.toArray(new String[0]); count = 0; iter = collection.iterator(); while (iter.hasNext()) { String value = iter.next(); assertTrue(collection.contains(value)); assertEquals(values_array[count], value); count++; } values_array = collection.toArray(new String[collection.size()]); count = 0; iter = collection.iterator(); while (iter.hasNext()) { String value = iter.next(); assertTrue(collection.contains(value)); assertEquals(values_array[count], value); count++; } values_array = collection.toArray(new String[collection.size() * 2]); count = 0; iter = collection.iterator(); while (iter.hasNext()) { String value = iter.next(); assertTrue(collection.contains(value)); assertEquals(values_array[count], value); count++; } assertNull(values_array[collection.size()]); assertNull(values_array[collection.size()]); Collection<String> other = new ArrayList<String>(collection); assertFalse(collection.retainAll(other)); other.remove(vals[5]); assertTrue(collection.retainAll(other)); assertFalse(collection.contains(vals[5])); assertFalse(map.containsKey(keys[5])); collection.clear(); assertTrue(collection.isEmpty()); }
6
@EventHandler(priority = EventPriority.NORMAL) public void onBlockBurn(BlockBurnEvent event) { if (event.isCancelled()) return; // plugin.debug(event.getEventName()); Block block = event.getBlock(); if (plugin.isProtected(block)) { plugin.debug("Blocking block burn at " + block.getWorld().getName() + " " + block.getX() + " " + block.getY() + " " + block.getZ()); event.setCancelled(true); return; } }
2
private void populateEntity() { enemys = new ArrayList<Enemy>(); entities = new ArrayList<EntitySpecial>(); Slugger s; Crawler c; Point[] points = new Point[] {}; Point[] points2 = new Point[] {}; for (int i = 0; i < points.length; i++) { s = new Slugger(tileMap); s.setPosition(points[i].x, points[i].y); enemys.add(s); } for (int i = 0; i < points2.length; i++) { c = new Crawler(tileMap); c.setPosition(points2[i].x, points2[i].y); enemys.add(c); } }
2
public static LinkedList<Pair<Integer, Set<CharacterClass>>> getOverlaps(Set<CharacterClass> ccs) { LinkedList<Pair<Integer, Set<CharacterClass>>> overlaps = new LinkedList<Pair<Integer,Set<CharacterClass>>>(new Pair<Integer, Set<CharacterClass>>(0, new ShareableHashSet<CharacterClass>())); // insert all ranges of all characterclasses into the list for (CharacterClass cc : ccs) { LinkedList<Pair<Integer, Set<CharacterClass>>> l = overlaps; for (int i = 0; i < cc.size; ) { int c1 = cc.ranges[i++]; int c2 = cc.ranges[i++]; // from while (l.next != null && l.next.elem.a <= c1) { l = l.next; } if (l.elem.a == c1) { // do nothing } else { Pair<Integer, Set<CharacterClass>> p = new Pair<Integer, Set<CharacterClass>>(c1, new ShareableHashSet<CharacterClass>()); p.b.addAll(l.elem.b); l = l.insert(p); } // to while (l.next != null && l.next.elem.a <= c2) { l.elem.b.add(cc); l = l.next; } if (l.next == null) { l.insert(new Pair<Integer, Set<CharacterClass>>(c2 + 1, new ShareableHashSet<CharacterClass>())); } else if (l.next.elem.a == c2 + 1) { // do nothing } else { Pair<Integer, Set<CharacterClass>> p = new Pair<Integer, Set<CharacterClass>>(c2 + 1, new ShareableHashSet<CharacterClass>()); p.b.addAll(l.elem.b); l.insert(p); } l.elem.b.add(cc); } } return overlaps; }
9
protected Map<Integer, Sugar> getFreeSugar() { Map<Integer, Sugar> freeSugar = new HashMap<Integer, Sugar>(); for (Sugar sugar : getSugar().values()) { boolean free = true; for (Team team : world.getTeams().values()) { for (Ant ant : team.getAnts().values()) { if (!ant.isSweet()) continue; if (sugar.getX()==ant.getX() && sugar.getY()==ant.getY()) { free = false; break; } } if (!free) break; } if (free) freeSugar.put(sugar.toPositionHash(), sugar); } return freeSugar; }
8
public boolean isBST2(BTPosition<T> current, T min) { if (current == null) return true; Stack<BTPosition<T>> s = new Stack<>(); while (!s.isEmpty() || current != null) { if (current != null) { s.push(current); current = current.getLeft(); } else { current = s.pop(); if (comp.compare(min, current.element()) > 0) return false; min = current.element(); current = current.getRight(); } } return true; }
5
private TableColumn<Object, ?> getNextColumn(boolean forward) { List<TableColumn<Object, ?>> columns = new ArrayList<>(); for (TableColumn<Object, ?> column : getTableView().getColumns()) { columns.addAll(getLeaves(column)); } //There is no other column that supports editing. if (columns.size() < 2) { return null; } int currentIndex = columns.indexOf(getTableColumn()); int nextIndex = currentIndex; if (forward) { nextIndex++; if (nextIndex > columns.size() - 1) { nextIndex = 0; } } else { nextIndex--; if (nextIndex < 0) { nextIndex = columns.size() - 1; } } return columns.get(nextIndex); }
8
@Override public DBConfig get() { Properties props = new Properties(); try { FileReader reader = new FileReader("Database.properties"); props.load(reader); } catch(IOException io) { } log.info("------- URL--------- : " + System.getProperty("connection.url")); log.info("------- USER ------- : " + System.getProperty("connection.user")); log.info("------- PASS ------- : " + System.getProperty("connection.pass")); ConfigurationObjectFactory c = new ConfigurationObjectFactory(props); return c.build(DBConfig.class); }
1
private void postPlugin(boolean isPing) throws IOException { // Server software specific section PluginDescriptionFile description = plugin.getDescription(); String pluginName = description.getName(); boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled String pluginVersion = description.getVersion(); String serverVersion = Bukkit.getVersion(); int playersOnline = Bukkit.getServer().getOnlinePlayers().length; // END server software specific section -- all code below does not use any code outside of this class / Java // Construct the post data final StringBuilder data = new StringBuilder(); // The plugin's description file containg all of the plugin data such as name, version, author, etc data.append(encode("guid")).append('=').append(encode(guid)); encodeDataPair(data, "version", pluginVersion); encodeDataPair(data, "server", serverVersion); encodeDataPair(data, "players", Integer.toString(playersOnline)); encodeDataPair(data, "revision", String.valueOf(REVISION)); // New data as of R6 String osname = System.getProperty("os.name"); String osarch = System.getProperty("os.arch"); String osversion = System.getProperty("os.version"); String java_version = System.getProperty("java.version"); int coreCount = Runtime.getRuntime().availableProcessors(); // normalize os arch .. amd64 -> x86_64 if (osarch.equals("amd64")) { osarch = "x86_64"; } encodeDataPair(data, "osname", osname); encodeDataPair(data, "osarch", osarch); encodeDataPair(data, "osversion", osversion); encodeDataPair(data, "cores", Integer.toString(coreCount)); encodeDataPair(data, "online-mode", Boolean.toString(onlineMode)); encodeDataPair(data, "java_version", java_version); // If we're pinging, append it if (isPing) { encodeDataPair(data, "ping", "true"); } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(pluginName))); // Connect to the website URLConnection connection; // Mineshafter creates a socks proxy, so we can safely bypass it // It does not reroute POST requests so we need to go around it if (isMineshafterPresent()) { connection = url.openConnection(Proxy.NO_PROXY); } else { connection = url.openConnection(); } connection.setDoOutput(true); // Write the data final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data.toString()); writer.flush(); // Now read the response final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); final String response = reader.readLine(); // close resources writer.close(); reader.close(); if (response == null || response.startsWith("ERR")) { throw new IOException(response); //Throw the exception } }
5
public Coordinate getEndPoint1() { Coordinate coord1 = new Coordinate(0,0); if ((rotation % 2) == 1 ) { coord1 = new Coordinate(x-100, y); } if ((rotation % 2) == 0 ) { coord1 = new Coordinate(x, y-100); } return coord1; }
2
public void flush() throws IOException { synchronized(forked) { for(OutputStream s : forked) s.flush(); } }
1
public static void addModsToInstallation() { TroveModLoader.getTroveModLoaderGUI().disableButtons(true); if (getTroveInstallLocation() != null && !getTroveInstallLocation().isEmpty()) { File installDirectory = new File(getTroveInstallLocation()); for (File mod : TroveMods.getMods()) { try { unzipFileIntoDirectory(new ZipFile(mod), installDirectory); } catch (IOException ex) { ex.printStackTrace(); } } } TroveModLoader.getTroveModLoaderGUI().enabledButtons(); if (TroveMods.getMods().size() <= 0) { return; } saveMods(); setTroveModText(); }
5
public void setup(String prefixChat, String prefixPermissions, boolean createDirectory) { server = getServer(); this.prefixChat = (prefixChat + ChatColor.WHITE); this.permissionHandler = new PermissionHandler(prefixPermissions); this.permissionHandler.setupPermissions(); this.myLog = new MyLogger(this.getDescription().getName()); PermissionHelper.setupPermissions(getServer()); if (createDirectory) { if (!getDataFolder().exists()) { getDataFolder().mkdir(); } File config = new File(getDataFolder() + "/config.yml"); if (!config.exists()) { try { config.createNewFile(); onConfigurationDefault(this.getConfig()); this.saveConfig(); } catch (IOException e) { e.printStackTrace(); } } try { loadLang(); } catch (IOException e) { e.printStackTrace(); } } }
5
synchronized public void writeEnableContinuousUpdates(boolean enable, int x, int y, int w, int h) { if (!cp.supportsContinuousUpdates) throw new ErrorException("Server does not support continuous updates"); startMsg(MsgTypes.msgTypeEnableContinuousUpdates); os.writeU8((enable?1:0)); os.writeU16(x); os.writeU16(y); os.writeU16(w); os.writeU16(h); endMsg(); }
2
public void gameOverPopUp(){ manager.removeKeyEventDispatcher(controls); nomJoueur = JOptionPane.showInputDialog(null, "Fin de la partie \nNombre de rangée compléter : " + nbRangeeCompleted +"\nEntrez votre nom pour le classement."); temps = (int)((System.currentTimeMillis() - startTime)/1000) ; if (nomJoueur == null) nomJoueur = ("Anonyme"); else nomJoueur = nomJoueur.replaceAll("[\\s]",""); addScore(nomJoueur); manager.addKeyEventDispatcher(controls); Fenetre topFrame = (Fenetre) SwingUtilities.getWindowAncestor(this); topFrame.getStatistique().setRangeeComplete(nbRangeeCompleted); topFrame.enableDifficulte(false); }
1
public String getName() { return name; }
0
@Override public byte[] getHTTPMessageBody() { PartialContentParser partialContentParser = new PartialContentParser(byteRange); try { return partialContentParser.getPartialContent(Files.readAllBytes(Paths.get(directory + "/" + uri))); } catch (Exception e) { e.printStackTrace(); } return "Request Invalid".getBytes(); }
1
public void setSize(Dimension paramDimension) { MapCell[][] arrayOfMapCell = new MapCell[paramDimension.width][paramDimension.height]; for (int i = 0; i < paramDimension.width; i++) for (int j = 0; j < paramDimension.height; j++) if ((i >= this.mapsize.width) || (j >= this.mapsize.height)) arrayOfMapCell[i][j] = new MapCell(); else arrayOfMapCell[i][j] = this.mapdata[i][j]; this.mapdata = arrayOfMapCell; this.mapsize = paramDimension; }
4
public void messageReceived(MessageEvent e) { if (!Widgets.get(335).getChild(9).isOnScreen() || !Widgets.get(334).getChild(8).isOnScreen()) { if (e.getMessage().toLowerCase().contains("ilovehf") || e.getMessage().toLowerCase().contains("i love rs")) { if (!getPlayerName(e.getSender())) { play = e.getSender(); writePlayername(); } } } }
5
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed /* Muestra los datos de las ventas comprendidas entre los montos ingresados en los Spinner, * estos valores son validados de modo que el valor maximo sea mayor que el mínimo requerido. */ if((int) jSpinner1.getValue() > (int) jSpinner2.getValue()){ JOptionPane.showMessageDialog(this, "Ingrese montos en forma correcta"); } int a = (int) jSpinner1.getValue(); int b = (int) jSpinner2.getValue(); boolean match=false; for(int i=0;i<jTable1.getRowCount();i++){ if((Integer.parseInt(String.valueOf(jTable1.getValueAt(i, 6))) >= a) && (Integer.parseInt(String.valueOf(jTable1.getValueAt(i, 6))) <= b)){ match=true; } if(match==true){ Object ed[]={jTable1.getValueAt(i, 0),jTable1.getValueAt(i, 1),jTable1.getValueAt(i, 2), jTable1.getValueAt(i, 3),jTable1.getValueAt(i, 4),jTable1.getValueAt(i, 5), jTable1.getValueAt(i, 6)}; Datos.addRow(ed); jTable2.setModel(Datos); } } }//GEN-LAST:event_jButton2ActionPerformed
5
public static <T extends RestObject> T postRestObject(Class<T> restObject, String url) throws RestfulAPIException { InputStream stream = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setConnectTimeout(15000); conn.setReadTimeout(15000); stream = conn.getInputStream(); String data = IOUtils.toString(stream, Charsets.UTF_8); T result = gson.fromJson(data, restObject); if (result == null) { throw new RestfulAPIException("Unable to access URL [" + url + "]"); } if (result.hasError()) { throw new RestfulAPIException("Error in response: " + result.getError()); } return result; } catch (SocketTimeoutException e) { throw new RestfulAPIException("Timed out accessing URL [" + url + "]", e); } catch (MalformedURLException e) { throw new RestfulAPIException("Invalid URL [" + url + "]", e); } catch (JsonParseException e) { throw new RestfulAPIException("Error parsing response JSON at URL [" + url + "]", e); } catch (IOException e) { throw new RestfulAPIException("Error accessing URL [" + url + "]", e); } finally { IOUtils.closeQuietly(stream); } }
6
public static void printAll() { try { PreparedStatement stmt = Main.EMART_CONNECTION.prepareStatement("select * " + "from customer"); ResultSet rs = stmt.executeQuery(); System.out.println("Customers:"); while (rs.next()) { System.out.println(rs.getString("cid") + " | " + rs.getString("password") + " | " + rs.getString("customer_name") + " | " + rs.getString("email") + " | " + rs.getString("address") + " | " + rs.getString("status") + " | " + rs.getString("is_manager")); PreparedStatement cartStmt = Main.EMART_CONNECTION.prepareStatement("select * from cartitem where cid = ?"); System.out.println("Cart Items:"); cartStmt.setString(1, rs.getString("cid")); ResultSet cartrs = cartStmt.executeQuery(); while (cartrs.next()) { System.out.println(cartrs.getString("stock_number") + " x" + cartrs.getInt("amount")); } } } catch (SQLException e) { e.printStackTrace(); } }
3
public void removePhiAtBlock(final Block block) { final PhiStmt phi = phis[cfg.preOrderIndex(block)]; if (phi != null) { if (SSA.DEBUG) { System.out.println(" removing " + phi + " at " + block); } phi.cleanup(); phis[cfg.preOrderIndex(block)] = null; } }
2
protected Collection<Object> getCellsForChange(mxUndoableChange change) { mxIGraphModel model = getGraph().getModel(); Set<Object> result = new HashSet<Object>(); if (change instanceof mxChildChange) { mxChildChange cc = (mxChildChange) change; Object parent = model.getParent(cc.getChild()); if (cc.getChild() != null) { result.add(cc.getChild()); } if (parent != null) { result.add(parent); } if (cc.getPrevious() != null) { result.add(cc.getPrevious()); } } else if (change instanceof mxTerminalChange || change instanceof mxGeometryChange) { Object cell = (change instanceof mxTerminalChange) ? ((mxTerminalChange) change) .getCell() : ((mxGeometryChange) change).getCell(); if (cell != null) { result.add(cell); Object parent = model.getParent(cell); if (parent != null) { result.add(parent); } } } return result; }
9
public boolean delete(Prestamos p){ PreparedStatement ps; try { ps = mycon.prepareStatement("DELETE FROM Prestamos WHERE id=?"); ps.setInt(1, p.getId()); return (ps.executeUpdate()>0); } catch (SQLException ex) { Logger.getLogger(PrestamosCRUD.class.getName()).log(Level.SEVERE, null, ex); } return false; }
1
public Speaking(Gob gob, Coord off, String text) { super(gob); if(sb == null) sb = new IBox("gfx/hud/emote", "tl", "tr", "bl", "br", "el", "er", "et", "eb"); svans = Resource.loadtex("gfx/hud/emote/svans"); this.off = off; this.text = Text.render(text, Color.BLACK); }
1
@Override public boolean equals(Object obj) { return obj instanceof SinglePlayerGame ? ((SinglePlayerGame) obj).name.equals(this.name) : false; }
1
protected void updateTargetRequest() { repairStartLocation(); ChangeBoundsRequest request = (ChangeBoundsRequest) getTargetRequest(); request.setEditParts(getOperationSet()); Dimension delta = getDragMoveDelta(); request.setConstrainedMove(getCurrentInput().isModKeyDown( MODIFIER_CONSTRAINED_MOVE)); request.setSnapToEnabled(!getCurrentInput().isModKeyDown( MODIFIER_NO_SNAPPING)); // constrains the move to dx=0, dy=0, or dx=dy if shift is depressed if (request.isConstrainedMove()) { float ratio = 0; if (delta.width != 0) ratio = (float) delta.height / (float) delta.width; ratio = Math.abs(ratio); if (ratio > 0.5 && ratio < 1.5) { if (Math.abs(delta.height) > Math.abs(delta.width)) { if (delta.height > 0) delta.height = Math.abs(delta.width); else delta.height = -Math.abs(delta.width); } else { if (delta.width > 0) delta.width = Math.abs(delta.height); else delta.width = -Math.abs(delta.height); } } else { if (Math.abs(delta.width) > Math.abs(delta.height)) delta.height = 0; else delta.width = 0; } } Point moveDelta = new Point(delta.width, delta.height); request.getExtendedData().clear(); request.setMoveDelta(moveDelta); snapPoint(request); request.setLocation(getLocation()); request.setType(getCommandName()); }
8
public static void printRes(int one, int two, int five, int ten, int twenty, int fifty, int hund, int twoHund) { for(int i = 0; i < one; i++) System.out.print("one, "); for(int i = 0; i < two; i++) System.out.print("two, "); for(int i = 0; i < five; i++) System.out.print("five, "); for(int i = 0; i < ten; i++) System.out.print("ten, "); for(int i = 0; i < twenty; i++) System.out.print("twenty, "); for(int i = 0; i < fifty; i++) System.out.print("fifty, "); for(int i = 0; i < hund; i++) System.out.print("hund, "); for(int i = 0; i < twoHund; i++) System.out.print("twoHund, "); System.out.println(); }
8
@Override public void setRandomSeed(long seed) { r = new Random(seed); for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) for (int k = 0; k < zsize; k++) for (int d = 0; d < density; d++) for (int e = 0; e < dimensions; e++) grid[i][j][k][d][e] = r.nextDouble(); }
5
public void execute(CommandSender sender, String[] args) { if (!sender.hasPermission("bungeeannouncer.admin")) { sender.sendMessage(FontFormat.translateString("&4You do not have permission to use this command")); return; } if (args.length != 1) { sender.sendMessage(FontFormat.translateString("&7Usage: /announce_remove <message>")); return; } try { int id = Integer.parseInt(args[0]); plugin.getConfigStorage().removeAnnouncement(sender, id); } catch (NumberFormatException e) { sender.sendMessage(FontFormat.translateString("&4You can only use numeric values.")); return; } }
3
private void grow() { Bucket[] oldBuckets = buckets; int newCap = buckets.length * 2 + 1; threshold = (int) (loadFactor * newCap); buckets = new Bucket[newCap]; for (int i = 0; i < oldBuckets.length; i++) { Bucket nextBucket; for (Bucket b = oldBuckets[i]; b != null; b = nextBucket) { if (i != Math.abs(b.hash % oldBuckets.length)) throw new RuntimeException("" + i + ", hash: " + b.hash + ", oldlength: " + oldBuckets.length); int newSlot = Math.abs(b.hash % newCap); nextBucket = b.next; b.next = buckets[newSlot]; buckets[newSlot] = b; } } }
3
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: if (time == null) { JOptionPane.showMessageDialog(null, "Por favor, selecione uma data para pesquisar"); return; } Calendar cal = Calendar.getInstance(); cal.setTime(time); int day = cal.get(Calendar.DAY_OF_MONTH); int month = cal.get(Calendar.MONTH); int year = cal.get(Calendar.YEAR); try { if(totalRecebido.isSelected()){ resultado.setText(String.valueOf(fac.totalRecebido(year,month,day))); }else if (totalPago.isSelected()){ resultado.setText(String.valueOf(fac.numeroTicketPago(year,month,day))); }else if (totalSemPagamento.isSelected()) { resultado.setText(String.valueOf(fac.numeroTicketsLiberadosSemPagamento(year,month,day))); } } catch (CancelaDAOException ex) { Logger.getLogger(GerencialTicket.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton1ActionPerformed
5
public String getEntityValue(String ename) { Object entity[] = (Object[]) entityInfo.get(ename); if (entity == null) { return null; } else { return (String) entity[3]; } }
1
private void processPacketQueue() { if (this.packetBuffer.size() > 0 && !this.encoding) { Packet pack = this.packetBuffer.remove(0); this.packet(pack); } }
2
public static void handleNick(String nick) { if ( nick.isEmpty() ) { appendError("Nebyla zadána nová přezdívka."); return; } getCurrentServerTab().getConnection().changeNick(nick); clearInput(); }
1
public void keyPressed(KeyEvent key){ if(key.getKeyCode() == KeyEvent.VK_ESCAPE){ if(!over){ paused = !paused; }else{ st.currentLevel = 0; } } if(key.getKeyCode() == KeyEvent.VK_ENTER){ if(over){ restart(); } } }
4
public Stats getLastStats(int mode) { try { switch(mode) { case 0: return getStatsOsuStandard(new TreeSet<>(this.stats_normal.keySet()).last()); case 1: return getStatsTaiko(new TreeSet<>(this.stats_taiko.keySet()).last()); case 2: return getStatsCTB(new TreeSet<>(this.stats_ctb.keySet()).last()); case 3: return getStatsOsuMania(new TreeSet<>(this.stats_mania.keySet()).last()); } } catch(NoSuchElementException e) { return null; } throw new IllegalArgumentException("Mode must be between 0 and 3!"); }
5
@Override public void update() { super.update(); boolean finished = false; if(generationNum==numGenerations && !flag) { flag = true; OrganismRepository.getInstance().printResults(); System.out.println("=================================!"); System.out.println("FINISHED!"); System.out.println("FINISHED!"); System.out.println("FINISHED!"); System.out.println("=================================!"); } if(testsStarted) { for(Future<Float> f: resultsFuturesList) { finished = f.isDone(); } if(finished) { for(Organism o: organismList) { o.getOrganismJme().getOrganismTimer().setFinished(true); } if(generationNum<=numGenerations) { testsStarted=false; List<OrganismTree> newGen = null; cleanUpPhysics(); try { newGen = gaManager.step(generationNum); System.out.println("GENERATION "+generationNum); } catch (DeepCopyException e) { e.printStackTrace(); } rootNode.detachAllChildren(); organismList.clear(); makePopulation(newGen); } } } };
8
protected boolean endsWithCVC (String str) { char c, v, c2 = ' '; if (str.length() >= 3) { c = str.charAt(str.length() - 1); v = str.charAt(str.length() - 2); c2 = str.charAt(str.length() - 3); } else { return false; } if ((c == 'w') || (c == 'x') || (c == 'y')) { return false; } else if (isVowel(c)) { return false; } else if (!isVowel(v)) { return false; } else if (isVowel(c2)) { return false; } else { return true; } } // end function
7
public void removeItem(int slot, int amount) { Item item = beastItems.get(slot); if (item == null) return; Item[] itemsBefore = beastItems.getItemsCopy(); int maxAmount = beastItems.getNumberOf(item); if (amount < maxAmount) item = new Item(item.getId(), amount); else item = new Item(item.getId(), maxAmount); int freeSpace = player.getInventory().getFreeSlots(); if (!item.getDefinitions().isStackable()) { if (freeSpace == 0) { player.getPackets().sendGameMessage( "Not enough space in your inventory."); return; } if (freeSpace < item.getAmount()) { item.setAmount(freeSpace); player.getPackets().sendGameMessage( "Not enough space in your inventory."); } } else { if (freeSpace == 0 && !player.getInventory().containsItem(item.getId(), 1)) { player.getPackets().sendGameMessage( "Not enough space in your inventory."); return; } } beastItems.remove(slot, item); beastItems.shift(); player.getInventory().addItem(item); refreshItems(itemsBefore); }
7
private void handleAction() { if(actionButton.getText().equals("Find IP")){ Integer ip = dnsDB.findIP(nameText.getText()); if(ip == null){ JOptionPane.showMessageDialog(GUI.this, "Could not find an IP address with host name: " + nameText.getText()); } else{ ipText.setText(DNSDB.IPToString(ip)); } } else if(actionButton.getText().equals("Find Host Name")){ Integer ip = DNSDB.stringToIP(ipText.getText()); if(ip == null){ JOptionPane.showMessageDialog(GUI.this, "'" + ipText.getText() + "' is not a valid IP address."); } else{ String name = dnsDB.findHostName(ip); if(name == null){ JOptionPane.showMessageDialog(GUI.this, "Could not find a host name with IP address: " + ipText.getText()); } else{ nameText.setText(name); } } } else if(actionButton.getText().equals("Test Name-IP Pair")){ Integer ip = DNSDB.stringToIP(ipText.getText()); if(ip == null){ JOptionPane.showMessageDialog(GUI.this, "'" + ipText.getText() + "' is not a valid IP address."); } else{ boolean valid = dnsDB.testPair(ip, nameText.getText()); if(valid){ JOptionPane.showMessageDialog(GUI.this, "'" + ipText.getText() + "' is correctly mapped to '" + nameText.getText() + "'."); } else{ JOptionPane.showMessageDialog(GUI.this, "'" + ipText.getText() + "' is not the IP address for '" + nameText.getText() + "'."); } } } }
8
public void saveResult() { if (ea != null && ea.bestSolution != null) { fj.showSaveDialog(this); if (fj.getSelectedFile() != null) { try { PrintWriter out = new PrintWriter(fj.getSelectedFile()); for (int i = 0; i < ea.bestSolution.length; ++i) { out.printf("v%d : %d\n", i + 1, ea.bestSolution[i]); } out.close(); } catch (FileNotFoundException ex) { Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(rootPane, "Nieudana próba zapisu!"); } } } else { JOptionPane.showMessageDialog(rootPane, "Brak wyniku!"); } }
5
private void affTraceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_affTraceActionPerformed if (trace == false){ trace = true; } else if (trace == true){ trace = false; } }//GEN-LAST:event_affTraceActionPerformed
2
public void printZigZag(BSTNode<T> root) { LinkedList<Pair> nextLevelStack = new LinkedList<>(); // this keeps odd level nodes LinkedList<Pair> currentLevelStack = new LinkedList<>(); // this keeps even level nodes //add the root to even level stack currentLevelStack.addFirst(new Pair(root, 0)); int printLevel = 0; // iterate while both are not empty while(!currentLevelStack.isEmpty() || !nextLevelStack.isEmpty() ) { // for even printLevel if(printLevel %2 ==0) { // pop even level stack Pair p = currentLevelStack.removeFirst(); // print the data without new line System.out.print(" "+ p.node.data+ " "); //push left child to nextLevel(odd level) stack if it is present if(p.node.left != null) { nextLevelStack.addFirst(new Pair(p.node.left,p.level+1)); } //push right child to nextLevel(odd level) stack if it is present if(p.node.right != null) { nextLevelStack.addFirst(new Pair(p.node.right,p.level+1)); } // check if evenLevel stack is empty .. if yes increment the print level if(currentLevelStack.isEmpty()){ printLevel ++; // this is for printing level by level in new line System.out.println(); } } else { Pair p = nextLevelStack.removeFirst(); System.out.print(" "+p.node.data+" "); if(p.node.right != null) { currentLevelStack.addFirst(new Pair(p.node.right,p.level+1)); } if(p.node.left != null) { currentLevelStack.addFirst(new Pair(p.node.left,p.level+1)); } if(nextLevelStack.isEmpty()){ printLevel ++; System.out.println(); } } } }
9
public void run() { prevFps = 0; fps = 0; prevTime = System.nanoTime(); // grab current time in nano second this.preStart().start().postStart(); while (this.sceneOnPlay()) { currTime = System.nanoTime(); length = currTime - prevTime; prevTime = currTime; delta = length / ((double)optimalTime); prevFps += length; fps++; if (prevFps >= 1000000000) { newSecond = true; grabFps = fps; System.out.println("(fps: "+fps+")"); prevFps = 0; fps = 0; } else { newSecond = false; } // ImageManager + AudioManager update DataManager.update(); this.update(); ImageManager.update(); try { if ((prevTime-System.nanoTime() + optimalTime)/1000000 > 0) Thread.sleep( (prevTime-System.nanoTime() + optimalTime)/1000000 ); } catch (InterruptedException exp) { System.out.println(exp); }; } this.preEnd().end().postEnd(); }
4
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ListasItens)) { return false; } ListasItens other = (ListasItens) object; if ((this.iListaItens == null && other.iListaItens != null) || (this.iListaItens != null && !this.iListaItens.equals(other.iListaItens))) { return false; } return true; }
5
@Override public Product getProduct(String id) { Product prod; Session session = null; Transaction trx = null; try { session = sessionFactory.openSession(); trx = session.beginTransaction(); Criteria cr = session.createCriteria(Product.class); cr.add(Restrictions.eq("asin", id)); List result = cr.list(); Iterator it = result.iterator(); if(it.hasNext()) return (Product)it.next(); else return null; } catch(HibernateException e) { if(trx != null) { try {trx.rollback(); } catch(HibernateException he) {} } } finally { try { if( session != null ) session.close(); } catch( Exception exC1 ) {} } return null; }
6
public boolean isExist(int number, int counter){ int x = 0; while(x < counter){ if(number == randlist[x]){ return false; } x++; } return true; }
2
private Shape createShapeWithOneParameter(BufferedReader reader, String shape, ShapeColor color, Map<String, String[]> shapeMap) { // Ask for one parameter System.out.println(shapeMap.get(shape)[0] + ":"); double param = readParameter(reader); // Create class try { shape = "Shapes." + StringUtils.capitalize(shape); Class<?> newShape = Class.forName(shape); Class[] parameters = new Class[] { ShapeColor.class, double.class }; Constructor<?> constructor = newShape.asSubclass(Shape.class) .getConstructor(parameters); Object objShape = constructor.newInstance(color, param); return (Shape) objShape; } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; }
9
public CodeMap8 set(final int index, final int value) { final int i0 = index >>> 28; int[][][][][][][] map1 = map[i0]; if (map1 == null) map[i0] = map1 = new int[MAX_INDEX][][][][][][]; final int i1 = (index >>> 24) & 0xf; int[][][][][][] map2 = map1[i1]; if (map2 == null) map1[i1] = map2 = new int[MAX_INDEX][][][][][]; final int i2 = (index >>> 20) & 0xf; int[][][][][] map3 = map2[i2]; if (map3 == null) map2[i2] = map3 = new int[MAX_INDEX][][][][]; final int i3 = (index >>> 16) & 0xf; int[][][][] map4 = map3[i3]; if (map4 == null) map3[i3] = map4 = new int[MAX_INDEX][][][]; final int i4 = (index >>> 12) & 0xf; int[][][] map5 = map4[i4]; if (map5 == null) map4[i4] = map5 = new int[MAX_INDEX][][]; final int i5 = (index >>> 8) & 0xf; int[][] map6 = map5[i5]; if (map6 == null) map5[i5] = map6 = new int[MAX_INDEX][]; final int i6 = (index >>> 4) & 0xf; int[] map7 = map6[i6]; if (map7 == null) { map6[i6] = map7 = new int[MAX_INDEX]; for (int i = 0; i < MAX_INDEX; ++i) map7[i] = NOT_FOUND; } map7[index & 0xf] = value; return this; }
8
public void shortestPaths(int s, int t) { /* Initialize structures */ for (int i = 0; i < g.getNumVertices(); i++) { inTree[i] = Boolean.FALSE; distance[i] = Double.MAX_VALUE; parents[i] = -1; } distance[s] = 0; int x = s; while (!inTree[x]) { inTree[x] = Boolean.TRUE; /* Assign desirability values to neighbors of x */ EdgeNode p = g.getEdges(x); while (p != null) { int y = p.y; double weight = p.weight; if (distance[y] > distance[x] + weight) { distance[y] = distance[x] + weight; parents[y] = x; } p = p.next; } /* Select vertex with highest desirability (shortest path) */ double dist = Double.MAX_VALUE; for (int i = 0; i < g.getNumVertices(); i++) { if (!inTree[i] && distance[i] < dist) { dist = distance[i]; x = i; } } } }
7
public void actionPerformed(ActionEvent e) { for (int i = 0; i < enemyHeads.size(); i++) { EnemyHead a = (EnemyHead) enemyHeads.get(i); if (a.isVisible()) a.move(); else enemyHeads.remove(i); } try { heads.move(); } catch (MalformedURLException ex) { Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedAudioFileException ex) { Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex); } try { checkCollisions(); } catch (MalformedURLException ex) { Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedAudioFileException ex) { Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex); } repaint(); }
8
Rectangle(double x, double y, double width, double height) // constructor { this.X = x; this.Y = y; this.Width = width; this.Height = height; }
0
@Override protected int drawUnselectedText(Graphics graphics, int x, int y, int p0, int p1) { setRenderingHits((Graphics2D) graphics); Font saveFont = graphics.getFont(); Color saveColor = graphics.getColor(); SyntaxDocument doc = (SyntaxDocument) getDocument(); Segment segment = getLineBuffer(); // Draw the right margin first, if needed. This way the text overalys // the margin if (rightMarginColumn > 0) { int m_x = rightMarginColumn * graphics.getFontMetrics().charWidth('m'); int h = graphics.getFontMetrics().getHeight(); graphics.setColor(rightMarginColor); graphics.drawLine(m_x, y, m_x, y - h); } try { // Colour the parts Iterator<Token> i = doc.getTokens(p0, p1); int start = p0; while (i.hasNext()) { Token t = i.next(); // if there is a gap between the next token start and where we // should be starting (spaces not returned in tokens), then draw // it in the default type if (start < t.start) { doc.getText(start, t.start - start, segment); x = DEFAULT_STYLE.drawText(segment, x, y, graphics, this, start); } // t and s are the actual start and length of what we should // put on the screen. assume these are the whole token.... int l = t.length; int s = t.start; // ... unless the token starts before p0: if (s < p0) { // token is before what is requested. adgust the length and s l -= (p0 - s); s = p0; } // if token end (s + l is still the token end pos) is greater // than p1, then just put up to p1 if (s + l > p1) { l = p1 - s; } doc.getText(s, l, segment); x = styles.drawText(segment, x, y, graphics, this, t); start = t.end(); } // now for any remaining text not tokenized: if (start < p1) { doc.getText(start, p1 - start, segment); x = DEFAULT_STYLE.drawText(segment, x, y, graphics, this, start); } } catch (BadLocationException ex) { log.log(Level.SEVERE, "Requested: " + ex.offsetRequested(), ex); } finally { graphics.setFont(saveFont); graphics.setColor(saveColor); } return x; }
7
@Override protected void updateBucketVersioningStatusImpl(String bucketName, boolean enabled, boolean multiFactorAuthDeleteEnabled, String multiFactorSerialNumber, String multiFactorAuthCode) throws S3ServiceException { if (log.isDebugEnabled()) { log.debug( (enabled ? "Enabling" : "Suspending") + " versioning for bucket " + bucketName + (multiFactorAuthDeleteEnabled ? " with Multi-Factor Auth enabled" : "")); } try { XMLBuilder builder = XMLBuilder .create("VersioningConfiguration").a("xmlns", Constants.XML_NAMESPACE) .e("Status").t( (enabled ? "Enabled" : "Suspended") ).up() .e("MfaDelete").t( (multiFactorAuthDeleteEnabled ? "Enabled" : "Disabled")); Map<String, String> requestParams = new HashMap<String, String>(); requestParams.put("versioning", null); Map<String, Object> metadata = new HashMap<String, Object>(); if (multiFactorSerialNumber != null || multiFactorAuthCode != null) { metadata.put(Constants.AMZ_MULTI_FACTOR_AUTH_CODE, multiFactorSerialNumber + " " + multiFactorAuthCode); } try { performRestPutWithXmlBuilder(bucketName, null, metadata, requestParams, builder); } catch (ServiceException se) { throw new S3ServiceException(se); } } catch (ParserConfigurationException e) { throw new S3ServiceException("Failed to build XML document for request", e); } }
9
public void addUser(User user) { try { beginTransaction(); session.save(user); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } finally { closeSession(); } }
1
protected static Date handleDateSpecification(String specification) throws NumberFormatException, ParseException { if (specification == null) return null; else if (specification.toLowerCase().startsWith("in ")) { specification = specification.substring(3).trim().replace(" +", "").toLowerCase(); long expiryUnit = 1; if (specification.endsWith("h")) { expiryUnit = 60 * 60 * 1000; specification = specification.substring(0, specification.length() - 1); } else if (specification.endsWith("d")) { expiryUnit = 24 * 60 * 60 * 1000; specification = specification.substring(0, specification.length() - 1); } else if (specification.endsWith("w")) { expiryUnit = 7 * 24 * 60 * 60 * 1000; specification = specification.substring(0, specification.length() - 1); } else if (specification.endsWith("m")) { expiryUnit = (long) (30.436875 * 24 * 60 * 60 * 1000); specification = specification.substring(0, specification.length() - 1); } else if (specification.endsWith("y")) { expiryUnit = (long) (365.2425 * 24 * 60 * 60 * 1000); specification = specification.substring(0, specification.length() - 1); } long expiryCount = Long.parseLong(specification); return new Date(-expiryCount * expiryUnit); } else return MediaWiki.timestampToDate(specification); }
7
public void setFile(File file) { File oldFile = this.file; this.file = file; distributeFileChangeEvent(new FileChangeEvent(this, oldFile)); }
0
public void testObtenirDocument() { // simulation de documents PreProcessingEngineFichier pPEFichier = new PreProcessingEngineFichier(); try { String racine = new String(); if (System.getProperty("os.name").equals("Windows 8.1")) { racine = "C:/Users/Jérémie/Documents/TU/CrawlerTest/"; } else { racine = "/tmp/TU/CrawlerTest/"; } // Création de l'arborescence File arbo = new File(racine); arbo.mkdirs(); // création de fichier 1 File doc1temp = new File(racine + "DocTestUCrawler1.txt"); FileWriter writer1 = new FileWriter( racine + "DocTestUCrawler1.txt", true); writer1.write(contenuDocument, 0, contenuDocument.length()); writer1.close(); // création de fichier 2 File doc2temp = new File(racine + "DocTestUCrawler2.txt"); // doc2temp.deleteOnExit(); FileWriter writer2 = new FileWriter( racine + "DocTestUCrawler2.txt", true); writer2.write(contenuDocument2, 0, contenuDocument2.length()); writer2.close(); RobotFichier D = new RobotFichier(racine); D.collecter(pPEFichier); assertThat(pPEFichier.tailleDeLaFileDAttente(), IsEqual.equalTo(2)); // suppression du premier documentapres l'assertion if (doc1temp.exists()) { doc1temp.delete(); } // suppression du second document if (doc2temp.exists()) { doc2temp.delete(); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
4
private void processMouseDraggedEvent(MouseEvent e) { if (!isEnabled()) return; int x = e.getX(); int w2 = knob.width / 2; if (knobHeld) { if (x > w2 && x < fillLocator + w2) { knob.x = x - w2; } else if (x <= w2) { knob.x = 0; } else if (x >= fillLocator + w2) { knob.x = fillLocator; } calculateCurrentFrame(); if (movie == null) return; movie.setCurrentFrameIndex(currentFrame); movie.showFrame(currentFrame); movie.notifyMovieListeners(new MovieEvent(movie, MovieEvent.FRAME_CHANGED, currentFrame)); repaint(); } }
7
public static Filter isAbstract() { return new IsAbstract(); }
0
public static boolean writeEvents(int numNodes, int idTraffic) { double percent = 0; int qntNodeEv = 0; double lambda = 0; Distribution distTraffic = null; System.out.println("------------------------------------------------------"); System.out.println("ConfigTest"); System.out.println("------------------------------------------------------"); try { percent = Configuration.getDoubleParameter("ConfigTest/NodeEvents/percent"); qntNodeEv = (int) (numNodes * percent) / 100; System.out.println("ConfigTest/NodeEvents/percent = "+percent); System.out.println("qntNodeEv = "+qntNodeEv); } catch (CorruptConfigurationEntryException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { lambda = Configuration.getDoubleParameter("ConfigTest/Traffic/lambda"); distTraffic = new PoissonDistribution(lambda); } catch (CorruptConfigurationEntryException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { PrintStream ps = new PrintStream("./Traffic/"+idTraffic+"_traffic_"+numNodes+".txt"); ps.println("Number of nodes: " + numNodes); Configuration.printConfiguration(ps); ps.println(separator); UniformDistribution ud = new UniformDistribution(2, numNodes); Set<Integer> setNodes = new HashSet<Integer>(); while(setNodes.size() <= qntNodeEv){ setNodes.add((int) ud.nextSample()); } Iterator<Integer> it = setNodes.iterator(); while(it.hasNext()){ ps.println(it.next()+" "+(int)distTraffic.nextSample()); } /*for(Node n : Tools.getNodeList()) { Position p = n.getPosition(); ps.println(p.xCoord + ", " + p.yCoord + ", " + p.zCoord); }*/ ps.close(); return true; } catch (FileNotFoundException e) { // TODO Auto-generated catch block Tools.minorError(e.getMessage()); } System.out.println("------------------------------------------------------"); System.out.println("End ConfigTest"); System.out.println("------------------------------------------------------"); return false; }
5
protected void FillBuff() throws java.io.IOException { int i; if (maxNextCharInd == 4096) maxNextCharInd = nextCharInd = 0; try { if ((i = inputStream.read(nextCharBuf, maxNextCharInd, 4096 - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { if (bufpos != 0) { --bufpos; backup(0); } else { bufline[bufpos] = line; bufcolumn[bufpos] = column; } throw e; } }
4
@Override public boolean acceptsDraggableObject(DraggableObject object) { if(object instanceof DraggableObjectFile) { DraggableObjectFile fileobj = ((DraggableObjectFile)object); if(fileobj.file != null) { if(Animation.isValidFile(fileobj.file.getName())) return true; } } return false; }
3
public int upgradeLevel(Upgrade type) { if (upgrades == null) return 0 ; int num = 0 ; for (int i = 0 ; i < upgrades.length ; i++) { if (upgrades[i] == type && upgradeStates[i] == STATE_INTACT) num++ ; } return num ; }
4
public String[] getLine() throws IOException{ int lineNumber = -1; ArrayList<String> v = new ArrayList<String>(); if (tokenCache != null){ v.add(tokenCache); lineNumber = lineCache; } while ((tokenCache = lexer.getNextToken()) != null && (lineNumber == -1 || lexer.getLineNumber() == lineNumber)){ v.add(tokenCache); lineNumber = lexer.getLineNumber(); } if (v.size() == 0){ return null; } lastLine = lineNumber; lineCache = lexer.getLineNumber(); String[] result = new String[v.size()]; return v.toArray(result); }
5
public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader("jobs.txt")); int number = Integer.parseInt(br.readLine()); final Integer[][] schedule1 = new Integer[number][3]; final Double[][] schedule2 = new Double[number][3]; long sum_weight1 = 0, sum_weight2 = 0; String line; int counter =0; while((line = br.readLine())!=null){ String[] split = line.trim().split("(\\s)+"); schedule1[counter][0] = Integer.parseInt(split[0]); schedule1[counter][1] = Integer.parseInt(split[1]); schedule1[counter][2] = schedule1[counter][0] - schedule1[counter][1]; schedule2[counter][0] = Double.parseDouble(split[0]); schedule2[counter][1] = Double.parseDouble(split[1]); schedule2[counter][2] = schedule2[counter][0] / schedule1[counter][1]; counter++; } br.close(); final Comparator<Integer[]> arrayComparator1 = new Comparator<Integer[]>() { @Override public int compare(Integer[] int1, Integer[] int2) { if (int1[2] != int2[2]){ return int1[2].compareTo(int2[2]); } else return int1[0].compareTo(int2[0]); } }; final Comparator<Double[]> arrayComparator2 = new Comparator<Double[]>() { @Override public int compare(Double[] dou1, Double[] dou2) { if (dou1[2] != dou2[2]){ return dou1[2].compareTo(dou2[2]); } else return dou1[0].compareTo(dou2[0]); } }; Arrays.sort(schedule1, arrayComparator1); Arrays.sort(schedule2, arrayComparator2); for(int i = 0; i < number; i++){ System.out.print(schedule1[i][0] + " "); System.out.print(schedule1[i][1] + " "); System.out.print(schedule1[i][2]); System.out.println(); } int current_length = 0; for(int i = number - 1; i >= 0; i--){ current_length += schedule1[i][1]; sum_weight1 += current_length*schedule1[i][0]; } current_length = 0; for(int i = number - 1; i >= 0; i--){ current_length += schedule2[i][1]; sum_weight2 += current_length*schedule2[i][0]; } System.out.println(sum_weight1); System.out.println(sum_weight2); }
6
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed //Se finaliza el programa System.exit(0); }//GEN-LAST:event_jMenuItem4ActionPerformed
0
public void setReload(final Expr expr, final boolean flag) { if (SSAPRE.DEBUG) { System.out.println(" setting reload for " + expr + " to " + flag); } reloads.put(expr, new Boolean(flag)); }
1
public Game() { // Set the instance variable instance = this; BoardSize = Options.getGameSize(); Player1 = Options.Player1; Player2 = Options.Player2; thisTurn = Player1; TimerRunning = false; ConsecutiveRun = 0; // Reset the scores and turns of each player Player1.newGame(); Player2.newGame(); // Update the labels on the GamePanel GamePanel.getThis().updateLabels(); Board = new CardButton[BoardSize][BoardSize]; LinkedList<CardButton> Pool = new LinkedList<CardButton>(); LinkedList<Integer> Considered = new LinkedList<Integer>(); // Every board should have two creepers :) Pool.add(new CardButton(Card.getByID(Card.CREEPER))); Pool.add(new CardButton(Card.getByID(Card.CREEPER))); Considered.add(Card.CREEPER); // If the board is big, add Herobrine ;) if (BoardSize > Options.toInt(GameSize.C6)) { Considered.add(Card.HEROBRINE); Pool.add(new CardButton(Card.getByID(Card.HEROBRINE))); // If the board is bigger, add another Herobrine ;) if (BoardSize == Options.toInt(GameSize.C8)) { Pool.add(new CardButton(Card.getByID(Card.HEROBRINE))); } } // Fill the rest of the pool randomly Random rand = new Random(); int randInt; while (Pool.size() < Math.pow(BoardSize, 2)) { // Randomized range of size-1 because this doesn't include Herobrine // Helps limit excess loops, even if just a little :) randInt = rand.nextInt(Card.Collection.size() - 1); if (!Considered.contains(randInt)) { Pool.add(new CardButton(Card.getByID(randInt))); Pool.add(new CardButton(Card.getByID(randInt))); Considered.add(randInt); } } // Shuffle the pool in shuffle(Pool); // Tell the GamePanel to update GamePanel.getThis().newGame(); // Play morning-time music :) Card.Clips.get("Start").play(); }
4
@Override public boolean equals(Object o) { if (o instanceof Peer) { Peer p = (Peer) o; if (p.peer_ip.equals(this.peer_ip) && p.port_number == this.port_number) { return true; } return false; } else if (o == this) { return true; } else { return false; } }
4
public void setPcaCantidad(Integer pcaCantidad) { this.pcaCantidad = pcaCantidad; }
0
public boolean getUse(String compType) { switch (compType) { case "Ext": return useExtension; case "Hash": return useHash; case "Name": return useName; case "Size": return useSize; case "Thorough": return useThorough; default: return false; } }
5
@Override public void executeMsg(final Environmental myHost, final CMMsg msg) { super.executeMsg(myHost,msg); if((affected!=null) &&(affected instanceof MOB) &&(msg.amISource((MOB)affected)||msg.amISource(((MOB)affected).amFollowing())||(msg.source()==invoker())) &&(msg.sourceMinor()==CMMsg.TYP_QUIT)) { unInvoke(); if(msg.source().playerStats()!=null) msg.source().playerStats().setLastUpdated(0); } }
7
static ChannelError fromSigError(int flag, int ctype, ByteBuffer data) { String message = ""; message = "Bad signal"; if (ctype == ContentType.UTF8 && data != null) { Charset charset = Charset.forName("UTF-8"); CharsetDecoder decoder = charset.newDecoder(); int pos = data.position(); try { message = decoder.decode(data).toString(); } catch (CharacterCodingException ex) { } finally { data.position(pos); } } return new ChannelError(message); }
3
public static void catalog(String contentRoot, String catalogFile) { //TODO add support for refreshing or adding to catalog // Try to open the output file before spending all that time doing // processing, in case the file path was wrong. ObjectOutputStream oos = null; try { FileOutputStream fos = new FileOutputStream(catalogFile); BufferedOutputStream bos = new BufferedOutputStream(fos, 4096*4); oos = new ObjectOutputStream(bos); } catch(IOException e) { System.out.println("Problem openning catalogFile: " + e); return; } ArrayList<File> allFiles = new ArrayList<File>(1024); //System.out.println("contentRoot: " + contentRoot); System.out.println("Cataloging list of PDFs..."); File contentRootFile = new File(contentRoot); if (contentRootFile.isDirectory()) { //System.out.println("Directory: " + contentRootFile); recursivelyCatalogPDFs(allFiles, contentRootFile); } else if (contentRootFile.isFile()) { //System.out.println("File: " + contentRootFile); addFileIfIsPDF(allFiles, contentRootFile); } allFiles.trimToSize(); System.out.println("Cataloged " + allFiles.size() + " PDF files"); try { oos.writeObject(allFiles); oos.flush(); oos.close(); } catch(IOException e) { System.out.println("Problem saving catalog of PDF files: " + e); } }
4
public double getDiffuseLayerPotential(){ if(!this.sternOption){ System.out.println("Class: GouyChapmanStern\nMethod: getDiffuseLayerPotential\nThe Stern modification was not included"); System.out.println("The value of the diffuse layer potential has been set equal to the surface potential"); return getSurfacePotential(); } if(this.psi0set && this.sigmaSet){ return this.diffPotential; } else{ if(this.sigmaSet){ this.getSurfacePotential(); return this.diffPotential; } else{ if(this.psi0set){ this.getSurfaceChargeDensity(); return this.diffPotential; } else{ System.out.println("Class: GouyChapmanStern\nMethod: getDiffuseLayerPotential\nThe value of the diffuse layer potential has not been calculated\nzero returned"); System.out.println("Neither a surface potential nor a surface charge density have been entered"); return 0.0D; } } } }
5
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("image/jpeg"); BufferedImage bi = new BufferedImage(300,203,BufferedImage.TYPE_INT_RGB); //int[] rgbarray={255,48,48}; //bi.setRGB(0, 0, 300, 203,rgbarray,0,0); Graphics g = bi.getGraphics(); numberobject=zufall(); switch(numberobject){ case 1: g.setColor(Color.yellow); g.fillOval(23, 39, 80, 69); break; case 2: g.setColor(Color.yellow); g.fillOval(90, 70, 40, 120); break; case 3: g.setColor(Color.green); g.fillRoundRect(40, 55, 70, 30, 40, 44); break; case 4: g.setColor(Color.orange); g.fillRect(70, 20, 130, 180); break; case 5: g.setColor(Color.yellow); g.fillArc(40, 30,50, 80, 33,55); break; case 6: g.setColor(Color.green); g.fillRect(130, 99, 80, 140); break; } OutputStream ous= response.getOutputStream(); g.dispose(); try{ ImageIO.write(bi,"jpeg",ous); } catch(Exception e){ System.out.println(e.getMessage()); } }
7
public static String trimTrailingCharacter(String str, char trailingCharacter) { if (!hasLength(str)) { return str; } StringBuilder sb = new StringBuilder(str); while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); }
3
public void setDestTermid(String[] destTermid) { DestTermid = destTermid; }
0
public void computeCellsToSolve() { int cells = 0; for (int i = 0; i < 9; i++) { for (int j = 0; j < 0; j++) { if (board[i][j].getValue() == 0) { cells++; } } } cellsToSolve = cells; }
3
public void setGraphPanel(GraphPanel graphPanel) { this.graphPanel = graphPanel; }
0
@Test public void bothPlayersPlaceButterflyAndContinueSeed5() throws HantoException { HantoGameManager.clearInstance(); HantoPlayer bluePlayer = new HantoPlayer(); HantoPlayer redPlayer = new HantoPlayer(); bluePlayer.RANDOM_SEED = 5; bluePlayer.startGame(HantoGameID.EPSILON_HANTO, HantoPlayerColor.BLUE, true); redPlayer.startGame(HantoGameID.EPSILON_HANTO, HantoPlayerColor.RED, false); HantoMoveRecord b = bluePlayer.makeMove(null); if (b.getFrom() != null){ assertEquals(true, redPlayer.getManager().getCellManager().isALegalMove((HantoPiece) HantoPieceFactory.makeHantoPiece(b.getPiece(), HantoPlayerColor.BLUE), (HantoCell) b.getFrom(), (HantoCell) b.getTo())); } HantoMoveRecord r = redPlayer.makeMove(b); if (b.getFrom() != null){ assertEquals(true, bluePlayer.getManager().getCellManager().isALegalMove((HantoPiece) HantoPieceFactory.makeHantoPiece(r.getPiece(), HantoPlayerColor.RED), (HantoCell) r.getFrom(), (HantoCell) r.getTo())); } b = bluePlayer.makeMove(r); if (b.getFrom() != null){ assertEquals(true, redPlayer.getManager().getCellManager().isALegalMove((HantoPiece) HantoPieceFactory.makeHantoPiece(b.getPiece(), HantoPlayerColor.BLUE), (HantoCell) b.getFrom(), (HantoCell) b.getTo())); } r = redPlayer.makeMove(b); if (b.getFrom() != null){ assertEquals(true, bluePlayer.getManager().getCellManager().isALegalMove((HantoPiece) HantoPieceFactory.makeHantoPiece(r.getPiece(), HantoPlayerColor.RED), (HantoCell) r.getFrom(), (HantoCell) r.getTo())); } b = bluePlayer.makeMove(r); if (b.getFrom() != null){ assertEquals(true, redPlayer.getManager().getCellManager().isALegalMove((HantoPiece) HantoPieceFactory.makeHantoPiece(b.getPiece(), HantoPlayerColor.BLUE), (HantoCell) b.getFrom(), (HantoCell) b.getTo())); } r = redPlayer.makeMove(b); if (b.getFrom() != null){ assertEquals(true, bluePlayer.getManager().getCellManager().isALegalMove((HantoPiece) HantoPieceFactory.makeHantoPiece(r.getPiece(), HantoPlayerColor.RED), (HantoCell) r.getFrom(), (HantoCell) r.getTo())); } b = bluePlayer.makeMove(r); if (b.getFrom() != null){ assertEquals(true, redPlayer.getManager().getCellManager().isALegalMove((HantoPiece) HantoPieceFactory.makeHantoPiece(b.getPiece(), HantoPlayerColor.BLUE), (HantoCell) b.getFrom(), (HantoCell) b.getTo())); } r = redPlayer.makeMove(b); if (b.getFrom() != null){ assertEquals(true, bluePlayer.getManager().getCellManager().isALegalMove((HantoPiece) HantoPieceFactory.makeHantoPiece(r.getPiece(), HantoPlayerColor.RED), (HantoCell) r.getFrom(), (HantoCell) r.getTo())); } b = bluePlayer.makeMove(r); if (b.getFrom() != null){ assertEquals(true, redPlayer.getManager().getCellManager().isALegalMove((HantoPiece) HantoPieceFactory.makeHantoPiece(b.getPiece(), HantoPlayerColor.BLUE), (HantoCell) b.getFrom(), (HantoCell) b.getTo())); } HantoMoveRecord randMove = null; List<HantoCell> possCells = new ArrayList<HantoCell>(); possCells.addAll(redPlayer.getManager().getCellManager().generatePossibleMoves()); randMove = redPlayer.placeRandomPiece(possCells); assertNotNull(randMove); assertNotNull(redPlayer.getGame()); assertNotNull(redPlayer.placeFailMoveCheck()); assertNotNull(redPlayer.getColor()); assertNotNull(redPlayer.getPlayer()); }
9
private static Set findFinal(Automaton a) { Set finalized = new HashSet(); finalized.addAll(Arrays.asList(a.getFinalStates())); boolean added = finalized.size() != 0; Transition[] t = a.getTransitions(); while (added) { added = false; for (int i = 0; i < t.length; i++) if (finalized.contains(t[i].getToState())) added = added || finalized.add(t[i].getFromState()); } return finalized; }
4
@Override public void solve(BlockMatrix64F B, BlockMatrix64F X) { if( B.blockLength != blockLength ) throw new IllegalArgumentException("Unexpected blocklength in B."); D1Submatrix64F L = new D1Submatrix64F(chol.getT(null)); if( X != null ) { if( X.blockLength != blockLength ) throw new IllegalArgumentException("Unexpected blocklength in X."); if( X.numRows != L.col1 ) throw new IllegalArgumentException("Not enough rows in X"); } if( B.numRows != L.col1 ) throw new IllegalArgumentException("Not enough rows in B"); // L * L^T*X = B // Solve for Y: L*Y = B BlockTriangularSolver.solve(blockLength,false,L,new D1Submatrix64F(B),false); // L^T * X = Y BlockTriangularSolver.solve(blockLength,false,L,new D1Submatrix64F(B),true); if( X != null ) { // copy the solution from B into X BlockMatrixOps.extractAligned(B,X); } }
6
private final void isaac() { int i, x, y; b += ++c; for (i = 0; i < SIZE; ++i) { x = mem[i]; switch (i & 3) { case 0: a ^= a << 13; break; case 1: a ^= a >>> 6; break; case 2: a ^= a << 2; break; case 3: a ^= a >>> 16; break; } a += mem[i + SIZE / 2 & SIZE - 1]; mem[i] = y = mem[(x & MASK) >> 2] + a + b; rsl[i] = b = mem[(y >> SIZEL & MASK) >> 2] + x; } }
5
private boolean generateSaveLocals(Node node) { int count = 0; for (int i = 0; i < firstFreeLocal; i++) { if (locals[i] != 0) count++; } if (count == 0) { ((FunctionNode)scriptOrFn).addLiveLocals(node, null); return false; } // calculate the max locals maxLocals = maxLocals > count ? maxLocals : count; // create a locals list int[] ls = new int[count]; int s = 0; for (int i = 0; i < firstFreeLocal; i++) { if (locals[i] != 0) { ls[s] = i; s++; } } // save the locals ((FunctionNode)scriptOrFn).addLiveLocals(node, ls); // save locals generateGetGeneratorLocalsState(); for (int i = 0; i < count; i++) { cfw.add(ByteCode.DUP); cfw.addLoadConstant(i); cfw.addALoad(ls[i]); cfw.add(ByteCode.AASTORE); } // pop the array off the stack cfw.add(ByteCode.POP); return true; }
7
@Override public int getCurrentFrame() { assert !isGameOver(); int currentFrame = 1; for (int i = 0; i < rollCount; i++) { int pinsKnockedDown = pinsKnockedDownArray[i]; if (currentFrame == 10) { return 10; } if (pinsKnockedDown == 10) { currentFrame++; } else if (pinsKnockedDown > 0) { int j = i + 1; if (j < rollCount) { currentFrame++; i++; } } } return currentFrame; }
5
@Override public void onAddParent( GameObject parent ) { super.onAddParent( parent ); if ( triangles != null ) { for ( Triangle triangle : triangles ) parent.addComponent( triangle ); } }
2
public int ingresarPreguntaTema(Pregunta_Tema p) { try { if (con.isClosed()) { con = bd.conexion(); } String consulta; if (p.getRespuesta() != 0) { consulta = "INSERT INTO Pregunta_Tema VALUES('" + p.getTema().getCodigo() + "','" + p.getPregunta().getCodigo() + "','" + p.getRespuesta() + "','" + p.getNroPregunta() + "','" + p.getCombinacion().getCodigo() + "')"; } else { consulta = "INSERT INTO Pregunta_Tema (f_tema, f_pregunta, nroPregunta, combinacionOpcion_idcombinacion) VALUES('" + p.getTema().getCodigo() + "','" + p.getPregunta().getCodigo() + "','" + p.getNroPregunta() + "','" + p.getCombinacion().getCodigo() + "')"; } Statement sta = con.createStatement(); int rs = sta.executeUpdate(consulta); //con.close(); if (rs == 1 || rs == 4) { return 1; } else { return 0; } } catch (Exception ex) { System.out.println("Problemas creando preguntaTema!. Error: " + ex); } finally { if (con != null) { try { con.close(); } catch (SQLException ignore) { } } } return 0; }
7
static String nameHand(int rank) { String name; switch (rank) { case 9: name = "Strait Flush"; break; case 8: name = "Four of a Kind"; break; case 7: name = "Full House"; break; case 6: name = "Flush"; break; case 5: name = "Strait"; break; case 4: name = "Three of a Kind"; break; case 3: name = "Two Pair"; break; case 2: name = "One Pair"; break; default: name = "High Card"; break; } return name; }
8
public final static boolean finish() throws FatalError { try { // HTTP parameters stores header etc. HttpParams params = new BasicHttpParams(); params.setParameter("http.protocol.handle-redirects", false); HttpGet httpget = new HttpGet(Config.getHost() + "arbeitsamt/index"); httpget.setParams(params); HttpResponse response = Control.current.httpclient.execute(httpget); // obtain redirect target Header locationHeader = response.getFirstHeader("location"); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { resEntity.consumeContent(); } if (locationHeader != null) { if (locationHeader.getValue().equalsIgnoreCase( (Config.getHost() + "arbeitsamt/serve").toLowerCase())) { try { JSONTokener js = new JSONTokener(Utils .getString("services/serviceData")); JSONObject result = new JSONObject(js); // [truncated] // {"currentTime":43,"fullTime":3600,"urlCancel":"\/arbeitsamt\/cancel","urlFinish":"\/arbeitsamt\/finish","workTotalTime":"1","workFee":"112","workFeeType":"gold","workText":"Die // Kellnerin im Goldenen Igel kommt nach einem langen int seconds = result.getInt("fullTime") - result.getInt("currentTime") + 20; Output.printTabLn( "Letzte Arbeit wurde nicht beendet. Schlafe " + Math.round(seconds / 60) + " Minuten.", 1); // cut it into parts to safe session while (seconds > 600) { // sleep for 10 min Control.sleep(6000, 2); seconds -= 600; Control.current.getCharacter(); } Control.sleep(10 * seconds, 2); Utils.visit("arbeitsamt/finish"); } catch (JSONException e) { Output.error(e); return false; } } else if (locationHeader.getValue().equalsIgnoreCase( (Config.getHost() + "arbeitsamt/finish").toLowerCase())) { Utils.visit("arbeitsamt/finish"); } else { Output.println("Es ging was schief.", 0); return false; } } } catch (IOException e) { Output.println("Es ging was schief.", 0); return false; } return true; }
7
public void run() { if(duration != -1) { Robot.getInstance().getMotion().getPilot().backward(); Delay.msDelay(duration); if(!getInterrupted()) { Robot.getInstance().getMotion().getPilot().stop(); Robot.getInstance().getMotion().setRunnableRobot(null); Robot.getInstance().warn(new Event(TypeEvent.GOBACKWARD_END)); } else { Robot.getInstance().warn(new Event(TypeEvent.INTERRUPTED, TypeEvent.GOBACKWARD_END.toString())); } } else { Robot.getInstance().getMotion().getPilot().travel(-distance, true); while(Robot.getInstance().getMotion().getPilot().isMoving()) { if(!getInterrupted()) { Thread.yield(); } else break; } if(!getInterrupted()) { Robot.getInstance().getMotion().setRunnableRobot(null); if(!neg) { Robot.getInstance().warn(new Event(TypeEvent.GOBACKWARD_END)); } else { Robot.getInstance().warn(new Event(TypeEvent.GOFORWARD_END)); } } else { if(!neg) Robot.getInstance().warn(new Event(TypeEvent.INTERRUPTED, TypeEvent.GOBACKWARD_END.toString())); else Robot.getInstance().warn(new Event(TypeEvent.INTERRUPTED, TypeEvent.GOFORWARD_END.toString())); } } }
7
public void compExecTime() { double newExeTime; double newCost; dEval = 0; dTime = 0; dCost = 0; for (int i = 0; i < iClass; i++) { newExeTime = 0; // System.out.print("Cost[" + i + "]"); for (int j = 0; j < iSite; j++) { if (dmAlloc[i][j] != -1) { if (dmAlloc[i][j] < 1) { newExeTime = 0; } else { newExeTime = (dmDist[i][j] * dmPrediction[i][j]) / dmAlloc[i][j]; if (newExeTime > dDeadline + 1) { newExeTime = Double.MAX_VALUE; } } } if (newExeTime > dDeadline + 1) { // System.out.println("newExeTime - dDeadline="+ (newExeTime // - dDeadline -1)); newCost = Double.MAX_VALUE; } else { newCost = dmDist[i][j] * dmPrediction[i][j] * daPrice[j]; } dTime += newExeTime; dCost += newCost; dEval += dmCost[i][j] - dCost; dmExeTime[i][j] = newExeTime; dmCost[i][j] = newCost; // System.out.print(dmCost[i][j] + ", "); } // System.out.println(); } for (int i = 0; i < iClass; i++) { System.out.print("Time[" + i + "]"); for (int j = 0; j < iSite; j++) { System.out.print(dmExeTime[i][j] + ", "); } System.out.println(); } // System.out.println("AllTime = " + dTime + " AllCost = " + dCost); // System.out.println(); }
8
public MapObjectType getObjectType(int positionX, int positionY){ if(mapObjectGrid[positionX][positionY] != null) return MapObjectType.Object; if(characterGrid[positionX][positionY] != null) return MapObjectType.Character; return MapObjectType.Null; }
2
public static double averageAltitudes(int[] altiList) { int sum = 0; for (int i = 0; i < altiList.length; i++) { /*Check to see if all spots in array are full in order to average*/ if (altiList[i] == ' ') { System.out.println("Some spots in the array are blank\n Can not calculate average"); } /*Check to see if any of the numbers in the array are negative*/ if (altiList[i] < 0) { System.out.println("Some of the numbers are negative\n Can not calculate average"); } sum = sum + altiList[i]; } double average = sum / altiList.length; return average; }
3
@Override public boolean hasNext() { if (reader == null) return false; // No input stream? if (next == null) { next = readNext(); // Try reading next item. if ((next == null) && autoClose) close(); // End of file or any problem? => Close file } return (next != null); }
4
static void draw_sprites(osd_bitmap bitmap, int priority) { int offs, sx, sy; for (offs = 4096 - 32; offs >= 0; offs -= 32) { int code; int attr = stfight_sprite_ram.read(offs + 1); int flipx = (((attr & 0x10) != 0 ? 1 : 0) ^ stfight_flipscreen); int flipy = (stfight_flipscreen); int color = attr & 0x0f; int pri = (attr & 0x20) >> 5; if (pri != priority) { continue; } sy = stfight_sprite_ram.read(offs + 2); sx = stfight_sprite_ram.read(offs + 3); // non-active sprites have zero y coordinate value if (sy > 0) { // sprites which wrap onto/off the screen have // a sign extension bit in the sprite attribute if (sx >= 0xf0) { if ((((attr & 0x80) != 0 ? 1 : 0) ^ stfight_flipscreen) != 0) { sx -= 0x100; } } if (stfight_flipscreen != 0) { sy = 256 - 16 - sy; sx = 256 - 16 - sx; } code = stfight_sprite_base + stfight_sprite_ram.read(offs); drawgfx(bitmap, Machine.gfx[4], code, color, flipx, flipy, sx, sy, Machine.drv.visible_area, TRANSPARENCY_PEN, 0x0f); } } }
8
private final void removeChannel(String channel) { channel = channel.toLowerCase(); synchronized (_channels) { _channels.remove(channel); } }
0