text
stringlengths
14
410k
label
int32
0
9
public static SanitaryFacilityEnumeration fromValue(String v) { for (SanitaryFacilityEnumeration c: SanitaryFacilityEnumeration.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); }
2
@SuppressWarnings("unchecked") @EventHandler public void onSignEdit(SignChangeEvent event){ for(String line:event.getLines()){ for(String word:simplify(ChatColor.stripColor(line)).split("[,./:;-`~()\\[\\]{}+ ]")) if(wordList.fuzzilyContains(word)){ swearReport(event.getPlayer().getName()); event.getPlayer().sendMessage(config.getString("swear.sign.message").replace("<WARNING>", Integer.toString(plist.getInt("tracker."+event.getPlayer().getName()))+Ordinal.getOrdinal(plist.getInt("tracker."+event.getPlayer().getName()))).replace("<PLAYER>", event.getPlayer().getDisplayName())); if(config.getString("swear.sign.mode").equalsIgnoreCase("cancel")){ event.setCancelled(true); }else if(config.getString("swear.sign.mode").equalsIgnoreCase("censor")){ for(int i=0;i<3;i++){ line.replaceAll("(?i:"+word+")", ChatColor.RESET+bleepColor+Bleeper.generateBleep(word,(List<String>) config.getList("swear.bleep.chars"))+ChatColor.RESET); event.setLine(i, line); } } } } }
6
private static void runEntityProcessorThread() { Thread rawEntityConsumerThread = new Thread(new RawEntityConsumer()); rawEntityConsumerThread.start(); }
0
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new menu().setVisible(true); } }); }
6
public String getEmployeeId() { return employeeId; }
0
public ListGroup(TKey key) { this._key = key; }
0
public static void toggleExpansion(Node currentNode, JoeTree tree, OutlineLayoutManager layout, boolean shiftDown) { JoeNodeList nodeList = tree.getSelectedNodes(); for (int i = 0, limit = nodeList.size(); i < limit; i++) { Node node = nodeList.get(i); if (node.isExpanded()) { node.setExpanded(false, !shiftDown); } else { if (shiftDown) { node.ExpandAllSubheads(); } else { node.setExpanded(true, true); } } } layout.draw(currentNode, OutlineLayoutManager.ICON); }
3
public void processEntity(Entity entity, long elapsedTime) { Shoot shootComponent = entity.getComponent(Shoot.class); // Decrease their delayed shooting time so that they may be able to // fire again shootComponent.currentWaitingTime -= elapsedTime; if (shootComponent.shootRequired && shootComponent.currentWaitingTime <= 0) { // Create an instance of their bullet template Entity spawnedBullet = shootComponent.bulletTemplate.createEntity(); Spatial bulletSpatial = spawnedBullet.getComponent(Spatial.class); Spatial entitySpatial = entity.getComponent(Spatial.class); // Update the bullet's position to where it has been fired from, // and set the rotation to be the same as that which fired it bulletSpatial.x = entitySpatial.x; bulletSpatial.y = entitySpatial.y; bulletSpatial.setRotation(entitySpatial.getRotation()); // Set the velocity logic which is stored within the entity's // Shoot component Velocity bulletVelocity = spawnedBullet.getComponent(Velocity.class); bulletVelocity.acceleration = bulletVelocity.currentVelocity = bulletVelocity.velocityCap = shootComponent.bulletSpeed; // Give the bullet the damage details, this is what will be used // to reduce the health of an entity it collides with (assumming // it has a Health component) Damage bulletDamageComponent = spawnedBullet.getComponent(Damage.class); bulletDamageComponent.damageGiven = shootComponent.bulletDamage; // Add the timd delete component, so that it will be removed from // the system after the required duration in milliseconds has passed spawnedBullet.addComponentNoRefresh(new TimedDelete(shootComponent.bulletLife)); // Start the bullet accelerating as expected, the VelocitySystem // will handle this for us bulletVelocity.currentState = Velocity.VelocityState.Accelerate; // Place a the tag of the entity that fired the bullet so that // other systems can base logic around the it. For instance the // damage system may consider if a bullet can hurt the owner, or for // things like friendly fire possibly Bullet bulletComponent = spawnedBullet.getComponent(Bullet.class); bulletComponent.ignoreOwnerTag = entity.getComponent(NameTag.class); // Reset the shootRequired to false, as we've dealt with this // bullet now. If we didn't do this it would continuously shoot. // At this point we also reset the shooting time so that another // bullet can't be fired right away shootComponent.shootRequired = false; shootComponent.currentWaitingTime = shootComponent.requiredWaitingTime; } }
2
public static boolean isWin7() { if (os == null) { getOS(); } return (os.contains(WIN7_REGEX)); }
1
public int GetNextbusStop() { //get the next bus stop to visit return nextBusStop; }
0
@Override public void applyDisguise(Collection<Player> players) { UUID uid = new UUIDRetriever(name).getUUID(); GameProfile gp = new GameProfile(uid == null ? UUID.randomUUID() : uid, name); UUIDRetriever.setSkin(gp); EntityPlayer playerEntity = ((CraftPlayer) getPlayer()).getHandle(); EntityPlayer ep = this.ep == null ? this.ep = new EntityPlayer(playerEntity.server, (WorldServer) playerEntity.world, gp, new PlayerInteractManager(playerEntity.world)) : this.ep; ep.inventory = playerEntity.inventory; ep.locX = playerEntity.locX; ep.locY = playerEntity.locY; ep.locZ = playerEntity.locZ; ep.yaw = playerEntity.yaw; ep.pitch = playerEntity.pitch; PacketPlayOutEntityDestroy destroy = new PacketPlayOutEntityDestroy( playerEntity.getId()); PacketPlayOutPlayerInfo infoRemove = new PacketPlayOutPlayerInfo( EnumPlayerInfoAction.REMOVE_PLAYER, playerEntity); PacketPlayOutPlayerInfo infoAdd = new PacketPlayOutPlayerInfo( EnumPlayerInfoAction.ADD_PLAYER, ep); PacketPlayOutNamedEntitySpawn spawn = new PacketPlayOutNamedEntitySpawn( ep); for (Player p : players) { if (p == getPlayer()) continue; EntityPlayer aep = ((CraftPlayer) p).getHandle(); PlayerConnection pc = aep.playerConnection; pc.sendPacket(destroy); pc.sendPacket(infoRemove); pc.sendPacket(infoAdd); pc.sendPacket(spawn); } }
4
public static boolean kick(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.kick")){ //Checking if they have the permission node to proceed s.sendMessage(ChatColor.RED + "You lack sufficient permissions to kick a player from a guild. Talk to your server admin if you believe this is in error."); return false; } if(!Util.isInGuild(s) == true){ //Checking if they're already in a guild s.sendMessage(ChatColor.RED + "You need to be in a guild to use this command."); return false; } if(args.length > 2 || args.length == 1){ //Checking if the create command has proper args s.sendMessage(ChatColor.RED + "Incorrectly formatted guild kick command! Proper syntax is: \"/guild kick <player name>\""); return false; } if(Util.isGuildLeader(s.getName()) == false && Util.isOfficer(s) == false){ //Checking if the player is the guild leader s.sendMessage(ChatColor.RED + "You need to be the guild leader or officer to use that command."); return false; } targetPlayersName = args[1].toLowerCase(); targetPlayersGuild = Main.players.getString("Players." + targetPlayersName + ".Current_Guild"); sendersPlayerName = s.getName().toLowerCase(); sendersGuild = Main.players.getString("Players." + sendersPlayerName + ".Current_Guild"); if(!sendersGuild.matches(targetPlayersGuild)){ //Checking if the player is the guild leader s.sendMessage(ChatColor.RED + "That player isn't in the same guild as you, you can't kick them from their guild!"); return false; } currRosterSize = Main.guilds.getInt("Guilds." + sendersGuild + ".Roster_Size"); updRosterSize = currRosterSize - 1; Main.players.set("Players." + targetPlayersName + ".Guild_Leader", false); Main.players.set("Players." + targetPlayersName + ".Current_Guild", "None"); Main.players.set("Players." + targetPlayersName + ".Current_Rank", 0); Main.players.set("Players." + targetPlayersName + ".Guild_Contributions", 0); Main.players.set("Players." + targetPlayersName + ".Member_Since", "N/A"); Main.players.set("Players." + targetPlayersName + ".Current_Invitation", "N/A"); Main.guilds.set("Guilds." + sendersGuild + ".Roster_Size", updRosterSize); s.sendMessage(ChatColor.DARK_GREEN + "You kicked the user " + targetPlayersName + " from the guild " + sendersGuild + "."); Main.saveYamls(); return true; }
8
private void updateChanges() { Map<Integer, BoxState> changes = game.getLastChanges(); for (Map.Entry<Integer, BoxState> entry : changes.entrySet()) { int index = entry.getKey(); BoxState state = entry.getValue(); switch (state) { case SAFE: setButton(index, false, null, Integer.toString(game.getMapValue(index))); break; case MINE: setButton(index, false, mineIcon, ""); break; case UNEXPLORED: setButton(index, true, null, ""); break; case FLAGGED: setButton(index, true, flagIcon, ""); break; default: break; } } minesLeft.setText(Integer.toString(game.minesLeft())); if (game.isGameOver()) { newGameDialog("Game Over!"); } if (game.isWon()) { newGameDialog("You win!"); } }
7
public void getNewAbility() { // TODO Auto-generated method stub if(this.getLevel() == 2) { //lightning strike //deals more damage the less hp the opponent has addAbility(new Lightning()); } if(this.getLevel() == 4) { //mass fireball //aoe hits everything addAbility(new MassFireball()); } if(this.getLevel() == 7) { //drain life //damage + heal addAbility(new DrainLife()); } if(this.getLevel() == 10) { //thunderstorm //aoe hits everything addAbility(new LightningStorm()); } }
4
private Object callMethod(Method method, String o, Object arg, List<Object> initParametersProcessed) throws TemplateException { if (!((Class<?>) method.getDeclaringClass()).isAssignableFrom(((Class<?>) arg.getClass()))) { throw new TemplateException("Unable to render '\u2026:%s' at position '%s'. The function %s expects %s. It receives %s.", getIdentifier(), cursor.getPosition(), o, method.getDeclaringClass().getCanonicalName(), arg.getClass().getCanonicalName()); } else { if (initParametersProcessed.size() != method.getParameterTypes().length) { throw new TemplateException("Unable to render '\u2026:%s' at position '%s'. The function %s expects %d init-parameter(s) but receives %d init-parameter(s).", getIdentifier(), cursor.getPosition(), o, method.getParameterTypes().length, initParametersProcessed.size()); } } Exception occurred; try { return method.invoke(arg, initParametersProcessed.toArray()); } catch (IllegalAccessException e) { occurred = e; } catch (IllegalArgumentException e) { occurred = e; } catch (InvocationTargetException e) { occurred = e; } for (int i = 0; i < initParametersProcessed.size(); i++) { Object tmpVlue = initParametersProcessed.get(i); if (!isAssignable(method.getParameterTypes()[i], tmpVlue.getClass())) { throw new TemplateException("Unable to render '\u2026:%s' at position '%s'. The function %s expects %s for parameter #%d. It receives %s.", getIdentifier(), cursor.getPosition(), o, method.getParameterTypes()[i].getCanonicalName(), i + 1, tmpVlue.getClass().getCanonicalName()); } } throw new TemplateException(occurred, "Unable to determine reason."); }
9
public static Point calculateIntersectingPoint(Line lineOne, Line lineTwo) { double a1 = lineOne.getA(); double b1 = lineOne.getB(); double c1 = lineOne.getC(); double a2 = lineTwo.getA(); double b2 = lineTwo.getB(); double c2 = lineTwo.getC(); // two lines are parallel OR equal if (a1 == a2 && b1 == b2 || a1 == a2 && b1 == b2 && c1 == c2) { return null; } double x; double y; // the same way to calculate intersect point, but without dividing by zero if (a2 != 0) { x = -((c2 / a2) + b2 * (a1 * c2 - a2 * c1) / (a2 * (a2 * b1 - a1 * b2))); y = (a1 * c2 - a2 * c1) / (a2 * b1 - a1 * b2); } else { x = -((c1 / a1) + b1 * (a2 * c1 - a1 * c2) / (a1 * (a1 * b2 - a2 * b1))); y = (a2 * c1 - a1 * c2) / (a1 * b2 - a2 * b1); } return new Point(x, y); }
6
private void CboxOuderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CboxOuderActionPerformed CboxGezin.removeAllItems(); if (!CboxOuder.getSelectedItem().equals("Onbekend")) { Persoon p = (Persoon) CboxOuder.getSelectedItem(); if (p != null) { for (Iterator<Gezin> q = p.getGezinnen(); q.hasNext();) { this.CboxGezin.addItem(q.next()); } } } }//GEN-LAST:event_CboxOuderActionPerformed
3
protected boolean checkForCollision(int[][] tempBlock, int tempX, int tempY) { clearMovingBlocks(tempBlock, 1); for (int i = 0; i < tempBlock.length; ++i) { for (int j = 0; j < tempBlock[i].length; ++j) { //Testing if the block is in the bounds of gamestatus if (i + tempX>-1 && i + tempX < this.status.length && i + tempX > -1 && j + tempY < this.status[0].length && tempX > -1) { if (this.status[i + tempX][j + tempY] == 1 && tempBlock[i][j] == 1) { return true; } } else { return true; } } } return false; }
9
public String [] getOptions() { String [] options = new String [9]; int current = 0; options[current++] = "-X"; options[current++] = "" + getCrossVal(); if (m_evaluationMeasure != EVAL_DEFAULT) { options[current++] = "-E"; switch (m_evaluationMeasure) { case EVAL_ACCURACY: options[current++] = "acc"; break; case EVAL_RMSE: options[current++] = "rmse"; break; case EVAL_MAE: options[current++] = "mae"; break; case EVAL_AUC: options[current++] = "auc"; break; } } if (m_useIBk) { options[current++] = "-I"; } if (m_displayRules) { options[current++] = "-R"; } while (current < options.length) { options[current++] = ""; } return options; }
8
public void initInterfaceJeu(){ //HIGHSCORE bestScore = new BPBestScore(); //STATISTIQUE statistique = new BPStatistiques(); // JEU jeu = new PJeuTetris(10,20,new Dimension((int) (this.getWidth()*0.6), (int) (this.getHeight()*0.925))); if (couperSon.isSelected()){ mute = true; jeu.setMute(true); } jeu.start(2); enableDifficulte(true); }
1
@Test public void execute() { LOGGER.info("Starting test execute method..."); AreaLineManager gardenLineManager = new AreaLineManager(); gardenLineManager.initCommands(); String result; // 1. null input LOGGER.debug("testing null input..."); try { result = gardenLineManager.execute(null); assertEquals(result, ""); } catch (Exception e) { LOGGER.error("Unexpected error : " + e.getLocalizedMessage(), e); fail("Unexpected error : " + e.getLocalizedMessage()); } // 2. empty input LOGGER.debug("testing empty input..."); try { result = gardenLineManager.execute(""); assertEquals(result, ""); } catch (Exception e) { LOGGER.error("Unexpected error : " + e.getLocalizedMessage(), e); fail("Unexpected error : " + e.getLocalizedMessage()); } // 3. exit command LOGGER.debug("testing exit command..."); try { result = gardenLineManager.execute(gardenLineManager.getExitCommand()); assertNull(result); } catch (Exception e) { LOGGER.error("Unexpected error : " + e.getLocalizedMessage(), e); fail("Unexpected error : " + e.getLocalizedMessage()); } // 4. help command LOGGER.debug("testing help command..."); try { result = gardenLineManager.execute(gardenLineManager.getHelpCommand()); assertEquals(helpCommandReturn(gardenLineManager), result); } catch (Exception e) { LOGGER.error("Unexpected error : " + e.getLocalizedMessage(), e); fail("Unexpected error : " + e.getLocalizedMessage()); } // 5. invalid command LOGGER.debug("testing invalid command..."); try { result = gardenLineManager.execute("do nothing"); assertEquals(gardenLineManager.getPropertiesLoader().loadProperty(Constants.MAIN_INVALID_COMMAND), result); } catch (Exception e) { LOGGER.error("Unexpected error : " + e.getLocalizedMessage(), e); fail("Unexpected error : " + e.getLocalizedMessage()); } // 5. valid command LOGGER.debug("testing valid command..."); try { result = gardenLineManager.execute("tondre " + this.getClass().getResource("/valid/valid-file-1").getPath()); assertEquals("1 3 N\n5 1 E", result); } catch (Exception e) { LOGGER.error("Unexpected error : " + e.getLocalizedMessage(), e); fail("Unexpected error : " + e.getLocalizedMessage()); } // 6. valid command (file name contains espace) LOGGER.debug("testing valid command (file name contains espace)..."); try { String pathWithEspace = "\"" + this.getClass().getResource("/valid/valid file-2").getPath() + "\""; result = gardenLineManager.execute("tondre " + pathWithEspace.replace("%20", " ")); assertEquals("1 3 N\n5 1 E", result); } catch (Exception e) { LOGGER.error("Unexpected error : " + e.getLocalizedMessage(), e); fail("Unexpected error : " + e.getLocalizedMessage()); } LOGGER.info("Testing execute method ends."); }
7
public void mReleased(MouseEvent e) { if(rdown) { PermClass nodeToAdd = getClassUnderPoint(e.getX(), e.getY()); if(nodeToAdd != null) { boolean shouldAdd = true; if(nodeToAdd == selectedOne) { shouldAdd = false; } for(PermClass is : selectedOne.inheritsFrom) { if(is == nodeToAdd) { shouldAdd = false; break; } } if(shouldAdd) { selectedOne.inheritsFrom.add(nodeToAdd); System.out.println("Add!"); } } this.repaint(); } ldown = false; mdown = false; rdown = false; }
6
@Override public String analyze_round( List<Submission> list ) { if ( list.isEmpty() ) return null; List<Submission> trumps = is_suit(list, trump()); if (trumps.size() == 1) { return trumps.get(0).who; } if ( !trumps.isEmpty() ) { return is_rankier(trumps).who; } List<Submission> round = is_suit(list, list.get(0).card.suit()); if (round.size() == 1) { return round.get(0).who; } if ( !round.isEmpty() ) { return is_rankier(round).who; } return null; }
5
public final void need(int count) throws VerifyException { if (stackHeight < count) throw new VerifyException("stack underflow"); }
1
public void getNextMovesBack(List<State> nextStates) { // for each box. Chech which boxes we can reach // box : The current box we are looking at for (Position box : boxes) { // for each empty position adjucent to this box // adjucent : the current adjucent position to the box for (Position adjucent : Utils.getAdjucentPositionsBack(box, this)) { // find out if we can reach it from our current position w/o // moving any boxes String path_to_adjucent = Utils.findPath(player, adjucent, this); // check if there was such path if (path_to_adjucent != null) { // try to move the box Movement moved_path = Utils.tryToMoveBoxBack(box, adjucent, this); // check if we actually managed to move the box if (moved_path != null) { // create a new state State new_state; try { // clone this state new_state = (State) this.clone(); // update the BoxState we just moved new_state.boxes.remove(box); new_state.boxes.add(moved_path.getBox()); // update the player state new_state.player = moved_path.getPlayer(); // update the current path new_state.current_path = new StringBuilder(new_state.current_path). append(path_to_adjucent).append(moved_path.getPath()).toString(); new_state.updateValue(); /*Update the reachable positions*/ new_state.setReachPositions(); // add this state to the list to return nextStates.add(new_state); } catch (CloneNotSupportedException ex) { Logger.getLogger(State.class.getName()).log(Level.SEVERE, null, ex); } } // end checking if moved_path is null } // end checking if path to box is null } // end for each adjucent position to a box } // end for each box }
5
private void analyzeUtility() { if (getKingLocation( playerToMove.equals(KrakenColor.WHITE_PLAYER)? KrakenColor.BLACK_ITEM:KrakenColor.WHITE_ITEM) == null || actions(playerToMove.toLowerCase()).size()<1) utility = playerToMove.equals("W")? 1:0; }
4
public double weightedStandarError_as_Complex_ConjugateCalcn() { boolean hold = Stat.nFactorOptionS; if (nFactorReset) { if (nFactorOptionI) { Stat.nFactorOptionS = true; } else { Stat.nFactorOptionS = false; } } boolean hold2 = Stat.nEffOptionS; if (nEffReset) { if (nEffOptionI) { Stat.nEffOptionS = true; } else { Stat.nEffOptionS = false; } } boolean holdW = Stat.weightingOptionS; if (weightingReset) { if (weightingOptionI) { Stat.weightingOptionS = true; } else { Stat.weightingOptionS = false; } } double standardError = Double.NaN; if (!weightsSupplied) { System.out.println("weightedStandardError_as_Complex: no weights supplied - unweighted value returned"); standardError = this.standardError_as_Complex_ConjugateCalcn(); } else { Complex[] cc = this.getArray_as_Complex(); Complex[] wc = amWeights.getArray_as_Complex(); standardError = Stat.standardErrorConjugateCalcn(cc, wc); } Stat.nFactorOptionS = hold; Stat.nEffOptionS = hold2; Stat.weightingOptionS = holdW; return standardError; }
7
public Point getInitialP() { return initialP; }
0
public boolean checkVictory() { int yourLocation = yourPaddle.getPosition()[0]; int yourSize = Paddle.getSize()[0]; int[] ballLocation = ball.getPosition(); int radius = Ball.getSize(); if (ballLocation[1] < 300) { if (ballLocation[0] > 155 + radius && ballLocation[0] < 445 - radius) { if (ballLocation[0] < yourLocation - radius - 10 || ballLocation[0] > yourLocation + yourSize + radius + 10) { return true; } } } return false; }
5
public boolean equals(Object o) { if(o instanceof IMessage && o!=null) { IMessage c=(IMessage)o; if(c.taille()==this.taille()) { boolean trouve=false; int i=0; while(i<this.taille() && !trouve) { if(c.getChar(i)!=this.getChar(i)) { trouve=true; } i++; } return !trouve; } else { return false; } } else { return false; } }
6
public int removeDuplicates(int[] A) { if(A ==null || A.length ==0) return 0; int index =1; boolean flag = true; for (int i = 0;i < A.length-1 ;i++){ if(A[i] != A[i+1]){ flag = true; A[index++] = A[i+1]; }else if(flag){ flag =false; A[index++] = A[i+1]; } } return index; }
5
public static Double caculate(Model m, List<String> observe) { List<Double> initial = m.pi; List<Double> temp = new ArrayList<Double>(); Double result = 1d; for (String s : observe) { int index = m.V.indexOf(s); result *= Matrix.multiply(initial, m.B.get(index)); temp.clear(); for (int i = 0; i < m.S.size(); i++) { temp.add(Matrix.multiply(initial, m.A.get(i))); } } return result; }
2
public static void main(String[] args) { long start = System.nanoTime(); int totalSum = 0; for (Integer i = 2; i <= 194979; i++) { String intStr = i.toString(); int strLen = intStr.length(); int sum = 0; for (int k = 0; k < strLen; k++) { int num = Character.getNumericValue(intStr.charAt(k)); num = pow(num, 5); sum += num; } if (sum == i) { totalSum += sum; System.out.println(totalSum + " " + i); } } System.out.println(totalSum); System.out.println("Done in " + (double) (System.nanoTime() - start) / 1000000000 + " seconds."); }
3
@Override public Object getValueAt(int row, int col) { int round = currentRound + ( row / teamsPerTable ); int table = ( col - 1 ) / 2; if(col == 0) { if(row == 0) return "Playing:"; if(row == teamsPerTable) return "Next:"; } else if((col-1) % 2 == 0) { if(row == 0) return tableNames[(col-1)/2]; if(row == teamsPerTable) return tableNames[(col-1)/2]; } else if((col-1) % 2 == 1) { if(matches.get(round).getTeamsOnTable(table) != null) return matches.get(round).getTeamsOnTable(table).get(row % teamsPerTable).number; } return null; }
8
private TreeNode rotateLeft(TreeNode rotatingNode) { TreeNode rotatedTreeRootNode = rotatingNode.right; rotatedTreeRootNode.parent = rotatingNode.parent; rotatingNode.right = rotatedTreeRootNode.left; if (rotatingNode.right != null) { rotatingNode.right.parent = rotatingNode; } rotatedTreeRootNode.left = rotatingNode; rotatingNode.parent = rotatedTreeRootNode; if (rotatedTreeRootNode.parent != null) { if (rotatedTreeRootNode.parent.right == rotatingNode) { rotatedTreeRootNode.parent.right = rotatedTreeRootNode; } else if (rotatedTreeRootNode.parent.left == rotatingNode) { rotatedTreeRootNode.parent.left = rotatedTreeRootNode; } } setBalance(rotatingNode); setBalance(rotatedTreeRootNode); return rotatedTreeRootNode; }
4
public final void show() { StackPane parentRoot = (StackPane) ((Stage) stage.getOwner()) .getScene().getRoot(); parentRoot.getChildren().add(mask); stage.show(); }
0
public static HardwareAddress getHardwareAddressByString(String macStr) { if (macStr == null) { throw new NullPointerException("macStr is null"); } String[] macAdrItems = macStr.split(":"); if (macAdrItems.length != 6) { throw new IllegalArgumentException("macStr["+macStr+"] has not 6 items"); } byte[] macBytes = new byte[6]; for (int i=0; i<6; i++) { int val = Integer.parseInt(macAdrItems[i], 16); if ((val < -128) || (val > 255)) { throw new IllegalArgumentException("Value is out of range:"+macAdrItems[i]); } macBytes[i] = (byte) val; } return new HardwareAddress(macBytes); }
5
public void install() { try { if (plugin.getConfig().getBoolean("internet")) { try { String path = plugin.getDataFolder().getParent(); if (download(path)) { plugin.getLoggerUtility().log("Downloaded new Version!", LoggerUtility.Level.WARNING); plugin.getLoggerUtility().log("BookShop will be updated on the next restart!", LoggerUtility.Level.WARNING); } else { plugin.getLoggerUtility().log(" Cant download new Version!", LoggerUtility.Level.WARNING); } } catch (Exception e) { plugin.getLoggerUtility().log("Error on downloading new Version!", LoggerUtility.Level.ERROR); plugin.getReportHandler().report(3313, "Error on downloading new Version", e.getMessage(), "BookShop", e); e.printStackTrace(); plugin.getLoggerUtility().log("Uncatched Exeption!", LoggerUtility.Level.WARNING); } } if (plugin.getConfig().getBoolean("installondownload")) { plugin.getLoggerUtility().log("Found Update! Installing now because of 'installondownload = true', please wait!", LoggerUtility.Level.WARNING); } try { plugin.getPluginManager().unloadPlugin("BookShop"); } catch (NoSuchFieldException ex) { plugin.getLoggerUtility().log("Error on installing! Please check the log!", LoggerUtility.Level.ERROR); ex.printStackTrace(); } catch (IllegalAccessException ex) { plugin.getLoggerUtility().log("Error on installing! Please check the log!", LoggerUtility.Level.ERROR); ex.printStackTrace(); } try { plugin.getPluginManager().loadPlugin("BookShop"); } catch (InvalidPluginException ex) { plugin.getLoggerUtility().log("Error on loading after installing! Please check the log!", LoggerUtility.Level.ERROR); ex.printStackTrace(); } catch (InvalidDescriptionException ex) { plugin.getLoggerUtility().log("Error on loading after installing! Please check the log!", LoggerUtility.Level.ERROR); ex.printStackTrace(); } plugin.getLoggerUtility().log("Installing finished!", LoggerUtility.Level.INFO); } catch (Exception w) { w.printStackTrace(); plugin.getLoggerUtility().log("Uncatched Exeption!", LoggerUtility.Level.ERROR); plugin.getReportHandler().report(3314, "Uncatched Exeption on installing", w.getMessage(), "BookShop", w); } }
9
private void scanColorUnit(JPEGBitInputStream bis, Set<Integer> color_ids, Map<Integer, Integer> dc_base) throws MarkAppearException, IOException { // 对颜色空间进行扫描 for (int color_id : color_ids) { JPEGImage.JPEGLayer layer = mImg.getLayer(color_id); // 对每一种颜色的采样值进行扫描 for (int i = 0; i != layer.mHSamp*layer.mVSamp; ++i){ if (verbose > 1) { System.out.print(mImg.getColors()[color_id - 1] + ":"); } // 更新DC基值 int[] unit = new int[64]; Integer dc_val = dc_base.get(color_id); try { if (dc_val == null){dc_val = 0;} dc_val = scanColor(bis, layer, dc_val, unit); // 更新base值 dc_base.put(color_id, dc_val); // 插入数据 mImg.addDataUnit(color_id, unit); } catch (MarkAppearException e){ // EOI标志 if (e.mark == 0xd9){ throw e; } // RSTn标志,重置base值 FIXME : 这样处理对吗? 还是对所有color_id的base值都置0? System.err.println("Mark : RSTn "+e.mark+" color:"+color_id); dc_base.put(color_id, 0); } } } }
6
public Items getLast() { return last; }
0
public void restoreStatus(){ // EDebug.print("I am mucking with that data structure."); if (myDeck.size() == 0) return; Automaton p = null; while (myDeck.size() > 0 && (p = myDeck.pop()).hashCode() == myMaster.hashCode()); // EDebug.print("Master's hash is " + myMaster.hashCode()); // EDebug.print("Top hash is " + p.hashCode()); if (myDeck.size() == 0 && p.hashCode() == myMaster.hashCode()) return; sensitive = true; myBackDeck.push((Automaton) myMaster.clone()); if (myMaster instanceof TuringMachine) TuringMachine.become((TuringMachine) myMaster,(TuringMachine) p); else Automaton.become(myMaster, p); //pop off head sensitive = false; myMaster.getEnvironmentFrame().repaint(); }
6
private boolean equals( final Data item, final InnerDataSubscription subscription, final SystemObject transactionObject) { final SystemObject requiredObjectType = item.getReferenceValue("ObjektTyp").getSystemObject(); if(requiredObjectType != null && !subscription.getObject().getType().equals(requiredObjectType)) return false; if("Ja".equals(item.getTextValue("NurTransaktionsObjekt").getText())) { if(!subscription.getObject().equals(transactionObject)) return false; } final SystemObject requiredAttributeGroup = item.getReferenceValue("Attributgruppe").getSystemObject(); if(requiredAttributeGroup != null && !subscription.getAttributeGroup().equals(requiredAttributeGroup)) return false; final SystemObject requiredAspect = item.getReferenceValue("Aspekt").getSystemObject(); if(requiredAspect != null && !subscription.getAspect().equals(requiredAspect)) return false; // Sonst true zurückgeben return true; }
8
static LinkedHashSet<EXECUTION_MODE> getDefaultExecutionModes() { LinkedHashSet<EXECUTION_MODE> defaultExecutionModes = new LinkedHashSet<EXECUTION_MODE>(); if (OpenCLLoader.isOpenCLAvailable()) { defaultExecutionModes.add(GPU); defaultExecutionModes.add(JTP); } else { defaultExecutionModes.add(JTP); } final String executionMode = Config.executionMode; if (executionMode != null) { try { LinkedHashSet<EXECUTION_MODE> requestedExecutionModes; requestedExecutionModes = EXECUTION_MODE.getExecutionModeFromString(executionMode); logger.fine("requested execution mode ="); for (final EXECUTION_MODE mode : requestedExecutionModes) { logger.fine(" " + mode); } if ((OpenCLLoader.isOpenCLAvailable() && EXECUTION_MODE.anyOpenCL(requestedExecutionModes)) || !EXECUTION_MODE.anyOpenCL(requestedExecutionModes)) { defaultExecutionModes = requestedExecutionModes; } } catch (final Throwable t) { // we will take the default } } logger.info("default execution modes = " + defaultExecutionModes); for (final EXECUTION_MODE e : defaultExecutionModes) { logger.info("SETTING DEFAULT MODE: " + e.toString()); } return (defaultExecutionModes); }
8
public void stopGather(Player p) { if (registry.getGameController().multiplayerMode != registry.getGameController().multiplayerMode.CLIENT) { Resource resource = null; try { for (String key : resources.keySet()) { resource = (Resource) resources.get(key); if (resource != null) { if (resource.getIsCollecting()) { if (resource.getCollectingPlayer() == p && !resource.isNPCCollecting()) { resource.setCollecting(p, false); collectingResources.remove(resource.getId()); } } } } } catch (ConcurrentModificationException concEx) { //another thread was trying to modify resources while iterating //we'll continue and the new item can be grabbed on the next update } } }
7
public int compare(JAFieldDescription field1, JAFieldDescription field2) { Integer order1 = (field1.hasView()) ? (field1.getView().getOrder()) : -1; Integer order2 = (field2.hasView()) ? (field2.getView().getOrder()) : -1; if ((order1 >= 0) && (order2 < 0)) { return 1; } if ((order2 >= -1) && (order1 < -1)) { return -1; } if ((order1 >= 0) && (order2 >= 0)) { return order1.compareTo(order2); } return field1.getName().compareTo(field2.getName()); }
8
protected void checkFlush(Texture sprite) { if (sprite == null) throw new NullPointerException("null texture"); // we need to bind a different texture/type. this is // for convenience; ideally the user should order // their rendering wisely to minimize texture binds if (sprite != this.texture || idx >= maxIndex) { // apply the last texture flush(); this.texture = sprite; } }
3
@Override public String infix_toString(){ String representation = root.name; if(children.length != 0){ representation += "["; for(int index = 0; index < children.length; index++){ representation += children[index].toString(); } representation += "]"; } return representation; }
2
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null && line.length() != 0) { int times = Integer.parseInt(line.trim()); for (int i = 0; i < times; i++) { in.readLine(); int cells = Integer.parseInt(in.readLine().trim()); Floyd f = new Floyd(); f.inint(cells + 1); int exit = Integer.parseInt(in.readLine().trim()); int tle = Integer.parseInt(in.readLine().trim()); int con = Integer.parseInt(in.readLine().trim()); for (int j = 0; j < con; j++) { int[] v = readInts(in.readLine()); f.d[v[0]][v[1]] = v[2]; } int ans = 0; f.floyd(); for (int j = 1; j < f.d.length; j++) if (f.d[j][exit] <= tle) ans++; if (i != 0) out.append("\n"); out.append(ans + "\n"); } } System.out.print(out); }
7
public void setId(int id) { this.id = id; }
0
public String translate(final String key) { final String pattern = this.base.getString(key); if (pattern.equals("")) { this.plugin.getLogger().log(Level.FINEST, "String value not found for {0} in {1}", new Object[] { key, ( this.base.getCurrentPath().equals("") ? "(root)" : this.base.getCurrentPath() ) }); return null; } return ( this.formatCode == ChatColor.COLOR_CHAR ? pattern : ChatColor.translateAlternateColorCodes(this.formatCode, pattern) ); }
3
@Test @TestLink(internalId = 5) public void testSuccessInternal2() { assertTrue(true); }
0
public void doAction() { // Verificar se não existe toca if( isTocaNull() ) { // Incrementar número de vezes em que se comeu toca permanente e correr método de adição if( getEngine().getTocaPermanente().check() ) { numTocaPermanenteComida++; add(); } return; } // Verificar se não comeu a toca if( !check() ) { // Incrementar número de movimentos para tentar apanhar a toca temporária numMovimentos++; // Decrescer o número de ratos a cada Engine.NUM_COLUMNS/2 movimentos if( numMovimentos%(Engine.NUM_COLUMNS/2) == 0 && numMovimentos != 0) numRatos--; // Remover toca se não houver ratos if(numRatos == 0) remove(); return; } // Incrementar a pontuação getEngine().getPontuacao().addValor(numRatos); // Fazer crescer a cobra getEngine().getCobra().setTimesNotToMovePosTras( getEngine().getCobra().getTimesNotToMovePosTras()+numRatos ); // Remover toca remove(); }
6
public String getSpNum() { return spNum; }
0
public void setLength(double value) { if (value <= 0) { throw new IllegalArgumentException( "Illegal length, must be positive"); } else { length = value; weight = calculateTotalWeight(); } }
1
@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 Specialty)) { return false; } Specialty other = (Specialty) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
5
@Override public boolean waitForCardPresent(long timeout) throws CardException { long sleeptime = timeout / POLLING_INTERVAL; for (short i = 0; i < POLLING_INTERVAL; i++) { if (isCardPresent()) return true; try { Thread.sleep(sleeptime); } catch (InterruptedException e) { break; } } return false; }
3
public boolean caricaLista() { try { f1 = new FileReader("parole.txt"); fIN = new BufferedReader(f1); try { int l = 0; while (fIN.readLine() != null) { l++; } f1.close(); fIN.close(); f1 = new FileReader("parole.txt"); fIN = new BufferedReader(f1); italiano = new String[l]; inglese = new String[l]; nMax = italiano.length; System.out.println("nMax (caricaLista()): " + nMax); boolean stop = false; for (int i = 0; !stop; i++) { String tmp = fIN.readLine(); if (tmp == null) { stop = true; } else { String s[] = tmp.split(";"); // 1: inglese - 2: italiano inglese[i] = s[0]; italiano[i] = s[1]; } } } catch (IOException ex) { return true; } } catch (FileNotFoundException ex) { return true; } return false; }
5
@Override public int open(JoeTree tree, DocumentInfo docInfo, InputStream stream) { FileFormatManager manager = Outliner.fileFormatManager; String extension = getExtension(PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_PATH)); OpenFileFormat format = null; String format_name = null; if (PropertyContainerUtil.getPropertyAsBoolean(docInfo, DocumentInfo.KEY_IMPORTED)) { format_name = manager.getImportFileFormatNameForExtension(extension); format = manager.getImportFormat(format_name); } else { format_name = manager.getOpenFileFormatNameForExtension(extension); format = manager.getOpenFormat(format_name); } System.out.println("EXTENSION: " + extension); System.out.println("FORMAT_NAME: " + format_name); PropertyContainerUtil.setPropertyAsString(docInfo, DocumentInfo.KEY_FILE_FORMAT, format.getName()); return format.open(tree, docInfo, stream); }
1
public static void main(String[] args) { // Working with Method Parameters and Return Types System.out.println("string"); String name = "Madalin"; int nameLength = name.length(); System.out.println(nameLength); }
0
@Override public boolean hit(Ray ray, ShadeRec sr, FloatRef tmin) { float t = subtract(p0, ray.getOrigin()).dot(normal) / ray.getDirection().dot(normal); if (t <= K_EPSILON) return false; Vector3 p = ray.pointAt(t); Vector3 d = subtract(p, p0); double ddota = d.dot(a); if (ddota < 0.0 || ddota > aLenSquared) return false; double ddotb = d.dot(b); if (ddotb < 0.0 || ddotb > bLenSquared) return false; tmin.value = t; sr.normal = normal; sr.worldHitPoint = p; sr.localHitPoint = sr.worldHitPoint; return true; }
5
private void buildHeap(int index) {// using postOrder if (index + 1 > size) return; buildHeap(2 * index + 1); buildHeap(2 * index + 2); trickleDown(index); }
1
private void animateNextFrame() { // Animate next frame on buffer Graphics2D g = (Graphics2D) buffer.getDrawGraphics(); drawFrame(g); // Display the buffer if (!buffer.contentsLost()) { buffer.show(); } g.dispose(); // Repainting solves the problem of the applet not updating properly // on the Red Hat Linux computers. repaint(); }
1
public void doCSVHeaderAndTrailer() { try { final String mapping = ConsoleMenu.getString("Mapping ", CSVHeaderAndTrailer.getDefaultMapping()); final String data = ConsoleMenu.getString("Data ", CSVHeaderAndTrailer.getDefaultDataFile()); CSVHeaderAndTrailer.call(mapping, data); } catch (final Exception e) { e.printStackTrace(); } }
1
public final String getDisplay() { String data; data = "Welcome to Kohl's. Expect Great Things \n"; data += "------------------------------------------- \n"; data += "Customer Name: " + customer.getCustName() + "\n"; data += "Date of Purchase: " + formattedDate + "\n"; data += "------------------------------------------- \n"; for (int i = 0; i < lineItems.length; i++) { data += "Item Name: " + lineItems[i].getDescription() + "\n"; data += "Item Number: " + lineItems[i].getProduct() + "\n"; data += "Quantity: " + lineItems[i].getQty() + "\n"; data += "Product Price: " + lineItems[i].getProductAmount() + "\n"; data += "Discount Amount: " + lineItems[i].getDiscount() + "\n"; data += "--------------------------------------- \n"; } data += "Total Before Discount: " + getTotalBeforeDiscount() + "\n"; data += "Money Saved With Discount: " + getTotalAfterDiscount() + "\n"; double totalBill = getTotalBeforeDiscount() - getTotalAfterDiscount(); data += "Total Bill: " + totalBill; return data; }
1
public static Maze parseMaze(String filename) throws IOException{ /* Parse to lines of strings */ List<String> mazeText = new ArrayList<String>(); BufferedReader br = new BufferedReader(new FileReader(filename)); String line; int mazeHeight = 0; int mazeWidth = 0; while ((line = br.readLine()) != null) { // process the line. String noNewLine = line.split("\n")[0]; mazeText.add(noNewLine); mazeHeight++; } br.close(); mazeWidth = mazeText.get(0).length(); out.println("mazeHeight is " + mazeHeight); out.println("mazeWidth is " + mazeWidth); /* Get the size of the maze, allocate int maze */ int [][] maze = new int[mazeWidth][mazeHeight]; /* Find entrance and exit of the maze, mark walls and paths */ int [] start = new int[2]; // 0: width, 1: height ArrayList<Pair<Integer, Integer>> goals = new ArrayList<Pair<Integer, Integer>>(); String a = "00"; for(int i=0; i<mazeWidth; i++){ for(int j=0; j<mazeHeight; j++){ char curr = mazeText.get(j).charAt(i); if(curr == 'P'){ // entrance: s maze[i][j] = 2; start[0] = i; start[1] = j; } else if(curr == '.'){ // exit: g maze[i][j] = 3; Pair<Integer, Integer> goal = new Pair<Integer, Integer>(i, j); goals.add(goal); } else if(curr == '%'){ // walls: 1 maze[i][j] = 1; } else{ // path maze[i][j] = 0; } } } Maze myMaze = new Maze(start, goals, maze); return myMaze; }
6
public void testAllPairs(File file){ try { Scanner scan = new Scanner(file); while(scan.hasNextLine()){ String[] line = scan.nextLine().split("\t"); if(line.length != 2) continue; int ip = stringToIP(line[0].trim()); String host = line[1].trim(); if(!testPair(ip, host)){ System.out.println("Missing: " + IPToString(ip) + " -> " + host); } if(!testPair(host, ip)){ System.out.println("Missing: " + host + " -> " + IPToString(ip)); } } scan.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } }
5
public void work(Contract... contracts) { // do the most risky jobs first int maxRisk = Integer.MIN_VALUE; int riskIndex = 0; boolean theresJobToBeDone = true; while (theresJobToBeDone) { for (int i = 0; i < contracts.length; i++) { Contract contract = contracts[i]; int thisRisk = contract .volatility * contract.amount_of_work; if (thisRisk > maxRisk) { riskIndex = i; } } Contract contract = contracts[riskIndex]; // do the job contract.doit(); // send invoice if (contract.customer.prefers_email_invoice) { contract.invoice = new EmailInvoice(contract.customer.getEmailAddress(), contract.getDescription(), contract.get_hourly_rate(), contract.get_hours_of_work()); } else if (contract.customer.prefers_fax_invoice) { contract.invoice = new FaxInvoice(contract.customer.getFaxNumber(), contract.getDescription(), contract.get_hourly_rate(), contract.get_hours_of_work()); } else if (contract.customer.prefers_paper_invoice){ contract.invoice = new PaperInvoice(contract.customer.getInvoiceAddress(), contract.getDescription(), contract.get_hourly_rate(), contract.get_hours_of_work()); } else { System.out.println("Don't know how to bill this customer"); System.exit(-1); } InvoiceService.getInstance().sendInvoice(contract.invoice); // any job left to do? theresJobToBeDone = false; for (Contract c : contracts) { if (c.invoice == null) { theresJobToBeDone = true; } } } }
8
public static void getFilesHashAndUpdate(EcProrgressBar bar,EcButton btn,EcServerButton aquilla) throws NoSuchAlgorithmException, IOException { UpdateUtils.bar = bar; UpdateUtils.btn = btn; UpdateUtils.aquilla=aquilla; aquilla.setEnabled(false); btn.setEnabled(false); updateTextButton("Проверка и обновление","Пожалуйста, подождите..."); String jsonString = Utils.getInfo("hashes"); if(!jsonString.equals("error")){ System.out.println(jsonString); JsonObject obj= new JsonParser().parse(jsonString).getAsJsonObject(); String mainPath = Utils.getMainPath(); System.out.println(obj.entrySet().size()); bar.setMaximum(obj.entrySet().size()); HashMap<String,String> thisFiles = Utils.getMD5Files(); for (Map.Entry<String,JsonElement> entry : obj.entrySet()) { String currentFileName = mainPath + entry.getKey().replaceAll("/", Matcher.quoteReplacement(File.separator)); File currentFile = new File(currentFileName); btn.setText2("Проверка: "+currentFileName); btn.repaint(); if(!currentFile.exists()){ Path p = Paths.get(currentFileName); new File(p.getParent().toString()).mkdirs(); if(!getFile(entry.getKey(),currentFileName)){ btn.setText("Ошибка обновления...","Попробуйте позже"); btn.repaint(); return; } }else{ String s1 = entry.getValue().toString().replaceAll("\"",""); if(s1.length()>32)s1=s1.substring(1,s1.length()); String thisHash = Utils.getMD5File(currentFileName); if(!s1.equals(thisHash)){ System.out.println(currentFileName+" - BAD HASH! "+thisHash+"!="+s1); currentFile.delete(); if(!getFile(entry.getKey(),currentFileName)){ btn.setText("Ошибка обновления...","Попробуйте позже"); btn.repaint(); return; } }else{ System.out.println(currentFileName+" - OK! "+thisHash+"=="+s1); } } thisFiles.remove(entry.getKey().replaceAll("/",Matcher.quoteReplacement(File.separator))); updateProgress(1); } for(Map.Entry<String,String> entry: thisFiles.entrySet()){ new File(Utils.getMainPath()+entry.getKey()).delete(); } btn.setEnabled(true); updateTextButton("Обновлений не найдено!",""); } aquilla.setEnabled(true); }
8
private static void generateRandomTree(World world){ BlockLog b = null; TileMap tm = world.tileMap; for(int numTrees = 0; numTrees < 4; numTrees++){ int x = new Random().nextInt(tm.getXRows()); int y = new Random().nextInt(tm.getYRows()); for(int numLogs = 0; numLogs < 3; numLogs++){ if(y - numLogs > 0) if(world.tileMap.isAir(x, (y-numLogs))){ b = new BlockLog(tm, world); b.setPosition(x*32+16, (y-numLogs)*32+16); world.listWithMapObjects.add(b); System.out.println("added block at " + x + " " + (y-numLogs)); } } } }
4
public RegistrantList getRegistrantList(int aiMaxSize, String asLastModified) { String lsParam = ""; if (aiMaxSize > 0) { lsParam += "&max_size=" + Integer.toString(aiMaxSize); } if (UtilityMethods.isValidString(asLastModified)) { lsParam += "&last_modified=" + asLastModified; } if (UtilityMethods.isValidString(lsParam)) { lsParam = lsParam.replaceFirst("&", "?"); } return get(RegistrantList.class, REST_URL_REGISTRATION + lsParam); }
3
static private boolean jj_3R_16() { Token xsp; xsp = jj_scanpos; if (jj_scan_token(43)) { jj_scanpos = xsp; if (jj_scan_token(40)) { jj_scanpos = xsp; if (jj_scan_token(28)) { jj_scanpos = xsp; if (jj_scan_token(44)) { jj_scanpos = xsp; if (jj_scan_token(39)) { jj_scanpos = xsp; if (jj_3_14()) { jj_scanpos = xsp; if (jj_3R_19()) { jj_scanpos = xsp; if (jj_3R_20()) { jj_scanpos = xsp; if (jj_3R_21()) return true; } } } } } } } } return false; }
9
public static String GetDzienNoc() { String dziennoc; Calendar cal = Calendar.getInstance(); int s = cal.get(Calendar.HOUR_OF_DAY); int p; int dn; dn = 0; if (s>=19) { p = 5; dn = 0; } else { if (s>=13) { p = 4; dn = 1; } else { if (s>=11) { p = 3; dn = 1; } else { if (s>=5) { p = 2; dn = 1; } else { if (s>=0) { p = 1; dn = 0; } } }} } switch(dn) { case 1: dziennoc = "dzien"; break; case 0: dziennoc = "noc"; break; default: dziennoc ="błąd - nie pobrano"; break; } return dziennoc; }
7
@Override public int getAbilityFlagType(String strflag) { for (final String element : Ability.ACODE_DESCS) { if(element.equalsIgnoreCase(strflag)) return 1; } for (final String element : Ability.DOMAIN_DESCS) { if(element.equalsIgnoreCase(strflag)) return 2; } if(strflag.startsWith("!")) strflag=strflag.substring(1); for (final String element : Ability.FLAG_DESCS) { if(element.equalsIgnoreCase(strflag)) return 3; } if(CMClass.getAbility(strflag)!=null) return 0; return -1; }
8
@Override public String toString() { return nom; }
0
private synchronized void containMouse(int x, int y){ Window w = sm.getFullScreenWindow(); if(robot != null && w.isShowing()){ finalPos.x = x; finalPos.y = y; SwingUtilities.convertPointToScreen(finalPos, w); robot.mouseMove(x, y); } }
2
public void setProgress(String oid, String progress) { Objective o = q.getObjective(oid); if(o == null) throw new IllegalArgumentException("Quest \"" + q.getName() + "\" has no such objective: " + oid); if(!o.getType().isValid(progress)) throw new IllegalArgumentException("progress is not valid for type " + o.getType().getName()); if(o.getType().isComplete(o.getTarget(), progress)) { objprog.remove(oid); if(SkyQuest.isOnServer()) { Player p = Bukkit.getServer().getPlayerExact(player); if(p != null && o.isVisible())p.sendMessage(ChatColor.GREEN + "Objective completed: " + o.getName()); for(QuestAction r:o.getRewards()) { r.apply(player); } } } else objprog.put(oid, progress); }
7
private static Pair<Integer, Integer> findNest(String value, int target, boolean fromEnd){ int lastFound = Integer.MIN_VALUE; int nest = 0; for(int i = 0; i < value.length(); i++){ int search = fromEnd ? value.length() - 1 - i : i; if(value.charAt(search) == '('){ nest++; } else if(value.charAt(search) == ')'){ nest--; if(target == nest){ lastFound = search; } } } return new Pair<Integer, Integer>(nest, lastFound); }
5
public JCellule[][] getGrid() { return cellules; }
0
@Override public void rout(NetworkPacket networkPacket) throws IOException { if (networkPacket.isFlagSet(NetworkPacket.ARP)) { if (!networkPacket.getSourceAddress().equals(networkInterface.getLocalHost())) { networkInterface.process(networkPacket); if (networkPacket.getHopcount() > 0) { networkPacket.decrementHopcount(); networkInterface.send(networkPacket); } } else { if (networkPacket.getHopcount() > 0) { networkPacket.decrementHopcount(); networkInterface.send(networkPacket); } } return; } if (networkPacket.isFlagSet(NetworkPacket.TRANSPORT)) { if (!networkPacket.getDestinationAddresses().contains(networkInterface.getLocalHost())) { if (networkPacket.getSourceAddress().equals(networkInterface.getLocalHost())) { return; } if (networkPacket.getHopcount() > 0) { networkPacket.decrementHopcount(); networkInterface.send(networkPacket); } } else { if (networkPacket.getHopcount() > 0) { networkPacket.decrementHopcount(); networkInterface.send(networkPacket); networkInterface.process(networkPacket); } } return; } }
9
private void preOrderRec(Position<T> node) throws InvalidPositionException { if (node != null) { BTPosition<T> BTnode = checkPosition(node); System.out.print(node.element() + " "); preOrderRec(BTnode.getLeft()); preOrderRec(BTnode.getRight()); } }
1
@Override public int attack(double agility, double luck) { if(random.nextInt(100) < luck) { System.out.println("I just did the holy cross attack!"); return random.nextInt((int) agility) * 3; } return 0; }
1
public boolean isInterleave(String s1, String s2, String s3) { int m = s1.length(); int n = s2.length(); if(m + n != s3.length()) return false; //dp[i][j]: s1[0...i-1],和s2[0...j-1]可以交错匹配s3的最长长度 int dp[][] = new int[m+1][n+1]; dp[0][0] = 0; //初始化第一列,即只用s1 for(int i=1; i<=m; i++) { if (s1.charAt(i - 1) == s3.charAt(i - 1)) dp[i][0] = dp[i - 1][0] + 1; else break; } for(int i=1; i<=n; i++) { if (s2.charAt(i - 1) == s3.charAt(i - 1)) dp[0][i] = dp[0][i - 1] + 1; else break; } for(int i=1; i<=m; i++){ for(int j=1; j<=n; j++){ dp[i][j] = dp[i][j-1] + 1; if(s1.charAt(i-1) == s3.charAt(i+j-1)) dp[i][j] = dp[i-1][j] + 1; if(s2.charAt(j-1) == s3.charAt(i+j-1)) dp[i][j] = Math.max(dp[i][j - 1] + 1, dp[i][j]); } } return dp[m][n] == s3.length(); }
9
public void loadConfig(String config){ int configlength = config.length(); for (int i = 0; i < 369; i++){ int[] xy = indexToXY(i); int x = xy[0]; int y = xy[1]; String cellValue = ""; if (i < configlength){ char configValue = config.charAt(i); if(Character.isDigit(configValue) && configValue != '0'){ cellValue += configValue; } } SudokuCell sudokuCell = new SudokuCell(this.possibleValues); if (!cellValue.equals("")){ sudokuCell.setValue(cellValue); } this.sudokuField.get(y).put(x, sudokuCell); } }
5
private int validateSkill(String skillName, MainMenuHeroSlot temp) { for(int p = 0; p < temp.getcharacter().getSkillNames().length; p++) { if(temp.getcharacter().getSkillNames()[p].getDesc().equalsIgnoreCase(skillName)) return p; } // End for return -1; }
2
@EventHandler public void onPlayerMove(PlayerMoveEvent event) throws IOException { Player player = event.getPlayer(); String playerName = player.getName(); if (!statusData.containsKey(playerName)) { statusData.put(playerName, false); } Block block = player.getWorld().getBlockAt(player.getLocation()); String data = block.getWorld().getName() + "#" + String.valueOf(block.getX()) + "#" + String.valueOf(block.getY()) + "#" + String.valueOf(block.getZ()); if (plugin.portalData.containsKey(data)) { if (!statusData.get(playerName)) { statusData.put(playerName, true); String destination = plugin.portalData.get(data); if (player.hasPermission("BungeePortals.portal." + destination) || player.hasPermission("BungeePortals.portal.*")) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeUTF("Connect"); dos.writeUTF(destination); player.sendPluginMessage(plugin, "BungeeCord", baos.toByteArray()); baos.close(); dos.close(); } else { player.sendMessage(plugin.configFile.getString("NoPortalPermissionMessage").replace("{destination}", destination).replaceAll("(&([a-f0-9l-or]))", "\u00A7$2")); } } } else { if (statusData.get(playerName)) { statusData.put(playerName, false); } } }
6
private mxCell addNode(mxGraph graph, Object parent, mxGraphMlNode node) { mxCell v1; String id = node.getNodeId(); mxGraphMlData data = dataNodeKey(node); if (data != null && data.getDataShapeNode() != null) { Double x = Double.valueOf(data.getDataShapeNode().getDataX()); Double y = Double.valueOf(data.getDataShapeNode().getDataY()); Double h = Double.valueOf(data.getDataShapeNode().getDataHeight()); Double w = Double.valueOf(data.getDataShapeNode().getDataWidth()); String label = data.getDataShapeNode().getDataLabel(); String style = data.getDataShapeNode().getDataStyle(); v1 = (mxCell) graph.insertVertex(parent, id, label, x, y, w, h, style); } else { v1 = (mxCell) graph.insertVertex(parent, id, "", 0, 0, 100, 100); } cellsMap.put(id, v1); List<mxGraphMlGraph> graphs = node.getNodeGraph(); for (mxGraphMlGraph gmlGraph : graphs) { gmlGraph.addGraph(graph, v1); } return v1; }
3
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (response instanceof HttpServletResponse && request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; // skip auth for static content, middle of auth flow, notify servlet if (httpRequest.getRequestURI().startsWith("/static") || httpRequest.getRequestURI().equals("/oauth2callback") || httpRequest.getRequestURI().equals("/notify")) { LOG.info("Skipping auth check during auth flow"); filterChain.doFilter(request, response); return; } LOG.fine("Checking to see if anyone is logged in"); if (AuthUtil.getUserId(httpRequest) == null || AuthUtil.getCredential(AuthUtil.getUserId(httpRequest)) == null || AuthUtil.getCredential(AuthUtil.getUserId(httpRequest)).getAccessToken() == null) { // redirect to auth flow httpResponse.sendRedirect(WebUtil.buildUrl(httpRequest, "/oauth2callback")); return; } // Things checked out OK :) filterChain.doFilter(request, response); } else { LOG.warning("Unexpected non HTTP servlet response. Proceeding anyway."); filterChain.doFilter(request, response); } }
8
public final ObjectProperty<ToggleGroup> toggleGroupProperty() { if (null == toggleGroup) { toggleGroup = new ObjectPropertyBase<ToggleGroup>() { private ToggleGroup oldToggleGroup; @Override protected void invalidated() { final ToggleGroup toggleGroup = get(); if (null != toggleGroup && !toggleGroup.getToggles().contains(OnOffSwitch.this)) { if (oldToggleGroup != null) { oldToggleGroup.getToggles().remove(OnOffSwitch.this); } toggleGroup.getToggles().add(OnOffSwitch.this); } else if (null == toggleGroup) { oldToggleGroup.getToggles().remove(OnOffSwitch.this); } oldToggleGroup = toggleGroup; } @Override public Object getBean() { return OnOffSwitch.this; } @Override public String getName() { return "toggleGroup"; } }; } return toggleGroup; }
5
private static void setMapping(){ obsMapping = new SimpleBindings(); // creates an arrayList to contain the elements InputStreamReader isReader= new InputStreamReader(Obstacle.class.getClassLoader().getResourceAsStream(pathAttr)); try (BufferedReader reader = new BufferedReader(isReader)) { String line = reader.readLine(); // read the first line (containing some description text in csv file) while ((line = reader.readLine()) != null) { // Reading the file line by line String[] split = line.split(";"); int ID = Integer.parseInt(split[1]); boolean cT = (split[2].equals("1")); boolean cB = (split[3].equals("1")); boolean cS = (split[4].equals("1")); boolean v = (split[5].equals("1")); int h = Integer.parseInt(split[6]); genObstacle tmpGenObs = new genObstacle(ID,cT,cB,cS,v,h); obsMapping.put(split[0],tmpGenObs); } } catch (IOException x) { System.err.format("IOException: %s%n", x); } }
2
public static Iterator sqlQuery(Proposition proposition, LogicObject database, Stella_Object arguments) { RDBMS.checkForExternalDbUpdates(proposition, database); { MemoizationTable memoTable000 = null; Cons memoizedEntry000 = null; Stella_Object memoizedValue000 = null; if (Stella.$MEMOIZATION_ENABLEDp$) { memoTable000 = ((MemoizationTable)(RDBMS.SGT_RDBMS_F_SQL_QUERY_MEMO_TABLE_000.surrogateValue)); if (memoTable000 == null) { Surrogate.initializeMemoizationTable(RDBMS.SGT_RDBMS_F_SQL_QUERY_MEMO_TABLE_000, "(:MAX-VALUES 100 :TIMESTAMPS (:META-KB-UPDATE :EXTERNAL-DB-UPDATE))"); memoTable000 = ((MemoizationTable)(RDBMS.SGT_RDBMS_F_SQL_QUERY_MEMO_TABLE_000.surrogateValue)); } memoizedEntry000 = MruMemoizationTable.lookupMruMemoizedValue(((MruMemoizationTable)(memoTable000)), RDBMS.getQueryPatternMemoizationKey(proposition), ((Context)(Stella.$CONTEXT$.get())), (((Boolean)(Logic.$REVERSEPOLARITYp$.get())).booleanValue() ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER), Stella.MEMOIZED_NULL_VALUE, 6); memoizedValue000 = memoizedEntry000.value; } if (memoizedValue000 != null) { if (memoizedValue000 == Stella.MEMOIZED_NULL_VALUE) { memoizedValue000 = null; } } else { memoizedValue000 = MemoizableIterator.newMemoizableIterator(RDBMS.helpMemoizeSqlQuery(proposition, database, arguments)); if (Stella.$MEMOIZATION_ENABLEDp$) { memoizedEntry000.value = ((memoizedValue000 == null) ? Stella.MEMOIZED_NULL_VALUE : memoizedValue000); } } { Iterator value000 = MemoizableIterator.cloneMemoizedIterator(((MemoizableIterator)(memoizedValue000))); return (((Iterator)(value000))); } } }
7
public void recoverGoal(GoalDecider goalDecider) { Unit.MoveType mt; if (cost == CostDecider.ILLEGAL_MOVE && unit != null && current.getTile() != null && dst.getTile() != null && goalDecider != null && goalDecider.check(unit, path) && ((mt = unit.getSimpleMoveType(current.getTile(), dst.getTile())).isLegal() || mt == Unit.MoveType.MOVE_NO_ATTACK_CIVILIAN)) { // Pretend it finishes the move. movesLeft = unit.getInitialMovesLeft(); turns++; cost = PathNode.getCost(turns, movesLeft); resetPath(); } }
8
public void disconnect(String reason){ client.getSession().disconnect(reason); world = null; }
0
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Conserje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Conserje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Conserje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Conserje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Conserje().setVisible(true); } }); }
6
private String buildString() { StringBuffer builder = new StringBuffer(); if (!StringUtils.isBlank(this.protocol)) { builder.append(protocol); builder.append("://"); } if (!StringUtils.isBlank(this.host)) { builder.append(this.host); if (this.port > 0) { builder.append(":"); builder.append(this.port); } } if (params.size() > 0) { builder.append("?"); for (Entry<String, String> entry : params.entrySet()) { builder.append(entry.getKey()); builder.append("="); builder.append(entry.getValue()); builder.append("&"); } builder.deleteCharAt(builder.length() - 1); } return builder.toString(); }
5
public Object setMnemonic(String section,String tool,int key) { int i; for(i=0;i<_tb.size() && !_tb.get(i).name().equals(section);i++); if (i==_tb.size()) { return null; } else { toolbarSection sec=_tb.get(i); for(i=0;i<sec.size() && (sec.get(i)==null ? true : (!sec.get(i).getName().equals(tool))) ;i++); if (i==sec.size()) { return null; } else { if (section.substring(0,1).equals("@")) { return null; } else { JComponent comp=sec.getComponent(i); if (comp instanceof JButton) { JButton but=(JButton) comp; but.setMnemonic(key); return but; } else { return null; } } } } }
9
private float mtmWeights(float rate){ /* Link rate | MTM Weights | * ---------------------------------- * 11 | 1 | * 5.5 | 1.44 | * 2 | 3 | * 1 | 5.45 | * */ if(rate == 11f) return 1f; if(rate == 5.5f) return 1.44f; if(rate == 2f) return 3f; if(rate == 1f) return 5.54f; return 5.45f; }
4
private void paintBalls(Graphics g) { for (Ball b: com.github.abalone.elements.Board.getInstance().getBalls() ) { Coords ballCoords = b.getCoords(); Coords coords; if ( this.reversed ) coords = new Coords(-ballCoords.getRow(), ballCoords.getCol()); else coords = new Coords(ballCoords); Point point = this.getPoint(coords); switch ( b.getColor() ) { case WHITE: this.whiteBall.paintIcon(this, g, point.x, point.y); break; case BLACK: this.blackBall.paintIcon(this, g, point.x, point.y); break; } if ( this.selectedBalls.contains(ballCoords) ) { this.selection.paintIcon(this, g, point.x, point.y); } } }
5
public static void main(String[] args) { String count = "unknown"; switch (args.length) { case 0: count = "zero"; break; case 1: count = "one"; break; case 2: count = "two"; break; } switch (args.length) { case 200000: count = "two million"; break; case 100000: count = "one million"; break; case 300000: count = "three million"; break; } System.out.println(count); System.out.println(chooseGreeting("Java")); for (int i = 0; i < 100000; i++) { chooseGreeting("Java"); chooseGreeting("Scala"); chooseGreeting("Ruby"); } for (int i = 0; i < 100000; i++) { chooseGreeting("Java"); chooseGreeting("Scala"); chooseGreeting("Ruby"); } }
8
public AdditionProblem(int aNew, int bNew){ a = aNew; b = bNew; String tempaBinary = Integer.toBinaryString(a); String tempbBinary = Integer.toBinaryString(b); checkValue = a+b; diff = Math.abs(tempaBinary.length() - tempbBinary.length()); String temp = ""; for(int i = 0; i < diff; i++){ temp += "0"; } if(tempaBinary.length() < tempbBinary.length()){ tempaBinary = temp + tempaBinary; larger = tempbBinary.length(); } else if(tempbBinary.length() < tempaBinary.length()){ tempbBinary = temp + tempbBinary; larger = tempaBinary.length(); } else{ larger = tempaBinary.length(); } System.out.println(tempaBinary + "\n" + tempbBinary); bothBinary = new int[2][larger]; for(int i = 0; i < tempaBinary.length(); i++) bothBinary[0][i] = Character.getNumericValue(tempaBinary.charAt(tempaBinary.length() -1 -i)); for(int i = 0; i < tempbBinary.length(); i++) bothBinary[1][i] = Character.getNumericValue(tempbBinary.charAt(tempbBinary.length() -1 -i)); }
5
@Override public void run(){ System.out.println("RUN THREAD?"); if(this.type == 1) runRequestGenerator(); else runFailureGenerator(); if(this.type == 1) try { fis.append("Thread: "+ this.getId() + "\n"); fis.append("Clients: " + this.numberClients + "\n"); fis.append("Requests: " + this.numberRequests + "\n"); fis.append("Discarted: " + this.discarted + "\n"); fis.append("Rate: " + this.rateOfResponse() + "\n"); if(fis != null) fis.close(); } catch (IOException e) { System.out.println("Couldnt write the statistics."); } else try{ fis.append("Thread: "+ this.getId() + "\n"); fis.append("Target: " + this.target+"\n"); fis.append("Failures Generated: " + this.operations+"\n"); if(fis != null) fis.close(); } catch (IOException e) { System.out.println("Couldnt write the statistics."); } }
6