text
stringlengths
14
410k
label
int32
0
9
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { int type; if (commandLabel.equalsIgnoreCase("unban")) { if (sender.hasPermission(SeruBans.UNBANPERM) || sender.isOp() || (!(sender instanceof Player))) { if (args.length == 0) { return false; } else if (args.length > 1) { return false; } else { String BannedVictim = args[0]; plugin.log.info("Attempting to unban " + BannedVictim); if (HashMaps.keyIsInBannedPlayers(BannedVictim .toLowerCase())) { int bId = HashMaps.getBannedPlayers(BannedVictim .toLowerCase()); if (HashMaps.keyIsInTempBannedTime(bId)) { type = SeruBans.UNTEMPBAN; HashMaps.removeTempBannedTimeItem(bId); } else { type = SeruBans.UNBAN; } MySqlDatabase.updateBan(type, bId); HashMaps.removeBannedPlayerItem(BannedVictim .toLowerCase()); SeruBans.printServer(ChatColor.YELLOW + BannedVictim + ChatColor.GOLD + " was unbanned!"); plugin.log.info(BannedVictim + " was unbanned by " + sender.getName()); return true; } else { sender.sendMessage(ChatColor.RED + "This player is not banned!"); return true; } } } else { sender.sendMessage(ChatColor.RED + "You do not have permission!"); } } return false; }
8
@Override public boolean activate() { return (Inventory.isFull() && !Widgets.get(13, 0).isOnScreen() && !Constants.ESCAPE_AREA.contains(Players.getLocal()) && (Constants.VARROCK_WEST_BANK_AREA.contains(Players.getLocal()) || Constants.VARROCK_EAST_BANK_AREA.contains(Players.getLocal()))); }
4
private IRubyObject log(Level level, ThreadContext ctx, IRubyObject[] args, Block block) { IRubyObject nil = ctx.getRuntime().getNil(); IRubyObject message = args.length == 1 ? args[0] : null; if (block.isGiven()) { if (isSufficientLevel(level)) { message = block.yield(ctx, nil); } } if (message != null) { if (!(message instanceof RubyString)) { message = message.inspect(); } String messageString = message.asString().decodeString(); switch (level) { case DEBUG: logger.debug(messageString); break; case INFO: logger.info(messageString); break; case WARN: logger.warn(messageString); break; case ERROR: logger.error(messageString); break; } } return nil; }
9
public LibraryBean[] searchInBooleanMode(String query){ LinkedList<LibraryBean> list = new LinkedList<>(); try { PreparedStatement statement = connection.prepareStatement(SEARCH_IN_BOOLEAN_MODE); statement.setString(1, query); statement.setString(2, query); ResultSet resultSet = statement.executeQuery(); LinkedList<Integer> listOfId = new LinkedList<>(); while(resultSet.next() == true){ Integer idLibrary = Integer.parseInt(resultSet.getString("idlibrary")); listOfId.add(idLibrary); } LibraryDAO libraryDAO = new LibraryDAO(connection); for (Integer current : listOfId) { list.add(libraryDAO.getLibrary(current)); } } catch (SQLException e) { e.printStackTrace(); return null; } LibraryBean[] result = new LibraryBean[list.size()]; return list.toArray(result); }
3
@Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { rightPressed = true; } if (e.getKeyCode() == KeyEvent.VK_N) { nPressed = true; } if (e.getKeyCode() == KeyEvent.VK_P) { pPressed = true; } }
4
public static String GetTimeString() { SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss"); return sdf.format(new Date()); }
0
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final RequisicaoModel other = (RequisicaoModel) obj; if (!Objects.equals(this.pmProjeto, other.pmProjeto)) { return false; } if (!Objects.equals(this.strDescricao, other.strDescricao)) { return false; } if (!Objects.equals(this.strTipoRequisicao, other.strTipoRequisicao)) { return false; } return true; }
5
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; }
4
protected Field[] getFields(Object obj) { ArrayList<Field> allFields = new ArrayList<Field>(); ArrayList<Class<?>> classTower = this.getClasses(obj); // Printout to observe the shown packages //if(logger.isDebugEnabled()) // logger.debug("Object " + obj.toString() + "has " + // classTower.size() + " classes in its package hierarchy"); // System.out.println("Object " + obj.toString() + "has " + // classTower.size() + " classes in its package hierarchy."); // for (ArrayList<Class> c: classTower){ for (Class<?> cl : classTower) { Field[] fields = cl.getDeclaredFields(); for (Field f : fields) { // permit access to the protected and private field values ensureIsAccessible(f); int modif = f.getModifiers(); if ( (!(Modifier.isStatic(modif))) && (!(Modifier.isVolatile(modif))) && (!(Modifier.isTransient(modif))) && ((f.getDeclaringClass().equals(cl))) ){ /* if(logger.isDebugEnabled()) System.out.println("Field " + f.getName() + " in the class " + f.getDeclaringClass() + " added for class " + cl.getName()); */ // System.out.println("Field " + f.getName() + // " in the class " + // f.getDeclaringClass() + " added for class " + // cl.getName()); allFields.add(f); } } } // System.out.println("Object " + obj + "has " + // allFields.size() + " fields."); Field[] allFieldsArray = new Field[allFields.size()]; return allFields.toArray(allFieldsArray); }
8
private int maxMove(Board prev, int depth, int alpha, int beta) { moves++; if(depth >= maxDepth) return prev.getScore(); // exceeded maximum depth int maxScore = MIN_SCORE; Board b = new Board(prev); for(int j = 0; j < size; j++) { for(int i = 0; i < size; i++) { if(b.move(i, j)) // try move { int score = minMove(b, depth + 1, alpha, beta); //printMsg(true, depth, score, i, j); // fixme if(score > maxScore) maxScore = score; if(maxScore >= beta) { /*System.out.println("beta pruned");*/ return maxScore; } if(maxScore > alpha) alpha = maxScore; b = new Board(prev); } } } if(maxScore == MIN_SCORE) // no moves found { b.turn(); if(b.canMove()) { b.turn(); return minMove(b, depth + 1, alpha, beta); } else return prev.getScore(); } return maxScore; }
9
public void mouseClicked(MouseEvent e) { if (isDrawing && e.getButton() == MouseEvent.BUTTON3){ Polygon p = generatePolygon(); polygons.add(p); polygonsWithColors.put(p, color); polygonLineCreate(); } Set<Map.Entry<String, Boolean>> visibleSet = visible.entrySet(); for(Map.Entry m: visibleSet) { if ((Boolean)m.getValue()) { Location loc = points.get(m.getKey()); if (covers(loc, lastX, lastY)) { isDrawing = false; if (loc instanceof BusStop) busStopList.setSelectedItem(m.getKey()); else if (loc instanceof PointOfInterest) { JOptionPane.showMessageDialog(MapApp.this, ((PointOfInterest)loc).getDescription()); } } else{ isDrawing = true; } } } }
7
@Override public void exec(String channel, String sender, String commandName, String[] args, String login, String hostname, String message) { String fmlMessage = ""; try { URL url = new URL("http://rscript.org/lookup.php?type=fml"); BufferedReader bReader = new BufferedReader(new InputStreamReader(url.openStream())); while ((fmlMessage = bReader.readLine()) != null) { if (fmlMessage.startsWith("TEXT: ")) { fmlMessage = fmlMessage.replace("TEXT: ", ""); break; } } } catch (IOException ex) { if (ex.getMessage().contains("503")) { this.bot.sendMessage(channel, "Error: 503"); } if (ex.getMessage().contains("404")) { this.bot.sendMessage(channel, "Error: 503"); } } this.bot.sendMessage(channel, "[FML] " + fmlMessage); }
5
public Properties getProperties() { if (properties == null) { InputStream stream = TestSettings.class.getResourceAsStream("/usecases.properties"); try { properties = new Properties(); properties.load(stream); } catch (IOException e) { throw new RuntimeException("Fail to read properties", e); } finally { IOUtils.closeQuietly(stream); } } return properties; }
2
public String getFullName() { return fullNameText.getText(); }
0
public void filter(final String search) { RowFilter<TableModel, Object> rf = new RowFilter<TableModel, Object>() { @Override public boolean include(RowFilter.Entry<? extends TableModel, ? extends Object> entry) { final MediaElement elt = (MediaElement) entry.getModel().getValueAt((Integer) entry.getIdentifier(), 0); return elt.getVisible() && (search.equals("") || elt.getName().toLowerCase().contains(search.toLowerCase())); } }; ((TableRowSorter<TableModel>) table.getRowSorter()).setRowFilter(rf); }
4
public String toString() { PrintfFormat fmt = new PrintfFormat(cellFormat); StringBuffer buf = new StringBuffer(); // line 1 - a ruler buf.append(" "); buf.append(" "); for (int i=1; i<=s.length(); i++) buf.append(fmt.sprintf((double)i)); buf.append("\n"); // line 2 - the string buf.append(" "); buf.append(" "); for (int i=1; i<=s.length(); i++) buf.append(" "+trapNewline(sAt(i))+" "); buf.append("\n"); // line 2 - an hrule buf.append(" "); buf.append(" "); for (int i=1; i<=s.length(); i++) buf.append("---"); buf.append("\n"); // remaining lines for (int j=1; j<=t.length(); j++) { buf.append(fmt.sprintf((double)j)); buf.append(" "+trapNewline(tAt(j))+"|"); for (int i=1; i<=s.length(); i++) { if (!nearDiagonal(offsetFromDiagonal(i,j)) || defaultValue==get(i,j)) { buf.append(" * "); } else { double v = printNegativeValues ? -get(i,j) : get(i,j); buf.append(fmt.sprintf(v)); } } buf.append("\n"); } return buf.toString(); }
8
private String getEditorHtml(WikiContext context, String name) throws IOException { String template = null; try { // NOTE: There is CSS in this template. Keep it in sync with the add_header.css file. // // IMPORTANT: Only multipart/form-data encoding works in plugins. // IMPORTANT: Must be multipart/form-data even for standalone because // the Freenet ContentFilter rewrites the encoding in all forms // to this value. template = IOUtil.readUtf8StringAndClose(SettingConfig.class.getResourceAsStream("/edit_form.html")); } catch (IOException ioe) { return "Couldn't load edit_form.html template from jar???"; } String escapedName = escapeHTML(unescapedTitleFromName(name)); String href = makeHref(context.makeLink("/" +name), "save", null, null, null, null); String wikiText = "Page doesn't exist in the wiki yet."; if (context.getStorage().hasPage(name)) { wikiText = context.getStorage().getPage(name); } String parentWikiText = null; if (context.getStorage().hasUnmodifiedPage(name)) { parentWikiText = context.getStorage().getUnmodifiedPage(name); } String rebaseWikiText = null; if (context.getRemoteChanges().hasChange(name) && !context.getRemoteChanges().wasDeleted(name)) { rebaseWikiText = context.getRemoteChanges().getPage(name); } // Escaping should be OK. String diffsFromParentToLocal = getDiffHtml(parentWikiText, wikiText); String diffsFromParentToRebase = getDiffHtml(parentWikiText, rebaseWikiText); parentWikiText = nullToNone(parentWikiText); rebaseWikiText = nullToNone(rebaseWikiText); return String.format(template, escapedName, escapedName, href, escapeHTML(name), // i.e. with '_' chars escapeHTML(wikiText), // IMPORTANT: Required by Freenet Plugin. // Doesn't need escaping. context.getString("form_password", "FORM_PASSWORD_NOT_SET"), diffsFromParentToLocal, diffsFromParentToRebase, escapeHTML(parentWikiText), escapeHTML(rebaseWikiText)); }
5
public Item SwapHeadArmor(Item willBeSwappedItem) { return headArmorSlot.swap(willBeSwappedItem); //return false;// swap failed }
0
private boolean isHeader(Element el) { if(el == null) return false; return el.tagName().equals("h2") || el.tagName().equals("h3") || el.tagName().equals("h4"); }
3
public void listarPesqGerente() { UsuarioBO Gerente = new UsuarioBO(); try { tbResultadoBusca.setModel(DbUtils.resultSetToTableModel(Gerente.pesquisaGerente(txtCampoBuscaGerente.getText()))); } catch (SQLException ex) { } }
1
private static int stringSize(long num, int radix) { int exp; if (radix < 4) { exp = 1; } else if (radix < 8) { exp = 2; } else if (radix < 16) { exp = 3; } else if (radix < 32) { exp = 4; } else { exp = 5; } int size=0; do { num >>>= exp; size++; } while(num != 0); return size; }
5
public int compareMove(Move otherMove) { if(this.equals(otherMove)) { return 0; } else { switch (this) { case ROCK: return (otherMove == SCISSORS ? 1 : -1); case PAPER: return (otherMove == ROCK ? 1 : -1); case SCISSORS: return (otherMove == PAPER ? 1 : -1); } } return 0; }
7
public static int[] fillRandomInt(int length, int min, int max, int count) { int[] array = new int[length]; for (int i = 0; i < array.length; i++) { array[i] = (int) random(min, max, count); } return array; }
1
public boolean editEvidence(Evidence e) { Element evidenceE; Evidence evidence; boolean flag = false; for (Iterator i = root.elementIterator("evidence"); i.hasNext();) { evidenceE = (Element)i.next(); if (evidenceE.element("id").getText().equals(e.getId())) { evidenceE.element("title").setText(e.getTitle()); evidenceE.element("description").setText(e.getTitle()); // Write to xml try { XmlUtils.write2Xml(fileName, document); return true; } catch (IOException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } flag = true; break; } } return flag; }
3
public static void main(String[] args){ while(!Plateau.boucleJeu){ // Tant que le jeu n'est pas fini Mot m=new Mot(); Fenetre f=new Fenetre(); Chrono c=f.getChrono(); Plateau p=f.getPlateau(); int essais=0; m.init(f); while(!Plateau.boucleMots){ // Tant que le mot n'est pas trouve int iChrono=0; while(iChrono<125 && essais!=7){ // On fait... c.wait8ms(); // ... 8*125ms = 1 sec if(MyKey.go){ // Si l'utilisateur appuie sur entree essais++; p.update(f, m); f.testFin(essais); } iChrono++; } f.setDisplay(false); if(essais!=7){ c.updateChrono(); // Mise a jour du chrono f.repaint(); } } } }
6
private boolean add(ADD request){ if(request.username.matches("^.*[^a-zA-Z0-9 ].*$")) return false; byte[] salt = new byte[AuthServer.saltLength]; new SecureRandom().nextBytes(salt); String query_create = "INSERT INTO User values('" + request.username + "','" + request.name + "', 0x" + Misc.getHexBytes(Hash.getStretchedSHA256(request.userPW, salt, AuthServer.stretchLength), "") + ", 0x" + Misc.getHexBytes(salt, "") + ");"; String query_history = "INSERT INTO History(length, lastLoginIndex, userName) values(" + "6"/*<<history length*/ + ", 0, '" + request.username + "');"; try { if(connection == null) connect(); connection.setAutoCommit(false); Statement stmt_create = connection.createStatement(); Statement stmt_history = connection.createStatement(); //System.out.println(query_create + "\n" +query_history); stmt_create.executeUpdate(query_create); stmt_history.executeUpdate(query_history); if(!makeAdmin(request.adminName, request.username)) throw new SQLException(); connection.commit(); recordLogin(request.origin, request.username); } catch (SQLException e) { e.printStackTrace(); if(connection != null){ try { connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } return false; }finally{ try { if(connection != null) connection.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } return true; // "INSERT INTO User values(" + userName + "," + name + // ", 0x" + Misc.getHexBytes(stretchedPassword, "") + // ", 0x" + Misc.getHexBytes(salt, "") + ");" // "INSERT INTO History(length, lastLoginIndex, userName) values(" + // historyLength + ", 0, " + userName + ");" }
8
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed String userName = txtFieldUserName.getText(); char[] pw = txtFieldPassword.getPassword(); String password = new String(pw); String errorMessage = ""; if(userName.isEmpty()){ errorMessage = "* Please enter a username <br>"; } if((user == null) && (password.isEmpty())){ errorMessage += "* Please enter a password <br>"; } userName.trim(); password.trim(); if ("".equals(errorMessage)) { if (user == null) { User u = new User(); u.setUsername(userName); u.setPassword(password, true); u.setRank((Rank) cmbBoxType.getSelectedItem()); if (Controller.Instance().save(u)) { JOptionPane.showMessageDialog(this, "User \"" + u.getUsername() + "\" saved"); this.dispose(); } else { lblError.setText("* UserName already exsists"); } } else { user.setUsername(userName); if(!password.isEmpty()){ user.setPassword(password, true); } user.setRank((Rank) cmbBoxType.getSelectedItem()); if (Controller.Instance().update(user)) { JOptionPane.showMessageDialog(this, "User \"" + user.getUsername() + "\" saved"); this.dispose(); } else { lblError.setText("* Change User failed username already exsists"); } } } else { lblError.setText("<html> "+ errorMessage + " </html>"); } }//GEN-LAST:event_btnSaveActionPerformed
8
@Override public Point getDirection() { return direction; }
0
private void removeHelper(RedBlackNode<T> toRemove) { if (toRemove.isLeaf()) { if (toRemove.getColor() == Color.RED) { //removing a red leaf is never a problem delete(toRemove); } else { //it is a black leaf if (toRemove == root) { //there is only one node in the whole tree root = null; } else { // we are removing a black leaf, this is the hard case fixBlackLeaf(toRemove); delete(toRemove); } } } else if (toRemove.getRight() != null && toRemove.getLeft() != null) { //the node is not a leaf so we swap it's data with it's predecessor and remove that one (always a leaf) RedBlackNode<T> predecessor = findPredecessor(toRemove); assert(predecessor != null); toRemove.setData(predecessor.getData()); removeHelper(predecessor); } else if (toRemove.getLeft() != null) { //right branch is empty, left is not assert (toRemove.getColor() == Color.BLACK); assert (toRemove.getLeft().getColor() == Color.RED); toRemove.getLeft().setColor(Color.BLACK); replaceNode(toRemove, toRemove.getLeft()); delete(toRemove); } else if (toRemove.getRight() != null) { //left branch is empty, right is not assert (toRemove.getColor() == Color.BLACK); assert (toRemove.getRight().getColor() == Color.RED); toRemove.getRight().setColor(Color.BLACK); replaceNode(toRemove, toRemove.getRight()); delete(toRemove); } }
7
public void createGoodsMenu(final GoodsLabel goodsLabel) { final Goods goods = goodsLabel.getGoods(); final InGameController inGameController = freeColClient.getInGameController(); ImageLibrary imageLibrary = parentPanel.getLibrary(); this.setLabel("Cargo"); JMenuItem name = new JMenuItem(Messages.message(goods.getNameKey()) + " (" + Messages.message("menuBar.colopedia") + ")", imageLibrary.getScaledGoodsImageIcon(goods.getType(), 0.66f)); name.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { gui.showColopediaPanel(goods.getType().getId()); } }); this.add(name); if (!(goods.getLocation() instanceof Colony)) { if (freeColClient.getMyPlayer().canTrade(goods)) { JMenuItem unload = new JMenuItem(Messages.message("unload")); unload.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { inGameController.unloadCargo(goods, false); if (parentPanel instanceof CargoPanel) { CargoPanel cargoPanel = (CargoPanel) parentPanel; cargoPanel.initialize(); /* if (cargoPanel.getParentPanel() instanceof ColonyPanel) { ((ColonyPanel) cargoPanel.getParentPanel()).updateWarehouse(); } */ } parentPanel.revalidate(); } }); this.add(unload); } else { if (goods.getLocation() instanceof Unit && ((Unit)goods.getLocation()).isInEurope()) { JMenuItem pay = new JMenuItem(Messages.message("boycottedGoods.payArrears")); pay.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { inGameController.payArrears(goods.getType()); if (parentPanel instanceof CargoPanel) { CargoPanel cargoPanel = (CargoPanel) parentPanel; cargoPanel.initialize(); } parentPanel.revalidate(); } }); this.add(pay); } } JMenuItem dump = new JMenuItem(Messages.message("dumpCargo")); dump.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { inGameController.unloadCargo(goods, true); if (parentPanel instanceof CargoPanel) { ((CargoPanel) parentPanel).initialize(); } parentPanel.revalidate(); } }); this.add(dump); } }
7
public ArrayList<Entity> getSolidProps(Entity entity) { if(noChildren()) { ArrayList<Entity> tempProps = new ArrayList<Entity>(); for(int x = 0; x<props.size(); x++) { if(props.get(x).isSolid()) { tempProps.add(props.get(x)); } } return tempProps; //return props; } else { ArrayList<Entity> tempProps = new ArrayList<Entity>(); for(int x = 0; x<propChildren.length; x++) { if(propChildren[x].props.contains(entity)) { tempProps.addAll(propChildren[x].getSolidProps(entity)); } } return tempProps; } }
5
public static <E extends Enum<?>> E caseInsensitiveValueOf(E[] enumValues, String constant) { for (E candidate : enumValues) { if(candidate.toString().equalsIgnoreCase(constant)) { return candidate; } } throw new IllegalArgumentException( String.format("constant [%s] does not exist in enum type %s", constant, enumValues.getClass().getComponentType().getName())); }
3
public static Rule_LF parse(ParserContext context) { context.push("LF"); boolean parsed = true; int s0 = context.index; ArrayList<Rule> e0 = new ArrayList<Rule>(); Rule rule; parsed = false; if (!parsed) { { ArrayList<Rule> e1 = new ArrayList<Rule>(); int s1 = context.index; parsed = true; if (parsed) { boolean f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Terminal_NumericValue.parse(context, "%x0a", "[\\x0a]", 1); if ((f1 = rule != null)) { e1.add(rule); c1++; } } parsed = c1 == 1; } if (parsed) e0.addAll(e1); else context.index = s1; } } rule = null; if (parsed) rule = new Rule_LF(context.text.substring(s0, context.index), e0); else context.index = s0; context.pop("LF", parsed); return (Rule_LF)rule; }
7
@Override public void mouseReleased(MouseEvent mouse) { Tool tool = controls.getTool(); if (selectedMessage != null) { selectedMessage.selected = 0; selectedMessage = null; noClick = true; } if (tool.compatible(ToolType.create) && tool.compatible(ToolTarget.edge) && graph.player.state == RunState.stopped) { graph.createEdge(begin, graph.getVertex(mouseGetX(mouse), mouseGetY(mouse))); } begin = null; xlast = 0; ylast = 0; GUI.gRepaint(); }
4
private boolean checkIfTargetNearby() { try { if (getRatSurrounding().get(Direction.NORTH).isTarget()) { dir = Direction.NORTH; goForward(); return true; } else if (getRatSurrounding().get(Direction.EAST).isTarget()) { dir = Direction.EAST; goForward(); return true; } else if (getRatSurrounding().get(Direction.SOUTH).isTarget()) { dir = Direction.SOUTH; goForward(); return true; } else if (getRatSurrounding().get(Direction.WEST).isTarget()) { dir = Direction.WEST; goForward(); return true; } } catch (NullPointerException e) { //Shit happens, on start or target field or maze border not there } return false; }
5
private void reply_if_isACK(Packet packet) { TransportLayer tl = packet.getTransport(); if (tl instanceof TCP) { TCP transport = (TCP) tl; if (transport.isACK()) { Packet ack_packet = new Packet("TCP"); ack_packet.setIP_source(this.computer_ip); ack_packet.setIP_destination(packet.getIP_source()); TCP ack_transport = new TCP(transport.getDestination_port(), transport.getSource_port()); //determina o offset numa transferência de arquivos int next_offset = transport.getACK_number(); if (next_offset > 1) { next_offset = transport.getSequence_number() + 1460; this.data_offset = next_offset; } ack_transport.setSequence_number(transport.getACK_number()); ack_transport.setACK_number(next_offset); if (transport.isFIN()) ack_transport.setFIN(true); ack_packet.setTransport(ack_transport); send_packet(ack_packet); } } }
4
public GUICanvas() { super(); addMouseListener(this); }
0
private Map<String, String> loadChecksums(File file, int algorithm) { Map<String, String> checksums = new HashMap<String,String>(); if ( file.exists() ) { try { FileInputStream fis = new FileInputStream(file.getAbsolutePath()); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fis); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { String tokens[] = strLine.split(" "); String filename = tokens[0]; String checksum = null; switch ( algorithm ) { case Constants.CHECKSUM_ALG_MD_2: break; case Constants.CHECKSUM_ALG_MD_5: checksum = tokens[2];break; case Constants.CHECKSUM_ALG_SHA_1: break; case Constants.CHECKSUM_ALG_SHA_256: checksum = tokens[1]; break; case Constants.CHECKSUM_ALG_SHA_384: break; case Constants.CHECKSUM_ALG_SHA_512: break; default: throw new IllegalArgumentException("Invalid checksum algorithm specified ( " + algorithm + " )"); } checksums.put(filename, checksum); } } catch ( Exception ex ) { ex.printStackTrace(); } } else { return null; } return checksums; }
9
private void advance() { next = null; if(rs!=null) { try { int n = colNames.length; final Map<String,Object> mp = new LinkedHashMap<String,Object>(); for(int i=0;i<n;++i) { Object field = null; try { field = colInfos[i].extracter.getField(rs,i); } catch (Exception ex) { } if(null==field) { // belt and suspenders version field = SQLTypeAdapter.stringExtracter.getField(rs,i); } mp.put(colNames[i],field); } next = new BurstMap("db",mp); if(!rs.next()) { rs = null; } } catch (SQLException ex) { if(rs!=null) { try { rs.close(); } catch (SQLException cx) { } } rs = null; next = null; throw new RuntimeException(ex); } } }
8
static final void method1919(int i, float f, byte[] is, float f_0_, int i_1_, float f_2_, Class186 class186, float f_3_, int i_4_, byte i_5_, int i_6_, float f_7_, int i_8_) { try { int i_9_ = 0; if (i_5_ < 11) method1919(97, -1.4756906F, null, 0.7518226F, 93, -0.33127537F, null, -0.6670833F, 25, (byte) -96, 123, -1.8054857F, 43); for (/**/; i_9_ < i_6_; i_9_++) { Player.method2460(f, i_1_, f_0_, i_4_, i, f_7_, class186, i_9_, (byte) 30, i_8_, f_3_, is, i_6_, f_2_); i_1_ += i * i_8_; } anInt3250++; } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("u.B(" + i + ',' + f + ',' + (is != null ? "{...}" : "null") + ',' + f_0_ + ',' + i_1_ + ',' + f_2_ + ',' + (class186 != null ? "{...}" : "null") + ',' + f_3_ + ',' + i_4_ + ',' + i_5_ + ',' + i_6_ + ',' + f_7_ + ',' + i_8_ + ')')); } }
5
public void close() { socket.close(); }
0
public static boolean esCorrecta(int d, int m, int a){ int diasDelMes[]={31,29,31,30,31,30,31,31,30,31,30,31}; if(a<=0) { return false; } if(d<=0 || d>31) { return false; } if(m<=0 || m>12) { return false; } if(d>diasDelMes[m-1]) { return false; } if(m==2 && d==29 && !esBisiesto(a)) { return false; } return true; }
9
public void copyToPencilMode () { int i = 0, j = 0; for (i = 0; i < 16; i++){ for (j = 0; j < 16; j++) { if ((pencilEntries[i][j].isEditable()) && (pencilEntries[i][j].getText().equals(""))) { pencilEntries[i][j].setText(entries[i][j].getText()); } } } }
4
public boolean onCommand(CommandSender sender, Command cmd, String CommandLabel, String[] args){ final ChatColor yellow = ChatColor.YELLOW; final ChatColor red = ChatColor.RED; final ArrayList<Player> cFire = CrazyFeet.CrazyFire; if(args.length < 1) { if(sender instanceof Player) { Player player = (Player) sender; if(player.hasPermission("CrazyFeet.crazyfire")) { if(cFire.contains(player)) { cFire.remove(player); player.sendMessage(yellow+"The tingling sensation fades away.."); return true; } else { cFire.add(player); player.sendMessage(yellow+"You feel a tingling sensation in your feet!"); return true; } } else { player.sendMessage(red+"No permission."); return true; } } else { sender.sendMessage(red+"You must be an ingame player to do this!"); return true; } } else if(args.length == 1) { if(sender.hasPermission("CrazyFeet.crazyfireother")) { if(Bukkit.getServer().getPlayer(args[0]) != null) { Player targ = Bukkit.getServer().getPlayer(args[0]); if(cFire.contains(targ)) { cFire.remove(targ); targ.sendMessage(yellow+sender.getName()+" has disabled your CrazyFire!"); sender.sendMessage(yellow+targ.getDisplayName()+"'s CrazyFire has been disabled!"); return true; } else { cFire.add(targ); targ.sendMessage(yellow+sender.getName()+" has given you CrazyFire!"); sender.sendMessage(yellow+targ.getDisplayName()+" has been given CrazyFire!"); return true; } } else { sender.sendMessage(red+"The player "+yellow+args[0]+red+" is either offline or does not exist!"); return true; } } else { sender.sendMessage(red+"You do not have permission to toggle CrazyFire on others."); return true; } } else if(args.length > 1) { sender.sendMessage(red+"Incorrect usage. Use /crazyfeet for help!"); return true; } return false; }
9
public boolean Login(String email, String password, String loginUrl) { try { print("User : " + email + " log-in to the system.."); driver.get(loginUrl); waitTillElementLoad(By.id("email")); driver.findElement(By.id("email")).clear(); driver.findElement(By.id("email")).sendKeys(email); driver.findElement(By.id("password")).clear(); driver.findElement(By.id("password")).sendKeys(password); driver.findElement(By.id("submitButton")).click(); // Page load verification if (driver.getTitle().contains("Xero | Dashboard |")) { print("User : " + email + " successfully logged to the system.."); return true; } else { print("Log-in to the system failed."); return false; } } catch (Exception e) { print("Log-in to the system failed."); return false; } }
2
@Override public HashMap<String, Float> getDocWeightsForDoc(long idDoc) { try { HashMap<String, Integer> doc = index.getTfsForDoc(idDoc); int total = 0; for (int v : doc.values()) { total += v; } HashMap<String, Float> weights = new HashMap<String, Float>(); for (String key : doc.keySet()) { float wtd; switch (MODEL){ case 1: case 2: case 3: wtd = (float)(doc.get(key)) / total; break; case 4: wtd = (float)Math.log10((float)(doc.get(key)) / total); break; case 5: wtd = (float)Math.log10((float)(doc.get(key)) / total) * index.getIdfsForStem(key); break; default: wtd = (float)(doc.get(key)) / total; break; } weights.put(key,wtd); } return weights; } catch (IOException e) { e.printStackTrace(); System.out.println("Doc ID not found!"); return null; } }
8
@Override public void undo() { this.to.removePiece(this.piece); this.from.addPiece(this.piece); this.to.addPiece(this.capturedPiece); this.piece.decreaseMoveCount(); }
0
public static String toString(Map<String, List<Boolean>> _truth_table) { if (_truth_table == null) return ""; else { StringBuilder res = new StringBuilder(); List<String> col_head = new ArrayList<>(_truth_table.keySet()); if (col_head.size() == 0) return ""; Collections.sort(col_head); for (String str: col_head) { res.append(str); res.append(" "); } res.append("\n"); int n = _truth_table.get(col_head.get(0)).size(); for (int i = 0; i < n; i++) { for (int j = 0; j < col_head.size(); j++) { boolean b = _truth_table. get(col_head. get(j)). get(i); if (b) res.append("1 "); else res.append("0 "); if (j == col_head.size() - 1) res.append("\n"); } } return res.toString(); } }
7
public void removeApplicant(Applicant selectedApplicant) { em.remove(em.contains(selectedApplicant) ? selectedApplicant : em.merge(selectedApplicant)); }
1
public int count(String[] field,int dist){ this.field = field; this.dist = dist; if (field == null || field.length == 0||dist<0) return 0; height = field.length; width = field[0].length(); for (int[] row:grid){ Arrays.fill(row,0); } int count = 0; for (int i=0;i<height;i++){ for (int j=0;j<width;j++){ if(field[i].charAt(j)!='v'||grid[i][j]==1) continue; count++; dfs(j,i); } } int mod = 1; for (int i=1;i<=count;i++){ mod = (mod<<1)%1000000007; } mod = (mod-1+1000000007)%1000000007; return mod; }
9
private void addWwwRootDir(File wwwroot) { rootDirs.add(wwwroot); }
0
public void doStringBuffer() { final int repeat = ConsoleMenu.getInt("How many times?", 100000); final int characters = ConsoleMenu.getInt("How many char?", 20); long start = System.currentTimeMillis(); for (int i = 0; i < repeat; i++) { final StringBuffer sb = new StringBuffer(); for (int u = 0; u < 1000; u++) { sb.append("h"); } } long stop = System.currentTimeMillis(); System.out.println("Creating new SB " + (stop - start) + " ms."); start = System.currentTimeMillis(); final StringBuffer sb = new StringBuffer(); for (int i = 0; i < repeat; i++) { for (int u = 0; u < characters; u++) { sb.append("h"); } sb.delete(0, sb.length()); } stop = System.currentTimeMillis(); System.out.println("Deleting existing SB " + (stop - start) + " ms."); }
4
@Override protected void runInternal() throws IOException { //Get inputStream from context BitInputStream inputStream = _context.getInputBitStream(); //Init params int[] chunk = _context.getChunkArray(); int wordSize = _context.getWordSize(); int subChunkCounter = 1; int chunkIndex = 0; int chunkSize = _context.getChunkSize(); //Iterate over Chunk, while reaching chunkSize or EOF for (; chunkIndex < chunkSize && !inputStream.atEndOfFile(); subChunkCounter++) { //Read subChunk and write into array for (int l = Math.min(subChunkCounter * _context.subChunkSize, chunkSize); chunkIndex < l && !inputStream.atEndOfFile(); chunkIndex++) { chunk[chunkIndex] = inputStream.readBits(wordSize); } //set new available subChunks synchronized (_context.readCountSync) { _context.readSubChunks = subChunkCounter; } //set chunk size depending on imported data and lastSubChunk flag if (chunkIndex == chunkSize || inputStream.atEndOfFile()) { _context.setChunkSize(chunkIndex); _context.lastSubChunk = subChunkCounter; } //notify CountFrequencyTask about new available subChunks synchronized (_context.readCountSync) { _context.readCountSync.notify(); } } //imported chunk was smaller then specified chunkSize if (chunkIndex < chunkSize) { //Copy array to new array with correct size _context.setChunkArray(Arrays.copyOfRange(_context.getChunkArray(), 0, chunkIndex)); } //EOF reached, set flag if (inputStream.atEndOfFile()) _context.setLastChunk(true); }
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PeerInfo other = (PeerInfo) obj; if (ip == null) { if (other.ip != null) return false; } else if (!ip.equals(other.ip)) return false; if (port != other.port) return false; return true; }
7
public int multiplication() { if (stack.stackLength() > 1) { int firstNum = stack.top(); stack.pop(); int secondNum = stack.top(); stack.pop(); return firstNum * secondNum; } else { return error; } }
1
private Expression plus( List<Expression> args, String caller ) { boolean ints = true; boolean intsOrDecimals = true; for ( int i = 0; i < args.size(); ++i ) { // if it's not an int if ( ! args.get(i).show(defSubst, caller).matches("\\d+") ) { ints = false; } // if it's not an int or a decimal if ( ! args.get(i).show(defSubst, caller).matches("\\d+") && ! args.get(i).show(defSubst, caller).matches("\\d*.\\d+") ) { intsOrDecimals = false; } } // integer addition if ( ints ) { //System.err.println("INT ARTH"); Long result = new Long(0); for ( int i = 0; i < args.size(); ++i ) { result += new Long( args.get(i).show(defSubst, caller) ); } return new Value(result.toString()); } // double precision floating point addition else if ( intsOrDecimals ) { //System.err.println("DOUBLE ARTH"); Double result = new Double(0.0); for ( int i = 0; i < args.size(); ++i ) { result += new Double( args.get(i).show(defSubst, caller) ); } return new Value(result.toString()); } // error condition... else { System.err.println("Error: + expected only numbers as arguments"); return new Void(); } }
8
public static JSONObject getJSONObject(SampleEvent evt) { SampleResult res = evt.getResult(); long t = res.getTime(); long lt = res.getLatency(); long ts = res.getTimeStamp(); boolean s = res.isSuccessful(); String lb = escape(res.getSampleLabel()); String rc = escape(res.getResponseCode()); String rm = escape(res.getResponseMessage()); String tn = escape(res.getThreadName()); String dt = escape(res.getDataType()); int by = res.getBytes(); int sc = res.getSampleCount(); int ec = res.getErrorCount(); int ng = res.getGroupThreads(); int na = res.getAllThreads(); String localHostName = JMeterUtils.getLocalHostFullName(); String hn = XML.escape(localHostName != null ? localHostName : "localhost"); long in = res.getIdleTime(); JSONObject httpSample = new JSONObject(); try { httpSample.put("t", t); httpSample.put("lt", lt); httpSample.put("lt", lt); httpSample.put("ts", ts); httpSample.put("s", s); httpSample.put("lb", lb); httpSample.put("rc", rc); httpSample.put("rm", rm); httpSample.put("tn", tn); httpSample.put("dt", dt); httpSample.put("by", by); httpSample.put("sc", sc); httpSample.put("ec", ec); httpSample.put("ng", ng); httpSample.put("na", na); httpSample.put("hn", hn); httpSample.put("in", in); } catch (JSONException je) { BmLog.error("Error while converting sample to JSONObject"); } return httpSample; }
2
public boolean banUser(String name){ //ban a user by name if (name.equalsIgnoreCase("admin")) return false; //can't ban the admin UserAccount user = users.get(name.toLowerCase()); if (user==null) return false; user.setIsBanned(true); disconnectUser(user); return true; }
2
public Contact(byte[] record) { name = name.concat(Converter.getNameFromADNEntry(record)); int telefoneLength = record[14]; if (record[15] == (byte) 0x91) { phoneNumber = phoneNumber.concat("00"); } for (int j = 16; j < (15 + telefoneLength); j++) { String b = Converter.byteToHex(record[j]); String c = Converter.swapString(b); phoneNumber = phoneNumber.concat(c); } if (phoneNumber.contains("F")) { phoneNumber = phoneNumber.replace("F", ""); } if (phoneNumber.contains("A")) { phoneNumber = phoneNumber.replace("A", "*"); } if (phoneNumber.contains("B")) { phoneNumber = phoneNumber.replace("B", "#"); } }
5
public int getActionIndex( String action ){ if( action.equals(NOP) ){ return (getActionsNumber() - 1); }else{ int[] values = new int[3]; int k = 0; try { StreamTokenizer tokenizer = new StreamTokenizer(new StringReader( action)); while (k < 3 && tokenizer.nextToken() != StreamTokenizer.TT_EOF) { if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) { values[k] = (int) (tokenizer.nval); k++; } } return values[0] * DIGITS * DIGITS + values[1] * DIGITS + values[2] - 1; } catch (Exception e) { return -1; } } }
5
private static int method515(char arg0[], int arg1) { for (int k = arg1; k < arg0.length && k >= 0; k++) { if (arg0[k] >= '0' && arg0[k] <= '9') { return k; } } return -1; }
4
public static boolean adjacent(char x, char y) { initPositionSingleton(); KeyPosition pos = (KeyPosition) qwertyposSingleton.get(new Character(Character.toLowerCase(x))); if(pos == null) { return false; } int col = pos.getCol(); int row = pos.getRow(); String keyRow = QWERTY[row]; if(col == 0) { if(keyRow.charAt(col + 1) == Character.toLowerCase(y)) { return true; } } else { if(keyRow.charAt(col - 1) == Character.toLowerCase(y)) { return true; } if(col + 1 < keyRow.length() && keyRow.charAt(col + 1) == y) { return true; } } return false; }
6
public StructuredBlock[] getSubBlocks() { return (subBlock != null) ? new StructuredBlock[] { subBlock } : new StructuredBlock[0]; }
1
public void newPdf(List<String> fighterNames, Object fightersSorted[], int poolNumber, String filePathAndName, String tournamentName, String wightBox, String genderBox) { Document document = new Document(PageSize.A4, 50, 50, 50, 50); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filePathAndName + "_pool" + (poolNumber + 1) + ".pdf")); } catch (FileNotFoundException e) { System.out.println("Could not create file"); e.printStackTrace(); } catch (DocumentException e) { System.out.println("Could not initiate Document"); e.printStackTrace(); } document.open(); Paragraph tournamentNameParagraph = new Paragraph(tournamentName + "\n", FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD)); try { document.add(tournamentNameParagraph); } catch (DocumentException e) { // TODO Auto-generated catch block System.out.println("Could not add Tournament name to pdf");; e.printStackTrace(); } Paragraph GenderAndWeight = new Paragraph(genderBox + " " + wightBox + "\n" + "\n", FontFactory.getFont(FontFactory.HELVETICA, 14, Font.BOLD, new CMYKColor(0, 255, 255, 17))); try { document.add(GenderAndWeight); } catch (DocumentException e) { // TODO Auto-generated catch block System.out.println("Could not add gender and weight facts to pdf"); e.printStackTrace(); } for (int i = 0; i < fighterNames.size(); i++) { try { document.add(new Paragraph((i + 1) + ". " + fighterNames.get(i) + "\n", FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD))); } catch (DocumentException e) { System.out.println("Could not add fighter names to Pdf"); e.printStackTrace(); } } try { document.add(new Paragraph("\n")); } catch (DocumentException e) { System.out.println("Could not add whitespace to Pdf"); e.printStackTrace(); } for (int i = 0; i < fightersSorted.length; i++) { try { document.add(new Paragraph(fightersSorted[i].toString() + "\n", FontFactory.getFont(FontFactory.COURIER, 11, Font.BOLD))); } catch (DocumentException e) { System.out.println("Could not add generated fight order to Pdf"); e.printStackTrace(); } } document.close(); }
9
public boolean canPlayAt(int x, int y) { if (x >= 0 && x < boardSize && y >= 0 && y < boardSize && intersections[x][y] != UNPLAYED) { return false; } Intersection koIntersection = getKoIntersection(); if (koIntersection != null && koIntersection.x == x && koIntersection.y == y) { return false; } return true; }
8
private static BufferedReader createInputMessageReceiver(Socket clientSocket) { BufferedReader messageReceiver = null; try { messageReceiver = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); log.info("Create BufferedReader from clientSocket"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); log.severe("Create BufferedReader from clientSocket: fail"); } return messageReceiver; }
1
protected static String flattenIndent(final String wikiText) { String[] linesArr = wikiText.split("\\n"); for (int i = 0; i < linesArr.length; i++) { if (isStringTooIndent(linesArr[i])) { linesArr[i] = linesArr[i].replaceFirst(":{1,}", ""); } } return ArrayUtils.join(linesArr, "\n"); }
2
@Override public ICacheable get(Object key) { if (key == null) { throw new NullPointerException("key == null"); } ICacheable mapValue; synchronized (this) { mapValue = mCacheMap.get(key); if (mapValue != null) { mHitCount++; return mapValue; } mMissCount++; } return null; }
2
@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 Categoria)) { return false; } Categoria other = (Categoria) object; if ((this.idCategoria == null && other.idCategoria != null) || (this.idCategoria != null && !this.idCategoria.equals(other.idCategoria))) { return false; } return true; }
5
public boolean register(String user, String pass, String email) { if (!plugin.getConfig().getBoolean("registration.enabled")) { response = "register.error.disabled"; return false; } else if (player.isRegistered()) { response = "register.error.registered"; return false; } else if (!isWithinAccLimit(player.getIPAddress())) { response = "register.error.limit"; return false; } else if (!isValidPass(pass)) { response = "register.error.password"; return false; } else if (!isValidEmail(email)) { response = "register.error.email"; return false; } return execRegQuery(user, pass, email, false); }
5
public String toString() { if (nome != null) return nome.toString(); return id + ""; }
1
public String getInputString() { return myInputString; }
0
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(cmd.getName().equalsIgnoreCase("Nostalgia")) { if(sender instanceof Player) { Player p = (Player) sender; PlayerUtil pu = new PlayerUtil(p); if(pu.hasPermission("Nostalgia.Command.nostalgia", PermissionType.NORMAL)) { if(args.length == 0) { } else if (args.length >= 1) { if(args[0].equalsIgnoreCase("reload")) { this.onDisable(); this.onLoad(); this.onEnable(); p.sendMessage("reloaded"); } } } } else { } } return false; }
6
@Override protected void onPostExecute(Boolean result) { if (super.getSignatureListener() == null) { return; } if (result != null) { file.setTestResult(result); file.setLastCheckedDate(new Date()); StringBuilder str = new StringBuilder(); str.append("Check file :"); str.append(super.file.getFile().getName()); str.append(" [DONE]"); super.getSignatureListener().setProcessInformation(str.toString()); super.getSignatureListener().setResult(result); } }
2
public void run() { while (running) { show(); } }
1
@Override public CommandResponse executeCommand(RequestType requestType, List<Pair<String,String>> headers, String commandName, Object commandParameters, Class<?> responseCastClass){ System.out.println(); System.out.println(commandName); CommandResponse serverResponse = null; String translatedJson = jsonTrans.translateTo(commandParameters); try { URL url = new URL("http://" + Host + ':' + Port + "/" + commandName); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); for(Pair<String, String> header : headers){ System.out.println("Header: " + header.getKey() + " = " + header.getValue()); connection.addRequestProperty(header.getKey(), header.getValue()); } if(requestType.name().equals("GET")) { serverResponse = doGet(connection, responseCastClass); //will take the translated json object and the parameters and send a request to the server. } else { serverResponse = doPost(translatedJson, connection, responseCastClass); } } catch (IOException e) { // IO ERROR System.err.print("Unable to establish URL connection!"); e.printStackTrace(); } return serverResponse; }
4
public int index(XMLNodeWrapper child) { int count = childCount(); for (int i = 0; i < count; i++) { if (child.getE() == this.child(i).getE()) { return i; } } return -1; // Should never get here. }
2
public void refreshProfilesList() { Logger.getLogger(MainInterface.class.getName()).entering(MainInterface.class.getName(), "refreshProfilesList"); Logger.getLogger(MainInterface.class.getName()).log(Level.INFO, "Refresh the profiles list items and combo box"); try { refreshProfileComboBox(); refreshProfileRadioButtonMenuItem(); if (booksDirectory == null) { if (!profiles.getCurrentProfileFolder().equals("")) { booksDirectory = new File(profiles.getCurrentProfileFolder()); listSeries(); } } else if (!booksDirectory.toString().equals(profiles.getCurrentProfileFolder())) { booksDirectory = new File(profiles.getCurrentProfileFolder()); listSeries(); } } catch (Exception ex) { Logger.getLogger(MainInterface.class.getName()).log(Level.SEVERE, "Unknown exception", ex); new InfoInterface(InfoInterface.InfoLevel.ERROR, "unknown"); } Logger.getLogger(MainInterface.class.getName()).exiting(MainInterface.class.getName(), "refreshProfilesList"); }
4
public void writeControl (byte type, byte request, short value, short index, byte buf []) throws IOException { if (fd < 0) { throw new USBException("Dev.writeControl aborted",-USBException.IO_NotOpen); } if (buf == null) { //assume we're doing a No-Data-Control, and somebody has to make a 0-length buf buf = new byte[0]; } if (buf.length >= MAX_CONTROL_LENGTH || (type & ControlMessage.DIR_TO_HOST) != 0) throw new IllegalArgumentException (); if (MacOSX.trace) System.out.println ( "Dev.writeControl, rqt 0x" + Integer.toHexString (0xff & type) + ", req 0x" + Integer.toHexString (0xff & request) + ", value 0x" + Integer.toHexString (0xffff & value) + ", index 0x" + Integer.toHexString (0xffff & index) + ", len " + Integer.toString (buf.length) ); long status = controlMsg (fd, type, request, value, index, buf, 0, (short) buf.length); if (status < 0) { throw new USBException ("control write error", (int)(-status)); } }
6
public static int chebyshevDist(int color1, int color2) { int rd = Math.abs( ((color1 & RED_MASK) >> 16) - ((color2 & RED_MASK) >> 16) ); int gd = Math.abs( ((color1 & GREEN_MASK) >> 8) - ((color2 & GREEN_MASK) >> 8) ); int bd = Math.abs( (color1 & BLUE_MASK) - (color2 & BLUE_MASK) ); List<Integer> d = Arrays.asList(rd,gd,bd); int cheby = rd; for(int distance : d) { if(distance > cheby) cheby = distance; } return cheby; }
2
private void writeListTagPayload(ListTag tag) throws IOException { Class<? extends Tag> clazz = tag.getType(); List<Tag> tags = tag.getValue(); int size = tags.size(); os.writeByte(NBTUtils.getTypeCode(clazz)); os.writeInt(size); for(int i = 0; i < size; i++) { writeTagPayload(tags.get(i)); } }
2
public void keyReleased(KeyEvent e) { System.out.println("Key event initialized"); int key = e.getKeyCode(); //moveDirection = 0; if (key == KeyEvent.VK_LEFT) { Magnus.dx = 0; } if (key == KeyEvent.VK_RIGHT) { Magnus.dx = 0; } if (key == KeyEvent.VK_UP || key == KeyEvent.VK_SPACE) { Magnus.dy = (float) 1; } }
4
private void readDataFileHeader(MappedByteBuffer buffer) { int magic = buffer.getInt(); if (magic != TRACE_MAGIC) { System.err.printf( "Error: magic number mismatch; got 0x%x, expected 0x%x\n", magic, TRACE_MAGIC); throw new RuntimeException(); } // read version int version = buffer.getShort(); if (version != mVersionNumber) { System.err.printf( "Error: version number mismatch; got %d in data header but %d in options\n", version, mVersionNumber); throw new RuntimeException(); } if (version < 1 || version > 3) { System.err.printf( "Error: unsupported trace version number %d. " + "Please use a newer version of TraceView to read this file.", version); throw new RuntimeException(); } // read offset int offsetToData = buffer.getShort() - 16; // read startWhen buffer.getLong(); // read record size if (version == 1) { mRecordSize = 9; } else if (version == 2) { mRecordSize = 10; } else { mRecordSize = buffer.getShort(); offsetToData -= 2; } // Skip over offsetToData bytes while (offsetToData-- > 0) { buffer.get(); } }
7
public void shiftPressed() { HUD hud = null; for (int i = (huds.size() - 1); i >= 0; i--) { hud = huds.get(i); hud.shiftPressed(); } }
1
private boolean sendMessage(String message) { String currMessageMD5; boolean isStatus=false; try { //check if output got shutdown, this probably will never evaluate but worth a shot if (siriSocket.isOutputShutdown()) { throw new Exception("Output Shutdown"); } if (!siriSocket.isConnected()) { throw new Exception("Disconnected"); } if (siriSocket.isClosed()) { throw new Exception("Closed"); } //send data to the socket if (message.equals("status")) { isStatus=true; message=SiriStatusMessage.buildSiriMessage(); } out.println(message); if (isStatus) { System.out.println("SS 0 INFO: Sent status request"); if (!getResponse()) { throw new Exception("Timeout"); } } }catch (Exception e) { //we had a problem //only compute md5 in the case of an error currMessageMD5=MD5(message); //if we don't match the last error's message md5 we should alert the user, otherwise its redundant if (!(currMessageMD5.equals(lastErrorMD5))) { //logQueue.add("SS 0 ERROR: Could not send message " +message+ "!::" + e.getMessage()); lastErrorMD5=currMessageMD5; } return false; } return true; }
8
public void updatePosition(Mower mower, Lawn lawn) { final Direction direction = mower.getCurrentPosition().getDirection(); //mower changing direction if (direction == Direction.NORTH) { mower.getCurrentPosition().setDirection(Direction.EAST); } else if (direction == Direction.EAST) { mower.getCurrentPosition().setDirection(Direction.SOUTH); } else if (direction == Direction.SOUTH) { mower.getCurrentPosition().setDirection(Direction.WEST); } else if (direction == Direction.WEST) { mower.getCurrentPosition().setDirection(Direction.NORTH); } }
4
static public void run(String name) { if (states.containsKey(name)) { states.get(name).action(); } }
1
static int letterDistance(char c1, char c2){ int x1; int x2; int y1; int y2; if (KEYBOARD_MATRIX.get(0).contains(c1)) x1=0; else if (KEYBOARD_MATRIX.get(1).contains(c1)) x1=1; else if (KEYBOARD_MATRIX.get(2).contains(c1)) x1=2; else x1=3; if (KEYBOARD_MATRIX.get(0).contains(c2)) x2=0; else if (KEYBOARD_MATRIX.get(1).contains(c2)) x2=1; else if (KEYBOARD_MATRIX.get(2).contains(c2)) x2=2; else x2=3; y1 = KEYBOARD_MATRIX.get(x1).indexOf(c1); y2 = KEYBOARD_MATRIX.get(x2).indexOf(c2); //Account for spacebar being in the middle if (x1==3) y1=5; if (x2==3) y2=5; return (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2); }
8
public void visit_f2i(final Instruction inst) { stackHeight -= 1; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } stackHeight += 1; }
1
SelectorNode selector() { IdentNode subject = constIdent(); SelectorNode node = null; if (test(DOT)) { read(DOT, "."); node = new RecordSelectorNode(subject, constIdent()); } else if (test(LBRAC)) { read(LBRAC, "["); node = new ArraySelectorNode(subject, expr()); read(RBRAC, "]"); } else { failExpectation(". or ["); } while (test(DOT) || test(LBRAC)) { if (test(DOT)) { read(DOT, "."); node = new RecordSelectorNode(node, constIdent()); } else { read(LBRAC, "["); node = new ArraySelectorNode(node, expr()); read(RBRAC, "]"); } } return node; }
5
public void log(String line) { if (_verbose) { System.out.println(System.currentTimeMillis() + " " + line); } }
1
private static int getSubTypes(int types) { int result = 0; for (int i = 0; i < NUM_TYPES; i++) { if (((1 << i) & types) != 0) result |= subTypes[i]; } return result; }
2
public synchronized void mouseMoved(MouseEvent me) { if(isRelative) { Point p = me.getPoint(); dx += p.x - center.x; dy += p.y - center.y; if(!((dx == 0) && (dy == 0))) { centerMouse(); } } }
3
public void setHeight(int height) { this.height = height; }
0
public static int getEnvironmentalPressureUnit() throws ClassNotFoundException { int weightUnit = 0; try{ //Class derbyClass = RMIClassLoader.loadClass("lib/", "derby.jar"); Class.forName(driverName); Class.forName(clientDriverName); }catch(java.lang.ClassNotFoundException e) { throw e; } try (Connection connect = DriverManager.getConnection(databaseConnectionName)) { Statement stmt = connect.createStatement(); ResultSet thePilots = stmt.executeQuery("SELECT pressure_unit " + "FROM EnvironmentalUnits " + "WHERE unit_set = 0"); while(thePilots.next()) { try { weightUnit = Integer.parseInt(thePilots.getString(1)); }catch(NumberFormatException e) { //TODO What happens when the Database sends back invalid data JOptionPane.showMessageDialog(null, "Number Format Exception in reading from DB"); } } thePilots.close(); stmt.close(); }catch(SQLException e) { JOptionPane.showMessageDialog(null, e.getMessage()); return -1; } return weightUnit; }
4
public static void main(String[] args) throws Exception{ txtPath = args[0]; label = args[1]; ArrayList<File> files = FileFinder.GetAllFiles(txtPath, ".txt", true); int count = 0; for(File f : files){ @SuppressWarnings("resource") BufferedReader br = new BufferedReader(new FileReader(f)); String line = null; while ((line = br.readLine()) != null) { String[] split = line.split(splitmark); if (split.length < 2) continue; String word = split[0]; String annotated = split[split.length-2]; String predicted = split[split.length-1]; if(annotated.equals(label)) { System.out.println(f.getName()); count++; if(!annotated.equals(predicted)) { // System.out.println(f.getName()); System.out.println(count + ": " + word + splitmark + annotated +splitmark + predicted); System.out.println("=================================================================="); } else System.out.println(count + ": " + word + splitmark + annotated +splitmark + predicted); } } } }
5
public void visitEnd() { if (!subroutineHeads.isEmpty()) { markSubroutines(); if (LOGGING) { log(mainSubroutine.toString()); Iterator it = subroutineHeads.values().iterator(); while (it.hasNext()) { Subroutine sub = (Subroutine) it.next(); log(sub.toString()); } } emitCode(); } // Forward the translate opcodes on if appropriate: if (mv != null) { accept(mv); } }
4
public void migrateAgentToGroup(Agent a, Group toGroup) { //int numExternal = a.getNumExternalNeighbors(); numMigrations++; if(a.getNumExternalNeighbors() > 20) System.out.println("whaaaa"); //long[] profile = new long[10]; Group fromGroup = a.getGroup(); //remove neighbors from a's original set of agents fromGroup.removeAgent(a); a.group = null; //profile[0] = System.nanoTime(); for(Agent a1: a.getExternalNeighbors()){ a1.removeNeighbor(a); } //profile[1] = System.nanoTime(); //Add new neighbors to a1 (directed) //profile[2] = System.nanoTime(); a.setGroup(toGroup); toGroup.addAgent(a); //numEdges -= a.getNumExternalNeighbors(); a.resetExternal(); //profile[3] = System.nanoTime(); //int numExternal = 0; /*for(int i = 0; i < Constants._numnodes; i++) { if(rand.nextDouble() < Constants._p_ext) numExternal++; }//*/ //profile[4] = System.nanoTime(); double rndDub = rand.nextDouble(); int numExternal = (int)Math.round((agents.size()-toGroup.getAgents().size()) * ((rndDub*(rndDub-0.5)+1)*Constants._p_ext)); //*/ //int numExternal = (int)Math.round((agents.size()-toGroup.getAgents().size()) * Constants._p_ext); if(numExternal > agents.size() - toGroup.getAgents().size()) numExternal = agents.size() - toGroup.getAgents().size(); //*/ //profile[5] = System.nanoTime(); //numEdges += numExternal; //profile[6] = System.nanoTime(); ArrayList<Group> exGroupSet = new ArrayList<Group>(groups); exGroupSet.remove(toGroup); Group tGroup = exGroupSet.get(0); int rndAgentID; Agent rndAgent; for(int i = 0; i < numExternal; i++) { //tMeasure[1] += System.nanoTime(); do { rndAgentID = rand.nextInt(agents.size()-toGroup.getAgents().size()); for(Group g: exGroupSet) { if(rndAgentID >= (tGroup = g).getAgents().size()) rndAgentID -= g.getAgents().size(); else break; } rndAgent = tGroup.getAgents().get(rndAgentID); } while(a.hasNeighbor(rndAgent)); //tMeasure[2] += System.nanoTime(); a.addNeighbor(rndAgent); } //profile[7] = System.nanoTime(); //profile[8] = System.nanoTime(); //Set neighbors in opposite direction for(Agent a3: a.getExternalNeighbors()) { a3.addNeighbor(a); } //profile[9] = System.nanoTime(); }
8
@Override public void run() { InetAddress serverAddr= null; try { serverAddr= InetAddress.getByName(GlobalV.serverIP); } catch (UnknownHostException e1) { e1.printStackTrace(); } Socket socket = null; try { System.out.println("send Alert to server"); socket = new Socket(serverAddr,8020); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } PrintWriter out = null; try { out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.println(alert); System.out.print("alert sent"); }
4
public List<String> readHTMLWithOutWriteToFile(URL url, String site){ String str = ""; String tmp; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while((tmp = in.readLine()) != null){ str = str + tmp; } str = str.replace("\t", ""); str = str.replace("> <", "><"); str = str.replace(" ", ""); str = str.replace(" ", ""); searchLinkAndAddToList(str, site); Iterator<String> iterator = links.iterator(); while(iterator.hasNext()){ if(iterator.next().indexOf("http://tothegame.com/devinfo.asp?id=") < 0){ iterator.remove(); } } } catch (IOException e) { System.out.println("ERROR! " + e); } return links; }
4