text
stringlengths
14
410k
label
int32
0
9
@Override public void mouseClicked(MouseEvent e) { JButton clicked = (JButton)e.getComponent(); if (clicked.equals(this.addButton)) { List<Object> rowColumns = this.controlsController.addCurrentElement(); this.builtController.addRow(rowColumns); if (!rowColumns.isEmpty()) { this.keyOptions.removeItem(rowColumns.get(1)); } } else if (clicked.equals(this.resetButton)) { this.builtController.resetTable(); this.controlsController.resetControls(); } else if (clicked.equals(this.saveButton)) { VInstrument toSave = this.controlsController.getInstrumentBuilt(); VFileManager.instance.saveInstrument(toSave); } else if (clicked.equals(this.loadButton)) { VInstrument read = VFileManager.instance.readInstrument(); if (read != null) { loadInstrument(read); } } }
6
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; boolean success=proficiencyCheck(mob,0,auto); if(success) { invoker=mob; final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> gergle(s) at <T-NAMESELF>.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); if(msg.value()<=0) { if(target.location()==mob.location()) { target.location().show(target,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> start(s) gagging and spitting as <S-HIS-HER> mouth becomes clogged with gunk!")); success=maliciousAffect(mob,target,asLevel,0,-1)!=null; } } } } else return maliciousFizzle(mob,target,L("<S-NAME> gurgle(s) at <T-NAMESELF>, but the spell fizzles.")); // return whether it worked return success; }
7
* @param gId the id of the group whose contents are desired * @return the contents of the group in XML * @throws MVDException if the group was not found */ public String getContentsForGroup( int indent, short gId ) throws MVDException { StringBuffer sb = new StringBuffer(); // write group start tag for ( int i=0;i<indent;i++ ) sb.append( " " ); Group g1 = (gId != 0)?groups.get(gId-1):new Group((short)-1, "top level" ); if ( g1 == null ) throw new MVDException("group id "+gId+" not found!"); sb.append("<group name=\""+g1.name+"\" id=\""+gId+"\""); if ( gId != 0 ) sb.append(" parent=\""+g1.parent+"\""); sb.append( ">\n" ); // check for sub-groups for ( short i=0;i<groups.size();i++ ) { Group g = groups.get( i ); if ( g.parent == gId ) sb.append( getContentsForGroup(indent+2, (short)(i+1)) ); } // get sub-versions for ( short i=0;i<versions.size();i++ ) { Version v = versions.get( i ); if ( v.group == gId ) sb.append( v.toXML(indent+2,i+1) ); } // write group end tag for ( int i=0;i<indent;i++ ) sb.append( " " ); sb.append("</group>"); sb.append("\n"); return sb.toString(); }
9
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (this.actionOnUpgrade != null) { try { /* * Use reflection to get and instantiate the SQLite Database, the old verion number, and the new * version number, as defined by the user in the Runnable parameter passed to the createDb(String * dbName, Runnable actionOnUpgrade) method of the Dbtool instance. */ Class<?> actionClass = actionOnUpgrade.getClass(); Field[] fields = actionClass.getFields(); for (Field field : fields) { if (field.getType() == Class.forName("android.database.sqlite.SQLiteDatabase")) { field.set(actionOnUpgrade, db); } if (field.getType() == Class.forName("java.lang.Integer")) { if (field.getName() == "oldVersion") { field.set(actionOnUpgrade, oldVersion); } if (field.getName() == "newVersion") { field.set(actionOnUpgrade, newVersion); } } } this.actionOnUpgrade.run(); } catch (ClassNotFoundException ex) { // No SQLiteDatabase field in the runnable. Assume user does // not need to use any. } catch (Exception ex) { // Other error. } } }
9
RoomScheme generateRandomScheme(int days, int classTimes, Subject[] s){ Subject[][] sub = new Subject[days][classTimes]; RoomScheme r; for(int i=0; i<days; i++){ for(int j=0; j<classTimes; j++){ sub[i][j] = s[(int)(Math.random()*(s.length))]; } } r = new RoomScheme(sub); r.setFitness(getRoomFitness(r)); return r; }
2
public static List<Paiva> haePaivat() throws NamingException, SQLException { Yhteys tietokanta = new Yhteys(); Connection yhteys = tietokanta.getYhteys(); String sql = "SELECT * FROM Paiva"; PreparedStatement kysely = yhteys.prepareStatement(sql); ResultSet rs = kysely.executeQuery(); List<Paiva> paivat = new ArrayList<Paiva>(); while(rs.next()) { Paiva p = new Paiva(rs); paivat.add(p); } try { rs.close(); } catch (Exception e) {} try { kysely.close(); } catch (Exception e) {} try { yhteys.close(); } catch (Exception e) {} return paivat; }
4
public void onClose(int round){ boolean stop = false; synchronized (syncIncr) { if (!shouldDecrease || round == super.getNumberOfRounds()) { stop = true; } else { shouldDecrease = false; double decrease = ((super.getMaxPrice() - super.getMinPrice()) / (super.getNumberOfRounds() - 1)); super.setCurrentPrice(super.getCurrentPrice() - decrease); } if (stop) { if (bestBid != null) { double price = bestBid.getPrice(); if (price <= super.getReservePrice()) { super.setFinalPrice(price); super.setWinner(bestBid.getBidder()); } else { super.setFinalPrice(super.getCurrentPrice()); } } else { super.setFinalPrice(super.getCurrentPrice()); } closeAuction(); } } }
5
public TreeNode reValClone(TreeNode node,int offset){ if(node == null) return null; TreeNode newNode = new TreeNode(node.val + offset); newNode.left = reValClone(node.left,offset); newNode.right = reValClone(node.right,offset); return newNode; }
1
public void lower(int x, int y) { _map[y][x] -= 256; if (_map[y][x] < 0) _map[y][x] = 0; }
1
@Override public boolean move(int row, int col) { if (Math.abs(this.row - row) == 1 && Math.abs(this.col - col) == 2 || Math.abs(this.col - col) == 1 && Math.abs(this.row - row) == 2) { this.col = col; this.row = row; return true; } return false; }
4
public static void main(String[] args) throws IOException { // TODO Auto-generated method stub File file = new File("C:/1.txt"); BufferedReader in = new BufferedReader(new FileReader(file)); String line; while ((line = in.readLine()) != null) { if (line.length() <= 55) System.out.println(line); else if (line.length() > 55) { String subLine = line.substring(0, 37).trim() + "... <Read More>"; System.out.println(subLine); } } in.close(); }
3
public int[] toArray() { int[] result = new int[size]; System.arraycopy(data, 0, result, 0, size); return result; }
0
@Override public void applyTemporaryToCurrent() {cur = tmp;}
0
public boolean canGoto(float posX, float posY) { if(!noclip) for(int x1 = 0;x1<w;x1++) { for(int y1 = 0;y1<h;y1++) { float px = ((float)x1+posX)/Block.BLOCK_WIDTH; float py = ((float)y1+posY)/Block.BLOCK_HEIGHT; int gridX = (int) (px >= 0 ? Math.floor(px) : Math.floor(px)); int gridY = (int) (py); WorldChunk chunk = world.getChunkAt(gridX, gridY, false); if(chunk == null) return false; Block t = Block.getBlock(world.getBlockAt(gridX, gridY)); if(t.isSolid() && t.getCollisionBox(gridX, gridY).collide(this.clipAABB().setX(posX).setY(posY))) return false; } } return true; }
7
private void updatePosteriorDistribution() { for (int d = 0; d < param.D; ++d) { for (int t = 0; t < param.T; ++t) { thetasum[d][t] += (ndt[d][t] + param.alpha) / (ndsum[d] + tAlpha); } } for (int t = 0; t < param.T; ++t) { for (int ms = 0; ms < MS; ++ms) { phisum[t][ms] += (nts[t][ms] + param.beta) / (ntsum[t] + sBeta); } } for (int t = 0; t < param.T; ++t) { for (int ms = 0; ms < MS; ++ms) { int size = mustsets.getMustSet(ms).size(); for (int i = 0; i < size; ++i) { etasum[t][ms][i] += (ntsw[t][ms][i] + gamma[ms][i]) / (ntssum[t][ms] + vGamma[t][ms]); } } } ++numstats; }
7
public static void main(String[] args) { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = builderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } Document document; try { document = builder.parse( new FileInputStream("data/example_jira_search_rss.xml")); Element rootElement = document.getDocumentElement(); String attrValue = rootElement.getAttribute("version"); System.out.println( "This is document version: " + attrValue ); /* item title link project @key | text() */ NodeList nodes = rootElement.getElementsByTagName("item"); for(int i=0; i<nodes.getLength(); i++){ // System.out.println( node.getTextContent() ); Node node = nodes.item(i); if(node instanceof Element){ Element child = (Element) node; NodeList titleNodes = child.getElementsByTagName("title"); if (titleNodes.getLength() >= 0) { String title = titleNodes.item(0).getTextContent(); System.out.println( "title : " + title ); } NodeList linkNodes = child.getElementsByTagName("link"); if (linkNodes.getLength() >= 0) { String link = linkNodes.item(0).getTextContent(); System.out.println( "link : " + link ); } NodeList projectNodes = child.getElementsByTagName("project"); if (projectNodes.getLength() >= 0) { Element projectNode = (Element) projectNodes.item(0); String project = projectNode.getTextContent(); String projectKey = projectNode.getAttribute("key"); System.out.println( "project : " + project + " (" + projectKey + ")"); } } } /* NodeList nodes = rootElement.getChildNodes(); for(int i=0; i<nodes.getLength(); i++){ Node node = nodes.item(i); if(node instanceof Element){ //a child element to process //Element child = (Element) node; //String attribute = child.getAttribute("width"); System.out.println( node.getTextContent() ); } } */ } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
8
private void setAngle(double angle) { this.angle = angle % 360.0; if (this.angle < 0) this.angle += 360.0; }
1
@Override public void run() { String msg; try { while ((msg = in.readLine()) != null) { if(!msg.equals("")){ this.respuesta=msg; } } } catch (IOException e) { System.err.println(e); } }
3
public static ServerPerformanceData instanceFromResultSet(ResultSet rs, MineJMX plugin) throws SQLException { ServerPerformanceData sd = new ServerPerformanceData(plugin) ; String data = rs.getString("data") ; if(data.length() <=0 ) { return sd ; } String[] datas = data.split(",") ; for(String s : datas) { String[] keyval = s.split(":") ; if( keyval[0].equals("serverTicks") ) { sd.setServerTicks(Long.decode(keyval[1])) ; } else if( keyval[0].equals("runningTasks") ) { sd.setRunningTasks(Long.decode(keyval[1])) ; } else if( keyval[0].equals("pendingTasks") ) { sd.setPendingTasks(Long.decode(keyval[1])) ; } else if( keyval[0].equals("ticksPerSecondAverage") ) { sd.setTicksPerSecondAverage(Integer.decode(keyval[1])) ; } else if( keyval[0].equals("ticksPerSecondInstantious") ) { sd.setTicksPerSecondInstantious(Integer.decode(keyval[1])) ; } else if( keyval[0].equals("serverLag") ) { sd.setServerLag(Integer.decode(keyval[1])) ; } } return sd ; }
8
public void read() { StringBuilder builder; int read; builder = new StringBuilder(); do { try { read = System.in.read(); } catch (IOException e) { read = 0; } if (read >= 0 && read != '\r' && read != '\n') { builder.append((char) read); } } while (read != '\r' && read != '\n' && read > 0 && !builder.toString().equalsIgnoreCase("end")); Logger.printLine(builder.toString()); this.parseLine(builder.toString()); }
8
public List<Field> findAllAnnotatedFields(Class<? extends Annotation> annotationClass) { List<Field> annotatedFields = new LinkedList<Field>(); for(Field field : getFields()) { if(field.isAnnotationPresent(annotationClass)) { annotatedFields.add(field); } } getFieldDetailStore().addAllFields(annotatedFields); return annotatedFields; }
3
public void initTable(ITable table) { if(_table != null) { _table.removeTableListener(_listener); } super.initTable(table); _table = table; if(_table != null) { table.addTableListener(_listener); } }
2
public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; }
6
public void checkType(Symtab st) { exp1.setScope(scope); exp1.checkType(st); exp2.setScope(scope); exp2.checkType(st); if (!exp1.getType(st).equals("int") && !exp1.getType(st).equals("decimal")) { Main.error("type error in div!"); } if (!exp2.getType(st).equals("int") && !exp2.getType(st).equals("decimal")) { Main.error("type error in div!"); } }
4
@Override public void onPrivateMessage(PrivateMessageEvent e) { final String command = RUtils.getFirstWord(e.getMessage()); if (!command.equalsIgnoreCase("part")) return; final User u = e.getUser(); if (!PermissionHandler.isAuthedOrAdmin(u.getNick(), u.getServer())) { e.respond("You are not allowed to do this."); return; } String[] args = e.getMessage().split(" "); args = (String[]) ArrayUtils.subarray(args, 1, args.length); if (args.length < 1) { e.respond("Usage: part [channel]"); return; } final String channel = args[0]; if (!channel.startsWith("#")) { e.respond("Channel must start with \"#\" to be valid!"); return; } Channel c = null; for (Channel ch : e.getBot().getUserBot().getChannels()) { if (!ch.getName().equalsIgnoreCase(channel)) continue; c = ch; break; } if (c == null) { e.respond("Not in that channel."); return; } c.send().part(); e.respond("Attempted to part channel " + channel + "."); }
7
private int validateInsert() { try { String cid; String cpassword; String cname; String caddr; String cphone; if (custID.getText().trim().length() != 0) { cid = custID.getText().trim(); } else { return VALIDATIONERROR; } if (String.valueOf(password.getPassword()).trim().length() != 0) { cpassword = String.valueOf(password.getPassword()).trim(); } else { return VALIDATIONERROR; } if (custName.getText().trim().length() != 0) { cname = custName.getText().trim(); } else { cname = null; } if (custAddr.getText().trim().length() != 0) { caddr = custAddr.getText().trim(); } else { caddr = null; } if (custPhone.getText().trim().length() != 0 && isNumeric(custPhone.getText())) { cphone = custPhone.getText().trim(); } else { cphone = null; } if (customer.findCustomer(cid)) { JOptionPane.showMessageDialog(this, "Customer ID \"" + cid + "\" already exists. Try another one.", "Error", JOptionPane.ERROR_MESSAGE); return OPERATIONFAILED; } else if (customer.insertCustomer(cid, cname, cpassword, caddr, cphone)) { JOptionPane.showMessageDialog(this, "Registration of \"" + cid + "\" complete! Login now."); return OPERATIONSUCCESS; } else { Toolkit.getDefaultToolkit().beep(); return OPERATIONFAILED; } } catch (NumberFormatException ex) { // this exception is thrown when a string // cannot be converted to a number return VALIDATIONERROR; } }
9
public static HashMap<String, Integer> getCountMap(List<File> fastaFiles) throws Exception { HashMap<String, Integer> map = new HashMap<String, Integer>(); for( File f : fastaFiles) { BufferedReader reader = new BufferedReader(new FileReader(f)); String nextLine = reader.readLine(); while ( nextLine != null ) { String header = nextLine; header = new StringTokenizer(header).nextToken(); if( header.startsWith(">")) header = header.substring(1); if( map.keySet().contains(header) ) throw new Exception("Duplicate key " + header); nextLine = reader.readLine(); int count = 0; while ( nextLine != null && ! nextLine.startsWith(">") ) { count+= stripWhiteSpace( nextLine ).length(); nextLine = reader.readLine(); } map.put(header, count); } reader.close(); } return map; }
6
private static byte[] toCstr(String str) { int length = str.length(); byte[] result = new byte[length + 1]; for (int i = 0; i < length; i++) { result[i] = (byte) str.charAt(i); } result[length] = 0; return result; }
1
@Override public boolean processButtonClick(int interfaceId, int componentId, int slotId, int packetId) { if (interfaceId == 374) { switch (componentId) { case 5: resetOrb(); player.setNextWorldTile(new WorldTile(LOBBY_TELEPORT)); break; case 11: case 12: case 13: case 14: case 15: for (int i = 0; i < 4; i++) { if (i + 11 == componentId) { sendOrb(); player.setNextWorldTile(ORB_TELEPORTS[i]); } } break; } } return true; }
9
public int GetOutputBuffer() { return outputBuffer; }
0
public node[] recombExecute(double gen,int popIndex, doublePointer location){ /* pick location */ double loc; double temp; double temp1; recombStructure temprecomb = recombs; double rr = 0; double end; /* choosing location.. */ temp1 = random.randomDouble(); temp = (double) (temp1 * (recombRate)); while (temprecomb != null && temprecomb.startBase < length && rr < temp) { if (temprecomb.next == null || temprecomb.next.startBase > length) { rr += (length - temprecomb.startBase) * temprecomb.rate; } else { rr += (temprecomb.next.startBase - temprecomb.startBase) * temprecomb.rate; } if (rr < temp) { temprecomb = temprecomb.next; } } if (temprecomb.next == null || temprecomb.next.startBase > length) end = length; else end = temprecomb.next.startBase; loc = (double)((int) (end - (rr - temp) / temprecomb.rate)) / length; location.setDouble(loc); return dem.recombineByIndex(popIndex, gen, loc); }
8
public byte [] get_frame_data(int n){ byte [] frame_info = mpf[n].get_info(); byte [] frame_data = mpf[n].get_main_data(); byte [] anc_data = mpf[n].get_anc_data(); byte [] reserve = mpf[n].get_reserve(); int len = mpf[n].get_framesize(); byte [] frame = new byte [len]; int end = frame_info.length; int start = 0; System.arraycopy(frame_info, 0, frame, start, end); if( frame_data != null ){ start = end; end += frame_data.length; System.arraycopy(frame_data, 0, frame, start, frame_data.length); } if( anc_data!=null ){ start = end; end += anc_data.length; System.arraycopy(anc_data, 0, frame, start, anc_data.length); } if(reserve!=null){ start = end; end += reserve.length; System.arraycopy(reserve, 0, frame, start, reserve.length); } return frame; }
3
private void getLatestThreads(Map<String, Object> jsonrpc2Params) throws Exception { Map<String, Object> params = getParams(jsonrpc2Params, new NullableExtendedParam(Constants.Param.Name.LIMIT, true)); Integer limit = (Integer) params.get(Constants.Param.Name.LIMIT); if(limit == null){ limit = Constants.Database.DEFAULT_LATEST_THREADS_LIMIT; } List<models.Thread> threads = getAllColumns(models.Thread.class); Collections.sort(threads, timeSort()); List<models.Thread> returnThreads = new LinkedList<models.Thread>(); for(int i= 0; i<limit && i<threads.size(); i++){ returnThreads.add(threads.get(i)); } responseParams.put(Constants.Param.Name.THREADS, serialize(returnThreads)); responseParams.put(Constants.Param.Status.STATUS, Constants.Param.Status.SUCCESS); }
3
public boolean matchesAddress(String address, int port) { if(address == null) return (clientAddress == null && port == clientPort); return (address.equals(clientAddress) && port == clientPort); }
3
public void startAlarms() throws InterruptedException { a.setHigh(Integer.parseInt(maxValue.getSelectedItem().toString())); a.setLow(Integer.parseInt(minValue.getSelectedItem().toString())); dataShare.setAlarm(a); int temp = dataShare.getBPM(); if (temp > 0) { a.check(temp); if (a.active()) { alterText(dataShare.genTime(temp)); alterText(a.info()); a.deactivate(); } } }
2
@Override public String execute(String s) { if (s.matches("PRENDRE.* (ROCHE|CLIFF)") && utiliserLampe && !pritRoche) { pritRoche = true; InventoryManager.getInstance().addItem("Cliff"); return "Vous prenez la roche."; } else if (s.matches("(UTILISER|ALLUMER).* LAMPE DE POCHE")) { utiliserLampe = true; return "Il fait maintenant clair."; } else if (s.matches("UTILISER.* CLIFF") && pritRoche && !utiliserRoche) { utiliserRoche = true; LevelManager.getInstance().notifyCurrentLevel("outOfSurplomb"); return "Vous lancez la roche dans le mur de planches.\n" + "Roche : Aaaaaaaaaoutch!\n" + "Etrange... vous reprenez Cliff."; } else if (s.matches("OUI") && veutTomber) { LevelManager.getInstance().notifyCurrentLevel("estMort"); return null; } return null; }
9
private void consumeFutureUninterruptible( Future<?> f ) { try { boolean interrupted = false; while ( true ) { try { f.get(); break; } catch ( InterruptedException e ) { interrupted = true; } } if( interrupted ) Thread.currentThread().interrupt(); } catch ( ExecutionException e ) { throw new RuntimeException( e ); } }
5
@Override public boolean isObstacle(Element e) { if (isActive() && e instanceof Player) return true; return false; }
2
@RequestMapping(method = RequestMethod.GET, value = "login") private String showLoginPage(@RequestParam(value = "error", required = false) String error, Model model) { if (model.containsAttribute("loggedUser")) { return REDIRECT_PREFIX + "/"; } else if (error == null) { return "loginPage"; } return "errorPage"; }
2
public static List<String> getLocalIPs() { Enumeration<NetworkInterface> interfaces; try { interfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { return null; } List<String> ips = new ArrayList<String>(); while(interfaces.hasMoreElements()) { NetworkInterface current = interfaces.nextElement(); if(current != null) { Enumeration<InetAddress> addresses = current.getInetAddresses(); while(addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); if(addr != null) { ips.add(addr.getHostAddress()); } } } } return ips; }
5
public boolean checkMapRectCollision(Shape collisionShape){ int collWidth; int collHeight; int rectX; int rectY; boolean testBoolean = false; for(int i = 0; i <= tileMap[0].length-1; i++){ for(int c = 0; c <= tileMap.length-1; c++){ if(tileMap[c][i] != null){ if(tileMap[c][i].hasCollision){ collWidth = tileMap[c][i].getWidth(); collHeight = tileMap[c][i].getHeight(); rectX = mapX*GameplayState.MAP_WIDTH+(c*collWidth); rectY = mapY*GameplayState.MAP_HEIGHT+(i*collHeight); Rectangle temp = new Rectangle(rectX, rectY, collWidth,collHeight); if(collisionShape.intersects(temp)){ testBoolean = true; } } } } } return testBoolean; }
5
public String format(Double number) { int sign = 1; if (number < 0) { sign = -1; } number = Math.abs(number); String fractionalPart = ":"; int integerPart; integerPart = ((int)Math.floor(number)); double fractional = Math.abs(number - integerPart); if (fractionLength < 6) { double minutes = fractional * 60; String form = "%02.0f"; if (fractionLength == 5) { form = "%04.1f"; } Formatter formatter = new Formatter(Locale.US); String newMinutes = formatter.format(form, minutes).toString(); if (Double.parseDouble(newMinutes) >= 60.0) { minutes = 0.0; integerPart++; } formatter = new Formatter(Locale.US); fractionalPart += formatter.format(form, minutes); } else { double minutes = Math.floor(fractional * 60); double rest = fractional - ((double)minutes / 60.0); double seconds = rest * 3600; String form = "%02.0f"; if (fractionLength == 8) { form = "%04.1f"; } else if (fractionLength == 9) { form = "%05.2f"; } Formatter formatter = new Formatter(Locale.US); String newSeconds = formatter.format(form, seconds).toString(); if (Double.parseDouble(newSeconds) >= 60.0) { seconds = 0.0; minutes++; } formatter = new Formatter(Locale.US); String newMinutes = formatter.format("%02.0f", minutes).toString(); if (Double.parseDouble(newMinutes) >= 60.0) { minutes = 0.0; integerPart++; } formatter = new Formatter(Locale.US); fractionalPart += formatter.format("%02.0f:" + form, minutes, seconds); } String res = integerPart + fractionalPart; if (sign < 0) { res = "-" + res; } res = padLeft(res, length); return res; }
9
private void drawTitlebox(boolean loggedIn) { // drawLoginScreen resetImageProducers(); leftCanvas.initDrawingArea(); titleBox.drawIndexedSprite(0, 0); if (loginScreenState == 0) { // Default smallFont.drawCenteredText(0x75a9a9, 180, onDemandFetcher.statusString, 180, true); boldFont.drawCenteredText(0xffff00, 180, "Welcome to RuneScape", 80, true); titleButton.drawIndexedSprite(27, 100); boldFont.drawCenteredText(0xffffff, 100, "New User", 125, true); titleButton.drawIndexedSprite(187, 100); boldFont.drawCenteredText(0xffffff, 260, "Existing User", 125, true); } if (loginScreenState == 2) { // Existing User if (loginMessage1.length() > 0) { boldFont.drawCenteredText(0xffff00, 180, loginMessage1, 45, true); boldFont.drawCenteredText(0xffff00, 180, loginMessage2, 60, true); } else { boldFont.drawCenteredText(0xffff00, 180, loginMessage2, 53, true); } boldFont.drawText(true, 90, 0xffffff, "Username: " + myUsername + (loginScreenCursorPos == 0 & Client.loopCycle % 40 < 20 ? "@yel@|" : ""), 90); boldFont.drawText(true, 92, 0xffffff, "Password: " + TextUtil.censorPassword(myPassword) + (loginScreenCursorPos == 1 & Client.loopCycle % 40 < 20 ? "@yel@|" : ""), 105); if (!loggedIn) { titleButton.drawIndexedSprite(27, 130); boldFont.drawCenteredText(0xffffff, 100, "Login", 155, true); titleButton.drawIndexedSprite(187, 130); boldFont.drawCenteredText(0xffffff, 260, "Cancel", 155, true); } } if (loginScreenState == 3) { // New User boldFont.drawCenteredText(0xffff00, 180, "Create a free account", 40, true); boldFont.drawCenteredText(0xffffff, 180, "To create a new account you need to", 65, true); boldFont.drawCenteredText(0xffffff, 180, "go back to the main RuneScape webpage", 80, true); boldFont.drawCenteredText(0xffffff, 180, "and choose the red 'create account'", 95, true); boldFont.drawCenteredText(0xffffff, 180, "button at the top right of that page.", 110, true); titleButton.drawIndexedSprite(107, 130); boldFont.drawCenteredText(0xffffff, 180, "Cancel", 155, true); } leftCanvas.drawGraphics(171, super.graphics, 202); if (welcomeScreenRaised) { welcomeScreenRaised = false; topLeftCanvas.drawGraphics(0, super.graphics, 128); bottomLeftCanvas.drawGraphics(371, super.graphics, 202); titleBoxLeftCanvas.drawGraphics(265, super.graphics, 0); bottomRightCanvas.drawGraphics(265, super.graphics, 562); smallLeftCanvas.drawGraphics(171, super.graphics, 128); smallRightCanvas.drawGraphics(171, super.graphics, 562); } }
8
public void resetDirection(Direction d){ if (d == null){ return; } switch(d){ case EAST: moveRight = true; break; case NORTH: moveUp = true; break; case SOUTH: moveUp = false; break; case WEST: moveRight = false; break; } }
5
private void processGridlet(Sim_event ev, int type) { int gridletId = 0; int userId = 0; try { // if a sender using gridletXXX() methods int data[] = (int[]) ev.get_data(); gridletId = data[0]; userId = data[1]; } // if a sender using normal send() methods catch (ClassCastException c) { try { Gridlet gl = (Gridlet) ev.get_data(); gridletId = gl.getGridletID(); userId = gl.getUserID(); } catch (Exception e) { System.out.println(super.get_name() + ": Error in processing Gridlet"); System.out.println( e.getMessage() ); return; } } catch (Exception e) { System.out.println(super.get_name() + ": Error in processing a Gridlet."); System.out.println( e.getMessage() ); return; } // begins executing .... switch (type) { case GridSimTags.GRIDLET_CANCEL: policy_.gridletCancel(gridletId, userId); break; case GridSimTags.GRIDLET_PAUSE: policy_.gridletPause(gridletId, userId, false); break; case GridSimTags.GRIDLET_PAUSE_ACK: policy_.gridletPause(gridletId, userId, true); break; case GridSimTags.GRIDLET_RESUME: policy_.gridletResume(gridletId, userId, false); break; case GridSimTags.GRIDLET_RESUME_ACK: policy_.gridletResume(gridletId, userId, true); break; default: break; } }
8
public static void searchForWord(String text, JLabel jlbempty) { InputStream stream = HangManCore.class.getResourceAsStream(text); int lines = 0; Random lineGen = new Random(); try { lines = countLines(stream); } catch (IOException e1) { logger.log(Level.WARNING, "Could not count lines in file: words.txt", e1); ; } int linePicked = lineGen.nextInt(lines); try { stream = HangManCore.class.getResourceAsStream("words.txt"); LineNumberReader br = new LineNumberReader(new InputStreamReader( stream)); String strLine = null; int line = 0; int strLenght = 0; while ((strLine = br.readLine()) != null) { line = line + 1; if (line == linePicked) { strLenght = strLine.length(); new KeyChecker(strLenght); char[] words = splitWordChar(strLine); word = words; Screen.print(words, jlbempty, strLenght, true, false); System.out.print("\n" + linePicked + " - " + strLine + " ("+ strLenght + ")"); logger.log(Level.CONFIG, linePicked + " - " + strLine + " (" + strLenght + ")"); Text = strLine; rline = linePicked; lenght = strLenght; } } } catch (Exception e2) { logger.log(Level.WARNING, "Could not generate random word", e2); } }
4
public static void Command(CommandSender sender) { if(sender.hasPermission("gm.creative.all")) { for(Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.getGameMode() != GameMode.CREATIVE) { player.setGameMode(GameMode.CREATIVE); if(sender instanceof Player) { me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Changed Target GameMode").toString(), sender, (Player) sender, player, true, false, false, null); me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Player Changed Your GameMode").toString(), sender, (Player) sender, player, false, true, false, null); } else { me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Changed Target GameMode").toString(), sender, null, player, true, false, false, null); me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Player Changed Your GameMode").toString(), sender, null, player, false, true, false, null); } } else { if(sender instanceof Player) me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Target Already in GameMode").toString(), sender, (Player) sender, player, true, false, false, null); else me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Target Already in GameMode").toString(), sender, null, player, true, false, false, null); } } } else { if(sender instanceof Player) me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.No Permission").toString(), sender, (Player) sender, null, true, false, false, null); else me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.No Permission").toString(), sender, null, null, true, false, false, null); } }
6
public SetModeFiring(){ super(Color.FIRING); }
0
@Override protected double calcFitness() { double invalidColoredEdges = 0; for(int i = 0; i<this.getGenotype().length; i++ ) { int fromNode = phenotype.getEdges()[0][i] - 1; int toNode = phenotype.getEdges()[1][i] - 1; if( (this.getGenotype()[ fromNode ]).getValue() % this.maxColor == (this.getGenotype()[ toNode ]).getValue() % this.maxColor) invalidColoredEdges++; } if( invalidColoredEdges == 0 ) isValidColoring = true; return (1 - ( this.maxColor / (double) phenotype.getNumNodes() ) - ( invalidColoredEdges / (double) this.getGenotype().length )) / 2.0; }
3
public static boolean isRectangleDimension(boolean[][] matrix) { if(matrix == null) return false; int width = matrix[0].length; for(int row = 0; row < matrix.length; row++) { if(width != matrix[row].length) return false; } return true; }
3
public boolean ChangeState() { if ((this.GetBaseItem().Interaction.equals("default") || this.GetBaseItem().Interaction.equals("gate")) && (this.GetBaseItem().InteractionModesCount > 1)) { if (ExtraData.isEmpty()) { ExtraData = "0"; } Integer Temp = Integer.parseInt(ExtraData) + 1; if (Temp >= this.GetBaseItem().InteractionModesCount) { ExtraData = "0"; } else { ExtraData = "1"; } return true; } else { return false; } }
5
private void roundToHtml(StringBuffer buf, int round) { // array of results below buttons buf.append("<div>"); buf.append("<div style=\"width: 200px; height: 40px; text-align: center;font-size: 25px; font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">" + "Round #" + round + "</div>\n"); // empty up left square buf.append(" <div style=\"width: 34px; height: 40px; float:left;\"></div>\n"); // color squares for (int c = 0; c < FRUIT_NAMES.length; c++) { String color = FRUIT_COLORS[c]; String cname = Character.toString((char)(65+c)); buf.append("<div style=\"width: 34px; height: 40px; font-size:20px; font-weight:bold;font-family:'Comic Sans MS', cursive, sans-serif;text-align:center;float:left; border: 1px solid black; background-color: " + color + "\">" + cname + "</div>\n"); } // empty up right square buf.append(" <div style=\"width: 34px; height: 40px; float:left;\"></div>\n"); buf.append(" <div style=\"clear:both;\"></div>\n"); // result lines for (int p = 0 ; p != players.length ; ++p) { // player name buf.append(" <div style=\"width: 34px; height: 40px; float:left; border: 1px solid black; text-align: center;"); if (round == this.round && p == currentPlayer) buf.append("background-color:green;"); // indicate current player is moving buf.append("\n"); buf.append(" font-size: 20px; font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">" + players[p].name + "</div>\n"); int total = 0; buf.append(" <div style=\"width: 432px; height: 40px; float: left; border: 1px solid black;\">\n"); for (int r = 0 ; r != FRUIT_NAMES.length ; ++r) { String s; if (bowlOfPlayer[round][p] == null) s = "-"; else { s = Integer.toString(bowlOfPlayer[round][p][r]); total += bowlOfPlayer[round][p][r] * preference[p][r]; } buf.append(" <div style=\"width: 36px; height: 40px; float:left; text-align: center; font-size: 20px;\n"); buf.append(" font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">" + s + "</div>\n"); } buf.append(" </div>\n"); // score buf.append(" <div style=\"width: 36px; height: 40px; float:left; border: 1px solid black; text-align: center;\n"); buf.append(" font-size: 20px; font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">" + total + "</div>\n"); buf.append(" <div style=\"clear:both;\"></div>\n"); } // close result array buf.append(" </div>\n"); }
6
public void setRankcap(String cap) { if (cap.compareTo("12")==0) this.LevelUnlocked = 0; else if (cap.compareTo("11")==0) this.LevelUnlocked = 0; else if (cap.compareTo("10")==0) this.LevelUnlocked = 1; else if (cap.compareTo("9")==0) this.LevelUnlocked = 2; else if (cap.compareTo("6")==0) this.LevelUnlocked = 3; else if (cap.compareTo("3")==0) this.LevelUnlocked = 4; }
6
static boolean isPrime(long n) { if (n < 2) return false; if (n == 2 || n == 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; long sqrtN = (long) Math.sqrt(n) + 1; for (long i = 6L; i <= sqrtN; i += 6) { if (n % (i - 1) == 0 || n % (i + 1) == 0) return false; } return true; }
8
protected void setModelProperty(String propertyName, Object newValue) { for (AbstractModel model : registeredModels) { try { Method method = model.getClass().getMethod( "set" + propertyName, new Class[] { newValue.getClass() }); method.invoke(model, newValue); } catch (Exception ex) { LOG.error(ex); } } }
2
@Test public void testResetWorld() { System.out.println("resetWorld"); World instance = new World(); instance.generateRandomContestWorld(); instance.resetWorld(); }
0
public synchronized void close() { try { if (!isInterrupted()) interrupt(); } catch (Exception exc) { exc.printStackTrace(); } try { if (socket != null) socket.close(); } catch (Exception exc) { exc.printStackTrace(); } try { if (out != null) out.close(); } catch (Exception exc) { exc.printStackTrace(); } try { if (in != null) in.close(); } catch (Exception exc) { exc.printStackTrace(); } if (this.regLevel != -1) { this.regLevel = -1; //for (int i = listeners.length - 1; i >= 0; i--) //listeners[i].onDisconnected(); } socket = null; in = null; out = null; }
9
@Override public void onEnable() { instance = this; ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager(); ConfigurationSerialization.registerClass(PlayerConfiguration.class, "PlayerConfig"); //noinspection unchecked censorWords = (List<String>) getConfig().getList("censor.words"); enabledByDefault = getConfig().getBoolean("defaults.enabledOnFirstJoin"); ConfigurationSection section = getConfig().getConfigurationSection("censor.players"); if (section != null) { Map<String, Object> playersTmp = getConfig().getConfigurationSection("censor.players").getValues(false); for (Map.Entry<String, Object> entry : playersTmp.entrySet()) players.put(entry.getKey(), (PlayerConfiguration) entry.getValue()); } getConfig().options().copyDefaults(true); saveConfig(); protocolManager.addPacketListener(new PacketInterceptor(this)); getCommand("filterme").setExecutor(new CommandCensorToggle()); }
2
public ResultSet listeMetaDonneesParTitre(String titre) { Connection connexion; java.sql.Statement requete; ResultSet resultat = null; try { Class.forName("org.sqlite.JDBC"); connexion = DriverManager.getConnection("jdbc:sqlite:dbged"); requete = connexion.createStatement(); resultat = requete.executeQuery("select * from images where nom='" + titre + "'"); } catch (Exception e) { e.printStackTrace(); } return resultat; }
1
private List<RelationInstance> run(String normalizedSentence) throws FileNotFoundException, UnsupportedEncodingException { List<RelationInstance> instances = null; try { instances = relationExtraction.extractRelations(normalizedSentence); } catch(Exception e){ e.printStackTrace(); System.out.println("Resuming..."); } if(instances!=null && instances.size()>0){ for(RelationInstance instance : instances){ System.out.println("Instance: " + instance.getOriginalRelation()); for(Argument arg : instance.getArguments()){ System.out.println("\tArg: [" + arg.getEntityName() +"] - Type: " + arg.getArgumentType()); } } } return instances; }
5
private Vehicle createRandomVehicle(List<Cell> possibleLocations, Direction dir, int length) { int numIterations = 0; // limit iterations to prevent infinite loop if conditions cannot possibly be met while (numIterations < 1000) { // generate random r,g,b values for vehicle color int red = rand.nextInt(256), green = rand.nextInt(256), blue = rand.nextInt(256); // prevent the color from being too gray which would blend in with the background while (red - green < 20 && red - blue < 20) { red = rand.nextInt(256); green = rand.nextInt(256); blue = rand.nextInt(256); } // if invalid length, generate random length if (length < MIN_CAR_LENGTH) length = rand.nextInt(MAX_CAR_LENGTH - MIN_CAR_LENGTH + 1) + MIN_CAR_LENGTH; // create the random vehicle Vehicle newCar = new Vehicle( possibleLocations.get(rand.nextInt(possibleLocations.size())), length, new Color(red, green, blue), dir); // check all of the cells underneath vehicle to make sure they are unoccupied and on the board boolean locationValid = true; List<Cell> vehicleCells = getVehicleCells(newCar); for(int j = 0; j < vehicleCells.size(); j++) { Cell vehicleCell = vehicleCells.get(j); if (vehicleCell == null || vehicleCell.isOccupied() || vehicleCell.getRow() == exitCell().getRow()) { // this cell already has a vehicle over it, location is not valid locationValid = false; break; } } if (locationValid){ // if none of the cells are occupied then location is valid return newCar; } numIterations++; } return null; }
9
public void move(int xa, int ya) { if (xa != 0 && ya != 0) { move(xa, 0); move(0, ya); return; } if (xa > 0) dir = 1; if (xa < 0) dir = 3; if (ya > 0) dir = 2; if (ya < 0) dir = 0; if (!collision(xa, ya)) { // System.out.println("collision not detected!"); x += xa; y += ya; } }
7
@Override public void start(Stage primaryStage) { //eigen getter & setter DoubleProperty a = new SimpleDoubleProperty(5); System.out.println("De waarde van a is :" + a.get()); a.set(2); System.out.println("De waarde van a is nu : " + a.get()); System.out.println(); //listeners toevoegen StringProperty name = new SimpleStringProperty("Jan"); name.addListener(new InvalidationListener() { @Override public void invalidated(Observable o) { System.out.println("Name is aangepast"); } }); name.addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> ov, String oldValue, String newValue) { System.out.println("Name is aangepast van " + oldValue + "naar " + newValue); } }); name.set("Piet"); name.set("Mieke"); System.out.println(); IntegerProperty b = new SimpleIntegerProperty(2); NumberBinding c = b.add(3).multiply(2); // bindings via fluent api System.out.println("c begint op " + c.intValue()); b.set(3); System.out.println("c is nu " + c.intValue()); //bindings maken IntegerProperty d = new SimpleIntegerProperty(2); IntegerProperty e = new SimpleIntegerProperty(3); NumberBinding f = Bindings.when(d.greaterThan(e)).then(d).otherwise(e); System.out.println("f begint op" + f.intValue()); d.set(4); System.out.println("f is nu" + f.intValue()); System.out.println(); final IntegerProperty g = new SimpleIntegerProperty(1); BooleanBinding isgEven = new BooleanBinding() { { super.bind(g); } @Override protected boolean computeValue() { return g.get() % 2 == 0; } }; System.out.println("is g even ?" + isgEven.get()); System.out.println("is g nu even?" + isgEven.get()); ObservableList<String> namen = FXCollections.observableArrayList(); namen.addListener(new ListChangeListener<String>() { @Override public void onChanged(ListChangeListener.Change<? extends String> change) { while (change.next()) { if (change.wasAdded()) { System.out.println("zijn toegevoegd : " + change.getAddedSubList()); } if (change.wasRemoved()) { System.out.println("zijn verwijderd : " + change.getRemoved()); } } } }); namen.addAll("Jan", "Piet"); namen.remove("Piet"); Platform.exit(); }
5
public ArrayList<Planet>getPlanets() { ArrayList<Planet>p = new ArrayList<Planet>(); for(int i = 0; i < sprites.size(); i++){ if(sprites.get(i) instanceof Planet)p.add((Planet) sprites.get(i)); } return p; }
2
private static void compareMatches( byte[] matchData, Match[] matches ) throws MVDTestException { int pos = 0; while ( pos < matchData.length ) { Match match = new Match( matchData, pos ); System.out.println(match); for ( int i=0;i<matches.length;i++ ) { if ( !matches[i].isFound() ) { if ( matches[i].equals(match) ) { matches[i].setFound( true ); break; } } } pos += match.getSrcLen(); } for ( int i=0;i<matches.length;i++ ) if ( !matches[i].isFound() ) throw new MVDTestException("Match "+matches[i]+" not found"); }
6
DeviceImpl (USB bus, String drivername, int a) throws IOException, SecurityException { super (null, bus, a); usb = bus; path = drivername;//f.getPath (); // should only fail if the device unplugged before // we opened it, or permissions were bogus, or ... if ((fd = openNative (path)) < 0) { String message; message = "can't open device file r/w, " + path; /* if (fd == -USBException.EPERM) throw new SecurityException (message); else */ throw new USBException (message, -fd); } int num_descriptor_retries = 0; IOException descriptor_exception = null; do { // fd's open; NOW we can get the device descriptor try { byte buf []; buf = ControlMessage.getStandardDescriptor (this, Descriptor.TYPE_DEVICE, (byte) 0, 0, 18); descriptor = new DeviceDescriptor (this, buf); // ... and configuration descriptor getConfiguration (); if (Windows.trace) System.err.println ("new: " + path); return; } catch (USBException ue) { if (Windows.debug) ue.printStackTrace (); else if(Windows.trace) System.err.println ("get dev descr fail: " + path + ", " + ue.getMessage ()); descriptor_exception = ue; } catch (IOException e) { if (Windows.debug) System.err.println ("get dev descr fail: " + path + ", " + e.getMessage ()); throw e; } } while ( num_descriptor_retries++ < 4 ); throw descriptor_exception; }
8
public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { StringBuffer sb = new StringBuffer(); appendAccess(access | ACCESS_CLASS, sb); AttributesImpl att = new AttributesImpl(); att.addAttribute("", "access", "access", "", sb.toString()); if (name != null) { att.addAttribute("", "name", "name", "", name); } if (signature != null) { att.addAttribute("", "signature", "signature", "", encode(signature)); } if (superName != null) { att.addAttribute("", "parent", "parent", "", superName); } att.addAttribute("", "major", "major", "", Integer.toString(version & 0xFFFF)); att.addAttribute("", "minor", "minor", "", Integer.toString(version >>> 16)); addStart("class", att); addStart("interfaces", new AttributesImpl()); if (interfaces != null && interfaces.length > 0) { for (int i = 0; i < interfaces.length; i++) { AttributesImpl att2 = new AttributesImpl(); att2.addAttribute("", "name", "name", "", interfaces[i]); addElement("interface", att2); } } addEnd("interfaces"); }
6
private void readLuminance() { int type = sourceImage.getType(); if (type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB) { int[] pixels = (int[]) sourceImage.getData().getDataElements(0, 0, width, height, null); for (int i = 0; i < picsize; i++) { int p = pixels[i]; int r = (p & 0xff0000) >> 16; int g = (p & 0xff00) >> 8; int b = p & 0xff; data[i] = luminance(r, g, b); } } else if (type == BufferedImage.TYPE_BYTE_GRAY) { byte[] pixels = (byte[]) sourceImage.getData().getDataElements(0, 0, width, height, null); for (int i = 0; i < picsize; i++) { data[i] = (pixels[i] & 0xff); } } else if (type == BufferedImage.TYPE_USHORT_GRAY) { short[] pixels = (short[]) sourceImage.getData().getDataElements(0, 0, width, height, null); for (int i = 0; i < picsize; i++) { data[i] = (pixels[i] & 0xffff) / 256; } } else if (type == BufferedImage.TYPE_3BYTE_BGR) { byte[] pixels = (byte[]) sourceImage.getData().getDataElements(0, 0, width, height, null); int offset = 0; for (int i = 0; i < picsize; i++) { int b = pixels[offset++] & 0xff; int g = pixels[offset++] & 0xff; int r = pixels[offset++] & 0xff; data[i] = luminance(r, g, b); } } else { throw new IllegalArgumentException("Unsupported image type: " + type); } }
9
public static StackEntry of(String descriptor, ConstPool pool) { if(!DescriptorUtils.isPrimitive(descriptor)) { return new StackEntry(StackEntryType.OBJECT, descriptor, pool); }else { char ret = descriptor.charAt(0); switch (ret) { case 'I': case 'Z': case 'S': case 'B': case 'C': return new StackEntry(StackEntryType.INT, descriptor); case 'F': return new StackEntry(StackEntryType.FLOAT, descriptor); case 'D': return new StackEntry(StackEntryType.DOUBLE, descriptor); case 'J': return new StackEntry(StackEntryType.LONG, descriptor); } } throw new RuntimeException("Unknown descriptor: " + descriptor); }
9
private void go(){ int[] p = new int[N]; for(int i=2;i<N;i++) p[i]=1; sieve(p); int count =0; int sum=0; for(int i=10;i<N;i++){ if(p[i] == 1 && trunLeft(i, p) && trunRight(i, p)){ count++; sum+=i; System.out.println(i); } if(count>=11) break; } System.out.println(sum); }
6
public static /*unsigned*/ char OPLRead(FM_OPL OPL, int a) { if ((a & 1) == 0) { /* status port */ return (char) ((OPL.status & (OPL.statusmask | 0x80)) & 0xFF); } /* data port */ switch (OPL.address) { case 0x05: /* KeyBoard IN */ if((OPL.type&OPL_TYPE_KEYBOARD)!=0) { if(OPL.keyboardhandler_r!=null) { return (char)OPL.keyboardhandler_r.handler(OPL.keyboard_param); } else { //Log(LOG_WAR,"OPL:read unmapped KEYBOARD port\n"); } } return 0; case 0x19: /* I/O DATA */ if((OPL.type&OPL_TYPE_IO)!=0) { if(OPL.porthandler_r!=null) { return (char)OPL.porthandler_r.handler(OPL.port_param); } else { //Log(LOG_WAR,"OPL:read unmapped I/O port\n"); } } return 0; case 0x1a: /* PCM-DATA */ return 0; } return 0; }
8
private static ConsumerManager getConsumerManager() { try { if (consumerManager == null) { consumerManager = new ConsumerManager(); consumerManager.setAssociations(new InMemoryConsumerAssociationStore()); consumerManager.setNonceVerifier(new InMemoryNonceVerifier(10000)); } } catch (Exception e) { String message = "Exception creating ConsumerManager!"; log.error(message, e); throw new RuntimeException(message, e); } return consumerManager; }
2
public static int addContestant(Contestant c) { if (NUM_TEST_CONTESTANTS > list.size()) { if (isIDValid(c.getID())) list.add(c); else return -1; } else { return -2; } return 0; }
2
@RequestMapping(value = "/before-event-comment-list/{hallEventId}", method = RequestMethod.GET) @ResponseBody public EventCommentListResponse beforeEventCommentList( @PathVariable(value = "hallEventId") final String hallEventIdStr ) { Boolean success = true; String errorMessage = null; List<EventComment> eventCommentList = null; Long hallEventId = null; try { hallEventId = controllerUtils.convertStringToLong(hallEventIdStr, true); eventCommentList = specialityPresenter.findBeforeEventCommentsByHallEventId(hallEventId); } catch (UrlParameterException e) { success = false; errorMessage = "Hall event ID is wrong or empty"; } return new EventCommentListResponse(success, errorMessage, eventCommentList); }
1
private String Complement(String binaryString) { StringBuilder complementBuilder = new StringBuilder(binaryString); for(int i = 0; i < binaryString.length(); ++i) { char flip = binaryString.charAt(i) == '0' ? '1' : '0'; complementBuilder.setCharAt(i, flip); } return complementBuilder.toString(); }
2
public static double[][] rotation3D(double[] axis, double angle) { double[][] res = new double[3][3]; if (axis.length == 3) { double nx = axis[0]; double ny = axis[1]; double nz = axis[2]; double cos = Math.cos(angle); double sin = Math.sin(angle); res[0][0] = nx*nx*(1 - cos) + cos; res[1][0] = nx*ny*(1 - cos) - nz*sin; res[2][0] = nx*nz*(1 - cos) + ny*sin; res[0][1] = nx*ny*(1 - cos) + nz*sin; res[1][1] = ny*ny*(1 - cos) + cos; res[2][1] = ny*nz*(1 - cos) - nx*sin; res[0][2] = nx*nz*(1 - cos) - ny*sin; res[1][2] = ny*nz*(1 - cos) + nx*sin; res[2][2] = nz*nz*(1 - cos) + cos; } return toHomogeneousCoordinates(res); }
1
@Override protected Class<?> findClass(final String name) throws ClassNotFoundException { final java.io.InputStream in; final int size; final JarFile jarFile; assert this.cp.length >= 1; final Lookup found = find(name.split("\\."), ".class"); if (found == null) { return null; } in = found.in; size = found.size; jarFile = found.jarFile; assert in != null; if (this.buffer.length < size) { this.buffer = new byte[(size & 0xffff_ff00) + 0x100]; } try { int offset = in.read(this.buffer); while (offset < size) { offset += in.read(this.buffer, offset, size - offset); } } catch (final IOException e) { e.printStackTrace(); System.out.printf("findClass(%s)\n", name); return null; } try { in.close(); } catch (final IOException e) { e.printStackTrace(); } if (jarFile != null) { try { jarFile.close(); } catch (final IOException e) { e.printStackTrace(); } } final Class<?> c = defineClass(name, this.buffer, 0, size); this.map.put(name, c); return c; }
9
@Override public boolean preLoadBuffers( LinkedList<byte[]> bufferList ) { // Stream buffers can only be queued for streaming sources: if( errorCheck( channelType != SoundSystemConfig.TYPE_STREAMING, "Buffers may only be queued for streaming sources." ) ) return false; // Make sure we have a SourceDataLine: if( errorCheck( sourceDataLine == null, "SourceDataLine null in method 'preLoadBuffers'." ) ) return false; sourceDataLine.start(); if( bufferList.isEmpty() ) return true; // preload one stream buffer worth of data: byte[] preLoad = bufferList.remove( 0 ); // Make sure we have some data: if( errorCheck( preLoad == null, "Missing sound-bytes in method 'preLoadBuffers'." ) ) return false; // If we are using more than one stream buffer, pre-load the // remaining ones now: while( !bufferList.isEmpty() ) { streamBuffers.add( new SoundBuffer( bufferList.remove( 0 ), myFormat ) ); } // Pre-load the first stream buffer into the dataline: sourceDataLine.write( preLoad, 0, preLoad.length ); processed = 0; return true; }
5
protected static Ptg calcMode( Ptg[] operands ) { Ptg[] alloperands = PtgCalculator.getAllComponents( operands ); Vector vals = new Vector(); Vector occurences = new Vector(); double retval = 0; for( Ptg p : alloperands ) { try { Double d = new Double( String.valueOf( p.getValue() ) ); if( vals.contains( d ) ) { int loc = vals.indexOf( d ); Double nums = (Double) occurences.get( loc ); Double newnum = nums + 1; occurences.setElementAt( newnum, loc ); } else { vals.add( d ); occurences.add( (double) 1 ); } } catch( NumberFormatException e ) { } ; } double biggest = 0; double numvalues = 0; for( int i = 0; i < vals.size(); i++ ) { Double size = (Double) occurences.elementAt( i ); if( size > biggest ) { biggest = size; Double newhigh = (Double) vals.elementAt( i ); retval = newhigh; } } PtgNumber pnum = new PtgNumber( retval ); return pnum; }
5
@SuppressWarnings("unchecked") private <S> ServiceProviderInfo<S> findProviderInfo(Class<S> serviceClass) { ServiceProviderInfo<S> result; // Try to avoid synchronization by looking in our thread-local cache, // which is just a (potential) subset of the global service provider // class cache. If not found here, proceed if (threadServiceProviderInfoCache.get()!=null) { result=threadServiceProviderInfoCache.get().get(serviceClass); if (result!=null) { return result; } } synchronized (SERVICE_PROVIDER_INFO) { result=SERVICE_PROVIDER_INFO.get(serviceClass); if (result!=null) { updateThreadServiceProviderClassCache(); return result; } // TODO: Do we want to think about using Thread's context class // loader for those cases where the Services instance may be // instantiated more than once? Right now, there is only a single // global instance, so our own class loader should be sufficient. // Also, consider that the context class loader would only be // appropriate for request-scoped services. List<Class<? extends S>> providerClasses= findProviders(serviceClass,getClass().getClassLoader()); // We have a bit of a problem here, since there is no guarantee // that the one provider that we choose to return will be // instantiatable. Take a chance for now and solve this problem // later. (We might want to introduce an annotation of the priority // so that we can look for providers in a particular order.) for (Class<? extends S> providerClass: providerClasses) { ServiceProvider annotation= providerClass.getAnnotation(ServiceProvider.class); if (annotation!=null) { result=new ServiceProviderInfo<S>( serviceClass,providerClass); // Cache the provider class so we can create more // instances later SERVICE_PROVIDER_INFO.put(serviceClass,result); updateThreadServiceProviderClassCache(); // Put a copy on the local thread's cache break; } else { // Ignore implementation class because it's not annotated System.out.println("Ignoring service provider class "+ providerClass.getName()+" for service "+ serviceClass.getName()+" because it has not been "+ "annotated as a provider. See "+ ServiceProvider.class.getName()+"."); } } return result; } }
7
@Override public void start(Stage stage) throws Exception { buildComponents(); stage.setScene(scene); stage.show(); animate(); explodeAnimate(); Task<Object> t = new Task<Object>() { @Override protected Object call() throws Exception { double i = 0.0; while (i < 1) { try { Thread.sleep((long) (Math.random() * 5000)); i += 0.1; update(i); } catch (InterruptedException ex) { Logger.getLogger(Loading.class.getName()).log( Level.SEVERE, null, ex); } } return null; } }; Thread th = new Thread(t); th.start(); }
2
public void handleSeeds(int seedId, WorldObject object) { /*if (!canPlantSeeds(player, object)) { player.getPackets().sendGameMessage("You must clear the weeds before you may plant some seeds here."); return; }*/ for (PatchStatus patch : player.getFarmingPatches()) { if (patch.getObjectId() == object.getId()) { player.getPackets().sendGameMessage("There is already something growing here."); return; } } for (Seeds.Seed seed : Seeds.Seed.values()) { if (seedId == seed.getItem().getId()) { if (player.getSkills().getLevel(Skills.FARMING) < seed.getLevel()) { player.getPackets().sendGameMessage("You need at least "+seed.getLevel()+" Farming in order to plant this."); return; } ObjectDefinitions defs = ObjectDefinitions.getObjectDefinitions(seedId); if (!player.getInventory().containsItem(seed.getItem().getId(), seed.getItem().getAmount())) { player.getPackets().sendGameMessage("You need at least "+seed.getItem().getAmount()+" "+defs.name+"'s."); return; } for (int i = 0; i < seed.getSuitablePatch().length; i++) { if (seed.getSuitablePatch()[i] == object.getId()) { player.getPackets().sendGameMessage("You plant some "+defs.name+"'s."); player.getSkills().addXp(Skills.FARMING, seed.getPlantXP()); player.getInventory().deleteItem(seed.getItem()); player.setNextAnimation(new Animation(2291)); player.getFarmingPatches().add(new PatchStatus(object.getId(), object.getDefinitions().configFileId, seed.getConfigValues()[0], seed.getConfigValues()[4], "Some "+defs.name+"'s have been planted here.")); startGrowth(object, seed.getTime() / 2); } } } } }
8
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Map<String, String[]> requestParameters = req.getParameterMap(); String uri = url.toString(); Query query = null; PostMethod proxyMethod = new PostMethod(uri); for (String name : requestParameters.keySet()) { for (String value : requestParameters.get(name)) { if ("query".equals(name)) query = new Query(value); // TODO determine what subscriptions can be affected by this // query // query.subscriptionsImpact proxyMethod.addParameter(name, value); } } if (query != null) { query.setStartTime(System.currentTimeMillis()); LOGGER.debug(query.getQuery()); } proxy.executeMethod(proxyMethod); if (query != null) { query.setEndTime(System.currentTimeMillis()); Queries.getInstance().addQuery(query); LOGGER.debug("duration:" + (query.getEndTime() - query.getStartTime())); } write(proxyMethod.getResponseBodyAsStream(), resp.getOutputStream()); proxyMethod.releaseConnection(); }
5
protected void readLines(String fileText) { rows.clear(); try { CsvReader csvReader = initializeReader(new StringReader(fileText)); // case when the first line is the encoding if (!displayFirstLine) { csvReader.skipLine(); } boolean setHeader = false; while (csvReader.readRecord()) { String[] rowValues = csvReader.getValues(); CSVRow csvRow = new CSVRow(rowValues, this); if (!rowValues[0].startsWith(String.valueOf(getCommentChar()))) { if (isFirstLineHeader() && !setHeader) { setHeader = true; csvRow.setHeader(true); populateHeaders(rowValues); } } else { csvRow.setCommentLine(true); } rows.add(csvRow); if (rowValues.length > nbOfColumns) { nbOfColumns = rowValues.length; } } if (!isFirstLineHeader()) { populateHeaders(null); } csvReader.close(); } catch (Exception e) { System.out.println("exception in readLines " + e); e.printStackTrace(); } }
8
private boolean saveStory() { boolean XMLProject = true; // make a proj file JFileChooser j = new JFileChooser(); j.setSelectedFile(new File(map.getStory().getName())); j.setDialogTitle("Select a location to save the project"); j.setAcceptAllFileFilterUsed(false); j.setFileFilter(new ExtensionFileFilter( new String[]{".PROJ"}, "*.iStory.proj")); int dialog = j.showSaveDialog(this); // Catch actions of the File Chooser Dialog Window if (dialog == JFileChooser.APPROVE_OPTION) { try { String XMLcontent = this.story.printXML(XMLProject); this.story.setPrinted(false); // Add no linked nodes at the end XMLcontent += this.map.printNodeXML(); String filePathName = j.getSelectedFile().toString(); // Add ".iStory.proj at the end of the string (only if it not exists) if (!filePathName.endsWith(".iStory.proj")) { filePathName += ".iStory.proj"; } /* XML */ // Create an XML-file File projectFile = new File(filePathName); // Check if the iStory file already exists boolean exists = projectFile.createNewFile(); if (!exists) { // Confirm the save int option = JOptionPane.showConfirmDialog(null, "There is already a file with the same name in the selected folder. \n " + "Do you want to overwrite this file?", "File already exists", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (option == JOptionPane.YES_OPTION) { projectFile.delete(); } else if (option == JOptionPane.NO_OPTION) { saveStory(); return false; } else if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) { return false; } } FileWriter fstream = new FileWriter(filePathName); BufferedWriter out = new BufferedWriter(fstream); out.write(XMLcontent); out.close(); JOptionPane.showMessageDialog( Main.this, "The project has been saved", "Saved succes..", JOptionPane.INFORMATION_MESSAGE); // Set the changed to false to be able to close the program story.setSomethingChanged(false); return true; } catch (IOException ioe) { LOGGER.log(Level.SEVERE, "Input- Output exception: {0}", ioe); return false; } } return false; }
8
public SimpleStringProperty titleProperty() { return title; }
0
public Node getParent() { return this.parent; }
0
public final LatticeIF getImplementation(final LatticeType type) { switch(type) { case SHORT_RATE: { this.implementation = new ShortRateLatticeImpl(); break; } case ZERO_COUPON_BOND: { this.implementation = new ZeroCouponBondLatticeImpl(); break; } case AMER_CALL_ZERO: { this.implementation = new AmericanCallZeroLatticeImpl(); break; } case BOND_FORWARD: { this.implementation = new BondForwardImpl(); break; } case BOND_FUTURES: { this.implementation = new BondFuturesImpl(); break; } case SWAP: { this.implementation = new SwapImpl(); break; } case SWAPTION: { this.implementation = new SwaptionImpl(); break; } default: { System.err.println("No approriate implementation."); break; } } // switch ( searchType ) return this.implementation; }
7
@Override public void run() { try { for (int i = 0; i < 1; ++i) { Integer number = new Integer(rand.nextInt(20)); // System.out.println("probuje wstawic liczbe " + number); lista.add(number); } for (int i = 0; i < 1; ++i) { Integer number = new Integer(rand.nextInt(20)); // System.out.println("szukam liczby " + number); lista.contains(number); } for (int i = 0; i <1; ++i) { Integer number = new Integer(rand.nextInt(20)); // System.out.println("usuwam liczbe " + number); lista.remove(number); } } catch (InterruptedException e) { } }
4
public Meter(HtmlMidNode parent, HtmlAttributeToken[] attrs){ super(parent, attrs); for(HtmlAttributeToken attr:attrs){ String v = attr.getAttrValue(); switch(attr.getAttrName()){ case "form": form = Form.parse(this, v); break; case "high": high = High.parse(this, v); break; case "low": low = Low.parse(this, v); break; case "max": max = Max.parse(this, v); break; case "min": min = Min.parse(this, v); break; case "optimum": optimum = Optimum.parse(this, v); break; case "value": value = Value.parse(this, v); break; } } }
8
@Override protected void paintLevel() { super.paintLevel(); Level level = getState().getLevel(); World world = getState().getWorld(); if (passableImage == null) { BufferedImage image = new BufferedImage(getScreen() .getScreenWidth(), getScreen().getScreenHeight(), BufferedImage.TYPE_4BYTE_ABGR); BufferedImage adjacencyImage = new BufferedImage(getScreen() .getScreenWidth(), getScreen().getScreenHeight(), BufferedImage.TYPE_4BYTE_ABGR); Graphics2D imGfx = image.createGraphics(); imGfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Graphics2D imAdjacencyGfx = adjacencyImage.createGraphics(); imAdjacencyGfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); double testRadius = getScreen().screenToWorldDistance(10); // 10 // screen // pixels double stepSize = getScreen().screenToWorldDistance(3); // 3 screen // pixels for (double x = testRadius; x <= level.getWorldWidth() - testRadius; x += stepSize) { for (double y = testRadius; y <= level.getWorldHeight() - testRadius; y += stepSize) { double randomizedX = x + (-0.5 + Math.random()) * stepSize * 2; double randomizedY = y + (-0.5 + Math.random()) * stepSize * 2; Graphics2D targetGraphics = imGfx; boolean isPassable = false; if (getFacade().isImpassable(world, randomizedX, randomizedY, testRadius)) { targetGraphics.setColor(new Color(255, 0, 0, 4)); } else if (getFacade().isAdjacent(world, randomizedX, randomizedY, testRadius)) { targetGraphics = imAdjacencyGfx; targetGraphics.setColor(new Color(0, 255, 0, 64)); } else { isPassable = true; targetGraphics.setColor(new Color(0, 0, 255, 4)); } if (!isPassable || PAINT_PASSABLE) { Double circle = GUIUtils.circleAt( getScreenX(randomizedX), getScreenY(randomizedY), getScreen() .worldToScreenDistance(testRadius)); targetGraphics.fill(circle); } } } imGfx.drawImage(adjacencyImage, 0, 0, null); imAdjacencyGfx.dispose(); imGfx.dispose(); this.passableImage = image; } currentGraphics.drawImage(passableImage, 0, 0, null); drawCrossMarker(getScreenX(0), getScreenY(0), 10, Color.BLUE); drawCrossMarker(getScreenX(0), getScreenY(getLevel().getWorldHeight()), 10, Color.BLUE); drawCrossMarker(getScreenX(getLevel().getWorldWidth()), getScreenY(0), 10, Color.BLUE); drawCrossMarker(getScreenX(getLevel().getWorldWidth()), getScreenY(getLevel().getWorldHeight()), 10, Color.BLUE); }
7
private void filtrarMedio(String texto, DefaultMutableTreeNode raizArbol, DefaultMutableTreeNode raizNegativa, boolean filtrar) { int artista, albumes, canciones; artista = albumes = canciones = 0; DefaultMutableTreeNode nodoArtista, nodoAlbum, nodoCancion; DefaultMutableTreeNode nodoArtistaClon, nodoAlbumClon, nodoCancionClon; boolean filtrando = false; artista = raizArbol.getChildCount(); for (int i = 0; i < artista; i++) { albumes = raizArbol.getChildAt(i).getChildCount(); for (int j = 0; j < albumes; j++) { canciones = raizArbol.getChildAt(i).getChildAt(j) .getChildCount(); for (int k = 0; k < canciones; k++) { nodoArtista = (DefaultMutableTreeNode) raizArbol .getChildAt(i); nodoAlbum = (DefaultMutableTreeNode) nodoArtista .getChildAt(j); nodoCancion = (DefaultMutableTreeNode) nodoAlbum .getChildAt(k); Archivo ar = (Archivo) nodoCancion.getUserObject(); String[] opciones = biblio .opcionesPorNombre("criterio-busqueda"); if (filtrar) {// si se esta filtrando... busque las que no // tengan coincidencias // filtrando = (ar.getNombreCortoArchivo().toLowerCase() // .indexOf(texto.toLowerCase()) < 0); filtrando = (ar.tieneEstosDatos(texto, opciones, filtrar)); } else {// si se esta quitando el filtro... busque las // que tengan coincidencias filtrando = (ar.getNombreCortoArchivo().toLowerCase() .indexOf(texto.toLowerCase()) >= 0); filtrando = (ar.tieneEstosDatos(texto, opciones, filtrar)); } if (filtrando) { /** * Copiar nodos de un arbol a otro */ nodoArtistaClon = (DefaultMutableTreeNode) nodoArtista .clone(); nodoAlbumClon = (DefaultMutableTreeNode) nodoAlbum .clone(); nodoCancionClon = (DefaultMutableTreeNode) nodoCancion .clone(); nodoArtistaClon = obtenerNodo(raizNegativa, nodoArtistaClon.toString()); if (nodoArtistaClon == null) { nodoArtistaClon = (DefaultMutableTreeNode) nodoArtista .clone(); raizNegativa.add(nodoArtistaClon); } nodoAlbumClon = obtenerNodo(nodoArtistaClon, nodoAlbumClon.toString()); if (nodoAlbumClon == null) { nodoAlbumClon = (DefaultMutableTreeNode) nodoAlbum .clone(); nodoArtistaClon.add(nodoAlbumClon); } nodoAlbumClon.add(nodoCancionClon); /** * Borrar los nodos copiados */ modeloArbol.removeNodeFromParent(nodoCancion); canciones--;// acortar el ciclo por que k--;// acabo de eliminar un nodo if (nodoAlbum.getChildCount() == 0) { modeloArbol.removeNodeFromParent(nodoAlbum); albumes--; j--; if (nodoArtista.getChildCount() == 0) { modeloArbol.removeNodeFromParent(nodoArtista); artista--; i--; } } } } } } // esto es necesario para actualizar la estructura del arbol modeloArbol.reload(); // esto expande todos los nodos del arbol expandirTodo(arbolPrincipal, true); }
9
private void setupHandListener() { textbBranchListener = new MouseAdapter() { @Override public void mouseMoved(MouseEvent e) { Cursor handCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); Cursor defaultCursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); JTextPane textPane = (JTextPane) e.getSource(); Point pt = new Point(e.getX(), e.getY()); int pos = textPane.viewToModel(pt); if (pos >= 0) { StyledDocument doc = textPane.getStyledDocument(); if (doc instanceof StyledDocument){ StyledDocument hdoc = (StyledDocument) doc; Element el = hdoc.getCharacterElement(pos); AttributeSet a = el.getAttributes(); String href = (String) a.getAttribute(HTML.Attribute.HREF); Integer branch = (Integer) a.getAttribute(HTML.Attribute.LINK); if (href != null || (branch != null && branch !=-1)){ if(getCursor() != handCursor){ textPane.setCursor(handCursor); } } else{ textPane.setCursor(defaultCursor); } } } } }; }
6
private void renderElement(XmlElement element) { if (element instanceof XmlTextElement) { System.out.println(String.format("RENDERING '%s' with formats %s", element.getText(), formatStack)); } else if (element instanceof XmlTagElement) { XmlTagElement tag = (XmlTagElement)element; switch(tag.getLabel()) { case "img": System.out.println("DISPLAYING PICTURE INLINE: " + tag.getAttributes().get("src")); return; case "i": formatStack.push(new Formatting(FormattingType.ITALIC, tag.getAttributes())); break; case "b": formatStack.push(new Formatting(FormattingType.BOLD, tag.getAttributes())); break; case "span": default: formatStack.push(new Formatting(FormattingType.SPAN, tag.getAttributes())); break; } if (tag.getChildren() != null) { for(XmlElement child : tag.getChildren().getElements()) { renderElement(child); } } formatStack.pop(); } }
8
private void drop(Point p) { if (b != null && player != null) { int zx = 0, zy = 0, px = 0; for (Item i : b.getItems()) { if (px > b.getTotal()) { return; } Rectangle r = new Rectangle(x + (zx * nWidth), y + (zy * nHeight), nWidth, nHeight); if (r.contains(p)) { player.getContainer().dropItem(i); return; } zx++; if (zx * nWidth >= width) { zx = 0; zy++; } px++; } } }
6
public Person4(String pname) { name = pname; }
0
public static AgentController createClientAgent() { try { ConditionalVariable startUpLatch = new ConditionalVariable(); Method m = ClientMainFrame.class.getMethod("onContainerFromAgent", Object.class); m.invoke(null, "s"); AgentController ac = containerController.createNewAgent("newClientAgent", "scit.diploma.client.ClientAgent", new Object[] {startUpLatch, m}); ac.start(); startUpLatch.waitOn(); ac.putO2AObject("String", AgentController.ASYNC); } catch (StaleProxyException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; }
5
public Station getStation() { return this._station; }
0
public static Map<String, Object> get(String filePath) { if (! filePath.endsWith(".json")) { filePath += ".json"; } if (jsonMap.containsKey(filePath)) { // Check if the file is cached. // If so, return the cached version of the file. return jsonMap.get(filePath); } else { try { @SuppressWarnings("unchecked") // We know that it will always be a Map<String, Object> Map<String, Object> data = parser.parseJson(new FileInputStream(filePath), "UTF-8"); jsonMap.put(filePath, data); return data; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; // If the try/catch block fails, then return null. The json could not be loaded. }
3
private static void translate(int tx, int ty) { ImageData imageData = original.getImageData(); int[][] two1 = new int[imageData.height][imageData.width]; for (int i = 0; i < imageData.height; i++) { for (int j = 0; j < imageData.width; j++) { two1[i][j] = imageData.getPixel(j, i); } } int w = imageData.width; int h = imageData.height; int ow = w + tx; int oh = h + ty; int[] one1 = ImageUtils.two2one(two1); int[] one2 = GT.translate(one1, tx, ty, w, h, ow, oh); int[][] two2 = ImageUtils.one2two(one2, ow, oh); imageData = new ImageData(ow, oh, 8, imageData.palette); for (int i = 0; i < oh; i++) { for (int j = 0; j < ow; j++) { imageData.setPixel(j, i, two2[i][j]); } } translate = new Image(original.getDevice(), imageData); translateHisto = ImageUtils.analyzeHistogram(translate.getImageData()); }
4