text
stringlengths
14
410k
label
int32
0
9
public String stringApiValue() { if (isEmpty()) { return "(list)"; } final int fullSlices = (size() / MAX_STRING_API_VALUE_LIST_LITERAL_SIZE); if (fullSlices > MAX_STRING_API_VALUE_LIST_LITERAL_SIZE) { // @todo this could be improved upon, since the // (NCONC (LIST ... slice1 ... ) (LIST ... slice2 ...)) // trick could be wrapped with another level of NCONC to handle even bigger // expressions, and so on and so forth, requiring only // MAX_STRING_API_VALUE_LIST_LITERAL_SIZE+nesting depth stack space // at any one point ... throw new IllegalArgumentException("Cannot currently handle LISTs longer than " + MAX_STRING_API_VALUE_LIST_LITERAL_SIZE * MAX_STRING_API_VALUE_LIST_LITERAL_SIZE); } final int tailSliceStart = fullSlices * MAX_STRING_API_VALUE_LIST_LITERAL_SIZE; final boolean fitsIntoOneSlice = fullSlices == 0; final StringBuilder result = new StringBuilder(size() * 20); final boolean properList = isProperList(); if (!fitsIntoOneSlice) { // we have multiple slices result.append("(nconc").append(" "); for (int i = 0; i < fullSlices; i++) { int start = i * MAX_STRING_API_VALUE_LIST_LITERAL_SIZE; int end = start + MAX_STRING_API_VALUE_LIST_LITERAL_SIZE; // and full slices are ALL proper appendSubSlice(result, start, end, true); } } // @note if fullSlices is 0, tailSliceStart will be 0 also appendSubSlice(result, tailSliceStart, getProperListSize(), properList); if (!fitsIntoOneSlice) { result.append(")"); } return result.toString(); }
5
public void clearField() { for (int i = 0; i < gameFieldView().dBricksView().size(); i++) { BARRIERS_GROUP.remove(gameFieldView().dBricksView().get(i).sprite()); } gameFieldView().dBricksView().clear(); for (int i = 0; i < gameFieldView().iBricksView().size(); i++) { BARRIERS_GROUP.remove(gameFieldView().iBricksView().get(i).sprite()); } gameFieldView().iBricksView().clear(); for (int i = 0; i < gameFieldView().ballsView().size(); i++) { BALLS_GROUP.remove(gameFieldView().ballsView().get(i).sprite()); } gameFieldView().ballsView().clear(); if (gameFieldView().racketView() != null) { BARRIERS_GROUP.remove(gameFieldView().racketView().sprite()); RACKET_GROUP.remove(gameFieldView().racketView().sprite()); gameFieldView().deleteElementFieldView(gameFieldView().racketView()); } }
4
@Override public Balance Accesscreate() { return Balance.create(); }
0
@RequestMapping(value="agregarStock", method=RequestMethod.POST) public ModelAndView agregarStock(@ModelAttribute(value="nombreProducto") String nombreProducto, @ModelAttribute(value="cantidadProducto") Integer cantidadProducto) { Stock stock = Stock.getInstance(); if (cantidadProducto != null) { stock.agregarStock(nombreProducto, cantidadProducto); } cantidadProducto = stock.obtenerStockDisponible(nombreProducto); ModelMap model = new ModelMap(); model.put("producto", nombreProducto); model.put("stock", cantidadProducto); return new ModelAndView("agregarStock", model); }
1
private boolean kill(String[] args) { if (args.length >= 2) { Client client; if (clientList.containsKey(args[1])) { client = clientList.get(args[1]); if (args.length == 2) { client.disconnect(); return true; } else { /* Build a string from the given arguments */ String reason = ""; for (int i = 2; i < args.length; i++) { reason = reason+" "+args[i]; } client.disconnect(reason); return true; } } else { System.out.printf("The client: \"%s\" is not currently connected.\n", args[1]); return false; } } else { System.out.println("Incorrect usage. \"kill <client_username>\""); return false; } }
4
private Card getLowestCard(Player p) { Card lowest = null; for (Card card : p.getHand()) { Card.Rank rank = card.getRank(); if (rank != Card.Rank.TWO && rank != Card.Rank.TEN && (lowest == null || rank.compareTo(lowest.getRank()) < 0)) lowest = card; } return lowest; }
5
@Override public boolean containsInteger(String name) { JOSObject<? , ?> raw = this.getObject(name); if(raw == null) return false; if(raw.getName().equalsIgnoreCase(INTEGER_NAME)) return true; return false; }
4
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) public void onEntityDamage(EntityDamageEvent event) { if(!(event.getEntity() instanceof Player)) return; Player p = (Player) event.getEntity(); AGPlayer agp = pH.getAGPlayer(p.getName()); if(agp == null) return; if(agp.isPraying()) { agp.setPraying(false); if(ConfigHandler.usePotionEffects) { p.removePotionEffect(PotionEffectType.BLINDNESS); p.removePotionEffect(PotionEffectType.CONFUSION); } Messenger.sendMessage(p, Message.interrupted); } }
4
public void kickStartSimulatedAnnealing(){ OutputWriter.println(SA_START_MSG); AnnealedProgramsGatherer gatherer = new AnnealedProgramsGatherer(); List<Thread> annealedSimulators = new ArrayList<Thread>(); List<Program> toAnneal = selectionCrossoverOp.select(population, populationSize/2 + 1); List<Thread> threads = new ArrayList<Thread>(); for(final Program program: toAnneal) { Thread t = new Thread(new SimulatedAnnealingThread(program.clone(), gatherer, population.getFitnessFunction())); threads.add(t); t.start(); } try { for(Thread t: threads) t.join(); } catch (InterruptedException e) { e.printStackTrace(); } population.clear(); population.addAllPrograms(gatherer.getAnnealed()); doIteration(); }
3
public void handle(UserProcessingEvent event) { if (Boolean.getBoolean(Configuration.MULTI_LANE_MODES)) { ProcessingWorkEntry entry = new ProcessingWorkEntry(); ProcessingWork work = new ProcessingWork(); work.setEvent(event); entry.setWork(work); try { WorkManagerFactory.getInstance().getWorkManager(WorkType.COMMAND).schedule(UUID.randomUUID(), entry); } catch (InterruptedException e) { e.printStackTrace(); } return; } State currentState = event.getCurrentState(); State nextState = StatesMachine.getNextState(currentState); if (event.getRetryingCount() > 3) { // throw out and dump into places for future investigation } else { Processing processing = StatesMachine.getProcessing(nextState); if(processing != null) { StandalonePusher<UserProcessingEvent, UserProcessingEventQueue> pusher = EventSystem.getPusher(EventType.USER_PROCESSING); if(processing.processing(event)) { //Successfully } else { //Failed will retry at least 3 times } try { pusher.push(event); } catch (EventProcessingException e) { //Add logic future consoleLogger.logError("Cannot push into the queue " + EventType.USER_PROCESSING, e); } } else if (processing == null && currentState == State.END) { //Reach the final tasks we can finished the round of processing. } else if (processing == null) { //May caused by one step didn't have configuration, wired situation. } } }
9
public void runMixer(int motor, int time) { if (!isConnected()) { error("Robot is not connected!", "RXTXRobot", "runMixer"); return; } if (!getOverrideValidation() && (motor < RXTXRobot.MOTOR1 || motor > RXTXRobot.MOTOR4)) { error("You must supply a valid motor port: RXTXRobot.MOTOR1, MOTOR2, MOTOR3, or MOTOR4.", "RXTXRobot", "runMixer"); return; } if (!getOverrideValidation() && time < 0) { error("You must supply a positive time.", "RXTXRobot", "runMixer"); return; } debug("Running mixer on port " + motor + " at speed " + getMixerSpeed() + " for time of " + time); if (!"".equals(sendRaw("d " + motor + " " + getMixerSpeed() + " " + time))) sleep(time); }
7
private boolean checkCondition(CommandSender s, String[] a, String command, String type) { if(!hasPermission(s, command)) { s.sendMessage("You have no Permission for this Command."); return false; } if(a.length < 4) { s.sendMessage(ChatColor.RED + _modText.getAdminAdd("args", PlayerCache.getLang(s.getName())).addVariables("", s.getName(), "")); return false; } if(!PlayerCache.playerExists(a[1])) { s.sendMessage(ChatColor.RED + _modText.getExperience("noPlayerExist", getPlayerLanguage(s)).addVariables("", s.getName(), "")); return false; } String jobName = McJobs.getPlugin().getLanguage().getJobNameByLangName(a[2], getPlayerLanguage(s)); if(!PlayerJobs.getJobsList().containsKey(jobName)) { s.sendMessage(ChatColor.RED + _modText.getAdminCommand("exist", getPlayerLanguage(s)).addVariables(_modText.getJobNameInLang(jobName, getPlayerLanguage(s)), s.getName(), s.getName())); } if(!PlayerCache.hasJob(a[1], jobName)) { s.sendMessage(ChatColor.RED + _modText.getExperience("nojob", getPlayerLanguage(s)).addVariables(_modText.getJobNameInLang(jobName, getPlayerLanguage(s)), s.getName(), "")); return false; } if(!StringToNumber.isNumeric(a[3])) { s.sendMessage(ChatColor.RED + _modText.getExperience("need" + type, getPlayerLanguage(s)).addVariables(_modText.getJobNameInLang(jobName, getPlayerLanguage(s)), s.getName(), "")); return false; } if(Integer.parseInt(a[3]) < 1) { s.sendMessage(ChatColor.RED + _modText.getExperience("need" + type, getPlayerLanguage(s)).addVariables(_modText.getJobNameInLang(jobName, getPlayerLanguage(s)), s.getName(), "")); return false; } return true; }
7
public synchronized static ChatSocketServer getServerSingleton() { if (instance == null) { instance = new ChatSocketServer(); } return instance; }
1
private void btnRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrarActionPerformed //Asigna lo que hay en las cajas de texto a los String, int, double //Guarda lo que hay en los atributos en un vector String archivo = txtNArchivo.getText(); String nombre = txtNombre.getText(); String materia = txtMateria.getText(); String datos[] = new String[4]; datos[0]=nombre; datos[2]=materia; if(!"".equals(nombre)) if(!"".equals(materia)) if(!"".equals(archivo)) try{ int codigo = Integer.parseInt(txtCodigo.getText()); datos[1]=String.valueOf(codigo); try{ double nota = Double.parseDouble(txtNota.getText()); datos[3]=String.valueOf(nota); if(nota>=0){ if(codigo>0){ tabla.addRow(datos); //Se crean 2 objetos RegistroAlumno rA = new RegistroAlumno(); General g = new General(); try { //Se utiliza el objeto de l clase RegistroAlumno y su metodo registroAlArchivo rA.registroAlArchivo(g, archivo, nombre, codigo, materia, nota); JOptionPane.showMessageDialog(null, "Se a guardado los datos en el archivo"); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Error"); } //Vacia todas las cajas de taxto txtNArchivo.setText(""); txtNombre.setText(""); txtCodigo.setText(""); txtMateria.setText(""); txtNota.setText(""); } else{ JOptionPane.showMessageDialog(null, "El codigo Ingresado" + " es menor que cero"); } } else{ JOptionPane.showMessageDialog(null, "La nota ingresada es" + " menor que cero"); } } catch(NumberFormatException e){ JOptionPane.showMessageDialog(null, "Debe ingresar numeros" + " en la nota"); } } catch(NumberFormatException e){ JOptionPane.showMessageDialog(null, "Debe ingresar numeros" + " en el codigo"); } else{ JOptionPane.showMessageDialog(null, "El campo del nombre " + "del archivo esta vacio"); } else{ JOptionPane.showMessageDialog(null, "El campo de la materia " + "esta vacio"); } else{ JOptionPane.showMessageDialog(null, "El campo de la nombre de la " + "persona esta vacio"); } }//GEN-LAST:event_btnRegistrarActionPerformed
8
public static String tickets(int[] peopleInLine) { int count50 = 0; int count25 = 0; for (int current : peopleInLine){ if (current == 25){ count25++; } if (current == 50){ count25--; if (count25 < 0){ return "NO"; } count50++; } if (current == 100){ if (count50 > 0){ count50--; count25--; } else { count25 -= 3; } if (count25 < 0){ return "NO"; } } } return "YES"; }
7
public static String readContent(String filePath) throws Exception { File file = new File(filePath); if (file.exists()) { StringBuffer sb = new StringBuffer(); InputStream in = new FileInputStream(file); InputStreamReader inReader = new InputStreamReader(in,"UTF-8"); BufferedReader beReader = new BufferedReader(inReader); String line = null; while ((line = beReader.readLine()) != null) { sb.append(line); } beReader.close(); inReader.close(); in.close(); return sb.toString(); } else { throw new IOException("读取文件出错:目标文件不存在,路径:" + file.getAbsolutePath()); } }
2
public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof OrderdetailPK)) { return false; } OrderdetailPK castOther = (OrderdetailPK)other; return (this.orderNumber == castOther.orderNumber) && this.productCode.equals(castOther.productCode); }
3
public static String reverseWords(String input) { //first reverse the string char[] buff = input.toCharArray(); int left = 0; int right = buff.length-1; while(left<right) { char temp = buff[right]; buff[right] = buff[left]; buff[left] = temp; right--; left++; } //now traverse a word and reverse it left =0; while(true) { right = left; //move right to the space for(;right<input.length() && buff[right]!=' '; right ++) { continue; } //save the space as pivot int pivot = right; //adjust the right to a character before space right = right-1; //reverse the string from left to right while(left<right){ char temp = buff[right]; buff[right] = buff[left]; buff[left] = temp; right--; left++; } //check if pivot has reached or exceeded the string length if(pivot>=input.length()-1){ break; } else { // take the left index to the next letter for(left=pivot; left<input.length() && buff[left] == ' '; left++){ continue; } } } return String.valueOf(buff); }
8
@Override public String request() { if(subject == null) { System.out.println("Subject inactive"); subject = new Subject(); } System.out.println("Subject active"); return "Proxy: Call to " + subject.request(); }
1
public void addOkMessage(String message) { Document docs = textArea.getDocument(); SimpleAttributeSet attrSet = new SimpleAttributeSet(); StyleConstants.setForeground(attrSet, Color.BLACK); try { docs.insertString(docs.getLength(), "\r\n" + lineNumber++ + ": " + message, attrSet); } catch (BadLocationException e) { e.printStackTrace(); } textArea.setCaretPosition(docs.getLength()); }
1
public static boolean input(String question) { System.out.println(question); Scanner sc = new Scanner(System.in); String text = sc.nextLine(); try { return Boolean.parseBoolean(text); } catch (NumberFormatException e) { System.err.println("Enter a valid boolean"); return input(question); } }
1
protected void centerOnClientArea() { Rectangle clientArea = shell.getDisplay().getPrimaryMonitor().getClientArea(); Point shellSize = shell.getSize(); int xPos = clientArea.x + (clientArea.width - shellSize.x) / 2; int yPos = clientArea.y + (clientArea.height - shellSize.y) / 2; if (xPos >= 0 && yPos >= 0) { shell.setLocation(xPos, yPos); } else { shell.setLocation(0, 0); } }
2
public Set getSymbolsWithReplacements() { return symbolToReplacements.keySet(); }
0
public String retrieveNetworkPool(String adminLink) throws Exception{ String response = doGet(adminLink + "extension/"); String networkPools = findElement(response, Constants.VCLOUD_LINK, Constants.NETWORK_POOLS, null); response = doGet(networkPools); String element = findElement(response, Constants.NET_POOL, Constants.NETWORK_POOLS_REF, null); if( element == null){ throw new Exception(" "); } return element; }
1
private synchronized void processEvent(Sim_event ev) { double currentTime = GridSim.clock(); boolean success = false; if(ev.get_src() == myId_) { if (ev.get_tag() == UPT_SCHEDULE) { if(currentTime > lastSchedUpt) { // updates the schedule, finishes jobs, reservations, etc. updateSchedule(); lastSchedUpt = currentTime; } success = true; } } if(!success) { processOtherEvent(ev); } }
4
@Override protected void drawChildren(boolean selection) { super.drawChildren(selection); if(!selection && this.isActive() && dc > 0 && this.cursorInside()) this.cursor.draw(); dc-= Settings.get(SetKeys.R_MAX_FPS, Integer.class)/60 * 2; if(dc < -Settings.get(SetKeys.R_MAX_FPS, Integer.class)) dc = Settings.get(SetKeys.R_MAX_FPS, Integer.class); }
5
public boolean isSyncCurrentPosition(int syncmode) throws BitstreamException { int read = readBytes(syncbuf, 0, 4); int headerstring = ((syncbuf[0] << 24) & 0xFF000000) | ((syncbuf[1] << 16) & 0x00FF0000) | ((syncbuf[2] << 8) & 0x0000FF00) | ((syncbuf[3] << 0) & 0x000000FF); try { source.unread(syncbuf, 0, read); } catch (IOException ex) { } boolean sync = false; switch (read) { case 0: sync = true; break; case 4: sync = isSyncMark(headerstring, syncmode, syncword); break; } return sync; }
3
@Override public void addNode(String path, byte[] data) { if ((nodes.get(path) != null) && nodes.get(path).exists()) { throw new IllegalStateException("Node '" + path + "' already exists"); } if ((nodes.get(getParent(path)) == null) || !nodes.get(getParent(path)).exists()) { throw new IllegalArgumentException("Node '" + path + "' can't be created. Its parent node doesn't exist"); } try { zk.create(path, data, org.apache.zookeeper.ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
6
static protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
9
private AbstractMob findBestTarget(ArrayList<AbstractMob> list){ AbstractMob best = null; for (int i = 0; i < list.size(); i++){ if (!(list.get(i) instanceof Zombie)){ best = list.get(i); break; } } return best; }
2
static int getIndex(int year,int month ,int day){ Calendar calendar=new GregorianCalendar(TimeZone.getTimeZone("GMT")); calendar.set(Calendar.YEAR,year); calendar.set(Calendar.MONTH,month-1); calendar.set(Calendar.DATE,day); calendar.set(Calendar.HOUR_OF_DAY,0); calendar.set(Calendar.MINUTE,0); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MILLISECOND,0); return (int)((calendar.getTime().getTime()-startDay.getTime())/milliSecondsOnyDay); }
0
public static void createTables() throws SQLException { String query; Connection con = getConnection(); PreparedStatement statement = null; if (tableExists(Config.sqlPrefix + "Lifestones") == false) { System.out.println("Creating Lifestones.Lifestones table."); query = "CREATE TABLE `" + Config.sqlPrefix + "Lifestones` (`id` INT PRIMARY KEY AUTO_INCREMENT, `world` VARCHAR(32) NOT NULL, `x` INT NOT NULL, `y` INT NOT NULL, `z` INT NOT NULL) ENGINE = InnoDB"; statement = con.prepareStatement(query); statement.executeUpdate(); } if (tableExists(Config.sqlPrefix + "Attunements") == true) {// old // table; System.out.println("Removing unique attribute from player in Attunements."); con.prepareStatement("ALTER TABLE " + Config.sqlPrefix + "Attunements DROP INDEX player").executeUpdate(); // con.prepareStatement("ALTER TABLE "+Config.sqlPrefix + // "Attunements add unique index(player, world);").executeUpdate(); con.prepareStatement("RENAME TABLE `" + Config.sqlPrefix + "Attunements` TO `" + Config.sqlPrefix + "Attunements_v2`").executeUpdate(); } else if (tableExists(Config.sqlPrefix + "Attunements_v2") == false) { System.out.println("Creating Lifestones.Attunements table."); query = "CREATE TABLE `" + Config.sqlPrefix + "Attunements_v2` (`id` INT PRIMARY KEY AUTO_INCREMENT, `player` VARCHAR(32) NOT NULL, `world` VARCHAR(32) NOT NULL, `x` DOUBLE NOT NULL, `y` DOUBLE NOT NULL, `z` DOUBLE NOT NULL, `yaw` FLOAT NOT NULL, `pitch` FLOAT NOT NULL) ENGINE = InnoDB"; statement = con.prepareStatement(query); statement.executeUpdate(); } // statement.close(); con.close(); }
3
private Location getLocationFromString(String s) { switch(s) { case "trein": return this._trainPlatform; case "vrachtauto": return this._truckPlatform; case "binnenschip": return this._riverBoatPlatform; case "zeeschip": return this._seaShipPlatform; default: return null; } }
4
public static int blueTicket( int a, int b, int c ) { int ab = a + b; int bc = b + c; int ac = a + c; if ( ab == 10 || bc == 10 || ac == 10 ) { return 10; } if ( ab - bc == 10 || ab - ac == 10 ) { return 5; } return 0; }
5
public static final BasicGraphEditor getEditor(ActionEvent e) { if (e.getSource() instanceof Component) { Component component = (Component) e.getSource(); while (component != null && !(component instanceof BasicGraphEditor)) { component = component.getParent(); } return (BasicGraphEditor) component; } return null; }
3
public void onFruitCatched(Fruit.Type fruitType){ // if (Log.VERBOSE) Log.v(LOG_TAG, "catched " + fruitType); System.out.println(LOG_TAG + " Catched: " + fruitType); Ingredient<Fruit.Type> fruit = currentProgress.getIngredient(fruitType); actionOcurred(GameActionFactory.createFruitCatchedAction(fruitType, fruit != null)); if (fruit != null) { score.upgradeScore(fruitType.getScore()); if (progressListener != null) progressListener.onChangedFruitIngredient(fruit); long currentTime = System.currentTimeMillis(); if (timeTrackIncrease != 0 && (currentTime - timeTrackIncrease < INCREASE_MODIFIER_TIME)) { score.increaseModifier(); } timeTrackIncrease = currentTime; } else { score.resetModifier(); } }
4
@Test public void testInfest() { try { // Clear the mosaic re.clear(); // Set the parameters of the mosaic using a raster template re.setPresenceMap("./resource files/Age.txt",species); // Set the environment such that no cells are infested re.setPresenceMap("NONE",species); re.setHabitatMap("ALL", species); // Generate a List of propagules - note, these are coordinates, NOT // indices i.e. y is flipped. List<Coordinate> test_propagules = new ArrayList<Coordinate>(); test_propagules.add(new Coordinate(0.5, 9.5)); test_propagules.add(new Coordinate(1.5, 8.5)); test_propagules.add(new Coordinate(2, 7.5)); test_propagules.add(new Coordinate(4.5, 6)); test_propagules.add(new Coordinate(7, 3)); // Ensure cells are not infested assertFalse(re.getPatches().get(0).isInfestedBy(species)); assertFalse(re.getPatches().get(20).isInfestedBy(species)); assertFalse(re.getPatches().get(42).isInfestedBy(species)); assertFalse(re.getPatches().get(64).isInfestedBy(species)); assertFalse(re.getPatches().get(127).isInfestedBy(species)); // Run the infestation re.infest(species, test_propagules); // Ensure cells are now infested assertTrue(re.getPatches().get(0).isInfestedBy(species)); assertTrue(re.getPatches().get(21).isInfestedBy(species)); assertTrue(re.getPatches().get(42).isInfestedBy(species)); assertTrue(re.getPatches().get(64).isInfestedBy(species)); assertTrue(re.getPatches().get(127).isInfestedBy(species)); // Ensure no other cells are infested for (int i = 0; i < 10; i++) { for (int j = 0; j < 20; j++) { int key = i * 20 + j; if (key == 0 || key == 21 || key == 42 || key == 64 || key == 127 || re.getPatches().get(key).hasNoData()) { continue; } assertFalse(re.getPatches().get(key).isInfestedBy(species)); } } } catch (IOException e) { e.printStackTrace(); } }
9
@Override public void actionPerformed(ActionEvent e) { JButton clicked = (JButton) e.getSource(); { if(clicked == buttons[0]) { if(owner != null) { owner.switchState(Game.EnumState.GAME_STATE); } } else if(clicked == buttons[1]) { JOptionPane.showMessageDialog(this, "Help Info will be here at a later date"); } else if(clicked == buttons[2]) { JOptionPane.showMessageDialog(this, "Options will be here at a later date"); } else if(clicked == buttons[3]) { System.exit(0); } } }
5
public void setDescription(String description) { this.description = description; }
0
public static void main(String[] args) { BaseballGame game1 = new BaseballGame("Static Brawlers", "Instantiated Kickers"); BaseballGame game2 = new BaseballGame("Blue Cats", "Red Cats"); System.out.println(game1.getTeams()); System.out.println(game2.getTeams()); System.out.println(BaseballGame.getTotalGamesPlayed()); }
0
protected void func_27255_a(int par1, int par2) { this.field_27268_b = -1; if (par1 >= 79 && par1 < 115) { this.field_27268_b = 0; } else if (par1 >= 129 && par1 < 165) { this.field_27268_b = 1; } else if (par1 >= 179 && par1 < 215) { this.field_27268_b = 2; } if (this.field_27268_b >= 0) { this.func_27266_c(this.field_27268_b); GuiStats.getMinecraft2(this.field_27269_g).sndManager.playSoundFX("random.click", 1.0F, 1.0F); } }
7
public Vector solve(Matrix A, Vector b, Vector x) throws IterativeSolverNotConvergedException { checkSizes(A, b, x); double rho = 0, rho_1 = 0, xi = 0, gamma = 1., gamma_1 = 0, theta = 0, theta_1 = 0, eta = -1., delta = 0, ep = 0, beta = 0; A.multAdd(-1, x, r.set(b)); v_tld.set(r); M1.apply(v_tld, y); rho = y.norm(Norm.Two); w_tld.set(r); M2.transApply(w_tld, z); xi = z.norm(Norm.Two); for (iter.setFirst(); !iter.converged(r, x); iter.next()) { if (rho == 0) throw new IterativeSolverNotConvergedException( NotConvergedException.Reason.Breakdown, "rho", iter); if (xi == 0) throw new IterativeSolverNotConvergedException( NotConvergedException.Reason.Breakdown, "xi", iter); v.set(1 / rho, v_tld); y.scale(1 / rho); w.set(1 / xi, w_tld); z.scale(1 / xi); delta = z.dot(y); if (delta == 0) throw new IterativeSolverNotConvergedException( NotConvergedException.Reason.Breakdown, "delta", iter); M2.apply(y, y_tld); M1.transApply(z, z_tld); if (iter.isFirst()) { p.set(y_tld); q.set(z_tld); } else { p.scale(-xi * delta / ep).add(y_tld); q.scale(-rho * delta / ep).add(z_tld); } A.mult(p, p_tld); ep = q.dot(p_tld); if (ep == 0) throw new IterativeSolverNotConvergedException( NotConvergedException.Reason.Breakdown, "ep", iter); beta = ep / delta; if (beta == 0) throw new IterativeSolverNotConvergedException( NotConvergedException.Reason.Breakdown, "beta", iter); v_tld.set(-beta, v).add(p_tld); M1.apply(v_tld, y); rho_1 = rho; rho = y.norm(Norm.Two); A.transMultAdd(q, w_tld.set(-beta, w)); M2.transApply(w_tld, z); xi = z.norm(Norm.Two); gamma_1 = gamma; theta_1 = theta; theta = rho / (gamma_1 * beta); gamma = 1 / Math.sqrt(1 + theta * theta); if (gamma == 0) throw new IterativeSolverNotConvergedException( NotConvergedException.Reason.Breakdown, "gamma", iter); eta = -eta * rho_1 * gamma * gamma / (beta * gamma_1 * gamma_1); if (iter.isFirst()) { d.set(eta, p); s.set(eta, p_tld); } else { double val = theta_1 * theta_1 * gamma * gamma; d.scale(val).add(eta, p); s.scale(val).add(eta, p_tld); } x.add(d); r.add(-1, s); } return x; }
9
protected Node<T> getLeast(Node<T> startingNode) { if (startingNode == null) return null; Node<T> lesser = startingNode.lesser; while (lesser != null && lesser.id != null) { Node<T> node = lesser.lesser; if (node != null && node.id != null) lesser = node; else break; } return lesser; }
5
public byte[] getCursorMoveSequence(int direction, int times) { byte[] sequence = null; if (times == 1) { sequence = new byte[3]; } else { sequence = new byte[times * 3]; } for (int g = 0; g < times * 3; g++) { sequence[g] = ESC; sequence[g + 1] = LSB; switch (direction) { case TerminalIO.UP: sequence[g + 2] = A; break; case TerminalIO.DOWN: sequence[g + 2] = B; break; case TerminalIO.RIGHT: sequence[g + 2] = C; break; case TerminalIO.LEFT: sequence[g + 2] = D; break; default: break; } g = g + 2; } return sequence; }// getCursorMoveSequence
6
public void visit_d2f(final Instruction inst) { stackHeight -= 2; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } stackHeight += 1; }
1
public void searchMultiTripFlightsPartOne() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Where is your MySQL JDBC Driver?"); e.printStackTrace(); } PreparedStatement ps = null; Connection con = null; ResultSet rs; try { con = DriverManager.getConnection("jdbc:mysql://mysql2.cs.stonybrook.edu:3306/mlavina", "mlavina", "108262940"); if (con != null) { con.setAutoCommit(false); String sql = "Create OR Replace view SearchResults(Name, FlightNo, DepTime, ArrTime, DepAirportID, ArrAirportID, LegNo, Class, fare, AirlineID)\n" + "as\n" + "SELECT DISTINCT R.Name, L.FlightNo, L.DepTime, L.ArrTime, L.DepAirportId, L.ArrAirportId, L.LegNo, M.Class, M.Fare, L.AirlineID\n" + "FROM Flight F, Leg L, Airport A , Fare M, Airline R\n" + "WHERE F.AirlineID = L.AirlineID AND F.FlightNo = L.FlightNo \n" + " AND (L.DepAirportId = ? OR L.ArrAirportId = ?) AND M.AirlineID = L.AirlineID \n" + "AND M.FlightNo = L.FlightNo AND R.Id = L.AirlineID AND M.FareType = 'Regular' \n" + "AND L.DepTime > ? AND L.DepTime < ? "; ps = con.prepareStatement(sql); ps.setString(1, flightFrom); ps.setString(2, flightMiddle); ps.setDate(3, new java.sql.Date(departing.getTime())); ps.setDate(4, new java.sql.Date(departing.getTime() + +(1000 * 60 * 60 * 24))); try { ps.execute(); sql = "select Distinct A.Name, A.FlightNo, A.DepTime, B.ArrTime ,A.class, A.fare, A.DepAirportID, A.LegNo, A.AirlineID, B.ArrAirportID\n" + "From searchresults A, searchresults B\n" + "Where ((A.ArrAirportID = B.DepAirportID) OR (A.DepAirportID = ? AND B.ArrAirportID = ?))"; ps = con.prepareStatement(sql); ps.setString(1, flightFrom); ps.setString(2, flightMiddle); ps.execute(); rs = ps.getResultSet(); flightResults.removeAll(flightResults); int i = 0; while (rs.next()) { //flightResults.add() flightResults.add(new Flight(rs.getString("AirlineID"), rs.getString("Name"), rs.getInt("FlightNo"), rs.getTimestamp("DepTime"), rs.getTimestamp("ArrTime"), rs.getString("Class"), rs.getDouble("fare"), rs.getString("DepAirportID"), rs.getString("ArrAirportID"), i, rs.getInt("LegNo"))); i++; } con.commit(); } catch (Exception e) { con.rollback(); } } } catch (Exception e) { System.out.println(e); } finally { try { con.setAutoCommit(true); con.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } }
6
public void resurectHero() { if (player.getDeadHeroes().size() == 0) { QMessageBox.warning(this, "Nie można wskrzesić bohatera", "Nie posiadasz martwego bohatera którego można wskrzesić"); } else if (castle.getHero() != null) { QMessageBox.warning(this, "Nie można wskrzesić bohatera", "W tym zamku znajduje się już inny bohater"); } else { Map<String, core.Hero> list = new HashMap<String, core.Hero>(); for (core.Hero hero: player.getDeadHeroes()) { int cost = 500+hero.getLevel()*500; list.put(hero.getName()+" (poziom "+hero.getLevel()+") za "+cost+" złota", hero); } String select = QInputDialog.getItem(this, "Wskrześ bohatera", "Wybierz bohatera którego chcesz wskrzesić", new ArrayList(list.keySet()), 0, false); if (select != null) { core.Hero hero = list.get(select); int cost = 500+hero.getLevel()*500; System.out.println(hero.getName()); if (player.getResource(core.ResourceType.GOLD) < cost) { QMessageBox.warning(this, "Nie można wynająć bohatera", "Nie posiadasz wystarczającej ilości złota"); } else { player.resurectHero(hero); addNewHero(hero); player.addResource(core.ResourceType.GOLD, -cost); updateResources(); } } } }
5
@Override public void run() { while (running) { synchronized (lock) { if (cacheIndex < 500) { mouseXCache[cacheIndex] = client.mouseX; mouseYCache[cacheIndex] = client.mouseY; cacheIndex++; } } try { Thread.sleep(50L); } catch (Exception exception) { } } }
3
public void setWidth(double value) { if (value <= 0) { throw new IllegalArgumentException( "Illegal width, must be positive"); } else { width = value; weight = calculateTotalWeight(); } }
1
public void newIssueFired(ActionEvent event) { final String selectedProject = getSelectedProject(); if (model != null && selectedProject != null) { ObservableIssue issue = model.createIssueFor(selectedProject); if (table != null) { // Select the newly created issue. table.getSelectionModel().clearSelection(); table.getSelectionModel().select(issue); } } }
3
private void animateBar(){ for( ActionListener aL : animationTimer.getActionListeners()){ animationTimer.removeActionListener(aL); } animationTimer.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ if(nextValue > currentValue){ currentValue+=1; currentWidth = (int)((double)width * ((double)currentValue/(double)max)); if(currentValue >= nextValue){ animationTimer.stop(); nextValue = currentValue; } }else{ currentValue-=1; currentWidth = (int)((double)width * ((double)currentValue/(double)max)); if(currentValue <= nextValue){ animationTimer.stop(); nextValue = currentValue; } } repaint(); } }); animationTimer.start(); }
4
public boolean predict(FeatureVector featureVector, SingleDecision decision) throws MaltChainedException { if (model == null) { try { model = Linear.loadModel(new BufferedReader(getInstanceInputStreamReaderFromConfigFile(".mod"))); } catch (IOException e) { throw new LiblinearException("The model cannot be loaded. ", e); } } if (model == null) { throw new LiblinearException("The Liblinear learner cannot predict the next class, because the learning model cannot be found. "); } else if (featureVector == null) { throw new LiblinearException("The Liblinear learner cannot predict the next class, because the feature vector cannot be found. "); } if (featurePruning) { return predictWithFeaturePruning(featureVector, decision); } // if (cardinalities == null) { // if (getConfigFileEntry(".car") != null) { // cardinalities = loadCardinalities(getInstanceInputStreamReaderFromConfigFile(".car")); // } else { // cardinalities = getCardinalities(featureVector); // } // } //System.out.println("METHOD PREDICT CARDINALITIES SIZE" + cardinalities.length + " FEATURE VECTOR SIZE " +featureVector.size()); if (xlist == null) { xlist = new ArrayList<FeatureNode>(featureVector.size()); } // int offset = 1; // int i = 0; // for (FeatureFunction feature : featureVector) { // final FeatureValue featureValue = feature.getFeatureValue(); // if (!(excludeNullValues == true && featureValue.isNullValue())) { // if (featureValue instanceof SingleFeatureValue) { // if (((SingleFeatureValue)featureValue).getCode() < cardinalities[i]) { // xlist.add(new FeatureNode(((SingleFeatureValue)featureValue).getCode() + offset, 1)); // } // } else if (featureValue instanceof MultipleFeatureValue) { // for (Integer value : ((MultipleFeatureValue)featureValue).getCodes()) { // if (value < cardinalities[i]) { // xlist.add(new FeatureNode(value + offset, 1)); // } // } // } // } // offset += cardinalities[i]; // i++; // } FeatureNode[] xarray = new FeatureNode[xlist.size()]; for (int k = 0; k < xlist.size(); k++) { xarray[k] = xlist.get(k); } if (decision.getKBestList().getK() == 1) { decision.getKBestList().add((int) Linear.predict(model, xarray)); } else { liblinear_predict_with_kbestlist(model, xarray, decision.getKBestList()); } xlist.clear(); return true; }
8
public static Cons visibleModules(Module from) { if (from == null) { from = ((Module)(Stella.$MODULE$.get())); } { MemoizationTable memoTable000 = null; Cons memoizedEntry000 = null; Stella_Object memoizedValue000 = null; if (Stella.$MEMOIZATION_ENABLEDp$) { memoTable000 = ((MemoizationTable)(Stella.SGT_STELLA_F_VISIBLE_MODULES_MEMO_TABLE_000.surrogateValue)); if (memoTable000 == null) { Surrogate.initializeMemoizationTable(Stella.SGT_STELLA_F_VISIBLE_MODULES_MEMO_TABLE_000, "(:MAX-VALUES 50 :TIMESTAMPS (:MODULE-UPDATE))"); memoTable000 = ((MemoizationTable)(Stella.SGT_STELLA_F_VISIBLE_MODULES_MEMO_TABLE_000.surrogateValue)); } memoizedEntry000 = MruMemoizationTable.lookupMruMemoizedValue(((MruMemoizationTable)(memoTable000)), from, Stella.MEMOIZED_NULL_VALUE, null, null, -1); memoizedValue000 = memoizedEntry000.value; } if (memoizedValue000 != null) { if (memoizedValue000 == Stella.MEMOIZED_NULL_VALUE) { memoizedValue000 = null; } } else { memoizedValue000 = Module.helpMemoizeVisibleModules(from); if (Stella.$MEMOIZATION_ENABLEDp$) { memoizedEntry000.value = ((memoizedValue000 == null) ? Stella.MEMOIZED_NULL_VALUE : memoizedValue000); } } { Cons value000 = ((Cons)(memoizedValue000)); return (value000); } } }
7
public boolean isDefending() { return this.isDefendingNow; }
0
private static Set difFiles(String[] files1, String[] files2) { Set set1 = new HashSet(); Set set2 = new HashSet(); Set extra = new HashSet(); for (int x=0; x < files1.length; x++) { set1.add(files1[x]); } for (int x=0; x < files2.length; x++) { set2.add(files2[x]); } Iterator i1 = set1.iterator(); while (i1.hasNext()) { Object o = i1.next(); if (!set2.contains(o)) { extra.add(o); } } Iterator i2 = set2.iterator(); while (i2.hasNext()) { Object o = i2.next(); if (!set1.contains(o)) { extra.add(o); } } return extra; }
6
public boolean padding() { if (h_padding_bit == 0) return false; else return true; }
1
public EventComment findEventCommentById(final Long id) { return new EventComment(); }
0
@Override public void caseAIntArrHexp(AIntArrHexp node) { inAIntArrHexp(node); if(node.getRSq() != null) { node.getRSq().apply(this); } if(node.getExp() != null) { node.getExp().apply(this); } if(node.getLSq() != null) { node.getLSq().apply(this); } if(node.getInt() != null) { node.getInt().apply(this); } if(node.getNew() != null) { node.getNew().apply(this); } outAIntArrHexp(node); }
5
public static String eBookingCarrier2SoushippingCarrier(String eBookingCarrier){ String retSoushippingCarrier=null; if(eBookingCarrier.equals("MAERSK")) { retSoushippingCarrier = "MSK"; }else if (eBookingCarrier.equals("EMI")) { retSoushippingCarrier = "EMIRATES"; }else if (eBookingCarrier.equals("EMC")) { retSoushippingCarrier = "EVERGREEN"; }else if (eBookingCarrier.equals("HAM-SUD")) { retSoushippingCarrier = "HAMBURG SüD"; }else if (eBookingCarrier.equals("HPL")) { retSoushippingCarrier = "HAPAG-LLOYD"; }else if (eBookingCarrier.equals("KLINE")) { retSoushippingCarrier = "K.LINE"; }else if (eBookingCarrier.equals("NCL")) { retSoushippingCarrier = "NORASIA"; }else if (eBookingCarrier.equals("WHL")) { retSoushippingCarrier = "WANHAI"; }else if (eBookingCarrier.equals("YML")) { retSoushippingCarrier = "YANGMING"; }else { retSoushippingCarrier = eBookingCarrier; } return retSoushippingCarrier; }
9
@SuppressWarnings("unchecked") protected void calcRows(List results) { if (results.size() == 0){ setTruthValue(Boolean.FALSE); return; } if (results.size() == 1) { Object val = results.get(0); if ((val instanceof CycSymbol) && (((CycSymbol)val).toString().equalsIgnoreCase("nil"))) { setTruthValue(Boolean.TRUE); return; } } for (List<CycList> bindingSet : (List<List>)results) { List<Object> row = addEmptyRow(); for (CycList binding : bindingSet) { CycVariable colVar = (CycVariable)binding.get(0); int colIndex = possiblyAddColVar(colVar); String col = colVar.toString(); Object val = binding.rest(); row.set(colIndex, val); } } }
6
public boolean foundAllTypes() { for (int i = 0; i < types.length; i++) if (types[i] == null) return false; return true; }
2
public void stop() { thread = null; }
0
public static void displayURL(String url) { boolean windows = isWindowsPlatform(); String cmd = null; try { if (windows) { // cmd = 'rundll32 url.dll,FileProtocolHandler http://...' cmd = WIN_PATH + " " + WIN_FLAG + " " + url; Process p = Runtime.getRuntime().exec(cmd); } else { // Under Unix, Netscape has to be running for the "-remote" // command to work. So, we try sending the command and // check for an exit value. If the exit command is 0, // it worked, otherwise we need to start the browser. // cmd = 'netscape -remote openURL(http://www.javaworld.com)' cmd = UNIX_PATH + " " + UNIX_FLAG + "(" + url + ")"; Process p = Runtime.getRuntime().exec(cmd); try { // wait for exit code -- if it's 0, command worked, // otherwise we need to start the browser up. int exitCode = p.waitFor(); if (exitCode != 0) { // Command failed, start up the browser // cmd = 'netscape http://www.javaworld.com' cmd = UNIX_PATH + " " + url; p = Runtime.getRuntime().exec(cmd); } } catch(InterruptedException x) { System.err.println("Error bringing up browser, cmd='" + cmd + "'"); System.err.println("Caught: " + x); } } } catch(IOException x) { // couldn't exec browser System.err.println("Could not invoke browser, command=" + cmd); System.err.println("Caught: " + x); } }
4
private boolean isNeedsEscape(String character) { if (character.matches("\\(")) { return true; } else if (character.matches("\\)")) { return true; } else if (character.matches("\\$")) { return true; } else if (character.matches("\\^")) { return true; } else if (character.matches("\\!")) { return true; } else { return false; } }
5
public static void notify(String title, String message) { _shell = new Shell(Display.getDefault(), SWT.ON_TOP | SWT.NO_TRIM); _shell.setLayout(new FillLayout()); _shell.setForeground(_fgColor); _shell.setBackgroundMode(SWT.INHERIT_DEFAULT); _shell.addListener(SWT.Dispose, new Listener() { @Override public void handleEvent(Event event) { _activeShells.remove(_shell); } }); final Composite inner = new Composite(_shell, SWT.NONE); GridLayout gl = new GridLayout(2, false); gl.marginLeft = 5; gl.marginTop = 0; gl.marginRight = 5; gl.marginBottom = 5; inner.setLayout(gl); _shell.addListener(SWT.Resize, new Listener() { @Override public void handleEvent(Event e) { try { // get the size of the drawing area Rectangle rect = _shell.getClientArea(); // create a new image with that size Image newImage = new Image(Display.getDefault(), Math.max(1, rect.width), rect.height); // create a GC object we can use to draw with GC gc = new GC(newImage); // fill background gc.setForeground(_bgFgGradient); gc.setBackground(_bgBgGradient); gc.fillGradientRectangle(rect.x, rect.y, rect.width, rect.height, true); // draw shell edge gc.setLineWidth(2); gc.setForeground(_borderColor); gc.drawRectangle(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2); // remember to dipose the GC object! gc.dispose(); // now set the background image on the shell _shell.setBackgroundImage(newImage); // remember/dispose old used iamge if (_oldImage != null) { _oldImage.dispose(); } _oldImage = newImage; } catch (Exception err) { err.printStackTrace(); } } }); GC gc = new GC(_shell); String lines[] = message.split("\n"); Point longest = null; int typicalHeight = gc.stringExtent("X").y; for (String line : lines) { Point extent = gc.stringExtent(line); if (longest == null) { longest = extent; continue; } if (extent.x > longest.x) { longest = extent; } } gc.dispose(); int minHeight = typicalHeight * lines.length; CLabel imgLabel = new CLabel(inner, SWT.NONE); imgLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_BEGINNING)); CLabel titleLabel = new CLabel(inner, SWT.NONE); titleLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_CENTER)); titleLabel.setText(title); titleLabel.setForeground(_titleFgColor); Font f = titleLabel.getFont(); FontData fd = f.getFontData()[0]; fd.setStyle(SWT.BOLD); fd.height = 11; titleLabel.setFont(FontCache.getFont(fd)); Label text = new Label(inner, SWT.WRAP); Font tf = text.getFont(); FontData tfd = tf.getFontData()[0]; tfd.setStyle(SWT.BOLD); tfd.height = 8; text.setFont(FontCache.getFont(tfd)); GridData gd = new GridData(GridData.FILL_BOTH); gd.horizontalSpan = 2; text.setLayoutData(gd); text.setForeground(_fgColor); text.setText(message); minHeight = 50; int minWidth = 350; _shell.setSize(minWidth, minHeight); Rectangle clientArea = Display.getDefault().getClientArea(); int startX = clientArea.x + clientArea.width - minWidth - 2; int startY = clientArea.y + clientArea.height - minHeight - 2; // move other shells up if (!_activeShells.isEmpty()) { List<Shell> modifiable = new ArrayList<Shell>(_activeShells); Collections.reverse(modifiable); for (Shell shell : modifiable) { Point curLoc = shell.getLocation(); shell.setLocation(curLoc.x, curLoc.y - minHeight); if (curLoc.y - minHeight < 0) { _activeShells.remove(shell); shell.dispose(); } } } _shell.setLocation(startX, startY); _shell.setAlpha(0); _shell.setVisible(true); _activeShells.add(_shell); fadeIn(_shell); }
8
private static ConnectionHandler getConnection() { for ( ConnectionHandler c : connections ) { if ( !c.isUsed() ) { return c; } } // create a new connection as none are free Connection connection = null; ConnectionHandler ch = null; try { Class.forName( "com.mysql.jdbc.Driver" ); connection = DriverManager.getConnection( "jdbc:mysql://" + MainConfig.host + ":" + MainConfig.port + "/" + MainConfig.database, MainConfig.username, MainConfig.password ); } catch ( SQLException | ClassNotFoundException ex ) { System.out.println( "SQL is unable to create a new connection" ); } ch = new ConnectionHandler( connection ); connections.add( ch ); System.out.println( "Created new sql connection!" ); return ch; }
3
static String serializeNodeValue(Object value) { String strValue; if (value == null) { strValue = null; } else if (value instanceof Boolean) { strValue = XMPUtils.convertFromBoolean(((Boolean) value).booleanValue()); } else if (value instanceof Integer) { strValue = XMPUtils.convertFromInteger(((Integer) value).intValue()); } else if (value instanceof Long) { strValue = XMPUtils.convertFromLong(((Long) value).longValue()); } else if (value instanceof Double) { strValue = XMPUtils.convertFromDouble(((Double) value).doubleValue()); } else if (value instanceof XMPDateTime) { strValue = XMPUtils.convertFromDate((XMPDateTime) value); } else if (value instanceof GregorianCalendar) { XMPDateTime dt = XMPDateTimeFactory.createFromCalendar((GregorianCalendar) value); strValue = XMPUtils.convertFromDate(dt); } else if (value instanceof byte[]) { strValue = XMPUtils.encodeBase64((byte[]) value); } else { strValue = value.toString(); } return strValue != null ? Utils.removeControlChars(strValue) : null; }
9
public boolean matches( IPAddress dest ) { if( equals(dest) ) return true; if( dest instanceof IP6Address ) { IP6Address dest6 = (IP6Address)dest; long hi = getUpper64(), lo = getLower64(); // solicited node multicast? if( hi == 0xFF02000000000000l && (lo & 0xFFFFFFFFFF000000l) == 0x00000001FF000000l && (lo & 0x0000000000FFFFFFl) == (dest6.getLower64() & 0x0000000000FFFFFFl) ) return true; } return false; }
5
@Override public boolean execute(MOB mob, List<String> commands, int metaFlags) throws java.io.IOException { commands.remove(0); final String protectMe=CMParms.combine(commands,0); if(protectMe.length()==0) { mob.tell(L("Protect whom? Enter a player name to protect from autopurge.")); return false; } if((!CMLib.players().playerExists(protectMe))&&(!CMLib.players().accountExists(protectMe))&&(CMLib.clans().getClan(protectMe)==null)) { mob.tell(L("Protect whom? '@x1' is not a known player.",protectMe)); return false; } final List<String> protectedOnes=Resources.getFileLineVector(Resources.getFileResource("protectedplayers.ini",false)); if((protectedOnes!=null)&&(protectedOnes.size()>0)) for(int b=0;b<protectedOnes.size();b++) { final String B=protectedOnes.get(b); if(B.equalsIgnoreCase(protectMe)) { mob.tell(L("That player already protected. Do LIST NOPURGE and check out #@x1.",""+(b+1))); return false; } } mob.tell(L("The player '@x1' is now protected from autopurge.",protectMe)); final StringBuffer str=Resources.getFileResource("protectedplayers.ini",false); if(protectMe.trim().length()>0) str.append(protectMe+"\n"); Resources.updateFileResource("::protectedplayers.ini",str); return false; }
9
public static Movimientos getInstance(int tipo){ switch(tipo){ case 1: return movimientos1; case 2: return movimientos2; case 3: return movimientos3; case 4: return movimientos4; } return null; }
4
private void updatePlaerInfoPosition(PlayerInfo playerInfo, Direction direction) { switch (direction) { case NORTH: playerInfo.decrementY(); break; case EAST: playerInfo.incrementX(); break; case SOUTH: playerInfo.incrementY(); break; case WEST: playerInfo.decrementX(); break; case NORTH_EAST: playerInfo.incrementX(); playerInfo.decrementY(); break; case SOUTH_EAST: playerInfo.incrementX(); playerInfo.incrementY(); break; case SOUTH_WEST: playerInfo.decrementX(); playerInfo.incrementY(); break; case NORTH_WEST: playerInfo.decrementX(); playerInfo.decrementY(); break; default: // TODO throw an exception here)(?) log.error("wrong direction!!!"); break; } byte posZ = mapReader.getCellAltitude(playerInfo.getPosX(), playerInfo.getPosY()); playerInfo.setPosZ(posZ); }
8
private int writeToStream(OutputStream streamOut, int count) throws IOException { int oldVirtualSize = virtualSize; if (virtualSize > 0) { // If the buffer isn't empty int bytesToWrite; // If the virtual buffer wraps if (head + virtualSize >= physicalSize && count > 0) { bytesToWrite = Math.min(count, physicalSize - head); if (streamOut != null) { streamOut.write(buffer, head, bytesToWrite); } count -= bytesToWrite; skip(bytesToWrite); // head may wrap to zero with this call } // If the virtual buffer doesn't wrap if (head + virtualSize < physicalSize && count > 0) { bytesToWrite = Math.min(count, getTail() - head); if (streamOut != null) { streamOut.write(buffer, head, bytesToWrite); } skip(bytesToWrite); } } return oldVirtualSize - virtualSize; }
7
public void stopTime() { if (this.timer != null) { this.timer.cancel(); } }
1
void parse_frame() throws BitstreamException { // Convert Bytes read to int int b=0; byte[] byteread = frame_bytes; int bytesize = framesize; // Check ID3v1 TAG (True only if last frame). //for (int t=0;t<(byteread.length)-2;t++) //{ // if ((byteread[t]=='T') && (byteread[t+1]=='A') && (byteread[t+2]=='G')) // { // System.out.println("ID3v1 detected at offset "+t); // throw newBitstreamException(INVALIDFRAME, null); // } //} for (int k=0;k<bytesize;k=k+4) { byte b0 = 0; byte b1 = 0; byte b2 = 0; byte b3 = 0; b0 = byteread[k]; if (k+1<bytesize) b1 = byteread[k+1]; if (k+2<bytesize) b2 = byteread[k+2]; if (k+3<bytesize) b3 = byteread[k+3]; framebuffer[b++] = ((b0 << 24) &0xFF000000) | ((b1 << 16) & 0x00FF0000) | ((b2 << 8) & 0x0000FF00) | (b3 & 0x000000FF); } wordpointer = 0; bitindex = 0; }
4
@Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if(aValue != null){ Message Msg = ListMsg.get(rowIndex); MessageDAO MsgDAO = new MessageDAO(); switch(columnIndex){ case 0: break; case 1: Msg.setId_message((int)aValue); break; case 2: Msg.setTo((String)aValue); break; case 3: Msg.setObject((String)aValue); break; case 4: Msg.setContent((String)aValue); break; } } }
6
public void run(){ for( int k = lastSteps + 1; k < maxIter; k++){ for( int m = 0; m < maxTemp; m++ ){ for( int j = 0; j < maxStep; j++ ) { for( int h = 0; h < dim; h++){ // Step in a random direction for each dimension. double f = obj.eval(); double r = randomStepScale(); while( ! obj.inBounds(h, r * v[h] ) ){ r = randomStepScale(); } obj.step( h, r * v[h] ); double fp = obj.eval(); decide( f, fp, h); } } // This is where we update the step vector. for( int u = 0; u < v.length; u++ ){ double n = (double) obj.getAcceptCount( u ); if( n > 0.6 * maxStep ){ v[ u ] = Math.min( v[ u ] + (v[u] * 2 * n / (0.4 * maxStep)) - (1.5 * 2 * v[ u ]), maxStepLength ); } else if( n < 0.4 * maxStep ){ v[ u ] = Math.max( v[u] / ( 1 + 2 - (n / (0.4 * maxStep) )), minStepLength ); } } obj.reset(); reduceTemp(); } //Update value history and check for termination fHist[ k ] = obj.eval(); if( hasConverged( k ) ) break; else obj.set( xOpt ); } }
9
@Override public List<StrasseDTO> findStreetsByStartPoint(Long startPunktId, boolean b) { List<StrasseDTO> ret = new ArrayList<StrasseDTO>(); if(startPunktId ==1){ StrasseDTO s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(1)); s.setEndPunktId(Long.valueOf(2)); // s.setStartPunktName("A"); // s.setEndPunktName("B"); s.setDistanz(Long.valueOf(2)); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(1)); s.setEndPunktId(Long.valueOf(3)); // s.setStartPunktName("A"); // s.setEndPunktName("C"); s.setDistanz(Long.valueOf(4)); ret.add(s); } else if(startPunktId==2) { StrasseDTO s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(2)); s.setEndPunktId(Long.valueOf(1)); // s.setStartPunktName("B"); // s.setEndPunktName("A"); s.setDistanz(Long.valueOf(2)); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(2)); s.setEndPunktId(Long.valueOf(3)); // s.setStartPunktName("B"); // s.setEndPunktName("C"); s.setDistanz(Long.valueOf(2)); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(2)); s.setEndPunktId(Long.valueOf(4)); // s.setStartPunktName("B"); // s.setEndPunktName("D"); s.setDistanz(Long.valueOf(4)); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(2)); s.setEndPunktId(Long.valueOf(5)); // s.setStartPunktName("B"); // s.setEndPunktName("E"); s.setDistanz(Long.valueOf(10)); ret.add(s); } else if(startPunktId==3) { StrasseDTO s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(3)); s.setEndPunktId(Long.valueOf(1)); // s.setStartPunktName("C"); // s.setEndPunktName("A"); s.setDistanz(Long.valueOf(4)); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(3)); s.setEndPunktId(Long.valueOf(2)); // s.setStartPunktName("C"); // s.setEndPunktName("B"); s.setDistanz(Long.valueOf(2)); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(3)); s.setEndPunktId(Long.valueOf(4)); // s.setStartPunktName("C"); // s.setEndPunktName("D"); s.setDistanz(Long.valueOf(1)); ret.add(s); } else if(startPunktId==4) { StrasseDTO s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(4)); s.setEndPunktId(Long.valueOf(2)); // s.setStartPunktName("D"); // s.setEndPunktName("B"); s.setDistanz(Long.valueOf(4)); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(4)); s.setEndPunktId(Long.valueOf(3)); // s.setStartPunktName("D"); // s.setEndPunktName("C"); s.setDistanz(Long.valueOf(1)); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(4)); s.setEndPunktId(Long.valueOf(5)); // s.setStartPunktName("D"); // s.setEndPunktName("E"); s.setDistanz(Long.valueOf(4)); ret.add(s); } else { StrasseDTO s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(5)); s.setEndPunktId(Long.valueOf(2)); // s.setStartPunktName("E"); // s.setEndPunktName("B"); s.setDistanz(Long.valueOf(10)); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(5)); s.setEndPunktId(Long.valueOf(4)); // s.setStartPunktName("E"); // s.setEndPunktName("D"); s.setDistanz(Long.valueOf(4)); ret.add(s); } return ret; }
4
public static byte[] encrypt(byte[] in,byte[] key){ K = expandKey(key); int lenght=0; byte[] padding = new byte[1]; int i; lenght = 16 - in.length % 16; padding = new byte[lenght]; padding[0] = (byte) 0x80; for (i = 1; i < lenght; i++) padding[i] = 0; byte[] tmp = new byte[in.length + lenght]; byte[] bloc = new byte[16]; int count = 0; for (i = 0; i < in.length + lenght; i++) { if (i > 0 && i % 16 == 0) { bloc = encryptBloc(bloc); System.arraycopy(bloc, 0, tmp, i - 16, bloc.length); } if (i < in.length) bloc[i % 16] = in[i]; else{ bloc[i % 16] = padding[count % 16]; count++; } } if(bloc.length == 16){ bloc = encryptBloc(bloc); System.arraycopy(bloc, 0, tmp, i - 16, bloc.length); } return tmp; }
6
public static void main(String[] args) throws IOException { InputStreamReader ir = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(ir); int num = Integer.parseInt(in.readLine()); for (int i = 0; i < num; i++) { String line = in.readLine(); String result = ""; int half = line.length()%2 == 0 ? line.length()/2-1 : line.length()/2; for (int k = line.length() - 1; k >= 0; k--) { char c = line.charAt(k); if (k > half) { if(isLetter(c)) c = (char) (c + 3); } else{ if(isLetter(c)) c = (char) (c + 2); else c = (char) (c - 1); } result += c; } System.out.println(result); } }
6
public void renderSprite(int xp, int yp, Sprite sprite, boolean fixed) { if (fixed) { xp -= xOffset; yp -= yOffset; } for (int y = 0; y < sprite.getHeight(); y++) { int ya = y + yp; for (int x = 0; x < sprite.getWidth(); x++) { int xa = x + xp; if (xa < 0 || xa >= width || ya < 0 || ya >= height) continue; pixels[x + y * width] = sprite.pixels[x + y *sprite.getWidth()]; } } }
7
private void populateNodes() { if (andList != null && andList.size() > 0 && orList != null && orList.size() > 0) { return; } if (currentNode != null && currentNode.children != null && currentNode.children.length == 3) { SimpleNode left = (SimpleNode) currentNode.children[0]; SimpleNode right = (SimpleNode) currentNode.children[2]; SimpleNode op = (SimpleNode) currentNode.children[1]; // TreeOperand l = new TreeOperand(left); // TreeOperand r = new TreeOperand(right); // expression = new BasicExpression(l, r, op.id); } }
7
private final String[] create( int aInSize, int aInSingleIndentSize, boolean aInStartWithEmpty, String aInFirst, String aInLast, String aInCommon) { boolean lIsDefault = ((!isTab) && (DEFAULT_FIRST.equals(aInFirst) && DEFAULT_LAST.equals(aInLast) && DEFAULT_COMMON.equals(aInCommon))) || (isTab && (DEFAULT_FIRST_TAB.equals(aInFirst)) && (DEFAULT_LAST_TAB.equals(aInLast)) && (DEFAULT_COMMON_TAB.equals(aInCommon))); String[] $Tbl = new String[aInSize]; for (int i = 0; i < aInSize; i++) { if (lIsDefault) { $Tbl[i] = getDefault(i, aInSingleIndentSize, aInStartWithEmpty); } else { $Tbl[i] = createEntry( i, aInSingleIndentSize, aInStartWithEmpty, aInFirst, aInLast, aInCommon); } } return $Tbl; }
9
public void setRight(PExp node) { if(this._right_ != null) { this._right_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._right_ = node; }
3
private void botonComenzarImportacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonComenzarImportacionActionPerformed String col = getIdColeccion().getText(); String em = getIdEmision().getText(); String rut = getRutaCarpeta().getText(); int valor = 0; if(col.equals("") || em.equals("") || rut.equals("")){ JOptionPane.showMessageDialog(this,"No puede dejar ningún campo en blanco","Campos en blanco",JOptionPane.INFORMATION_MESSAGE); }else{ //antes que nada validar que los ids existan al igual que la ruta //Gavarela: las cadenas de conexión se están almacenando en Control. //String cadenaOlib = (String)urlOlib.get(comboOlib.getSelectedIndex()); //String cadenaDspace = (String)urlDspace.get(comboDspace.getSelectedIndex()); String cadenaOlib = Ejecutable.getControl().getConexiónOlib(); String cadenaDspace = Ejecutable.getControl().getConexiónDSpace(); try { valor = Ejecutable.getControl().validarDatos(idColeccion.getText(), idEmision.getText(), rutaCarpeta.getText(), cadenaOlib, cadenaDspace); switch (valor) { case 3: JOptionPane.showMessageDialog(this, "El ID de colección ingresada no existe en " + nomUrlDspace.get(urlDspace.indexOf(cadenaDspace)), "Colección no valida", JOptionPane.INFORMATION_MESSAGE); break; case 4: JOptionPane.showMessageDialog(this, "El ID del titulo ingresado no existe en " + nomUrlDspace.get(urlDspace.indexOf(cadenaDspace)), "Titulo no valido", JOptionPane.INFORMATION_MESSAGE); break; case 2: JOptionPane.showMessageDialog(this, "La ruta de carpeta especificada no es valida", "Ruta no valida", JOptionPane.INFORMATION_MESSAGE); break; } } catch (SQLException ex) { JOptionPane.showMessageDialog(this, "Error de conexión. " + ex.getMessage(), "SQL Exception", JOptionPane.ERROR_MESSAGE); Ejecutable.getControl().imprimirLogFisico("Error de conexión. " + ex.getMessage()); } catch (ClassNotFoundException ex) { JOptionPane.showMessageDialog(this, "Hacen falta controladores de Oracle, favor contéctese con soporte. " + ex.getMessage(), "Error de driver", JOptionPane.ERROR_MESSAGE); Ejecutable.getControl().imprimirLogFisico("Hacen falta controladores de Oracle, favor contáctese con soporte" + ex.getMessage()); } if(valor == 1){ /*Gavarela: Ya se está conectado a Samba desde la ventana pasada (AccesoServidores) // LOGUEO DE SAMBA String dspace = (String)nomUrlDspace.get(urlDspace.indexOf(cadenaDspace)); dspace = Ejecutable.getControl().cortarCadena(dspace); new LogeoSamba(dspace).setVisible(true); this.setVisible(false); // si todo sale bien en LogueoSamba, entonces se llama el método importacion()*/ importacion(); } } }//GEN-LAST:event_botonComenzarImportacionActionPerformed
9
private synchronized void writeLog(String message) throws Exception { try { bw.write(message); bw.newLine(); bw.flush(); } catch (Exception e) { throw new Exception(e.getMessage()); } }
1
public static PsdObject loadPsdObject(PsdInputStream stream) throws IOException { String type = stream.readString(4); PsdObject.logger.finest("loadPsdObject.type: " + type); if (type.equals("Objc")) { return new PsdDescriptor(stream); } else if (type.equals("VlLs")) { return new PsdList(stream); } else if (type.equals("doub")) { return new PsdDouble(stream); } else if (type.equals("long")) { return new PsdLong(stream); } else if (type.equals("bool")) { return new PsdBoolean(stream); } else if (type.equals("UntF")) { return new PsdUnitFloat(stream); } else if (type.equals("enum")) { return new PsdEnum(stream); } else if (type.equals("TEXT")) { return new PsdText(stream); } else if (type.equals("tdta")) { return new PsdTextData(stream); } else { throw new IOException("UNKNOWN TYPE <" + type + ">"); } }
9
public static String stringFor_cl_gl_object_type(int n) { switch (n) { case CL_GL_OBJECT_BUFFER: return "CL_GL_OBJECT_BUFFER"; case CL_GL_OBJECT_TEXTURE2D: return "CL_GL_OBJECT_TEXTURE2D"; case CL_GL_OBJECT_TEXTURE3D: return "CL_GL_OBJECT_TEXTURE3D"; case CL_GL_OBJECT_RENDERBUFFER: return "CL_GL_OBJECT_RENDERBUFFER"; case CL_GL_OBJECT_TEXTURE2D_ARRAY: return "CL_GL_OBJECT_TEXTURE2D_ARRAY"; case CL_GL_OBJECT_TEXTURE1D: return "CL_GL_OBJECT_TEXTURE1D"; case CL_GL_OBJECT_TEXTURE1D_ARRAY: return "CL_GL_OBJECT_TEXTURE1D_ARRAY"; case CL_GL_OBJECT_TEXTURE_BUFFER: return "CL_GL_OBJECT_TEXTURE_BUFFER"; } return "INVALID cl_gl_object_type: " + n; }
8
public List<V> get(Object key) { return this.map.get(key); }
0
public void changeName(String id, String newName) { if(participants.containsKey(id)) { participants.get(id).setName(newName); setChanged(); notifyObservers(ModelNotification.LIST_OF_PARTICIPANTS_CHANGED); setChanged(); notifyObservers(ModelNotification.NAME_CHANGED); } }
1
public void run() { running = true; try { if (!main.getConfig().getBoolean("force-update")) { VersionChecker.checkVersion(main.getApi()); while (askUpdate) { // Wait user. Thread.sleep(10L); } } else { doUpdate = true; } UpdaterWorker.determinePackages(main.getApi()); if (doUpdate) { UpdaterWorker.update(main.getApi()); } percentage = 90; } catch (final Exception e) { e.printStackTrace(); } running = false; }
4
private void exitCompositeState(CompositeState<TransitionInput> composite) { for(StateMachineEventListener<TransitionInput> eventListener : eventListeners) { eventListener.beforeCompositeStateExited(composite, this); } composite.onExit(); for(StateMachineEventListener<TransitionInput> eventListener : eventListeners) { eventListener.afterCompositeStateExited(composite, this); } }
2
private void readSkills(String path, DataModel dataModel) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File(path)); // normalize text representation doc.getDocumentElement().normalize(); NodeList listOfSkillTrees = doc.getElementsByTagName("skillTree"); for (int s = 0; s < listOfSkillTrees.getLength(); s++) { Node skillTreeNode = listOfSkillTrees.item(s); if (skillTreeNode.getNodeType() == Node.ELEMENT_NODE) { Element skillTreeElement = (Element) skillTreeNode; SkillTree tree = new SkillTree(skillTreeElement.getAttribute("name")); dataModel.getSkillTrees().add(tree); NodeList listOfSkill = skillTreeElement.getElementsByTagName("skill"); for (int s2 = 0; s2 < listOfSkill.getLength(); s2++) { Node skillNode = listOfSkill.item(s2); if (skillNode.getNodeType() == Node.ELEMENT_NODE) { Element skillElement = (Element) skillNode; Skill skill = new Skill(getTagValue("tag", skillElement), LanguageTools.translate(getTagValue( "name", skillElement))); skill.setValue(Integer.parseInt(getTagValue("value", skillElement))); skill.setMaxValue(Integer.parseInt(getTagValue("maxValue", skillElement))); skill.setRank(Integer.parseInt(getTagValue("rank", skillElement))); skill.setPosition(Integer.parseInt(getTagValue("position", skillElement))); skill.setIconName(getTagValue("icon", skillElement)); String dependencyTag = getTagValue("dependency", skillElement); if (dependencyTag != null) { skill.setDependency(dataModel.getSkill(dependencyTag)); } dataModel.getSkills().add(skill.getTag(), skill); tree.addSkill(skill); skill.setParentTree(tree); } } } } } catch (SAXParseException err) { System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); System.out.println(" " + err.getMessage()); } catch (SAXException e) { Exception x = e.getException(); ((x == null) ? e : x).printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } }
9
public EmployeeDaoStub() { map = new HashMap<Integer, Employee>(); for (int i = 0; i < 10; i++) { Employee employee = new Employee(); employee.setEmail("v@pupkin" + i + ".com"); employee.setFirstName("Vasya" + i); employee.setId((long) i); employee.setLastName("Pupkin" + i); map.put(i,employee); } }
1
@SuppressWarnings("unchecked") @Override public <T> T adaptTo(Class<T> type) { if (type.equals(ClassElement.class)) { return (T) this; } return null; }
1
public void lireMateriel() { if (simu.touchePressee(1)) { controleur.start(); } if (simu.touchePressee(2)) { controleur.stop(); } if (simu.touchePressee(3)) { controleur.inc(); } if (simu.touchePressee(4)) { controleur.dec(); } float p = simu.position(); if (p != prevp) { controleur.updateMolette((int) p); prevp = p; } }
5
@Override public boolean equals(Object o) { if(o == null) return false; if(o == this) return true; if(!(o instanceof Auftrag)) return false; Auftrag a = (Auftrag)o; if(a.getNr() != nr || a.isIstAbgeschlossen() != istAbgeschlossen) return false; if(!a.getBeauftragAm().equals(beauftragAm)) return false; if(!a.getAngebot().equals(angebot)) return false; return true; }
7
private static List<String> processDeltas(List<String> origLines, List<Delta<String>> deltas, int contextSize) { List<String> buffer = new ArrayList<String>(); int origTotal = 0; // counter for total lines output from Original int revTotal = 0; // counter for total lines output from Original int line; Delta<String> curDelta = deltas.get(0); // NOTE: +1 to overcome the 0-offset Position int origStart = curDelta.getOriginal().getPosition() + 1 - contextSize; if (origStart < 1) { origStart = 1; } int revStart = curDelta.getRevised().getPosition() + 1 - contextSize; if (revStart < 1) { revStart = 1; } // find the start of the wrapper context code int contextStart = curDelta.getOriginal().getPosition() - contextSize; if (contextStart < 0) { contextStart = 0; // clamp to the start of the file } // output the context before the first Delta for (line = contextStart; line < curDelta.getOriginal().getPosition(); line++) { // buffer.add(" " + origLines.get(line)); origTotal++; revTotal++; } // output the first Delta buffer.addAll(getDeltaText(curDelta)); origTotal += curDelta.getOriginal().getLines().size(); revTotal += curDelta.getRevised().getLines().size(); int deltaIndex = 1; while (deltaIndex < deltas.size()) { // for each of the other Deltas Delta<String> nextDelta = deltas.get(deltaIndex); int intermediateStart = curDelta.getOriginal().getPosition() + curDelta.getOriginal().getLines().size(); for (line = intermediateStart; line < nextDelta.getOriginal() .getPosition(); line++) { // output the code between the last Delta and this one buffer.add(" " + origLines.get(line)); origTotal++; revTotal++; } buffer.addAll(getDeltaText(nextDelta)); // output the Delta origTotal += nextDelta.getOriginal().getLines().size(); revTotal += nextDelta.getRevised().getLines().size(); curDelta = nextDelta; deltaIndex++; } // Now output the post-Delta context code, clamping the end of the file contextStart = curDelta.getOriginal().getPosition() + curDelta.getOriginal().getLines().size(); for (line = contextStart; (line < (contextStart + contextSize)) && (line < origLines.size()); line++) { buffer.add(" " + origLines.get(line)); origTotal++; revTotal++; } // Create and insert the block header, conforming to the Unified Diff // standard StringBuffer header = new StringBuffer(); header.append("@@ -"); header.append(origStart); header.append(","); header.append(origTotal); header.append(" +"); header.append(revStart); header.append(","); header.append(revTotal); header.append(" @@"); buffer.add(0, header.toString()); return buffer; }
8
public final void handleEnergyCharge(final int skillid, final byte targets) { final ISkill echskill = SkillFactory.getSkill(skillid); final byte skilllevel = getSkillLevel(echskill); if (skilllevel > 0) { if (targets > 0) { if (getBuffedValue(MapleBuffStat.ENERGY_CHARGE) == null) { echskill.getEffect(skilllevel).applyEnergyBuff(this, true); // Infinity time } else { Integer energyLevel = getBuffedValue(MapleBuffStat.ENERGY_CHARGE); if (energyLevel < 10000) { energyLevel += (100 * targets); setBuffedValue(MapleBuffStat.ENERGY_CHARGE, energyLevel); client.getSession().write(MaplePacketCreator.giveEnergyChargeTest(energyLevel)); if (energyLevel >= 10000) { energyLevel = 10001; } } else if (energyLevel == 10001) { echskill.getEffect(skilllevel).applyEnergyBuff(this, false); // One with time energyLevel = 10002; } } } } }
6
public void crearTabla(){ int x=0; while(x<NumeroEntradas){ List<Boolean> newLista=new List(); int y=0; while(y<LargoLista){ for(int i=0;i<alternado;i++){ newLista.append(true); y++; } for(int i=0;i<alternado;i++){ newLista.append(false); y++; } } entradas.append(newLista); alternado=alternado/2; x++; } }
4
protected void stepFWDBackTrack(boolean showSteps) { // Global alignment: start from D(m,n) // TODO: Not very elegant. To be changed! CellElement theOneBefore = null; if (!m_backTrackList.isEmpty()) { theOneBefore = (CellElement) m_backTrackList.getLast(); } if (m_backtrackLastSel == null) { // Policy for automatic pointer selection!! m_backTrackList.add(theOneBefore.getPointerWithPolicy( m_backtrackingPolicy)); } else { m_backTrackList.add(m_backtrackLastSel); } CellElement currentCell = (CellElement) m_backTrackList.getLast(); if (m_backTrackList.size() > 1) { setResultString(theOneBefore, currentCell); } Point D = new Point(currentCell.getColumn() - 1, currentCell.getRow() - 1); m_l1Choiche.setBackground(m_mainPane.getBackground()); m_l2Choiche.setBackground(m_mainPane.getBackground()); m_l3Choiche.setBackground(m_mainPane.getBackground()); CellElement leftCell = currentCell.getLeftPointer(); CellElement topCell = currentCell.getTopPointer(); CellElement topLeftCell = currentCell.getDiagPointer(); String DEqual = "D(" + (D.y) + ", " + (D.x) + ") = Select"; String DLeft = ""; String DTop = ""; String DTopLeft = ""; m_dpTable.clearInteractiveCells(); // Init choosen array LinkedList highlightList = new LinkedList(); if (leftCell == null) { DLeft = "No Pointer"; } else { DLeft = "D(" + (leftCell.getRow() - 1) + ", " + (leftCell.getColumn() - 1) + ")"; m_dpTable.addInteractiveCell(leftCell); highlightList.add(leftCell); } if (topCell == null) { DTop = "No Pointer"; } else { DTop = "D(" + (topCell.getRow() - 1) + ", " + (topCell.getColumn() - 1) + ")"; m_dpTable.addInteractiveCell(topCell); highlightList.add(topCell); } if (topLeftCell == null) { DTopLeft = "No Pointer"; } else { DTopLeft = "D(" + (topLeftCell.getRow() - 1) + ", " + (topLeftCell.getColumn() - 1) + ")"; m_dpTable.addInteractiveCell(topLeftCell); highlightList.add(topLeftCell); } m_lDEqual.setText(DEqual); m_l1Choiche.setText(DLeft); m_l2Choiche.setText(DTop); m_l3Choiche.setText(DTopLeft); m_dpTable.setTriArrows(currentCell, false); m_dpTable.setMultipleCellHighlight(highlightList); currentCell.setColor(Color.green); if (currentCell.getColumn() == 1 && currentCell.getRow() == 1) { m_btnNext.setEnabled(false); m_btnEnd.setEnabled(false); m_dpTable.clearAllArrows(); m_dpTable.clearGridCircle(); } else { // TODO: Not elegant. To be changed m_btnNext.setEnabled(true); m_btnEnd.setEnabled(true); } if (showSteps) { m_dpTable.paint(m_dpTable.getGraphics()); } m_backtrackLastSel = null; }
9