text
stringlengths
14
410k
label
int32
0
9
public void reactToLight(Light.LightStatus lightStatus, double currentTime){ calcCurrentState(currentTime); P.p("Current position: "+position); P.p("Reacting to lightStatus: " + lightStatus); switch(lightStatus){ case GREEN: P.p("lightStatus is green"); if(saved != null && !saved.exited) { ahead = saved; ahead.changeState(currentTime); } else { ahead = null; changeState(currentTime); } // create event for accelerating // changeState(currentTime); break; case YELLOW: P.p("lightStatus is yellow"); // calculate when it will need to start decelerating // processSpeed(Metrics.WALK_LEFT, 0, currentTime); saved = ahead; ahead = Crosswalk.stopped; changeState(currentTime); // if(behind != null) // behind.changeState(currentTime); break; default: break; } }
4
public static int[][] one2two(int[] one, int w, int h) { int[][] two = new int[h][w]; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { two[i][j] = one[i * w + j]; } } return two; }
2
@SuppressWarnings("unchecked") public E peek() { if (count == 0) return null; return (E) elements[head]; }
1
public boolean checkProjectileCollision(GameActor proj, GameActor other) { // currently we are only interested in collision between a projectile and another type of actor if(proj == null || other == null) { return false; } PhysicsComponent projPC = (PhysicsComponent)proj.getComponent("PhysicsComponent"); PhysicsComponent otherPC = (PhysicsComponent)other.getComponent("PhysicsComponent"); if(projPC == null || otherPC == null) { return false; } Rectangle projHb = projPC.getHitbox(); Rectangle otherHb = otherPC.getHitbox(); if(projHb.x + projHb.width < otherHb.x) { return false; } if(projHb.x > otherHb.x + otherHb.width) { return false; } if(projHb.y + projHb.height < otherHb.y) { return false; } if(projHb.y > otherHb.y + otherHb.height) { return false; } // we got here, we got a HIT! Application.get().getEventManager().queueEvent(new CollisionEvent(proj, other)); otherPC.takeDamage(projPC.getDamage()); /* // TODO: figure something better out here (or rather somewhere else...) if(otherPC.takeDamage(projPC.getDamage())) { InventoryComponent giver = (InventoryComponent)other.getComponent("InventoryComponent"); StatusComponent sc = (StatusComponent)proj.getComponent("StatusComponent"); if(sc.getAlleciange().equals("friendly")) { GameActor p = Application.get().getLogic().getActor(Application.get().getHumanView().getAttachedActor()); InventoryComponent getter = (InventoryComponent)p.getComponent("InventoryComponent"); getter.addMoney(giver.getMoney()); } } * */ Application.get().getEventManager().executeEvent(new ActorDestroyedEvent(proj)); // destroy the projectile return true; }
8
public static Stella_Object access_retrieval_Slot_Value(retrieval self, Symbol slotname, Stella_Object value, boolean setvalueP) { if (slotname == Plsoap.SYM_PLSOAP_TARGET_MODULE) { if (setvalueP) { self.targetModule = ((module)(value)); } else { value = self.targetModule; } } else if (slotname == Plsoap.SYM_PLSOAP_NRESULTS) { if (setvalueP) { self.nresults = ((nresults)(value)); } else { value = self.nresults; } } else if (slotname == Plsoap.SYM_LOGIC_PATTERN) { if (setvalueP) { self.pattern = ((pattern)(value)); } else { value = self.pattern; } } else if (slotname == Plsoap.SYM_STELLA_OPTIONS) { if (setvalueP) { self.options = ((options)(value)); } else { value = self.options; } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + slotname + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } return (value); }
8
public void run(int maxSteps, double minError) { double[] output; int i; double error = 1; //for (i = 0; i < maxSteps && error > minError; i++) { // Train neural network until minError reached or maxSteps exceeded for (i = 0; error > minError; i++) { error = 0; for (int j = 0; j < patterns.size(); j++) { network.setInput(patterns.get(j).getInput()); network.activateNetwork(); output = network.getOutput(); patterns.get(j).setResult(output); // double oError = 0; for (int k = 0; k < patterns.get(j).getOutput().length; k++) { double err = Math.pow(output[k] - patterns.get(j).getOutput()[k], 2); error += err; } network.applyBackpropagation(patterns.get(j).getOutput()); } error = 1.0/2.0 * error; Collections.shuffle(patterns); // added recently } System.out.println("Sum of squared errors = " + error + " %"); System.out.println("##### EPOCH " + i+"\n"); if (i == maxSteps) { System.out.println("!Error training try again"); } }
4
public static String makeSegText(String[] units, Boolean[] stresses, Boolean[] segmentation) { StringBuilder out = new StringBuilder(); // Connect all but the last unit with the right connection, then add on // the final one for (int i=0; i < units.length - 1; i++) { out.append(units[i]); if (stresses[i]) out.append("(1)"); out.append(segmentation[i] ? WORD_BOUNDARY : SYLL_BOUNDARY); } // Stick on final unit and stress out.append(units[units.length - 1]); if (stresses[units.length - 1]) out.append("(1)"); return out.toString(); }
4
public static boolean getPlayerInfo(String[] args, CommandSender s){ //Various checks if(Util.isBannedFromGuilds(s) == true){ //Checking if they are banned from the guilds system s.sendMessage(ChatColor.RED + "You are currently banned from interacting with the Guilds system. Talk to your server admin if you believe this is in error."); return false; } if(!s.hasPermission("zguilds.player.playerinfo")){ //Checking if they have the permission node to proceed s.sendMessage(ChatColor.RED + "You lack sufficient permissions to get player info. Talk to your server admin if you believe this is in error."); return false; } if(args.length > 2 || args.length == 1){ //Checking if the create command has proper args s.sendMessage(ChatColor.RED + "Incorrectly formatted guild player info command! Proper syntax is: \"/guild playerinfo <player name>\""); return false; } targetPlayer = args[1].toLowerCase(); if(Main.players.getConfigurationSection("Players." + targetPlayer) == null){ s.sendMessage(ChatColor.RED + "That player doesn't exist."); return false; } targetPlayersGuild = Main.players.getString("Players." + targetPlayer + ".Current_Guild"); if(targetPlayersGuild.matches("None")){ s.sendMessage(ChatColor.RED + "The player " + targetPlayer + " is not currently in a guild."); return false; } targetPlayersRankNumber = Main.players.getInt("Players." + targetPlayer + ".Current_Rank"); targetPlayersRankString = Main.guilds.getString("Guilds." + targetPlayersGuild + ".Ranks." + targetPlayersRankNumber); targetPlayersContributions = Main.players.getInt("Players." + targetPlayer + ".Guild_Contributions"); targetPlayersMemberSince = Main.players.getString("Players." + targetPlayer + ".Member_Since"); s.sendMessage(ChatColor.DARK_GREEN + "--- Player Info for: " + targetPlayer + " ---"); s.sendMessage(ChatColor.DARK_GREEN + "Current Guild: " + targetPlayersGuild); s.sendMessage(ChatColor.DARK_GREEN + "Guild Contributions: " + targetPlayersContributions); s.sendMessage(ChatColor.DARK_GREEN + "Current Rank: " + targetPlayersRankString); s.sendMessage(ChatColor.DARK_GREEN + "Member Since: " + targetPlayersMemberSince); return true; }
6
public ArrayList<Location> getPossibleMoves(Chessboard boardToCheck, Location pieceLoc) { ArrayList<Location> possibleMoves = new ArrayList<>(); Chessboard chessboardCopy = new Chessboard(boardToCheck); Tile[][] tileBoardCopy = chessboardCopy.getBoard(); //Piece pieceToCheck = tileBoardCopy[pieceLoc.getRow()][pieceLoc.getColumn()].getPiece(); for(int i = 0; i < BOARD_LENGTH; i++) { for(int j = 0; j < BOARD_LENGTH; j++) { Location possibleMove = new Location(i, j); if(chessboardCopy.testMovePiece(pieceLoc, possibleMove, tileBoardCopy)) { possibleMoves.add(possibleMove); } } } System.out.println("Available moves for this piece: "); for(Location l : possibleMoves) { System.out.println(l); } return possibleMoves; }
4
public void reset(){ for (int i = 0; i < 3; i++){movementX [i] = 0; movementY[i] = 0;} hasMovement = false; if (tileId < 2){ tileId = 0; } refresh(); }
2
public Field getField(int stepNumber){ if (stepNumber >= MIN_NUMBER_OF_STEPS && stepNumber < MAX_NUMBER_OF_STEPS){ return history[stepNumber]; } else{ return getCurrentField(); } }
2
int time_seek(float seconds){ // translate time to PCM position and call pcm_seek int link=-1; long pcm_total=pcm_total(-1); float time_total=time_total(-1); if(!seekable) return (-1); // don't dump machine if we can't seek if(seconds<0||seconds>time_total){ //goto seek_error; pcm_offset=-1; decode_clear(); return -1; } // which bitstream section does this time offset occur in? for(link=links-1; link>=0; link--){ pcm_total-=pcmlengths[link]; time_total-=time_total(link); if(seconds>=time_total) break; } // enough information to convert time offset to pcm offset { long target=(long)(pcm_total+(seconds-time_total)*vi[link].rate); return (pcm_seek(target)); } //seek_error: // dump machine so we're in a known state //pcm_offset=-1; //decode_clear(); //return -1; }
5
@Override public int attack(double agility, double luck) { System.out.println("I tried to do a special attack but I haven't set it so I failed at this turn..."); return 0; }
0
public boolean setUsertileImageFrameWidth(int width) { boolean ret = true; if (width <= 0) { this.usertileImageFrame_Width = UISizeInits.USERTILE_IMAGEFRAME.getWidth(); ret = false; } else { this.usertileImageFrame_Width = width; } setUsertileImageOverlay_Width(this.usertileImageFrame_Width); somethingChanged(); return ret; }
1
@Override public Coup genererCoup(Plateau etatJeu) { //Algorithme repris de l'énoncé du TP Noeud meilleurCoup = null; ArrayList<Position> positionsPossibles = etatJeu.etatId(0); Joueur j; for (Position p : positionsPossibles) { Coup cCourant = new Coup(this.id, p); Noeud nCourant = new Noeud(cCourant); etatJeu.jouer(cCourant); ArrayList<Coup> sit = etatJeu.getSituation(); for (int i = 0; i < this.nbSimulation; i++) { j = this.factory.CreerPartieAleatoireVSAleatoire(sit).jouerPartie(false); if (j != null) { if (j.getId() == super.getId()) { nCourant.ajouterVictoire(); } else { nCourant.ajouterDefaite(); } } } if ((meilleurCoup == null) || (meilleurCoup.getNbSimulation() == 0) || (meilleurCoup.getMoyenne() < nCourant.getMoyenne())) { meilleurCoup = nCourant; } etatJeu.annuler(); } return meilleurCoup.getCoup(); }
7
public boolean collisionDepl(int x, int y) { int Dx = pieceCourante.x + x; int Dy = pieceCourante.y + y; for (int i = 0; i < 4; i++) { int test = Dx + pieceCourante.Cases[i].getX(); int test2 = Dy + pieceCourante.Cases[i].getY(); if ((test > largeur - 1) || (test < 0)) { return false; } if (test2 > hauteur - 1) { return false; } if (tab[test][test2] != 0) { return false; } } return true; }
5
public Vector<Integer> getLeaders() { Vector<Integer> leaders = new Vector<Integer>(); int leaderY = Integer.MAX_VALUE; for (int t=0; t<turtles.length; t++) { int tY = turtles[t].getY(); if (tY < leaderY) { leaders.clear(); leaders.add(t+1); leaderY = tY; } else if (tY == leaderY) { if (!leaders.contains(t+1)) { leaders.add(t+1); } } } return leaders; }
4
@Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub switch (e.getKeyCode()) { case KeyEvent.VK_S: { downPressed=false; } break; case KeyEvent.VK_W: { upPressed=false; } break; case KeyEvent.VK_D: { rightPressed=false; } break; case KeyEvent.VK_A: { leftPressed=false; } break; } }
4
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target.fetchEffect(this.ID())!=null) { mob.tell(target,null,null,L("<S-NAME> already <S-HAS-HAVE> wings.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> @x1 that <T-NAME> be given the gift of flight.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> grow(s) an enormous pair of wings!")); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 for wings, but <S-HIS-HER> plea is not answered.",prayWord(mob))); // return whether it worked return success; }
8
private TreeNodePageWrapper searchListForPageWrapperOrCreateNew(List<TreeNodePageWrapper> list, AbstractPage page) { if (list == null) return new TreeNodePageWrapper(page, (DefaultTreeModel) tree.getModel()); for (TreeNodePageWrapper element: list) if (element.page.url.equals(page.url)) return element; return new TreeNodePageWrapper(page, (DefaultTreeModel) tree.getModel()); }
3
public boolean delete(Object value) { Node node = search(value); if (node == null) { return false; } Node deleted = node.getSmaller() != null && node.getLarger() != null ? node.successor() : node; assert deleted != null : "deleted can't be null"; Node replacement = deleted.getSmaller() != null ? deleted.getSmaller() : deleted.getLarger(); if (replacement != null) { replacement.setParent(deleted.getParent()); } if (deleted == _root) { _root = replacement; } else if (deleted.isSmaller()) { deleted.getParent().setSmaller(replacement); } else { deleted.getParent().setLarger(replacement); } if (deleted != node) { Object deletedValue = node.getValue(); node.setValue(deleted.getValue()); deleted.setValue(deletedValue); } --_size; return true; }
8
private boolean isPointsInTriangle(int a, int b, int c, int[] verts) { Point2D pa = points[verts[a]]; Point2D pb = points[verts[b]]; Point2D pc = points[verts[c]]; final double e = 1e-6; double abcSquare = square(pa,pb,pc); for (Point2D pd : points) { // если точки совпадают if (pd.equals(pa) || pd.equals(pb) || pd.equals(pc)) continue; double abdSquare = square(pa, pb, pd); double adcSquare = square(pa, pd, pc); double dbcSquare = square(pd, pb, pc); // если треугольник выржден в линию if (abdSquare == 0 || adcSquare == 0 || dbcSquare == 0) continue; double sum = abdSquare + adcSquare + dbcSquare; if (sum - abcSquare < e) return true; } return false; }
8
@Override public void setActiveForTask(int id_task, Boolean active) { try { connection = getConnection(); ptmt = connection.prepareStatement("UPDATE Task_executors SET active=? WHERE id_task=?;"); ptmt.setBoolean(1, active); ptmt.setInt(2, id_task); ptmt.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(TaskExecutorsDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (ptmt != null) { ptmt.close(); } if (connection != null) { connection.close(); } if (resultSet != null) { resultSet.close(); } } catch (SQLException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } } }
5
public void init() { buildMenu(); //make a split panel splitPanel = new HorizontalSplitPanel(); splitPanel.setSizeFull(); splitPanel.setSplitPosition(25, Sizeable.UNITS_PERCENTAGE); splitPanel.setLocked(false); splitPanel.setVisible(true); //make a tree as the first component webpageTree = new Tree("Your Site's Web Pages"); webpageTree.setSizeUndefined(); webpageTree.addItem("Your Website"); webpageTree.setImmediate(true); splitPanel.setFirstComponent(webpageTree); //make a text area as the second component webpageText = new RichTextArea(); webpageText.setSizeFull(); splitPanel.setSecondComponent(webpageText); webpageTree.addListener(new Property.ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { if (event.getProperty().getValue() != null) { Website2EbookmakerApplication app = ((Website2EbookmakerApplication)MainLayout.this.getApplication()); if (currentPage.equals(websitename)) { app.getWebScraper().saveFormattedPageText(currentPage, (String) webpageText.getValue()); } else if (!currentPage.isEmpty()) { if (currentPage.startsWith(websitename)) { app.getWebScraper().saveFormattedPageText(currentPage, (String) webpageText.getValue()); } else { app.getWebScraper().saveFormattedPageText(websitename + "/" + currentPage, (String) webpageText.getValue()); } } if (!((String)event.getProperty().getValue()).startsWith(websitename)) { webpageText.setValue(app.getWebScraper().getPageText(websitename + "/" + (String) event.getProperty().getValue())); } else { webpageText.setValue(app.getWebScraper().getPageText((String) event.getProperty().getValue())); } currentPage = (String) event.getProperty().getValue(); webpageText.requestRepaint(); } else { webpageText.setValue(""); } } }); this.addComponent(splitPanel); this.setExpandRatio(splitPanel, 0.9f); }
5
static public void main(String args[]) { double x, y; Random rand = new Random(); String firstLetter = "STNH"; String secondLetter = "ABCDEFGHJKLMNOPQRSTUVWXYZ"; double sumx, sumx2; int nsum; OSGB osgb = new OSGB(); osgb.setErrorTolerance(0.0001); nsum = 0; sumx = sumx2 = 0.0; for (int i = 0; i < 10000; i++) { x = 100000.0 * rand.nextDouble(); y = 100000.0 * rand.nextDouble(); DPoint p0 = new DPoint(x, y); int ia, ib; ia = rand.nextInt() % 4; if (ia < 0) ia += 4; ib = rand.nextInt() % 25; if (ib < 0) ib += 25; char ca = firstLetter.charAt(ia); char cb = secondLetter.charAt(ib); DPoint dp = osgb.GridSquareToOffset(ca, cb); p0.offsetBy(dp); char[] pfx = osgb.GridToGridSquare(p0); String pfxs = new String(pfx); DPoint p1 = osgb.GridToLongitudeAndLatitude(p0); double phi, lambda; lambda = (180.0 / Math.PI) * p1.getX(); phi = (180.0 / Math.PI) * p1.getY(); System.out.println("Grid coordinates (" + ca + cb + " " + p0.getX() + ", " + p0.getY() + ") map to:"); double ls = Math.abs(lambda); double ps = Math.abs(phi); int ld, lm, pd, pm; ld = (int) ls; ls = 60.0 * (ls - ld); lm = (int) ls; ls = 60.0 * (ls - lm); pd = (int) ps; ps = 60.0 * (ps - pd); pm = (int) ps; ps = 60.0 * (ps - pm); System.out.print((lambda < 0.0) ? "West " : "East "); System.out.println(ld + " " + lm + " " + ls); System.out.print((phi < 0.0) ? "South " : "North "); System.out.println(pd + " " + pm + " " + ps); System.out.println("Grid letters are " + pfxs); DPoint p2 = osgb.LatitudeAndLongitudeToGrid(p1); System.out.println("Reverse transform:"); System.out.println(" Easting = " + p2.getX()); System.out.println(" Northing = " + p2.getY()); double d = p2.distanceFrom(p0); System.out.println(" DISTANCE = " + d); if (ca != pfx[0] || cb != pfx[1]) System.out.println("*** MISMATCH OF PREFIX ***"); if (Math.abs(d) > 0.01) System.out.println("*** POSITION ERROR *** " + pfxs + " " + d); else { nsum += 1; sumx += d; sumx2 += d * d; } } sumx /= (double) nsum; sumx2 /= (double) nsum; sumx2 -= sumx * sumx; sumx2 = Math.sqrt(sumx2); System.err.println("From " + nsum + " samples, mean = " + sumx + " and sigma = " + sumx2); }
8
@Override public void deserialize(Buffer buf) { int limit = buf.readUShort(); titles = new short[limit]; for (int i = 0; i < limit; i++) { titles[i] = buf.readShort(); } limit = buf.readUShort(); ornaments = new short[limit]; for (int i = 0; i < limit; i++) { ornaments[i] = buf.readShort(); } activeTitle = buf.readShort(); if (activeTitle < 0) throw new RuntimeException("Forbidden value on activeTitle = " + activeTitle + ", it doesn't respect the following condition : activeTitle < 0"); activeOrnament = buf.readShort(); if (activeOrnament < 0) throw new RuntimeException("Forbidden value on activeOrnament = " + activeOrnament + ", it doesn't respect the following condition : activeOrnament < 0"); }
4
public void setBodypart(BodyPart b){ this.bodypart = b; }
0
private void btnAgregarHMPMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAgregarHMPMouseClicked HMP h = new HMP(); h.setIdAula(Integer.parseInt(String.valueOf(this.cmbAulaHMP.getSelectedItem()))); h.setIdGrupo(Integer.parseInt(String.valueOf(this.cmbGrupoHMP.getSelectedItem()))); h.setIdHorario(Integer.parseInt(String.valueOf(this.cmbHorarioHMP.getSelectedItem()))); h.setIdMateria(Integer.parseInt(String.valueOf(this.cmbMateriaHMP.getSelectedItem()))); h.setIdUsuario(Integer.parseInt(String.valueOf(this.cmbUsuarioHMP.getSelectedItem()))); switch(String.valueOf(this.cmbDiaHMP.getSelectedItem())){ case "LUNES":{ h.setDia(2); break; } case "MARTES":{ h.setDia(3); break; } case "MIERCOLES":{ h.setDia(4); break; } case "JUEVES":{ h.setDia(5); break; } case "VIERNES":{ h.setDia(6); break; } default: break; } this.hmp.addHMP(h); try { loadDataToTableHMP(); } catch (SQLException ex) { Logger.getLogger(SCAdministrador.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_btnAgregarHMPMouseClicked
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Term other = (Term) obj; if (field == null) { if (other.field != null) return false; } else if (!field.equals(other.field)) return false; if (text == null) { if (other.text != null) return false; } else if (!text.equals(other.text)) return false; return true; }
9
private RsToken quotedString() throws RsParsingException { int value; StringBuffer sbuff; sbuff=token.getStringBuffer(); while(true){ value=nextChar(); // check for special characters if(value=='\"'){ token.setType(RsToken.TT_STRING); return token; }else if(value=='\\'){ value=nextChar(); if(value=='n') value='\n'; else if(value=='t') value='\t'; }else if(value=='\n'){ throw gripe("End-of-line within quoted string on line "); } sbuff.append((char)value); } }
6
public int getPlayerScores(){ return playerScores; }
0
private Ingredient createIngredient(String name, double amount) { switch (name) { case "avocado": return new Avocado(amount); case "crab": return new Crab(amount); case "eel": return new Eel(amount); case "rice": return new Rice(amount); case "salmon": return new Salmon(amount); case "seaweed": return new Seaweed(amount); case "shrimp": return new Shrimp(amount); case "tuna": return new Tuna(amount); } //this will not execute...just appeasing the compiler gods return null; }
8
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!super.okMessage(myHost,msg)) return false; if(msg.targetMinor()==CMMsg.TYP_ENTER) { if(msg.target()==this) { final MOB mob=msg.source(); if((mob.location()!=null)&&(mob.location().roomID().length()>0)) { int direction=-1; for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--) { if(mob.location().getRoomInDir(d)==this) direction=d; } if(direction<0) { mob.tell(L("Some great evil is preventing your movement that way.")); return false; } msg.modify(msg.source(), getAltRoomFrom(mob.location(),direction), msg.tool(), msg.sourceCode(), msg.sourceMessage(), msg.targetCode(), msg.targetMessage(), msg.othersCode(), msg.othersMessage()); } } } return true; }
8
public void showProducts(int rol){ ArrayList<beansProducto> listaProductos; listaProductos = ManejadorProductos.getInstancia().listaProductos(); if(listaProductos.size() >= 0){ for(beansProducto producto : listaProductos){ if(rol == 1){ mostrarProducto(producto); }else{ if(producto.getExistencias() > 0){ mostrarProducto(producto); } } } }else{ System.out.println("No hay productos ingresados"); } }
4
public static String InventoryToString (Inventory invInventory) { String serialization = invInventory.getSize() + ";"; for (int i = 0; i < invInventory.getSize(); i++) { ItemStack is = invInventory.getItem(i); if (is != null) { String serializedItemStack = new String(); String isType = String.valueOf(is.getType().getId()); serializedItemStack += "t@" + isType; if (is.getDurability() != 0) { String isDurability = String.valueOf(is.getDurability()); serializedItemStack += ":d@" + isDurability; } if (is.getAmount() != 1) { String isAmount = String.valueOf(is.getAmount()); serializedItemStack += ":a@" + isAmount; } Map<Enchantment,Integer> isEnch = is.getEnchantments(); if (isEnch.size() > 0) { for (Entry<Enchantment,Integer> ench : isEnch.entrySet()) { serializedItemStack += ":e@" + ench.getKey().getId() + "@" + ench.getValue(); } } if (is.getItemMeta().getDisplayName() != null) { String[] itemDisplayName = is.getItemMeta().getDisplayName().split(" "); serializedItemStack += ":n@"; for (int m = 0; m < itemDisplayName.length; m++) { serializedItemStack += itemDisplayName[m] + "="; } } serialization += i + "#" + serializedItemStack + ";"; } } return serialization; }
8
private void populateStage() { String iconFile; switch (type) { case ACCEPT: iconFile = "Dialog-accept.jpg"; addOKButton(); break; case ERROR: iconFile = "Dialog-error.jpg"; addOKButton(); break; case INFO: iconFile = "Dialog-info.jpg"; addOKButton(); break; case QUESTION: iconFile = "Dialog-question.jpg"; break; default: iconFile = "Dialog-info.jpg"; break; } try { loadIconFromResource(iconFile); } catch (Exception ex) { System.err.println("Exception trying to load icon file: " + ex.getMessage()); } BorderPane.setAlignment(icon, Pos.CENTER); BorderPane.setMargin(icon, new Insets(5, 5, 5, 5)); pane.setLeft(icon); BorderPane.setAlignment(message, Pos.CENTER); BorderPane.setMargin(message, new Insets(5, 5, 5, 5)); pane.setCenter(message); scene = new Scene(pane); for (int i = 0; i < stylesheets.size(); i++) { try { scene.getStylesheets().add(stylesheets.get(i)); } catch (Exception ex) { System.err.println("Unable to load specified stylesheet: " + stylesheets.get(i)); System.err.println(ex.getMessage()); } } stage.setScene(scene); }
7
private void addFictitiousInterval() { if (intervals.size() == 0) { throw new IndexOutOfBoundsException("There must be at least one interval to add fictitious one"); } // TODO take mass of the QWs for the fictitious layer // intervals.add(0, new MatterInterval(0, 0, 0, // intervals.get(0).getMass(), intervals.get(0) // .getDiel())); intervals.add(0, new MatterInterval(0, 0, 0, intervals.get(0).getMass(), intervals.get(0).getDiel())); // intervals.add(0, new // MatterInterval(-intervals.get(0).getWidth(), 0, 0, // intervals.get(0).getMass(), intervals.get(0).getDiel())); getFictitiousInterval().setLabel("Fictitious"); fictitiousRegionReady = true; }
1
public void findStaffOnProject(Project project){ try{ SetOfUsers staffOnProject = new SetOfUsers(); ResultSet staffResults = null; Statement statement; statement = connection.createStatement(); staffResults = statement.executeQuery( "SELECT Project.projectID, User.userID, User.firstName, User.surname, Staff.role" + "FROM User INNER JOIN (Staff INNER JOIN (Project INNER JOIN StaffOnProjects ON Project.projectID = StaffOnProjects.projectID)" + " ON Staff.staffID = StaffOnProjects.staffID) ON User.userID = Staff.staffID" + "WHERE Project.projectID=" + project.getProjectID() + ";"); while (staffResults.next()) { for(int i=0;i<allUsers.size();i++){ if(allUsers.get(i).getUserID()==staffResults.getInt("staffID")){ staffOnProject.addUser(allUsers.get(i)); } } } }catch(Exception e){ JOptionPane.showMessageDialog(null,e); } }
4
public void walkDown() { face = 2; if (!(y == Realm.WORLD_HEIGHT - 1) && !walkblockactive) if (!Collision.check(new Position(x, y), face)) { y += walkspeed; setWalkBlock(walkblocktick); } }
3
private static Day parseCalendarDay(int dayOfWeek) { switch (dayOfWeek) { case Calendar.SUNDAY: return SUN; case Calendar.MONDAY: return MON; case Calendar.TUESDAY: return TUE; case Calendar.WEDNESDAY: return WED; case Calendar.THURSDAY: return THU; case Calendar.FRIDAY: return FRI; case Calendar.SATURDAY: return SAT; default: throw new RuntimeException("There is no Day for " + dayOfWeek); } }
7
private boolean isPassable(Point p) { if (zoneState[((int) p.x)][((int) p.y)] == TileState.PASSABLE_OPAQUE || zoneState[((int) p.x)][((int) p.y)] == TileState.PASSABLE_TRANSPARENT) { return true; } return false; }
2
@Override public void encode(Object bean, CodedOutputStream output) throws ConverterException { try { Collection collection = (Collection) field.get(bean); for (Object obj : collection) { if (obj != null) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); CodedOutputStream innerOutput = CodedOutputStream.newInstance(bout); try { byte[] bytes = (byte[]) itemConverter.encode(obj); innerOutput.writeBytes(1, ByteString.copyFrom(bytes)); innerOutput.flush(); output.writeBytes(id, ByteString.copyFrom(bout.toByteArray())); } catch (IOException e) { throw new ConverterException("Could not write collection '" + field.getName() + "' to byte array!", e); } finally { try { bout.close(); } catch (IOException e) { throw new RuntimeException("Could not close output stream!", e); } } } } } catch (IllegalAccessException | RuntimeException e) { throw new ConverterException("Exception during serialization", e); } }
5
private boolean jj_3_61() { if (jj_scan_token(MINUS)) return true; return false; }
1
@Override public String getColumnName(int column) { String name = "??"; switch (column) { case 0: name = "Name"; break; case 1: name = "Size"; break; case 2: name = "Status"; break; case 3: name = "Down Speed"; break; case 4: name = "Up Speed"; break; case 5: name = "Peers"; break; } return name; }
6
public static synchronized void runInSecurity(SecurityManager m,final Runnable task,int millisecondsTimeOut){ final SecurityManager old=System.getSecurityManager(); final SecurityManager delegate=m; final boolean[]allows={false}; System.setSecurityManager(new SecurityManager() { public void checkPermission(Permission p) { if (p instanceof RuntimePermission && "setSecurityManager".equals(p.getName()) && allows[0]){ return; } else delegate.checkPermission(p); } }); FutureTask<Object> control=new FutureTask<Object>(new Callable<Object>(){ public Object call() throws Exception {task.run();return null;}} ); Thread t=new Thread(control); t.start(); try { control.get(millisecondsTimeOut, TimeUnit.MILLISECONDS);} catch (TimeoutException ex) { throw new Error("The run time of your code was over the fixed time limit");} catch (InterruptedException ex) { throw new Error("We experienced some tecnical difficulties, try to submit your code again.");} catch (ExecutionException ex) { throw new Error(ex.getCause());} finally{ allows[0]=true; System.setSecurityManager(old); control.cancel(true); //log.finer("Stopping thread %s".format(t.getName())); t.stop(); } }
6
public static void main(String[] args) { //Buffer to read the contents from the file. ByteBuffer buffer = ByteBuffer.allocate(100); //The file to read the contents from. Path path = Paths.get("/home/tests/test.txt"); //Creating the asynchronous channel to the file which allows reading and writing of content. try (AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path)) { //Returns a Future instance which can be used to read the contents of the file. Future<Integer> fileResult = asyncChannel.read(buffer, 0); //Waiting for the file reading to complete. Another way to do this is using completionHandler while (!fileResult.isDone()) { System.out.println("Waiting to complete the file reading ..."); } //Print the number of bytes read. System.out.println("Number of bytes read: " + fileResult.get()); //Reset the current position of the buffer to the beginning and the limit to the current position. buffer.flip(); //Decode the contents of the byte buffer. System.out.println("Contents of file: "); System.out.println(Charset.defaultCharset().decode(buffer)); } catch (IOException | InterruptedException | ExecutionException ex) { ex.printStackTrace(); } }
2
@Override public boolean next() { return dataSet != null ? dataSet.next() : false; }
1
@Override public Boolean value(final Double a, final Double b) { if (a == null || b == null || Double.isInfinite(a) || Double.isNaN(a) || Double.isInfinite(b) || Double.isNaN(b)) return false; double denominator = Math.max(Math.abs(a), Math.abs(b)); if (denominator == 0.0) return true; /* * In an attempt to not destroy a large number of significant * digits the code does not subtract a from b, but considers * if the smallest absolute value times the sign of the product * relative to the largest absolute value is close to 1. * See [1]. */ double numerator = Math.min(Math.abs(a), Math.abs(b)) * Math.signum(a * b); return 1.0 - this.getPrecision() <= (numerator / denominator); }
7
private void removeClass(String name) { Class<?> clazz = classes.remove(name); try { if ((clazz != null) && (ConfigurationSerializable.class.isAssignableFrom(clazz))) { Class<? extends ConfigurationSerializable> serializable = clazz.asSubclass(ConfigurationSerializable.class); ConfigurationSerialization.unregisterClass(serializable); } } catch (NullPointerException ex) { // Boggle! // (Native methods throwing NPEs is not fun when you can't stop it before-hand) } }
5
private void waitForThread() { if ((this.thread != null) && this.thread.isAlive()) { try { this.thread.join(); } catch (final InterruptedException e) { this.plugin.getLogger().log(Level.SEVERE, null, e); } } }
3
public List getObjects(String HQLQuery) { List lista = null; try { Query q = cx.createQuery(HQLQuery); lista = q.list(); } catch (Exception e) { } return lista; }
1
public void run() { setName("DB Cleanup"); Logger.log("Running Cleanup..."); try { for (ResultSet rs : activeResults.keySet()) clean(rs); for (PreparedStatement ps : activeStatements) forceClean(ps); DB_CONN.close(); } catch (Throwable t) { } Logger.log("Cleanup Done."); }
3
public Pickable(String value, int x, int y) throws SlickException{ this.x = x * Play.TILESIZE; this.y = y * Play.TILESIZE; this.value = value; if(!value.equals("exit")){ Image[] pSprites = new Image[8]; Image spriteSheet = new Image("res/powerups/" + value + ".png"); for(int i = 0 ; i < pSprites.length; i++){ pSprites[i] = spriteSheet.getSubImage(i*20, 0, 20, 20); } int a = 100, b = 150; animation = new Animation(pSprites, new int[] { a,a,a,a,b,b,b,b } , true); } else{ Image[] pSprites = new Image[2]; pSprites[0] = new Image("res/TP1.png"); pSprites[1] = new Image("res/TP2.png"); animation = new Animation(pSprites, new int[] { 300, 300 } , true); } }
2
public boolean equals(Object other) { if (other instanceof Pair) { Pair<A,B> otherPair = (Pair<A,B>) other; return (( this.first == otherPair.first || ( this.first != null && otherPair.first != null && this.first.equals(otherPair.first))) && ( this.second == otherPair.second || ( this.second != null && otherPair.second != null && this.second.equals(otherPair.second))) ); } return false; }
8
public Date getDataRegistrazione() { return dataRegistrazione; }
0
public void ticking() { if (t.Ring()) { destroy(); } else { x += xVel; y += yVel; setBounds((int) x, (int) y, width, height); } for (int i = 0; i < w.tiles.length; i++) { for (int j = 0; j < w.tiles[0].length; j++) { if (this.intersects(w.tiles[i][j]) && w.tiles[i][j].solid) { destroy(); } } } // TODO : Collision with entityes }
5
private void fillFundamentalData(float[] values, float[] rawData) { for (int k = 0; k < 82; k++) { values[k] = rawData[k]; } values[82] = rawData[172]; values[83] = rawData[173]; values[84] = rawData[174]; // values[85] = values[40] / values[41]; // pet/pef assumed lower is better: // under 1 especially // values[86] = values[69] / values[70]; // 50day/200day assumed higher is // good indicates - recent price // increase // values[87] = values[72] / values[71]; // 10day/300day volume higher // assumed good - recent // increase // in volume }
1
static String getQuadrantXY(String v, String h) { int hor = Integer.valueOf(h); int vert = 1; if (v.equals("b")) { vert = 2; }else if (v.equals("c")) { vert = 3; }else if (v.equals("d")) { vert = 4; }else if (v.equals("e")) { vert = 5; }else if (v.equals("f")) { vert = 6; }else if (v.equals("g")) { vert = 7; }else if (v.equals("h")) { vert = 8; }else if (v.equals("i")) { vert = 9; } return (vert - 1) * 64 + "_" + (hor - 1 )* 64; }
8
public Player checkDiagsWin(){ if (field.getCell(0,0).getPlayer()!= null && field.getCell(0,0).getPlayer() == field.getCell(1,1).getPlayer() && field.getCell(0,0).getPlayer() == field.getCell(2,2).getPlayer()) { return field.getCell(0,0).getPlayer(); }else if (field.getCell(0,2).getPlayer()!= null && field.getCell(0,2).getPlayer() == field.getCell(1,1).getPlayer() && field.getCell(0,2).getPlayer() == field.getCell(2,0).getPlayer()) { return field.getCell(0,2).getPlayer(); }else return null; }
6
@Override public void close () throws IOException { if ( isClosed() ) { return; } super.close(); this.impl.close(); if ( this.boundEndpoint != null ) { NativeUnixSocket.unlink(this.boundEndpoint.getSocketFile()); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownThread); } catch ( IllegalStateException e ) {} }
3
@Override public void onPlayerJoin(PlayerJoinEvent event) { String player = event.getPlayer().getName(); // Alert player of any new sale alerts if (plugin.showSalesOnJoin == true){ List<SaleAlert> saleAlerts = plugin.dataQueries.getNewSaleAlertsForSeller(player); for (SaleAlert saleAlert : saleAlerts) { event.getPlayer().sendMessage(plugin.logPrefix + "You sold " + saleAlert.getQuantity() + " " + saleAlert.getItem() + " to " + saleAlert.getBuyer() + " for "+ saleAlert.getPriceEach() + " each."); plugin.dataQueries.markSaleAlertSeen(saleAlert.getId()); } } // Alert player of any new mail if (plugin.dataQueries.hasMail(player)) { event.getPlayer().sendMessage(plugin.logPrefix + "You have new mail!"); } // Determine permissions int canBuy = 0; int canSell = 0; int isAdmin = 0; if (plugin.permission.has(event.getPlayer(), "wa.canbuy")) { canBuy = 1; } if (plugin.permission.has(event.getPlayer(), "wa.cansell")) { canSell = 1; } if (plugin.permission.has(event.getPlayer(), "wa.webadmin")) { isAdmin = 1; } if (null != plugin.dataQueries.getPlayer(player)) { plugin.log.info(plugin.logPrefix + "Player found - "+ player+ " with permissions: canbuy = " + canBuy + " cansell = " + canSell + " isAdmin = " + isAdmin); // Update permissions plugin.dataQueries.updatePlayerPermissions(player, canBuy, canSell, isAdmin); } }
7
@Override public void run() { //Set console cheat. }
0
public synchronized void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode >= 0 && keyCode < KEY_COUNT) { currentKeys[keyCode] = true; } }
2
private void addNewSymbols() { addSymbol(new Operator("+", 20, true) { @Override public String execute(final Integer a, final Integer b) { return String.valueOf(a + b); } @Override public String execute(Integer a) { // TODO Auto-generated method stub return null; } }); addSymbol(new Operator("-", 20, true) { @Override public String execute(final Integer a, final Integer b) { return String.valueOf(b - a); } @Override public String execute(Integer a) { // TODO Auto-generated method stub return null; } }); addSymbol(new Operator("*", 30, true) { @Override public String execute(final Integer a, final Integer b) { return String.valueOf(a * b); } @Override public String execute(Integer a) { // TODO Auto-generated method stub return null; } }); addSymbol(new Operator("/", 30, true) { @Override public String execute(final Integer a, final Integer b) { return String.valueOf(b / a); } @Override public String execute(Integer a) { // TODO Auto-generated method stub return null; } }); addSymbol(new Operator("%", 30, true) { @Override public String execute(final Integer a, final Integer b) { return String.valueOf(b % a); } @Override public String execute(Integer a) { // TODO Auto-generated method stub return null; } }); addSymbol(new Operator(">", 10, false) { @Override public String execute(final Integer a, final Integer b) { return (b > a) ? String.valueOf(1) : String.valueOf(0); } @Override public String execute(Integer a) { // TODO Auto-generated method stub return null; } }); addSymbol(new Operator(">=", 10, false) { @Override public String execute(final Integer a, final Integer b) { return (b >= a) ? String.valueOf(1) : String.valueOf(0); } @Override public String execute(Integer a) { // TODO Auto-generated method stub return null; } }); addSymbol(new Operator("<", 10, false) { @Override public String execute(final Integer a, final Integer b) { return (b < a) ? String.valueOf(1) : String.valueOf(0); } @Override public String execute(Integer a) { // TODO Auto-generated method stub return null; } }); addSymbol(new Operator("<=", 10, false) { @Override public String execute(final Integer a, final Integer b) { return (b <= a) ? String.valueOf(1) : String.valueOf(0); } @Override public String execute(Integer a) { // TODO Auto-generated method stub return null; } }); addSymbol(new Operator("==", 7, false) { @Override public String execute(final Integer a, final Integer b) { return (a == b) ? String.valueOf(1) : String.valueOf(0); } @Override public String execute(Integer a) { // TODO Auto-generated method stub return null; } }); addSymbol(new Operator("!=", 7, false) { @Override public String execute(final Integer a, final Integer b) { return (a != b) ? String.valueOf(1) : String.valueOf(0); } @Override public String execute(Integer a) { // TODO Auto-generated method stub return null; } }); addSymbol(new Operator("!", 7, false) { @Override public String execute(final Integer a) { if (a > 0) { int result = 1; for (int i = 1; i <= a; i++) { result *= i; } return String.valueOf(result); } return "Factorial must be calculated for unsigned number"; } @Override public String execute(Integer a, Integer b) { // TODO Auto-generated method stub return null; } }); }
8
public final ChannelBuffer getArchivePacketData(int indexId, int archiveId, boolean priority) { byte[] archive = indexId == 255 ? Cache.STORE.getIndex255() .getArchiveData(archiveId) : Cache.STORE.getIndexes()[indexId] .getMainFile().getArchiveData(archiveId); if (archive == null || !priority) return null; int compression = archive[0] & 0xff; int length = ((archive[1] & 0xff) << 24) + ((archive[2] & 0xff) << 16) + ((archive[3] & 0xff) << 8) + (archive[4] & 0xff); int settings = compression; if (!priority) settings |= 0x80; System.out.println(" "+indexId+" "+archiveId); ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(); buffer.writeByte(indexId); buffer.writeInt(archiveId); buffer.writeByte(settings); buffer.writeInt(length); int realLength = compression != 0 ? length + 4 : length; for (int index = 5; index < realLength + 5; index++) { if (buffer.writerIndex() % 512 == 0) { buffer.writeByte(255); } buffer.writeByte(archive[index]); } int v = encryptionValue; if (v != 0) { for (int i = 0; i < buffer.arrayOffset(); i++) buffer.setByte(i, buffer.getByte(i) ^ v); } return buffer; }
9
@Override public void visitBaseType(final char descriptor) { switch (descriptor) { case 'V': declaration.append("void"); break; case 'B': declaration.append("byte"); break; case 'J': declaration.append("long"); break; case 'Z': declaration.append("boolean"); break; case 'I': declaration.append("int"); break; case 'S': declaration.append("short"); break; case 'C': declaration.append("char"); break; case 'F': declaration.append("float"); break; // case 'D': default: declaration.append("double"); break; } endType(); }
8
public void update() { timeStatic++; if(timeStatic >= 9200) timeStatic = 0; if(timeStatic >= type.getSpawnTime()) { currentParticle++; if(currentParticle >= particles.size()) { currentParticle = 0; } Particle p = particles.get(currentParticle); if(!p.spawned) { p.xx = random.nextInt((x + spawnRadiusX) - (x - spawnRadiusX) + 1) + (x - spawnRadiusX); p.yy = random.nextInt((y + spawnRadiusY) - (y - spawnRadiusY) + 1) + (y - spawnRadiusY); p.spawned = true; } timeStatic = 0; } for(int i = 0; i < particles.size(); i++) { particles.get(i).updateIndividual(); } }
5
private void onRead(SocketChannel sc) { try { if (this.ioHandler == null) { logger.error("未绑定ioHandler"); return; } Object msg=null; IoHandler handler = this.ioHandler; IoSession session = socketChannelSessionMap.get(sc); if(this.socketEnum==NioSocketEnum.SERVER){ msg=handler.onRead(sc); if(msg!=null&&msg instanceof NioSessionClient){ System.out.println("服务端读事件1。。。"); NioSessionClient nsc=((NioSessionClient)msg); System.out.println("---------接收序列化对象getUsername-----="+nsc.getUsername()); System.out.println("---------接收序列化对象sc-----="+nsc.getChannel()); System.out.println("---------接收序列化对象socket-----="+nsc.getLocalIp()+":"+nsc.getLocalPort()); //设置服务端的客户信息.... Iterator<SocketChannel> iter = socketChannelSessionMap.keySet().iterator(); while(iter.hasNext()){ SocketChannel key=iter.next(); if(key.socket().getPort()==nsc.getLocalPort()){ System.out.println("---------key.socket().getPort()socket-----="+key.socket().getPort()); NioSession s = (NioSession)socketChannelSessionMap.get(key); s.setUsername(nsc.getUsername()); s.setPassword(nsc.getPassword()); socketChannelSessionMap.put(key, s); } } }else{ System.out.println("服务端读事件2。。。"); this.registerSocket(session, SelectionKey.OP_READ); session.setReceiveMessage(msg); } } if(this.socketEnum==NioSocketEnum.CLIENT){ System.out.println("客户端读事件。。。"); msg = handler.onRead(sc); this.registerSocket(session, SelectionKey.OP_READ); session.setReceiveMessage(msg); } Event event = new Event(EventEnum.E_READ_DATA); event.setSession(session); addEventQueue(event); } catch (NioException e) { // e.printStackTrace(); //此处异常有些古怪 ,关闭后正常,程序后不断进行onRead操作 Event event = new Event(EventEnum.E_CLOSE_SESSION); event.setSc(sc); doCloseSession(event); } catch (Exception e) { // e.printStackTrace(); Event event = new Event(EventEnum.E_CLOSE_SESSION); event.setSc(sc); doCloseSession(event); } }
9
public void close() { parent = null; logQueue = null; if (children.size() != 0) { for (CogLog child : children) child.close(); children.clear(); } }
2
private LocationProfile parseToProfile(Document document, String contextPath) throws CitysearchException { LocationProfile response = null; if (document != null && document.hasRootElement()) { Element locationElem = document.getRootElement().getChild(LOCATION); if (locationElem != null) { response = new LocationProfile(); Element addressElem = locationElem.getChild(ADDRESS); if (addressElem != null) { response.setStreet(addressElem.getChildText(STREET)); response.setCity(addressElem.getChildText(CITY)); response.setState(addressElem.getChildText(STATE)); response.setPostalCode(addressElem .getChildText(POSTAL_CODE)); } Element contactInfo = locationElem.getChild(CONTACT_INFO); if (contactInfo != null) { response.setPhone(contactInfo.getChildText(PHONE)); } Element urlElm = locationElem.getChild(URLS); if (urlElm != null) { response.setProfileUrl(urlElm.getChildText(PROFILE_URL)); response.setSendToFriendUrl(urlElm .getChildText(SEND_TO_FRIEND_URL)); response.setReviewsUrl(urlElm.getChildText(REVIEWS_URL)); response.setWebsiteUrl(urlElm.getChildText(WEBSITE_URL)); response.setMenuUrl(urlElm.getChildText(MENU_URL)); response.setReservationUrl(urlElm .getChildText(RESERVATION_URL)); response.setMapUrl(urlElm.getChildText(MAP_URL)); } Element review = locationElem.getChild(REVIEWS); if (review != null) { response.setReviewCount(review .getChildText(TOTAL_USER_REVIEWS)); } response.setImageUrl(getImage(locationElem.getChild(IMAGES), locationElem.getChild(CATEGORIES), contextPath)); } } return response; }
7
public static void main(String[] args) { // TODO Auto-generated method stub jpcap.NetworkInterface[] devices = JpcapCaptor.getDeviceList(); for (int i = 0; i < devices.length; i++) { //print out its name and description System.out.println(devices[i]); System.out.println(i+": "+devices[i].name + "(" + devices[i].description+")"); System.out.println(" datalink: "+devices[i].datalink_name + "(" + devices[i].datalink_description+")"); //print out its MAC address System.out.print(" MAC address:"); for (byte b : devices[i].mac_address) System.out.print(Integer.toHexString(b&0xff) + ":"); System.out.println(); /* InetAddress s = null; //print out its IP address, subnet mask and broadcast address for (NetworkInterfaceAddress a : devices[i].addresses) s = a.address; System.out.println(s.getAddress()); // System.out.println(s); // System.out.println(" address:"+a.address + " " + a.subnet + " "+ a.broadcast); byte[] addressArray; */ // System.out.println(" address:"+a.address); } }
2
private PreparedStatement buildInsertStatement(Connection conn_loc, String tableName, List colDescriptors) throws SQLException { StringBuffer sql = new StringBuffer("INSERT INTO "); (sql.append(tableName)).append(" ("); final Iterator i = colDescriptors.iterator(); while (i.hasNext()) { (sql.append((String) i.next())).append(", "); } sql = new StringBuffer((sql.toString()).substring(0, (sql.toString()).lastIndexOf(", ")) + ") VALUES ("); for (int j = 0; j < colDescriptors.size(); j++) { sql.append("?, "); } final String finalSQL = (sql.toString()).substring(0, (sql.toString()).lastIndexOf(", ")) + ")"; //System.out.println(finalSQL); return conn_loc.prepareStatement(finalSQL); }
2
@Override public List<FullMemberRecord> getFullMemberList() { final List<FullMemberRecord> members=new Vector<FullMemberRecord>(); final List<MemberRecord> subMembers=filterMemberList(CMLib.database().DBReadClanMembers(clanID()), -1); for(final MemberRecord member : subMembers) { if(member!=null) { final MOB M=CMLib.players().getPlayer(member.name); if(M!=null) { final boolean isAdmin=CMSecurity.isASysOp(M) || M.phyStats().level() > CMProps.getIntVar(CMProps.Int.LASTPLAYERLEVEL); if(M.lastTickedDateTime()>0) members.add(new FullMemberRecord(member.name,M.basePhyStats().level(),member.role,M.lastTickedDateTime(),member.mobpvps,member.playerpvps,isAdmin)); else members.add(new FullMemberRecord(member.name,M.basePhyStats().level(),member.role,M.playerStats().getLastDateTime(),member.mobpvps,member.playerpvps,isAdmin)); } else { final PlayerLibrary.ThinPlayer tP = CMLib.database().getThinUser(member.name); if(tP != null) { final boolean isAdmin=CMSecurity.isASysOp(tP) || tP.level() > CMProps.getIntVar(CMProps.Int.LASTPLAYERLEVEL); members.add(new FullMemberRecord(member.name,tP.level(),member.role,tP.last(),member.mobpvps,member.playerpvps,isAdmin)); } else { Log.warnOut("Clan "+clanID()+" removed member '"+member.name+"' due to being nonexistant!"); CMLib.database().DBUpdateClanMembership(member.name, clanID(), -1); } } } } return members; }
7
private boolean handleSelectionRollover(SelectionRolloverDirection direction) { for (SelectionRolloverListener listener : selectionRolloverListeners) { if(listener.selectionRollingOver(direction)) return true; } return false; }
2
@Override public void move(Excel start, Excel finish) { if (start.getX() == begin.getX() && start.getY() == begin.getY()) { begin = finish; setColoredExes(); } if (start.getX() == end.getX() && start.getY() == end.getY()) { end = finish; setColoredExes(); } }
4
private static int asInt(Object obj){ if(obj == null){ return 0; }else if(obj instanceof Number){ return ((Number)obj).intValue(); }else if(obj instanceof Character){ return ((Character)obj).charValue(); }else if(obj instanceof Boolean){ return ((Boolean)obj).booleanValue()?1:0; }else if(obj instanceof String){ try{ return Integer.parseInt((String)obj); }catch(NumberFormatException e){} } return 0; }
7
public void addMessage(InetAddress source, InetAddress destination, String body, long timestamp, boolean private_msg) { PaneTab selectedTab = null; if (destination.equals(this.client.getOwnUser().getIP())) { if (getTab(source) != null || AddIncomingTab(source)) { selectedTab = getTab(source); } } if (source.equals(this.client.getOwnUser().getIP()) || destination.equals(this.client.getMulticastAddress())) { selectedTab = getTab(destination); } if (selectedTab != null) { JTextArea chatArea = selectedTab.getTextArea(); User sourceUser = client.getUser(source); String userName = source.getHostName().replace(".local", ""); if (sourceUser != null) { userName = sourceUser.getName(); } String result = "[" + convertTime(timestamp) + "] " + userName + ": " + body + "\n"; chatArea.append(result); chatArea.setCaretPosition(chatArea.getDocument().getLength()); } }
7
public static String waitAnswer(){ while(true){ try { String input = reader.readLine(); if(input.matches("(^[a-h][1-8]$)|(^[9][9]$)|(^[0][0])$")) return input; else{ Printer.invalidInput(); continue; } } catch(IOException e) { e.printStackTrace(); System.exit(1); } break; } return null; }
3
public static void hexToBin(String slovo) { StringBuffer s = new StringBuffer(4 * slovo.length()); String[] table = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001"}; for (int i = 0; i < slovo.length(); i++) { switch (slovo.toLowerCase().charAt(i)) { case 'a' : s.append("1010");break; case 'b' : s.append("1011");break; case 'c' : s.append("1100");break; case 'd' : s.append("1101");break; case 'e' : s.append("1110");break; case 'f' : s.append("1111");break; default : s.append(table[(Integer.valueOf(slovo.toLowerCase().charAt(i)).intValue() - 48)]);break; } } System.out.println("hex: " + s); }
7
public String getContent(String name) { if (name.equals("l_graph")) { return player.graph.getTypeString(); } else if (name.equals("l_program")) { return player.model.program.getString(); } else if (name.equals("l_running")) { String s = player.getSendSpeedString(5) + " : " + player.getSendSpeedString(-5); if (player.state == RunState.running) return "Playing " + s; else if (player.state == RunState.paused) return "Paused (" + s + ")"; else return "Stopped (" + s + ")"; } else { return name; } }
5
@Override public void valueChanged(ListSelectionEvent event) { if (gui.connected & firstloaded & !event.getValueIsAdjusting()) { if (!settingRow) { settingRow = true; if (event.getSource().equals( mainTablePane.getListSelectionModel())) { for (TablePane reference : referenceTable) { try { reference.setSelectedRow(mainTablePane); } catch (SQLException e) { gui.handleSQLException(e); } finally { settingRow = false; } } } else { for (TablePane reference : referenceTable) { if (reference.getListSelectionModel().equals( event.getSource())) { try { mainTablePane.setReferencedID(reference); } catch (SQLException e) { if (e.getErrorCode() == 0) { // no current row selected } else { gui.handleSQLException(e); } } finally { settingRow = false; } } } } } } }
9
@Override public int hashCode() { int hash = 3; hash = 11 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; }
1
public void listenSocket() { long deltaTime = System.currentTimeMillis() - lastDataTime; if(!this.socket.isClosed() && deltaTime<TIMEOUT) { int currentBytesAvailable = 0; try { currentBytesAvailable = inputStream.available(); } catch (IOException e) { e.printStackTrace(); } if(currentBytesAvailable > 0) { //log.debug("receive " + currentBytesAvailable + " bytes"); read(); } } else { log.debug("time out"); internalClose(); } }
4
public boolean match(ItemStack item) { if (getId() != null && getId() == item.getTypeId()) { if (dataId == 0 || dataId == item.getDurability()) { return true; } } Material mat = Material.getMaterial(name); return (mat != null && mat.getId() == item.getTypeId()); }
5
public static void main(String[] args) throws Exception { String baseFilename = args[0]; int nShards = Integer.parseInt(args[1]); String fileType = (args.length >= 3 ? args[2] : null); /* Create shards */ FastSharder sharder = createSharder(baseFilename, nShards); sharder.setAllowSparseDegreesAndVertexData(false); if (baseFilename.equals("pipein")) { // Allow piping graph in sharder.shard(System.in); } else { sharder.shard(new FileInputStream(new File(baseFilename)), fileType); } /* Run engine */ GraphChiEngine<Integer, Integer> engine = new GraphChiEngine<Integer, Integer>(baseFilename, nShards); engine.setEdataConverter(new IntConverter()); engine.setVertexDataConverter(new IntConverter()); engine.setModifiesInedges(false); // Important optimization engine.run(new SmokeTest(), 5); /* Test vertex iterator */ Iterator<VertexIdValue<Integer>> iter = VertexAggregator.vertexIterator(engine.numVertices(), baseFilename, new IntConverter(), engine.getVertexIdTranslate()); int i=0; while(iter.hasNext()) { VertexIdValue<Integer> x = iter.next(); int internalId = engine.getVertexIdTranslate().forward(x.getVertexId()); int expectedValue = internalId + 4; if (expectedValue != x.getValue()) { throw new IllegalStateException("Expected internal value to be " + expectedValue + ", but it was " + x.getValue() + "; internal id=" + internalId + "; orig=" + x.getVertexId()); } if (i % 10000 == 0) { logger.info("Scanning vertices: " + i); } i++; } if (i != engine.numVertices()) throw new IllegalStateException("Error in iterator: did not have numVertices vertices: " + i + "/" + engine.numVertices()); logger.info("Ready."); }
6
public UpdateTimeCheck() { try { in=new BufferedReader(new FileReader(new File(Main.SAVEFILES[0]))); String line; while((line=in.readLine())!=null){ if(line.contains(TIMEMARK)){ // System.out.println(line); regexMatcher=timeregex.matcher(line); if(regexMatcher.find()){ updatetime=regexMatcher.group(1); String timeinfo[]=updatetime.split("\\."); remotetime=timeinfo[0]+"-"+timeinfo[1]+"-"+timeinfo[2]; setDetailTime(); } } } System.out.println("Remotetime: "+remotetime); // while((line=in.readLine())!=null){ // if(line.contains(";version")){ // remotetime=line.substring(line.indexOf('=')+1); // DETAILTIME=remotetime.substring(0,4)+"-"+remotetime.substring(4,6)+"-"+remotetime.substring(6,8)+" "+remotetime.substring(8,10)+":"+remotetime.substring(10,12)+":00"; // remotetime=DETAILTIME.substring(0,DETAILTIME.indexOf(' ')); // System.out.println(remotetime+" "+DETAILTIME); // } // } in.close(); System.out.println("LocalTime: "+getLocalTime()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
5
public boolean isValidElementContent() { boolean isValid=true; for(FtanValue value: values) { if(!(value instanceof FtanString) && !(value instanceof FtanElement)) { isValid=false; break; } } return isValid; }
3
public String toShortString() { switch (this) { case IssuerSecurityDomain: return "ISD"; case Application: return "App"; case SecurityDomain: return "SeD"; case ExecutableLoadFiles: return "Exe"; case ExecutableLoadFilesAndModules: return "ExM"; } return "???"; }
5
public void emulateStep() { String code = (String) view.getMemoryTable().getValueAt(programCounter, 0); if (code.equals("") && !code.equals("0000")) { getBearing(); code = (String) view.getMemoryTable().getValueAt(programCounter, 0); } if (!code.equalsIgnoreCase("0000")) { boolean good = executeNextStep(code); setRegisters(); counter++; if (code.startsWith("1")) { if (findNegative(code.substring(0, 4))) { view.setNegBit(true); } } if (!good) { EmulatorControl.addError(new EmulatorError(">>ERROR<< AN ERROR OCCURED WHEN EMULATING", 0)); return; } } else { executeNextStep(code); ran = true; } }
6
public void setManPage(String manPage) { ManPage page = ManPage.HELP; if (manPage != null && !manPage.isEmpty()) { try { page = ManPage.valueOf(manPage.toUpperCase()); } catch (IllegalArgumentException e) { page = ManPage.HELP; } } this.manPage = page; }
3
final void process(Socket clnt) throws IOException { InputStream in = new BufferedInputStream(clnt.getInputStream()); String cmd = readLine(in); logging(clnt.getInetAddress().getHostName(), new Date().toString(), cmd); while (skipLine(in) > 0){ } OutputStream out = new BufferedOutputStream(clnt.getOutputStream()); try { doReply(in, out, cmd); } catch (BadHttpRequest e) { replyError(out, e); } out.flush(); in.close(); out.close(); clnt.close(); }
2
private static String getArgs(Class<?> s) { if (s.isArray()) { return "array."; } String t = s.getName().toLowerCase().replace("java.lang.", "").replace("java.util.", ""); switch (t) { case "long": case "int": case "double": return "number."; case "arraylist": return "array."; case "date": case "string": return t + "."; default: return "object."; } }
8
private void routeReplyReceived(RREP rrep, String senderNodeAddress) { //rrepRoutePrecursorAddress is an local int used to hold the next-hop address from the forward route String rrepRoutePrecursorAddress = ""; //Create route to previous node with unknown seqNum (neighbour) if(routeTableManager.createForwardRouteEntry( senderNodeAddress, senderNodeAddress, Constants.UNKNOWN_SEQUENCE_NUMBER, 1, true)){ Debug.print("Receiver: RREP where received and route to: "+senderNodeAddress+" where created with destSeq: "+Constants.UNKNOWN_SEQUENCE_NUMBER); } Debug.print("Receiver: RREP get"); rrep.incrementHopCount(); if (!rrep.getSourceAddress().equals(srcIPAddress)) { //forward the RREP, since this node is not the one which requested a route sender.queuePDUmessage(rrep); // handle the first part of the route (reverse route) - from this node to the one which originated a RREQ try { //add the sender node to precursors list of the reverse route ForwardRouteEntry reverseRoute = routeTableManager.getForwardRouteEntry(rrep.getSourceAddress()); reverseRoute.addPrecursorAddress(senderNodeAddress); rrepRoutePrecursorAddress = reverseRoute.getNextHop(); } catch (AodvException e) { //no reverse route is currently known so the RREP is not sure to reach the originator of the RREQ } } // handle the second part of the route - from this node to the destination address in the RREP try { ForwardRouteEntry oldRoute = routeTableManager.getForwardRouteEntry(rrep.getDestinationAddress()); if(!rrepRoutePrecursorAddress.equals("")){ oldRoute.addPrecursorAddress(rrepRoutePrecursorAddress); } //see if the RREP contains updates (better seqNum or hopCountNum) to the old route routeTableManager.updateForwardRouteEntry(oldRoute, new ForwardRouteEntry( rrep.getDestinationAddress(), senderNodeAddress, rrep.getHopCount(), rrep.getDestinationSequenceNumber(), oldRoute.getPrecursors())); } catch (NoSuchRouteException e) { ArrayList<String> precursorNode = new ArrayList<String>(); if(!rrepRoutePrecursorAddress.equals("")){ precursorNode.add(rrepRoutePrecursorAddress); } routeTableManager.createForwardRouteEntry( rrep.getDestinationAddress(), senderNodeAddress, rrep.getDestinationSequenceNumber(), rrep.getHopCount(), precursorNode, true); } catch (RouteNotValidException e) { //FIXME den er gal paa den Debug.print("Receiver: FATAL ERROR"); try { //update the previously known route with the better route contained in the RREP routeTableManager.setValid(rrep.getDestinationAddress(), rrep.getDestinationSequenceNumber()); if(!rrepRoutePrecursorAddress.equals("")){ routeTableManager.getForwardRouteEntry(rrep.getDestinationAddress()).addPrecursorAddress(rrepRoutePrecursorAddress); } }catch (AodvException e1) { } } }
9
public ArrayList<Sijainti> viereisetSijainnit() { Sijainti keski = sijainti(); ArrayList<Sijainti> viereiset = new ArrayList<Sijainti>(); for(int y = -1; y <= 1; y++) for(int x = -1; x <= 1; x++) if(x != 0 || y != 0) viereiset.add(new Sijainti(keski.x() + x, keski.y() + y)); return viereiset; }
4
private void calculateEnabledState(Document doc) { if (doc == null) { this.tree = null; if (this.isVisible()) { attPanel.update(this); } } else if (doc.getTree() != this.tree) { this.tree = doc.getTree(); if (this.isVisible()) { attPanel.update(this); } } }
4
private void funcionmedicamentosFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_funcionmedicamentosFieldKeyTyped // TODO add your handling code here: if (!Character.isLetter(evt.getKeyChar()) && !Character.isISOControl(evt.getKeyChar()) && !Character.isWhitespace(evt.getKeyChar())) { Toolkit.getDefaultToolkit().beep(); evt.consume(); } if(funcionmedicamentosField.getText().length() == 45) { Toolkit.getDefaultToolkit().beep(); evt.consume(); JOptionPane.showMessageDialog(this, "Funcion de medicamento demasiado larga", "ADVERTENCIA", WIDTH); } }//GEN-LAST:event_funcionmedicamentosFieldKeyTyped
4
public static <E> ArrayList<E> newArrayList(E... objects){ ArrayList<E> list=new ArrayList<E>(); for (E e : objects) { list.add(e); } return list; }
1
@Override public void unInvoke() { if(canBeUninvoked()) { if(affected instanceof MOB) { final MOB mob=(MOB)affected; if((buildingI!=null)&&(!aborted)) { if(messedUp) { if(activity == CraftingActivity.MENDING) messedUpCrafting(mob); else if(activity == CraftingActivity.LEARNING) { commonEmote(mob,L("<S-NAME> fail(s) to learn how to make @x1.",buildingI.name())); buildingI.destroy(); } else commonEmote(mob,L("<S-NAME> mess(es) up smithing @x1.",buildingI.name())); } else if(activity==CraftingActivity.LEARNING) { deconstructRecipeInto( buildingI, recipeHolder ); buildingI.destroy(); } else { if(activity == CraftingActivity.MENDING) { buildingI.setUsesRemaining(100); CMLib.achievements().possiblyBumpAchievement(mob, AchievementLibrary.Event.MENDER, 1, this); } else { dropAWinner(mob,buildingI); CMLib.achievements().possiblyBumpAchievement(mob, AchievementLibrary.Event.CRAFTING, 1, this); } } } buildingI=null; activity = CraftingActivity.CRAFTING; } } super.unInvoke(); }
9
private Node normaliseRightResidualPath() throws MVDException { Node arcTo = arc.to; arc.to.removeIncoming( arc ); if ( rightSubArc != null ) { arcTo.addIncoming( rightSubArc ); arcTo = new Node(); arcTo.addOutgoing( rightSubArc ); } if ( rightSubGraph == null ) { if ( arcTo != graph.end ) rightSubGraph = createEmptyRightSubgraph(); // else nothing to do } else // rightSubGraph != null { if ( arcTo == graph.end ) { Arc a = createEmptyArc( version ); arcTo.addIncoming( a ); arcTo = new Node(); arcTo.addOutgoing( a ); } // else there's already a residual path } return arcTo; }
4
public static URL extractJarFileURL(URL jarUrl) throws MalformedURLException { String urlFile = jarUrl.getFile(); int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR); if (separatorIndex != -1) { String jarFile = urlFile.substring(0, separatorIndex); try { return new URL(jarFile); } catch (MalformedURLException ex) { // Probably no protocol in original jar URL, like "jar:C:/mypath/myjar.jar". // This usually indicates that the jar file resides in the file system. if (!jarFile.startsWith("/")) { jarFile = "/" + jarFile; } return new URL(FILE_URL_PREFIX + jarFile); } } else { return jarUrl; } }
3