text
stringlengths
14
410k
label
int32
0
9
static void draw_sprites(osd_bitmap bitmap) { /* sprite information is scattered through memory */ /* and uses a portion of the text layer memory (outside the visible area) */ UBytePtr spriteram_area1 = new UBytePtr(spriteram, 0x28); UBytePtr spriteram_area2 = new UBytePtr(spriteram_2, 0x28); UBytePtr spriteram_area3 = new UBytePtr(kyugo_videoram, 0x28); int n; for (n = 0; n < 12 * 2; n++) { int offs, y, sy, sx, color; offs = 2 * (n % 12) + 64 * (n / 12); sx = spriteram_area3.read(offs + 1) + 256 * (spriteram_area2.read(offs + 1) & 1); if (sx > 320) { sx -= 512; } sy = 255 - spriteram_area1.read(offs); if (flipscreen != 0) { sy = 240 - sy; } color = spriteram_area1.read(offs + 1) & 0x1f; for (y = 0; y < 16; y++) { int attr2, code, flipx, flipy; attr2 = spriteram_area2.read(offs + 128 * y); code = spriteram_area3.read(offs + 128 * y); if ((attr2 & 0x01) != 0) { code += 512; } if ((attr2 & 0x02) != 0) { code += 256; } flipx = attr2 & 0x08; flipy = attr2 & 0x04; if (flipscreen != 0) { flipx = NOT(flipx); flipy = NOT(flipy); } drawgfx(bitmap, Machine.gfx[1], code, color, flipx, flipy, sx, flipscreen != 0 ? sy - 16 * y : sy + 16 * y, Machine.drv.visible_area, TRANSPARENCY_PEN, 0); } } }
8
private void saveMoveHistory(boolean won){ //Disregard games that didn't have any moves if (moves_in_round == 0) return; //Score how well the AI did this round //double fac = scoreMetric() - initialScore; //double rate = LEARN_RATE * fac; double rate = 0.01; if (rate > .0001){ //System.out.println("Training with "+drawHistory.size()+" instances"); //Train for drawing for (DataInstance d: drawHistory){ drawNet.compute(d.inputs); drawNet.trainBackprop(rate, (int) d.output); } //Train for playing for (DataInstance p: playHistory){ playNet.compute(p.inputs); playNet.trainBackprop(rate, (int) p.output); } } }
4
public static void main(String[] args) throws IOException { // write your code here int menu; do { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("1 - Create Author(s)\n2 - Create Publisher(s)\n3 - Quit"); try { menu = Integer.parseInt(br.readLine()); }catch (NumberFormatException ignore){ menu = 5; } switch (menu) { case 1: AuthorMenu authorMenu = new AuthorMenu(); authorMenu.readAuthors(); break; case 2: PublisherMenu publisherMenu = new PublisherMenu(); publisherMenu.readPublisher(); break; case 3: return; default: System.out.println("Invalid choice!"); } }while(true); }
5
public static JEditTextArea getTextArea(EventObject evt) { if(evt != null) { Object o = evt.getSource(); if(o instanceof Component) { // find the parent text area Component c = (Component)o; for(;;) { if(c instanceof JEditTextArea) return (JEditTextArea)c; else if(c == null) break; if(c instanceof JPopupMenu) c = ((JPopupMenu)c) .getInvoker(); else c = c.getParent(); } } } // this shouldn't happen System.err.println("BUG: getTextArea() returning null"); System.err.println("Report this to Slava Pestov <sp@gjt.org>"); return null; }
6
static boolean isThereAFour(Hand hand) { for (int z =0; z < hand.size();z++) {int count = 0; for(int y=0;y < hand.size();y++) { if (hand.get(z).getValue() == hand.get(y).getValue()) count++; if (count == 4) return true; // four of a kind }} return false; }
4
public int read() throws IOException { if (closed) { return 0; } else { return inputStream.read(); } }
1
void parseTargetStatistics(Element el) { this.targetStatistics = new ArrayList<Statistic>(); NodeList paramList = el.getElementsByTagName("targetStatistic"); // for each parameter for (int j = 0; j < paramList.getLength(); j++) { Node node = paramList.item(j); String name = ((Element)node).getAttributes().getNamedItem("name").getNodeValue(); String value = ((Element)node).getAttributes().getNamedItem("value").getNodeValue(); if (name.equals("calculateFromFile")) { String targetDataName = value; if (verbose) { System.out.println("Generating target statistics from file using "+modelType.getModelName()); System.out.println("Reading in data from "+targetDataName); } TraceFileReader trace = new TraceFileReader(); List<Double[]> targetData = trace.readData(targetDataName); if (verbose) { for (String h : trace.getHeader()) { System.out.println(h); } } modelType.calculateStatistics(targetData); targetStatistics = new ArrayList<Statistic>(); for (Statistic stat : modelType.getStatistics()) { // include nominal 10% tolerance ResultStatistic res = new ResultStatistic( stat.getName(), stat.getValue(), stat.getValue()*0.1); targetStatistics.add(res); } //targetStatistics = modelType.getStatistics(); if (verbose) { System.out.println("Calculated target statistics from trace file:"); for (Statistic stat : targetStatistics) { System.out.println("TargetStatistic = "+stat.toString()); } } } else { Double val = Double.parseDouble(value); String tolerance = ((Element)node).getAttributes().getNamedItem("tolerance").getNodeValue(); Double tol = Double.parseDouble(tolerance); Statistic ts = new ResultStatistic( name, val, tol ); this.targetStatistics.add(ts); if (verbose) { System.out.println("TargetStatistic = "+ts.toString()); } } } }
9
public void fire(){ Bullet bullet = new Bullet(this) ; if( this.direction == Tank.direction_up){ bullet.setLocation_x(this.location_x + this.width/2 - bullet.getWidth()/2 - 1); bullet.setLocation_y(this.location_y); }else if(this.direction == Tank.direction_down){ bullet.setLocation_x(this.location_x + this.width/2 - bullet.getWidth()/2 - 1); bullet.setLocation_y(this.location_y + this.height - 3); }else if(this.direction == Tank.direction_left){ bullet.setLocation_x(this.location_x); bullet.setLocation_y(this.location_y + this.width/2 - 1); }else if(this.direction == Tank.direction_right){ bullet.setLocation_x(this.location_x + this.height - 3); bullet.setLocation_y(this.location_y + this.width/2 - 1); } bullet.setDirection(direction); //set bullet type if( this.tank_type == Tank.HREO){ bullet.setType(Bullet.BULLET_HERO); }else{ bullet.setType(Bullet.BULLET_ENEMY); } bullet.setMainFrame(this.getMainFrame()); this.bullts.add(bullet); bullet.start(); //sound play if( this.tank_type == Tank.HREO){ SoundPlayFactory.getSoundByName("heroFire"); } }
6
private void prepareSpawn(){ if (time % spawnRate == 0){ if (maxSpawnCount > spawnCount){ spawn(mobsToSpawn); spawnCount++; wp.setLeft (maxSpawnCount - spawnCount); } } if (level % 10 == 0){ s.stopAmbient(); s.playBoss(); }else{ s.stopBoss(); s.playAmbient(); } if (maxSpawnCount <= spawnCount && mobs.size() == 0){ levelStart = false; spawnCount = 0; time = 0; level++; if (level == 51){ winGame(); return; } numMobs = data.getCurrentMaxSpawn(); numCreeps = 0; ui.setWaveData (0, nextElement, level); List <Tower> tempTower = getObjects (Tower.class); for (Tower t: tempTower){ t.setActive (false); } wp.reset(); } }
7
public void drawRaster(int[] p, int w, int h, int x, int y) { // Finds the bounds (in world space) of the pixels that are visible and are on the tile map final int startX = (x < 0) ? 0 : x; final int endX = (x + w > imageWidth) ? imageWidth : w + x; final int startY = (y < 0) ? 0 : y; final int endY = (y + h > imageHeight) ? imageHeight : h + y; int offset, i; // For each visible row in world space defined by the bounds above for (int row = startY; row < endY; row++) { // Calculate the position of the first pixel of the row on the view port offset = (row * imageWidth + startX); // For each pixel in the row for (i = 0; i < endX - startX; i++) { pixels[i + offset] = p[i]; } } }
6
private void loadPerson() { // TODO Auto-generated method stub Pendinng = Satisfied.getInstanceSatisfied().getPendingCompanyApplication(); fila = new Object[5]; for (int i = 0, j=1; i <Satisfied.getInstanceSatisfied().getPendingCompanyApplication().getCompanyApplications().size(); i++,j++) { fila[0] = i+1; fila[1] = Satisfied.getInstanceSatisfied().getPendingCompanyApplication().getCompanyApplication(i).getCompany().getRNC(); fila[2] = Satisfied.getInstanceSatisfied().getPendingCompanyApplication().getCompanyApplication(i).getCompany().getName(); fila[3] = Satisfied.getInstanceSatisfied().getPendingCompanyApplication().getCompanyApplication(i).getCompany().getArea(); fila[4] = Satisfied.getInstanceSatisfied().getPendingCompanyApplication().getCompanyApplication(i).getEmployeeCant(); tableModel.addRow(fila); tableModel.addRow(fila); } table.setModel(tableModel); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.getTableHeader().setReorderingAllowed(false); TableColumnModel columnModel = table.getColumnModel(); columnModel.getColumn(0).setPreferredWidth(70); columnModel.getColumn(1).setPreferredWidth(160); columnModel.getColumn(2).setPreferredWidth(240); columnModel.getColumn(3).setPreferredWidth(120); columnModel.getColumn(4).setPreferredWidth(240); }
1
@Override public String action() { StringBuilder builder = new StringBuilder(); builder.append(ZapporRestUtils.SEARCH_ACTION); builder.append("?term="); if (term != null) { builder.append(term); } builder.append("&filters="); StringBuilder value = new StringBuilder(); value.append("{\"price\":"); value.append("[\""); value.append(price); value.append("\"]"); if (includeOnSale) { value.append(",\"onSale\":"); value.append(":[\""); value.append(onSale); value.append("\"]"); } value.append("}"); try { builder.append(URLEncoder.encode(value.toString(), "utf-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } builder.append("&limit="); builder.append(limit); return builder.toString(); }
3
private static <V> V findAbbreviatedValue(Map<? extends IKey, V> map, IKey name, boolean caseSensitive) { String string = name.getName(); Map<String, V> results = Maps.newHashMap(); for (IKey c : map.keySet()) { String n = c.getName(); boolean match = (caseSensitive && n.startsWith(string)) || ((!caseSensitive) && n.toLowerCase().startsWith(string.toLowerCase())); if (match) { results.put(n, map.get(c)); } } V result; if (results.size() > 1) { throw new ParameterException("Ambiguous option: " + name + " matches " + results.keySet()); } else if (results.size() == 1) { result = results.values().iterator().next(); } else { result = null; } return result; }
8
@Override public synchronized void execute(final Runnable command) { tasks.offer(new Runnable() { public void run() { try { command.run(); } finally { scheduleNext(); } } });//insert one task if (active == null) { scheduleNext(); } }
1
public boolean endTurn(Integer activePlayerId) { // Cooldowns for (Attack a : this.getAttacks()) { if (a.getCooldownRemaining() < 0) { a.setCooldownRemaining(0); } else if (a.getCooldownRemaining() > 0) { a.setCooldownRemaining(a.getCooldownRemaining() - 1); } } // TODO: Regen // Update Moves if (activePlayerId.toString().equalsIgnoreCase(playerId)) { this.setMovesRemaining(0); } else { this.setMovesRemaining(this.getMoveDistance()); } // Status effects Iterator<String> i = statusEffects.keySet().iterator(); while (i.hasNext()) { String name = i.next(); StatusEffect se = statusEffects.get(name); if (se.durationRemaining > 0) { if (!se.execute(this)) { // LOG FAILURE // It would be cool if it also logged an ID of the failure // and included it in the client error logs // so they could reference like a bug status or something } } se.durationRemaining--; if (se.durationRemaining <= 0) { statusEffects.remove(name); } } // To live or Die? if (this.getCurrentHp() <= 0) { this.setDead(true); } return true; }
9
SimulatedIVPump2(Spawner spawn, InitialJFrame app) { super("Gamma Infusion Pump"); title = new JLabel(" Gamma Infusion Pump"); title.setFont(new Font("Arial", Font.PLAIN, 32)); title.setForeground(Color.WHITE); title.setBackground(Color.BLACK); setSize(defaultWidth, defaultHeight); getContentPane().setBackground(Color.BLACK); setLayout(new GridLayout(7, 1)); Standby = new JButton("STANDBY"); Standby.setBackground(green); Standby.setFocusPainted(false); Standby.addActionListener(this); Active = new JButton("INTERLOCK"); Active.setBackground(regular); Active.setFocusPainted(false); Active.addActionListener(this); Manual = new JButton("MANUAL"); Manual.setBackground(regular); Manual.setFocusPainted(false); Manual.addActionListener(this); Q4 = new JButton("Q4 - NOT ASSOCIATED (Click to Associate)"); Q4.setBackground(regular); Q4.setFocusPainted(false); Q4AssociationStatus.Q = false; Q4.addActionListener(this); Q5 = new JButton("Q5 - NOT ASSOCIATED (Click to Associate)"); Q5.setBackground(regular); Q5.setFocusPainted(false); Q5AssociationStatus.Q = false; Q5.addActionListener(this); MStart = new JButton("X"); MStop = new JButton("X"); MStart.setBackground(Color.GRAY); MStop.setBackground(Color.GRAY); MStart.setFocusPainted(false); MStop.setFocusPainted(false); MStart.addActionListener(this); MStop.addActionListener(this); JPanel manualContainer = new JPanel(); manualContainer.setLayout(new GridLayout(1, 3)); manualContainer.setBackground(Color.BLACK); manualContainer.add(Manual); manualContainer.add(MStart); manualContainer.add(MStop); ModeStatus = PumpMode.STANDBY; stop = true; stopped = false; modeLock = false; pumpNotice = new JLabel(ModeStatus.toString() + " Mode - " + (stop == true ? "PCA Off" : "PCA On")); pumpNotice.setFont(new Font("Arial", Font.PLAIN, (int)(15))); pumpNotice.setForeground(Color.YELLOW); pumpNotice.setBackground(Color.BLACK); JPanel pumpNoticeContainer = new JPanel(); pumpNoticeContainer.setLayout(new BoxLayout(pumpNoticeContainer, BoxLayout.X_AXIS)); pumpNoticeContainer.setBackground(Color.BLACK); pumpNoticeContainer.add(Box.createHorizontalGlue()); pumpNoticeContainer.add(pumpNotice); pumpNoticeContainer.add(Box.createHorizontalGlue()); add(title); add(Q4); add(Q5); add(Active); add(Standby); add(manualContainer); add(pumpNoticeContainer); warningType = WarningType.NULL; requestedMode = IVMode.NULL; requestedDisassociation = Disassociation.NULL; application = app; spawner = spawn; spawned = false; setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); WindowAdapter exitListener = new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { int confirm = JOptionPane.showOptionDialog(null, "Are You Sure You Want To Close Simulated IV Pump?", "Exit Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (confirm == 0) { generator.interrupt(); spawner.infusionPumpClosed(); if (application.isQ4Associated().equals(true)) application.toggleQ4(); if (application.isQ5Associated().equals(true)) application.toggleQ5(); dispose(); } } }; addWindowListener(exitListener); }
4
public static void exportReestr(List <Reception> receptions) { List<ReestrColumn> reestrColumns = ReestrColumns.getInstance().getActiveColumns(); // List<Reception> receptions = ReceptionsModel.getInstance().getFilteredReceptions(); SXSSFWorkbook wb = new SXSSFWorkbook(100); Sheet sh = wb.createSheet(); // Впечатываем наименования Row titleRow = sh.createRow(0); for (int colnum = 0; colnum < reestrColumns.size(); colnum++) { int width = reestrColumns.get(colnum).getWidth(); sh.setColumnWidth(colnum, 256*width); Cell cell = titleRow.createCell(colnum); String value = reestrColumns.get(colnum).getName(); cell.setCellValue(value); CellStyle cellStyle = wb.createCellStyle(); cellStyle.setWrapText(true); cellStyle.setBorderTop(CellStyle.BORDER_THIN); cellStyle.setBorderLeft(CellStyle.BORDER_THIN); cellStyle.setBorderRight(CellStyle.BORDER_THIN); cellStyle.setBorderBottom(CellStyle.BORDER_THIN); cell.setCellStyle(cellStyle); } // Впечатываем значения for (int rownum = 0; rownum < receptions.size(); rownum++) { Row row = sh.createRow(rownum+1); for (int colnum = 0; colnum < reestrColumns.size(); colnum++) { Cell cell = row.createCell(colnum); String value = reestrColumns.get(colnum).getValue(receptions.get(rownum)).toString(); cell.setCellValue(value); CellStyle cellStyle = wb.createCellStyle(); cellStyle.setWrapText(true); cellStyle.setBorderTop(CellStyle.BORDER_THIN); cellStyle.setBorderLeft(CellStyle.BORDER_THIN); cellStyle.setBorderRight(CellStyle.BORDER_THIN); cellStyle.setBorderBottom(CellStyle.BORDER_THIN); cell.setCellStyle(cellStyle); } } WebFileChooser fileChooser = new WebFileChooser(); //fileChooser.setMultiSelectionEnabled(false); FileFilter fileFilter = new FileNameExtensionFilter("Excel file", "xlsx"); fileChooser.setFileFilter(fileFilter); File file = null; file = fileChooser.showSaveDialog(); if (file == null) { return; } String filePath = file.getPath(); if(filePath.indexOf(".xlsx") == -1) { filePath += ".xlsx"; file = new File(filePath); } if (file.exists()) { } try { file.createNewFile(); FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); } catch (Exception e) { e.printStackTrace(); } // wb.dispose(); }
7
@Override public Matrix<Double> value(final Matrix<Double> firstInput, final Matrix<Double> secondInput) { if (firstInput.getFirstColumn() != secondInput.getFirstRow()) throw new ArithmeticException("The matrices are not " + "conforming in dimensions: First column does not " + "match the first row."); if (firstInput.getColumns() != secondInput.getRows()) throw new ArithmeticException("The matrices are not " + "conforming in dimensions: Number of columns does not " + "match the number of rows."); int fr = firstInput.getFirstRow(); int rs = firstInput.getRows(); int fc = secondInput.getFirstColumn(); int cs = secondInput.getColumns(); MatrixReal mp = new MatrixReal(fr, rs, fc, cs); rs += fr; cs += fc; int fi = firstInput.getFirstColumn(); int is = fi + firstInput.getColumns(); for (int r = fr; r < rs; r++) for (int c = fc; c < cs; c++) { double v = 0.0; for (int i = fi; i < is; i++) v += firstInput.getValue(r, i) * secondInput.getValue(i, c); mp.setValue(r, c, v); } return mp; }
5
public void setDstType(String type) { if ("string".equalsIgnoreCase(type)){ this.dstType = DstColumnType.STRING; } else if ("integer".equalsIgnoreCase(type)){ this.dstType = DstColumnType.INTEGER; } else if ("blob".equalsIgnoreCase(type)){ this.dstType = DstColumnType.BLOB; } else if ("list".equalsIgnoreCase(type)){ this.dstType = DstColumnType.LIST; } else if ("map".equalsIgnoreCase(type)){ this.dstType = DstColumnType.MAP; } else if ("llist".equalsIgnoreCase(type)){ this.dstType = DstColumnType.LLIST; } else if ("float".equalsIgnoreCase(type)){ this.dstType = DstColumnType.FLOAT; } }
7
public SteganoDialog(Controller controller) { super(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); bundle = Application.getResourceBundle(); setTitle("Steganography"); // Closing the window is equal to pressing the Abort-Button WindowListener windowListener = (new WindowAdapter() { public void windowClosing(WindowEvent evt) { pressedAbort(); } }); addWindowListener(windowListener); ActionListener actionListener = (new ActionListener() { public void actionPerformed(ActionEvent evt) { if (evt.getSource() == btEncrypt) pressedEncrypt(); else if (evt.getSource() == btDecrypt) pressedDecrypt(); else if (evt.getSource() == btAbort) pressedAbort(); } }); // Enter is equal to pressing the Send-Button and // Escape is equal to pressing the Abort-Button KeyListener keyListener = (new KeyAdapter() { @Override public void keyPressed(KeyEvent evt) { if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) pressedAbort(); } }); addKeyListener(keyListener); imgPickerTxt = new JLabel("Image:"); filePickertxt = new JLabel("File:"); stegInfo = new JLabel("Hide a file in an image!"); filePickertxt.setHorizontalAlignment(JLabel.RIGHT); pfPasswd = new JPasswordField(""); btEncrypt = new JButton("Encrypt"); btDecrypt = new JButton("Decrypt"); btAbort = new JButton(bundle.getString("cancel")); imgchooser = new JFileChooser(); fchooser = new JFileChooser(); btImgChoose = new JButton("Choose Image"); btFChoose = new JButton("Choose file"); txtImage = new JTextField(""); txtFile = new JTextField(""); btImgChoose.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if (fchooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) txtImage.setText(fchooser.getSelectedFile().getCanonicalPath()); } catch (IOException ioex) { displayError(bundle.getString("error"), ioex.getLocalizedMessage()); } } }); btFChoose.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if (fchooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) txtFile.setText(fchooser.getSelectedFile().getCanonicalPath()); } catch (IOException ioex) { displayError(bundle.getString("error"), ioex.getLocalizedMessage()); } } }); imgPickerTxt.setHorizontalAlignment(JLabel.RIGHT); btEncrypt.addActionListener(actionListener); btDecrypt.addActionListener(actionListener); btAbort.addActionListener(actionListener); btAbort.addKeyListener(keyListener); JPanel pnlMain = new JPanel(); pnlMain.setBorder(BorderFactory.createEmptyBorder(8, 8, 10, 8)); pnlMain.setLayout(new GridLayout(4, 1, 4, 4)); pnlMain.add(stegInfo); JPanel imgPickPnl = new JPanel(); imgPickPnl.setLayout(new GridLayout(1, 3, 2, 2)); imgPickPnl.add(imgPickerTxt); imgPickPnl.add(txtImage); imgPickPnl.add(btImgChoose); pnlMain.add(imgPickPnl); JPanel fPickPanel = new JPanel(); fPickPanel.setLayout(new GridLayout(1, 3, 2, 2)); fPickPanel.add(filePickertxt); fPickPanel.add(txtFile); fPickPanel.add(btFChoose); pnlMain.add(fPickPanel); JPanel buttonPannel = new JPanel(); buttonPannel.setLayout(new GridLayout(1, 3, 2, 2)); buttonPannel.add(btEncrypt); buttonPannel.add(btDecrypt); buttonPannel.add(btAbort); pnlMain.add(buttonPannel); Container contFrame = getContentPane(); contFrame.setLayout(new BorderLayout()); contFrame.add(pnlMain, "Center"); pack(); }
8
private static boolean getPersonGender() { Scanner keyboard2 = new Scanner(System.in); String gender; do { System.out.print("Gender?:"); gender = keyboard2.nextLine().toLowerCase(); if (!(gender.matches("f(emale)?") || gender.matches("m(ale)?"))) { System.out.println("The gender must be F,Female,M or Male in any case"); } } while (!(gender.matches("f(emale)?") || gender.matches("m(ale)?"))); return gender.matches("f(emale)?"); }
4
public static void main(String[] args) { StockStrategy stockStrategy=new StockStrategy(); int[] arr={6,1,3,2,4,7}; System.out.println(stockStrategy.maxProfit(arr)); }
0
public void bytesRead(int bytes, int clientId) { if (this.clientId == clientId) { for (Iterator i = observers.iterator(); i.hasNext();) { ObservableStreamListener listener = (ObservableStreamListener) i .next(); listener.bytesRead(bytes, clientId); } } }
2
private void load() { assets = new AssetManager(); assets.setLoader(TiledMap.class, new TmxMapLoader(new InternalFileHandleResolver())); assets.setLoader(Script.class, new ScriptLoader(new InternalFileHandleResolver())); assets.setLoader(EntityList.class, new EntityLoader(new InternalFileHandleResolver())); assets.setLoader(PokeDB.class, new PokemonLoader(new InternalFileHandleResolver())); assets.setLoader(TriggerList.class, new TriggerLoader(new InternalFileHandleResolver())); //Maps FileHandle f = new FileHandle("res/maps/"); for (FileHandle map : f.list()) { assets.load(map.path() + "/map.tmx", TiledMap.class); assets.load(map.path() + "/entity.lst", EntityList.class); assets.load(map.path() + "/trigger.lst", TriggerList.class); for (FileHandle script: map.list()) if (script.extension().equals("ps")) assets.load(script.path(), Script.class); } //Sprites f = new FileHandle("res/entity/sprites"); for (FileHandle img : f.list()) if (img.extension().equals("png")) assets.load(img.path(), Texture.class); //Gui assets.load("res/gui/border.png", Texture.class); assets.load("res/gui/arrow.png", Texture.class); assets.load(com.github.Danice123.javamon.screen.menu.gen1.Pokedex.pokeball, Texture.class); //Scripts f = new FileHandle("res/scripts"); for (FileHandle s : f.list()) assets.load(s.path(), Script.class); //Pokemon assets.load("db/pokemon", PokeDB.class); }
6
public byte[] handle(ConnectionDetails connectionDetails, byte[] buffer, int bytesRead) throws java.io.IOException { final StringBuffer stringBuffer = new StringBuffer(); boolean inHex = false; for(int i=0; i<bytesRead; i++) { final int value = (buffer[i] & 0xFF); // If it's ASCII, print it as a char. if (value == '\r' || value == '\n' || (value >= ' ' && value <= '~')) { if (inHex) { stringBuffer.append(']'); inHex = false; } stringBuffer.append((char)value); } else { // else print the value if (!inHex) { stringBuffer.append('['); inHex = true; } if (value <= 0xf) { // Where's "HexNumberFormatter?" stringBuffer.append("0"); } stringBuffer.append(Integer.toHexString(value).toUpperCase()); } } m_out.println("------ "+ connectionDetails.getDescription() + " ------"); m_out.println(stringBuffer); return null; }
8
private void setPrev(Vector<vslIndexView<D>> prevVec) throws vslInputException { if (record instanceof vslIndexUpdateRecord) { vslIndexUpdateRecord update = (vslIndexUpdateRecord) record; if (update.prev == null) { Vector<vslRecKey> prevKeys = new Vector<vslRecKey>(); for (vslIndexView<D> prev: prevVec) { // throw exception if prev record is a delete record if (prev.isDelete()) { String err = "Attempt to add an Update with a prev record that is a delete record [" + prev.getRecKey() +"]"; vslLog.log(vslLog.ERROR, err); throw new vslInputException(err); } prevKeys.add(prev.getRecKey()); } update.prev = prevKeys; } } else if (record instanceof vslIndexDeleteRecord) { vslIndexDeleteRecord del = (vslIndexDeleteRecord) record; if (del.prev == null) { Vector<vslRecKey> prevKeys = new Vector<vslRecKey>(); for (vslIndexView<D> prev: prevVec) { // throw exception if prev record is a delete record if (prev.isDelete()) { String err = "Attempt to add a Delete with a prev record that is a delete record [" + prev.getRecKey() +"]"; vslLog.log(vslLog.ERROR, err); throw new vslInputException(err); } prevKeys.add(prev.getRecKey()); } del.prev = prevKeys; } } this.prevViews = prevVec; }
8
public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Productos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Productos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Productos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Productos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { Productos dialog = new Productos(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
6
private Format getFileFormat(File file) { BufferedReader br; String line; String [] parts; Scanner scanner = new Scanner(""); try { br = new BufferedReader(new FileReader(file)); // Skip the lines that don't contain data (comments and such) while((line = br.readLine()) != null) { scanner = new Scanner(line); if(scanner.hasNextInt()) break; } if(line == null) { br.close(); return Format.Unknown; } // Count the number of substrings in line, by splitting it around sets of white-space characters line = line.trim(); // Remove leading and trailing whitespace, so it doesn't mess with 'split' parts = line.split("[\\s ]+"); br.close(); if(parts.length == 2) return Format.Simple; else if(parts.length >= 9) // This allows comments in the data line. (Normal line gives the length of 9) return Format.Full; } catch (IOException e) { JOptionPane.showConfirmDialog(mainFrame, "Can't read the file!", "Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); return Format.ReadError; } return Format.Unknown; }
6
@Override public void componentHidden(ComponentEvent e) { }
0
public static synchronized Response connect(Request request) throws IOException{ Response response = null; ObjectOutputStream oos = null; ObjectInputStream ois = null; try { socket = new Socket("localhost", 4444); oos = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream())); oos.writeObject(request); oos.flush(); }catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { ois = new ObjectInputStream(new BufferedInputStream(socket != null ? socket.getInputStream() : null)); response = (Response) ois.readObject(); }catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (oos != null) { oos.close(); } if (ois != null) { ois.close(); } if (socket != null) { socket.close(); } } return response; }
7
public static int howMuchDigits(int number) { int count = 1; while (number / 10 != 0) { count++; number /= 10; } return count; }
1
private static int parseChanges(int index, List<Word> wordList, List<Change> changes, String comma) throws SQLCompilerException { while (index < wordList.size()) { ParseExpressionResult result = ExpressionParser.parse(index, wordList); if (result.getIndex() <= index) { break; } else { Expression exp = result.getExpression(); check((exp != null && exp.getType() == Expression.EXPRESSION && Keywords.ASSIGN.equals(exp.getName()) && exp.getParameters().size() == 2 && exp .getParameters().get(0).getType() == Expression.REFER), wordList.get(index), ErrorCode.ERROR, ErrorCode.SP_INVALID_SENTENCE, "Invalid assignment expression."); Change change = new Change(); Expression field = exp.getParameters().get(0); change.setDomain(field.getDomain()); change.setField(field.getName()); change.setValue(exp.getParameters().get(1)); changes.add(change); index = result.getIndex(); if (index < wordList.size()) { Word w = wordList.get(index); if (w.getType() == WordDef.DE && comma.equals(w.getWord())) { index++; } } } } return index; }
9
public MessagePost (String username, String message){ super(username); this.message = message; }
0
public void connect() throws JSchException{ try{ Session _session=getSession(); if(!_session.isConnected()){ throw new JSchException("session is down"); } if(io.in!=null){ thread=new Thread(this); thread.setName("DirectTCPIP thread "+_session.getHost()); if(_session.daemon_thread){ thread.setDaemon(_session.daemon_thread); } thread.start(); } else { sendChannelOpen(); } } catch(Exception e){ io.close(); io=null; Channel.del(this); if (e instanceof JSchException) { throw (JSchException) e; } } }
5
private void removed (DeviceImpl dev) { if (MacOSX.trace) System.err.println ("notify bus->removed(dev): " + dev.getPath()); // call synch'd on devices try { dev.close (); } catch (IOException e) { // normally ignore if (MacOSX.debug) e.printStackTrace (); } //in Mac OS X we want to close device (blocking further ctrl msgs) before // calling 'removed' listeners! Do that in other OS's too? // call synch'd on devices for (int i = 0; i < listeners.size (); i++) { USBListener listener; listener = (USBListener) listeners.elementAt (i); try { listener.deviceRemoved (dev); } catch (Exception e) { if (MacOSX.debug) e.printStackTrace (); } } }
6
public static BufferedImage cellImage(PixelType type){ if(type == PixelType.NOFILL){ return getImage(101, false); }else if(type == PixelType.FILL){ return getImage(102, false); }else if(type == PixelType.CROSS){ return getImage(103, false); }else if(type == PixelType.GUESS_NOFILL){ return getImage(104, false); }else if(type == PixelType.GUESS_FILL){ return getImage(105, false); }else if(type == PixelType.GUESS_CROSS){ return getImage(106, false); }else if(type == PixelType.CHECK){ return getImage(107, false); }else{ return null; } }
7
private static Structure parseHeader(CallParser parser) { ParseError.validate(parser.size() > 2, parser.firstCall().lineN, "Malformed callable header"); ParseError.validate(parser.get(0).qualifiesAsKeyword(), parser.firstCall().lineN, "Malformed callable header"); ParseError.validate(parser.get(1).qualifiesAsKeyword(), parser.firstCall().lineN, "Malformed callable header"); ExecutionMode em = null; if (parser.get(0).callName.equals("instantiated")) { // TODO switch block em = ExecutionMode.INSTANTIATED; } else if (parser.get(0).callName.equals("static")) { em = ExecutionMode.STATIC; } else if (parser.get(0).callName.equals("inline")) { em = ExecutionMode.INLINE; } ParseError.validate(em != null, parser.firstCall().lineN, "Malformed callable header (no ExecutionMode indicated)"); RunMode rm = null; if (parser.get(1).callName.equals("parallel")) { rm = RunMode.PARALLEL; } else if (parser.get(1).callName.equals("sequence")) { rm = RunMode.SEQUENTIAL; } ParseError.validate(rm != null, parser.firstCall().lineN, "Malformed callable header (no RunMode indicated)"); ParsedCall call = parser.get(2); parser.removeFirstN(3); // Remove the two keywords and the declaration StructInput[] inputNodes = new StructInput[call.inParams.length]; StructOutput[] outputNodes = new StructOutput[call.outParams.length]; for (int i = 0; i < call.inParams.length; i++) { inputNodes[i] = new StructInput(call.inParams[i], inputNodes, call.lineN); } for (int i = 0; i < call.outParams.length; i++) { outputNodes[i] = new StructOutput(call.outParams[i], inputNodes, call.lineN); } return new Structure(em, rm, inputNodes, outputNodes, call.callName, call.lineN); }
7
void run() { try { // 1. creating a server socket providerSocket = new ServerSocket(2004, 10); // 2. Wait for connection System.out.println("Waiting for connection"); connection = providerSocket.accept(); System.out.println("Connection received from " + connection.getInetAddress().getHostName()); // 3. get Input and Output streams out = new ObjectOutputStream(connection.getOutputStream()); out.flush(); in = new ObjectInputStream(connection.getInputStream()); sendMessage("Connection successful"); // 4. The two parts communicate via the input and output streams do { try { message = (String) in.readObject(); System.out.println("client>" + message); if (message.equals("bye")) sendMessage("bye"); else sendMessage("Roger"); } catch (ClassNotFoundException classnot) { System.err.println("Data received in unknown format"); } } while (!message.equals("bye")); } catch (IOException ioException) { ioException.printStackTrace(); } finally { // 4: Closing connection try { in.close(); out.close(); providerSocket.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } }
5
public EU2Country getOwner() { int id = getId(); String sid = go.getString("id"); if (!scenario.provCanHaveOwner(id)) return null; for (GenericObject c : scenario.countries) if (c.getChild("ownedprovinces").contains(sid)) return scenario.getCountry(c.getString("tag")); return null; //not found }
3
protected int computeState(int neighbors[]){ int numberOfLiveNeighbors = 0; for(int i = 1; i < neighbors.length; i++){ if(neighbors[i] != CellularAutomatonConstants.NO_VALUE){ if(neighbors[i] == GameOfLifeAutomaton.CELL_LIVE){ numberOfLiveNeighbors++; } } } if(neighbors[0] == GameOfLifeAutomaton.CELL_LIVE){ if(numberOfLiveNeighbors == 0 || numberOfLiveNeighbors == 1 || numberOfLiveNeighbors > 3){ return CELL_DEAD; } } else{ if(numberOfLiveNeighbors != 3){ return CELL_DEAD; } } return CELL_LIVE; }
8
final public List<Literal> literals() throws ParseException { List<Literal> literals=new ArrayList<Literal>(); String literalFunction=null; Literal literal=null; if (jj_2_48(7)) { literalFunction = literalFunction(); } else if (jj_2_49(7)) { literal = literal(); } else { jj_consume_token(-1); throw new ParseException(); } if (null!=literalFunction) { literal=DomUtilities.getLiteralVariable(literalFunction,false); } literals.add(literal); literalFunction=null; literal=null; label_7: while (true) { if (jj_2_50(7)) { ; } else { break label_7; } jj_consume_token(ARGUMENT_SEPARATOR); if (jj_2_51(7)) { literalFunction = literalFunction(); } else if (jj_2_52(7)) { literal = literal(); } else { jj_consume_token(-1); throw new ParseException(); } if (null!=literalFunction) { literal=DomUtilities.getLiteralVariable(literalFunction,false); //literal=new LiteralVariable(literalFunction,false); } literals.add(literal); literalFunction=null; literal=null; } {if (true) return literals;} throw new Error("Missing return statement in function"); }
9
public void removeNeighbour(Agent a) { neighbours.remove(a); }
0
public TrackingAndRecognitionMenu() { super("Tracking & Recognition"); setEnabled(true); JMenuItem imageTracking = new JMenuItem("Image"); imageTracking.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Panel panel = (((Window) getTopLevelAncestor()).getPanel()); if (panel.getImage() == null) { return; } JDialog trackingDialog = new RgbImageTrackingDialog(panel); trackingDialog.setVisible(true); } }); JMenuItem rgbVideoTracking = new JMenuItem("RGB Video"); rgbVideoTracking.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Panel panel = (((Window) getTopLevelAncestor()).getPanel()); if (panel.getImage() == null) { return; } JDialog trackingDialog = new RgbVideoTrackingDialog(panel); trackingDialog.setVisible(true); } }); JMenuItem hvsVideoTracking = new JMenuItem("HVS Video"); hvsVideoTracking.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Panel panel = (((Window) getTopLevelAncestor()).getPanel()); if (panel.getImage() == null) { return; } JDialog trackingDialog = new HsvVideoTrackingDialog(panel); trackingDialog.setVisible(true); } }); JMenu sift = new JMenu("SIFT"); JMenuItem siftAnalyze = new JMenuItem("Analyze"); siftAnalyze.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Panel panel = (((Window) getTopLevelAncestor()).getPanel()); Image a = panel.getImage(); if (a == null) { return; } panel.setImage(SiftUtils.sift(a)); panel.repaint(); } }); JMenuItem siftCompare = new JMenuItem("Compare"); siftCompare.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Panel panel = (((Window) getTopLevelAncestor()).getPanel()); Image a = panel.getImage(); if (a == null) { return; } Image b = getSecondaryImage(); Image[] pair = SiftUtils.sift(a, b); panel.setImage(pair[0]); panel.repaint(); Window w = new Window(); w.getPanel().setImage(pair[1]); w.setVisible(true); } }); add(imageTracking); add(new JSeparator()); add(rgbVideoTracking); add(hvsVideoTracking); add(new JSeparator()); add(sift); sift.add(siftAnalyze); sift.add(siftCompare); }
5
public Keygen(HtmlMidNode parent, HtmlAttributeToken[] attrs){ super(parent, attrs); for(HtmlAttributeToken attr:attrs){ String v = attr.getAttrValue(); switch(attr.getAttrName()){ case "autofocus": autofocus = Autofocus.parse(this, v); break; case "challenge": challenge = Challenge.parse(this, v); break; case "disabled": disabled = Disabled.parse(this, v); break; case "form": form = Form.parse(this, v); break; case "keytype": keytype = Keytype.parse(this, v); break; case "name": name = Name.parse(this, v); break; } } }
7
public boolean followUrl(final Url url) { if (visitedUrls.get(url) != null) { return false; } visitedUrls.put(url, ""); return visitor.followUrl(url); }
1
public Weapon(int x, int y, String name) { this.x = x << 4; this.y = y << 4; type = Type.WEAPON; ammotype = Ammotype.BULLET; if (name == "Pistol") { up = new AnimatedSprite(SpriteSheet.player_pistol_up, 32, 32, 3, 10); down = new AnimatedSprite(SpriteSheet.player_pistol_down, 32, 32, 3, 10); left = new AnimatedSprite(SpriteSheet.player_pistol_left, 32, 32, 5, 10); right = new AnimatedSprite(SpriteSheet.player_pistol_right, 32, 32, 5, 10); } else if (name == "SMG") { up = new AnimatedSprite(SpriteSheet.player_smg_up, 32, 32, 3, 10); down = new AnimatedSprite(SpriteSheet.player_smg_down, 32, 32, 3, 10); left = new AnimatedSprite(SpriteSheet.player_smg_left, 32, 32, 5, 10); right = new AnimatedSprite(SpriteSheet.player_smg_right, 32, 32, 5, 10); } else if (name == "Shotgun") { up = new AnimatedSprite(SpriteSheet.player_shotgun_up, 32, 32, 3, 10); down = new AnimatedSprite(SpriteSheet.player_shotgun_down, 32, 32, 3, 10); left = new AnimatedSprite(SpriteSheet.player_shotgun_left, 32, 32, 5, 10); right = new AnimatedSprite(SpriteSheet.player_shotgun_right, 32, 32, 5, 10); } else if (name == "Rifle") { up = new AnimatedSprite(SpriteSheet.player_rifle_up, 48, 48, 3, 10); down = new AnimatedSprite(SpriteSheet.player_rifle_down, 48, 48, 3, 10); left = new AnimatedSprite(SpriteSheet.player_rifle_left, 48, 48, 5, 10); right = new AnimatedSprite(SpriteSheet.player_rifle_right, 48, 48, 5, 10); } }
4
public static void update(){ if (draw != null) { draw.repaint(); } }
1
public int getWallObjectUid(int z, int x, int y) { GroundTile groundTile = groundTiles[z][x][y]; if (groundTile == null || groundTile.wallObject == null) { return 0; } else { return groundTile.wallObject.uid; } }
2
public static ArrayList<Productos> sqlSelectAtributos(Productos pro){ ArrayList<Productos> prod = new ArrayList(); String sql = "SELECT de.nombre, at.atributo " + "FROM atributos at " + "INNER JOIN cat_subcat_tit_attr_descr pr ON at.idatributos = pr.atributos_id " + "INNER JOIN descripcion de ON de.iddescripcion = pr.descripcion_id " + "WHERE 1=1 " + "AND pr.categorias_id = '"+pro.getIdCat()+"' " + "AND pr.subcategorias_id = '"+pro.getIdSubCat()+"' " + "AND pr.titulo_id = '"+pro.getIdTitulo()+"'" + " ORDER BY textarea ASC"; if(!BD.getInstance().sqlSelect(sql)){ return prod; } while(BD.getInstance().sqlFetch()){ prod.add(new Productos(BD.getInstance().getString("atributo") ,BD.getInstance().getString("nombre") )); } return prod; }
2
public Class<?> getTargetType() { return this.targetType; }
1
public boolean isContained(char axis) { switch (axis) { case 'x': if (getMinX() < -0.5f * model.getLength() || getMaxX() > 0.5f * model.getLength()) return false; break; case 'y': if (getMinY() < -0.5f * model.getWidth() || getMaxY() > 0.5f * model.getWidth()) return false; break; case 'z': if (getMinZ() < -0.5f * model.getHeight() || getMaxZ() > 0.5f * model.getHeight()) return false; break; } return true; }
9
public static void leptet( int[][] tabla ) { b = 1; jatekos = 0; while( !Ellenor.jatekVege(tabla) ) { AktualisRajzol.rajzol(tabla); jatekos = Jatek.melyJatekosKovetkezik(b, jatekos, 1); sor = sc.nextLine(); String splitSor[] = sor.split(" "); if( splitSor.length != 2 ) { System.out.println( "Rossz formátumban adtál meg értéket!\n" + "Add meg, hova szeretnéd léptetni a bábúdat! Példa: A1 A4\n" + "Probáld újra!\n" ); b = b--; continue; } String honnanSor = splitSor[0]; String hovaSor = splitSor[1]; if( Ellenor.ellenorLerak(honnanSor) == false || Ellenor.ellenorLerak(hovaSor) == false || splitSor[0] == null || splitSor[1] == null) { System.out.println( "Rossz formátumban adtál meg értéket!\n" + "Add meg, hova szeretnéd léptetni a bábúdat! Példa: A1 A4\n" + "Probáld újra!\n" ); logger.error("Hibás formátum"); b = b--; continue; } else { if( Helyezz.leptet(honnanSor, hovaSor, jatekos, tabla, babu1, babu2) == 0 ) { b = b--; continue; } else { logger.info("Malom figyelés."); Jatek.malomCheck(jatekos, tabla); } } b++; } }
7
private String readFile(File file) { StringBuilder stringBuffer = new StringBuilder(); BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(file)); String text; while ((text = bufferedReader.readLine()) != null) { stringBuffer.append(text); } } catch (FileNotFoundException ex) { Logger.getLogger(IOManager.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(IOManager.class.getName()).log(Level.SEVERE, null, ex); } finally { try { bufferedReader.close(); } catch (IOException ex) { Logger.getLogger(IOManager.class.getName()).log(Level.SEVERE, null, ex); } } return stringBuffer.toString(); }
4
public synchronized List<Long> getWaysIds(int pos) { if (nodes.size()>pos) return ways.get(pos); else return new ArrayList<Long>(); }
1
public static void putLongNullable(ByteBuffer out, Long x) { if (x == null) { out.put( NULL ); } else { long value = (x < 0 ? -x : x); int sign = (x < 0 ? BYTE_SIGN_NEG : BYTE_SIGN_POS); long a = (value & 0x1F); int more = (value >>= 5) != 0 ? BYTE_MORE : 0; out.put( (byte)(more | sign | BYTE_NOT_NULL | a) ); while (more != 0) { a = value & 0x7F; more = (value >>= 7) != 0 ? BYTE_MORE : 0; out.put( (byte)(more | a) ); } } }
6
@Override public void controlObject(GObject target, Context context) { if (tick > duration) { // We've been reused. Get out. return; } // Is this our first run? if (tick == 0) { // We may have other tweens that should be run at the same time. for (TweenController tween : with) { // Add the controller. target.addController(tween); // Since it won't be invoked until next frame (and will be one // frame off), invoke it manually to get it on track. tween.controlObject(target, context); } } // Interpolate! interpolate(target, context, interpolationType.calculateInterpolation(tick, duration)); // Advance. tick++; // Are we done now? if (tick > duration) { // We're done. Remove ourself. target.removeController(this); // Do we chain? if (next != null) { // Do so. target.addController(next); } } }
5
public Object clone() { return new LRParseTable(this); }
0
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CovingtonConfig that = (CovingtonConfig)obj; if (input.size() != that.getInput().size()) return false; if (dependencyGraph.nEdges() != that.getDependencyGraph().nEdges()) return false; for (int i = 0; i < input.size(); i++) { if (input.get(i).getIndex() != that.getInput().get(i).getIndex()) { return false; } } return dependencyGraph.getEdges().equals(that.getDependencyGraph().getEdges()); }
7
public static List<String> getChildren(URL url) { List<String> result = new ArrayList<String>(); if ("file".equals(url.getProtocol())) { File file = new File(url.getPath()); if (!file.isDirectory()) { file = file.getParentFile(); } addFiles(file, result, file); } else if ("jar".equals(url.getProtocol())) { try { JarFile jar = ((JarURLConnection) url.openConnection()) .getJarFile(); Enumeration<JarEntry> e = jar.entries(); while (e.hasMoreElements()) { JarEntry entry = e.nextElement(); result.add(entry.getName()); } } catch (IOException e) { // Do nothing } } return result; }
5
private PlayerPawn findPlayerPawnById(int id){ for (int i = 0; i < playerPawns.size(); i++) { if (playerPawns.get(i).getId() == id) { return playerPawns.get(i); } } return null; }
2
@Override public void delBehavior(Behavior to) { if(behaviors==null) return; if(behaviors.remove(to)) { if(behaviors.isEmpty()) behaviors=new SVector<Behavior>(1); if(((behaviors==null)||(behaviors.isEmpty()))&&((scripts==null)||(scripts.isEmpty()))) CMLib.threads().deleteTick(this,Tickable.TICKID_ROOM_BEHAVIOR); } }
7
@Test(dataProvider="createTimer") public void testSchedulingTasksThenCancellingEverySecondTask(TimeScheduler timer) { final int NUM=20; Future<?>[] futures=new Future<?>[NUM]; try { for(int i=0; i < NUM; i++) { futures[i]=timer.schedule(new MyRunnable(i), 1000, TimeUnit.MILLISECONDS); if(i % 2 == 0) futures[i].cancel(false); } Util.sleep(3000); for(int i=0; i < NUM; i++) { Future<?> future=futures[i]; System.out.println("[" + i + "] done=" + future.isDone() + ", cancelled=" + future.isCancelled()); } for(int i=0; i < NUM; i++) { Future<?> future=futures[i]; assert future.isDone(); if(i % 2 == 0) assert future.isCancelled(); else assert !future.isCancelled(); } } finally { timer.stop(); } }
9
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final MappingProduct other = (MappingProduct) obj; if (!Objects.equals(this.pcodeScylla, other.pcodeScylla)) { return false; } return true; }
3
@Override public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String[] args) { try { if(args.length < 1) { throw new IllegalArgumentException("must be more than one"); } PluginCommand pluginCmd = Bukkit.getServer().getPluginCommand(cmdLabel + " " + args[0]); if(!pluginCmd.testPermissionSilent(sender)) { sender.sendMessage(ChatColor.RED + "[" + plugin.getName().toString() + "] You don't have permission."); return true; } return pluginCmd.execute(sender, cmdLabel, args); }catch(Exception e) { PluginDescriptionFile description = plugin.getDescription(); sender.sendMessage(ChatColor.GOLD + "[" + plugin.getName().toString() + "] Version " + description.getVersion()); Map<String, Map<String, Object>> customers = description.getCommands(); Set<String> keys = customers.keySet(); for(String singleKey : keys) { sender.sendMessage(ChatColor.GOLD + " " + customers.get(singleKey).get("description")); sender.sendMessage(ChatColor.GOLD + " - usage: " + ChatColor.WHITE + customers.get(singleKey).get("usage")); sender.sendMessage(ChatColor.GOLD + " - permission: " + ChatColor.WHITE + customers.get(singleKey).get("permission")); sender.sendMessage(ChatColor.GOLD + " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ "); } return true; } }
4
public int getValueAsInt() throws IllegalArgumentException { if (!isOptionAsInt(code)) { throw new IllegalArgumentException("DHCP option type (" + this.code + ") is not int"); } if (this.value == null) { throw new IllegalStateException("value is null"); } if (this.value.length != 4) { throw new DHCPBadPacketException("option " + this.code + " is wrong size:" + this.value.length + " should be 4"); } return ((this.value[0] & 0xFF) << 24 | (this.value[1] & 0xFF) << 16 | (this.value[2] & 0xFF) << 8 | (this.value[3] & 0xFF)); }
3
public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); for (int x = 0; x < n; x++) { String[] in = br.readLine().split(" "); int row = Integer.parseInt(in[0]); int col = Integer.parseInt(in[1]); int[][] distArr = new int[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { distArr[i][j] = Integer.MAX_VALUE; } } char[][] inArr = new char[row][col]; for (int i = 0; i < row; i++) { inArr[i] = br.readLine().toCharArray(); for (int j = 0; j < col; j++) { if (inArr[i][j] == '1') { fillNeighbor(distArr, i, j, 0); } } } for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { System.out.print(distArr[i][j] + " "); } System.out.println(""); } } }
8
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { EmployeeManager mgr = new EmployeeManager(); boolean success = false; //COLLECT ALL THE VARIOUS PARAMETERS String firstName = req.getParameter("firstName"); String lastName = req.getParameter("lastName"); String email = req.getParameter("email"); String dept = req.getParameter("dept"); String eqType = req.getParameter("eqType"); String eqName = req.getParameter("eqName"); // CHECK FOR AN EQUIPMENT PARAMETER if (!(req.getParameter("eqType")==null || req.getParameter("eqName")==null || req.getParameter("email")==null)) { //ADD EQUIPMENT success = mgr.addEquipment(eqType, eqName,email); if (success) { resp.getWriter().println("EQUIPMENT RECORD INSERTED"); } else { resp.getWriter().println("EQUIPMENT NOT ADDED (No Employee with that email, or problem accessing the database)"); } } else { //ASSUME NEW EMPLOYEE AND ADD THE EMPLOYEE RECORD success = mgr.addEmployee(firstName, lastName, dept, email); if (success) { resp.getWriter().println("EMPLOYEE RECORD INSERTED"); } else { resp.getWriter().println("ERROR INSERTING EMPLOYEE RECORD"); } } }
5
private void loopCycle() { // Logic processHits(); while(Keyboard.next()) { // Only listen to events where the key was pressed (down event) if (!Keyboard.getEventKeyState()) continue; // Switch textures depending on the key released switch (Keyboard.getEventKey()) { case Keyboard.KEY_1: textureSelector = 0; break; case Keyboard.KEY_2: textureSelector = 1; break; } } // Render GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); GL20.glUseProgram(pId); // Bind the texture GL13.glActiveTexture(GL13.GL_TEXTURE0); GL11.glBindTexture(GL11.GL_TEXTURE_2D, 1); d.draw(); //GL11.glBindTexture(GL11.GL_TEXTURE_2D, 2); d2.draw(); /* // Bind to the VAO that has all the information about the vertices GL30.glBindVertexArray(vaoId); GL20.glEnableVertexAttribArray(0); GL20.glEnableVertexAttribArray(1); GL20.glEnableVertexAttribArray(2); // Bind to the index VBO that has all the information about the order of the vertices GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboiId); // Draw the vertices GL11.glDrawElements(GL11.GL_TRIANGLES, indicesCount, GL11.GL_UNSIGNED_BYTE, 0); // Put everything back to default (deselect) GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0); GL20.glDisableVertexAttribArray(0); GL20.glDisableVertexAttribArray(1); GL20.glDisableVertexAttribArray(2); GL30.glBindVertexArray(0); */ GL20.glUseProgram(0); this.exitOnGLError("loopCycle"); }
4
@Override public void execute() throws MojoExecutionException, MojoFailureException { if(skipTests || mavenTestSkip) { getLog().info("Skipping all Octave tests, because 'skipTests' is set to true."); } else { getLog().info("running Octave tests @" + url); try { final HttpClient httpclient = new DefaultHttpClient(); final HttpGet httpget = new HttpGet(new URI(url.toString())); final HttpResponse response = httpclient.execute(httpget); final StatusLine statusLine = response.getStatusLine(); getLog().debug(statusLine.toString()); final HttpEntity entity = response.getEntity(); if (entity != null) { try (InputStream instream = entity.getContent()) { final Result result = new Gson().fromJson(new InputStreamReader(instream), Result.class); boolean failed = false; for (final Test test: result.tests) { getLog().info(" * name: " + test.name + ", success: " + test.success); failed |= test.success; } if (failed && !mavenTestFailureIgnore) { throw new MojoFailureException("Octave tests failed."); } else if (failed && mavenTestFailureIgnore) { getLog().warn("Octave test failures ignored, because 'maven.test.failure.ignore' is set to true."); } } } } catch (IOException | URISyntaxException e) { throw new MojoExecutionException("Error executing Octave tests: " + e.getMessage(), e); } } }
9
public static void main(String[] args) { new Cli(); }
0
public static String readLog(String name) { String tmpDir = System.getProperty("java.io.tmpdir") + File.separator + "DarkIRC"; if (!(new File(tmpDir)).exists()) { (new File(tmpDir)).mkdirs(); } String text = ""; try { InputStream flux = new FileInputStream(tmpDir + File.separator + name); InputStreamReader lecture = new InputStreamReader(flux); BufferedReader buff = new BufferedReader(lecture); String ligne; while ((ligne = buff.readLine()) != null) { text += ligne + "\n"; } buff.close(); } catch (Exception e) { // System.out.println(e.toString()); return ""; } return text; }
3
public void setSourceItem( DefaultBox<?> sourceItem ) { if( this.sourceItem != null ) { this.sourceItem.removeDependent( this ); } this.sourceItem = sourceItem; if( this.sourceItem != null ) { this.sourceItem.addDependent( this ); } }
3
@Override public boolean equals(Object o) { if (!(o instanceof User)) return false; User user = (User) o; return this.login == user.login && this.password == user.password && this.firstName == user.firstName && this.lastName == user.lastName && this.birthDate == user.birthDate && this.avatarPath == user.avatarPath; }
6
private void analyzeForLinking(ResultSet rs, String cmd) throws SQLException { if (rs == null) { return; } Statement stmt = rs.getStatement(); if (stmt == null) { return; } Connection conn = stmt.getConnection(); if (conn == null) { return; } this.conn = conn; if (conn.isReadOnly()) { return; } final String tableName = findTableName(cmd); if (tableName.length() == 0) { return; } this.tableName = tableName; this.updatable = true; List<String> pkList = findPrimaryKeys(conn, tableName); if (pkList.isEmpty()) { return; } @SuppressWarnings("unchecked") final Collection<Object> columnIdentifiers = this.columnIdentifiers; if (!columnIdentifiers.containsAll(pkList)) { return; } if (findUnion(cmd)) { return; } this.primaryKeys = pkList.toArray(new String[pkList.size()]); this.linkable = true; }
8
private String display() { String displayString = ""; if (this.address == -1) { return displayString; //If address line holds -1, signifies transfer from memory to MBR (no address). } displayString += this.address; return displayString; }
1
public static boolean isZero(int x, int y, int[][] sea) { return (isTile(x, y, sea) && sea[x][y] == 0); }
1
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } /* * ゲームモードを変更する * * @gm [0,1,2] * 0 = Survival * 1 = Creative * 2 = Adventure */ if (cmd.getName().equalsIgnoreCase("gm")) { if (player != null) { if (args.length == 0) { player.sendMessage(ChatColor.RED + "数値が正しくありません。"); return false; } else if (args.length == 1) { //ゲームモードの選択選択 if (args[0].equalsIgnoreCase("0")) { player.sendMessage(ChatColor.AQUA + "サバイバルモードに変更しました。"); player.setGameMode(GameMode.SURVIVAL); return true; } else if (args[0].equalsIgnoreCase("1")) { player.sendMessage(ChatColor.AQUA + "クリエイティブモードに変更しました。"); player.setGameMode(GameMode.CREATIVE); return true; } else if (args[0].equalsIgnoreCase("2")) { /* * 動かない!!!!!! * なんで!!!! if(!args[1].isEmpty()) { Player other = (Bukkit.getServer().getPlayer(args[1])); //対象の選択 if(other == null) { player.sendMessage(ChatColor.RED + args[1] + "は、オフラインです!"); return false; } else { //ここに実行したいことをかく other.sendMessage(ChatColor.AQUA + "アドベンチャーモードに変更しました。"); other.setGameMode(GameMode.ADVENTURE); player.sendMessage(ChatColor.AQUA + args[1] + "を、アドベンチャーモードに変更しました。"); return true; } } */ player.sendMessage(ChatColor.AQUA + "アドベンチャーモードに変更しました。"); player.setGameMode(GameMode.ADVENTURE); return true; } else { player.sendMessage(ChatColor.RED + "数値が正しくありません。"); return false; } } } else { sender.sendMessage("このコマンドはプレイヤー専用です。"); } return true; } return false; }
8
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String questionType = request.getParameter("newQuestionType"); if(questionType.equals("")){ RequestDispatcher dispatch = request.getRequestDispatcher("createQuiz/chooseQuestionType.jsp"); dispatch.forward(request, response); }else{ HttpSession session = request.getSession(); session.setAttribute("QuestionType", questionType); String pageString = "new_quiz_question"; if(questionType.equals("Question-Response")){ pageString = "createQuiz/new_quiz_question.jsp"; }else if(questionType.equals("Fill in the Blank")){ pageString = "createQuiz/new_quiz_question_fillInBlank.jsp"; }else if(questionType.equals("Multiple Choice")){ pageString = "createQuiz/new_quiz_question_multiChoice.jsp"; }else if(questionType.equals("Picture-Response Questions")){ pageString = "createQuiz/new_quiz_question_picture.jsp"; }else if(questionType.equals("Multiple-Answer Questions")){ pageString = "createQuiz/new_quiz_question_multiAnswer.jsp"; }else if(questionType.equals("Multiple Choice with Multiple Answers")){ pageString = "createQuiz/new_quiz_question_multiChoiceAndAnswer.jsp"; }else if(questionType.equals("Matching")){ pageString = "createQuiz/new_quiz_question_matching.jsp"; } RequestDispatcher dispatch = request.getRequestDispatcher(pageString); dispatch.forward(request, response); } }
8
public int setErrorHandler (PdbErrorHandler anErrorHandler) { // we don't accept null handlers if (anErrorHandler == null) { return NULL_OBJECT_REFERENCE ; } // end if // set it, return in triumph ourErrorHandler = anErrorHandler ; return SUCCESS ; } // end method setErrorHandler
1
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(LoginWindowInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(LoginWindowInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(LoginWindowInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LoginWindowInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { Thread.sleep(2000); } catch (Exception e) { } new LoginWindowInterface().setVisible(true); } }); }
7
public boolean getAcceptByFinalState(){ return turingAcceptByFinalState; }
0
public void addOnlyInstrumentReg(String arg) { String patternString = arg.substring(ONLY_INSTRUMENT_REG_PREFIX.length()); if (patternString.startsWith("/")) patternString = patternString.substring(1); defaultSkip = true; try { patternMatchers.add(PatternMatcherRegEx.getIncludePatternMatcher(patternString)); } catch (PatternSyntaxException e) { setInvalid(format("Invalid pattern '%s'", patternString)); e.printStackTrace(System.err); } }
2
private void bla() throws Exception { if(0==0) throw new Exception("bla"); }
1
public void printJobRequiresAttention(PrintJobEvent pje) { System.out.println("Job requires attention"); PrinterStateReasons psr = pje.getPrintJob().getPrintService().getAttribute(PrinterStateReasons.class); if (psr != null) { Set<PrinterStateReason> errors = psr.printerStateReasonSet(Severity.REPORT); for (PrinterStateReason reason : errors) System.out.printf(" Reason : %s", reason.getName()); System.out.println(); } }
2
private static String getFileContents(String filename) throws IOException, FileNotFoundException { File file = new File(filename); StringBuilder contents = new StringBuilder(); BufferedReader input = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = input.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } } finally { input.close(); } return contents.toString(); }
1
@Override public boolean keyup(KeyEvent ev) { if (ev.getKeyCode() == KeyEvent.VK_UP) APXUtils.wPressed = false; if (ev.getKeyCode() == KeyEvent.VK_LEFT) APXUtils.aPressed = false; if (ev.getKeyCode() == KeyEvent.VK_DOWN) APXUtils.sPressed = false; if (ev.getKeyCode() == KeyEvent.VK_RIGHT) APXUtils.dPressed = false; if (ev.getKeyCode() == KeyEvent.VK_RIGHT || ev.getKeyCode() == KeyEvent.VK_DOWN || ev.getKeyCode() == KeyEvent.VK_LEFT || ev.getKeyCode() == KeyEvent.VK_UP) return true; else return false; }
8
public Location getAdjacentLocation(int direction) { // reduce mod 360 and round to closest multiple of 45 int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE; if (adjustedDirection < 0) adjustedDirection += FULL_CIRCLE; adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT; int dc = 0; int dr = 0; if (adjustedDirection == EAST) dc = 1; else if (adjustedDirection == SOUTHEAST) { dc = 1; dr = 1; } else if (adjustedDirection == SOUTH) dr = 1; else if (adjustedDirection == SOUTHWEST) { dc = -1; dr = 1; } else if (adjustedDirection == WEST) dc = -1; else if (adjustedDirection == NORTHWEST) { dc = -1; dr = -1; } else if (adjustedDirection == NORTH) dr = -1; else if (adjustedDirection == NORTHEAST) { dc = 1; dr = -1; } return new Location(getRow() + dr, getCol() + dc); }
9
private void returnBook(String bookTitle) { for (Book currBook : list) { if (currBook.getTitle().equals(bookTitle)) { if (currBook.isBorrowed()) { currBook.returned(); System.out.println("You successfully returned " + currBook.getTitle()); return; } } } System.out.println("This book doesn't belong to us."); }
3
public void actionPerformed(ActionEvent e) { Object obj; if ((obj = e.getSource()) == bFile) { JFileChooser filechooser = new JFileChooser(new File("./")); int selected = filechooser.showOpenDialog(this); if (selected == JFileChooser.APPROVE_OPTION) { File file = filechooser.getSelectedFile(); newRun.createMaze(file.getPath()); initMaze(); fileName.setText("Opened file: " + file.getName()); bStart.setEnabled(true); } else if (selected == JFileChooser.CANCEL_OPTION) { fileName.setText("Operation canceled"); } else if (selected == JFileChooser.ERROR_OPTION) { fileName.setText("Error opening file"); } } else if (obj == bClear) { bStart.setEnabled(false); bNext.setEnabled(false); unsetColor(); newRun.resetAll(); initMaze(); } else if (obj == bReset) { bStart.setEnabled(true); bNext.setEnabled(false); unsetColor(); newRun.resetDroid(); initMaze(); } else if (obj == bNext) { unsetColor(); newRun.makeNextMove(); setColors(); updateMaze(); } else if (obj == bStart) { bStart.setEnabled(false); bNext.setEnabled(true); startMaze(); setColors(); } else { JOptionPane.showMessageDialog(this, "Something went wrong..."); } } // end method
8
private String IaddINode(String resource_id, String inode_id) { String node_id = null; String resource_node_id = null; OrientGraph graph = null; try { node_id = getINodeId(resource_id,inode_id); if(node_id != null) { //System.out.println("Node already Exist: region=" + region + " agent=" + agent + " plugin=" + plugin); } else { resource_node_id = getResourceNodeId(resource_id); if(resource_node_id == null) { resource_node_id = addResourceNode(resource_id); } if(resource_node_id != null) { graph = factory.getTx(); Vertex fromV = graph.addVertex("class:iNode"); fromV.setProperty("inode_id", inode_id); fromV.setProperty("resource_id", resource_id); //ADD EDGE TO RESOURCE Vertex toV = graph.getVertex(resource_node_id); graph.addEdge("class:isResource", fromV, toV, "isResource"); graph.commit(); node_id = fromV.getId().toString(); } } } catch(com.orientechnologies.orient.core.storage.ORecordDuplicatedException exc) { //eat exception.. this is not normal and should log somewhere System.out.println("Error 0 " + exc.getMessage()); } catch(com.orientechnologies.orient.core.exception.OConcurrentModificationException exc) { //eat exception.. this is normal System.out.println("Error 1 " + exc.getMessage()); } catch(Exception ex) { long threadId = Thread.currentThread().getId(); System.out.println("IaddINode: thread_id: " + threadId + " Error " + ex.toString()); } finally { if(graph != null) { graph.shutdown(); } } return node_id; }
7
@Override public void update(Observable arg0, Object arg1) { if (presenter.getState().isInAnyPlayingState()) { getPointsView().setPoints(presenter.getClientModel().getServerModel().getPlayers().get(presenter.getPlayerInfo().getIndex()).getVictoryPoints()); if (presenter.getClientModel().getServerModel().getWinner() > -1) { if (presenter.getPlayerInfo().getIndex() == presenter.getClientModel().getServerModel().getWinner()) { getFinishedView().setWinner(presenter.getClientModel().getServerModel().getPlayers().get(presenter.getPlayerInfo().getIndex()).getName(), true); getFinishedView().showModal(); } else { getFinishedView().setWinner(presenter.getClientModel().getServerModel().getPlayers().get(presenter.getPlayerInfo().getIndex()).getName(), false); getFinishedView().showModal(); } } } }
3
public static void main(String[] args) throws Exception { if(args.length < 2) { System.out.println("Usage: java JGrep (file or directory) regex"); System.exit(0); } Pattern p = Pattern.compile(args[1]); if(!(findDir(args[0], p) || findFile(args[0], p))) { if(new File(args[0]).listFiles() == null) { System.out.println("no such directory: " + args[0]); System.exit(0); } File[] files = new File(args[0]).listFiles(); System.out.println(args[0] + ": subdir of files: " + Arrays.asList(files)); for(File f : files) { int index = 0; Matcher m = p.matcher(""); for(String line : new TextFile(args[0] + "\\" + f.getName())) { m.reset(line); while(m.find()) { System.out.println(index++ + ": " + m.group() + ": " + m.start()); } } System.out.println(); } } }
7
public int calculateTotal() { total = 0; for (int i = 0; i < hand.size(); i++) { total += hand.get(i).getValue(); } return total; }
1
@Override public void mousePressed(MouseEvent evt) { int x = evt.getX(); int y = evt.getY(); if ((evt.getModifiersEx() & MouseEvent.BUTTON3_DOWN_MASK) == MouseEvent.BUTTON3_DOWN_MASK) { if (pd == PD.RightMouseB) { Dimension d = getSize(); jumpX = x; jumpY = y; // Draw distribution only inside the visible region if (jumpX > (0.75 * d.width)) jumpX = (int) (0.75 * d.width); if (jumpY > (0.75 * d.height)) jumpY = (int) (0.75 * d.height); repaint(); return;// true; } else return; } else if ((evt.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) == MouseEvent.BUTTON1_DOWN_MASK) { float bestDist = Float.MAX_VALUE; NodeGNG n; float dist; for (int i = 0 ; i < nNodes ; i++) { n = nodes[i]; dist = (n.x - x) * (n.x - x) + (n.y - y) * (n.y - y); if (dist <= bestDist) { pick = n; bestDist = dist; } } pickfixed = pick.isMouseSelected; pick.isMouseSelected = true; pick.x = x; pick.y = y; if (algo.isDiscrete()) pick.hasMoved = true; nodesMovedB = true; repaint(); } }
8
public void build() { for (int i = 1; i <= graph.V(); i++) { KK<Integer> next = new KK<>(graph); next.add(i); clusters.add(next); } List<WeightedGraph.Edge> edges = graph.edges(); Collections.sort(edges); int k = clusters.size(); int i = 0; while (k != K) { System.err.println("------------ " + k); for (i = 0; i < edges.size(); i++) { WeightedGraph.Edge next = edges.get(i); System.err.println("::" + i + " " + next.weight()); int either = next.either(); int other = next.other(either); KK clus1 = find(either); KK clus2 = find(other); if (clus1 != clus2) { k--; clus1.merge(clus2); clusters.remove(clus2); edges.remove(next); break; } } } for (i = 0; i < edges.size(); i++) { WeightedGraph.Edge next = edges.get(i); int either = next.either(); int other = next.other(either); KK clus1 = find(either); KK clus2 = find(other); if (clus1 != clus2) { break; } } System.err.println("DIST:" + (i) + " " + edges.get(i).weight()); for (KK next : clusters) { System.err.println("Cluster: " + next); } }
7
private void initValues() { try { enableFrameSkip.setSelected(Settings.get(Settings.AUTO_FRAME_SKIP).equals("true")?true:false); } catch (NullPointerException e) { enableFrameSkip.setSelected(false); } try { limitGameSpeed.setSelected(Settings.get(Settings.CPU_LIMIT_SPEED).equals("true")?true:false); } catch (NullPointerException e) { limitGameSpeed.setSelected(false); } try { autoSkipFrames.setValue(Settings.getInt(Settings.FRAMES_TO_SKIP)); } catch (NumberFormatException e) { autoSkipFrames.setValue(5); } }
5
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Een dispatcher verkrijgen van de request en er een JSP mee associeren RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW); // Een simpele dynamische boodschap genereren // Een groet die afhangt van het uur van de dag String message; Calendar calendar = Calendar.getInstance(); int uur = calendar.get(Calendar.HOUR_OF_DAY); if (uur >= 6 && uur < 12) { message = "Goede morgen,"; } else if (uur >= 12 && uur < 18) { message = "Goede middag,"; } else { message = "Goede avond,"; } // een attribuut toevoegen aan de request request.setAttribute("naamDieInJSPKanAangesprokenWorden", message); // de request forwarden naar de JSP dispatcher.forward(request, response); }
4
private void downdatePosition() { if (direction == 1) { pos_y++; } if (direction == 2) { pos_x++; } if (direction == 3) { pos_y--; } if (direction == 4) { pos_x--; } System.out.println(name + ": new position (down) " + pos_x + " " + pos_y); }
4
private Entry<K,V> successor(Entry<K,V> t) { if (t == null) return null; else if (t.right != null) { Entry<K,V> p = t.right; while (p.left != null) p = p.left; return p; } else { Entry<K,V> p = t.parent; Entry<K,V> ch = t; while (p != null && ch == p.right) { ch = p; p = p.parent; } return p; } }
5
@Override public void actionPerformed(ActionEvent e) { // File Menu if (e.getActionCommand().equals(OK)) { main_ok(); } else if (e.getActionCommand().equals(APPLY)) { main_apply(); } else if (e.getActionCommand().equals(CANCEL)) { main_cancel(); } }
3