text
stringlengths
14
410k
label
int32
0
9
public static HashMap<String, String> getMeta(Class<?> cl) { HashMap<String, String> ret = new HashMap<String, String>(); FileSystemResource resource = new FileSystemResource(META_FILE_NAME); File text = resource.getFile(); try{ BufferedReader br = new BufferedReader(new InputStreamReader( cl.getClassLoader().getResourceAsStream( "com/imilkaeu/sprcrp/dao/parser_ru_meta.txt"))); String metaString; while ((metaString = br.readLine()) != null) { String[] metaStringSplitted = metaString.split(";"); if(metaStringSplitted[1].matches("case")) metaStringSplitted[1]="`case`"; ret.put(metaStringSplitted[0],metaStringSplitted[1]); logger.info("ADDING TO METAHASHMAP " + metaStringSplitted[0]); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ret; }
5
@Override public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { //TODO: Get sprites Image[] mUP = {new Image("res/Zornespritefs.png"), new Image("res/Zornespritefs.png")}; Image[] mDown = {new Image("res/Zornespritefs.png"), new Image("res/Zornespritefs.png")}; Image[] mLeft = {new Image("res/ZornespritefsL1.png"), new Image("res/ZornespritefsL1.png")}; Image[] mRight = {new Image("res/Zornespritefs.png"), new Image("res/Zornespritefs.png")}; board = new Image("res/bgs1.png"); aPillar = new Image("res/pillars1a.png"); bPillar = new Image("res/pillars1b.png"); background = new Image("res/bg.png"); moveUp = new Animation(mUP, duration, false); moveDown = new Animation(mDown, duration, false); moveLeft = new Animation(mLeft, duration, false); moveRight = new Animation(mRight, duration, false); player = moveDown; firstPass = true; health = 100; activeBombs = 0; currentBomb = 0; cooldown = 0; bombs = new Bomb[3]; pillars = new Pillar[40]; for(int i = 0; i < bombs.length; i++) bombs[i] = new Bomb(); int index = 0; for(int col = 135; col < GAME_HEIGHT + 85; col+= 100){ for(int row = 265; row < GAME_WIDTH + 215; row+= 100){ if(Math.random() * 10 > 6) pillars[index] = new Pillar(row, col, bPillar); else pillars[index] = new Pillar(row, col, aPillar); ++index; } } /** Load IMG assets **/ try { //Load Stage music from file stageMusic = AudioLoader.getStreamingAudio("OGG", ResourceLoader.getResource("res/FreudiasStage.ogg")); //Load damage noise from file damage = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream("res/hit.wav")); //Load bomb set noise from file bombSet = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream("res/bom_set.wav")); //load bomb explode noise from file bombExplode = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream("res/bom_last.wav")); } catch (IOException e) { e.printStackTrace(); } }
5
public String getAddTransPhysical(MemPartition b, int logicalAddr, List<MemPartition> memory) { // logicalAddr belongs to process logical space ProcessComplete p = b.getAllocated().getParent(); // Segment ? int startsegment = 0; ProcessComponent programSegment = null; boolean found = false; int i = 0; while (i < p.getNumBlocks() && !found) { programSegment = p.getBlock(i); if (startsegment + programSegment.getSize() > logicalAddr) found = true; else startsegment += programSegment.getSize(); i++; } int offset = logicalAddr - startsegment; // Segment not loaded if (!programSegment.isLoad()) return Translation.getInstance().getLabel("me_87"); // segment fault Iterator<MemPartition> it = memory.iterator(); MemPartition block = null; found = false; while (it.hasNext() && !found) { block = it.next(); if (block.getAllocated() != null && block.getAllocated().equals(programSegment)) found = true; } if (found) return "@" + new Integer(block.getStart() + offset).toString(); else return ""; // never }
9
public String getCommandTypeName(int commandType) { Integer commandTypeKey = getCommandTypeKey(commandType); if (null == commandTypeKey) { return "UNKNOWN COMMAND TYPE 0x" + Integer.toHexString(commandType); } switch(commandTypeKey.intValue()) { case EVENT_COMMAND__ScheduleEvent: return "ScheduleEvent"; case EVENT_COMMAND__ScheduleEventSet: return "ScheduleEventSet"; case EVENT_COMMAND__EV_StopDoor: return "EV_StopDoor"; case EVENT_COMMAND__IfHasItemRangeQty: return "IfHasItemRangeQty"; case EVENT_COMMAND__TakeItemRangeQty: return "TakeItemRangeQty"; case EVENT_COMMAND__LaunchParty: return "LaunchParty"; case EVENT_COMMAND__IfHasBountyRange: return "IfHasBountyRange"; case EVENT_COMMAND__IfPCCanAct: return "IfPCCanAct"; default: return super.getCommandTypeName(commandType); } }
9
private void create(Shell parent, int inSym) { result = -1; FormLayout layout = new FormLayout(); layout.marginTop = 5; layout.marginBottom = 5; layout.marginLeft = 5; layout.marginRight = 5; layout.spacing = 5; shell = new Shell(parent, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM); shell.setText("Sym Login"); shell.setLayout(layout); shell.setImage(RepDevMain.smallSymAddImage); Label symLabel = new Label(shell, SWT.NONE); symLabel.setText("Sym:"); Label aixUserLabel = new Label(shell, SWT.NONE); aixUserLabel.setText("AIX Username:"); Label aixPasswordLabel = new Label(shell, SWT.NONE); aixPasswordLabel.setText("AIX Password:"); Label userIDLabel = new Label(shell, SWT.NONE); userIDLabel.setText("UserID:"); final Text symText = new Text(shell, SWT.BORDER | (inSym != -1 ? SWT.READ_ONLY : SWT.NONE)); if (inSym != -1) symText.setText(String.valueOf(inSym)); final Text aixUserText = new Text(shell, SWT.BORDER); aixUserText.setText(lastUsername); final Text aixPasswordText = new Text(shell, SWT.BORDER | SWT.PASSWORD); aixPasswordText.setText(lastPassword); final Text userIDText = new Text(shell, SWT.BORDER | SWT.PASSWORD); userIDText.setText(lastUserID); Button ok = new Button(shell, SWT.PUSH); ok.setText("Login"); ok.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { try { sym = Integer.parseInt(symText.getText().trim()); } catch (Exception ex) { MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); dialog.setMessage("The Sym number you entered was invalid"); dialog.setText("Input Error"); dialog.open(); symText.setFocus(); return; } aixUsername = aixUserText.getText().trim(); aixPassword = aixPasswordText.getText().trim(); userID = userIDText.getText().trim(); lastUsername = aixUsername; lastPassword = aixPassword; lastUserID = userID; Config.setLastPassword(lastPassword); Config.setLastUsername(lastUsername); Config.setLastUserID(lastUserID); result = 1000; shell.dispose(); } }); Button cancel = new Button(shell, SWT.PUSH); cancel.setText("Cancel"); cancel.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { result = -1; shell.dispose(); } }); if( symText.isEnabled() && symText.getText().trim().equals("")) symText.setFocus(); else if( aixUserText.getText().trim().equals("") ) aixUserText.setFocus(); else if ( aixPasswordText.getText().trim().equals("") ) aixPasswordText.setFocus(); else if( userIDText.getText().trim().equals("") ) userIDText.setFocus(); FormData data; data = new FormData(); data.left = new FormAttachment(0); data.top = new FormAttachment(0); data.width = LABEL_WIDTH; symLabel.setLayoutData(data); data = new FormData(); data.left = new FormAttachment(symLabel); data.top = new FormAttachment(0); data.right = new FormAttachment(100); data.width = 160; symText.setLayoutData(data); data = new FormData(); data.left = new FormAttachment(0); data.top = new FormAttachment(symText); data.width = LABEL_WIDTH; aixUserLabel.setLayoutData(data); data = new FormData(); data.left = new FormAttachment(aixUserLabel); data.top = new FormAttachment(symText); data.right = new FormAttachment(100); aixUserText.setLayoutData(data); data = new FormData(); data.left = new FormAttachment(0); data.top = new FormAttachment(aixUserText); data.width = LABEL_WIDTH; aixPasswordLabel.setLayoutData(data); data = new FormData(); data.left = new FormAttachment(aixPasswordLabel); data.top = new FormAttachment(aixUserText); data.right = new FormAttachment(100); aixPasswordText.setLayoutData(data); data = new FormData(); data.left = new FormAttachment(0); data.top = new FormAttachment(aixPasswordText); data.width = LABEL_WIDTH; userIDLabel.setLayoutData(data); data = new FormData(); data.left = new FormAttachment(userIDLabel); data.top = new FormAttachment(aixPasswordText); data.right = new FormAttachment(100); userIDText.setLayoutData(data); data = new FormData(); data.top = new FormAttachment(userIDText); data.right = new FormAttachment(100); cancel.setLayoutData(data); data = new FormData(); data.top = new FormAttachment(userIDText); data.right = new FormAttachment(cancel); ok.setLayoutData(data); shell.setDefaultButton(ok); shell.pack(); shell.open(); }
8
public void update_MessageTrace(String msg){ if(reorder_msg==0 || reorder_msg==1){ synchronized(test_network.MessageTrace){ String whoamI=""; if(test_index<test_network.numProposers()) whoamI="Proposer - "+test_index; if(test_index>=test_network.numProposers() && test_index<test_network.numAcceptors()+test_network.numProposers()) whoamI="Acceptor - "+test_index; if(test_index>=test_network.numAcceptors()+test_network.numProposers() && test_index<test_network.test_totalProcesses) whoamI="Learner - "+test_index; test_network.MessageTrace.add(getCurTime()+" "+whoamI+msg); } } }
7
public static boolean banPlayer(String[] args, CommandSender s) { //Various checks if(Util.isBannedFromGuilds(s) == true){ //Checking if they are banned from the guilds system s.sendMessage(ChatColor.RED + "You are currently banned from interacting with the Guilds system. Talk to your server admin if you believe this is in error."); return false; } if(!s.hasPermission("zguilds.admin.banplayer")){ //Checking if they have the permission node to proceed s.sendMessage(ChatColor.RED + "You lack sufficient permissions to ban a player from using guilds. Talk to your server admin if you believe this is in error."); return false; } if(args.length != 3){ //Checking if the create command has proper args s.sendMessage(ChatColor.RED + "Incorrectly formatted guild ban command! Proper syntax is: \"/guild admin ban <playerName>\""); return false; } targetPlayersName = args[2].toLowerCase(); if(Main.players.getConfigurationSection("Players." + targetPlayersName) == null){ //Checking if the create command has proper args s.sendMessage(ChatColor.RED + "No player by that name exists."); return false; } if(!Main.players.getString("Players." + targetPlayersName + ".Current_Guild").matches("None")){ s.sendMessage(ChatColor.RED + "Your target player is in a guild, remove them from their guild first."); return false; } if(Main.players.getBoolean("Players." + targetPlayersName + ".Banned") == true){ //Checking if the create command has proper args s.sendMessage(ChatColor.RED + "That player is already banned from using Guilds."); return false; } Main.players.set("Players." + targetPlayersName + ".Banned", true); s.sendMessage(ChatColor.DARK_GREEN + "You banned " + targetPlayersName + " from using Guilds functionality."); Main.saveYamls(); return true; }
6
public boolean ExistsInVector(Vector<Move> moves){ for (int i = 0; i<moves.size(); i++){ if (this.Equals(moves.elementAt(i))){ return true; } } return false; }
2
@Override public void run() { do { try { getNextChar(); if (isEndOfStream()) closeRemainingStreams(); else if (isSeperatorMet()) checkSeparator(); else if (shouldCheck) checkMatching(); else passChar(); } catch (IOException e) { // TODO: handle this situation } } while (!isEndOfStream()); }
5
public static boolean checkInputs(String startingAmount, String goalAmount, DateTime beginDate, DateTime endDate ) { boolean valid = true; if(!GeneralUtill.stringToBigDecimalCheck(startingAmount)){ GuiUtill.showError("Incorrect input", "please put in the correct in put in your starting amount"); valid = false; } if(!GeneralUtill.stringToBigDecimalCheck(goalAmount)){ GuiUtill.showError("Incorrect input", "please put in the correct in put in your goal amount"); valid = false; } if(endDate.isBefore(beginDate)){ GuiUtill.showError("Incorrect date input", "Your end date is before the start date. This is not allowed"); valid = false; } if(beginDate.plusWeeks(1).isAfter(endDate)){ GuiUtill.showError("More than week", "Ensure the begin date and end date are duther apart than one week"); valid = false; } return valid; }
4
public static void main(String[] args) throws Exception { String env = null; if (args != null && args.length > 0) { env = args[0]; } if (! "dev".equals(env)) if (! "prod".equals(env)) { System.out.println("Usage: $0 (dev|prod)\n"); System.exit(1); } // Topology config Config conf = new Config(); // Load parameters and add them to the Config Map configMap = YamlLoader.loadYamlFromResource("config_" + env + ".yml"); conf.putAll(configMap); log.info(JSONValue.toJSONString((conf))); // Set topology loglevel to DEBUG conf.put(Config.TOPOLOGY_DEBUG, JsonPath.read(conf, "$.deck36_storm.debug")); // Create Topology builder TopologyBuilder builder = new TopologyBuilder(); // if there are not special reasons, start with parallelism hint of 1 // and multiple tasks. By that, you can scale dynamically later on. int parallelism_hint = JsonPath.read(conf, "$.deck36_storm.default_parallelism_hint"); int num_tasks = JsonPath.read(conf, "$.deck36_storm.default_num_tasks"); // Create Stream from RabbitMQ messages // bind new queue with name of the topology // to the main plan9 exchange (from properties config) // consuming only CBT-related events by using the rounting key 'cbt.#' String badgeName = RaiderOfTheKittenRobbersTopology.class.getSimpleName(); String rabbitQueueName = badgeName; // use topology class name as name for the queue String rabbitExchangeName = (String) JsonPath.read(conf, "$.deck36_storm.RaiderOfTheKittenRobbersBolt.rabbitmq.target_exchange"); String rabbitRoutingKey = "#"; // Get JSON deserialization scheme Scheme rabbitScheme = new SimpleJSONScheme(); // Setup a Declarator to configure exchange/queue/routing key RabbitMQDeclarator rabbitDeclarator = new RabbitMQDeclarator(rabbitExchangeName, rabbitQueueName, rabbitRoutingKey); // Create Configuration for the Spout ConnectionConfig connectionConfig = new ConnectionConfig( (String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.host"), (Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.port"), (String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.user"), (String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.pass"), (String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.vhost"), (Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.heartbeat")); ConsumerConfig spoutConfig = new ConsumerConfigBuilder().connection(connectionConfig) .queue(rabbitQueueName) .prefetch((Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.prefetch")) .requeueOnFail() .build(); // add global parameters to topology config - the RabbitMQSpout will read them from there conf.putAll(spoutConfig.asMap()); // For production, set the spout pending value to the same value as the RabbitMQ pre-fetch // see: https://github.com/ppat/storm-rabbitmq/blob/master/README.md if ("prod".equals(env)) { conf.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, (Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.prefetch")); } // Add RabbitMQ spout to topology builder.setSpout("incoming", new RabbitMQSpout(rabbitScheme, rabbitDeclarator), parallelism_hint) .setNumTasks((Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.spout_tasks")); // construct command to invoke the external bolt implementation ArrayList<String> command = new ArrayList(15); // Add main execution program (php, hhvm, zend, ..) and parameters command.add((String) JsonPath.read(conf, "$.deck36_storm.php.executor")); command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.executor_params")); // Add main command to be executed (app/console, the phar file, etc.) and global context parameters (environment etc.) command.add((String) JsonPath.read(conf, "$.deck36_storm.php.main")); command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.main_params")); // Add main route to be invoked and its parameters command.add((String) JsonPath.read(conf, "$.deck36_storm.RaiderOfTheKittenRobbersBolt.main")); List boltParams = (List<String>) JsonPath.read(conf, "$.deck36_storm.RaiderOfTheKittenRobbersBolt.params"); if (boltParams != null) command.addAll(boltParams); // Log the final command log.info("Command to start bolt for RaiderOfTheKittenRobbers badge: " + Arrays.toString(command.toArray())); // Add constructed external bolt command to topology using MultilangAdapterBolt builder.setBolt("badge", new MultilangAdapterBolt(command, "badge"), parallelism_hint) .setNumTasks(num_tasks) .shuffleGrouping("incoming"); builder.setBolt("rabbitmq_router", new Plan9RabbitMQRouterBolt( (String) JsonPath.read(conf, "$.deck36_storm.RaiderOfTheKittenRobbersBolt.rabbitmq.target_exchange"), "RaiderOfTheKittenRobbers" // RabbitMQ routing key ), parallelism_hint) .setNumTasks(num_tasks) .shuffleGrouping("badge"); builder.setBolt("rabbitmq_producer", new Plan9RabbitMQPushBolt(), parallelism_hint) .setNumTasks(num_tasks) .shuffleGrouping("rabbitmq_router"); if ("dev".equals(env)) { LocalCluster cluster = new LocalCluster(); cluster.submitTopology(badgeName + System.currentTimeMillis(), conf, builder.createTopology()); Thread.sleep(2000000); } if ("prod".equals(env)) { StormSubmitter.submitTopology(badgeName + "-" + System.currentTimeMillis(), conf, builder.createTopology()); } }
8
public static void main(String[] args)throws Exception { DerbyHelper db = new DerbyHelper("Library", 1527,"app","app"); // List<String> cmd = Files.readAllLines(Paths.get("DataBook.txt"), StandardCharsets.UTF_8); // for(String s : cmd){ // List<String> params = Arrays.asList(s.split(",")); // db.executeUpdate("INSERT INTO Book (isbn,bookname,author) VALUES(?,?,?)", params); // } // ResultSet res = db.query("SELECT * FROM book"); // System.out.printf("%10s %-30S %-30S\n","ISBN","BOOKNAME","AUTHOR"); // System.out.println("================================================="); // while(res.next()){ // System.out.printf("%10s %-30s %-30s\n",res.getString("isbn"), // res.getString("bookname"),res.getString("author")); // } // db.close(); // Scanner sc = new Scanner(System.in); // String sql = "SELECT * FROM BOOK"; // ResultSet res = db.query(sql); // int col = res.getMetaData().getColumnCount(); // String ans = ""; // List<String> params = new ArrayList<>(); // List<String> colName = new ArrayList<>(); // do{ // for(int i=1;i<=col;i++){ // String cName = res.getMetaData().getColumnName(i); // System.out.print("Enter book's "+cName+" : "); // colName.add(cName); // params.add(sc.nextLine()); // } // System.out.println("==============================="); // System.out.println("Are you sure to add this book ?"); // System.out.println("==============================="); // for(int i=0;i<colName.size();i++){ // System.out.println(colName.get(i)+" : "+params.get(i)); // } // System.out.print("\nAnswer (Y/N) :"); // ans = sc.next(); // }while(ans.toLowerCase().equals("n")); // // sql = "INSERT INTO book VALUES(?,?,?)"; // db.executeUpdate(sql, params); // System.out.println("Insert complete !!!"); Scanner sc = new Scanner(System.in); String input=null; do{ System.out.println("-----------------Library System-----------------"); System.out.println("1. Find book by ISBN"); System.out.println("2. Find book by name"); System.out.println("------------------------------------------------"); System.out.println("0. Exit"); System.out.println(""); System.out.print("Select : "); input = sc.next(); if(input.equals("1")){ System.out.print("Enter book's ISBN : "); input = sc.next(); List<Book> books = Book.findByIsbn(input); System.out.printf("%10s %-30S %-30S\n","ISBN","BOOKNAME","AUTHOR"); System.out.println("================================================="); if(books.size()>0) for(Book b : books){ System.out.printf("%10s %-30S %-30S\n",b.getIsbn(),b.getBookName(),b.getAuthor()); } else System.out.println("NOT FOUND!!!"); }else if(input.equals("2")){ System.out.print("Enter book's name : "); input = sc.next(); List<Book> books = Book.findByName(input); System.out.printf("%10s %-30S %-30S\n","ISBN","BOOKNAME","AUTHOR"); System.out.println("================================================="); if(books.size()>0) for(Book b : books){ System.out.printf("%10s %-30S %-30S\n",b.getIsbn(),b.getBookName(),b.getAuthor()); } else System.out.println("NOT FOUND!!!"); } System.out.println(""); }while(!input.equals("0")); }
7
private Expression rest( List<Expression> args, String caller ) { if ( args.size() != 1 ) { System.err.println("rest/tail expected exactly one argument and got " + args.size() ); return new Void(); } Expression expr = args.get(0).eval(defSubst, caller); if ( expr.getType().compareTo("quotelist") != 0 ) { System.err.println("rest/tail expected a quotelist as an argument and got a " + expr.getType() ); return new Void(); } QuoteList ourList = (QuoteList) expr; // the elements of the list List<Expression> elements = ourList.getElements(); // if the list is empty -> error // otherwise -> return all but the first element of the list if ( elements.size() == 0 ) { //return args.get(0).eval(defSubst); // the empty list System.err.println("Can't get rest of an empty list"); return new Void(); } else { elements.remove(0); QuoteList newList = new QuoteList(elements); return newList.eval(defSubst, caller); } }
3
public File getConfigFile() { return this.config_file; }
0
public boolean getBoolean(String key) throws JSONException { Object object = this.get(key); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); }
6
private void checkType(String key, Class<? extends Object> clazz) throws NoConfigException, DataWrongTypeException { List<String> keys = this.config(clazz); if (!keys.contains(key)) { throw new DataWrongTypeException(String.format("%s got the wrong type[%s].", key, clazz.getName())); } }
2
public final void setEnd() { panel.setBackground(Color.BLACK); String text; if (correct > incorrect || correct == incorrect) { text = "<h1>YOU WIN!</h1>"; } else { text = "<h1>YOU LOSE!</h1>"; } text += "<h2>You answered " + (int) (correct) + " of " + (int) (correct + incorrect) + " questions correctly. (" + ((int) ((correct / (correct + incorrect)) * 100)) + "%)</h2>" + "<br><i>Press any key to continue...</i>"; mainPanel.setText("<html><center>" + text + "</center></html>"); timer.startAndControlClock(timerLabel, 11); }
2
@Override public String toString() { String board = "===\n"; for (int i = 7; i >= 0; i--) { board += " "; for (int j = 0; j < 8; j++) { board += " " + _contents[i][j].textName(); } board += "\n"; } String t = turn().toString().equals("B") ? "black" : "white"; board += "Next move: " + t + "\n" + "Moves: " + movesMade() + "\n" + "==="; return board; }
3
int getCountCorrect() { int count = 0; for(int i=0;i<sudokuSize;i++) { for(int j=0;j<sudokuSize;j++) { if(cells[i][j].valueState == intializedByServer || cells[i][j].valueState == acceptedByAgent || cells[i][j].valueState == acceptedByUser) count++; } } return count; }
5
public int showPlayerSelect() { JPanel panel = new JPanel(); JLabel chooseText = new JLabel(); panel.add(chooseText); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); ButtonGroup buttongroup = new ButtonGroup(); JRadioButton[] buttons = new JRadioButton[6]; // makes radio button for each character for (Game.Character character : Game.Character.values()){ JRadioButton button = new JRadioButton(character.toString()); // sets action command to the ordinal number of the character button.setActionCommand(character.name()); buttongroup.add(button); buttons[character.ordinal()] = button; if (players.contains(new Player(new CharacterPiece(character)))){ // if there is already a player with that character, disable button button.setEnabled(false); } panel.add(button); } // initialise first button to be selected for (JRadioButton button : buttons){ if (button.isEnabled()){ button.setSelected(true); break; } } chooseText.setText("Pick character for player: "+players.size()); int response = JOptionPane.showOptionDialog(null, panel, "Pick character", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[]{"next", "done"} , null); ButtonModel buttonSelected = buttongroup.getSelection(); // if no buttons are selected. if (buttonSelected == null){ if (response == NEXT_CHARACTER){ Dialogs.showMessageBox("Oi", "Must select a player"); } return response; } // add player to the game Game.Character characterSelected = Game.Character.valueOf(buttonSelected.getActionCommand()); CharacterPiece piece = new CharacterPiece(characterSelected); if (response == NEXT_CHARACTER){ players.add(new Player(piece)); } return response; }
7
private int percolateDown(int hole, E value){ while(hole*4 + 1 <= index){ // compare the four children of the given hole find out the one with smallest value // for the index i, its parent index is (i-1)/4, its children are 4i+1,..,4i+4 int target = hole*4 + 1; // first child int second = hole*4 + 2; // second child int third = hole*4 + 3; // third child int last = hole*4 + 4; // last child //set the target to be the leftmost children and compare to change the target if(second <= index && comparator.compare(arr[target], arr[second])>0){ target = second; } if(third <= index && comparator.compare(arr[target], arr[third])>0){ target = third; } if(last <= index && comparator.compare(arr[target], arr[last])>0){ target = last; } if(comparator.compare(arr[target], value) < 0){ arr[hole] = arr[target]; hole = target; }else{ break; } } return hole; }
8
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed String searchString = txtFieldSearch.getText(); ArrayList<Staff> foundStaff = new ArrayList<Staff>(); if (searchString.isEmpty()) { foundStaff = Controller.Instance().getStaff(); } else { int searchId = -1; try { searchId = Integer.parseInt(searchString); } catch (NumberFormatException nfe) { Logger.getLogger(GenericTableModel.class.getName()).log(Level.FINER, null, nfe.getMessage()); } if (searchId != -1) { foundStaff.addAll(Controller.Instance().SearchStaff(searchId)); } Staff.PersonalType st = null; try { st = (Staff.PersonalType.valueOf(searchString)); } catch (IllegalArgumentException iae) { Logger.getLogger(GenericTableModel.class.getName()).log(Level.FINER, null, iae.getMessage()); } if(st!= null){ foundStaff.addAll(Controller.Instance().SearchStaff(st)); } foundStaff.addAll(Controller.Instance().SearchStaff(searchString)); } tblPersonal.setModel(new GenericTableModel<Staff>(foundStaff)); }//GEN-LAST:event_btnSearchActionPerformed
5
public void waitForConnect() { // fire off an action even to tell the GUI to display the waiting for // client dialogue // Start up a ServerSocket on port PORTNUM. try { serverSocket = new ServerSocket(PORTNUM); } catch (IOException e) { // Should be an actionEvent System.err.println("Could not listen on port " + PORTNUM + ". Exception: \n" + e + "\n\nProgram exiting..."); cleanup(); // Questionable // theDriver.endGame(); } // Set a timeout boolean eThrown = false; for ( int i = 0; eThrown && i < 4; i++ ) { try { serverSocket.setSoTimeout( TIMEOUT ); } catch ( SocketException e ) { System.err.println( "Couldn't set timeout for serverSocket:\n" + e ); eThrown = true; } } eThrown = false; try { // Wait for a connect request, then initialize clientSocket clientSocket = serverSocket.accept(); // For communication over network out = new ObjectOutputStream( clientSocket.getOutputStream() ); in = new ObjectInputStream( clientSocket.getInputStream() ); } catch (InterruptedIOException e) { System.err.println("Timed out while witing for client to connect. " + "Program exiting..."); cleanup(); eThrown = true; } catch (IOException e) { System.err.println("Error while waiting for client to connect " + "(not a timeout). Program exiting..."); cleanup(); eThrown = true; // Questionable //theDriver.endGame(); } // if eThrown == true, something should be done HERE! // if a client connects begin setting up the game // get the client player's name takeName(); // tell the client our name sendName(); // send the client their color sendColor(); }
6
private static void restartMIFU(){ try { @SuppressWarnings("unused") Process proc = Runtime.getRuntime().exec("java -jar "+CONSTS.UDIR+"/MIFU.jar"); } catch (IOException e) { e.printStackTrace(); } System.exit(0); }
1
public NationOptions(Specification specification, Advantages advantages) { this.specification = specification; setNationalAdvantages(advantages); if (specification != null) { int counter = 0; Map<Nation, NationState> defaultNations = new HashMap<Nation, NationState>(); for (Nation nation : specification.getNations()) { if (nation.getType().isREF()) { continue; } else if (nation.getType().isEuropean() && nation.isSelectable()) { if (counter < DEFAULT_NO_OF_EUROPEANS) { defaultNations.put(nation, NationState.AVAILABLE); counter++; } else { defaultNations.put(nation, NationState.NOT_AVAILABLE); } } else { defaultNations.put(nation, NationState.AI_ONLY); } } setNations(defaultNations); } }
6
* @Post: The appropriate rook is moved to the point that the king jumped over * @Return: */ private void moveCastlingRook(Point p) { if(chosenPiece.getX()-p.x>0)//left castle, move rook two right { Piece theRookToMove = getPiece(new Point(0,chosenPiece.getY())); if(! (theRookToMove instanceof Rook)) { throw new AssertionError("the piece being moved by the castling isn't a rook"); } myBoard.movePiece(theRookToMove, new Point(2,p.y)); theRookToMove.wasMoved(); }else//right castle, mvoe rook 3 left { Piece theRookToMove=getPiece(new Point(7,chosenPiece.getY())); if(!(theRookToMove instanceof Rook)) { throw new AssertionError("the piece being moved by the castling isn't a rook"); } myBoard.movePiece(theRookToMove,new Point(4,chosenPiece.getY())); theRookToMove.wasMoved(); } }
3
public void loadMapData(boolean enableBWTA) { String mapName = new String(getMapName()); map = new Map(getMapWidth(), getMapHeight(), mapName, getMapFileName(), getMapHash(), getHeightData(), getBuildableData(), getWalkableData()); if (!enableBWTA) { return; } // get region and choke point data File bwtaFile = new File(map.getHash() + ".jbwta"); boolean analyzed = bwtaFile.exists(); int[] regionMapData = null; int[] regionData = null; int[] chokePointData = null; int[] baseLocationData = null; HashMap<Integer, int[]> polygons = new HashMap<Integer, int[]>(); // run BWTA if (!analyzed) { analyzeTerrain(); regionMapData = getRegionMap(); regionData = getRegions(); chokePointData = getChokePoints(); baseLocationData = getBaseLocations(); for (int index = 0; index < regionData.length; index += Region.numAttributes) { int id = regionData[index]; polygons.put(id, getPolygon(id)); } // store the results to a local file (bwta directory) try { BufferedWriter writer = new BufferedWriter(new FileWriter(bwtaFile)); writeMapData(writer, regionMapData); writeMapData(writer, regionData); writeMapData(writer, chokePointData); writeMapData(writer, baseLocationData); for (int id : polygons.keySet()) { writer.write("" + id + ","); writeMapData(writer, polygons.get(id)); } writer.close(); } catch (Exception e) { e.printStackTrace(); } } // load from file else { try { BufferedReader reader = new BufferedReader(new FileReader(bwtaFile)); regionMapData = readMapData(reader); regionData = readMapData(reader); chokePointData = readMapData(reader); baseLocationData = readMapData(reader); // polygons (first integer is ID) int[] polygonData; while ((polygonData = readMapData(reader)) != null) { int[] coordinateData = Arrays.copyOfRange(polygonData, 1, polygonData.length); polygons.put(polygonData[0], coordinateData); } reader.close(); } catch (Exception e) { e.printStackTrace(); } } map.initialize(regionMapData, regionData, polygons, chokePointData, baseLocationData); }
7
public void rechPeriodique(String livre) { Integer issn = this.getIdentifiant(livre); Periodique per = this.getPeriodique(issn); if (this.getVueConsulterPeriodique() != null) { per.addObserver(getVueConsulterPeriodique()); getVueConsulterPeriodique().setPeriodique(per); per.notifierObservateurs(); if (per.getNbParutions() == 0) { if(Message.confirmation("Aucune parution pour ce périodique, voulez-vous en créer ?", "Aucune Parution") == JOptionPane.YES_OPTION ) { fermerVue(getVueConsulterPeriodique()); saisirParution(); } } } if (this.getVueNouvelleParution() != null) { per.addObserver(getVueNouvelleParution()); getVueNouvelleParution().setPeriodique(per); this.getVueNouvelleParution().setEtat(Vue.finale); per.notifierObservateurs(); } if (this.getVueNouvelArticle() != null) { if (per.getNbParutions() != 0) { per.addObserver(getVueNouvelArticle()); getVueNouvelArticle().setPeriodique(per); getVueNouvelArticle().setEtat(Vue.inter1); per.notifierObservateurs(); } else if (per.getNbParutions() == 0) { if(Message.confirmation("Il n'y a pas de parutions, voulez-vous les créer ?", "Erreur Parutions") == JOptionPane.YES_OPTION ) { fermerVue(getVueNouvelArticle()); saisirParution(); } else { per.addObserver(getVueNouvelArticle()); getVueNouvelArticle().setPeriodique(per); getVueNouvelArticle().setEtat(Vue.initiale); per.notifierObservateurs(); } } } }
8
public static void main(String[] args) { if (args.length == 2) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); double c = Math.sqrt(a * a + b * b); System.out.println(c); } }
1
public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_N){ reset(); } if(e.getKeyCode() == KeyEvent.VK_D && cardStack.size() > 0){ dealNewRow(); } repaint(); }
3
public void addCommand(Command _command) { if(!this.hasCommand(_command)) { this.commands.add(_command); } }
1
public PlanBooster(JSONObject object, Object boost) throws FatalError { super("Booster"); if (boost != null && boost instanceof Integer) { booster = (Integer) boost; } else { throw new ConfigError("Booster"); } switch (this.booster) { case 1: case 2: case 3: case 4: case 5: case 6: break; default: Output .println( "Sie haben einen falschen Boosterlevel gesetzt. Jetzt steht er auf 1.", 0); this.booster = 1; break; } }
8
public void setSector(String sector) { Sector = sector; }
0
private Instances assignClassValue(Instances dataSet) { if (dataSet.classIndex() < 0) { if (m_logger != null) { m_logger. logMessage("[ClassValuePicker] " + statusMessagePrefix() + " No class attribute defined in data set."); m_logger.statusMessage(statusMessagePrefix() + "WARNING: No class attribute defined in data set."); } return dataSet; } if (dataSet.classAttribute().isNumeric()) { if (m_logger != null) { m_logger. logMessage("[ClassValuePicker] " + statusMessagePrefix() + " Class attribute must be nominal (ClassValuePicker)"); m_logger.statusMessage(statusMessagePrefix() + "WARNING: Class attribute must be nominal."); } else { m_logger.statusMessage(statusMessagePrefix() + "remove"); } return dataSet; } if (m_classValueIndex != 0) { // nothing to do if == 0 // swap selected index with index 0 try { SwapValues sv = new SwapValues(); sv.setAttributeIndex(""+(dataSet.classIndex()+1)); sv.setFirstValueIndex("first"); sv.setSecondValueIndex(""+(m_classValueIndex+1)); sv.setInputFormat(dataSet); Instances newDataSet = Filter.useFilter(dataSet, sv); newDataSet.setRelationName(dataSet.relationName()); return newDataSet; } catch (Exception ex) { if (m_logger != null) { m_logger. logMessage("[ClassValuePicker] " +statusMessagePrefix() + " Unable to swap class attibute values."); m_logger.statusMessage(statusMessagePrefix() + "ERROR (See log for details)"); } } } return dataSet; }
7
public String join(String separator) throws JSONException { int len = this.length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < len; i += 1) { if (i > 0) { sb.append(separator); } sb.append(JSONObject.valueToString(this.myArrayList.get(i))); } return sb.toString(); }
2
public void onCommand(CommandSender sender, ChunkyCommand command, String label, String[] args) { if (!(sender instanceof Player)) { Language.IN_GAME_ONLY.bad(sender); return; } if (args.length == 0) { Language.CMD_CHUNKY_PLAYER_SET_MODE_HELP.bad(sender); return; } ChunkyPlayer cPlayer = ChunkyManager.getChunkyPlayer((Player) sender); List<String> modes = Arrays.asList(args); for (String mode : modes) { mode = mode.toLowerCase(); } boolean cleared = false; if (modes.contains("claim")) { ChunkyPlayer.getClaimModePlayers().add(cPlayer); } if (modes.contains("clear")) { cleared = true; ChunkyPlayer.getClaimModePlayers().remove(cPlayer); } if (!cleared) Language.PLAYER_MODE_SET.good(cPlayer); else Language.PLAYER_MODE_CLEAR.good(cPlayer); }
6
protected double getBreedingProbability() { return BREEDING_PROBABILITY; }
0
public synchronized HashMap<String, GameObjectInformation> updateGameObjects(int userID, Integer[] actions, HashMap<String, GameObjectInformation> clientPlayerObjects, int gameID) throws UnknownHostException, IOException, SocketTimeoutException, ClassNotFoundException { if(actions == null){ actions = new Integer[0]; } Socket socket = new Socket(SERVER_ADDRESS_GAME, GAME_PORT); socket.setSoTimeout(TIMEOUT); OutputStream outputStream = socket.getOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); InputStream inputStream = socket.getInputStream(); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); objectOutputStream.writeObject("UPDATE_GAME_INFORMATION"); objectOutputStream.writeInt(userID); objectOutputStream.writeObject(actions); objectOutputStream.writeObject(clientPlayerObjects); objectOutputStream.writeInt(gameID); objectOutputStream.flush(); HashMap<String, GameObjectInformation> gameObjectInformation = new HashMap<>(); gameObjectInformation = (HashMap<String, GameObjectInformation>)objectInputStream.readObject(); socket.close(); return gameObjectInformation; }
1
public void addUnits(int x, int y, char ch) { if (units.isEmpty()) { left = right = x; top = bottom = y; } else { if (x < left) left = x; else if (x > right) right = x; if (y < top) top = y; else if (y > bottom) bottom = y; } units.add(new Unit(x, y, ch)); }
5
public List<Team> simulateGroupStage(int nWinners, boolean verbose, int nTimeSteps) { if(teams.size() < 2) return null; //Get all 2 element combinations of all teams in group, //simulate match. for(int i = 0; i < teams.size()-1; i++) for(int j = i+1; j < teams.size(); j++) { Team A = teams.get(i); Team B = teams.get(j); Team winner = MatchSimulator.match(A, B, nTimeSteps, false, verbose); System.out.print("Match: " + A.getName() + " x " + B.getName()); if(winner != null) { Team loser = (winner.equals(A)) ? B : A; winner.incWins(); loser.incLosses(); System.out.println(" >> Winner: " + winner.getName()); continue; } A.incDraws(); B.incDraws(); System.out.println(" >> Draw"); } //Get n best teams PriorityQueue<Team> pq = new PriorityQueue<>(teams.size(), new TeamComparator()); List<Team> winners = new ArrayList<>(); Iterator<Team> it = teams.iterator(); while(it.hasNext()) pq.add(it.next()); for(int i = 0; i < nWinners; i++) winners.add(pq.poll()); return winners; }
7
public void loadBanPhraseList() { banPhraseLists = new HashMap<Integer, List<Pattern>>(); File f = new File("bannedphrases.cfg"); if (!f.exists()) try { f.createNewFile(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { Scanner in = new Scanner(f, "UTF-8"); while (in.hasNextLine()) { String line = in.nextLine().replace("\uFEFF", ""); if (line.length() > 0) { if (line.startsWith("#")) continue; String[] parts = line.split("\\|", 2); int severity = Integer.parseInt(parts[0]); line = parts[1]; if (line.startsWith("REGEX:")) line = line.replaceAll("REGEX:", ""); else line = ".*\\b" + Pattern.quote(line) + "\\b.*"; LOGGER_D.debug(line); Pattern tempP = Pattern.compile(line, Pattern.CASE_INSENSITIVE); for (int c = severity; c >= 0; c--) { if (!banPhraseLists.containsKey(c)) banPhraseLists.put(c, new LinkedList<Pattern>()); banPhraseLists.get(c).add(tempP); LOGGER_D.debug("Adding " + tempP.toString() + " to s=" + c); } } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
9
private void setWeight(double m) { this.weight = m; }
0
@Override public boolean checkActivated(String user) throws SQLException, ClassNotFoundException { sqlClass(); sqlCon(); if (!customField.isEmpty()) { query = "SELECT user_id FROM " + tablePref + "profile_fields_data WHERE pf_" + customField + "='" + user + "'"; ResultSet rs = SELECT(query); if (rs.next()) { query = "SELECT * FROM " + tablePref + "users WHERE user_id='" + rs.getInt("user_id") + "' AND user_type = '0'"; rs = SELECT(query); if (rs.next()) { closeCon(); return true; } else { closeCon(); return false; } } else { return false; } } else { query = "SELECT * FROM " + tablePref + "users WHERE username='" + user + "' AND user_type = '0'"; ResultSet rs = SELECT(query); if (rs.next()) { closeCon(); return true; } else { closeCon(); return false; } } }
4
public boolean updateOrderStatus(String orderNumber, String status) { try { Connection conn = UtilDAO.getConn(); if (!status.equals("OK") && !status.equals("NOK") && !status.equals("undefined")) { return false; } int numeroPedido = Integer.parseInt(orderNumber); String cmd = "UPDATE PEDIDO SET STATUS = ? WHERE NUMERO_PEDIDO=?"; PreparedStatement stmt = conn.prepareStatement(cmd); stmt.setString(1, status); stmt.setInt(2, numeroPedido); stmt.execute(); conn.commit(); return true; } catch (Exception e) { return false; } }
4
private void whoisonline(ServerClient activeclient) throws IOException { ArrayList<String> clientsOnline = new ArrayList<String>(); for (ServerClient sc : connectedClients) { if (sc != activeclient) // dont ask active client for its name he knows that already ^^ { clientsOnline.add(sc.getNickname()); } } try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } activeclient.getSt().writeMsg(activeclient.getClientsocket(), activeclient.getOut(), new Msg("", "server", 'C', clientsOnline)); }
3
@Override public State run(final String program, final State s) { Map<String, Integer> methodMap = Utils.getMethods(program); ClassWriter cw = new ClassWriter(0); FieldVisitor fv; MethodVisitor mv; cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER, CLASS_NAME, null, "java/lang/Object", null); cw.visitSource(CLASS_NAME + ".java", null); fv = cw.visitField(ACC_PRIVATE + ACC_STATIC, "cell", "[B", null, null); fv.visitEnd(); fv = cw.visitField(ACC_PRIVATE + ACC_STATIC, "p", "I", null, null); fv.visitEnd(); fv = cw.visitField(ACC_PRIVATE + ACC_STATIC, "add", "B", null, null); fv.visitEnd(); mv = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null); mv.visitCode(); mv.visitLdcInsn(new Integer(65536)); mv.visitIntInsn(NEWARRAY, T_BYTE); mv.visitFieldInsn(PUTSTATIC, CLASS_NAME, "cell", "[B"); mv.visitInsn(ICONST_0); mv.visitFieldInsn(PUTSTATIC, CLASS_NAME, "p", "I"); mv.visitInsn(ICONST_0); mv.visitFieldInsn(PUTSTATIC, CLASS_NAME, "add", "B"); mv.visitInsn(RETURN); mv.visitMaxs(1, 0); mv.visitEnd(); { mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); mv.visitInsn(RETURN); Label l1 = new Label(); mv.visitLabel(l1); mv.visitLocalVariable("this", "LHelloWorld;", null, l0, l1, 0); mv.visitMaxs(1, 1); mv.visitEnd(); } mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "run", "()V", null, null); mv.visitCode(); mv.visitFieldInsn(GETSTATIC, CLASS_NAME, "p", "I"); mv.visitVarInsn(ISTORE, 0); convertMethod2BC(mv, methodMap, program, false); mv.visitVarInsn(ILOAD, 0); mv.visitFieldInsn(PUTSTATIC, CLASS_NAME, "p", "I"); mv.visitInsn(RETURN); mv.visitMaxs(4, 1); mv.visitEnd(); for (Map.Entry<String, Integer> entry : methodMap.entrySet()) { mv = cw.visitMethod(ACC_PRIVATE + ACC_STATIC, "meth" + entry.getValue(), "(I)I", null, null); mv.visitCode(); convertMethod2BC(mv, methodMap, entry.getKey(), true); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(IRETURN); mv.visitMaxs(4, 1); mv.visitEnd(); } DynamicClassLoader loader = new DynamicClassLoader(); Class<?> helloWorldClass = loader.define(CLASS_NAME, cw.toByteArray()); try { helloWorldClass.getMethod("run").invoke(null); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } return null; }
7
public Object getProperty(String name, Object opNode) { validate(name, opNode); if(opNode instanceof RenderedOp && name.equalsIgnoreCase("roi")) { RenderedOp op = (RenderedOp)opNode; ParameterBlock pb = op.getParameterBlock(); // Retrieve the rendered source image and its ROI. RenderedImage src = pb.getRenderedSource(0); Object property = src.getProperty("ROI"); if (property == null || property.equals(java.awt.Image.UndefinedProperty) || !(property instanceof ROI)) { return null; } ROI srcROI = (ROI)property; // Determine the effective source bounds. Rectangle srcBounds = null; PlanarImage dst = op.getRendering(); if(dst instanceof WarpOpImage && !((OpImage)dst).hasExtender(0)) { WarpOpImage warpIm = (WarpOpImage)dst; srcBounds = new Rectangle(src.getMinX() + warpIm.getLeftPadding(), src.getMinY() + warpIm.getTopPadding(), src.getWidth() - warpIm.getWidth() + 1, src.getHeight() - warpIm.getHeight() + 1); } else { srcBounds = new Rectangle(src.getMinX(), src.getMinY(), src.getWidth(), src.getHeight()); } // If necessary, clip the ROI to the effective source bounds. if(!srcBounds.contains(srcROI.getBounds())) { srcROI = srcROI.intersect(new ROIShape(srcBounds)); } // Retrieve the scale factors float sx = 1.0F/pb.getIntParameter(1); float sy = 1.0F/pb.getIntParameter(2); // Create an equivalent transform. AffineTransform transform = new AffineTransform(sx, 0.0, 0.0, sy, 0, 0); // Create the scaled ROI. ROI dstROI = srcROI.transform(transform); // Retrieve the destination bounds. Rectangle dstBounds = op.getBounds(); // If necessary, clip the warped ROI to the destination bounds. if(!dstBounds.contains(dstROI.getBounds())) { dstROI = dstROI.intersect(new ROIShape(dstBounds)); } // Return the warped and possibly clipped ROI. return dstROI; } else { return null; } }
9
public int trap(int[] height) { if(height==null||height.length<=2) return 0; int len = height.length-1; int sum = 0; int start = 0; if(height[1]>height[0]) start = findNextHighPoint(height,0); // if(isLog) // System.out.println("start "+start); for(int i=start;i<len-1;i++){ int left = i; int right = findNextHighPoint(height, i); // if(isLog) // System.out.println(i+" right:"+right); if(right >0){ sum+=calc(height,left,right); i=right-1; }else{ break; } } return sum; }
5
public static int BSLargerThanSearch_solution2(int[] array, int key, boolean print) { if(key<array[0]) { if(print) System.out.println("Result is " + array[0]); return 0; } if(key>array[array.length-1]) { if(print) System.out.println("No Result"); return -1; } int start = 0; int end = array.length-1; int mid; while(start<end) { mid = start + (end-start)/2; if(array[mid] <= key) { start = mid+1; } else if(array[mid] > key) { end = mid; } } if(print) System.out.println("Result is " + array[start]); return start; }
8
private ArrayList<Integer> getUpdSeedSet(DatasetPattern pattern){ ArrayList<Integer> updSeedIndex = new ArrayList<Integer>(); for (int i = 0; i < this.dataset.size(); i++) { DatasetPattern p = this.dataset.get(i); if(pattern.getID() == p.getID()) continue; if(!p.isVisited()) break; double distance = EuclideanDistance.calculateDistance(pattern, p); // System.out.println("distance = " + distance); if(distance > this.eps) continue; pattern.addToNeighborhoodPoints(p.getID()); p.addToNeighborhoodPoints(pattern.getID()); if(p.getPointsAtEpsIndexs().size() == this.minPts){ p.pointCausedToBeCore(pattern.getID()); updSeedIndex.add(p.getID()); continue; } if(p.isCore(this.minPts)) updSeedIndex.add(p.getID()); } return updSeedIndex; }
6
public Double getDeterminant() { double positivo = 0.0; if (rows == 2 && cols == 2) { return values[0][0] * values[1][1] - values[1][0] * values[0][1]; } for (int i = 0; i < rows; i++) { double mult = 1.0; for (int j = 0; j < cols; j++) { int row = i + j; if (row >= rows) { row %= rows; } mult *= values[row][j]; } positivo += mult; } double negativo = 0.0; for (int i = 0; i < rows; i++) { double mult = -1.0; for (int j = 0; j < cols; j++) { int row = i + j; if (row > rows - 1) { row %= rows; } mult *= values[rows - 1 - row][j]; } negativo += mult; } return positivo + negativo; }
8
public static String createDeploymentDiagram(SoftwareSystem system, String id, String name, boolean withRespectToEP) { String deploymentDiagram = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; deploymentDiagram += "<uml:Model xmi:version=\"" + Utils.getVersionFromDate() + "\" xmlns:xmi=\"http://www.omg.org/spec/XMI/20110701\" xmlns:uml=\"http://www.eclipse.org/uml2/4.0.0/UML\" xmi:id=\"" + id + "\" name=\"" + name + "\">\n"; for (HardwareSetAlternative hardwareSetAlternative : system.getHardwareSystem().getHardwareSetAlternatives()) if (withRespectToEP) deploymentDiagram += createDevice(hardwareSetAlternative, system.getDeploymentEP()); else deploymentDiagram += createDevice(hardwareSetAlternative, system.getDeploymentW()); deploymentDiagram += "</uml:Model>"; return deploymentDiagram; }
2
public static long insert(User newUser) throws SQLException { PreparedStatement s = null; long rowCount = 0; try { // Connect to database and try to insert newUser into the database try { Class.forName("org.postgresql.Driver");} catch (ClassNotFoundException e) {} currentCon = DriverManager.getConnection(dbName); String query = "INSERT INTO users (name, age, state, role) VALUES (?, ?, ?, ?)"; s = currentCon.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); s.setString(1, newUser.getName()); s.setInt(2, newUser.getAge()); s.setString(3, newUser.getState()); s.setString(4, newUser.getRole()); // Execute the query to update the database rowCount = s.executeUpdate(); } finally { // Close connections if (rs != null) try {rs.close();} catch (SQLException ignore) {} if (s != null) try {s.close();} catch (SQLException ignore) {} if (currentCon != null) try {currentCon.close();} catch (SQLException ignore) {} } // Returns the user that was put into the database return rowCount; }
7
public static Vector localSearch(Vector v) { // Incrementally optimize this vector v = v.clone(); // don't modify the original double bestLength = Double.MAX_VALUE; Vector bestVector = v.clone(); int[] increments = new int[] { -4, 1, 1, 1, 1, 1, 1, 1, 1, -4 }; boolean improved = true; while (improved) { improved = false; // n^2 search over coefficient length v = bestVector; cLoop: for(int j = 0; j < v.coef.length; j++) { for(int inc1 : increments) { v.coef[j] = v.coef[j] + inc1; Vector v1= v.clone(); for(int i = 0; i < v1.coef.length; i++) { for(int inc2 : increments) { v1.coef[i] = v1.coef[i] + inc2; if(v1.length() > 0 && v1.length() < bestLength) { bestLength = v1.length(); bestVector = v1.clone(); improved = true; break cLoop; } } } } } } return bestVector; }
7
@Override public void setSoTimeout(int timeout) { try { mySocket.setSoTimeout(timeout); } catch (SocketException e) { e.printStackTrace(); } }
1
public static void cloneFileFromJar(String jarPath, String fileToMove, String pathTo) throws IOException { notNull(jarPath, "String jarPath"); notNull(fileToMove, "String fileToMove"); notNull(pathTo, "String pathTo"); notEmpty(jarPath, "String jarPath"); notEmpty(fileToMove, "String fileToMove"); notEmpty(pathTo, "String pathTo"); JarFile jar = null; FileOutputStream out = null; IOException exThrown = null; try { jar = new JarFile(jarPath); JarEntry entry = jar.getJarEntry(fileToMove); InputStream in = jar.getInputStream(entry); out = new FileOutputStream(pathTo); ReadableByteChannel rbc = Channels.newChannel(in); out.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (IOException ioex) { exThrown = ioex; } finally { try { if (out != null) { out.close(); } if (jar != null) { jar.close(); } } catch (IOException e) { // IGNORED } } if (exThrown != null) { throw exThrown; } }
5
static Handler remove(Handler h, Label start, Label end) { if (h == null) { return null; } else { h.next = remove(h.next, start, end); } int hstart = h.start.position; int hend = h.end.position; int s = start.position; int e = end == null ? Integer.MAX_VALUE : end.position; // if [hstart,hend[ and [s,e[ intervals intersect... if (s < hend && e > hstart) { if (s <= hstart) { if (e >= hend) { // [hstart,hend[ fully included in [s,e[, h removed h = h.next; } else { // [hstart,hend[ minus [s,e[ = [e,hend[ h.start = end; } } else if (e >= hend) { // [hstart,hend[ minus [s,e[ = [hstart,s[ h.end = start; } else { // [hstart,hend[ minus [s,e[ = [hstart,s[ + [e,hend[ Handler g = new Handler(); g.start = end; g.end = h.end; g.handler = h.handler; g.desc = h.desc; g.type = h.type; g.next = h.next; h.end = start; h.next = g; } } return h; }
7
public Integer evaluate(ArrayList<String> needle, ArrayList<String> haystack) { if (needle == null) { return Integer.valueOf(-1); } if (haystack == null) { return null; } for (int ii = 0; ii < haystack.size() - needle.size() + 1; ++ii) { boolean found = true; for (int jj = 0; jj < needle.size(); ++jj) { if (haystack.get(ii + jj) == null || needle.get(jj) == null || !haystack.get(ii + jj).equals(needle.get(jj))) { found = false; break; } } if (found) { return Integer.valueOf(ii); } } return Integer.valueOf(-1); }
8
void setTile(int x, int y, Tile tile) { // Extract the position within the chunk x = x % Chunk.width; y = y % Chunk.height; // Make sure the tile is within bounds if( x >= Chunk.width || y >= Chunk.height || x < 0 || y < 0) { return; } contents[x][y] = tile; }
4
public static void main(String[] args) throws Throwable{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); num = new HashMap<Integer, Integer>(); StringTokenizer st = new StringTokenizer(in.readLine()); boolean valid = true; int cont = 0; for (int i = 0; i < n; i++) { int a = Integer.parseInt(st.nextToken()); if(a!=0){ if( num.get(a)!=null){ num.put(a, num.get(a)+1); }else{ num.put(a, 1); } if( num.get(a) > 2 ) valid = false; } } if( valid ){ for (Integer key : num.keySet()) { if( num.get(key)==2) cont++; } System.out.println(cont); }else System.out.println("-1"); }
7
public void setLightValue(EnumSkyBlock par1EnumSkyBlock, int par2, int par3, int par4, int par5) { if (par2 >= -30000000 && par4 >= -30000000 && par2 < 30000000 && par4 < 30000000) { if (par3 >= 0) { if (par3 < 256) { if (this.chunkExists(par2 >> 4, par4 >> 4)) { Chunk var6 = this.getChunkFromChunkCoords(par2 >> 4, par4 >> 4); var6.setLightValue(par1EnumSkyBlock, par2 & 15, par3, par4 & 15, par5); for (int var7 = 0; var7 < this.worldAccesses.size(); ++var7) { ((IWorldAccess)this.worldAccesses.get(var7)).markBlockNeedsUpdate2(par2, par3, par4); } } } } } }
8
protected void updateAmount(int newAmount) { final int oldAmount = this.amount ; if (oldAmount == newAmount) return ; clearAllAttachments() ; // // First, determine how many crates and packets of the good should be // shown- int numPacks = (int) Math.ceil(newAmount * 1f / ITEM_UNIT), numCrates = 0 ; while (numPacks > 4) { numPacks -= 4 ; numCrates++ ; } final int total = numCrates + numPacks, numLevels = total / 4, topOffset = (4 * (int) Math.ceil(total / 4f)) - total ; // // Then iterate through the list of possible positions, and fill 'em up. for (int i = 0 ; i < total ; i++) { final int level = i / 4, coordIndex = (level < numLevels) ? (i % 4) : (i % 4) + topOffset ; final float coord[] = ATTACH_COORDS[coordIndex] ; attach( (i < numCrates) ? CRATE_MODEL : itemModel, coord[0], coord[1], level * 0.2f ) ; } amount = newAmount ; }
5
public int readCompass() { if (!isConnected()) { error("Robot is not connected!", "RXTXRobot", "readCompass"); return -1; } try { this.attemptTryAgain = true; String[] split = sendRaw("c", 300).split("\\s+"); this.attemptTryAgain = false; if (split.length <= 1) { error("No response was received from the Arduino.", "RXTXRobot", "readCompass"); return -1; } if (split.length - 1 != 1) { error("Incorrect length returned: " + split.length + ".", "RXTXRobot", "readCompass"); if (getVerbose()) for (int x = 0; x < split.length; ++x) this.getErrStream().println("[" + x + "] = " + split[x]); return -1; } return Integer.parseInt(split[1]); } catch (NumberFormatException e) { error("Returned string could not be parsed into an Integer.", "RXTXRobot", "readCompass"); } catch (Exception e) { error("A generic error occurred.", "RXTXRobot", "readCompass"); if (getVerbose()) { this.getErrStream().println("Stacktrace: "); e.printStackTrace(this.getErrStream()); } } return -1; }
8
public static Object getUIDefaultOfClass(Class clazz, String property) { Object retVal = null; UIDefaults defaults = getUIDefaultsOfClass(clazz); List<Object> listKeys = Collections.list(defaults.keys()); for (Object key : listKeys) { if (key.equals(property)) { return defaults.get(key); } if (key.toString().equalsIgnoreCase(property)) { retVal = defaults.get(key); } } return retVal; }
3
public void paint(Graphics g){ // if(!set) return; Graphics2D g2 = (Graphics2D)g; for(int i = 0; i < map.length; i++){ for(int j = 0; j < map[0].length; j++){ float x = map[i][j]; if(x > 1) x = 1; else if (x < 0) x = 0; g2.setColor(new Color(x,x,x)); g2.fillRect(i*scale,j*scale,scale,scale); g2.setColor(Color.black); } } }
4
public String getConteudoCarta(int i, int j) throws PosicaoDeCartaInvalidaException { if (i > 3 || i < 0 || j > 3 || j < 0) throw new PosicaoDeCartaInvalidaException( "Posição de carta fora dos limites do tabuleiro!"); return tabuleiro[i][j].getHistoria(); }
4
public void makeNonVoid() { if (type != Type.tVoid) throw new alterrs.jode.AssertError("already non void"); type = subExpressions[0].getType(); }
1
public boolean checkFinalState(PhysicsEvent event) { boolean filter = true; int pc = event.countByCharge(+1); int pm = event.countByCharge(-1); int pn = event.countByCharge( 0); if(pc<this.getMinimumByCharge(+1)||pc>this.getMaximumByCharge(+1)) return false; if(pm<this.getMinimumByCharge(-1)||pm>this.getMaximumByCharge(-1)) return false; if(pn<this.getMinimumByCharge( 0)||pn>this.getMaximumByCharge( 0)) return false; Set<Integer> pKeys = this.getIdKeys(); Iterator it = pKeys.iterator(); while(it.hasNext()) { Integer key = (Integer) it.next(); int idcount = this.getIdCount(key); if(event.countByPid(key)<idcount) return false; } return filter; }
8
public void disconnect(int frameNo) { switch (frameNo) { case 1: jCheckBox1.setSelected(false); bpmValue1.setText("Not connected"); minValue1.setText(""); maxValue1.setText(""); lastUpdateValue1.setText(""); alarmLog1.setText(""); break; case 2: jCheckBox2.setSelected(false); bpmValue2.setText("Not connected"); minValue2.setText(""); maxValue2.setText(""); lastUpdateValue2.setText(""); alarmLog2.setText(""); break; case 3: jCheckBox3.setSelected(false); bpmValue3.setText("Not connected"); minValue3.setText(""); maxValue3.setText(""); lastUpdateValue3.setText(""); alarmLog3.setText(""); break; case 4: jCheckBox4.setSelected(false); bpmValue4.setText("Not connected"); minValue4.setText(""); maxValue4.setText(""); lastUpdateValue4.setText(""); alarmLog4.setText(""); break; default: break; } }
4
protected CycList unescape(CycList cycList) { CycList unescapedCycList = new CycList(); final int cycList_size = cycList.getProperListSize(); for (int i = 0; i < cycList_size; i++) { Object obj = cycList.get(i); if (obj instanceof CycList) unescapedCycList.add(unescape((CycList) obj)); else if (obj instanceof String) { unescapedCycList.add(StringUtils.unescapeDoubleQuotes((String) obj)); } else unescapedCycList.add(obj); } if (! cycList.isProperList()) { Object dottedElement = cycList.getDottedElement(); if (dottedElement instanceof CycList) dottedElement = unescape((CycList) dottedElement); else if (dottedElement instanceof String) { dottedElement = StringUtils.unescapeDoubleQuotes((String) dottedElement); } unescapedCycList.setDottedElement(dottedElement); } return unescapedCycList; }
6
public void update(){ totalTime++; if(totalTime > 200 && !(component.getScreen() instanceof MainMenu)) setScreen(new MainMenu(component, this, input)); boolean switchScreen = false; if(logoTransparancy < 1.0f){ logoTransparancy += (float) RTSComponent.MS_PER_TICK / 2000; }else{ logoTransparancy = 1.0f; switchScreen = true; } if(switchScreen){ if(!(component.getScreen() instanceof MainMenu)) setScreen(new MainMenu(component, this, input)); } }
5
private int hash(String input) { int output = 0; for(int i = 0; i < input.length(); i++) { output += (int)input.charAt(i); } output %= this.size; return output; }
1
public static void gameOn() { int numOfPlayers = Integer.parseInt(JOptionPane.showInputDialog("Number of players?")), playerTurn = 0; Player currentPlayer; Deck selectedCard; ArrayList<Deck> currentPlayerCards; String resultMessage = "", catMessage = ""; createPlayers(numOfPlayers); scarecrowsOnDeck = true; while (scarecrowsOnDeck) { currentPlayer = players.get(playerTurn); // Result message resultMessage = "There are " + deck.size() + " cards on the deck.\n\nScarecrow cards found: " + scarecrowCounter + ".\n\n"; resultMessage += "Player's turn: " + currentPlayer.getName().toUpperCase() + "\n\nRESULTS TABLE:\n"; for (int i = 0; i < players.size(); i++) { resultMessage += players.get(i).getName().toUpperCase() + " has: " + players.get(i).getNumberOfBirdCards() + " Bird cards.\n"; } selectedCard = deck.remove(deck.size() - 1); resultMessage += "\n" + catMessage; JOptionPane.showMessageDialog(null, resultMessage); catMessage = ""; if (selectedCard.getKind() == Deck.KindOfCard.BirdCard) { currentPlayer.addCard(selectedCard); } else if (selectedCard.getKind() == Deck.KindOfCard.ScarecrowCard) { scarecrowCounter++; if (scarecrowCounter == 6) { scarecrowsOnDeck = false; } } else { catMessage = "A cat has scared all of your birds " + currentPlayer.getName().toUpperCase() + "."; deck.add(selectedCard); currentPlayerCards = currentPlayer.getCards(); for (Deck card : currentPlayerCards) { deck.add(card); } currentPlayer.clearPlayerCards(); shuffle(); } playerTurn++; if (playerTurn > numOfPlayers - 1) { playerTurn = 0; } } gameOver(); }
7
public void keyPressed(KeyEvent e) { if (e.getKeyChar() == 'a' || e.getKeyChar() == 'A') { theMap.getCharacter().setDirection(-1); } else if (e.getKeyChar() == 'd' || e.getKeyChar() == 'D') { theMap.getCharacter().setDirection(1); } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { System.exit(0); } else if (e.getKeyCode() == KeyEvent.VK_W){ theMap.getCharacter().jump(); } }
6
public double GetItemShopValue(int ItemID, int Type, int fromSlot) { double ShopValue = 1; double Overstock = 0; double TotPrice = 0; for (int i = 0; i < server.itemHandler.MaxListedItems; i++) { if (server.itemHandler.ItemList[i] != null) { if (server.itemHandler.ItemList[i].itemId == ItemID) { ShopValue = server.itemHandler.ItemList[i].ShopValue; } } } /*Overstock = server.shopHandler.ShopItemsN[MyShopID][fromSlot] - server.shopHandler.ShopItemsSN[MyShopID][fromSlot];*/ TotPrice = (ShopValue * 1); //Calculates price for 1 item, in db is stored for 0 items (strange but true) /*if (Overstock > 0 && TotPrice > 1) { //more then default -> cheaper TotPrice -= ((ShopValue / 100) * (1 * Overstock)); } else if (Overstock > 0 && TotPrice < 1) { //more then default -> cheaper TotPrice = ((ShopValue / 100) * (1 * Overstock)); } else if (Overstock < 0) { //less then default -> exspensive TotPrice += ((ShopValue / 100) * (1 * Overstock)); }*/ if (server.shopHandler.ShopBModifier[MyShopID] == 1) { TotPrice *= 1; //25% more expensive (general stores only) if (Type == 1) { TotPrice *= 1; //general store buys item at 40% of its own selling value } } else if (Type == 1) { TotPrice *= 1; //other stores buy item at 60% of their own selling value } return TotPrice; }
6
protected void tickEntities() { for(int i = 0;i<entities.size();i++) { Entity e = entities.get(i); if(e != null) { if(e.world != this) { entities.remove(e); } else e.tick(); } } if(!this.tileEntities.isEmpty()) { for(int i = 0 ; i < this.tileEntities.size() ; i++) { TileEntity e = this.tileEntities.get(i); if(e != null) { e.onUpdate(); } } } }
6
private static int dividers(int n){ // assumes n >= 1 int count=1; // 1 is always a divider int i=0; for (i=2;i<=Math.sqrt(n);i++){ if (n%i == 0){ if (i == Math.sqrt(n)) count+=1; else count+=2; } } return count; }
3
private void getAlarmList() { try { List<Alarm> alarms; DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeBytes(ServerFrame.getAlarmListCmd + "\n"); ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); alarms = (List<Alarm>) ois.readObject(); updateAlarmListComboBox.removeAllItems(); dropAlarmComboBox.removeAllItems(); if(!alarms.isEmpty()) { for(Alarm a : alarms) { AlarmListViewHelper helper = new AlarmListViewHelper(a); updateAlarmListComboBox.addItem(helper); dropAlarmComboBox.addItem(helper); } } } catch(Exception e) { connect(); } }
3
public static int getRecommendedExpansionDeployment(BotState state) { int out = 0; String gameState = GameStateCalculator.calculateGameState(state); if (gameState.equals("open")) { out = getRecommendedExpansionDeploymentGameOpen(state); } else if (gameState.equals("stalemate")) { out = getRecommendedExpansionDeploymentGameStalemate(state); } else if (gameState.equals("won")) { out = getRecommendedExpansionDeploymentGameWon(state); } else if (gameState.equals("lost")) { out = getRecommendedExpansionDeploymentGameLost(state); } else if (gameState.equals("timeWorkingForUs")) { out = getRecommendedExpansionDeploymentTimeWorkingForUs(state); } else if (gameState.equals("timeWorkingAgainstUs")) { out = getRecommendedExpansionDeploymentTimeWorkingAgainstUs(state); } else if (gameState.equals("armiesAdvantage")) { // Debug out = getRecommendedExpansionDeploymentGameOpen(state); } else if (gameState.equals("armiesDisadvantage")) { // Debug out = getRecommendedExpansionDeploymentGameOpen(state); } return out; }
8
@Override public List<Product> getAll() throws SQLException { List<Product>products = null; Session session=null; try{ session=HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); products = session.createCriteria(Product.class).list(); session.getTransaction().commit(); }catch(Exception e){ e.printStackTrace(); }finally{ if(session!=null && session.isOpen()) session.close(); } return products; }
3
private java.util.ArrayList<Element> getAttributes(Node attributeGroup){ java.util.ArrayList<Element> elements = new java.util.ArrayList<Element>(); String name = DOM.getAttributeValue(attributeGroup, "name"); String ref = DOM.getAttributeValue(attributeGroup, "ref"); if (name.length()>0){ NodeList attributes = attributeGroup.getChildNodes(); for (Node attribute : DOM.getNodes(attributes)){ String attributeNodeName = stripNameSpace(attribute.getNodeName()); if (attributeNodeName.equalsIgnoreCase("attribute")){ Element element = new Element(attribute); elements.add(element); if (element.IsComplex){ decomposeComplexType(stripNameSpace(element.Type), element); } } else if (attributeNodeName.equalsIgnoreCase("attributeGroup")){ java.util.Iterator<Element> it = getAttributes(attribute).iterator(); while (it.hasNext()){ elements.add(it.next()); } } } } else if (ref.length()>0){ Element temp = new Element("", name); decomposeComplexType(stripNameSpace(ref), temp); java.util.Iterator<Object> it = temp.children.iterator(); while (it.hasNext()){ Object obj = it.next(); if (obj instanceof Element){ elements.add((Element)obj); } } } return elements; }
9
public void addPlayer(String name , PlayerData player) { if( player == null ) { player = new PlayerData(this) ; } // Register the MBean ObjectName oName ; try { oName = new ObjectName("org.dkhenry.minejmx:type=PlayerData,name="+name); if( mbs.isRegistered(oName) ) { mbs.unregisterMBean(oName) ; } mbs.registerMBean(player, oName) ; } catch (InstanceAlreadyExistsException e) { e.printStackTrace(); } catch (MBeanRegistrationException e) { e.printStackTrace(); } catch (NotCompliantMBeanException e) { e.printStackTrace(); } catch (MalformedObjectNameException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } catch (InstanceNotFoundException e) { e.printStackTrace(); } this.playerData.put(name, player) ; }
8
public boolean checkInput() { for (JTextField i : components) if((i.getText() == null) || (i.getText().equals(""))) return false; return true; }
3
protected boolean fillOutCopyCodes(final Modifiable E, List<String> ignoreStats, String defPrefix, XMLTag piece, Map<String,Object> defined) throws CMException { final String copyStatID = findOptionalStringNow(E,ignoreStats,defPrefix,"COPYOF",piece,defined, false); if(copyStatID!=null) { final List<String> V=CMParms.parseCommas(copyStatID,true); for(int v=0;v<V.size();v++) { String s = V.get(v); if(s.startsWith("$")) s=s.substring(1).trim(); final XMLTag statPiece =(XMLTag)defined.get(s.toUpperCase().trim()); if(statPiece == null) { Object o=CMClass.getMOBPrototype(s); if(o==null) o=CMClass.getItemPrototype(s); if(o==null) o=CMClass.getObjectOrPrototype(s); if(!(o instanceof Modifiable)) throw new CMException("Invalid copystat: '"+s+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100)); final Modifiable E2=(Modifiable)o; fillOutCopyStats(E,E2); } else { final XMLTag likePiece =(XMLTag)defined.get(s.toUpperCase().trim()); if(likePiece == null) throw new CMException("Invalid copystat: '"+s+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100)); final BuildCallback callBack=new BuildCallback() { @Override public void willBuild(Environmental E2, XMLTag XMLTag) { fillOutCopyStats(E,E2); } }; findItems(E,likePiece,defined,callBack); findMobs(E,likePiece,defined,callBack); findAbilities(E,likePiece,defined,callBack); findExits(E,likePiece,defined,callBack); } } return V.size()>0; } return false; }
8
@Override public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) { Paint p = new Paint(); Point point_to_draw = new Point(); //Projection projection = mapView.getProjection(); //p.setColor(Color.BLUE); p.setARGB(255, 0, 0, 0); if(isVisible()) if(shadow==false) { if(mFollowFix) { mapView.getController().setCenter(getMainActor().getPosition()); //wmap.invalidate(); } // adjust the zoom to farthest actors if (mAdjustFix){ WPoint first_farthest = actors.get(getFarthestActor(FIRST_FARTHEST_ACTOR)).getPosition(); //wmap.adjustMap(first_farthest); mapView.getController().zoomToSpan( 2*Math.abs(first_farthest.getLatitudeE6() - getMainActor().getPosition().getLatitudeE6()), 2*Math.abs(first_farthest.getLongitudeE6() - getMainActor().getPosition().getLongitudeE6())); //System.out.println("mAdjust"); //wmap.invalidate(); } /* for(int i=0; i < this.getActorNumber(); i++) { //Drawable icon = actors.get(i).getMarker(0) //projection.toPixels(actors.get(i).getPosition(),point_to_draw); if(compassEnabled && i==main_actor_index){ actors.get(i).draw(canvas, mapView, shadow, when, mAzimuth); } else{ if(i==main_actor_index) actors.get(i).draw(canvas, mapView, shadow, when); else if(actors.get(i).isOriented()) actors.get(i).draw(canvas, mapView, shadow, when, mAzimuth); else actors.get(i).draw(canvas, mapView, shadow, when); } //actors.get(i).getMarker(0) } */ for(int i=0; i < this.getActorNumber(); i++) { if(compassEnabled && i==0){ actors_ordered.get(i).draw(canvas, mapView, shadow, when, mAzimuth); } else{ if(i==main_actor_index) { actors_ordered.get(i).draw(canvas, mapView, shadow, when); } else if(actors.get(i).isOriented()) actors_ordered.get(i).draw(canvas, mapView, shadow, when, mAzimuth); else actors_ordered.get(i).draw(canvas, mapView, shadow, when); } } wmap.postInvalidate(); //wmap.postInvalidate(); } return shadow; }
9
private void parseDirectory(WZDirectoryEntry dir) { int entries = WZTool.readValue(lea); for (int i = 0; i < entries; i++) { byte marker = lea.readByte(); String name = null; @SuppressWarnings("unused") int dummyInt; int size, checksum; switch (marker) { case 0x02: name = WZTool.readDecodedStringAtOffsetAndReset(slea, lea.readInt() + this.headerSize + 1); size = WZTool.readValue(lea); checksum = WZTool.readValue(lea); dummyInt = lea.readInt(); dir.addFile(new WZFileEntry(name, size, checksum, dir)); break; case 0x03: case 0x04: name = WZTool.readDecodedString(lea); size = WZTool.readValue(lea); checksum = WZTool.readValue(lea); dummyInt = lea.readInt(); if (marker == 3) { dir.addDirectory(new WZDirectoryEntry(name, size, checksum, dir)); } else { dir.addFile(new WZFileEntry(name, size, checksum, dir)); } break; default: log.error("Default case in marker ({}):/", marker); } } for (MapleDataDirectoryEntry idir : dir.getSubdirectories()) { parseDirectory((WZDirectoryEntry) idir); } }
6
public void reduce(IntWritable docId, Iterable<Text> termFrequencies, Context context) throws IOException { /* Dont collect to reduce rather write straight-away to $OUTPUT_FOLDER/Index/TermIndex/ */ int[] finalTermFrq = new int[2]; boolean mtTypeIncdence = false; Configuration conf = context.getConfiguration(); String termCountString = conf.get("TermCount"); int termCount = /*10000; conf.setIfUnset("TermCount", "10000"); if(termCountString != null) termCount =*/ Integer.parseInt(termCountString); System.out.println("Reducer Conf : Working on TermDocIndexer with "+conf.get("DocCount")+" documents using "+conf.get("TermCount")+" terms"); float[] docVector = new float[termCount]; int termFreq = 0; for (Text termInformation : termFrequencies) { String termInfo[] = termInformation.toString().split("\t"); System.out.println("Input is : "+termInformation); if(termInfo.length>=2) { int curTermIdx = Integer.parseInt(termInfo[0]); float curTermWt = Float.parseFloat(termInfo[1]); if(curTermWt == 2) mtTypeIncdence = true; if(curTermIdx<termCount && curTermIdx>=0) docVector[curTermIdx] += curTermWt; else { System.out.println("ERROR !! - TermIdx "+curTermIdx+" with frequency "+curTermWt+" out of range"); } } } String val = ""; for(int i=0;i<termCount;i++) { if(mtTypeIncdence==true) { if(docVector[i]!=0) val+="1\t"; else val+="0\t"; } else { val+=docVector[i]+"\t"; } } try { context.write(docId, new Text(val)); } catch (InterruptedException e) { // TODO Auto-generated catch block System.out.println("Failed emitting from reducer"); e.printStackTrace(); } }
9
public boolean containsMappings() { if (this.mapping != null) { return true; } for (int i = 0; i < propertyCount(); i++) { if (getProperty(i).getMapping() != null) { return true; } } for (int i = 0; i < sectionCount(); i++) { if (getSection(i).containsMappings()) { return true; } } return false; }
5
@Override public void unInvoke() { if(canBeUninvoked()) { if(affected instanceof MOB) { final MOB mob=(MOB)affected; if((found!=null)&&(!aborted)&&(mob.location()!=null)) { final CMMsg msg=CMClass.getMsg(mob,found,this,getCompletedActivityMessageType(),null); msg.setValue(CMLib.dice().roll(1,7,3)*(baseYield()+abilityCode())); if(mob.location().okMessage(mob, msg)) { String s="s"; if(msg.value()==1) s=""; msg.modify(L("<S-NAME> manage(s) to chop up @x1 pound@x2 of @x3.",""+msg.value(),s,foundShortName)); mob.location().send(mob, msg); for(int i=0;i<msg.value();i++) { final Item newFound=(Item)found.copyOf(); if(!dropAWinner(mob,newFound)) { break; } } } } } } super.unInvoke(); }
9
public GraphicsConnection(Socket clientSocket, GraphicsContainer containerArg){ messages = new ConcurrentLinkedQueue<JSONObject>(); container = containerArg; socket = clientSocket; try { inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (IOException e){ Debug.error("error creating connection handler: " + e); } debugConnection = this; }
1
public static void main(String args[]) { //prompt System.out.println("Convert your weight on earth to:"); //output list for (Destination d : Destination.values()) { System.out.print(d.getChoice() + ". " + d.name() + "\n"); } //prompt for user input System.out.print("Select a destination by number: "); //define destination answer int destination = in.nextInt(); //loop through values for (Destination d : Destination.values()) { //if it is the current dest and is not quit if (d.getChoice() == destination && d != Destination.Quit) { //ask user for their weight System.out.print("Enter your weight: "); //define weight int weight = in.nextInt(); //give answer System.out.println("Your weight on " + d.name() + " would be " + Round.tenths(weight * d.getValue()) + " pounds.\n"); break; } else if (d == Destination.Quit) { //quit program System.out.println("Bye!"); System.exit(0); } } //restart program main(null); }
5
public void setId(long Id) { this.Id = Id; }
0
double[][] graySmooth(BufferedImage image) { double[][] graySmoothed = new double[image.getWidth()][image.getHeight()]; for(int x = 0; x < graySmoothed.length; ++x) { for(int y = 0; y < graySmoothed[x].length; ++y) { if(x < 1 || x >= graySmoothed.length - 1 || y < 1 || y >= graySmoothed[x].length - 1) { graySmoothed[x][y] = grayscale(image.getRGB(x, y)); continue; } graySmoothed[x][y] = smooth(x, y, image); } } return graySmoothed; }
6
public static void main(String[] args) { Scanner entrada = new Scanner(System.in); int num1, num2, num3, num4, num5, menor, mayor; System.out.print("Escriba el primer entero: "); num1 = entrada.nextInt(); menor = num1; mayor = num1; System.out.print("Escriba el segundo entero: "); num2 = entrada.nextInt(); if(num2 < menor) menor = num2; if(num2 > mayor) mayor = num2; System.out.print("Escriba el tercer entero: "); num3 = entrada.nextInt(); if(num3 < menor) menor = num3; if(num3 > mayor) mayor = num3; System.out.print("Escriba el cuarto entero: "); num4 = entrada.nextInt(); if(num4 < menor) menor = num4; if(num4 > mayor) mayor = num4; System.out.print("Escriba el quinto entero: "); num5 = entrada.nextInt(); if(num5 < menor) menor = num5; if(num5 > mayor) mayor = num5; System.out.printf("\nMenor: %d", menor); System.out.printf("\nMayor: %d\n", mayor); }
8
protected UVW computeUVW() { Vector3 w = subtract(eye, look).normalize(); Vector3 up = rotate(this.up, w, roll); // take care of the singularity by hardwiring in specific camera orientations if (eye.getX() == look.getX() && eye.getZ() == look.getZ() && eye.getY() > look.getY()) { // camera looking vertically down return new UVW( new Vector3(0, 0, 1), new Vector3(1, 0, 0), new Vector3(0, 1, 0)); } if (eye.getX() == look.getX() && eye.getZ() == look.getZ() && eye.getY() < look.getY()) { // camera looking vertically up return new UVW( new Vector3(1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, -1, 0)); } //Otherwise, calculate UVW Vector3 u = cross(up, w).normalize(); Vector3 v = cross(w, u); return new UVW(u, v, w); }
6
protected void loadFields(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { super.loadFields(__in, __typeMapper); __in.peekTag(); if (__typeMapper.isElement(__in, CreatedBy__typeInfo)) { setCreatedBy((com.sforce.soap.enterprise.sobject.Name)__typeMapper.readObject(__in, CreatedBy__typeInfo, com.sforce.soap.enterprise.sobject.Name.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CreatedById__typeInfo)) { setCreatedById(__typeMapper.readString(__in, CreatedById__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CreatedDate__typeInfo)) { setCreatedDate((java.util.Calendar)__typeMapper.readObject(__in, CreatedDate__typeInfo, java.util.Calendar.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, Field__typeInfo)) { setField(__typeMapper.readString(__in, Field__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, IsDeleted__typeInfo)) { setIsDeleted((java.lang.Boolean)__typeMapper.readObject(__in, IsDeleted__typeInfo, java.lang.Boolean.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, NewValue__typeInfo)) { setNewValue((java.lang.Object)__typeMapper.readObject(__in, NewValue__typeInfo, java.lang.Object.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, OldValue__typeInfo)) { setOldValue((java.lang.Object)__typeMapper.readObject(__in, OldValue__typeInfo, java.lang.Object.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, Parent__typeInfo)) { setParent((com.sforce.soap.enterprise.sobject.Cloudswarm__Opportunity_Swarm_Rule__c)__typeMapper.readObject(__in, Parent__typeInfo, com.sforce.soap.enterprise.sobject.Cloudswarm__Opportunity_Swarm_Rule__c.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, ParentId__typeInfo)) { setParentId(__typeMapper.readString(__in, ParentId__typeInfo, java.lang.String.class)); } }
9
@Test public void convertGameStateToStringTest2() { City_Graph city_graph2 = new City_Graph(); city_graph2.loadMap("res/test2.mp"); assertEquals(city_graph2.convertGameStateToString(),"CRNNNNRNNC"); }
0
private int countNeighbours(Point p) { int count = 0; for(int dx = -1; dx <= 1; dx++) for(int dy = -1; dy <= 1; dy++) { Point neighbour = new Point(p.x + dx, p.y + dy); if ((dx != 0 || dy != 0) && neighbour.x >= 0 && neighbour.x < size.height && neighbour.y >= 0 && neighbour.y < size.width && grid.getState(neighbour) == CellState.ALIVE) count++; } return count; }
9
public static Menu getInstance() { if (uniqueInstance == null) { synchronized (Orders.class) { if (uniqueInstance == null) { uniqueInstance = new Menu(Storage.getInstance()); } } } return uniqueInstance; }
2
public static void setDynEffects(Modifiable M, HTTPRequest httpReq) { final QuadVector<String,String,String,String> theclasses=new QuadVector<String,String,String,String>(); boolean supportsRoles=CMParms.contains(M.getStatCodes(), "GETREFFROLE"); if(httpReq.isUrlParameter("REFFS1")) { int num=1; String behav=httpReq.getUrlParameter("REFFS"+num); while(behav!=null) { if(behav.length()>0) { String parm=httpReq.getUrlParameter("REFPRM"+num); if(parm==null) parm=""; String levl=httpReq.getUrlParameter("REFLVL"+num); if(levl==null) levl="0"; String roles=null; if(supportsRoles) roles=httpReq.getUrlParameter("REFROL"+num); if(roles==null) roles=""; theclasses.addElement(behav,parm,levl,roles); } num++; behav=httpReq.getUrlParameter("REFFS"+num); } } M.setStat("NUMREFF", ""+theclasses.size()); for(int i=0;i<theclasses.size();i++) { M.setStat("GETREFF"+i, theclasses.elementAt(i).first); M.setStat("GETREFFLVL"+i, theclasses.elementAt(i).third); M.setStat("GETREFFPARM"+i, theclasses.elementAt(i).second); if(supportsRoles) M.setStat("GETREFFROLE"+i, theclasses.elementAt(i).fourth); } }
9