text
stringlengths
14
410k
label
int32
0
9
public Integer monthIndex(String candidateMonth) { if (candidateMonth == null) { return null; } candidateMonth = candidateMonth.toUpperCase(); // First, try for an exact match Integer monthIndex = monthMap.get(candidateMonth); // If no match, try an abbrev of four characters if possible if (monthIndex == null && candidateMonth.length() > 4) { monthIndex = monthMap.get(candidateMonth.substring(0, 4)); } // If still no match, truncate to 3 characters and retry // Consider where candidateMonth="DEC." and abbrev="DEC". if (monthIndex == null && candidateMonth.length() > 3) { monthIndex = monthMap.get(candidateMonth.substring(0, 3)); } return monthIndex; }
5
public Persistence() { // AQUI LOS RECUPERO (usarlo cuando abres la iu) try { FileInputStream fis = new FileInputStream(pathDB); ObjectInputStream ois = new ObjectInputStream(fis); Database database = (Database) ois.readObject(); activityService.setActivities(database.getActivities()); bookingService.setBookings(database.getBookings()); familyService.setStudents(database.getStudents()); bookingService.setDiningHall(database.getDiningHall()); familyService.setHousehold(database.getHouseholds()); ois.close(); } catch (FileNotFoundException e) { this.save(); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
3
public static void handleEvent(int eventId) { if(eventId == 1) { System.out.println("Exit load game menu selected"); Main.loadGameMenu.setVisible(false); Main.loadGameMenu.setEnabled(false); Main.loadGameMenu.setFocusable(false); Main.mainFrame.remove(Main.loadGameMenu); Main.mainFrame.add(Main.mainMenu); Main.mainMenu.setVisible(true); Main.mainMenu.setEnabled(true); Main.mainMenu.setFocusable(true); Main.mainMenu.requestFocusInWindow(); } else if(eventId == 2) { } else if(eventId == 3) { } else if(eventId == 4) { } else if(eventId == 5) { } }
5
public boolean exist(char[][] board, String word) { if (board == null || board.length == 0 || word == null || word.length() == 0) { return false; } for (int i = 0; i < board.length; i++) { char[] rowArray = board[i]; for (int j = 0; j < rowArray.length; j++) { if (search(board, i, j, word, 0, new HashMap<Integer, Boolean>())) { return true; } } } return false; }
7
@Override public void run() { if(animationStage == 1) { //System.out.println("Animation stage updated to 2!"); animationStage = 2; } else { //System.out.println("Animation stage updated to 1!"); animationStage = 1; } }
1
public static void main(String[] args) { boolean displayConsole = true; if (args.length > 0) { // it has arguments if (args.length == 1 && args[0].equalsIgnoreCase(Main.help)) { System.out.println("Starts the KOI server"); System.out.println("\nArguments:"); System.out.println(Main.noConsoleArg + " - does not create " + "a seperate console."); } int i; for (i = 0; i < args.length; ++i) { if (args[i].equalsIgnoreCase(Main.noConsoleArg)) { displayConsole = false; } } } // initialize the systems EventManager.getInstance();// creates the event manager PackageManager.getInstance();// creates the package manager if (displayConsole) { Console c = new Console(EventManager.getInstance()); PackageManager.getInstance().loadPackage(c); if (!PackageManager.getInstance().enableOnLoad()) { if (!PackageManager.getInstance().isEnabled(c.getName())) { PackageManager.getInstance().enable(c.getName()); } } } TaskManager manager = new TaskManager(PackageManager.getInstance()); manager.setVisible(true); ServerController servController = new ServerController(); PackageManager.getInstance().loadPackage(servController); PackageManager.getInstance().enable(servController); EventManager.getInstance().fireEvent(new ServerStarted()); }
8
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GrowthRate that = (GrowthRate) o; if (Double.compare(that.rate, rate) != 0) return false; return true; }
4
public Ticker(int tickrateMS) { rate = tickrateMS; s2 = Ticker.getTime(); }
0
private static final String unescapeHTML(String s, int start) { int i, j, k, l; i = s.indexOf("&", start); start = i + 1; if (i > -1) { j = s.indexOf(";", i); /* we don't want to start from the beginning the next time, to handle the case of the & thanks to Pieter Hertogh for the bug fix! */ if (j > i) { // ok this is not most optimized way to // do it, a StringBuffer would be better, // this is left as an exercise to the reader! String temp = s.substring(i, j + 1); // search in htmlEscape[][] if temp is there k = 0; while (k < htmlEscape.length) { if (htmlEscape[k][0].equals(temp)) { break; } else { k++; } } if (k < htmlEscape.length) { s = s.substring(0, i) + htmlEscape[k][1] + s.substring(j + 1); return unescapeHTML(s, start); // recursive call } } } return s; }
5
@Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { if(command.getName().equalsIgnoreCase("mb")) { if(args.length == 0){ // TODO show plugin help getLogger().info("Plugin help coming soon!"); return true; } // ************************************ // TODO make this permanent per map for minigame server else if(args[0].equalsIgnoreCase("firstbase")) { GameplayBlocks.firstBase = Bukkit.getServer().getPlayer(sender.getName()).getLocation().getBlock(); return true; } else if(args[0].equalsIgnoreCase("secondbase")) { GameplayBlocks.secondBase = Bukkit.getServer().getPlayer(sender.getName()).getLocation().getBlock(); return true; } else if(args[0].equalsIgnoreCase("thirdbase")) { GameplayBlocks.thirdBase = Bukkit.getServer().getPlayer(sender.getName()).getLocation().getBlock(); return true; } else if(args[0].equalsIgnoreCase("homeplate")) { GameplayBlocks.homePlate = Bukkit.getServer().getPlayer(sender.getName()).getLocation().getBlock(); return true; } else if(args[0].equalsIgnoreCase("pitchersmound")) { if(!GameplayBlocks.pitchersMound.contains(Bukkit.getServer().getPlayer(sender.getName()).getLocation().getBlock())) { GameplayBlocks.pitchersMound.add(Bukkit.getServer().getPlayer(sender.getName()).getLocation().getBlock()); } return true; } // ************************************ return false; } return false; }
8
public boolean isValidSudoku(char[][] board) { if ((board == null) || (board.length % 3 != 0) || (board.length != board[0].length)) return false; for (int y = 0; y < board.length; y++) { for (int x = 0; x < board.length; x++) { if (board[y][x] == '.') { continue; } if (isValidInRow(x, y, board) && isValidInColumn(x, y, board) && isValidInRegion(x, y, board)) { continue; } else { return false; } } } return true; }
9
public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; }
0
private static int partition(int data[], int left, int right){ // pre: left <= right // post: data[left] placed in the correct (returned) location while (true){ // move right "pointer" toward left while (left < right && data[left] < data[right]) right--; if (left < right) swap(data,left++,right); else return left; // move left pointer toward right while (left < right && data[left] < data[right]) left++; if (left < right) swap(data,left,right--); else return right; } }
7
public DatagramURL(String url) throws MalformedURLException { if (url == null) { throw new MalformedURLException("URL is null"); } if (!url.startsWith("udp://")) { throw new MalformedURLException("URL is not using the udp protocol"); } int portSep = url.indexOf(':', 6); if (portSep == -1) { throw new MalformedURLException("URL must specify the port"); } this.host = url.substring(6, portSep); try { this.port = Integer.parseInt(url.substring(portSep + 1)); } catch (NumberFormatException nfe) { throw new MalformedURLException("Invalid port number: " + url); } if (this.port < 1 || this.port > 65535) { throw new MalformedURLException("Invalid port number: " + url); } }
6
public void setAttribute(String nazwa, String wartosc) { DataRow parametry = new DataRow(); parametry.setTableName(nazwa); parametry.addAttribute("name", wartosc); for(AbstractAttribute atrybut : attributes) { if(atrybut.getType().equals(nazwa)) { atrybut.load(DataVector.getInstance().dbManager.select(parametry).get(0)); if(row.containsAttribute(atrybut.getName())) { row.update(nazwa, wartosc); } else { row.insert(nazwa, wartosc); } } } }
3
public static void main(String [] args) { boolean done = false; for (int a = 1; a < 1001 && !done; a++) { for (int b = 1; b < 1001 && !done; b++) { for (int c = 1; c < 1001 && !done; c++) { if (a+b+c == 1000 && (a*a + b*b == c*c)) { System.out.println(a*b*c); System.out.println("a,b,c" + a + ". " + b + ", " + c); done = true; } } } } }
8
private static void rsaEncGenKeysText(CryptobyConsole console) { scanner = new Scanner(System.in); String privateKey; String publicKey; // Set Default Key Size keySize = 1024; do { System.out.println("\n"); System.out.println("Choose Key Size in Bit"); System.out.println("----------------------\n"); System.out.println("1 - 1024"); System.out.println("2 - 2048"); System.out.println("3 - 4096"); System.out.println("4 - Back"); System.out.print("Enter Number: "); while (!scanner.hasNextInt()) { System.out.print("That's not a number! Enter 1,2,3 or 4: "); scanner.next(); } choice = scanner.nextInt(); } while (choice < 1 || choice > 4); switch (choice) { case 1: keySize = 1024; break; case 2: keySize = 2048; break; case 3: keySize = 4096; break; case 4: rsaCrypterText(console); break; default: rsaEncGenKeysText(console); } // Input your String Text to encrypt plainByte = scanPlainText(console); // Initial RSA Crypt Object initRSAKeyGen(console); // Get Public Key in Bytecode System.out.println("\nGenerate Private and Public RSA Keys..."); console.getCore().getKeyGenAsym().initGenerator(keySize); publicKeyByte = console.getCore().getKeyGenAsym().getPublicKeyByte(); // Get Public and Private Key as String publicKey = console.getCore().getKeyGenAsym().getPublicKey(); privateKey = console.getCore().getKeyGenAsym().getPrivateKey(); // Encrypt the String Text with given Key System.out.println("\nEncryption in progress..."); cryptByte = console.getCore().getCryptAsym().encrypt(plainByte, publicKeyByte); System.out.println("\nEncryption successfull..."); // Convert crypted byte Array into a Hexcode String charTextHex = CryptobyHelper.bytesToHexStringUpper(cryptByte).toCharArray(); // Print encrypted Text in Hex Block form System.out.println(CryptobyHelper.printHexBlock("RSA", keySize, charTextHex)); // Print Private Keys System.out.println(CryptobyHelper.printPrivateKeyBlock(privateKey)); // Print Public Keys System.out.println(CryptobyHelper.printPublicKeyBlock(publicKey)); // Back to Menu rsaCrypter with Enter (Return) Key System.out.println("\nGo back to RSA Text Crypter Menu: Press Enter"); CryptobyHelper.pressEnter(); rsaCrypterText(console); }
7
public void writeError(String toWrite, Boolean severe) { if (severe) { if (toWrite != null) { this.log.severe(Assignment.logPrefix + toWrite); } } else { if (toWrite != null) { this.log.warning(Assignment.logPrefix + toWrite); } } }
3
public static void main(String[] args) { // TODO code application logic here long startTime = 0, elapsedTime = 0; // Parses the command line arguments and collects all data in memory Util sudoku = new Util(args); // Constructs Sudoku Boards and stores them in an array SudokuBoard[] board = sudoku.createSudokuBoards(); Solver solver = null; // Solver will solve all boards in the array one by one if (board != null) { for (int i=0; i < board.length; i++) { if (board[i] != null) { board[i].displayGrid(); // Loads a Sudoku board in to the Solver solver = new Solver(board[i]); // Solver Solves Board and times the performance startTime = System.currentTimeMillis(); solver.solve(); elapsedTime = System.currentTimeMillis() - startTime; } } // Displays the state of all boards for (int i=0; i < board.length; i++) { if (board[i] != null) { board[i].displayGrid(); } } // if (solver != null) { // solver.groupCandidates(); // } System.out.println("Solver took " + elapsedTime + "ms to solve."); } else { System.out.println("All boards are set to null."); } }
5
public static List<Article> selectArtcile() { String query = null; List<Article> listearticle = new ArrayList<Article>(); ResultSet resultat; try { query = "SELECT * from ARTICLE "; PreparedStatement pStatement = (PreparedStatement) ConnectionBDD.getInstance().getPreparedStatement(query); resultat = pStatement.executeQuery(query); while (resultat.next()) { System.out.println(resultat.getString("ARTLIBELLE")); Article aa = new Article(resultat.getInt("ID_ARTICLE"), resultat.getInt("ID_COULEUR"), resultat.getInt("ID_TVA"), resultat.getString("ARTLIBELLE"), resultat.getString("ARTREF"), resultat.getFloat("ARTPRXHT"), resultat.getString("ARTPHOTO")); listearticle.add(aa); } } catch (SQLException ex) { Logger.getLogger(RequetesArticle.class.getName()).log(Level.SEVERE, null, ex); } return listearticle; }
2
private String scan(OCRImage image, String identifier, boolean spaces, int spaceDistance, int brightness, double tolerance) { ArrayList<CharacterDataMap> temp = getCharacterArray(image, brightness, spaces, spaceDistance); ArrayList<CharacterDataMap> characters = characterMap.get(identifier); String str = ""; for(CharacterDataMap map : characters) { for(int i = 0; i < temp.size(); i++) { if(temp.get(i).getImage() == null) continue; if(temp.get(i).equal(map, tolerance)) { if(temp.get(i).getCharacter() == null || temp.get(i).getCharacter().isEmpty()) temp.get(i).setCharacter(map.getCharacter()); } } } for(CharacterDataMap a : temp) { if(a.getCharacter() != null) str += a.getCharacter(); } return str.trim(); }
8
public void setResteAFaire(double resteAFaire) throws IllegalArgumentException{ // La user story est modifiée uniquement si son statut est planifié et que le resteAFaire est > 0 if(this.getEtatUserStory() == EtatUserStory.PLANIFIEE && resteAFaire>=0){ this.resteAFaire = resteAFaire; this.setChanged(); this.notifyObservers(); if(this.getResteAFaire() == 0){ this.setEtatUserStory(EtatUserStory.FERMEE); } } else{ throw new IllegalArgumentException("Le RAF ne peut être changé à cause de sont état"); } }
3
public static boolean inAWTEventThread() { try { return javax.swing.SwingUtilities.isEventDispatchThread(); } catch (Throwable e) { return false; } }
1
private synchronized void processOutputs() { try { // write status - this has the highest transmission priority, thus it is executed first if thread gets interrupted early hmi.dataOut.writeInt(Command.OUT_STATUS.ordinal()); hmi.dataOut.writeInt(GuidanceAT.getCurrentStatus().ordinal()); hmi.dataOut.flush(); RConsole.println("Status data geflusht."); // getParkingSlots() returns null until it is implemented if (hmi.navigation.getParkingSlots() == null) { // do nothing } else { // write new parking slot - these are aperiodic information, thus should be sent as early as possible, // but less important than status updates. //Iterate over complete array to determine number of parking slots that are not null int i = hmi.noOfParkingSlotsInList; while(i < hmi.navigation.getParkingSlots().length) { if(hmi.navigation.getParkingSlots()[i] != null) { i++; } else { hmi.noOfParkingSlotsInList = i; i = hmi.navigation.getParkingSlots().length; } } int newSlots = hmi.noOfParkingSlotsInList - hmi.noOfParkingSlots; hmi.noOfParkingSlots += newSlots; // Record new slots while (newSlots > 0) { ParkingSlot newSlot = hmi.navigation.getParkingSlots()[hmi.noOfParkingSlots - newSlots]; //Check if parking slot is null if(newSlot != null) { // if(newSlot.getStatus() == slotWithGoodStatus.getStatus()) // { hmi.dataOut.writeInt(Command.OUT_PARKSLOT.ordinal()); hmi.dataOut.writeInt(newSlot.getStatus().ordinal()); hmi.dataOut.writeInt(newSlot.getID()); hmi.dataOut.writeFloat(newSlot.getFrontBoundaryPosition().x); hmi.dataOut.writeFloat(newSlot.getFrontBoundaryPosition().y); hmi.dataOut.writeFloat(newSlot.getBackBoundaryPosition().x); hmi.dataOut.writeFloat(newSlot.getBackBoundaryPosition().y); hmi.dataOut.flush(); // } } newSlots--; } } // write position - this has least priority, no damage is caused when position is not delivered during one cycle. Pose pose = hmi.navigation.getPose(); hmi.dataOut.writeInt(Command.OUT_POSITION.ordinal()); hmi.dataOut.writeFloat(pose.getX()); hmi.dataOut.writeFloat(pose.getY()); hmi.dataOut.writeFloat(pose.getHeading()); // Distance sensor values in clockwise directions (front, right, back, left) in mm hmi.dataOut.writeDouble(hmi.perception.getFrontSensorDistance()); hmi.dataOut.writeDouble(hmi.perception.getFrontSideSensorDistance()); hmi.dataOut.writeDouble(hmi.perception.getBackSensorDistance()); hmi.dataOut.writeDouble(hmi.perception.getBackSideSensorDistance()); hmi.dataOut.flush(); } catch (IOException e) { System.out.println("IO-Exception in processOutputs()"); } }
6
private boolean clickedOnAcePile(MouseEvent e) { return e.getX() >= X_BOARD_OFFSET + CARD_WIDTH * 6 + CARD_X_GAP * 6 && e.getX() <= X_BOARD_OFFSET + CARD_WIDTH * 7 + CARD_X_GAP * 6 && e.getY() >= Y_BOARD_OFFSET && e.getY() < Y_BOARD_OFFSET + CARD_HEIGHT * 4 + CARD_Y_GAP * 3; }
3
private void checkCollision(){ for (int i= 0; i < 4; i++){ int pX= this.player.getX(); int pY= this.player.getY(); int gX= this.ghosts[i].getX(); int gY= this.ghosts[i].getY(); if ((pX == gX) && (pY == gY)){ if (this.ghosts[i].isEatenBy(this.player)) killGhost(i); else { this.isDead= true; this.playerStateTimer.stop(); this.deathTimer.start(); } } } }
4
public void performSaveAsCommand() { JFileChooser fileChooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( "Timeflecks Database Files", "db"); fileChooser.setFileFilter(filter); boolean success = false; do { int returnVal = fileChooser.showSaveDialog(menu); if (returnVal == JFileChooser.APPROVE_OPTION) { GlobalLogger.getLogger().logp(Level.INFO, "MenuBar", "performSaveAsCommand", "User chose file " + fileChooser.getSelectedFile()); File selectedFile = fileChooser.getSelectedFile(); if (FileUtility.fileExistsAndIsNotSame(selectedFile)) { // We need to prompt the user to see if they want to // overwrite the file. Object[] options = { "Overwrite File", "Choose New File" }; int reply = JOptionPane .showOptionDialog( menu, "This file already exists. Would you like to overwrite it with the current data file?", "File Exists", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]); if (reply == JOptionPane.YES_OPTION) { // The user selected to overwrite the file GlobalLogger.getLogger().logp(Level.INFO, "MenuBar", "performSaveAsCommand", "User elected to overwrite existing file."); // We just keep going } else { // User selected to not overwrite file GlobalLogger .getLogger() .logp(Level.INFO, "MenuBar", "performSaveAsCommand", "User declined to overwrite file, prompting for new file choice."); success = false; continue; } } // Take the file that comes in and try, catch // IllegalArgumentException, show alert asking for new file - // they can go back and cancel // Call switch try { Timeflecks.getSharedApplication().saveDatabaseFileAs( selectedFile); success = true; } catch (IllegalArgumentException e) { GlobalLogger .getLogger() .logp(Level.WARNING, "MenuBar", "performSaveAsCommand", "Illegal argument from SQLiteConnector when attempting to switch database. Showing dialog, prompting for proper extension."); success = false; JOptionPane .showMessageDialog( menu, "Invalid filename. (1200)\nPlease make sure that your file is valid and has the extension \".db\".", "Invalid Filename", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { ExceptionHandler.handleDatabaseSaveException(e, this .getClass().getName(), "performSaveAsCommand()", "1300"); } } else { GlobalLogger.getLogger().logp(Level.INFO, "MenuBar", "performSaveAsCommand", "User cancelled Save As operation, continuing."); success = true; } } while (!success); }
6
public static int RentsPerMonth(String monthYear) { try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } int x =0; //ophalen van de data uit de db. deze statement geeft alle transacties terug die "mm/jjjj" formaat hebben. Dus enkel de maand en het jaar met het "/" teken inbegrepen. try { PreparedStatement stmnt = conn.prepareStatement("SELECT COUNT(*) AS total FROM RentTransactions WHERE RIGHT(date_out, 7) = ? "); stmnt.setString(1, monthYear ); ResultSet res; res = stmnt.executeQuery(); while(res.next()){ x = res.getInt("total"); } } catch(SQLException e){ e.printStackTrace(); } return x; }
5
private void dropClient() { if (anInt1011 > 0) { processLogout(); return; } gameScreenCanvas.initDrawingArea(); aFont_1271.drawANCText(0, "Connection lost", 144, 257); aFont_1271.drawANCText(0xffffff, "Connection lost", 143, 256); aFont_1271.drawANCText(0, "Please wait - attempting to reestablish", 159, 257); aFont_1271.drawANCText(0xffffff, "Please wait - attempting to reestablish", 158, 256); gameScreenCanvas.drawGraphics(4, super.graphics, 4); anInt1021 = 0; destX = 0; Socket rsSocket = socketStream; loggedIn = false; loginFailures = 0; login(myUsername, myPassword, true); if (!loggedIn) { processLogout(); } try { rsSocket.close(); } catch (Exception exception) { } }
3
@Override public final double days(final GregorianCalendar from, final GregorianCalendar to) { if (0 < from.compareTo(to)) return -this.days(to, from); final GregorianCalendar f = this._Adjust(from); final GregorianCalendar t = this._Adjust(to); double difference = Time.Gregorian.belowDateDifference(from, to); difference += t.get(GregorianCalendar.DATE) - f.get(GregorianCalendar.DATE); final int fromMonth = f.get(GregorianCalendar.MONTH); final int fromYear = f.get(GregorianCalendar.YEAR); final int toMonth = t.get(GregorianCalendar.MONTH); final int toYear = t.get(GregorianCalendar.YEAR); for (int month = 0; month < 12; month++) { if (month < fromMonth) difference -= this.month(fromYear, month); if (month < toMonth) difference += this.month(toYear, month); } for (int year = fromYear; year < toYear; year++) difference += this.year(year); return difference; }
5
public Map<Integer, Restaurant> readCSVFile(String csvFile) { Map<Integer, Restaurant> restMap = new ConcurrentHashMap<Integer, Restaurant>(); BufferedReader br = null; String line; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { String[] csvLine = line.split(cvsSplitBy); int restId = Integer.parseInt(csvLine[0]); Double itemPrice = Double.parseDouble(csvLine[1]); if(restMap.get(restId)==null){ Map<String, Double> item_Price_Map = new HashMap<String, Double>(); item_Price_Map.put(getItemLabel(csvLine), itemPrice); restMap.put(restId, new Restaurant(restId, item_Price_Map)); }else{ restMap.get(restId).getItem_PriceMap().put(getItemLabel(csvLine), itemPrice); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return restMap; }
6
public BusStop(int busStopNumber) { //initialize the bus stop busStop = new PriorityQueue<Person>(); //set the initial priority at stop priority = 0; //set the bus stop number this.busStopNumber = busStopNumber; //set minimum passenger this.minimumPassenger = Integer.MAX_VALUE; //set maximum passenger this.maximumPassenger = Integer.MIN_VALUE; //set the average number of person on the stop averageNumberOfPersons = 0; //set the average person wait time averagePersonsWaitTime = 0; }
0
public int getWidth() { return width; }
0
public void build () throws ExceptionInvalidParam { if (upperAngleBound <= lowerAngleBound || upperHeightBound <= lowerHeightBound || destWidth <= 0 || destHeight <= 0 || sourceModule == null || destNoiseMap == null) throw new ExceptionInvalidParam ("Invalid Parameter in NoiseMapBuilderCylinder"); // Resize the destination noise map so that it can store the new output // values from the source model. destNoiseMap.setSize (destWidth, destHeight); // Create the cylinder model. Cylinder cylinderModel = new Cylinder(); cylinderModel.setModule (sourceModule); double angleExtent = upperAngleBound - lowerAngleBound ; double heightExtent = upperHeightBound - lowerHeightBound; double xDelta = angleExtent / (double)destWidth ; double yDelta = heightExtent / (double)destHeight; double curAngle = lowerAngleBound ; double curHeight = lowerHeightBound; // Fill every point in the noise map with the output values from the model. for (int y = 0; y < destHeight; y++) { curAngle = lowerAngleBound; for (int x = 0; x < destWidth; x++) { float curValue = (float)cylinderModel.getValue (curAngle, curHeight); destNoiseMap.setValue(x, y, curValue); curAngle += xDelta; } curHeight += yDelta; setCallback (y); } }
8
public void sendServerMessage(String message) { for (int i = clients.size() - 1; i >= 0; i--) { clients.get(i).getWriter().println("伺服器公告:" + message + "(廣播)"); clients.get(i).getWriter().flush(); } }
1
@Override public State nextState(Random random) { State newState; int value = random.nextInt(100); if (Utils.isBetween(value, 0, P_NM)) { newState = new Modified(); } else if (Utils.isBetween(value, P_NM, P_NU)) { newState = new Unmodified(); } else { newState = new Deleted(); } return newState; }
2
public String getQuote(){ String quote = null; try { crs = qb.selectFrom("qotd").all().executeQuery(); if(crs.next()) { quote = crs.getString("qotd"); } } catch (SQLException e) { e.printStackTrace(); } finally { try { crs.close(); } catch (SQLException e) { e.printStackTrace(); } } return quote; }
3
public static List<Tag> constructTags(Response res) throws WeiboException { try { JSONArray list = res.asJSONArray(); int size = list.length(); List<Tag> tags = new ArrayList<Tag>(size); for (int i = 0; i < size; i++) { tags.add(new Tag(list.getJSONObject(i))); } return tags; } catch (JSONException jsone) { throw new WeiboException(jsone); } catch (WeiboException te) { throw te; } }
3
@EventHandler public void onPlayerDamage(EntityDamageByEntityEvent e) { if (invulnerable) if (e.getEntity().getType() == EntityType.PLAYER) if (this.getPlayers().contains(e.getEntity())) e.setCancelled(true); }
3
@Override public void mouseClicked(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON3) ColorUsedPanel.this.model.setColor(c); else if(e.getButton() == MouseEvent.BUTTON1){ AlienFXProfile profile = profileModel.getProfile(); Color changedColor = c; if(profile != null){ for(AlienFXProfileSetting s : profile.getSettings()){ for(AlienFXAction a : s.getSequence()){ if(a.getLeadingColor().getRGB() == changedColor.getRGB()) a.getLeadingColorModel().setColor(ColorUsedPanel.this.model.getColor()); if(a.getTrailingColor().getRGB() == changedColor.getRGB()) a.getTrailingColorModel().setColor(ColorUsedPanel.this.model.getColor()); } } } } }
7
@Override public boolean accept(File file) { if (this.isExtension) return file.getName().toLowerCase().endsWith(this.keyword); return (file.getName().toLowerCase().indexOf(this.keyword) >= 0); }
1
protected BufferedImage getScaledUpInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint, boolean higherQuality) { int type = BufferedImage.TYPE_INT_ARGB; BufferedImage ret = (BufferedImage) img; int w, h; if (higherQuality) { // Use multi-step technique: start with original size, then // scale down in multiple passes with drawImage() // until the target size is reached w = img.getWidth(); h = img.getHeight(); } else { // Use one-step technique: scale directly from original // size to target size with a single drawImage() call w = targetWidth; h = targetHeight; } do { if (higherQuality && w < targetWidth) { w *= 2; if (w > targetWidth) { w = targetWidth; } } if (higherQuality && h < targetHeight) { h *= 2; if (h > targetHeight) { h = targetHeight; } } BufferedImage tmp = new BufferedImage(w, h, type); Graphics2D g2 = tmp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint); g2.drawImage(ret, 0, 0, w, h, null); g2.dispose(); ret = tmp; tmp = null; } while (w != targetWidth || h != targetHeight); return ret; }
9
public String[] dataCacheToArray(ArrayList <String> dataCache, String dataField){ /* * @param: (ArrayList <String> dataCache, "link" || "seed" || "leech" || "size") * example (BuildDataCache(String[] foo), "size")) will return all the torrent sizes in a string array. * Parses the SizeStats ArrayList into one dimensional array (seeders, leechers, links, size) */ try{ String[] parsedArray = new String[dataCache.size()]; int listPos = 0; if(dataField.equals("link")) listPos = 3; if(dataField.equals("leech"))listPos = 2; if(dataField.equals("seed")) listPos = 1; if(dataField.equals("size")) listPos = 0; for (int i = 0; i < dataCache.size()/4; i++){ parsedArray[i] = dataCache.get(listPos); listPos = listPos+4; } System.out.print("#"); return parsedArray; }catch(Exception e){ return null; } }
6
public Polygon2D deleteVertexBefore(int k) { int n = vertex.length; if (n < 4) return this; float[] x = new float[n - 1]; float[] y = new float[n - 1]; if (k > 0 && k < n) { for (int i = 0; i < k; i++) { x[i] = vertex[i].x; y[i] = vertex[i].y; } for (int i = k + 1; i < n; i++) { x[i - 1] = vertex[i].x; y[i - 1] = vertex[i].y; } } else if (k == 0) { for (int i = 1; i < n; i++) { x[i - 1] = vertex[i - 1].x; y[i - 1] = vertex[i - 1].y; } } else { return this; } return new Polygon2D(x, y); }
7
protected static void extractComments(Metadata metadata, XHTMLContentHandler xhtml, VorbisStyleComments comments) throws TikaException, SAXException { // Get the specific know comments metadata.set(TikaCoreProperties.TITLE, comments.getTitle()); metadata.set(TikaCoreProperties.CREATOR, comments.getArtist()); metadata.set(XMPDM.ARTIST, comments.getArtist()); metadata.set(XMPDM.ALBUM, comments.getAlbum()); metadata.set(XMPDM.GENRE, comments.getGenre()); metadata.set(XMPDM.RELEASE_DATE, comments.getDate()); metadata.add(XMP.CREATOR_TOOL, comments.getVendor()); metadata.add("vendor", comments.getVendor()); for(String comment : comments.getComments("comment")) { metadata.add(XMPDM.LOG_COMMENT.getName(), comment); } // Grab the rest just in case List<String> done = Arrays.asList(new String[] { VorbisComments.KEY_TITLE, VorbisComments.KEY_ARTIST, VorbisComments.KEY_ALBUM, VorbisComments.KEY_GENRE, VorbisComments.KEY_DATE, VorbisComments.KEY_TRACKNUMBER, "vendor", "comment" }); for(String key : comments.getAllComments().keySet()) { if(! done.contains(key)) { for(String value : comments.getAllComments().get(key)) { metadata.add(key, value); } } } // Output as text too xhtml.element("h1", comments.getTitle()); xhtml.element("p", comments.getArtist()); // Album and Track number if (comments.getTrackNumber() != null) { xhtml.element("p", comments.getAlbum() + ", track " + comments.getTrackNumber()); metadata.set(XMPDM.TRACK_NUMBER, comments.getTrackNumber()); } else { xhtml.element("p", comments.getAlbum()); } // A few other bits xhtml.element("p", comments.getDate()); for(String comment : comments.getComments("comment")) { xhtml.element("p", comment); } xhtml.element("p", comments.getGenre()); }
6
private List<RouteLeg> createRoute(String string) { List<RouteLeg> route = new ArrayList<RouteLeg>(); for (int index = 1; index < string.length(); index++) { route.add(new RouteLeg(string.substring(index-1, index), string.substring(index, index+1))); } return route; }
1
public void input(ArrayList<Action> history, int handStrength) { int numRaises = 0; for(Action a : history) { if(a == Action.RAISE) { numRaises++; } } int ahs = adjustedHandStrength(handStrength); if(historyToHandStrength.get(numRaises) == null) { int[] histogram = new int[] {0,0,0,0,0,0,0,0,0,0}; historyToHandStrength.put(numRaises, histogram); } int[] histogram = historyToHandStrength.get(numRaises); histogram[ahs] = histogram[ahs] + 1; System.out.print("OpponentModel["+numRaises+"] <- "); for(int i = 0; i < histogram.length; i++) { System.out.print(histogram[i] + " - "); } }
4
public void rebondProjectilesStructures(Projectiles proj, Structures struc) { if (proj.getPosition().getX() + proj.getBound().getX() > struc.getPosition().getX() && proj.getPosition().getX() < (struc.getPosition().getX() + struc.getBound().getX()) && proj.getPosition().getY() + proj.getBound().getY() > struc.getPosition().getY()) { if (proj.getVitesse().getX() < 0) { if (Math.abs((struc.getPosition().getX() + struc.getBound().getX()) - proj.getPosition().getX()) > Math.abs(struc.getPosition().getY() - proj.getPosition().getY())) { proj.getPosition().setY(struc.getPosition().getY()); module.rebond(proj, 'y'); } else { proj.getPosition().setX((struc.getPosition().getX() + struc.getBound().getX())); module.rebond(proj, 'x'); } } else { if (Math.abs(struc.getPosition().getX() - proj.getPosition().getX()- proj.getBound().getX()) > Math.abs(struc.getPosition().getY() - (proj.getPosition().getY() + proj.getBound().getY() ) )) { proj.getPosition().setY(struc.getPosition().getY()-proj.getBound().getY()-1); module.rebond(proj, 'y'); } else { proj.getPosition().setX(struc.getPosition().getX()-1-proj.getBound().getX()); module.rebond(proj, 'x'); } } } }
6
private static EnumOS2 getOS() { String s = System.getProperty("os.name").toLowerCase(); if (s.contains("win")) { return EnumOS2.windows; } if (s.contains("mac")) { return EnumOS2.macos; } if (s.contains("solaris")) { return EnumOS2.solaris; } if (s.contains("sunos")) { return EnumOS2.solaris; } if (s.contains("linux")) { return EnumOS2.linux; } if (s.contains("unix")) { return EnumOS2.linux; } else { return EnumOS2.unknown; } }
6
private void objectString(J_PositionTrackingPushbackReader var1, J_JsonListener var2) throws J_InvalidSyntaxException, IOException { char var3 = (char)this.readNextNonWhitespaceChar(var1); if(var3 != 123) { throw new J_InvalidSyntaxException("Expected object to start with { but got [" + var3 + "].", var1); } else { var2.func_27194_f(); char var4 = (char)this.readNextNonWhitespaceChar(var1); var1.func_27334_a(var4); if(var4 != 125) { this.aFieldToken(var1, var2); } boolean var5 = false; while(!var5) { char var6 = (char)this.readNextNonWhitespaceChar(var1); switch(var6) { case 44: this.aFieldToken(var1, var2); break; case 125: var5 = true; break; default: throw new J_InvalidSyntaxException("Expected either , or } but got [" + var6 + "].", var1); } } var2.func_27203_g(); } }
5
private InterfaceCommand getCommand(DebuggerVirtualMachine dvm) { UserInterface.print(": "); StringTokenizer tokenizer = null; InterfaceCommand command = null; try { tokenizer = new StringTokenizer((new BufferedReader(new InputStreamReader( System.in))).readLine()); } catch (IOException ex) { UserInterface.println(ex); } if (!tokenizer.hasMoreTokens()) { return null; } String keyboardCommand = (tokenizer.nextToken()).toLowerCase(); if ((command = CommandTable.get(keyboardCommand)) == null) { UserInterface.println("Invalid command. Enter h for help.\n"); return null; } List<String> argumentList = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { argumentList.add(tokenizer.nextToken().toLowerCase()); } if (!command.init(argumentList, dvm)) { return null; } return command; }
5
protected int setArmorModel(EntityPlayer par1EntityPlayer, int par2, float par3) { ItemStack var4 = par1EntityPlayer.inventory.armorItemInSlot(3 - par2); if (var4 != null) { Item var5 = var4.getItem(); if (var5 instanceof ItemArmor) { ItemArmor var6 = (ItemArmor)var5; if (var5 instanceof IArmorTextureProvider) { loadTexture(((IArmorTextureProvider)var5).getArmorTextureFile(var4)); } else { this.loadTexture("/armor/" + armorFilenamePrefix[var6.renderIndex] + "_" + (par2 == 2 ? 2 : 1) + ".png"); } ModelBiped var7 = par2 == 2 ? this.modelArmor : this.modelArmorChestplate; var7.bipedHead.showModel = par2 == 0; var7.bipedHeadwear.showModel = par2 == 0; var7.bipedBody.showModel = par2 == 1 || par2 == 2; var7.bipedRightArm.showModel = par2 == 1; var7.bipedLeftArm.showModel = par2 == 1; var7.bipedRightLeg.showModel = par2 == 2 || par2 == 3; var7.bipedLeftLeg.showModel = par2 == 2 || par2 == 3; this.setRenderPassModel(var7); if (var4.isItemEnchanted()) { return 15; } return 1; } } return -1; }
9
private void sortEntitiesToMap() { // Iterate the entities that need rendered and check if they're // visible for (Entity entity : entityList) { Spatial entitySpatial = entity.getComponent(Spatial.class); // I'll obviously offer an overloaded contains method for // spatials in the future (potentially) if (viewPort.contains(entitySpatial.x, entitySpatial.y, entitySpatial.width, entitySpatial.height)) { // Add it to be rendered addToRenderMap(entity, entitySpatial); } } }
2
@Override public Long getSocialId() { return socialId; }
0
@EventHandler public void BlazeRegeneration(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getBlazeConfig().getDouble("Blaze.Regeneration.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getBlazeConfig().getBoolean("Blaze.Regeneration.Enabled", true) && damager instanceof Blaze && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, plugin.getBlazeConfig().getInt("Blaze.Regeneration.Time"), plugin.getBlazeConfig().getInt("Blaze.Regeneration.Power"))); } }
6
public Map<String, Link> makeLinkMap(Map<String, Mass> massMap){ Map<String, Link> linkMap = new HashMap<String, Link>(); NodeList[] linkArray = {springs, muscles}; for (NodeList linkType: linkArray){ for (int i = 0; i < linkType.getLength(); i++) { Node node = linkType.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; String id1 = element.getAttribute("a"); String id2 = element.getAttribute("b"); double restLength = Double.parseDouble(element.getAttribute("restlength")); double k = getK(element, "contanst"); if (element.getNodeName().equals("spring")){ Spring spring = new Spring(massMap.get(id1), massMap.get(id2), restLength, k, springColor); linkMap.put("s"+id1+id2, spring); } else{ double amplitude = Double.parseDouble(element.getAttribute("amplitude")); Muscle muscle = new Muscle(massMap.get(id1), massMap.get(id2), restLength, k, amplitude, muscleColor); linkMap.put("m"+id1+id2, muscle); } } } } return linkMap; }
4
public void setCurrentLine(int lineNumber) { environmentStack.peek().setCurrentLineNumber(lineNumber); }
0
@EventHandler public void onInteract(PlayerInteractEvent e){ Player p = e.getPlayer(); if(e.getAction().equals(Action.RIGHT_CLICK_BLOCK) && p.getWorld().getName().equalsIgnoreCase("kitpvp") && e.getClickedBlock().getState() instanceof Sign){ Sign sign = (Sign) e.getClickedBlock().getState(); if(sign.getLine(0).equals(ChatColor.DARK_BLUE + "[Armory]")){ Integer price = Integer.parseInt(sign.getLine(3)); Integer amount = Integer.parseInt(sign.getLine(1)); if(p.getLevel() < price){ p.sendMessage(ChatColor.RED + "You do not have enough xp to purchase this item!"); return; } p.setLevel(p.getLevel() - price); Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "give " + p.getName() + " " + sign.getLine(2) + " " + amount); return; } } }
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Activity other = (Activity) obj; if (project == null) { if (other.project != null) return false; } else if (!project.equals(other.project)) return false; if (task == null) { if (other.task != null) return false; } else if (!task.equals(other.task)) return false; return true; }
9
public static final void copyDirectory(File source, File destination) throws IOException { if (!source.isDirectory()) { throw new IllegalArgumentException("Source (" + source.getPath() + ") must be a directory."); } if (!source.exists()) { throw new IllegalArgumentException("Source directory (" + source.getPath() + ") doesn't exist."); } if (destination.exists()) { throw new IllegalArgumentException("Destination (" + destination.getPath() + ") exists."); } destination.mkdirs(); File[] files = source.listFiles(); for (File file : files) { if (file.isDirectory()) { copyDirectory(file, new File(destination, file.getName())); } else { copyFile(file, new File(destination, file.getName())); } } }
5
public static GetProjects_Result getProjects(Database database, GetProjects_Param params) { Logger.getLogger(API.class.getName()).log(Level.FINE, "Entering API.getProjects()"); GetProjects_Result result; try { ValidateUser_Result vResult = validateUser(database, new ValidateUser_Param(params.username(), params.password())); if (vResult == null || !vResult.validated()) { result = null; } else { // Get all Projects ArrayList<Project> projects = (ArrayList) database.get(new Project()); // Add them to GetProjects_Result ArrayList<Integer> ids = new ArrayList<>(); ArrayList<String> names = new ArrayList<>(); for (Project project : projects) { ids.add(new Integer(project.projectId())); names.add(project.title()); } result = new GetProjects_Result(ids, names); } } catch (DatabaseException | GetFailedException ex) { result = null; Logger.getLogger(API.class.getName()).log(Level.WARNING, "getProjects request failed.", ex); } catch (GetProjects_Result.GetProjects_ResultException ex) { result = null; Logger.getLogger(API.class.getName()).log(Level.SEVERE, null, ex); } Logger.getLogger(API.class.getName()).log(Level.FINE, "Exiting API.getProjects()"); return result; }
5
public static void main(String[] args) { //Define loop to go through each number for (int i = 2; i <= 69; i++) { //if i is less than 20 and divisible by 2 if (i <= 20 && i % 2 == 0) { //output number System.out.println(i); //if i is between 21 and 41, and has been incremented by 3 } else if (i > 20 && i <= 41 && i % 3 == 2) { //output number System.out.println(i); //if i is between 32 and 69 and has been incremented by 4 } else if (i > 41 && i <= 69 && i % 4 == 1) { //output number System.out.println(i); } } BlockLetters.TONY_PAPPAS.outputBlockName(); }
9
public static void swapWords(Text text) { log.trace("Subtask N5"); LinkedList<Sentence> allElements = (LinkedList<Sentence>) text.getAllElements(); for (Sentence sentenceOrListing : allElements) { if (sentenceOrListing.getClass() != Listing.class) { int indexFirst = 0; int indexLast = 0; Sentence sentence = (Sentence) sentenceOrListing; List<SentencePart> sentenceParts = sentence.getAllElements(); for (int i = 0; i < sentenceParts.size(); i++) { SentencePart part = sentenceParts.get(i); if (part instanceof Word) { indexFirst = i; break; } } for (int i = sentenceParts.size() - 1; i >= 0; i--) { SentencePart part = sentenceParts.get(i); if (part instanceof Word) { indexLast = i; break; } } Collections.swap(sentenceParts, indexFirst, indexLast); } } }
6
public JSONObject countMetadataColors(JSONObject[] countMetadata, Color[] colors, float[] weights) throws TinEyeServiceException { MultipartEntity postEntity = new MultipartEntity(); JSONObject responseJSON = null; if (weights.length > 0 && colors.length != weights.length) throw new TinEyeServiceException("colors and weights lists must have the same number of entries"); try { int i = 0; for(JSONObject metaData: countMetadata) { postEntity.addPart("count_metadata[" + i + "]", new StringBody(metaData.toString())); i += 1; } // Store list of colors in hex format, and disgard // the alpha component from each color (which by default is white) int j = 0; for(Color color: colors) { String hexColor = Integer.toHexString(color.getRGB()).substring(2); postEntity.addPart("colors[" + j + "]", new StringBody(hexColor)); // weights must be the same length as the colors if the weights list is not empty. if (weights.length > 0) { postEntity.addPart("weights[" + j + "]", new StringBody(Float.toString(weights[j]))); } j += 1; } responseJSON = postAPIRequest("count_metadata", postEntity); } catch (Exception e) { logger.error("'countMetadataColors' failed: " + e.toString()); throw new TinEyeServiceException("'countMetadataColors' failed", e); } return responseJSON; }
6
public void actionPerformed(ActionEvent e) { String nick = GUIMain.userList.getSelectedValue().toString(); if (nick.startsWith("@")) { nick = nick.replace("@", ""); } else if (nick.startsWith("$")) { nick = nick.replace("$", ""); } else if (nick.startsWith("+")) { nick = nick.replace("+", ""); } else if (nick.startsWith("%")) { nick = nick.replace("%", ""); } else if (nick.startsWith("~")) { nick = nick.replace("~", ""); } Command.op(nick); }
5
private void updateBalance(TextField operation, BigDecimal value) throws IOException{ if(operation.equals(addField)){ balance = balance.add(value); } else if(operation.equals(subtractField)){ balance = balance.subtract(value); } balance = balance.setScale(2, RoundingMode.FLOOR); logWriter.writeToFile("The new balance is:"); logWriter.writeToFile(balance.toString()); balanceField.setText("$" + balance.toString()); }
2
public static void ConstructBox(int side) { for (int i = 1; i <= side; i++) { if (i == 1 || i == side) { for (int j = 1; j <= side; j++) { System.out.print("$ "); } } else if (i != 1 || i != side) { for (int k = 1; k <= side; k++) { if (k == 1 || k == side) { System.out.print("$ "); } else { System.out.print(" "); } } } System.out.println(""); } System.out.println(""); }
9
public float calculate(List<Book> liste) { float result = 0f; try { List<BundleBook> listBundleBook = new ArrayList<BundleBook>(); for (Book bookActu : liste) { boolean inserted = false; for (BundleBook bundleActu : listBundleBook) { if (!bundleActu.contains(bookActu)) { bundleActu.addBook(bookActu); inserted = true; break; } } if (!inserted) { BundleBook newBundle = new BundleBook(); newBundle.addBook(bookActu); listBundleBook.add(newBundle); } } for (BundleBook bundleActu : listBundleBook) { result += bundleActu.calculate(); } } catch (Exception e) { System.err.println("Erreur lors du calcul"); e.printStackTrace(); } return result; }
6
public void setjScrollPane1(JScrollPane jScrollPane1) { this.jScrollPane1 = jScrollPane1; }
0
public IToken nextToken() { if (m_currentOffset >= (m_docOffset + m_docLength)) { return Token.EOF; } IToken result = Token.UNDEFINED; int startOffset = m_currentOffset; int length = 0; try { // Get line information IRegion lineRegion = m_document.getLineInformationOfOffset(m_currentOffset); int lineMinOffset = lineRegion.getOffset(); int lineMaxOffset = lineMinOffset + lineRegion.getLength(); // Read char char current = m_document.getChar(m_currentOffset++); length++; // Check if we are at the end of the line if (current == '\n') { result = Token.WHITESPACE; m_tokenOffset = startOffset; m_tokenLength = length; m_currentColumn = 0; } else if (current == m_delimiter) { result = new CSVToken(CSVTokenType.SEPARATOR, m_currentColumn++); m_tokenOffset = startOffset; m_tokenLength = length; //System.out.println("Token found [" + m_document.get(m_tokenOffset, m_tokenLength) + "]"); } else { // Look for the next delimiter or the next line boolean scan = true; while (scan) { // check if we are at the end of the line if (m_currentOffset >= lineMaxOffset) { CSVTokenType type = ((m_currentColumn % 2) == 0) ? CSVTokenType.ODD_COLUMN : CSVTokenType.EVEN_COLUMN; result = new CSVToken(type, m_currentColumn); m_tokenOffset = startOffset; m_tokenLength = length; m_currentColumn= 0; //System.out.println("Token found [" + m_document.get(m_tokenOffset, m_tokenLength) + "]"); scan = false; } else { // iterate until a delimiter is found char next = m_document.getChar(m_currentOffset); if (next == m_delimiter) { CSVTokenType type = ((m_currentColumn % 2) == 0) ? CSVTokenType.ODD_COLUMN : CSVTokenType.EVEN_COLUMN; result = new CSVToken(type, m_currentColumn); m_tokenOffset = startOffset; m_tokenLength = length; //System.out.println("Token found [" + m_document.get(m_tokenOffset, m_tokenLength) + "]"); scan = false; } else { m_currentOffset++; length++; } } } } } catch (BadLocationException e) { e.printStackTrace(); result = Token.EOF; } return result; }
9
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(AltaLib.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AltaLib.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AltaLib.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AltaLib.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 AltaLib().setVisible(true); } }); }
6
public void setFrame(int frameNum, byte[] theFrame) throws SoundException { if(frameNum >= getAudioFileFormat().getFrameLength()) { printError("That frame, number "+frameNum+", does not exist. "+ "The last valid frame number is " + (getAudioFileFormat().getFrameLength() - 1)); } int frameSize = getAudioFileFormat().getFormat().getFrameSize(); if(frameSize != theFrame.length) printError("Frame size doesn't match, line 383. This should" + " never happen. Please report the problem to a TA."); for(int i = 0; i < frameSize; i++) { buffer[frameNum*frameSize+i] = theFrame[i]; } }
3
public byte[] encrypt(byte[] input) { int kl = key.length, il = input.length; int iterations = il / kl; if(il % kl > 0) iterations++; for(int i = 0; i < iterations; i++) { byte[] keystream = new byte[kl]; salsa20.crypto_stream(keystream, kl, nonce, 0, key); int lim = (i+1) * kl; // In the last iteration, the input length is our limit if(lim > il) lim = il; for(int n = i * kl; n < lim; n++) { input[n] ^= keystream[n % kl]; } nextNonce(); } return input; }
4
private List<SpriteInfoBlock> parseMetadata(String data) throws IOException { // Prepare a "syntax tree" to return List<SpriteInfoBlock> nodes = new ArrayList<SpriteInfoBlock>(); // Split the metadata into individual lines and parse them individually String[] lines = data.split("\n"); for(String line : lines) { // If the line is all spaces, or begins with #, ignore it if(line.matches("\\s*") || line.matches("#.*")) { continue; } // Create a regular expression to parse lines of the type: // key = value Pattern pattern = Pattern.compile("(\\s*)([^\\s]+)\\s*=\\s*(.*[^\\s])\\s*"); Matcher matcher = pattern.matcher(line); // Try to match our line against the key = value pattern boolean matchFound = matcher.matches(); if(!matchFound) throw new IOException("Malformed .DMI metadata"); // Extract key, value and indentation String indentation = matcher.group(1); String key = matcher.group(2); String value = matcher.group(3); // Build a new entry in our parsetree for it SpriteInfoBlock new_block = new SpriteInfoBlock(); new_block.indent = (indentation.length() != 0); new_block.key = key; new_block.value = value; nodes.add(new_block); } return nodes; }
4
public ArrayList<DonneeArgos> getPositions() { return positions; }
0
public void updateTimePanel () { panelStartTime.removeAll(); JPanel tripComponentPanel = new JPanel (new GridBagLayout ()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; for (Object o: tripListModel.toArray()) { TripComponent tc = (TripComponent) o; tripComponentPanel.add (new TripTimeLabelComponent (tc.getTrip()), c); c.gridx = 1; tripComponentPanel.add (new TripTimeIndicatorComponent (tc.getTrip()),c); c.gridy += 1; c.gridx = 0; } panelStartTime.add(tripComponentPanel); }
1
@Override public boolean equals(Object obj) { Point p = (Point)obj; if(this.type== p.type && Math.abs(this.x - p.x) < 0.00001 && Math.abs(this.y - p.y) <0.00001 && this.a.id == p.a.id){ if(this.b != null && p.b != null) { return (this.b.id == p.b.id)?true:false; } else if(this.b == null && p.b == null) { return true; } return false; } else return false; }
9
public void start() { ticks=System.currentTimeMillis(); }
0
public Object nextContent() throws JSONException { char c; StringBuilder sb; do { c = next(); } while (Character.isWhitespace(c)); if (c == 0) { return null; } if (c == '<') { return XML.LT; } sb = new StringBuilder(); for (; ; ) { if (c == '<' || c == 0) { back(); return sb.toString().trim(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } c = next(); } }
7
public static boolean checkSumUsingHash(int[] A, int x) { // Time complexity - O(n) if(A == null || A.length < 2) return false; int i, flag = 0; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(i = 0; i < A.length; i++) map.put(A[i], i); for(i = 0; i < A.length; i++) { if(map.get(x - A[i]) != null && map.get(x - A[i]) != i) { System.out.println("Pair " + A[i] + ", " + A[map.get(x - A[i])] + " has sum " + x); flag = 1; } } if(flag == 1) return true; return false; }
7
private void start() { try { System.out.println("Accepting connections."); while (true) { // recieve new connections net = new Network(this, ssocket.accept()); Thread t = new Thread(net); t.start(); } } catch (IOException e) { e.printStackTrace(); } }
2
Node applyExtensionRule2( Node node, int edgeLabelBegin, int edgeLabelEnd, int pathPos, int edgePos, Rule2Type type ) throws MVDException { Node newLeaf,newInternal,son; // newSon if ( type == Rule2Type.newSon ) { if ( debug ) System.out.println("rule 2: new leaf ("+edgeLabelBegin+"," +edgeLabelEnd+")"); // create a new leaf (4) with the characters of the extension newLeaf = new Node( node, edgeLabelBegin, edgeLabelEnd, pathPos ); // connect newLeaf (4) as the new son of node (1) son = node.sons; while ( son.rightSibling != null ) son = son.rightSibling; connectSiblings(son, newLeaf); // return (4) return newLeaf; } // split if ( debug ) System.out.println( "rule 2: split ("+edgeLabelBegin+"," +edgeLabelEnd+")" ); // create a new internal node (3) at the split point newInternal = new Node( node.father, node.edgeLabelStart, node.edgeLabelStart+edgePos, node.pathPosition ); // update the node (1) incoming edge starting index (it now starts // where node (3) incoming edge ends) node.edgeLabelStart += edgePos+1; // create a new leaf (2) with the characters of the extension newLeaf = new Node( newInternal, edgeLabelBegin, edgeLabelEnd, pathPos ); // connect newInternal (3) where node (1) was // connect (3) with (1)'s left sibling connectSiblings( node.leftSibling, newInternal ); // connect (3) with (1)'s right sibling connectSiblings( newInternal, node.rightSibling ); node.leftSibling = null; // connect (3) with (1)'s father if ( newInternal.father.sons == node ) newInternal.father.sons = newInternal; // connect newLeaf (2) and node (1) as sons of newInternal (3) newInternal.sons = node; node.father = newInternal; connectSiblings( node, newLeaf ); // return (3) return newInternal; }
5
@Override public void Lands (Player P) { //If nobody owns it if (Owner == -1) { //Ask if you want to buy. Game.requestBuy(P, this); } //If you land on enemy players shipping line else if (Owner != Game.players.indexOf(P)) { if ((Game.players.get(Owner)).InPrison == false) { //Pay to your enemy depending on how many shipping lines your enemy owns int Pay = 0; int cnt = CountShippingLines(); Player OPlayer = Game.players.get(Owner); if (cnt == 1) { Pay = 500; JOptionPane.showMessageDialog(null, "Du betaler leje: " + Pay + " til ejeren"); P.ChangeMoney(-Pay); OPlayer.ChangeMoney(Pay); } else if (cnt == 2) { Pay = 1000; JOptionPane.showMessageDialog(null, "Du betaler leje: " + Pay + " til ejeren"); P.ChangeMoney(-Pay); OPlayer.ChangeMoney(Pay); } else if (cnt == 3) { Pay = 2000; JOptionPane.showMessageDialog(null, "Du betaler leje: " + Pay + " til ejeren"); P.ChangeMoney(-Pay); OPlayer.ChangeMoney(Pay); } else if (cnt == 4) { Pay = 4000; JOptionPane.showMessageDialog(null, "Du betaler leje: " + Pay + " til ejeren"); P.ChangeMoney(-Pay); OPlayer.ChangeMoney(Pay); } } } }
7
public static boolean isSimilarDel(String a, String b, int similarityAcceptError) { a = Normalizer.normalize(a, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "").toUpperCase(); b = Normalizer.normalize(b, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "").toUpperCase(); if (a.equals(b)) return true; return levenshteinDelOK(a, b, a.length() - 1, b.length() - 1, similarityAcceptError, Math.min(0, a.length() - b.length()), Math.min(0, b.length() - a.length())); }
1
@Override public String toString(){ return "CellCreature("+ID+")"; }
0
private static boolean loadConfig() { File file = new File(configFilename); serverList = defaultServerList; port = defaultPort; authList = new HashMap<String, String>(defaultAuthList); if (file.exists()) { System.out.print("Load config ... "); Document doc = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new ErrorHandler() { @Override public void error(SAXParseException e) throws SAXException { throw e; } @Override public void fatalError(SAXParseException e) throws SAXException { System.out.println("Fatal error validating the config file:"); e.printStackTrace(); System.exit(0); } @Override public void warning(SAXParseException e) throws SAXException { System.out.println("Warning validating the config file:"); e.printStackTrace(); } }); doc = builder.parse(file); Node node = doc.getDocumentElement(); Node config = XMLUtil.getChildByName(node, "config"); name = XMLUtil.getAttributeValue(XMLUtil.getChildByName(config, "name"), "value", defaultName); port = Integer.valueOf(XMLUtil.getAttributeValue(XMLUtil.getChildByName(config, "port"), "number", Integer.toString(defaultPort))); serverList = XMLUtil.getAttributeValue(XMLUtil.getChildByName(config, "serverlist"), "url", defaultServerList); Node auth = XMLUtil.getChildByName(node, "auth"); NodeList list = auth.getChildNodes(); if (list != null) { for (int i = 0; i < list.getLength(); i++) { if (list.item(i).getNodeName().equals("user")) { authList.put(XMLUtil.getAttributeValue(list.item(i), "name"), XMLUtil .getAttributeValue(list.item(i), "password")); } } } } catch (Exception e) { System.out.println("failed!"); System.out.println("An error ocurred loading the config file"); e.printStackTrace(); return false; } System.out.println("done!"); } else { System.out.println("No config file exists. Using default data."); } return true; }
5
public double outputValue(boolean calculate) { if (Double.isNaN(m_unitValue) && calculate) { if (m_input) { if (m_currentInstance.isMissing(m_link)) { m_unitValue = 0; } else { m_unitValue = m_currentInstance.value(m_link); } } else { //node is an output. m_unitValue = 0; for (int noa = 0; noa < m_numInputs; noa++) { m_unitValue += m_inputList[noa].outputValue(true); } if (m_numeric && m_normalizeClass) { //then scale the value; //this scales linearly from between -1 and 1 m_unitValue = m_unitValue * m_attributeRanges[m_instances.classIndex()] + m_attributeBases[m_instances.classIndex()]; } } } return m_unitValue; }
7
public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please enter number of rows for a matrix operation"); int rows = Integer.parseInt(reader.readLine()); System.out.println("Please enter number of columns for a matrix operation"); int columns = Integer.parseInt(reader.readLine()); int[][] matrix = new int[rows][columns]; System.out.println("Please enter row elements the matrix"); for (int i = 0; i < rows; i++) { System.out.println("Please enter row " + i + " elements"); for (int j = 0; j < columns; j++) { matrix[i][j] = Integer.parseInt(reader.readLine()); } } System.out.println("Your Matrix is : "); for (int rowIndex = 0; rowIndex < matrix.length; rowIndex++) { int[] row = matrix[rowIndex]; if (row != null) { for (int columnIndex = 0; columnIndex < row.length; columnIndex++) { System.out.print(matrix[rowIndex][columnIndex] + "\t"); } } System.out.println(); } int[][] updatedMatrix = setRowColumnZero(matrix); System.out.println("Updatedf Matrix is : "); for (int rowIndex = 0; rowIndex < updatedMatrix.length; rowIndex++) { int[] row = updatedMatrix[rowIndex]; if (row != null) { for (int columnIndex = 0; columnIndex < row.length; columnIndex++) { System.out.print(updatedMatrix[rowIndex][columnIndex] + "\t"); } } System.out.println(); } }
8
final void method3940(int i) { if (anIDirect3DVertexShader9794 == null && ((((DirectxToolkit) this).aClass251Array8113 [((DirectxToolkit) this).anInt8175]) != Class348_Sub42_Sub18.aClass251_9685)) { if (Class239_Sub18.aClass251_6030 == (((DirectxToolkit) this).aClass251Array8113 [((DirectxToolkit) this).anInt8175])) ((DirectxToolkit) this).anIDirect3DDevice9810.SetTransform (((DirectxToolkit) this).anInt8175 + 16, ((DirectxToolkit) this).aClass101_Sub2Array8131 [((DirectxToolkit) this).anInt8175] .method928(aFloatArray9797, i ^ 0x0)); else ((DirectxToolkit) this).anIDirect3DDevice9810.SetTransform (16 - -((DirectxToolkit) this).anInt8175, ((DirectxToolkit) this).aClass101_Sub2Array8131 [((DirectxToolkit) this).anInt8175] .method918(aFloatArray9797, i ^ 0x1)); int i_72_ = method3963(594, (((DirectxToolkit) this).aClass251Array8113 [((DirectxToolkit) this).anInt8175])); if ((i_72_ ^ 0xffffffff) != (anIntArray9805[((DirectxToolkit) this).anInt8175] ^ 0xffffffff)) { ((DirectxToolkit) this).anIDirect3DDevice9810.SetTextureStageState (((DirectxToolkit) this).anInt8175, 24, i_72_); anIntArray9805[((DirectxToolkit) this).anInt8175] = i_72_; } } else { ((DirectxToolkit) this).anIDirect3DDevice9810 .SetTextureStageState(((DirectxToolkit) this).anInt8175, 24, 0); anIntArray9805[((DirectxToolkit) this).anInt8175] = 0; } if (i != 1) aBoolean9801 = true; }
5
public String batchSubscribe(final BatchSubscription batchSubscription) throws MailChimpException { return post("/lists/batch-subscribe", batchSubscription, new Function<BatchSubscription, String>() { @Override public String apply(BatchSubscription input) { return gson.toJson(input); } }); }
0
public int getResult() { sqrs.add(1); sqrs.add(4); for (int sum = 6; ; sum++) { if (sum % 300 == 0) { System.out.println(sum + " debug "); System.out.println(sqrs.size() + " siize "); } for (int i = sum - 3; i > sum / 2; i--) { for (int j = i - 1; j > 2; j--) { //for (int k = 1; k<j; k++){ int k = sum - i - j; if (k >= j || k <= 0) continue; if (i + j + k == sum) { if (checkSum(i, j, k)) { System.out.println(i + " " + j + " " + k + " sum " + sum); return sum; } } //} } } } }
8
@Override public boolean hasNext() { if(current!=null){ return current.getNext()!=null; }else{ return false; } }
1
public void run() { for(;;) { try { ++x; if(x==(wd)) x=0; repaint(); Thread.sleep(20); if(stopflag) break; }catch(Exception ee){} } }
4
@Override public JSONObject main(Map<String, String> params, Session session) throws Exception { JSONObject rtn = new JSONObject(); try { JSONArray jaUserId = new JSONArray(params.get("aUserId")); long[] aUserId = new long[jaUserId.length()]; for(int i=0;i<jaUserId.length();i++) { aUserId[i] = jaUserId.getLong(i); } rtn.put("rtnCode", this.getRtnCode(200)); rtn.put("msg", Appointment.getAvailableTimeSlot(aUserId)); return rtn; } catch (JSONException e1) { return CommonResponses.showParamError(); } }
2
public static double dist(Mat src1, Mat src2, NormType normType) { assert(src1.cols == src2.cols && src1.rows == src2.rows); if (src1.isEmpty()) { // is this proper way? return norm(src2, normType); // if src1 is empty , return norm of src2 } if (src2.isEmpty()) { // is this proper way? return norm(src1, normType); // if src1 is empty , return norm of src2 } double sum = 0.0; double diff; switch (normType) { // L1 norm, get absolute value of all elements, return the squared // root of sum case NORM_L1: { for (int i = 0; i < src1.data.length; i++) { diff = src1.data[i] - src2.data[i]; sum += diff > 0 ? diff : -diff; } break; } // L2 norm, get sum of squared of all elements, return the squared // root of sum case NORM_L2: { for (int i = 0; i < src1.data.length; i++) { diff = src1.data[i] - src2.data[i]; sum += diff * diff; } sum = Math.sqrt(sum); break; } default: break; } return sum; }
8
public void visitTypeInsn(final int opcode, final String type) { buf.setLength(0); buf.append(tab2).append(OPCODES[opcode]).append(' '); appendDescriptor(INTERNAL_NAME, type); buf.append('\n'); text.add(buf.toString()); if (mv != null) { mv.visitTypeInsn(opcode, type); } }
1
@Override public void startSetup(Attributes atts) { super.startSetup(atts); addActionListener(this); }
0
@Override public void mouseClicked(MouseEvent e) { if(isEmpty()) { return; } for(UIElement ui : uiElements) { if(e.isConsumed()) { return; } if(ui.getBoundsAsRect().contains(((MouseEvent) e).getPosition())) { ui.fireEvent(e); } } e.consume(); }
4
@Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof TestIntervalCategoryDataset)) { return false; } TestIntervalCategoryDataset that = (TestIntervalCategoryDataset) obj; if (!getRowKeys().equals(that.getRowKeys())) { return false; } if (!getColumnKeys().equals(that.getColumnKeys())) { return false; } int rowCount = getRowCount(); int colCount = getColumnCount(); for (int r = 0; r < rowCount; r++) { for (int c = 0; c < colCount; c++) { Number v1 = getValue(r, c); Number v2 = that.getValue(r, c); if (v1 == null) { if (v2 != null) { return false; } } else if (!v1.equals(v2)) { return false; } } } return true; }
9
private void print() { if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) || getCurrentTreePanel().getPhylogeny().isEmpty() ) { return; } if ( !getOptions().isPrintUsingActualSize() ) { getCurrentTreePanel().setParametersForPainting( getOptions().getPrintSizeX() - 80, getOptions().getPrintSizeY() - 140, true ); getCurrentTreePanel().resetPreferredSize(); getCurrentTreePanel().repaint(); } final String job_name = Constants.PRG_NAME; boolean error = false; String printer_name = null; try { printer_name = Printer.print( getCurrentTreePanel(), job_name ); } catch ( final Exception e ) { error = true; JOptionPane.showMessageDialog( this, e.getMessage(), "Printing Error", JOptionPane.ERROR_MESSAGE ); } if ( !error && ( printer_name != null ) ) { String msg = "Printing data sent to printer"; if ( printer_name.length() > 1 ) { msg += " [" + printer_name + "]"; } JOptionPane.showMessageDialog( this, msg, "Printing...", JOptionPane.INFORMATION_MESSAGE ); } if ( !getOptions().isPrintUsingActualSize() ) { getControlPanel().showWhole(); } }
9