text
stringlengths
14
410k
label
int32
0
9
boolean ehIgual(DadoMaterial dadoMaterial) { return titulo.equals(dadoMaterial.titulo) && descricao.equals(dadoMaterial.descricao) && edicao.ehIgual(dadoMaterial.edicao) && anoPublicacao.ehIgual(dadoMaterial.anoPublicacao) && autor.equals(dadoMaterial.autor) && editora.ehIgual(dadoMaterial.editora) && categoria.ehIgual(dadoMaterial.categoria) && publico.ehIgual(dadoMaterial.publico); }
7
private void loadPic() throws IOException { File jarfile = new File(this.isport, modName + ".jar"); File modpicfile = new File(isportinfo, modName+".png"); if(!modpicfile.exists()&&jarfile.exists()) { modpicfile.createNewFile(); InputStream in = null; BufferedImage bi = null; try { String inputFile = "jar:file:/" + jarfile.getAbsolutePath() + "!/"+modLogo; URL inputURL = new URL(inputFile); JarURLConnection conn = (JarURLConnection) inputURL.openConnection(); in = conn.getInputStream(); bi = ImageIO.read(in); ImageIO.write(bi, "png", modpicfile); men.picture.setIcon(new ImageIcon(new ImageScaler().scaleImage(bi, new Dimension(400, 225)))); } catch (Exception e){ } finally { if(in!=null) in.close(); if(bi!=null) { bi.flush(); bi.flush(); } } } if(modpicfile.exists()&&modpicfile.length()>10) { BufferedImage bi = null; try { bi = ImageIO.read(modpicfile); men.picture.setIcon(new ImageIcon(new ImageScaler().scaleImage(bi, new Dimension(400, 225)))); } catch (Exception e) { e.printStackTrace(); } finally { if(bi !=null) { bi.flush(); bi.flush(); } } } }
9
public static void main(String[] args) throws Exception { String inputfile = ""; String testfile = ""; if(args.length != 2) { System.out.println("Error in the arguments"); System.exit(0); } else { inputfile = args[0]; testfile = args[1]; } DecisionTree dt = new DecisionTree(); int status = dt.readFile(inputfile, -1); if(status > 0) { dt.root.depth = 0; dt.learnTree(dt.root); } DecisionTree testDt = new DecisionTree(); int testDtStatus = testDt.readFile(testfile, -1); if(testDtStatus > 0 && Arrays.equals(dt.attributePossibleValues, testDt.attributePossibleValues)) { int count = 0; int trainingSetSize = testDt.root.X.size(); for (int i = 0; i < trainingSetSize; i++) { DataPoint dp = testDt.root.X.get(i); TreeNode node = dt.root; while(node.children != null) { node = node.children[dp.attributes[node.selectedAttribute]]; } if(node.value == testDt.root.Y.get(i)) count++; } if(inputfile.equals(testfile)) System.out.println("Accurancy of training set (" + trainingSetSize + ") : " + (double)(count * 100)/trainingSetSize); else System.out.println("Accurancy of test set (" + trainingSetSize + ") : " + (double)(count * 100)/trainingSetSize); } }
8
private void broadcast(String message) { for (ChatMessageInbound connection : connections) { try { CharBuffer buffer = CharBuffer.wrap(message); connection.getWsOutbound().writeTextMessage(buffer); } catch (IOException ignore) { // Ignore } } }
2
@Override public void onEnable() { // Load Configuration config = new AutoSaveConfig(getConfiguration()); config.load(); // Test the waters, make sure we are running a build that has the // methods we NEED try { // Check Server org.bukkit.Server.class.getMethod("savePlayers", new Class[] {}); // Check World org.bukkit.World.class.getMethod("save", new Class[] {}); } catch (NoSuchMethodException e) { // Do error stuff log.severe(String.format("[%s] ERROR: Server version is incompatible with %s!", getDescription().getName(), getDescription().getName())); log.severe(String.format("[%s] Could not find method \"%s\", disabling!", getDescription().getName(), e.getMessage())); // Clean up getPluginLoader().disablePlugin(this); return; } // Test the waters further, see if setAutoSave exists! try { org.bukkit.World.class.getMethod("setAutoSave", boolean.class); bukkitHasSetAutoSave = true; } catch (NoSuchMethodException e) { // Do nothing, we will work around it anyways bukkitHasSetAutoSave = false; } // Disable built-in world saving for ASynchronous Mode if (config.varMode == Mode.ASYNCHRONOUS) { for (World world : getServer().getWorlds()) { if (bukkitHasSetAutoSave) { world.setAutoSave(false); } else { // this should be true because canSave is really noSave ((CraftWorld) world).getHandle().savingDisabled = true; } } } // Make an HTTP request for anonymous statistic collection startThread(ThreadType.REPORT); // Start AutoSave Thread startThread(ThreadType.SAVE); // Notify on logger load log.info(String.format("[%s] Version %s is enabled: %s", getDescription().getName(), getDescription().getVersion(), config.varUuid.toString())); }
5
void addAsIncoming( Node u, BitSet is ) throws MVDException { Iterator<Arc> iter = iterator(); boolean wasAttached = false; while ( iter.hasNext() ) { Arc a = (Arc) iter.next(); if ( a.versions.intersects(is) ) { u.addIncoming( a ); wasAttached = true; } } if ( wasAttached ) { // now remove the incoming arcs from the unattached set // because we can't remove while adding ListIterator<Arc> iter2 = u.incomingArcs(); while ( iter2.hasNext() ) { Arc a = iter2.next(); if ( remove(a) ) versions.andNot( a.versions ); } } }
5
public int getNumberOfFeatureSets() { int num= 0; if (this.extractRH) ++num; if (this.extractRP) ++num; if(this.extractSSD) ++num; return num; }
3
public Snail(MonsterManager mm, Registry rg, String im, String st, int x, int y, int minDist, int maxDist) { super(mm, rg, im, st, x, y, minDist, maxDist, false); name = "Snail"; displayName = "Snail"; monsterManager = mm; difficultyFactor = 0.60f; adjustHPForLevel(); topOffset = 17; baseOffset = 7; baseWidth = 58; startJumpSize = 20; jumpSize = 8; fallSize = 0; xMoveSize = 1; adjustTouchDamageForLevel(); dropChances.addDropChance("LargeShell", 75.0f, 1, 1); dropChances.addDropChance("WeemsDiceBag", 0.20f, 1, 1); //1 in 500 chance dropChances.addDropChance("ForrestsLaptop", 0.20f, 1, 1); //1 in 500 chance dropChances.addDropChance("BrandonsAbacus", 0.20f, 1, 1); //1 in 500 chance ai = new AI(registry, this); ai.clearGoals(); ai.addGoal(AI.GoalType.ATTACK_PLAYER_RANGED, "", (Rand.getRange(0, 1) + Rand.getFloat())); if (groundLevel == 0) { ai.addGoal(AI.GoalType.ATTACK_PLACEABLE, "", (Rand.getRange(0, 1) + Rand.getFloat())); } ai.activate(); }
1
public Long getTimestamp() { return timestamp; }
0
public void go() { BufferedReader br = null; BufferedWriter out = null; try { int numFloors; int numElevators; int numRiders; int maxCapacity; List<Rider> myRiders = new ArrayList<Rider>(); String sCurrentLine; br = new BufferedReader(new FileReader("inputs")); out = new BufferedWriter(new FileWriter("Elevator.log")); Building b = null; if ((sCurrentLine = br.readLine()) != null) { //This is the first line String[] inputs = sCurrentLine.split(" "); System.out.println(Arrays.toString(inputs)); b = new Building(Integer.parseInt(inputs[0]), Integer.parseInt(inputs[1]), out); } while ((sCurrentLine = br.readLine()) != null) { String[] inputs = sCurrentLine.split(" "); System.out.println(Arrays.toString(inputs)); int riderID = Integer.parseInt(inputs[0]); int currentFloor = Integer.parseInt(inputs[1]); int requestedFloor = -1; try { requestedFloor = Integer.parseInt(inputs[2]); } catch(NumberFormatException e) { System.out.println("Rider " + riderID + " does not have a valid request, bad behavior detected"); } if (requestedFloor != -1) { Rider r = new Rider(riderID, requestedFloor, currentFloor, b); r.setWriter(out); Thread t = new Thread(r); t.start(); t.setName("Rider " + r.riderID); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
7
public void setPortALabels(int t) { // t = t & 0b11111111; int a = t & 0b00000001; int b = t & 0b00000010; int c = t & 0b00000100; int d = t & 0b00001000; int e = t & 0b00010000; int f = t & 0b00100000; int g = t & 0b01000000; int h = t & 0b10000000; if (a > 0) { label_20.setText("1"); } else { label_20.setText("0"); } if (b > 0) { label_19.setText("1"); } else { label_19.setText("0"); } if (c > 0) { label_18.setText("1"); } else { label_18.setText("0"); } if (d > 0) { label_17.setText("1"); } else { label_17.setText("0"); } if (e > 0) { label_16.setText("1"); } else { label_16.setText("0"); } if (f > 0) { label_15.setText("1"); } else { label_15.setText("0"); } if (g > 0) { label_14.setText("1"); } else { label_14.setText("0"); } if (h > 0) { label_13.setText("1"); } else { label_13.setText("0"); } label_23.setText(String.valueOf(t)); }
8
private void addSplits(ArrayList<S3Item> fileList, SimpleQueue queue, int numSplits) { StringBuilder sb = new StringBuilder(); int mapNum = 0; long totalSize = 0; for (S3Item item : fileList) { totalSize += item.getSize(); } long splitSize = totalSize / numSplits + 1; logger.info("Total input file size: " + totalSize + ". Each split size: " + splitSize); long currentSize = 0; for (S3Item item : fileList) { long filePos = 0; while (filePos < item.getSize()) { long len = Math.min(item.getSize() - filePos, splitSize - currentSize); if (sb.length() > 0) { sb.append(","); } sb.append(item.getPath()); sb.append(","); sb.append(filePos); sb.append(","); sb.append(len); filePos += len; currentSize += len; if (currentSize == splitSize) { // prepend mapNum to uniquely identify each message, mapNum is the key, : is the separator queue.push(mapNum + Global.separator + sb.toString()); mapNum ++ ; currentSize = 0; sb = new StringBuilder(); } } } if (sb.length() > 0) { // prepend mapNum to uniquely identify each message queue.push(mapNum + Global.separator + sb.toString()); mapNum ++ ; } }
6
public Player(int x, int y, double angle, double vx, double vy, double vAngle, int numLives, int playerNo){ model = new PlayerModel(x, y, angle, vx, vy, vAngle, numLives, playerNo); this.playerNo = playerNo; if (playerNo == 0) color = Color.WHITE; else color = Color.blue; shape = new GeneralPath(GeneralPath.WIND_EVEN_ODD, 4); shape.moveTo(0, 14); shape.lineTo(14, -14); shape.lineTo(0, -5); shape.lineTo(-14, -14); shape.closePath(); }
1
public void addNewEnemy() throws SlickException{ // Gets a new random X location. int randX = xLoc.getX(); // Makes an enemy at (randX, 0), but doesn't display it on the screen. Enemy enemy = new Enemy(randX); // Runs at least once, then loops if the new enemy's word is the same as any of the current enemies. do{ // Words are innocent until proven guilty. wordAlreadyExists = false; // If there are still words that haven't been used. if (Play.enemiesOnScreen.size() < Play.words.size() && Play.enemiesOnScreen.size() != 0){ // Loops through enemies currently on the screen. for(int i = 0; i < Play.enemiesOnScreen.size(); i++){ // Check to see if the new enemy has a word that already exists. if(enemy.getWord().equals(Play.enemiesOnScreen.get(i).getWord())){ // If it does then keep the boolean variable true. wordAlreadyExists = true; // Set a new word for the enemy. enemy.setWord(); // Break out of the for loop because it only needs to match against one other - going further is pointless. break; } } } // If there are currently no enemies on the screen, go ahead and add one. else if (Play.enemiesOnScreen.size() == 0){ wordAlreadyExists = false; } // If there are not anymore unused words in the list. else if(Play.enemiesOnScreen.size() == Play.words.size()){ // The word must already exist. wordAlreadyExists = true; // But we need to break out because that will remain true until an enemy is shot or reaches the bottom. break; } } while(wordAlreadyExists); // If the new word isn't already on the screen. if (!wordAlreadyExists){ // Add the enemy to the screen. Play.enemiesOnScreen.add(enemy); // Play the launch sound. launch.play(); } }
8
public SmartRobot() throws AWTException { super(); // The anvil client sends over some non standard keycodes // (Android does not include the awt package) keyMap = new HashMap<Character, ShiftIndex>(); // Add Uppercase letter keys (sent as negatives of the lowercase) for(int x = -65; x > -91; x--){ keyMap.put((char)x, new ShiftIndex((0-x),true)); } // Add all shifted numsymbol keys keyMap.put('!', new ShiftIndex(KeyEvent.VK_1,true)); keyMap.put('@', new ShiftIndex(KeyEvent.VK_2,true)); keyMap.put('#', new ShiftIndex(KeyEvent.VK_3,true)); keyMap.put('$', new ShiftIndex(KeyEvent.VK_4,true)); keyMap.put('%', new ShiftIndex(KeyEvent.VK_5,true)); keyMap.put('^', new ShiftIndex(KeyEvent.VK_6,true)); keyMap.put('&', new ShiftIndex(KeyEvent.VK_7,true)); keyMap.put('*', new ShiftIndex(KeyEvent.VK_8,true)); keyMap.put('(', new ShiftIndex(KeyEvent.VK_9,true)); keyMap.put(')', new ShiftIndex(KeyEvent.VK_0,true)); keyMap.put('_', new ShiftIndex(KeyEvent.VK_MINUS,true)); keyMap.put('+', new ShiftIndex(KeyEvent.VK_EQUALS,true)); keyMap.put('~', new ShiftIndex(KeyEvent.VK_BACK_QUOTE,true)); keyMap.put('|', new ShiftIndex(KeyEvent.VK_BACK_SLASH,true)); keyMap.put(':', new ShiftIndex(KeyEvent.VK_SEMICOLON,true)); keyMap.put('"', new ShiftIndex(KeyEvent.VK_QUOTE,true)); keyMap.put('<', new ShiftIndex(KeyEvent.VK_COMMA,true)); keyMap.put('>', new ShiftIndex(KeyEvent.VK_PERIOD,true)); keyMap.put('?', new ShiftIndex(KeyEvent.VK_SLASH,true)); keyMap.put('{', new ShiftIndex(KeyEvent.VK_OPEN_BRACKET,true)); keyMap.put('}', new ShiftIndex(KeyEvent.VK_CLOSE_BRACKET,true)); // Lower case symbols keyMap.put(',', new ShiftIndex(KeyEvent.VK_COMMA,false)); keyMap.put('.', new ShiftIndex(KeyEvent.VK_PERIOD,false)); keyMap.put('/', new ShiftIndex(KeyEvent.VK_SLASH,false)); keyMap.put(';', new ShiftIndex(KeyEvent.VK_SEMICOLON,false)); keyMap.put('\'', new ShiftIndex(KeyEvent.VK_QUOTE,false)); keyMap.put('[', new ShiftIndex(KeyEvent.VK_OPEN_BRACKET,false)); keyMap.put(']', new ShiftIndex(KeyEvent.VK_CLOSE_BRACKET,false)); keyMap.put('\\', new ShiftIndex(KeyEvent.VK_BACK_SLASH,false)); keyMap.put('`', new ShiftIndex(KeyEvent.VK_BACK_QUOTE,false)); // Control keys sent as negative ASCII keycode keyMap.put((char)-8, new ShiftIndex(KeyEvent.VK_BACK_SPACE,false)); keyMap.put((char)-13, new ShiftIndex(KeyEvent.VK_ENTER,false)); keyMap.put((char)-16, new ShiftIndex(KeyEvent.VK_SHIFT,false)); keyMap.put((char)-32, new ShiftIndex(KeyEvent.VK_SPACE,false)); keyMap.put((char)-20, new ShiftIndex(KeyEvent.VK_CAPS_LOCK,false)); keyMap.put((char)-9, new ShiftIndex(KeyEvent.VK_TAB,false)); keyMap.put((char)-27, new ShiftIndex(KeyEvent.VK_ESCAPE,false)); keyMap.put((char)-17, new ShiftIndex(KeyEvent.VK_CONTROL,false)); keyMap.put((char)-18, new ShiftIndex(KeyEvent.VK_ALT,false)); keyMap.put((char)-45, new ShiftIndex(KeyEvent.VK_INSERT,false)); keyMap.put((char)-46, new ShiftIndex(KeyEvent.VK_DELETE,false)); keyMap.put((char)-36, new ShiftIndex(KeyEvent.VK_HOME,false)); keyMap.put((char)-35, new ShiftIndex(KeyEvent.VK_END,false)); keyMap.put((char)-33, new ShiftIndex(KeyEvent.VK_PAGE_UP,false)); keyMap.put((char)-34, new ShiftIndex(KeyEvent.VK_PAGE_DOWN,false)); keyMap.put((char)-145, new ShiftIndex(KeyEvent.VK_SCROLL_LOCK,false)); keyMap.put((char)-19, new ShiftIndex(KeyEvent.VK_PAUSE,false)); keyMap.put((char)-38, new ShiftIndex(KeyEvent.VK_UP,false)); keyMap.put((char)-40, new ShiftIndex(KeyEvent.VK_DOWN,false)); keyMap.put((char)-37, new ShiftIndex(KeyEvent.VK_LEFT,false)); keyMap.put((char)-39, new ShiftIndex(KeyEvent.VK_RIGHT,false)); // F1 - F12 keys dont seem to change codes // Numbers dont seem to change codes // Lower case letters map to the uppercase codes (uppercase require shift key) }
1
public void msgUserClicked(ArrayList<String> usersId, int result, int x, int y, String turnUserId, String winnerId) { String tmpl = "clicked %d %d %d %s"; // command x, y, result, {turnUserId|winUserId}, [win] if (winnerId != null) tmpl += " win"; String id = winnerId != null ? winnerId : turnUserId; for (String userId: usersId) { UserSession userSession = sessionIdToUserSession.get(userId); if (winnerId != null) { userSession.setStatus(UserSession.Status.playingEnd); } userSession.setInfoForSend(String.format(tmpl, x, y, result, id)); } }
4
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed if(this.tabPerksFlaws.getSelectedIndex() == TAB_PERKS) { if(this.listPerks.getSelectedValue() != null) { if(!this.characterPerks.contains((Perk)this.listPerks.getSelectedValue())) { this.characterPerks.add((Perk)this.listPerks.getSelectedValue()); } } } if(this.tabPerksFlaws.getSelectedIndex() == TAB_FLAWS) { if(this.listFlaws.getSelectedValue() != null) { this.characterFlaws.add((Flaw)this.listFlaws.getSelectedValue()); } } DefaultListModel dlm = new DefaultListModel(); dlm.addElement(new Category("Vorteile")); for(final Perk perk : this.characterPerks) { dlm.addElement(perk); } dlm.addElement(new Category("Nachteile")); for(final Flaw perk : this.characterFlaws) { dlm.addElement(perk); } this.listCharacterEdgesFlaws.setModel(dlm); }//GEN-LAST:event_jButton2ActionPerformed
7
public static int levenshteinDistance (String s, String t) { int d[][]; // matrix int n; // length of s int m; // length of t int i; // iterates through s int j; // iterates through t char s_i; // ith character of s char t_j; // jth character of t int cost; // cost // Step 1 n = s.length (); m = t.length (); if (n == 0) { return m; } if (m == 0) { return n; } d = new int[n+1][m+1]; // Step 2 for (i = 0; i <= n; i++) { d[i][0] = i; } for (j = 0; j <= m; j++) { d[0][j] = j; } // Step 3 for (i = 1; i <= n; i++) { s_i = s.charAt (i - 1); // Step 4 for (j = 1; j <= m; j++) { t_j = t.charAt (j - 1); // Step 5 if (s_i == t_j) { cost = 0; } else { cost = 1; } // Step 6 d[i][j] = Minimum (d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost); } } // Step 7 return d[n][m]; }
7
@Override public Confirmation deliver(final Message message) { int count = 0; for (final Permissible permissible : Bukkit.getPluginManager().getPermissionSubscriptions(this.permission)) if (permissible instanceof CommandSender && permissible.hasPermission(this.permission)) { final CommandSender target = (CommandSender) permissible; target.sendMessage(message.format(target).toString()); count++; } return new Confirmation(Level.FINER, count, "[PUBLISH-{1}({2})] {0}", message, PermissionSubscribers.this.permission, count); }
3
public int checkGameState() { ArrayList<Integer> player1Moves = getValidMoves(PLAYER1); ArrayList<Integer> player2Moves = getValidMoves(PLAYER2); if (player1Moves.isEmpty() && player2Moves.isEmpty()) { this.gameOn = false; return 0; } else return 1; }
2
private static boolean checkAABB(Position p1, Collidable c1, Position p2, Collidable c2) { return !((p1.x + c1.width - 1 < p2.x) || (p1.x > p2.x + c2.width - 1) || (p1.y + c1.height - 1 < p2.y) || (p1.y > p2.y + c2.height - 1)); }
3
@Override public void onEntityHit(Player p, MapObject mo) { jiggle = true; int wepDmg = 0; ItemStack wep = world.getPlayer().invArmor.getWeapon(); if(wep != null && effectiveTool == ((ItemTool)wep.getItem()).getEffectiveness()) wepDmg = ((ItemTool)wep.getItem()).getEffectiveDamage(); switch (getType()) { case ROCK: Music.play("hit_rock_" + (rand.nextInt(4)+1)); break; case WOOD: Music.play("hit_wood_" + (rand.nextInt(5)+1)); break; default: break; } health -= world.getPlayer().getAttackDamage() + wepDmg; //TODO add check so blocks might not be broken without specific tool //boolean check requiresTool ? // System.out.println(health); if(health <= 0) mine(p); }
5
@Override public void windowIconified(WindowEvent arg0) { // TODO Auto-generated method stub }
0
@Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof FindWithinGenerator<?>)) { return false; } FindWithinGenerator<?> other = (FindWithinGenerator<?>) obj; return other.useIfNone == useIfNone && !useIfNone || (other.ifNone == this.ifNone || other.ifNone != null && other.ifNone.equals(this.ifNone)); }
9
public static void updateStation(Station station) { PreparedStatement stat; try { stat = ConnexionDB.getConnection().prepareStatement("select * from station where id_station=?",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); stat.setInt(1, station.getId_station()); ResultSet res = stat.executeQuery(); if (res.next()) { res.updateString("serialNumber", station.getSerialNumber()); res.updateString("etat", station.getEtat()); res.updateString("latitude", station.getLatitude()); res.updateString("longitude", station.getLongitude()); res.updateRow(); } } catch (SQLException e) { while (e != null) { System.out.println(e.getErrorCode()); System.out.println(e.getMessage()); System.out.println(e.getSQLState()); e.printStackTrace(); e = e.getNextException(); } } }
3
@Override public Tile cross(Tile currentTile, Character crosser) { if (crosser == null || currentTile == null){ throw new IllegalArgumentException("crosser can not be null"); } if (!isLocked()){ //just cross, exit's already unlocked return super.cross(currentTile, crosser); } else if (crosser.hasItem(key)){ //check for key unlock(key); //unlock the door, since crosser has the key return super.cross(currentTile, crosser); } else throw new IllegalArgumentException("crosser did not have key"); }
4
public void loadConfigFiles(String board, String legend) throws IOException, BadConfigFormatException { rooms = new HashMap<Character, String>(); // Import Legend FileReader legendReader = new FileReader(legend); Scanner legendIn = new Scanner(legendReader); String line, parts[]; while(legendIn.hasNextLine()) { line = legendIn.nextLine(); parts = line.split(", "); if(parts.length != 2 || parts[0] == "" || parts[1] == "") { legendIn.close(); legendReader.close(); throw new BadConfigFormatException("Legend is malformed."); } // Map the Initial (char) to the name. rooms.put(parts[0].charAt(0), parts[1]); } legendIn.close(); legendReader.close(); // Import Clue Board FileReader boardReader = new FileReader(board); Scanner boardIn = new Scanner(boardReader); String configString = ""; int col_count = -1; int row_count = 0; while(boardIn.hasNextLine()) { line = boardIn.nextLine(); configString += line + ","; parts = line.split(","); if(col_count == -1) { col_count = parts.length; } else { if(col_count != parts.length) { boardIn.close(); boardReader.close(); throw new BadConfigFormatException("Line length mismatch in board config."); } } row_count += 1; } boardIn.close(); boardReader.close(); String[] tempConfig = configString.split(","); String value; for(String i : tempConfig) { value = rooms.get(i.charAt(0)); if(value == null) throw new BadConfigFormatException("Invalid room character in board config."); } numCols = col_count; numRows = row_count; config = tempConfig; }
9
public double getWidth() { return width; }
0
private TextMeasurer tm() { if(tm == null) tm = new TextMeasurer(str.getIterator(), rs.frc); return(tm); }
1
@Override public int getResponseSize(final ByteBuffer buf) throws Exception { // Need at least the encapsulation header int needed = 24 - buf.position(); if (needed > 0) return needed; // Buffer contains header (and maybe more after that) final short command_code = buf.getShort(0); final Command command = Command.forCode(command_code); if (command == null) throw new Exception("Received unknown command code " + command_code); if (command != this.command) throw new Exception("Received command " + command + " instead of " + this.command); final short body_size = buf.getShort(2); return 24 + body_size; }
3
public boolean lineFree(int x1, int y1, int x2, int y2) { if(x1 == x2) { int start = Math.min(y1, y2); int end = Math.max(y1, y2); for(int i = start; i <= end; i++) { if(evaluationMap[x1][i] == WALL_VALUE) return false; } return true; } else if(y1 == y2) { int start = Math.min(x1, x2); int end = Math.max(x1, x2); for(int i = start; i <= end; i++) { if(evaluationMap[i][y1] == WALL_VALUE) return false; } return true; } return false; }
6
@Override public void deserialize(Buffer buf) { name = buf.readString(); worldX = buf.readShort(); if (worldX < -255 || worldX > 255) throw new RuntimeException("Forbidden value on worldX = " + worldX + ", it doesn't respect the following condition : worldX < -255 || worldX > 255"); worldY = buf.readShort(); if (worldY < -255 || worldY > 255) throw new RuntimeException("Forbidden value on worldY = " + worldY + ", it doesn't respect the following condition : worldY < -255 || worldY > 255"); liberator = buf.readString(); }
4
@Basic @Column(name = "CSA_FECHA_HORA") public Date getCsaFechaHora() { return csaFechaHora; }
0
public static void uploadFileAsBlob(String fullPath) { // TODO Auto-generated method stub FileInputStream fis = null; try { CloudStorageAccount storageAccount = CloudStorageAccount .parse(Connection.storageConnectionString); CloudBlobClient blobClient = storageAccount.createCloudBlobClient(); CloudBlobContainer container = blobClient .getContainerReference(containerName); // System.out.println("The relative path is " + // FileFunctions.getRelativePath(fullPath)); CloudBlockBlob blob = container.getBlockBlobReference(FileFunctions .getRelativePath(fullPath)); File source = new File(fullPath); if (source.exists()) { if (blob.exists()) { blob.downloadAttributes(); if (new Date(blob.getMetadata().get("dateModified")) .after(new Date((FileFunctions .convertTimeToUTC(FileFunctions .convertTimestampToDate(source .lastModified())))))) { System.out.println(source.getName() + " is up to date so it is not uploaded"); return; } } fis = new FileInputStream(source); System.gc(); HashMap<String, String> meta = new HashMap<String, String>(); meta.put("dateModified", FileFunctions .convertTimeToUTC(FileFunctions .convertTimestampToDate(source.lastModified()))); blob.setMetadata(meta); if (!source.isHidden()) { System.out.println(source.getName() + " is not up to date so it is uploaded"); blob.upload(fis, source.length()); } fis.close(); } } catch (URISyntaxException | InvalidKeyException | StorageException | IOException ex) { Logger.getLogger(BlobManager.class.getName()).log(Level.SEVERE, null, ex); if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
9
private void EquipaSelecionada_LabelPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_EquipaSelecionada_LabelPropertyChange if(EquipaSelecionada_Label.getText().equals("nenhuma")) { for(Component component: DadosJogador_Panel.getComponents()) component.setEnabled(false); DadosJogador_Panel.setEnabled(false); } else { for(Component component: DadosJogador_Panel.getComponents()) component.setEnabled(true); DadosJogador_Panel.setEnabled(true); } }//GEN-LAST:event_EquipaSelecionada_LabelPropertyChange
3
public void process() { while (!eventQueue.isEmpty()) { Event event = eventQueue.poll(); if (listenerRegistry.containsKey(event.getType())) for (EventListener listener : listenerRegistry.get(event.getType())) listener.notify(event); } }
3
private void usage() { System.out.println( "Usage: java -jar jfht.jar [options]\n" + "\n" + "\t-n [num]: number of items to insert\n" + "\t-m [num]: number of right shifts of optimal bloom filter length\n" + "\t-k [num]: number of hash functions to use, none or 0 for optimal\n" + "\t-r [num]: number of bits to check for hash calculation\n" + "\t-c [num]: word size of compression\n" + "\t-s [num]: number of simulation runs\n" + "\t-t [num]: number of threads\n" + "\n" ); }
0
private void check() { //each route for (Route r : Solution.getRoutes()) { int type = r.getType(); if (r.getRequests().get(0).getNodeId() != -1) { int routeNodeStart = r.getRequests().get(0).getNodeId(); int routeNodeArrival = r.getRequests().get(r.getRequests().size()-1) .getNodeId(); //each vehicle for (Vehicle v : Instance.getFleet()) { if (v.getAttribute("type").get(0) != null) { int vehicleType = ((IntValue)v.getAttribute("type").get(0)).getValue(); if (vehicleType == type) { int vehicleNodeArrival = ((IntValue) v.getAttribute("arrivalNode").get(0)).getValue(); int vehicleNodeStart = ((IntValue) v.getAttribute("departureNode").get(0)).getValue(); if (vehicleNodeArrival != routeNodeArrival|| vehicleNodeStart != routeNodeStart){ cEval.addMessage("DepartureArrivalNode|On Route ID : "+r.getId()+ ", Departure Node : "+routeNodeStart+ ", Arrival Node : "+routeNodeArrival+ " but Vehicle of type "+vehicleType+ " Departure Node is "+vehicleNodeStart+ " and Arrival Node is "+vehicleNodeArrival); } } } else { int vehicleNodeArrival = ((IntValue) v.getAttribute("arrivalNode").get(0)).getValue(); int vehicleNodeStart = ((IntValue) v.getAttribute("departureNode").get(0)).getValue(); if (((IntValue) v.getAttribute("arrivalNode").get(0)).getValue() != routeNodeArrival|| ((IntValue) v.getAttribute("departureNode").get(0)).getValue() != routeNodeStart){ cEval.addMessage("DepartureArrivalNode|On Route ID : "+r.getId()+ ", Departure Node : "+routeNodeStart+ ", Arrival Node : "+routeNodeArrival+ " but Vehicle "+ " Departure Node is "+vehicleNodeStart+ " and Arrival Node is "+vehicleNodeArrival); } } } } } }
9
public BigDecimal getBigDecimal() { BigDecimal expValue2 = null; BigDecimal fraction2 = null; switch (numberType) { case Nan: return null; case Infinite: { return null; } case SubNormalized: // ����SubNormal����ֵ expValue2 = new BigDecimal("2").pow(config.MaxExp - 1); expValue2 = new BigDecimal("1").divide(expValue2); fraction2 = BigDecimal.valueOf(fraction).divide( new BigDecimal(2).pow(config.FractionBitCount)); // Attetion break; case Normalized: if (specialValue == FloatNumberSpecialValue.Zero) { if (negative) return BigDecimal.valueOf(-0d); else return BigDecimal.valueOf(0d); } expValue2 = new BigDecimal("2").pow(Math.abs(normalizedExp)); if (normalizedExp < 0) expValue2 = new BigDecimal("1").divide(expValue2); fraction2 = BigDecimal.valueOf(fraction) .divide(new BigDecimal(2).pow(config.FractionBitCount)) .add(new BigDecimal(1)); // Attetion break; } BigDecimal r = fraction2.multiply(expValue2); if (negative) r = r.multiply(new BigDecimal(-1)); return r; }
8
private void computeDeleCommand(String message) { String[] cmd = message.split(" "); if (cmd.length > 1) { int n = Integer.parseInt(cmd[1]); if (mails.containsKey(n)) { // Mail ist noch nicht geloescht if (!mailIsDeleted(n)) { // Mail wird geloescht deletedMails.add(n); try { writeToClient("+OK message " + n + " deleted"); } catch (IOException e) { deleteMailsOnException(); sTrace.error("Connection aborted by client! Thread" + name); } } else { // Mail wurde bereits geloescht try { writeToClient("-ERR message " + n + " already deleted"); } catch (IOException e) { deleteMailsOnException(); sTrace.error("Connection aborted by client! Thread" + name); } } } else { // Keine Mail mit der Nummer n gefunden try { writeToClient("-ERR no such message"); } catch (IOException e) { deleteMailsOnException(); sTrace.error("Connection aborted by client! Thread" + name); } } } else { // Nachricht enthielt kein Argument try { writeToClient("-ERR no argument found"); } catch (IOException e) { deleteMailsOnException(); sTrace.error("Connection aborted by client! Thread" + name); } } }
7
private File getURLClassFile(String url) { File classFile = new File("temp.class"); try { URL u = new URL(url); InputStream inputStream = u.openStream(); OutputStream outputStream = new FileOutputStream(classFile); byte[] buffer = new byte[1024]; int count; while ((count = inputStream.read(buffer)) != -1) outputStream.write(buffer, 0, count); outputStream.close(); inputStream.close(); return classFile; } catch (IOException e) { e.printStackTrace(); } return null; }
2
public static boolean addUser(DBC dbc, String username, String password, String email) throws addUserException{ boolean success = true; String errors ="", hash="", salt; // validate username if( !validUsername(username)){ errors += "Invalid Username. "; success = false; } else{ //if username is valid check if exists if(userExistsUsername(dbc,username)){ errors += "Username Exists. "; success = false; } } // validate email if( !email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$")){ errors += "Invalid Email. "; success = false; } else{ // check if email exists if(userExistsEmail(dbc,email)){ errors += "Email Exists. "; success = false; } } // check password.length if(password.length() < 7 ){ errors += "Password must be at least 7 characters. "; success = false; } // generate a large random number to hash for a salt Random generator = new Random(); salt = String.valueOf(generator.nextDouble()).replace('.', '9'); //hash the password with the salt try{ salt = doMD5(salt); password = doMD5(password); hash = doMD5(password + salt); } catch(NoSuchAlgorithmException e){ success=false; errors += "Hashing algorithm failed. "; } // If we've encountered any exceptions at all throw them here if(!success) throw new addUserException(errors); else{ // otherwise add the user to the DB String q = "INSERT INTO users " + "(username,email,password,salt)" + "VALUES ('"+ username +"','"+ email +"','"+ hash +"','"+ salt +"')"; try{ String key = dbc.executeUpdate(q); System.out.println("added new user " + key); q = "SELECT user_id FROM users WHERE rowid='"+key+"'"; ResultSet res = dbc.executeQuery(q); int uid=-1; if (res.next()) uid=res.getInt(1); System.out.println("added new user " + uid); } catch(SQLException e){ System.out.println("Error adding new user: " + e); System.out.println("With query: " + q); } } return success; }
9
public String getUserName() { return userName; }
0
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(args.length==1){ BansManager.banPlayer(sender.getName(),args[0], ""); return true; } if(args.length>1){ String msg = ""; for(String data: args){ if(!data.equals(args[0])){ msg+=data+" "; } } BansManager.banPlayer(sender.getName(),args[0],msg); return true; } return false; }
4
@Override public void affectCharStats(MOB affected, CharStats affectableStats) { super.affectCharStats(affected,affectableStats); if(increase <= 0) { increase = 1; if (affectableStats.getCurrentClass().baseClass().equals("Thief")) increase = 2; if (affectableStats.getCurrentClass().baseClass().equals("Bard")) increase = 2; if (affectableStats.getCurrentClass().baseClass().equals("Fighter")) increase = 3; if (affectableStats.getCurrentClass().baseClass().equals("Mage")) increase = 2; if (affectableStats.getCurrentClass().baseClass().equals("Cleric")) increase = 1; if (affectableStats.getCurrentClass().baseClass().equals("Druid")) increase = 1; increase += (getXLEVELLevel(invoker())+2)/3; } affectableStats.setStat(CharStats.STAT_DEXTERITY,affectableStats.getStat(CharStats.STAT_DEXTERITY) + increase); }
7
public void askWhereToSave() { String[] options = {trans.getString("GetPath.home"),trans.getString("GetPath.portable")}; int choose = JOptionPane.showOptionDialog(null,trans.getString("GetPath.WhereSaveQuestion"), trans.getString("GetPath.WhereSaveTitle"),JOptionPane.DEFAULT_OPTION,JOptionPane.QUESTION_MESSAGE,null, options,options[0]); if(choose == 1) { path = "StreamRipStar"; } else { //create the OS specific directories if (opsys.startsWith("Windows")) { path = home+"\\.StreamRipStar"; } else if(opsys.startsWith("Linux")) { path = home+"/.StreamRipStar"; } else { String sep = System.getProperty("file.separator"); path = home+sep+".StreamRipStar"; } } //finally create the directory for the config file new File(path).mkdir(); }
3
@Override public String toString() { return "STORE " + new Integer(offset).toString() + " " + identifier + " " + identifier + " = " + new Integer(storedValueForPrinting). toString(); }
0
protected String getDocPath (int docSelector) { // if we're outta bounds ... if ((docSelector < 0) || (docSelector > docPaths.length)) { // ... return bupkis return null ; } // end if // we're in bounds. return the path name return docPaths[docSelector] ; } // end method getDocPath
2
public <T> List<T> findMoreRefResult(String sql, List<Object> params, Class<T> cls) throws Exception { List<T> list = new ArrayList<T>(); int index = 1; pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int cols_len = metaData.getColumnCount(); while (resultSet.next()) { T resultObject = cls.newInstance(); for (int i = 0; i < cols_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null) { cols_value = ""; } Field field = cls.getDeclaredField(cols_name); field.setAccessible(true); field.set(resultObject, cols_value); } list.add(resultObject); } return list; }
6
private void inhibitLateralSameShapeRecognizers(int shape) { int shapeOffset = 2500 * shape; double inhibWeight = 1.0; int toNeuron; for (int neuron = 0; neuron < 2500; neuron += 5) { int fromNeuron = neuron + shapeOffset; int fromRow = neuron / 50; if ((fromRow % 10) >= 5) {// only for bottom half. // int fromBigRow = neuron/500; int fromCol = neuron % 50; int fromBigCol = fromCol / 10; for (int toBigCol = fromBigCol - 1; toBigCol <= fromBigCol + 1; toBigCol++) { // not off the edge if (toBigCol >= 0 && toBigCol < 5) { // not self if (!(toBigCol == fromBigCol)) { for (int i = 0; i < 10; i++) { toNeuron = fromRow * 50 + toBigCol * 10 + i; addConnection(fromNeuron, toNeuron, inhibWeight); } } } } } } }
7
public static ArrayList<Excel> rotateY(int angle, ArrayList<Excel> toScale) { ArrayList<Excel> result = new ArrayList<Excel>(); double matrix[][] = { {Math.cos(angle * Math.PI/180), 0, -Math.sin(angle* Math.PI/180),0}, {0, 1 ,0, 0}, {Math.sin(angle* Math.PI/180),0, Math.cos(angle* Math.PI/180),0}, {0, 0,0,1} }; Matrix scaleMatrix = new Matrix(4,4); scaleMatrix.setMatrix(matrix); for (Excel ex: toScale) { double l[][] = {{ex.getX()}, {ex.getY()}, {ex.getZ()}, {ex.getT()} }; Matrix line = new Matrix(4,1); line.setMatrix(l); Matrix multiplied = Matrix.matrixMultiplication(scaleMatrix, line); int x =(int) Math.round(multiplied.getEl(0, 0)); int y =(int) Math.round(multiplied.getEl(1, 0)); int z =(int) Math.round(multiplied.getEl(2, 0)); int t =(int) Math.round(multiplied.getEl(3, 0)); result.add(new Excel(x,y,z,t, ex.getColor())); } return result; }
1
public ProtocolThread(Socket socket) { System.out.println("Accepting connection from " + socket.getInetAddress() + "..."); this.socket = socket; try { out_socket = new PrintWriter(socket.getOutputStream(), true); in_socket = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (IOException e) { e.printStackTrace(); } }
1
public void visit_imul(final Instruction inst) { stackHeight -= 2; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } stackHeight += 1; }
1
@SuppressWarnings("serial") private Action getDeleteAction() { if (this.deleteAction == null) { String actionCommand = bundle.getString(DELETE_NODE_KEY); String actionKey = bundle.getString(DELETE_NODE_KEY + ".action"); this.deleteAction = new AbstractAction(actionCommand) { @Override public void actionPerformed(ActionEvent e) { System.out.println("actionPerformed(): action = " + e.getActionCommand()); if (checkAction()) { // Checks if several nodes will be deleted if (nodes.length > 1) { model.deleteNodes(nodes); } else { model.deleteNode(nodes[0]); } } } private boolean checkAction() { // No node selected if (nodes == null) { JOptionPane.showMessageDialog(JZVNode.this, bundle .getString("dlg.error.deleteWithoutSelection"), bundle.getString("dlg.error.title"), JOptionPane.ERROR_MESSAGE); return false; } return true; } }; this.deleteAction.putValue(Action.ACTION_COMMAND_KEY, actionKey); this.getInputMap(WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), actionKey); this.getActionMap().put(actionKey, this.deleteAction); } return this.deleteAction; }
4
@Override public void run() { int whatdo = Random.nextInt(0, 10); switch (whatdo) { case 0: case 1: Mouse.move(Random.nextInt(0, 750), Random.nextInt(16, 500)); break; case 2: case 3: case 5: case 4: case 7: case 8: Camera.setAngle(Random.nextInt(0, 360)); break; default: Camera.setAngle(Random.nextInt(0, 360)); break; } }
8
public Integer getTaskCount(){ return taskCounter.get().intValue(); }
0
public boolean isPassiv() { for (Vertrag vertrag : vertragCollection) { if (vertrag.getAktiv()) { return false; } } return true; }
2
public static void playGame(GameFactory factory) { Game s = factory.getGame(); while (s.move()) { } }
1
public static void main(String[] args) { for (int i = 1; i <= 100; i++){ if (i % 5 == 0 || i % 7 == 0){ if (i % 5 == 0){ if (i % 7 == 0) System.out.println("ABBA"); else System.out.println("A"); } else System.out.println("B"); } else System.out.println(i); } }
5
@Override public synchronized void down() { super.down(); if (bulbPower > 0) { bulbPower--; } if (bulbPower == 0) { startEntryPoint.insert(new ReachedBottom()); } sendImageToGUI(); }
2
private void initExceptionMessage() { if(descriptor.getException() == null) { add(createMessageLabel(), BorderLayout.CENTER); return; } JTabbedPane tabs = new JTabbedPane(); tabs.addTab("Description", createMessageLabel()); JTextArea expTA = new JTextArea(); expTA.setEditable(false); //Font f = expTA.getFont(); //expTA.setFont(f.deriveFont((float)f.getSize()-2)); JScrollPane sp = new JScrollPane(expTA); Throwable t = descriptor.getException(); expTA.append(t.getClass().getName()+":"); expTA.append((t.getMessage()!=null?t.getMessage():"")); expTA.append("\n"); while(t != null) { StackTraceElement st[] = t.getStackTrace(); for(int i=0;i<st.length;i++) { expTA.append(" at "+st[i].toString()+"\n"); } t = t.getCause(); if(t != null) { expTA.append("\nCaused By:"+t.getClass().getName()+":"); expTA.append((t.getMessage()!=null?t.getMessage():"")); expTA.append("\n"); } } tabs.addTab("Details", sp); tabs.setBorder(new EmptyBorder(5,5,5,5)); Dimension ps = tabs.getSize(); if(ps.width < 300 || ps.height < 300) { ps = new Dimension(300,300); tabs.setPreferredSize(ps); } add(tabs, BorderLayout.CENTER); }
8
public List<EventBranch> findEventBranchesByHallEventId(final Long hallEventId) { return new ArrayList<EventBranch>(); }
0
private boolean checkUserInDB(String s, String s1, String s2) { String s3 = null; s = s.trim().toLowerCase(); s1 = s1.trim().toLowerCase(); DbAccess dbaccess = null; try { dbaccess = dbManager.takeDbaRef(); } catch(Exception exception) { throw new UserError("Could not get database reference when checking user \"" + s + "\" with password \"" + s1 + "\".", exception); } try { ResultSet resultset = dbaccess.executeQuery("select * from users where userid = '" + s + "' and botid = '" + s2 + "'"); int i = 0; while(resultset.next()) { if(++i == 1) s3 = resultset.getString("password"); if(i == 0) { resultset.close(); dbManager.returnDbaRef(dbaccess); return false; } if(i > 1) throw new UserError("Duplicate user name: \"" + s + "\""); } resultset.close(); dbManager.returnDbaRef(dbaccess); } catch(SQLException sqlexception) { throw new UserError("Database error.", sqlexception); } if(s3 == null) return false; return s1.equals(s3); }
7
public void run() { init(); long start, elapsed, wait; while(running) { start = System.nanoTime(); update(); draw(); drawToScreen(); elapsed = System.nanoTime() - start; wait = TARGET_TIME - elapsed / 1000000; if(wait < 0) wait = TARGET_TIME; try { Thread.sleep(wait); } catch(Exception e) { e.printStackTrace(); } } }
3
private Socket getClientSocket() { Socket clientSocket = null; try { clientSocket = new Socket(this.destinationIpAddress, this.destinationPort); this.log.fine("Create new clientSocket: " + clientSocket.toString()); } catch (UnknownHostException e) { e.printStackTrace(); clientSocket = null; } catch (IOException e) { e.printStackTrace(); clientSocket = null; } return clientSocket; }
2
protected String getQueryString(RequestBean request) throws CitysearchException { log.info("Start OfferProxy getQueryString()"); StringBuilder strBuilder = new StringBuilder(); strBuilder.append(constructQueryParam(APIFieldNameConstants.RPP, RPP_OFFERS)); strBuilder.append(CommonConstants.SYMBOL_AMPERSAND); strBuilder.append(constructQueryParam(APIFieldNameConstants.CLIENT_IP, request.getClientIP())); strBuilder.append(CommonConstants.SYMBOL_AMPERSAND); if (!StringUtils.isBlank(request.getWhat())) { // Offers API throws internal error when reading sushi+restaurant String what = request.getWhat().trim(); try { what = URLEncoder.encode(what, "UTF-8"); } catch (UnsupportedEncodingException excep) { throw new CitysearchException("OffersHelper", "getQueryString", excep); } strBuilder.append(constructQueryParam(APIFieldNameConstants.WHAT, what)); } if (!StringUtils.isBlank(request.getLatitude()) && !StringUtils.isBlank(request.getLongitude())) { strBuilder.append(CommonConstants.SYMBOL_AMPERSAND); strBuilder.append(constructQueryParam( APIFieldNameConstants.LATITUDE, request.getLatitude() .trim())); strBuilder.append(CommonConstants.SYMBOL_AMPERSAND); strBuilder.append(constructQueryParam( APIFieldNameConstants.LONGITUDE, request.getLongitude() .trim())); } else { strBuilder.append(CommonConstants.SYMBOL_AMPERSAND); strBuilder.append(constructQueryParam(APIFieldNameConstants.WHERE, request.getWhere().trim())); } if (!StringUtils.isBlank(request.getTag())) { strBuilder.append(CommonConstants.SYMBOL_AMPERSAND); strBuilder.append(constructQueryParam(APIFieldNameConstants.TAG, request.getTag().trim())); } if (!StringUtils.isBlank(request.getExpiresBefore())) { strBuilder.append(CommonConstants.SYMBOL_AMPERSAND); strBuilder.append(constructQueryParam( APIFieldNameConstants.EXPIRES_BEFORE, request .getExpiresBefore().trim())); } if (!StringUtils.isBlank(request.getCustomerHasbudget())) { strBuilder.append(CommonConstants.SYMBOL_AMPERSAND); strBuilder.append(constructQueryParam( APIFieldNameConstants.CUSTOMER_HASBUDGET, String .valueOf(request.getCustomerHasbudget().trim()))); } if (!StringUtils.isBlank(request.getRadius())) { strBuilder.append(CommonConstants.SYMBOL_AMPERSAND); String radius = Utils.parseRadius(request.getRadius()); request.setRadius(radius); strBuilder.append(constructQueryParam(APIFieldNameConstants.RADIUS, request.getRadius())); } if (!StringUtils.isBlank(request.getCallBackFunction())) { strBuilder.append(CommonConstants.SYMBOL_AMPERSAND); strBuilder.append(constructQueryParam( APIFieldNameConstants.CALLBACK, request .getCallBackFunction().trim())); } log.info("Start OfferProxy getQueryString() querystring is " + strBuilder); return strBuilder.toString(); }
9
public void listen() { System.out.println("Node listening for requests..."); while (!m_exitFlag) { int incomingPolls = m_poller.poll(); if (incomingPolls > 0) { for (int i = 0; i < m_incomingSockets.size(); i++) { if (m_poller.pollin(i)) { receiveMessage(ZstIo.recv(m_poller.getSocket(i))); } } } } System.out.println("Exiting listen loop"); }
4
@Override public void cleanUp() { // Synchronise the waitingEventLists which stores the list of all events // which were collected during the previous logic update and clear each // individual key synchronized (waitingEventLists) { for (Collection<EventHolder> eventHolderList : waitingEventLists.values()) { eventHolderList.clear(); } } // Clear the list of all registered IKeyboardEventable that wanted to // recieve key events during the next logic update. synchronized (registeredListeningObjects) { registeredListeningObjects.clear(); } }
1
static Class<?> getClass(Type type) { if (type instanceof Class) { return (Class<?>) type; } else if (type instanceof ParameterizedType) { return getClass(((ParameterizedType) type).getRawType()); } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType) type).getGenericComponentType(); Class<?> componentClass = getClass(componentType); return componentClass == null ? null : newInstance(componentClass, 0).getClass(); } return null; // wildcard type or typevariable }
7
public Function getFunction (String literal) { int functionCount = this.functionList.size(); for(int i = 0;i<functionCount;i++) { Function currentFunction = this.functionList.get(i); String currentText = currentFunction.getLiteral(); boolean isMatchingExpression = literal.equals(currentText); if (isMatchingExpression) { return currentFunction; } } return null; }
2
private boolean allSitesHasVarRecover(int index) { for(int i: sitesHasVar(index).keySet()) { Site site = sitesHasVar(index).get(i); if(site.isUp()) { return false; } } return true; }
2
public void validity(){ }
0
private boolean isConcealedSquare(long n) { int[] digits = Numbers.getDigits(n * n); if(digits.length < 17) { return false; } return digits[0] == 9 && digits[2] == 8 && digits[4] == 7 && digits[6] == 6 && digits[8] == 5 && digits[10] == 4 && digits[12] == 3 && digits[14] == 2 && digits[16] == 1; }
9
@Override public IRailwayMap processRailwayGraph(final String graphInput) throws DuplicateRouteException, OrphanStationException { IRailwayMap trainMap = new RailwayMap(); HashMap<Character, Integer> checkLinkageMap = new HashMap<Character, Integer>(); String[] routes = preprocessGraphValue(graphInput); for (String route : routes) { if (isValidRouteSet(route)) { char fromStation = route.charAt(GRAPH_INPUT_FROM_STATION_INDEX); char toStation = route.charAt(GRAPH_INPUT_TARGET_STATION_INDEX); int distance = Integer.parseInt(route.substring(STATION_TO_STATION_DISTANCE_INDEX, route.length())); IRailwayEntity fromStationEntity = null; IRailwayEntity toStationEntity = null; // Create station if it hasn't been created before. if (!trainMap.hasStation(fromStation)) { fromStationEntity = new RailwayStation(fromStation); trainMap.insertRailEntity(fromStationEntity); } if (!trainMap.hasStation(toStation)) { toStationEntity = new RailwayStation(toStation); trainMap.insertRailEntity(toStationEntity); } fromStationEntity = trainMap.getStation(fromStation); toStationEntity = trainMap.getStation(toStation); // Create linkage between both stations fromStationEntity.addOutboundStation(toStationEntity, distance); // Mark the TO-station as accessible. if (!checkLinkageMap.containsKey(toStation)) { checkLinkageMap.put(toStation, 1); } } } // Validate the train map and ensure that it is not a broken graph // that is, every defined stations is accessible int orphanNodeCount = 0; for(Character stationName : checkLinkageMap.keySet()) { if (!checkLinkageMap.containsKey(stationName)) { // this station is defined but is not accessible from other location orphanNodeCount++; } } // Assumption #1 - The first node is assumed as it will never be accessible. if (orphanNodeCount > 1 ) { throw new OrphanStationException(); } return trainMap; }
8
private Quote takeQuote(int maxLinesLimit) { for ( Quote q : quotes ) { if ( q.lines() <= maxLinesLimit ) return q; } return quotes.get(0); }
2
public static Vertex convertNode(org.yaoqiang.bpmn.model.elements.core.common.FlowNode inputNode){ Vertex outputNode = null; String type = inputNode.getClass().getCanonicalName(); if(outputNode == null){ if(type.toLowerCase().contains("gateway")){ //a.e.println(type + " " + inputNode.getName()); outputNode = new Vertex("" + inputNode.getName(), GraphLoader.ExclusiveGateway); if(type.toLowerCase().contains("exclusivegateway")){outputNode.isXOR = true;} if(type.toLowerCase().contains("parallelgateway")){outputNode.isAND = true;} if(type.toLowerCase().contains("inclusivegateway")){outputNode.isOR = true;} if(inputNode.getOutgoingSequenceFlows().size() > 1) outputNode.isSplit = true; else outputNode.isJoin = true; }else if(type.toLowerCase().contains("event")){ outputNode = new Vertex("" + inputNode.getName(), GraphLoader.IntermediateThrowEvent); }else{ outputNode = new Vertex("" + inputNode.getName(), GraphLoader.Task); } } outputNode.id = UUID.randomUUID().toString(); return outputNode; }
7
public List<Telefone> listarTodos(int idPessoa){ try{ PreparedStatement comando = banco.getConexao() .prepareStatement("SELECT * FROM telefones WHERE id_pessoa = ? AND" + " ativo = 1"); comando.setInt(1, idPessoa); ResultSet consulta = comando.executeQuery(); comando.getConnection().commit(); List<Telefone> listaTelefones = new LinkedList<>(); while(consulta.next()){ Telefone tmp = new Telefone(); tmp.setDdd(consulta.getInt("ddd")); tmp.setId(consulta.getInt("id")); tmp.setNumero(consulta.getInt("numero")); listaTelefones.add(tmp); } return listaTelefones; }catch(SQLException ex){ ex.printStackTrace(); return null; }catch(ErroValidacaoException ex){ ex.printStackTrace(); return null; } }
3
public static boolean createCheddarXml(List<Partition> lop, CartsModel cm, String filename) { // -> file File dir = new File(Airsched.DEFAULT_OUTPUT_DIR); // File file = new File(OUTPUT_FILE); File output_file = new File(Airsched.DEFAULT_OUTPUT_DIR + "/" + filename + "_period-" + cm.getModel_period() + "_execution-" + cm.getModel_execution() + "_bandwith-" + cm.getModel_bandwith() + ".xml"); // System.out.println(dir.getCanonicalPath()); if (!dir.exists()) { dir.mkdirs(); } if (!output_file.exists()) { try { output_file.createNewFile(); } catch (IOException e) { e.printStackTrace(); return false; } } // dir.mkdir(); // sorts order SortsOrder(cm); try { int id = 0; BufferedWriter bwriter; bwriter = new BufferedWriter(new FileWriter(output_file)); bwriter.write("<?xml version=\"1.0\" standalone=\"yes\"?>\n"); bwriter.write("<cheddar>\n"); bwriter.write(" <core_units>\n"); id++; bwriter.write(" <core_unit id=\"id_" + id + "\">\n"); bwriter.write(" <object_type>CORE_OBJECT_TYPE</object_type>\n"); bwriter.write(" <name>core1</name>\n"); bwriter.write(" <scheduling>\n"); bwriter.write(" <scheduling_parameters>\n"); bwriter.write(" <scheduler_type>HIERARCHICAL_CYCLIC_PROTOCOL</scheduler_type>\n"); bwriter.write(" <quantum>0</quantum>\n"); bwriter.write(" <preemptive_type>PREEMPTIVE</preemptive_type>\n"); bwriter.write(" <capacity>0</capacity>\n"); bwriter.write(" <period>0</period>\n"); bwriter.write(" <priority>0</priority>\n"); bwriter.write(" <start_time>0</start_time>\n"); bwriter.write(" </scheduling_parameters>\n"); bwriter.write(" </scheduling>\n"); bwriter.write(" <speed>1.00000</speed>\n"); bwriter.write(" </core_unit>\n"); bwriter.write(" </core_units>\n"); bwriter.write(" <address_spaces>\n"); ArrayList<CartsComponent> comps = cm.getModel_components(); for (int i = 0; i < comps.size(); i++) { id++; bwriter.write(" <address_space id=\"id_" + id + "\">\n"); bwriter.write(" <object_type>ADDRESS_SPACE_OBJECT_TYPE</object_type>\n"); bwriter.write(" <name>" + comps.get(i).getName() + "</name>\n"); bwriter.write(" <cpu_name>processor1</cpu_name>\n"); bwriter.write(" <text_memory_size>0</text_memory_size>\n"); bwriter.write(" <stack_memory_size>0</stack_memory_size>\n"); bwriter.write(" <data_memory_size>0</data_memory_size>\n"); bwriter.write(" <heap_memory_size>0</heap_memory_size>\n"); bwriter.write(" <scheduling>\n"); bwriter.write(" <scheduling_parameters>\n"); bwriter.write(" <scheduler_type>RATE_MONOTONIC_PROTOCOL</scheduler_type>\n"); bwriter.write(" <quantum>" + comps.get(i).getExecution() + "</quantum>\n"); bwriter.write(" <preemptive_type>PREEMPTIVE</preemptive_type>\n"); bwriter.write(" <capacity>0</capacity>\n"); bwriter.write(" <period>0</period>\n"); bwriter.write(" <priority>0</priority>\n"); bwriter.write(" <start_time>0</start_time>\n"); bwriter.write(" </scheduling_parameters>\n"); bwriter.write(" </scheduling>\n"); bwriter.write(" </address_space>\n"); } /* * // IDLE PARTITION if (Airsched.getPartitionPaddingMode() == * Airsched.DUMMY_PARTITION_PADDING) { int sysIdle = * cm.getSystemIdle(); if (sysIdle > 0) { id++; * bwriter.write(" <address_space id=\" " + id + "\">\n"); * bwriter * .write(" <object_type>ADDRESS_SPACE_OBJECT_TYPE</object_type>\n" * ); bwriter.write(" <name>SYSTEM_IDLE</name>\n"); * bwriter.write(" <cpu_name>processor1</cpu_name>\n"); * bwriter.write(" <text_memory_size>0</text_memory_size>\n"); * bwriter * .write(" <stack_memory_size>0</stack_memory_size>\n"); * bwriter.write(" <data_memory_size>0</data_memory_size>\n"); * bwriter.write(" <heap_memory_size>0</heap_memory_size>\n"); * bwriter.write(" <scheduling>\n"); * bwriter.write(" <scheduling_parameters>\n"); * bwriter.write( * " <scheduler_type>RATE_MONOTONIC_PROTOCOL</scheduler_type>\n" * ); bwriter.write(" <quantum>" + sysIdle + * "</quantum>\n"); bwriter.write( * " <preemptive_type>PREEMPTIVE</preemptive_type>\n"); * bwriter.write(" <capacity>0</capacity>\n"); * bwriter.write(" <period>0</period>\n"); * bwriter.write(" <priority>0</priority>\n"); * bwriter.write(" <start_time>0</start_time>\n"); * bwriter.write(" </scheduling_parameters>\n"); * bwriter.write(" </scheduling>\n"); * bwriter.write(" </address_space>\n"); } } // END OF DUMMY * PARTITION */ bwriter.write(" </address_spaces>\n"); bwriter.write(" <processors>\n"); id++; bwriter.write(" <mono_core_processor id=\"id_" + id + "\">\n"); bwriter.write(" <object_type>PROCESSOR_OBJECT_TYPE</object_type>\n"); bwriter.write(" <name>processor1</name>\n"); bwriter.write(" <network>a_network</network>\n"); bwriter.write(" <processor_type>MONOCORE_TYPE</processor_type>\n"); bwriter.write(" <migration_type>NO_MIGRATION_TYPE</migration_type>\n"); bwriter.write(" <core ref=\"id_1\">\n"); bwriter.write(" </core>\n"); bwriter.write(" </mono_core_processor>\n"); bwriter.write(" </processors>\n"); bwriter.write(" <tasks>\n"); // for (Partition p : lop) { for (CartsComponent cc : comps) { Partition p = PartitionUtils.getPartition(lop, cc.getName()); if (p != null) { for (PeriodicTask pt : p.getWorkload()) { id++; bwriter.write(" <periodic_task id=\"id_" + id + "\">\n"); bwriter.write(" <object_type>TASK_OBJECT_TYPE</object_type>\n"); bwriter.write(" <name>" + p.getName() + "_" + pt.getName() + "</name>\n"); bwriter.write(" <task_type>PERIODIC_TYPE</task_type>\n"); bwriter.write(" <cpu_name>processor1</cpu_name>\n"); bwriter.write(" <address_space_name>" + p.getName() + "</address_space_name>\n"); bwriter.write(" <capacity>" + pt.getCapacity() + "</capacity>\n"); bwriter.write(" <deadline>" + pt.getPeriod() + "</deadline>\n"); bwriter.write(" <start_time>0</start_time>\n"); bwriter.write(" <priority>1</priority>\n"); bwriter.write(" <blocking_time>0</blocking_time>\n"); bwriter.write(" <policy>SCHED_FIFO</policy>\n"); bwriter.write(" <text_memory_size>0</text_memory_size>\n"); bwriter.write(" <stack_memory_size>0</stack_memory_size>\n"); bwriter.write(" <criticality>0</criticality>\n"); bwriter.write(" <context_switch_overhead>0</context_switch_overhead>\n"); bwriter.write(" <period>" + pt.getPeriod() + "</period>\n"); bwriter.write(" <jitter>0</jitter>\n"); bwriter.write(" </periodic_task>\n"); } } } bwriter.write(" </tasks>\n"); bwriter.write("</cheddar>"); bwriter.flush(); bwriter.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
8
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(ALLusers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ALLusers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ALLusers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ALLusers.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 ALLusers().setVisible(true); } }); }
6
public static double[][][] createGridAround(double[] point, int m){ double xAxis[][] = new double[m*2+1][2]; double yAxis[][] = new double[m*2+1][2]; for(int i=1;i<=m; i++){ double nextPoint[]= GeoUtil.nextPoint(point, 100*i, 0); xAxis[m+i] = nextPoint; } for(int i=1;i<=m; i++){ double nextPoint[]= GeoUtil.nextPoint(point, 100*i, Math.PI/2); yAxis[m+i] = nextPoint; } for(int i=1;i<=m; i++){ double nextPoint[]= GeoUtil.nextPoint(point, 100*i, Math.PI); xAxis[m-i] = nextPoint; } for(int i=1;i<=m; i++){ double nextPoint[]= GeoUtil.nextPoint(point, 100*i, 3*Math.PI/2); yAxis[m-i] = nextPoint; } xAxis[m]= point; yAxis[m]= point; int n = 2*m*2*m; double[][][] grid = new double[n][2][2]; for(int i=0;i<2*m; i++){ for(int j=0;j<2*m; j++){ grid[i*2*m+j][0][0]= yAxis[i][0]; grid[i*2*m+j][0][1]= xAxis[j][1]; grid[i*2*m+j][1][0]= yAxis[i+1][0]; grid[i*2*m+j][1][1]= xAxis[j+1][1]; } } return grid; }
6
*/ @Override public int compare(SchemaError arg0, SchemaError arg1) { if(arg0==null && arg1==null){ return 0; } if(arg0==null){ return 1; } if(arg1==null){ return -1; } if(arg0.getError().getErrorType()==arg1.getError().getErrorType()){ return 0; } return getRank(arg1.getError().getErrorType())-getRank(arg0.getError().getErrorType()); }
5
public void setName(String name) { this.name = name; }
0
public int Decode(Decoder rangeDecoder) throws IOException { int m = 1; for (int bitIndex = NumBitLevels; bitIndex != 0; bitIndex--) m = (m << 1) + rangeDecoder.DecodeBit(Models, m); return m - (1 << NumBitLevels); }
1
private BufferedImage VerticalFiltering(BufferedImage pbImage, int iOutH) { int iW = pbImage.getWidth(); int iH = pbImage.getHeight(); int value = 0; BufferedImage pbOut = new BufferedImage(iW, iOutH, BufferedImage.TYPE_INT_RGB); for (int y = 0; y < iOutH; y++) { int startY; int start; int Y = (int) (((double) y) * ((double) iH) / ((double) iOutH) + 0.5); startY = Y - nHalfDots; if (startY < 0) { startY = 0; start = nHalfDots - Y; } else { start = 0; } int stop; int stopY = Y + nHalfDots; if (stopY > (int) (iH - 1)) { stopY = iH - 1; stop = nHalfDots + (iH - 1 - Y); } else { stop = nHalfDots * 2; } if (start > 0 || stop < nDots - 1) { CalTempContrib(start, stop); for (int x = 0; x < iW; x++) { value = VerticalFilter(pbImage, startY, stopY, start, stop, x, tmpContrib); pbOut.setRGB(x, y, value); } } else { for (int x = 0; x < iW; x++) { value = VerticalFilter(pbImage, startY, stopY, start, stop, x, normContrib); pbOut.setRGB(x, y, value); } } } return pbOut; } // end of VerticalFiltering()
7
public void checkOperation (String operation, org.omg.CORBA.Any[] args) throws RTT.corba.CNoSuchNameException, RTT.corba.CWrongNumbArgException, RTT.corba.CWrongTypeArgException { org.omg.CORBA.portable.InputStream $in = null; try { org.omg.CORBA.portable.OutputStream $out = _request ("checkOperation", true); $out.write_string (operation); RTT.corba.CAnyArgumentsHelper.write ($out, args); $in = _invoke ($out); return; } catch (org.omg.CORBA.portable.ApplicationException $ex) { $in = $ex.getInputStream (); String _id = $ex.getId (); if (_id.equals ("IDL:RTT/corba/CNoSuchNameException:1.0")) throw RTT.corba.CNoSuchNameExceptionHelper.read ($in); else if (_id.equals ("IDL:RTT/corba/CWrongNumbArgException:1.0")) throw RTT.corba.CWrongNumbArgExceptionHelper.read ($in); else if (_id.equals ("IDL:RTT/corba/CWrongTypeArgException:1.0")) throw RTT.corba.CWrongTypeArgExceptionHelper.read ($in); else throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException $rm) { checkOperation (operation, args ); } finally { _releaseReply ($in); } } // checkOperation
5
public static void showPopularBooksReportsTable(ResultSet rs, String reportsQuery, Date[] years, int noBooks) { int numCols; ResultSetMetaData rsmd; JTextArea tableTitle = null; JTable table = null; try { rsmd = rs.getMetaData(); numCols = rsmd.getColumnCount(); String columnNames[] = new String[numCols]; for (int i = 0; i < numCols; i++) { columnNames[i] = rsmd.getColumnName(i + 1); } // For creating the size of the table PreparedStatement ps1 = Library.con.prepareStatement(reportsQuery); ps1.setDate(1, years[0]); ps1.setDate(2, years[1]); ps1.setInt(3, noBooks); ps1.executeQuery(); ResultSet count = ps1.getResultSet(); List<String> books = new ArrayList<String>(); while (count.next()) { books.add(count.getString("callNumber")); } Object data[][] = new Object[books.size()][numCols]; count.close(); String callNumber; String title; String mainAuthor; int timesBorrowed = 0; int j = 0; // Fill table while (rs.next()) { callNumber = rs.getString("callNumber"); title = rs.getString("title"); mainAuthor = rs.getString("mainAuthor"); timesBorrowed = rs.getInt("timesBorrowed"); Object tuple[] = { callNumber, title, mainAuthor, timesBorrowed }; data[j] = tuple; j++; } rs.close(); tableTitle = new JTextArea("Checked out Books Report"); table = new JTable(data, columnNames); if (data.length == 0) { new ErrorMessage("No books found."); } table.setEnabled(false); JScrollPane scrollPane = new JScrollPane(table); table.setAutoCreateRowSorter(true); // Display table table.setFillsViewportHeight(true); tablePane.removeAll(); tablePane.updateUI(); tableTitle.setEditable(false); tablePane.add(tableTitle); tablePane.add(scrollPane); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
5
public List<CertListing> getAll() { List<CertListing> courseListing = new ArrayList<CertListing>(); try { //Connect to database conn = DriverManager.getConnection(url, userName, password); stmt = conn.createStatement(); ResultSet rset = null; PreparedStatement pstmt = null; pstmt = conn.prepareStatement("select * FROM Certification group by Certification.number"); rset = pstmt.executeQuery(); while (rset.next()) { courseListing.add(new CertListing( rset.getDouble("price"), rset.getString("number"), rset.getString("name"), rset.getString("location"), rset.getString("unit"), rset.getString("duration"), rset.getString("type"), rset.getString("level"), rset.getString("category"), rset.getString("maxNumStudents"), rset.getString("program") )); } this.response = "Searched"; } catch (SQLException e) { response = "SQLException: " + e.getMessage(); while ((e = e.getNextException()) != null) { response = e.getMessage(); } } finally { try { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { response = "SQLException: " + e.getMessage(); while ((e = e.getNextException()) != null) { response = e.getMessage(); } } } return courseListing; }
7
public Object readResolve() { return INSTANCE; }
0
public SignatureVisitor visitReturnType() { endFormals(); if (seenParameter) { seenParameter = false; } else { declaration.append('('); } declaration.append(')'); returnType = new StringBuffer(); return new TraceSignatureVisitor(returnType); }
1
@Override public void run() { if (options.mode == Mode.BURIAL_ARMOUR) { final GameObject tunnel = ctx.objects.select().id(4618).nearest().poll(); if (tunnel.valid()) { if (ctx.camera.prepare(tunnel) && tunnel.interact("Climb")) { Condition.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return options.getAreaSmall().contains(ctx.players.local()); } }); } return; } } if (ctx.movement.findPath(ITile.randomize(options.getAreaSmall().getCentralTile(), 3, 3)).traverse() || ctx.movement.step(ITile.randomize(options.getAreaSmall().getCentralTile(), 3, 3))) { Condition.sleep(600); } /*if (LogArtisanWorkshop.getAreaSmall().getCentralTile().distanceTo(ctx.players.local()) > 100) { LogArtisanWorkshop.get().getLogHandler().print("Too far from Artisan Workshop"); }*/ }
6
public void service(){ while(true){ Socket socket=null; try { socket = serverSocket.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter pw = new PrintWriter(socket.getOutputStream(),true); String msg = null; while((msg=br.readLine())!=null){ System.out.println(msg); pw.println("server "+ msg); if(msg.equals("close server")){ break; } } } catch (IOException e) { e.printStackTrace(); }finally{ if(socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } System.exit(1); } } } }
6
private void testEntityCollision(double dt) { double xx = x + dx * dt; double yy = y + dy * dt; for (Entity e : level.getEntityNear(xx, yy, getWidth(), getHeight())) { if (e == this) continue; boolean collide = Collide.aabb(xx, yy + hIgnored, getWidth(), (int) (getHeight() - hIgnored), e.getBox().x, e.getBox().y, e.getBox().width, e.getBox().height); if (collide && collidesWith(e)) { this.onCollision(e); break; } } }
4
public void serialize(ByteWriter bw) throws IOException { int size = 16; byte[] label_b = label.getBytes(); size += label_b.length + 1; boolean u = false; if (!Charset.defaultCharset().newEncoder().canEncode(label)) { size += 4 + 1 + label.length() * 2 + 2; u = true; } bw.write4bytes(size); bw.write4bytes(dt); bw.write4bytes(dsn); int off = 16; if (u) off += 4; bw.write4bytes(off); off += label_b.length + 1; if (u) { off++; bw.write4bytes(off); off += label.length() * 2 + 2; } bw.writeBytes(label_b); bw.write(0); if (u) { bw.write(0); for (int i=0; i<label.length(); i++) bw.write2bytes(label.charAt(i)); bw.write2bytes(0); } }
5
private String getInvokerFor(File file) { String name = file.getName(); String ext = name.indexOf(".") != -1 ? name.substring(name.indexOf(".")) : ""; if (ext.equals(".exe")) return ""; else if (ext.equals(".jar")) return "java -jar "; else if (ext.equals(".bat")) return ""; else if (ext.equals("")) return ""; return null; }
5
private Config() { final InputStream in = getClass().getClassLoader().getResourceAsStream( CONFIG_FILE); if (in == null) { return; } byte[] bytes; try { bytes = new byte[in.available()]; in.read(bytes); final String[] lines = new String(bytes).split("\n"); Map<String, String> map = this.mapKV; for (final String line : lines) { if (!line.contains(" ")) { final String section = line; map = this.mapSKV.get(section); if (map == null) { final Map<String, String> _map = new LinkedMap<String, String>(); this.mapSKV.put(section, _map); map = _map; } } else { final String[] s = line.split(" ", 2); final String key = s[0]; final String value = s[1]; map.put(key, value); } } } catch (final IOException e) { e.printStackTrace(); } finally { try { in.close(); } catch (final IOException e) { e.printStackTrace(); } } }
6
public static List<String> twoArrayDiffData(String[] arr1,String[] arr2){ Integer arr1Length = arr1.length; Integer arr2Length = arr2.length; List<String> returnArr = new ArrayList<String>(); boolean flag = false; for(int i = 0; i< arr1Length; i++){ flag = false; for(int j = 0; j < arr2Length; j++){ if(arr2[j].equals(arr1[i])){ flag = true; } } if(!flag){ returnArr.add(arr1[i]); } } return returnArr; }
4
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AssRule other = (AssRule) obj; if (a == null) { if (other.a != null) return false; } else if (!a.equals(other.a)) return false; if (b == null) { if (other.b != null) return false; } else if (!b.equals(other.b)) return false; return true; }
9
public void writeToStream(OutputStream os) throws IOException { DataOutputStream dos = new DataOutputStream(os); for(int i = 0; i < ObjectList.size(); i++) { dos.writeBoolean(true); writeObjectToStream(ObjectList.get(i), ObjectType.get(i), ObjectNames.get(i), dos); } dos.writeBoolean(false); dos.flush(); }
1
public static String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String string = Double.toString(d); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
7
public void redirectError(Writer w) { if (w == null) { throw new NullPointerException("w"); } stderr = w; }
1