text
stringlengths
14
410k
label
int32
0
9
static public Menu getInstance() { if (m_instance == null) { m_instance = new Menu(); } return m_instance; }
1
public void play(String soundName) { Sound sound = sounds.get(soundName); if (sound != null) { sound.play(); } }
1
public void enemyAttacks() { // will choose a random square to attack in UserPanel if (canAttack) { enemyTarget = rand.nextInt(25); // get a target while (!battleSquare[enemyTarget].isEnabled()) { // check to see if the JButton is enabled // if JButton is not enabled, get a new target enemyTarget = rand.nextInt(25); } battleSquare[enemyTarget].setEnabled(false); canAttack = false; if (battleSquare[enemyTarget].getText().equals("SHIP")) { enemyHits++; battleSquare[enemyTarget].setText(""); battleSquare[enemyTarget].setIcon(boomIcon); } if (enemyHits == MAX_SCORE) { JOptionPane.showMessageDialog(null, "You Lost!"); System.exit(0); } } }
4
public T execute() throws SQLException { Connection conn = null; SQLException toThrow = null; T back = null; try { conn = factory.getConnection(); conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); conn.setAutoCommit(false); back = Transaction.this.run(); conn.commit(); } catch (SQLException e) { if (conn != null) { try {conn.rollback(); } catch (SQLException e1) { /* toHandle */ } } toThrow = e; } finally { if (conn == null) { return null; } try { conn.setAutoCommit(true); conn.close(); } catch (SQLException e) { } } if (toThrow != null) { throw toThrow; } return back; }
6
public Case(int x, int y) { Coordinates coord = new Coordinates(x, y); state = false; for (int a = 0; a < walls.length; a++) { walls[a] = true; } }
1
private SoundManager() { try { startClip = initSound("/sounds/start.wav"); warnClip = initSound("/sounds/warn.wav"); overClip = initSound("/sounds/over.wav"); } catch (UnsupportedAudioFileException e) { handleError("Wrong audio file!", e); } catch (IOException e) { handleError("Cannot read audio file!", e); } catch (LineUnavailableException e) { handleError("Problem with audio file!", e); } }
3
@Override public Object execute(HttpServletRequest request, HttpServletResponse response) throws Exception { Contexto oContexto = (Contexto) request.getAttribute("contexto"); oContexto.setVista("jsp/backlog/list.jsp"); try { BacklogDao oBacklogDAO = new BacklogDao(oContexto.getEnumTipoConexion()); Integer intPages = oBacklogDAO.getPages(oContexto.getNrpp(), oContexto.getAlFilter(), oContexto.getHmOrder()); Integer intRegisters = oBacklogDAO.getCount(oContexto.getAlFilter()); if (oContexto.getPage() >= intPages) { oContexto.setPage(intPages); } if (oContexto.getPage() < 1) { oContexto.setPage(1); } ArrayList<BacklogBean> listado = oBacklogDAO.getPage(oContexto.getNrpp(), oContexto.getPage(), oContexto.getAlFilter(), oContexto.getHmOrder()); String strUrl = "<a href=\"Controller?" + oContexto.getSerializedParamsExceptPage() + "&page="; ArrayList<String> vecindad = Pagination.getButtonPad(strUrl, oContexto.getPage(), intPages, 2); ArrayList<Object> a = new ArrayList<>(); a.add(listado); a.add(vecindad); a.add(intRegisters); return a; } catch (Exception e) { throw new ServletException("BacklogList1: View Error: " + e.getMessage()); } }
3
public void onGrowth(Tile t) { if (! structure.intact()) return ; // // Here, we average fertility over the plantation as a whole- // TODO: Possibly combine with irrigation effects from water supply or // life support? float avgMoisture = 0, count = 0 ; for (Plantation p : strip) { final Tile o = p.origin() ; for (int c = 0, i = 0 ; c < 4 ; c++) { final Tile u = world.tileAt( o.x + CROPS_POS[i++], o.y + CROPS_POS[i++] ) ; avgMoisture += u.habitat().moisture() ; count++ ; } } avgMoisture /= count * 10 ; if (type == TYPE_COVERED) avgMoisture = (avgMoisture + 1) / 2f ; // // Then apply growth to each crop- boolean anyChange = false ; for (Crop c : planted) if (c != null) { final int oldGrowth = (int) c.growStage ; c.doGrowth(avgMoisture, 0.25f) ; final int newGrowth = (int) c.growStage ; if (oldGrowth != newGrowth) anyChange = true ; world.ecology().impingeBiomass(this, c.health * c.growStage / 2f, true) ; } checkCropStates() ; if (anyChange) refreshCropSprites() ; }
8
public void setCipherValue(byte[] value) { this.cipherValue = value; }
0
public List<Integer> getIntegerList(String path) { List<?> list = getList(path); if (list == null) { return new ArrayList<Integer>(0); } List<Integer> result = new ArrayList<Integer>(); for (Object object : list) { if (object instanceof Integer) { result.add((Integer) object); } else if (object instanceof String) { try { result.add(Integer.valueOf((String) object)); } catch (Exception ex) { } } else if (object instanceof Character) { result.add((int) ((Character) object).charValue()); } else if (object instanceof Number) { result.add(((Number) object).intValue()); } } return result; }
8
public void getInput() { String command; Scanner inFile = new Scanner(System.in); do { this.display(); // display the menu // get commaned entered command = inFile.nextLine(); command = command.trim().toUpperCase(); switch (command) { case "B": this.helpMenuControl.displayBoardHelp(); break; case "C": this.helpMenuControl.displayCardChoiceHelp(); break; case "H": this.helpMenuControl.displayGameHelp(); break; case "O": this.helpMenuControl.displayOptionsHelp(); break; case "P": this.helpMenuControl.displayPlayersHelp(); break; case "Q": break; default: new MemoryError().displayError("Invalid command. Please enter a valid command."); continue; } } while (!command.equals("Q")); return; }
7
public void addUniform(String uniform) { int uniformLocation = glGetUniformLocation(program, uniform); if(uniformLocation == 0xFFFFFFFF) { System.err.println("Error: Could not find uniform: " + uniform); new Exception().printStackTrace(); System.exit(1); } uniforms.put(uniform, uniformLocation); }
1
private int[] getCheckedCrossP(float[] crosspoint, int[] originalpoint) { //Funktion prueft, ob der Endpunkt einer Linie nicht besser auf einer Anderen anstatt in der Luft liegen sollte //Richtungsvektor konstruieren int[] rp = new int[2]; float[] dv = new float[2]; dv[0] = originalpoint[0] - crosspoint[0]; dv[1] = originalpoint[1] - crosspoint[1]; if(Mat.getDistance(crosspoint, originalpoint) < 20) { if(dv[0] > 0) { //In positive Richtung runden rp[0] = (int) Math.ceil(crosspoint[0]); } else { //In negative Richtung runden rp[0] = (int) Math.floor(crosspoint[0]); } if(dv[1] > 0) { //In positive Richtung runden rp[1] = (int) Math.ceil(crosspoint[1]); } else { //In negative Richtung runden rp[1] = (int) Math.floor(crosspoint[1]); } } else { rp[0] = -1; rp[1] = -1; } return(rp); }
3
public static CoreType parseCoreType(String type) { if (type.equals(CLIENTE.toString())) return CLIENTE; else if (type.equals(HUB.toString())) return HUB; else if (type.equals(BASESTATION.toString())) return BASESTATION; else return null; }
3
public static void eatFlowerIfCollided(OneFlower o) { if (o.x == o.fx && o.y == o.fy) { o.score++; if (o.score == 75) { try { FileOutputStream out = new FileOutputStream(new File(System.getenv("APPDATA") + "\\OneFlower\\HardModeLock.data")); out.write(getSignedBytes((byte)0)); out.close(); Main.hardModeUnlocked = true; Main.updateHardModeButton(); } catch (Throwable t) { t.printStackTrace(); } } replaceFlower(o); } }
4
static public Vector3f findSimplex(List<Vector3f> simplex){ switch(simplex.size()){ case 2: return findLineSimplex(simplex); case 3: return findTriangleSimplex(simplex); default: return findTetrahedronSimplex(simplex); } }
2
public static VehicleModesOfTransportEnumeration fromString(String v) { if (v != null) { for (VehicleModesOfTransportEnumeration c : VehicleModesOfTransportEnumeration.values()) { if (v.equalsIgnoreCase(c.toString())) { return c; } } } throw new IllegalArgumentException(v); }
3
@Override public void run() { while (true) { try { Socket clientSocket = mServerSocket.accept(); Messenger messenger = new Messenger(clientSocket, mNotifyDisconnection); messenger.start(); mConnectedClients.add(messenger); if (mListener != null) mListener.onClientConnected(messenger); } catch (IOException e) { break; } } }
3
public int readByte() throws IOException { if(bNextByteIs255) return (byte)255; bNextByteIs255 = false; if(fakeInput!=null) throw new java.io.InterruptedIOException("."); if((rawin!=null) && (rawin.available()>0)) { final int read = rawin.read(); if(read==-1) throw new java.io.InterruptedIOException("."); if(debugBinInput && Log.debugChannelOn()) debugBinInputBuf.append(read).append(" "); return read; } throw new java.io.InterruptedIOException("."); }
7
public static String hashMapToString(Map<?, ?> dataUploadStatusMap, String seperator) { List<Entry<?, ?>> list = new ArrayList<Entry<?, ?>>(dataUploadStatusMap.entrySet()); return buildString('{', displayArray(list.toArray(), seperator), '}'); }
6
@Override public void executeMsg(Environmental oking, CMMsg msg) { super.executeMsg(oking,msg); if(affected instanceof MOB) { final MOB mob=(MOB)affected; if((msg.source()==mob) &&(msg.target()==mob.location()) &&(msg.targetMinor()==CMMsg.TYP_LEAVE)) unInvoke(); else if((CMLib.flags().isStanding(mob))||(CMLib.flags().isSleeping(mob))) unInvoke(); else if((msg.amITarget(mob))&&(msg.targetMinor()==CMMsg.TYP_GIVE)) msg.addTrailerMsg(CMClass.getMsg(mob,msg.source(),CMMsg.MSG_SPEAK,L("^T<S-NAME> say(s) 'Thank you gov'ner!' to <T-NAME> ^?"))); } }
8
private void modify() { delete(); modifiedObjectLoc = selectedObject.getLocationCopy(); switch (selectedObject.getObjectType()) { case DEFAULT: break; case SHAPE: new ShapeMaker((MainFrame) frame, selectedObject); break; case RECTANGLE: new RectangleMaker((MainFrame) frame, selectedObject); break; case ELLIPSE: new EllipseMaker((MainFrame) frame, selectedObject); break; case TEXT: new TextMaker((MainFrame) frame, (Text) selectedObject); break; case IMAGE: image(); break; case LATEX: latex(); } }
7
public long add(long millis, long value) { int year = get(millis); int newYear = year + FieldUtils.safeToInt(value); if (year < 0) { if (newYear >= 0) { newYear++; } } else { if (newYear <= 0) { newYear--; } } return set(millis, newYear); }
3
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed if(!cdb.getText().isEmpty()){ Buscar bs = new Buscar(); bs.setVisible(true); } else{ if(!idb.getText().isEmpty()){ Buscar bs = new Buscar(); bs.setVisible(true); } else{ proyecto.Error error = new proyecto.Error(this, true); error.ready("Porfavor, llene al menos un campo."); error.setVisible(true); } } }//GEN-LAST:event_jButton4ActionPerformed
2
private void move() { switch (dir) { case 0: if (x > player.getX()) { left(); } if (x < player.getX()-20) { right(); } break; case 2: if (x > player.getX()) { left(); } if (x < player.getX()) { right(); } break; default: break; } }
6
public static void textPack(byte packedData[], String text) { if (text.length() > 80) { text = text.substring(0, 80); } text = text.toLowerCase(); int carryOverNibble = -1; int ofs = 0; for (int idx = 0; idx < text.length(); idx++) { char c = text.charAt(idx); int tableIdx = 0; for (int i = 0; i < TranslationConstants.CHARACTER_XLATE_TABLE.length; i++) { if (c == (byte) TranslationConstants.CHARACTER_XLATE_TABLE[i]) { tableIdx = i; break; } } if (tableIdx > 12) { tableIdx += 195; } if (carryOverNibble == -1) { if (tableIdx < 13) { carryOverNibble = tableIdx; } else { packedData[ofs++] = (byte) tableIdx; } } else if (tableIdx < 13) { packedData[ofs++] = (byte) ((carryOverNibble << 4) + tableIdx); carryOverNibble = -1; } else { packedData[ofs++] = (byte) ((carryOverNibble << 4) + (tableIdx >> 4)); carryOverNibble = tableIdx & 0xf; } } if (carryOverNibble != -1) { packedData[ofs++] = (byte) (carryOverNibble << 4); } }
9
@Override public List<User> findUserByEventId(int eventId) { List<User> list = new ArrayList<User>(); Connection cn = null; PreparedStatement ps = null; ResultSet rs = null; try { cn = ConnectionHelper.getConnection(); ps = cn.prepareStatement(QTPL_SELECT_BY_EVENT_ID); ps.setInt(1, eventId); rs = ps.executeQuery(); while (rs.next()) { list.add(processResultSet(rs)); } } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } try { cn.close(); } catch (SQLException e) { e.printStackTrace(); } } return list; }
5
public void dragDropEnd(DragSourceDropEvent dsde) { Canvas canvas = (Canvas) dsde.getDragSourceContext().getComponent(); CanvasModel canvasModel = canvas.getCanvasModel(); Rectangle bounds = null; try { bounds = (Rectangle) dsde.getDragSourceContext().getTransferable().getTransferData(widgetFlavor); } catch (UnsupportedFlavorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if ( dsde.getDropSuccess() ) { if ( dsde.getDropAction() == DnDConstants.ACTION_MOVE) { // we need to remove the source element now Point p = new Point(bounds.x,bounds.y); CanvasWidget widget = null; for ( CanvasWidget searchWidget : canvasModel.widgetList ) { if ( searchWidget.getBounds().getLocation().equals(p) ) widget = searchWidget; } if ( widget != null) canvasModel.remove(widget); } } else { // we need to mark it as no longer moving Point p = new Point(bounds.x,bounds.y); CanvasWidget widget = canvasModel.getWidgetAt(p); widget.setMoving(false); canvasModel.notifyModelChanged(); } }
7
public void run() { while (ok != -1) { try { runs = true; lm.waitForEvent(); if (conn.isClosed()) { ok = -1; } } catch (InterruptedException e) { interrupt(); ok = -1; } try { if (ok != -1) { readAndPrintMsg(); getAndPrintConnected(); ok = writeGameName(); os.flush(); } } catch (IOException e) { // e.printStackTrace(); ok = -1; } if (this.isInterrupted()) { return; // keep socket } } runs = false; lm.deRegister(this); return; }
6
public String find(Statement stmt, String comboBox, String textField) { DefaultTableModel model = (DefaultTableModel) table.getModel(); model.setRowCount(0); if (stmt != null) { try { if (comboBox.equals("Αριθμό Διαβατηρίου")) { rs = stmt.executeQuery("select patient.*, medical_info.mid from patient JOIN medical_info on patient.pid = medical_info.pid where patient.pid = '" + textField + "';"); } else if (comboBox.equals("Αριθμό Φακέλου")) { rs = stmt.executeQuery("select patient.*, medical_info.mid from patient JOIN medical_info on patient.pid = medical_info.pid where medical_info.mid = '" + textField + "';"); } else if (comboBox.equals("Επώνυμο Ασθενή")) { rs = stmt.executeQuery("select patient.*, medical_info.mid from patient JOIN medical_info on patient.pid = medical_info.pid where patient.last_name = '" + textField + "';"); } else if (comboBox.equals("Όνομα Ασθενή")) { rs = stmt.executeQuery("select patient.*, medical_info.mid from patient JOIN medical_info on patient.pid = medical_info.pid where patient.first_name = '" + textField + "';"); } } catch (SQLException es) { System.out.println("Unable to create statement "); System.out.println(rs); return null; } } if (rs != null) { try { rs.previous(); while (rs.next()) { this.pid = rs.getString("pid"); this.fn = rs.getString("first_name"); this.ls = rs.getString("last_name"); this.dob = rs.getString("date_of_birth"); this.addr = rs.getString("address"); this.ct = rs.getString("city"); this.pc = rs.getString("post_code"); this.ph = rs.getString("phone"); this.it = rs.getString("insurance_type"); this.mid = rs.getString("mid"); model.addRow(new Object[]{fn, ls, dob, addr, ct, pc, pid, ph, it, mid}); } System.out.printf("NAME IS " + fn + " PASSPORT NUM IS " + pid + " MID IS " + mid + "%n"); return "Found"; } catch (SQLException e) { System.out.println("Unable to iterate over resultset"); JOptionPane.showMessageDialog(null, "Δεν βρέθηκε ασθενής", "Ανεπιτυχής Αναζήτηση", JOptionPane.ERROR_MESSAGE); model.setRowCount(0); return "This PID does not exist"; } } return "ERROR"; }
9
public void test_DateTime_new_Turk() { try { new DateTime(2007, 4, 1, 0, 0, 0, 0, MOCK_TURK); fail(); } catch (IllegalInstantException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } }
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 ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(STATUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ try { Thread.sleep(3000); } catch(InterruptedException ex) { } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new STATUI().setVisible(true); } }); }
4
private void siftUp(int pos) { if (pos == 0) return; if (heap.get(pos).compareTo(heap.get(pos / 2)) > 0){ swap(pos, pos / 2); siftUp(pos / 2); } }
2
public static List<String> command(String command) { boolean err = false; List<String> list = new LinkedList<String>(); try { Process process = new ProcessBuilder(command.split(" ")).start(); BufferedReader results = new BufferedReader(new InputStreamReader( process.getInputStream())); String s; while((s = results.readLine()) != null) { list.add(s); } BufferedReader errors = new BufferedReader(new InputStreamReader( process.getErrorStream())); // Report errors and return nonzero value // to calling process if there are problems: while((s = errors.readLine()) != null) { System.err.println(s); err = true; } } catch(Exception e) { // Compensate for Windows 2000, which throws an // exception for the default command line: if(!command.startsWith("CMD /C")) { command("CMD /C " + command); } else { throw new RuntimeException(e); } } if(err) { throw new OSExecuteException("Errors executing " + command); } return list; }
5
public static byte[] getMacAddress() { if(cachedMacAddress != null && cachedMacAddress.length >= 10) { return cachedMacAddress; } try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while(networkInterfaces.hasMoreElements()) { NetworkInterface network = networkInterfaces.nextElement(); byte[] mac = network.getHardwareAddress(); if(mac != null && mac.length > 0) { cachedMacAddress = new byte[mac.length * 10]; for(int i = 0; i < cachedMacAddress.length; i++) { cachedMacAddress[i] = mac[i - (Math.round(i / mac.length) * mac.length)]; } return cachedMacAddress; } } } catch (SocketException e) { Logger.logWarn("Failed to get MAC address, using default logindata key", e); } return new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; }
7
private void kingRightPossibleMove(Piece piece, Position position) { int x1 = position.getPositionX(); int y1 = position.getPositionY(); if((x1 >= 0 && y1 >= 0) && (x1 <= 6 && y1 < maxHeight)) { if(board.getChessBoardSquare(x1+1, y1).getPiece().getPieceType() != board.getBlankPiece().getPieceType()) { if(board.getChessBoardSquare(x1+1, y1).getPiece().getPieceColor() != piece.getPieceColor()) { // System.out.print(" " + coordinateToPosition(x1+1, y1)+"*"); Position newMove = new Position(x1+1, y1); piece.setPossibleMoves(newMove); } } else { // System.out.print(" " + coordinateToPosition(x1+1, y1)); Position newMove = new Position(x1+1, y1); piece.setPossibleMoves(newMove); } } }
6
public void sendDeleteUser() throws IOException{ String str = new String("deleteuser"+ "," + oldUsernameFld.getText()); System.out.println(str); InetAddress serverAddr= null; try { serverAddr= InetAddress.getByName(GlobalV.serverIP); } catch (UnknownHostException e1) { e1.printStackTrace(); } Socket socket = null; try { System.out.println("sending deleteuser to server"); socket = new Socket(serverAddr, GlobalV.sendingPortLogin); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } PrintWriter out = null; try { out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.println(str); System.out.print("delete user sent"); socket.close(); }
4
protected void handleMouseMoved(MouseEvent event) { synchronized (simulator) { if (simulator.isRunning()) { return; } if (inspector == null) { inspector = new CreatureInspector(); } Point2D point; try { point = getTransform().inverseTransform(event.getPoint(), null); } catch (NoninvertibleTransformException e) { throw new RuntimeException(e); } Iterator<ICreature> nearBy = simulator.creaturesNearByAPoint(point, 10.0).iterator(); if (!nearBy.hasNext()) { inspector.setCreature(null); return; } if (!inspector.isVisible()) { inspector.setVisible(true); } inspector.setCreature(nearBy.next()); } }
5
@Override public long getIdleTimeout() { return idleTimeout; }
0
private void finishText() { if (currentText != null) { String strValue = currentText.toString(); if (currentTextObject != null) { if (DefaultXmlNames.ELEMENT_Unicode.equals(insideElement)) { currentTextObject.setText(strValue); } else if (DefaultXmlNames.ELEMENT_PlainText.equals(insideElement)) { currentTextObject.setPlainText(strValue); } } if (metaData != null) { if (DefaultXmlNames.ELEMENT_Creator.equals(insideElement)) { metaData.setCreator(strValue); } else if (DefaultXmlNames.ELEMENT_Comments.equals(insideElement)) { metaData.setComments(strValue); } else if (DefaultXmlNames.ELEMENT_Created.equals(insideElement)) { metaData.setCreationTime(parseDate(strValue)); } else if (DefaultXmlNames.ELEMENT_LastChange.equals(insideElement)) { metaData.setLastModifiedTime(parseDate(strValue)); } } currentText = null; } }
9
private void parseFile(PDFPassword password) throws IOException { // start at the begining of the file fileBuf.rewind(); String versionLine = readLine(fileBuf); if (versionLine.startsWith(VERSION_COMMENT)) { processVersion(versionLine.substring(VERSION_COMMENT.length())); } fileBuf.rewind(); fileBuf.position(fileBuf.limit() - 1); if (!backscan(fileBuf, "startxref")) { throw new PDFParseException("This may not be a PDF File"); } int postStartXrefPos = fileBuf.position(); // ensure that we've got at least one piece of whitespace here, which // should be a carriage return if (!isWhiteSpace(fileBuf.get())) { throw new PDFParseException("Found suspicious startxref without " + "trialing whitespace"); } final StringBuilder xrefBuf = new StringBuilder(); char c = (char) nextNonWhitespaceChar(fileBuf); while (c >= '0' && c <= '9') { xrefBuf.append(c); c = (char) fileBuf.get(); } int xrefpos = Integer.parseInt(xrefBuf.toString()); fileBuf.position(xrefpos); try { readTrailersAndXrefs(password); } catch (UnsupportedEncryptionException e) { throw new PDFParseException(e.getMessage(), e); } }
6
public Boolean getDataTable(JTable table) { int y = 0; for (int i = 0; i < table.getRowCount(); i++) { System.out.println(table.getValueAt(i, 2)); lista.add(new ConstansToken(table.getValueAt(i, 0).toString(), i, table.getValueAt(i, 1).toString(), (Boolean) table.getValueAt(i, 2))); y = i; } lista.add(new ConstansToken(this.s[y + 2], y + 1, "", false)); return true; }
1
public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA28_49 = input.LA(1); int index28_49 = input.index(); input.rewind(); s = -1; if ( (( isCall() )) ) {s = 26;} else if ( (true) ) {s = 4;} input.seek(index28_49); if ( s>=0 ) return s; break; case 1 : int LA28_60 = input.LA(1); int index28_60 = input.index(); input.rewind(); s = -1; if ( (( isCall() )) ) {s = 26;} else if ( (true) ) {s = 4;} input.seek(index28_60); if ( s>=0 ) return s; break; } NoViableAltException nvae = new NoViableAltException(getDescription(), 28, _s, input); error(nvae); throw nvae; }
8
private void resultComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resultComboBoxActionPerformed // TODO add your handling code here: Sorter sort = new Sorter(DATA_POINTS); String optionChosen = sortComboBox.getSelectedItem().toString(); int mode = resultComboBox.getSelectedItem().toString().equals("Low to High") ? Sorter.LOW_TO_HIGH : Sorter.HIGH_TO_LOW; String data[][] = {}; if(optionChosen.equals(dataTableHeader[0])) { data = sort.sortBest(recentData, 0, mode); } else if(optionChosen.equals(dataTableHeader[1])) { data = sort.sortBest(recentData, 1, mode); } else if(optionChosen.equals(dataTableHeader[2])) { data = sort.sortBest(recentData, 2, mode); } else if(optionChosen.equals(dataTableHeader[3])) { data = sort.sortBest(recentData, 3, mode); } else if(optionChosen.equals(dataTableHeader[4])) { // Penalties box! Make another sorter! data = sort.filterPenalties(recentData, 4, mode); } else { System.err.println("OH GOD! THE BLOOD!! ITS EVERYWHERE"); System.exit(1); } displayData(data); updateTitle(recentTeamNumber + " - " + optionChosen); }//GEN-LAST:event_resultComboBoxActionPerformed
6
protected String getPresentationName() { if (countDifferences(oldValue, newValue) == 1) { for (Features feature : Features.values()) { if (feature.isChosen(oldValue) != feature.isChosen(newValue)) { if (feature.isChosen(newValue)) { return "set cell " + feature.toString(); } else { return "unset cell " + feature.toString(); } } } } return "change cell features"; }
4
public void clean() { ArrayList<String> Temp = new ArrayList<String>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!Temp.contains(line)) { Temp.add(line); } } writeArrayList(Temp); }
2
public BigAirplaneImage(String imageURL, int color) { super(imageURL); this.color=color; frameNumber=0; // initial frameNumber is 0 totalFrame=3; delayCounter=0; if(color==1) { this.setImage(frameNumber*65+frameNumber+5, yLocationSpriteSheet, width,height ,newWidth, newHeight); } else { this.setImage(xLocationSpriteSheet+frameNumber*65+frameNumber,yLocationSpriteSheet, width,height ,newWidth, newHeight); } }
1
public void mousePressed(MouseEvent paramMouseEvent) { Point localPoint1 = ClickDelegator.this.CurrentRenderer.getOffset(); Point localPoint2 = new Point(paramMouseEvent.getX() / 50 + localPoint1.x, paramMouseEvent.getY() / 50 + localPoint1.y); if (ClickDelegator.this.CurrentScene.getShroud().isVisible(localPoint2)) { Vector localVector = ClickDelegator.this.CurrentScene.getObjectAt(localPoint2); if (localVector != null) { for (int i = 0; i < localVector.size(); i++) { ((PhysicalObject)localVector.elementAt(i)).handleMouseClick(paramMouseEvent); } } } ClickDelegator.this.CurrentRenderer.requestFocus(); }
3
void nextCharNoPrint() throws Exception { if ((line == null) || (++linePos >= line.length())) { line = reader.readLine(); if (line != null) { while (line.length() > 0 && line.charAt(0) == ';') { line = reader.readLine(); } line += " "; linePos = 0; ch = line.charAt(0); } else { ch = 0; } } else { while (line.length() > 0 && line.charAt(linePos) == ';') { line = reader.readLine(); linePos = 0; nextChar(); } ch = line.charAt(linePos); } }
7
public static void rmDupChar(BufferedInputStream in) { if(in.markSupported()){ in.mark(256); try { count = in.read(b); String str = new String(b, 0, count); c = str.toCharArray(); } catch (IOException e) { e.printStackTrace(); } } a.add(c[0]); for(i = 1; i < count; i++){ temp = c[i]; for(j = 0; j < i-1; j++){ if (c[j]==temp) break; } if(j == i-1) a.add(temp); } }
6
public void actionPerformed(ActionEvent e) { if(e.getActionCommand().compareTo("Copiar")==0) { if(this.getSelectedText()!=null) this.copy(); } else if(e.getActionCommand().compareTo("Cortar")==0) { if(this.getSelectedText()!=null) { this.cut(); state = false; } } else if(e.getActionCommand().compareTo("Pegar")==0) { this.paste(); state = false; } else if(e.getActionCommand().compareTo("Seleccionar todo")==0) { this.selectAll(); } }
6
public void moveVertex(Object vertex, Point2D point) { addVertex(vertex, point); }
0
@SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (obj instanceof Tuple<?,?>) { if(x.equals(((Tuple<X,Y>)obj).x) && y.equals(((Tuple<X,Y>)obj).y)) { return true; } } return false; }
5
public static double Testing() { try { BufferedWriter out = new BufferedWriter(new FileWriter("WrongTestingFaces.txt")); int correctTests = 0; for(Face f: testingFaces) { if(TestingSingleFaceCorrect(f)) { correctTests++; }else { String faceStr = f.Print();//printing wrong face out.write(faceStr); out.write("Above face is supposed to be " + f.isFace); out.newLine(); } } //System.out.println((double)correctTests/(double)testingFaces.size()); out.close(); return (double)correctTests/(double)testingFaces.size(); } catch (IOException e) { e.printStackTrace(); } return -1; }
3
public OrderResponse orderWithoutPayment(OrderRequest request) throws GongmingConnectionException, GongmingApplicationException { URL path = _getPath(ORDER_WITHOUT_PAYMENT); OrderResponse response = _POST(path, request, OrderResponse.class); if (response.code != GMResponseCode.COMMON_SUCCESS) { throw new GongmingApplicationException(response.code.toString(), response.errorMessage); } return response; }
1
public boolean isValid(String s) { if (s == null || s.isEmpty()) { return false; } Map<String, String> bracketsMap = new HashMap<String, String>(); bracketsMap.put("(", ")"); bracketsMap.put("{", "}"); bracketsMap.put("[", "]"); Stack<String> allBrackets = new Stack<String>(); String curBracket = null; boolean isMath = false; for (int i = 0; i < s.length(); i++) { curBracket = s.substring(i, i + 1); if (bracketsMap.containsKey(curBracket)) { allBrackets.push(curBracket); } else { if (allBrackets.isEmpty()) { return false; } isMath = curBracket.equals(bracketsMap.get(allBrackets.pop())); if (!isMath) { return false; } } } if (allBrackets.size() != 0) { return false; } else { return true; } }
7
private void logHistory(){ //Get the log file File log = new File(System.getProperty("user.home")+"/.history/log.txt"); File folder=new File(System.getProperty("user.home")+"/.history"); String next=System.getProperty("line.separator"); //If the show button been pressed try { //If the log file not exist, create one if(!folder.exists()){ folder.mkdirs(); } if (!log.exists()) { log.createNewFile(); } else { BufferedReader br = new BufferedReader(new FileReader(log)); String str = null; // history.setText(""); while ((str = br.readLine()) != null) { str.trim(); String[] strList=str.split(" "); if (strList[0].equals(videoFile.getAbsolutePath())){ if(strList[1].equals("start")){ // set up the start } else{ //set up the end } } } } } catch (IOException e1) { e1.printStackTrace(); } }
6
public IIbasics(int previousSession) { this.previousSession = previousSession;// always set at the start // set the title if (previousSession == 0) { setTitle("New Project"); } else { setTitle("Project"); } // set up the layout manager JPanel infoPanel = new JPanel(new GridBagLayout()); // give it a black border infoPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK)); // make a new GridBagConstraints GridBagConstraints gbc = new GridBagConstraints(); // set this as content pane setContentPane(infoPanel); // set size // infoPanel.setPreferredSize(new Dimension(350, 270)); // set exit setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // Set insets gbc.insets = defaultInsets; int i = 0; // set the weights gbc.weightx = 0.0; gbc.weighty = 0.0; // set the fill gbc.fill = GridBagConstraints.BOTH; // ---------------Adding // add label: Name of the new project glb = new JLabel("Name of new project:"); gbc.gridx = 0; gbc.gridy = i; infoPanel.add(glb, gbc); gbc.weightx = 1.0; // add Text Field: for name of school - c_tf gbc.gridx = 1; gbc.gridy = i; infoPanel.add(c_tf, gbc); i++;// 1 gbc.weightx = 0.0; // add label: Name of school glb = new JLabel("Name of school:"); gbc.gridx = 0; gbc.gridy = i; // infoPanel.add(glb, gbc); // add Text Field: for name of school - a_tf // a_tf.setText("OLMC"); gbc.gridx = 1; gbc.gridy = i; // infoPanel.add(a_tf, gbc); i++;// 2 // add label: Number of Periods glb = new JLabel("Number of periods:"); gbc.gridx = 0; gbc.gridy = i; infoPanel.add(glb, gbc); // add Text Field: for number of periods - b_tf gbc.gridx = 1; gbc.gridy = i; infoPanel.add(b_tf, gbc); if (previousSession == -1) { b_tf.setEnabled(false); // a_tf.setText(secondaryDataBase.nameOfSchool); b_tf.setText(Integer.toString(secondaryDataBase.amountOfPeriods)); c_tf.setText(secondaryDataBase.projectName); } i++;// 3 // add label: Number of grades in the school glb = new JLabel("Number of grades:"); gbc.gridx = 0; gbc.gridy = i; // infoPanel.add(glb, gbc); // add RadioButtons gbc.gridx = 1; gbc.gridy = i; // infoPanel.add(gradeNumPanel(), gbc); i++;// 4 // add label: Number of grades in the school glb = new JLabel("School starts at which grade:"); gbc.gridx = 0; gbc.gridy = i; // infoPanel.add(glb, gbc); // add Text Field: for number of grades - e_tf gbc.gridx = 1; gbc.gridy = i; // infoPanel.add(e_tf, gbc); i++;// 5 // add label: Number of grades in the school glb = new JLabel("Number of semesters:"); gbc.gridx = 0; gbc.gridy = i; // infoPanel.add(glb, gbc); // add Text Field: for number of semesters - d_tf gbc.gridx = 1; gbc.gridy = i; // infoPanel.add(d_tf, gbc); i++;// 6 // ------------------------------------Buttons gbc.gridwidth = 1; ca_Btn = new JButton("Clear All"); gbc.gridx = 0; gbc.gridy = i; gbc.gridwidth = 2; infoPanel.add(ca_Btn, gbc); if (previousSession == -1) {// if editing fileName (constructed from // editMenu) ca_Btn.setEnabled(false); } i++; cancel_Btn = new JButton("Cancel"); gbc.gridx = 0; gbc.gridy = i; gbc.gridwidth = 1; infoPanel.add(cancel_Btn, gbc); next_Btn = new JButton("Next"); gbc.gridx = 1; gbc.gridy = i; infoPanel.add(next_Btn, gbc); // ----------------------------------Add Action Listeners ca_Btn.addActionListener(new clearAllBtnClick()); next_Btn.addActionListener(new setLunchPrefernces()); if (previousSession == -1) { next_Btn.setText("Update"); } cancel_Btn.addActionListener(new cancelClick()); // ---------------------------Loading // TODO: Fix loading // previousSession is 1: previous template (session) will be loaded // Use: when user want to edit everything from start to finish // **The Time Table will be refreshed** if (previousSession == 1) { loadPreviousSession(); IIcourses.checkLoad(true); IIroomsAndDepts.checkLoad(true); IIlunchPrefs.checkLoad(true); } // previousSession is 2: only the previous session for this frame will // be loaded // Use: when back is clicked from the lunch preferences frame else if (previousSession == 2) { loadPreviousSession(); } // previousSession is 0: user gets a blank template else if (previousSession == 0) { IIcourses.checkLoad(false); IIroomsAndDepts.checkLoad(false); IIlunchPrefs.checkLoad(false); } // anything else input will result in a blank template (Nothing will be // loaded) // ---------------Pack pack(); }
7
public PageUnpinnedException(Exception e, String name){ super(e, name); }
0
@Override public final void addPart(final String string) { // parse of "instrument ..." final String[] s = string.split(" "); final MidiInstrument m = MidiInstrument.valueOf(s[0]); if (m == null) { setError(); return; } this.activeInstrument = m.createNewTarget(); targetList.add(this.activeInstrument); if (s.length == 2) { try { this.activeInstrument.setParam("map", Integer.valueOf(s[1])); } catch (final Exception e) { this.error = true; } } }
3
public static void banIP( String bannedBy, String player, String reason ) throws SQLException { if ( reason.equals( "" ) ) { reason = Messages.DEFAULT_BAN_REASON; } ArrayList<String> accounts = null; if ( Utilities.isIPAddress( player ) ) { accounts = PlayerManager.getPlayersAltAccountsByIP( player ); } else { accounts = PlayerManager.getPlayersAltAccounts( player ); } for ( String a : accounts ) { if ( !isPlayerBanned( a ) ) { SQLManager.standardQuery( "INSERT INTO BungeeBans (player,banned_by,reason,type,banned_on,banned_until) VALUES ('" + a + "', '" + bannedBy + "', '" + reason + "', 'ipban', NOW(), NULL)" ); } else { SQLManager.standardQuery( "UPDATE BungeeBans SET type='ipban' WHERE player ='" + a + "')" ); } if ( PlayerManager.isPlayerOnline( a ) ) { disconnectPlayer( a, Messages.IPBAN_PLAYER.replace( "{message}", reason ).replace( "{sender}", bannedBy ) ); } } if ( BansConfig.broadcastBans ) { PlayerManager.sendBroadcast( Messages.IPBAN_PLAYER_BROADCAST.replace( "{player}", player ).replace( "{message}", reason ).replace( "{sender}", bannedBy ) ); } else { PlayerManager.sendMessageToPlayer( bannedBy, Messages.IPBAN_PLAYER_BROADCAST.replace( "{player}", player ).replace( "{message}", reason ).replace( "{sender}", bannedBy ) ); } }
6
private Color mandlebrotColor(int x, int y) { final double cA = left + x * horizontalIncrement; //real component of c final double cB = top + y * verticalIncrement; //imaginary component of c double zA = cA; //real component of z double zB = cB; //imaginary component of z for(int i = 0; i < itr; i++) { double zATemp = (zA * zA - zB * zB) + cA; //z = z^2 + c zB = (2 * zA * zB) + cB; zA = zATemp; if(zA * zA + zB * zB > 4.0)//if escaped { // return new Color(4004*i); //bands of color //smooth coloring //these two more iterations reduce the size //of the error term zATemp = (zA * zA - zB * zB) + cA; //z = z^2 + c zB = (2 * zA * zB) + cB; zA = zATemp; zATemp = (zA * zA - zB * zB) + cA; //z = z^2 + c zB = (2 * zA * zB) + cB; zA = zATemp; double magnitude = Math.sqrt(zA * zA + zB * zB); float fraction = (float) (i - (Math.log10(Math.log10(magnitude))) / Math.log10(2.0)) / itr; return Color.getHSBColor(.6f + 10f * fraction, .6f, 1); } } return Color.black; //if not escaped }
2
public static ABObject GetRoof (HashMap<ABObject, List<ABObject>> leftSupportee, HashMap<ABObject, List<ABObject>> rightSupportee) { List<ABObject> sameList = new ArrayList<ABObject>(); for (ABObject ab: leftSupportee.keySet()) { List<ABObject> leftList = leftSupportee.get(ab); for (ABObject ab1 : rightSupportee.keySet()) { List<ABObject> rightList = rightSupportee.get(ab1); for (int i = 0; i < leftList.size(); i++) { for (int j = 0 ; j < rightList.size(); j++) { if (leftList.get(i).id == rightList.get(j).id) { if (leftList.get(i).depth <= rightList.get(j).id) sameList.add(leftList.get(i)); else sameList.add(rightList.get(i)); } } } } } int min = Integer.MAX_VALUE; ABObject roof = null; for (int i = 0; i < sameList.size(); i++) { ABObject x = sameList.get(i); if (x.depth <= min) { roof = x; min = x.depth; } } return roof; }
8
public void showMiniMap(boolean s) { if (miniMapHUD != null) { miniMapHUD.shouldRender = s; } }
1
public int sendIP(String username){ try { String host = "localhost"; socket = new Socket(host, 2001); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); } catch (IOException ex) { Logger.getLogger(ServerCommunicator.class.getName()).log(Level.SEVERE, null, ex); } try { out.println("SENDIP"); if(in.readLine().startsWith("Ok")){ String ip = InetAddress.getLocalHost().toString(); System.out.println("Sending " + ip); out.println(ip); if(in.readLine().startsWith("Ok")){ System.out.println("Sending " + username); out.println(username); response = Integer.parseInt(in.readLine()); } else{ System.out.println("Bad response from server."); } } else{ System.out.println("Bad response from server."); } } catch (IOException ex) { Logger.getLogger(ServerCommunicator.class.getName()).log(Level.SEVERE, null, ex); } return response; }
4
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewAssociationView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewAssociationView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewAssociationView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewAssociationView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewAssociationView(new ProjectUML(),0).setVisible(true); } }); }
6
public void emite(InstruccionesPila operador, ArrayList<String> atributos) throws Exception { String inst; // codigo con dos parametros if (operador.equals(InstruccionesPila.apila) || operador.equals(InstruccionesPila.desapila_dir)) { inst = operador.toString()+"("+atributos.get(0)+","+atributos.get(1)+")"; } // codigo con un parametro else if (operador.equals(InstruccionesPila.apila_dir) || operador.equals(InstruccionesPila.ir_a) || operador.equals(InstruccionesPila.ir_f) || operador.equals(InstruccionesPila.mueve) || operador.equals(InstruccionesPila.ir_v) || operador.equals(InstruccionesPila.in) ) { inst = operador.toString()+"("+atributos.get(0)+")"; } /* else if(operador.equals(InstruccionesPila.in)) { inst = operador.toString() +"("+atributos.get(0)+","+atributos.get(1)+")"; }*/ else //codigo sin parametros inst = operador.toString(); codigo.push(inst); }
8
public MultiInputOptionPane(Handler handler) { JTextField option = new JTextField(3); option.addAncestorListener(new RequestFocusListener()); JPanel panel = new JPanel(); panel.add(new JLabel("Maximum number:")); panel.add(option); int result = JOptionPane.showConfirmDialog(null, panel, "Square Number Tester", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { try { if (!option.getText().matches("^[a-zA-Z]+$")) { if (Double.parseDouble(option.getText()) == (int) Double.parseDouble(option.getText())) { int number = (int) Double.parseDouble(option.getText()); if (number > 0) { if (number <= squareRootOfIntegerMaxValue) { System.out.println("Max number: " + option.getText()); handler.getDataHandler().setTotalNumberQuestions(number); handler.getDataHandler().setCorrectInFirstGo(handler.getDataHandler().getTotalNumberQuestions().intValue()); } else { throw new IllegalInputException("less than 46350"); } } else { throw new IllegalInputException("positive"); } } else { throw new IllegalInputException("an integer"); } } else { throw new IllegalInputException("a number"); } } catch (IllegalInputException e) { e.printStackTrace(); new MultiInputOptionPane(handler); } } else if (result == JOptionPane.CANCEL_OPTION || result == JOptionPane.CLOSED_OPTION) { System.exit(0); } else { new MultiInputOptionPane(handler); } }
8
public String getHost() { return host; }
0
private boolean evaluateRestrainClause(String str) { double x = parseMathExpression(str); if (Double.isNaN(x)) return false; if (x < 0) { out(ScriptEvent.FAILED, "Restraint cannot be negative: " + str); return false; } int nop = model.getNumberOfParticles(); if (nop <= 0) return true; float c = (float) (x * 0.01); for (int k = 0; k < nop; k++) { Particle p = model.getParticle(k); if (p.isSelected()) { if (c < ZERO) { p.setRestraint(null); } else { if (p.restraint == null) { p.setRestraint(new PointRestraint(c, p.rx, p.ry)); } else { p.restraint.k = c; } } } } view.repaint(); notifyChange(); return true; }
7
public void startBenchmark(){ System.out.println("Starting TarsosLSH benchmark with " + dataset.size() + " random vectors"); System.out.println(" Four close neighbours have been added to 100 vectors (100+4x100=500)."); System.out.println(" The results of LSH are compared with a linear search."); System.out.println(" The first four results of LSH and linear are compared."); //determine the radius for hash bins automatically System.out.println("Radius for Euclidean distance."); int radiusEuclidean = (int) LSH.determineRadius(dataset, new EuclideanDistance(), 20); System.out.println("\nRadius for City block distance."); int radiusCityBlock = (int) LSH.determineRadius(dataset, new CityBlockDistance(), 20); HashFamily[] families = { new EuclidianHashFamily(radiusEuclidean,dimensions), new CityBlockHashFamily(radiusCityBlock,dimensions), new CosineHashFamily(dimensions)}; for(HashFamily family:families){ int[] numberOfHashes = {2,4,8}; if(family instanceof CosineHashFamily){ numberOfHashes[0] *= 8; numberOfHashes[1] *= 8; numberOfHashes[2] *= 8; } int[] numberOfHashTables = {2,4,8,16}; LSH lsh = new LSH(dataset,family); System.out.println("\n--" + family.getClass().getName()); System.out.printf("%10s%15s%10s%10s%10s%10s%10s%10s\n","#hashes","#hashTables","Correct","Touched","linear","LSH","Precision","Recall"); for(int i = 0; i < numberOfHashes.length ; i++){ for(int j = 0 ; j < numberOfHashTables.length ; j++){ lsh.buildIndex( numberOfHashes[i], numberOfHashTables[j]); lsh.benchmark(numberOfNeighbours,family.createDistanceMeasure()); } } } }
4
@Override public Class<?> getColumnClass(int columnIndex) { switch (columnIndex) { case 0: return String.class; case 1: return String.class; case 2: return String.class; case 3: return String.class; default: throw new RuntimeException("coluna inválida"); } }
5
@Override public void run() { long ctsReceivedTime = 0; while (running) { try { // check if sending is okay: last seen CTS not meant for this // sender is > ctsDelayTime ago // Don't be greedy: even if maca is disabled, respect CTS for // other sender! if ((lastCTSSeen + ctsDelayTime) <= System.currentTimeMillis()) { // pick topmost packet (but keep it in the list, if we like // to resend it in case of a RTSPacket) Packet p = packetQueue.peek(); // if queue is empty: wait for queue to be filled again // @see sendPacket if (p == null) { Logger.getInstance().println("WLANSender.run: Packet queue empty, going to sleep", Logger.SPAM); synchronized (packetQueue) { packetQueue.wait(); } continue; } // transform packet to DatagramPacket byte[] b = p.serialize(); DatagramPacket wlanPacket = new DatagramPacket(b, b.length); wlanPacket.setAddress(Starter.getDestinationAddress()); wlanPacket.setPort(socket.getLocalPort()); Logger.getInstance().println("WLANSender.run: Send packet " + p.toString(), Logger.NOTICE); // send packet socket.send(wlanPacket); // if this packet was a "request to send" packet, sender // will wait for a "clear to send" one. If a CTS is received // (and meant for this sender), the receiver will remove the // RTS packet from this senders queue and will notify this // thread to go on // If no CTS is receive within the timeout time, the RTS // packet will remain in the queue and this thread will // wakeup to send the queue's topmost packet - which will be // a resend of the RTS packet and so on if (p instanceof RTSPacket) { long startWaitingTime = System.currentTimeMillis(); Logger.getInstance().println("WLANSender.run: RTC packet send, waiting for CTS", Logger.SPAM); // wait for retryRTSTimeout on the packet to be removed // from the receiver synchronized (p) { p.wait(retryRTSTimeout); } ctsReceivedTime= System.currentTimeMillis(); // if topmost packet is not a RTS packet, which means // the receiver polled the package due to a CTS packet, // we can calculate the time it required to receive a // RTS packet which we will use as a retryRTSTimeout if ( !(packetQueue.peek() instanceof RTSPacket) ) { // add a buffer of 10% on the new retryRTSTimeout retryRTSTimeout = Math.max(20, (long)((System.currentTimeMillis() - startWaitingTime)*1.20)); } } else { packetQueue.poll(); // if MACA is enabled, we wait the CTS delay time (starting when the CTS was received) to not // flood the channel with RTS pakets so that no other client may send any packets if ( useMaca && ctsReceivedTime != 0) { Thread.sleep(Math.max(1, ctsReceivedTime + ctsDelayTime - System.currentTimeMillis())); } // make room for other threads else { Thread.yield(); } } } // last CTS seen by the receiver still blocks this sender to // send any new packets. Wait, until delay is over else { Logger.getInstance().println("WLANSender.run: Last CTS blocks channel, waiting...", Logger.INFORMATION); Thread.sleep((lastCTSSeen + ctsDelayTime - System.currentTimeMillis())); } } catch (IOException e) { // The socket has thrown some IO exception: stop work e.printStackTrace(); break; } catch (InterruptedException e) { // Something forced this thread to wake up: // Just print stack and resume to work e.printStackTrace(); } } }
9
private Nodo sentencia() { Nodo tem = null; if (aux.getToken().equals("if")) { aux=(Tokens2)tok.next(); tem = this.seleccion(); } else if (aux.getToken().equals("while")) { aux=(Tokens2)tok.next(); tem = this.iteracion(); } else if (aux.getToken().equals("do")) { aux=(Tokens2)tok.next(); tem = this.repeticion(); } else if (aux.getToken().equals("read")) { aux=(Tokens2)tok.next(); tem = this.sentIn(); } else if (aux.getToken().equals("write")) { aux=(Tokens2)tok.next(); tem = this.sentOut(); } else { if (aux.getTipo()==Nodo.tipoToken.Identificador) { tem = new Nodo(aux.getToken(), aux.getTipo()); aux=(Tokens2)tok.next(); tem=asignacion(tem); } } return tem; }
6
public static void main(String[] args) { for(int i = 0; i < 100; i++) { if(i == 74) break; // Out of for loop if(i % 9 != 0) continue; // Next iteration System.out.print(i + " "); } System.out.println(); for(int i = 0; i < 100; i++) { if(i == 74) break; // Out of for loop if(i % 9 != 0) continue; // Next iteration System.out.print(i + " "); } System.out.println(); int i = 0; // An "infinite loop": while(true) { i++; int j = i * 27; if(j == 1269) break; // Out of loop if(i % 10 != 0) continue; // Top of loop System.out.print(i + " "); } }
9
public MyVector getPosition(int color) { MyVector initposition = null; int baulklinex = (int)(-boardwidth/2.0+0.2*boardwidth); switch (color) { case 0: initposition = new MyVector(baulklinex-10,-boardheight/12,0); break; case 1: initposition = new MyVector(baulklinex,-boardheight/6,0); break; case 2: initposition = new MyVector(baulklinex,+boardheight/6,0); break; case 3: initposition = new MyVector(baulklinex,0,0); break; case 4: initposition = new MyVector(0,0,0); break; case 5: initposition = new MyVector(0.25*boardwidth,0,0); break; case 6: initposition = new MyVector(boardwidth/2-boardheight/6,0,0); break; } return initposition; }
7
public String name() { Constant c = (Constant) constants.get(thisClass); Assert.isNotNull(c, "Null constant for class name"); if (c.tag() == Constant.CLASS) { final Integer nameIndex = (Integer) c.value(); if (nameIndex != null) { c = (Constant) constants.get(nameIndex.intValue()); if (c.tag() == Constant.UTF8) { return (String) c.value(); } } } throw new ClassFormatException("Couldn't find class name in file"); }
3
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof TournamentType)) return false; TournamentType other = (TournamentType) obj; if (idTournamentType != other.idTournamentType) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
7
public String toString() { //simple version: //return _heap.toString(); //prettier version: String lvlOrdTrav = "heap size " + _heap.size() + "\n"; if ( _heap.size() == 0 ) return lvlOrdTrav; int h = 1; //init height to 1 for( int i = 0; i < _heap.size(); i++ ) { lvlOrdTrav += i + ":" + _heap.get(i) + " "; if ( i >= Math.pow(2,h) - 2 ) { lvlOrdTrav += "\n"; h++; } } return lvlOrdTrav; }//O(n)
3
public static ArrayList<Pushbullet> getDevices(String api_key) { ArrayList<Pushbullet> devices = new ArrayList<Pushbullet>(); try { int i = 0; final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory .getDefault(); final URL url = new URL("https://api.pushbullet.com/api/devices"); final HttpsURLConnection connection = (HttpsURLConnection) url .openConnection(); connection.setSSLSocketFactory(sslSocketFactory); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); final String authStr = api_key + ":"; final String authEncoded = Base64.encode(authStr.getBytes()); connection.setRequestProperty("Authorization", "Basic " + authEncoded); final InputStream is = connection.getInputStream(); final BufferedReader rd = new BufferedReader(new InputStreamReader( is)); String line; final StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); JSONObject jsonResponse = new JSONObject(response.toString()); JSONArray jsonDevices = jsonResponse.getJSONArray("devices"); while (!jsonDevices.isNull(i)) { JSONObject jsonDevice = jsonDevices.getJSONObject(i); Pushbullet device = new Pushbullet(jsonDevice); devices.add(device); i++; } } catch (MalformedURLException e) { System.out.println("Error en URL" + e); } catch (ProtocolException e) { System.out.println("Error en protocolo" + e); } catch (IOException e) { System.out.println("Error en E/S: " + e); } return devices; }
5
@Override public boolean publish(Client client, PubMessage message) throws Exception { String payload = new String(message.getPayload(), Charset.forName("UTF-8")); if (payload.indexOf("Country Music") > -1) { // We don't do that stuff here! Return true to suppress processing of the message return true; } return super.publish(client, message); }
1
public void setTwoDarray(double[][] aarray){ if(this.numberOfRows != aarray.length)throw new IllegalArgumentException("row length of this Matrix differs from that of the 2D array argument"); if(this.numberOfColumns != aarray[0].length)throw new IllegalArgumentException("column length of this Matrix differs from that of the 2D array argument"); for(int i=0; i<numberOfRows; i++){ if(aarray[i].length!=numberOfColumns)throw new IllegalArgumentException("All rows must have the same length"); for(int j=0; j<numberOfColumns; j++){ this.matrix[i][j]=aarray[i][j]; } } }
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; WildcardQuery other = (WildcardQuery) obj; if (term == null) { if (other.term != null) return false; } else if (!term.equals(other.term)) return false; return true; }
6
public int cdlSeperatingLinesLookback( ) { return ((( ((( (this.candleSettings[CandleSettingType.ShadowVeryShort.ordinal()].avgPeriod) ) > ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ? ( (this.candleSettings[CandleSettingType.ShadowVeryShort.ordinal()].avgPeriod) ) : ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ) > ( (this.candleSettings[CandleSettingType.Equal.ordinal()].avgPeriod) )) ? ( ((( (this.candleSettings[CandleSettingType.ShadowVeryShort.ordinal()].avgPeriod) ) > ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ? ( (this.candleSettings[CandleSettingType.ShadowVeryShort.ordinal()].avgPeriod) ) : ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ) : ( (this.candleSettings[CandleSettingType.Equal.ordinal()].avgPeriod) )) + 1; }
3
public String getFiledName() { return filedName; }
0
private void renderElement(XmlElement element) { if (element instanceof XmlTextElement) { for (String text : element.getText().split(" ")) { elements.add(new TextInsert(text, formatStack)); } } else if (element instanceof XmlTagElement) { XmlTagElement tag = (XmlTagElement)element; switch(tag.getLabel()) { case "img": elements.add(new ImageInsert(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(); } }
9
public ArrayList<Double> solveSystem() { Collections.fill(x, 0.0); int k = 0; int size = x.size(); double delta = 0.0; ArrayList<ArrayList<Integer>> rows = matrixA.getRowIndexes(); do { double t1 = 0.0; double t2 = 0.0; delta = 0.0; for (int i = 0; i < size; i++) { t1 = b.get(i); t2 = 0.0; ArrayList<Integer> row = rows.get(i); for (Integer j : row) { double element = matrixA.getElement(i, j); t2 += element * x.get(j); } double value = (t1 - t2) / matrixA.getElement(i, i); double nI = value - x.get(i); nI = Math.abs(nI); delta += nI * nI; x.set(i, value); } delta = Math.sqrt(delta); } while (delta >= epsilon && k <= K_MAX && delta <= 100000000); if (delta < epsilon) { return x; } else { return null; } }
6
public boolean testPositionBateau(int longueur, int sens, int x, int y) { int pos = 0; for(int i=0;i<longueur;i++) { switch(sens) { case 1: // Horizontale pos = x+i+y*this._partie.getParametre().getNbCaseX(); if(this._cases.get(pos).getBateau() != null) { return false; } break; case 2: // Verticale pos = x+(y+i)*this._partie.getParametre().getNbCaseX(); if(this._cases.get(pos).getBateau() != null) { return false; } break; case 3: // Diagonale break; default: break; } } return true; } // testPositionBateau(int longueur, int sens)
6
@EventHandler public void onFurnaceBurn(FurnaceBurnEvent event) { plugin.cancelEvent(event); plugin.debugMessage(event); plugin.godMode(event); if (event.getFuel().getType().equals(Material.WEB)) { event.setBurnTime(100); } else if (event.getFuel().getType().equals(Material.BEDROCK)) { event.setBurning(false); } else if (event.getFuel().getType().equals(Material.STICK)) { event.setBurnTime(1000); } else if (event.getFuel().getType().equals(Material.LAVA_BUCKET)) { event.setBurning(false); } }
4
private boolean findMatch(String searchString, TableItem item, int column, boolean matchWord, boolean matchCase) { String tableText = matchCase ? item.getText(column) : item.getText(column).toLowerCase(); if (matchWord) { if (tableText != null && tableText.equals(searchString)) { return true; } } else { if(tableText!= null && tableText.indexOf(searchString) != -1) { return true; } } return false; }
6
public void mousePressed(MouseEvent me){ if(SwingUtilities.isRightMouseButton(me)){ if (table.columnAtPoint(me.getPoint()) == 0){ int index=table.getSelectedRow(); popAlternative.show(me.getComponent(), me.getX()+5, me.getY()+5); if(index==-1){ menuRemove.setEnabled(false); menuRename.setEnabled(false); } else{ menuRemove.setEnabled(true); menuRemove.setEnabled(true); } } } else if (SwingUtilities.isLeftMouseButton(me)){ try{ JTable tab = (JTable)(me.getSource()); if (tab.isEditing()){ last_value = (tab.getValueAt(tab.getSelectedRow(), tab.getSelectedColumn())).toString(); System.out.println("last_value: " + last_value); } } catch (java.lang.ClassCastException cce){} catch (java.lang.NumberFormatException nfe){} catch (java.lang.NullPointerException npe){ last_value = null; } } }
8
public static void main(String[] args) { System.out.print("Enter the number of students: "); Scanner scanner = new Scanner(System.in); int numberOfStudents = scanner.nextInt(); System.out.print("Enter " + numberOfStudents + " scores: "); double[] scores = new double [numberOfStudents]; double bestScore = 0; for (int i = 0; i < numberOfStudents; i++) { double score = scanner.nextDouble(); scores[i] = score; if (scores[i] > bestScore) { bestScore = scores[i]; } } char grade; for (int i = 0; i < numberOfStudents; i++) { if (scores[i] >= (bestScore - 10)) { grade = 'A'; } else if (scores[i] >= (bestScore - 20)) { grade = 'B'; } else if (scores[i] >= (bestScore - 30)) { grade = 'C'; } else if (scores[i] >= (bestScore - 40)) { grade = 'D'; } else { grade = 'F'; } System.out.println("Student " + i + " score is " + scores[i] + " and grade is " + grade); } }
7
public boolean addComponentParts(World par1World, Random par2Random, StructureBoundingBox par3StructureBoundingBox) { if (this.averageGroundLevel < 0) { this.averageGroundLevel = this.getAverageGroundLevel(par1World, par3StructureBoundingBox); if (this.averageGroundLevel < 0) { return true; } this.boundingBox.offset(0, this.averageGroundLevel - this.boundingBox.maxY + 12 - 1, 0); } this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 1, 3, 3, 7, 0, 0, false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 5, 1, 3, 9, 3, 0, 0, false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 0, 0, 3, 0, 8, Block.cobblestone.blockID, Block.cobblestone.blockID, false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 0, 3, 10, 0, Block.cobblestone.blockID, Block.cobblestone.blockID, false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 1, 0, 10, 3, Block.cobblestone.blockID, Block.cobblestone.blockID, false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 4, 1, 1, 4, 10, 3, Block.cobblestone.blockID, Block.cobblestone.blockID, false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 0, 4, 0, 4, 7, Block.cobblestone.blockID, Block.cobblestone.blockID, false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 4, 0, 4, 4, 4, 7, Block.cobblestone.blockID, Block.cobblestone.blockID, false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 8, 3, 4, 8, Block.cobblestone.blockID, Block.cobblestone.blockID, false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 5, 4, 3, 10, 4, Block.cobblestone.blockID, Block.cobblestone.blockID, false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 5, 5, 3, 5, 7, Block.cobblestone.blockID, Block.cobblestone.blockID, false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 9, 0, 4, 9, 4, Block.cobblestone.blockID, Block.cobblestone.blockID, false); this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 4, 0, 4, 4, 4, Block.cobblestone.blockID, Block.cobblestone.blockID, false); this.placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 0, 11, 2, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 4, 11, 2, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 2, 11, 0, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 2, 11, 4, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 1, 1, 6, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 1, 1, 7, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 2, 1, 7, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 3, 1, 6, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 3, 1, 7, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, this.getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 3), 1, 1, 5, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, this.getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 3), 2, 1, 6, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, this.getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 3), 3, 1, 5, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, this.getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 1), 1, 2, 7, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, this.getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 0), 3, 2, 7, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 2, 2, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 3, 2, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 4, 2, 2, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 4, 3, 2, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 6, 2, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 7, 2, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 4, 6, 2, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 4, 7, 2, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 2, 6, 0, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 2, 7, 0, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 2, 6, 4, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 2, 7, 4, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 3, 6, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 4, 3, 6, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 2, 3, 8, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, 2, 4, 7, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, 1, 4, 6, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, 3, 4, 6, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, 2, 4, 5, par3StructureBoundingBox); int var4 = this.getMetadataWithOffset(Block.ladder.blockID, 4); int var5; for (var5 = 1; var5 <= 9; ++var5) { this.placeBlockAtCurrentPosition(par1World, Block.ladder.blockID, var4, 3, var5, 3, par3StructureBoundingBox); } this.placeBlockAtCurrentPosition(par1World, 0, 0, 2, 1, 0, par3StructureBoundingBox); this.placeBlockAtCurrentPosition(par1World, 0, 0, 2, 2, 0, par3StructureBoundingBox); this.placeDoorAtCurrentPosition(par1World, par3StructureBoundingBox, par2Random, 2, 1, 0, this.getMetadataWithOffset(Block.doorWood.blockID, 1)); if (this.getBlockIdAtCurrentPosition(par1World, 2, 0, -1, par3StructureBoundingBox) == 0 && this.getBlockIdAtCurrentPosition(par1World, 2, -1, -1, par3StructureBoundingBox) != 0) { this.placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, this.getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 3), 2, 0, -1, par3StructureBoundingBox); } for (var5 = 0; var5 < 9; ++var5) { for (int var6 = 0; var6 < 5; ++var6) { this.clearCurrentPositionBlocksUpwards(par1World, var6, 12, var5, par3StructureBoundingBox); this.fillCurrentPositionBlocksDownwards(par1World, Block.cobblestone.blockID, 0, var6, -1, var5, par3StructureBoundingBox); } } this.spawnVillagers(par1World, par3StructureBoundingBox, 2, 1, 2, 1); return true; }
7
public boolean onLteamsCommand(CommandSender sender, Command cmd, String label, String[] args){ //First, are there any sessions or teams? if (sessions.size() == 0) { sender.sendMessage("There are currently no sessions."); return true; } //list the teams available to join. If they don't specify a session, list all sessions and teams if (args.length > 0) { //they passes a session? String sessionName = args[0]; CTFSession session = null; for (CTFSession s : sessions) { if (s.getName() == sessionName) { session = s; break; } } if (session != null) { String msg = "Teams: "; for (CTFTeam t : session.getTeams()) { msg += t.getName() + " | "; } sender.sendMessage(msg); return true; } else { //no session by that name. String msg = ""; for (CTFSession s: sessions) { msg += s.getName() + " | "; } sender.sendMessage("No valid session exists with that name. Valid sessions: " + msg); return true; } } //args == 0 //no session passed. Just list all teams with their respective session names String msg; for (CTFSession s: sessions) { msg = s.getName() + ": "; for (CTFTeam t: s.getTeams()) { msg += t.getName() + " | "; } sender.sendMessage(msg); } return true; }
9
public Boek() { }
0
public void execute(Object parent) { mxGraphHierarchyModel model = layout.getModel(); final Set<mxGraphHierarchyNode> seenNodes = new HashSet<mxGraphHierarchyNode>(); final Set<mxGraphHierarchyNode> unseenNodes = new HashSet<mxGraphHierarchyNode>( model.getVertexMapper().values()); // Perform a dfs through the internal model. If a cycle is found, // reverse it. mxGraphHierarchyNode[] rootsArray = null; if (model.roots != null) { Object[] modelRoots = model.roots.toArray(); rootsArray = new mxGraphHierarchyNode[modelRoots.length]; for (int i = 0; i < modelRoots.length; i++) { Object node = modelRoots[i]; mxGraphHierarchyNode internalNode = model .getVertexMapper().get(node); rootsArray[i] = internalNode; } } model.visit(new mxGraphHierarchyModel.CellVisitor() { public void visit(mxGraphHierarchyNode parent, mxGraphHierarchyNode cell, mxGraphHierarchyEdge connectingEdge, int layer, int seen) { // Check if the cell is in it's own ancestor list, if so // invert the connecting edge and reverse the target/source // relationship to that edge in the parent and the cell if ((cell) .isAncestor(parent)) { connectingEdge.invert(); parent.connectsAsSource.remove(connectingEdge); parent.connectsAsTarget.add(connectingEdge); cell.connectsAsTarget.remove(connectingEdge); cell.connectsAsSource.add(connectingEdge); } seenNodes.add(cell); unseenNodes.remove(cell); } }, rootsArray, true, null); Set<Object> possibleNewRoots = null; if (unseenNodes.size() > 0) { possibleNewRoots = new HashSet<Object>(unseenNodes); } // If there are any nodes that should be nodes that the dfs can miss // these need to be processed with the dfs and the roots assigned // correctly to form a correct internal model Set<mxGraphHierarchyNode> seenNodesCopy = new HashSet<mxGraphHierarchyNode>( seenNodes); // Pick a random cell and dfs from it mxGraphHierarchyNode[] unseenNodesArray = new mxGraphHierarchyNode[1]; unseenNodes.toArray(unseenNodesArray); model.visit(new mxGraphHierarchyModel.CellVisitor() { public void visit(mxGraphHierarchyNode parent, mxGraphHierarchyNode cell, mxGraphHierarchyEdge connectingEdge, int layer, int seen) { // Check if the cell is in it's own ancestor list, if so // invert the connecting edge and reverse the target/source // relationship to that edge in the parent and the cell if ((cell) .isAncestor(parent)) { connectingEdge.invert(); parent.connectsAsSource.remove(connectingEdge); parent.connectsAsTarget.add(connectingEdge); cell.connectsAsTarget.remove(connectingEdge); cell.connectsAsSource.add(connectingEdge); } seenNodes.add(cell); unseenNodes.remove(cell); } }, unseenNodesArray, true, seenNodesCopy); mxGraph graph = layout.getGraph(); if (possibleNewRoots != null && possibleNewRoots.size() > 0) { Iterator<Object> iter = possibleNewRoots.iterator(); List<Object> roots = model.roots; while (iter.hasNext()) { mxGraphHierarchyNode node = (mxGraphHierarchyNode) iter.next(); Object realNode = node.cell; int numIncomingEdges = graph.getIncomingEdges(realNode).length; if (numIncomingEdges == 0) { roots.add(realNode); } } } }
9
@Override public int getOperandCode() { switch (this.register) { case A: return 0x08; case B: return 0x09; case C: return 0x0A; case X: return 0x0B; case Y: return 0x0C; case Z: return 0x0D; case I: return 0x0E; case J: return 0x0F; case SP: return 0x19; default: throw new IllegalArgumentException("Register " + this.register + " is unknown"); } }
9
private boolean containsFilter(String[] searchFilterNames) { Vector filterNames = getFilterNames(); if (filterNames == null) return false; for (int i = 0; i < filterNames.size(); i++) { String filterName = filterNames.elementAt(i).toString(); for (String search : searchFilterNames) { if (search.equals(filterName)) { return true; } } } return false; }
4
private void locator(EnvParams ep){ try{ BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); //textEncryptor.setPassword(System.getenv("_WLS_PASS_KEY")); textEncryptor.setPassword("password"); String pass=textEncryptor.decrypt(ep.pass); props=new Hashtable(); props.put(javax.naming.Context.PROVIDER_URL,ep.host); props.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory"); props.put(javax.naming.Context.SECURITY_PRINCIPAL,ep.user); props.put(javax.naming.Context.SECURITY_CREDENTIALS,pass); props.put("dedicated.connection","true"); locator = LocatorFactory.createLocator(props); } catch(IllegalArgumentException e){ this.error="Exception: Password cannot be empty see README"; logger.error(this.error,e); e.printStackTrace(); } catch(Exception e){ this.error="Error in creating locator"; logger.error(this.error,e); e.printStackTrace(); } }
2
public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input = sc.next(); if(input.length() == 1) { System.out.println(input + input + input); } if(input.length() == 2) { for (int i = 0; i < input.length(); i++) { char firstChar = String.valueOf(input).charAt(i); for (int j = 0; j < input.length(); j++) { char secondChar = String.valueOf(input).charAt(j); for (int k = 0; k < input.length(); k++) { char thirdChar = String.valueOf(input).charAt(k); System.out.println(firstChar + "" + secondChar + "" + thirdChar + ""); } } } } if(input.length() == 3) { for (int i = 0; i < input.length(); i++) { char firstChar = String.valueOf(input).charAt(i); for (int j = 0; j < input.length(); j++) { char secondChar = String.valueOf(input).charAt(j); for (int k = 0; k < input.length(); k++) { char thirdChar = String.valueOf(input).charAt(k); System.out.println(firstChar + "" + secondChar + "" + thirdChar + ""); } } } } }
9