text
stringlengths
14
410k
label
int32
0
9
public String getDiagnostico() { return diagnostico; }
0
void setCellBackground () { if (!instance.startup) { table1.getItem (0).setBackground (1, cellBackgroundColor); } /* Set the background color item's image to match the background color of the cell. */ Color color = cellBackgroundColor; if (color == null) color = table1.getItem (0).getBackground (1); TableItem item = colorAndFontTable.getItem(CELL_BACKGROUND_COLOR); Image oldImage = item.getImage(); if (oldImage != null) oldImage.dispose(); item.setImage (colorImage(color)); }
3
@Override public Orientation getStepOrientation(int lineIndex) { switch(lineIndex) { case 0: case 4: return Orientation.LEFT; case 1: case 5: return Orientation.DOWN; case 2: case 6: return Orientation.UP; case 3: case 7: return Orientation.RIGHT; default: return Orientation.NONE; } }
8
@Override protected void execute(CommandSender sender, String Command, List<String> list) { this.init(sender); // /rm limit list <sell/rent> // /rm limit <region> <sell/rent> <int> // /rm limit <region> <sell/rent> if (list.get(0).equals("list")) { Map<String, Integer> limit = null; if (list.get(1).equals("sell")) { limit = this.getConfigHandler().getSelllimit(); this.reply("Sell-Limit list:"); } else if (list.get(1).equals("rent")) { limit = this.getConfigHandler().getRentlimit(); this.reply("Rent-Limit list:"); } else { this.error("/rm limit list <sell/rent>"); } String output = "["; for (String parent : limit.keySet()) { output += parent + ": " + limit.get(parent) + "; "; } this.reply(output + "]"); } if (list.get(0).equals("set")) { } }
5
@Override public byte[] getSchedule() { byte[] schedule = new byte[getScheduleSize()]; for (int i = 0; i < numSlots; i++) { if(desiredSlots[i]) { setSlot(schedule, i, footprints[i]); } } return schedule; }
2
private Hashtable<String, String> loadCsv(HttpServletRequest request, String tempFolder) throws IOException { Hashtable<String, String> items = new Hashtable<String, String>(); File csv = null; if (request.getParameter("uploadfile") != null && (request instanceof SabaHttpServletRequest)) { csv = ((SabaHttpServletRequest)request).getFile("uploadfile"); if (csv != null) { // file found in request, save to temporary folder _csvFilename = csv.getName(); FileWriter writer = new FileWriter(tempFolder + "/" + _csvFilename); BufferedReader reader = new BufferedReader(new FileReader(csv)); try { String line = reader.readLine(); while (line != null) { writer.write(line); writer.write("\r"); line = reader.readLine(); } } finally { reader.close(); writer.close(); } } } else { // file not found in request, read from temporary folder csv = new File(tempFolder + "/" + _csvFilename); } if (csv != null) { BufferedReader reader = new BufferedReader(new FileReader(csv)); try { String line = reader.readLine(); while (line != null) { String parts[] = line.split(","); if (parts != null && parts.length > 1) { items.put(parts[0], parts[1]); } line = reader.readLine(); } } catch (IOException ex) { // } finally { reader.close(); } } return items; }
9
public OnDemandRequest getNextNode() { OnDemandRequest onDemandRequest; synchronized (aClass19_1358) { onDemandRequest = (OnDemandRequest) aClass19_1358.popFront(); } if (onDemandRequest == null) { return null; } synchronized (queue) { onDemandRequest.unlinkSub(); } if (onDemandRequest.buffer == null) { return onDemandRequest; } int off = 0; try { GZIPInputStream gzipinputstream = new GZIPInputStream(new ByteArrayInputStream(onDemandRequest.buffer)); do { if (off == gzipInputBuffer.length) { throw new RuntimeException("buffer overflow!"); } int len = gzipinputstream.read(gzipInputBuffer, off, gzipInputBuffer.length - off); if (len == -1) { break; } off += len; } while (true); } catch (IOException exception) { throw new RuntimeException("error unzipping"); } onDemandRequest.buffer = new byte[off]; System.arraycopy(gzipInputBuffer, 0, onDemandRequest.buffer, 0, off); return onDemandRequest; }
6
public void setDescription(String description) { this.description = description; }
0
public void showMessage(String message, String title, int messageType){ JOptionPane.showMessageDialog(frame, message, title, messageType); }
0
@Override public void killProcess(String programName) throws IOException, InterruptedException, ProcessKillerException { logger.trace("Attempt to kill " + programName); int attempts = 0; if (!isProgramRunning(programName)) return; for (attempts = 0; attempts < HOW_MANY_ATTEMPTS_BEFORE_FAIL; attempts++) { if (!askToDieGracefully(programName)) { killAllResistants(programName); return; } if (!isProgramRunning(programName)) { logger.detailedTrace("Successfully killed all instances of " + programName); return; } sleep(SECONDS.toMillis(HOW_MANY_SECONDS_BETWEEN_ATTEMPTS)); } logger.error("Failed to kill " + programName + " (exception thrown)"); throw new ProcessKillerException("Couldn't kill process - " + HOW_MANY_ATTEMPTS_BEFORE_FAIL + " attempts failed"); }
4
public Object getArgument(String arg, String classDescription){ switch(classDescription) { case "boolean": return getBooleanArgument(arg,true); case "double": return getDoubleArgument(arg,true); case "long": return getLongArgument(arg,true); case "int": return getIntArgument(arg,true); case "java.lang.String": return getStringArgument(arg,true); default: System.err.println("Warning. Unknown classDescription: " + classDescription + " returning null"); return null; } }
5
public void unsubscribeEvent(String eventName, Object className) { HashMap<Object, String> eventCallbacks = this.eventMap.get(eventName); if(eventCallbacks != null) { if(eventCallbacks.containsKey(className)) { eventCallbacks.remove(className); if(eventCallbacks.size() == 0) { this.eventMap.remove(eventName); } } } }
3
private int findLekarzId(int nr_lekarza) { int id = 0; Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Query query = session.createQuery("from lekarze where nr_lekarza = :id "); query.setParameter("id", nr_lekarza); List<lekarze> l = query.list(); tx.commit(); for(lekarze p:l) { id=p.getLekarz_id(); } } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); Log.log(Level.WARNING, "Blad usuwania pacjenta", e); return 0; } catch(Exception ex) { Log.log(Level.SEVERE, "Blad usuwania pacjenta, severe", ex); return 0; } finally { session.close(); return id; } }//findLekarzId
4
@Override public void execute(VirtualMachine vm) { }
0
private void push(JSONObject jo) throws JSONException { if (this.top >= maxdepth) { throw new JSONException("Nesting too deep."); } this.stack[this.top] = jo; this.mode = jo == null ? 'a' : 'k'; this.top += 1; }
2
public static void init(){ Toolbox.debugPrint(TAG, numLines + ""); tb = new TextBox(); lines = new Label[numLines]; tb.setX(3); tb.setY(CMConfig.WINDOW_HEIGHT - 17); tb.setHintText("Enter Command"); tb.getLabel().setFont("data/roboto_small.fnt", "data/roboto_small_0.png"); tb.setListener(new GenericListener<Integer>() { @Override public void onEvent(Integer param) { if(param == Keyboard.KEY_RETURN){ String[] cmd = tb.getLabel().getText().split(" "); if(cmd.length > 0){ if(cmd[0].equalsIgnoreCase("loadscript")){ if(cmd.length >= 2){ File script = new File(cmd[1]); if(script.exists()){ ScriptManager.doScript(script); }else{ Toolbox.errPrint(TAG, "Invalid File"); } }else{ Toolbox.errPrint(TAG, "Usage: loadscript (Path)"); } }else if(cmd[0].equalsIgnoreCase("do")){ if(cmd.length >= 2){ ScriptManager.doScript("ConsoleScript", cmd[1]); }else{ Toolbox.errPrint(TAG, "Usage: do (Script)"); } } }else{ printLine("Please enter a command"); } tb.getLabel().setText(""); } } }); kl = new KeyboardListener() { @Override public void onKeyPress(int key) { if(key == Keyboard.KEY_GRAVE){ toggleVisibility(); } } @Override public void onKeyRelease(int key) { } }; KeyboardManager.addListener(kl); for(int x = 0; x < lines.length; x++){ lines[x] = new Label(); lines[x].setFont("data/roboto_small.fnt", "data/roboto_small_0.png"); lines[x].setY((CMConfig.WINDOW_HEIGHT - 34) - (x * 17)); lines[x].setX(3); } hasInit = true; }
9
private static int[] matchNodes(SquareMatrix S) { // Number of rows <= Number of columns int numRows = S.getNumberOfRows(); int numCols = S.getNumberOfColumns(); int[] matches = new int[numRows]; ArrayList<Integer> tabuRows = new ArrayList<Integer>(); ArrayList<Integer> tabuCols = new ArrayList<Integer>(); for (int n = 0; n < matches.length; n++) { int bestRow = 0; int bestCol = 0; int bestScore = -2000; int nextScore; for (int i = 0; i < numRows; i++) { if (tabuRows.contains(i)) { continue; } for (int j = 0; j < numCols; j++) { if (tabuCols.contains(j)) { continue; } nextScore = S.getElement(i, j); if (nextScore > bestScore) { bestRow = i; bestCol = j; bestScore = nextScore; } } } matches[bestRow] = bestCol; tabuRows.add(bestRow); tabuCols.add(bestCol); } return matches; }
6
public void removeLastStmt() { final ListIterator iter = stmts.listIterator(stmts.size()); while (iter.hasPrevious()) { final Stmt s = (Stmt) iter.previous(); if (s instanceof LabelStmt) { continue; } iter.remove(); return; } }
2
@Override public boolean execute(String code) { int indexValue = 0; int pointerToAdd = 0; String effectiveAddress = ""; String val = ""; seperateCode(code); // Get the addressing mode. int addressMode = getAddressingMethod(code); try { if (isIndirect) { address = address.substring(0, address.indexOf("*")); } // Get the corresponding address depending on the type of mode if (addressMode == 0) { executeSTA(this.address); } else { if (addressMode == 1 || addressMode == 3) { indexValue = Integer.parseInt(ASCView.getIndexValue(this.register), 16); effectiveAddress = Integer.toHexString(Integer.parseInt(this.address, 16) + indexValue); } if (addressMode == 2 || addressMode == 3) { pointerToAdd = Integer.parseInt(address, 16); if (isIndexed) { int buffer = Integer.parseInt((String) ASCView.getMemoryTable().getValueAt(pointerToAdd, 0), 16); buffer += indexValue; effectiveAddress = formatText(Integer.toHexString(buffer)); } else { effectiveAddress = formatText((String) ASCView.getMemoryTable().getValueAt((pointerToAdd), 0)); } } if (effectiveAddress.equalsIgnoreCase("dddd")) { EmulatorControl.addError(new EmulatorError(">>ERROR<< AN ERROR OCCURED WITH THE STA OPERATION.", 0)); return false; } // Execute with the new address executeSTA(effectiveAddress); } } catch (NumberFormatException nfe) { EmulatorControl.addError(new EmulatorError(">>ERROR<< AN ERROR OCCURED WITH THE STA OPERATION.", 0)); return false; } Emulator.incrementProgramCounter(); return true; }
9
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(TelaExcluiTicket.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaExcluiTicket.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaExcluiTicket.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaExcluiTicket.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 TelaExcluiTicket().setVisible(true); } }); }
6
public static void main(String[] args) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for( String linea; (linea = in.readLine() ) != null ; ) { v = new boolean[12]; int guess = Integer.parseInt(linea); if(guess == 0) break; String resp = in.readLine(); while( !resp.equals("right on") ){ if( resp.equals("too high") ) for (int i = guess; i < v.length; i++) v[i]=true; else for (int i = guess; i >= 0; i--) v[i] = true; guess = Integer.parseInt(in.readLine()); resp = in.readLine(); } if( v[guess] ) System.out.println("Stan is dishonest"); else System.out.println("Stan may be honest"); } }
7
private void sendQuickLaunchFiles(){ if(client_connected){ // Notify connected client of new files (TCP) for(int x = 0; x < quick_launch_files.length; x++){ sendQuickLaunchFile(x); } } }
2
private void calculateEnabledState(JoeTree tree) { Document doc = tree.getDocument(); if (doc == Outliner.documents.getMostRecentDocumentTouched()) { Node node = tree.getEditingNode(); if (tree.getComponentFocus() == OutlineLayoutManager.TEXT) { if (node.isLeaf()) { setEnabled(false); } else { setEnabled(true); } } else if (tree.getComponentFocus() == OutlineLayoutManager.ICON) { if (tree.getNumberOfSelectedNodes() == 1) { if (node.isLeaf()) { setEnabled(false); } else { setEnabled(true); } } } } }
6
protected boolean verificaVencedor() { boolean daVez = jogador1.obterDaVez(); boolean ocupada; boolean haAdversarios; Troglodita troglodita; Posicao posicaoTemporaria; //Verifica se não há trogloditas adversários, e depois se há próprio troglodita na última linha. if(daVez){ haAdversarios = jogador2.haTrogloditas(); if(!haAdversarios){ jogador1.defineDaVez(false); jogador1.defineVencedor(); return true; } boolean simboloJogador1 = jogador1.obterSimbolo(); for(int j = 0; j < posicoes[0].length; j++){ posicaoTemporaria = posicoes[0][j]; ocupada = posicaoTemporaria.estaOcupada(); if(ocupada){ troglodita = posicaoTemporaria.retorneTroglodita(); if(simboloJogador1 == troglodita.retorneSimbolo()){ jogador1.defineDaVez(false); jogador1.defineVencedor(); return true; } } } } else { haAdversarios = jogador1.haTrogloditas(); if(!haAdversarios){ jogador2.defineDaVez(false); jogador2.defineVencedor(); return true; } boolean simboloJogador2 = jogador2.obterSimbolo(); for(int j = 0; j < posicoes[0].length; j++){ posicaoTemporaria = posicoes[6][j]; ocupada = posicaoTemporaria.estaOcupada(); if(ocupada){ troglodita = posicaoTemporaria.retorneTroglodita(); if(simboloJogador2 == troglodita.retorneSimbolo()){ jogador2.defineDaVez(false); jogador2.defineVencedor(); return true; } } } } return false; }
9
private void initMenu() { connectItem = new JMenuItem("Connect"); connectItem.setEnabled(false); connectItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (JCheckBoxMenuItem portItem : portItems) { portItem.setEnabled(false); } for (JComponent component : components) { component.setEnabled(true); } connectItem.setEnabled(false); disconnectItem.setEnabled(true); try { serial.setPortName(currentItemPort.getText()); serial.connect(); } catch (SerialPortException ex) { ex.printStackTrace(); } } }); disconnectItem = new JMenuItem("Disconnect"); disconnectItem.setEnabled(false); disconnectItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { connectItem.setEnabled(true); disconnectItem.setEnabled(false); for (JComponent component : components) { component.setEnabled(false); } for (JCheckBoxMenuItem portItem : portItems) { portItem.setEnabled(true); } rSlider.setValue(0); gSlider.setValue(0); bSlider.setValue(0); try { serial.disconnect(); } catch (SerialPortException ex) { ex.printStackTrace(); } } }); JMenu actionMenu = new JMenu("Action"); actionMenu.add(connectItem); actionMenu.add(disconnectItem); JMenu serialPortMenu = new JMenu("Serial Port"); for (String port : SerialUtil.getPorts()) { JCheckBoxMenuItem portItem = new JCheckBoxMenuItem(port); portItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JCheckBoxMenuItem portItem = (JCheckBoxMenuItem) e.getSource(); if (currentItemPort == null) { currentItemPort = portItem; currentItemPort.setState(true); connectItem.setEnabled(true); } else { if (portItem == currentItemPort) { currentItemPort.setState(false); currentItemPort = null; connectItem.setEnabled(false); } else { currentItemPort.setState(false); currentItemPort = portItem; currentItemPort.setState(true); } } } }); serialPortMenu.add(portItem); portItems.add(portItem); } JMenuBar menuBar = new JMenuBar(); menuBar.add(actionMenu); menuBar.add(serialPortMenu); setJMenuBar(menuBar); }
9
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ConsultantInfo)) { return false; } ConsultantInfo other = (ConsultantInfo) object; if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) { return false; } return true; }
5
private final AStarNode obtainOpenWithLowestCost() { Iterator<Entry<Float, Vector<AStarNode>>> entries = open.entrySet().iterator(); if (!entries.hasNext()) return null; Vector<AStarNode> costEntry = entries.next().getValue(); int lastCostEntry = costEntry.size() - 1; AStarNode lowestCostNode = costEntry.get(lastCostEntry); costEntry.remove(lastCostEntry); if (costEntry.size() == 0) entries.remove(); isOpen[(int)lowestCostNode.getLocation().getX()][(int)lowestCostNode.getLocation().getY()] = false; return lowestCostNode; }
2
public void decodeToFile(BufferedReader br, BufferedWriter bw, int total) throws IOException{ int input; boolean[] new_bits; while ((input = br.read()) != -1 && total > 0) { if(total <= 0){ System.out.println("stopped due to max words!"); } new_bits = byteToBooleans(input); addToQueue(new_bits); while(index > chunkSize){ writeNextChar(bw); total--; } bw.flush(); } System.out.println("no more to read in, doing rest of the work! total: " + total); System.out.println("index size: " + index); while(index > 0 && total > 0){ writeNextChar(bw); total--; } System.out.println("index size: " + index); br.close(); bw.flush(); bw.close(); }
6
public ArrayList<AreaFormacao> listar(String condicao) throws Exception { ArrayList<AreaFormacao> listaAreaFormacao = new ArrayList<AreaFormacao>(); String sql = "SELECT * FROM areaformacao " + condicao; try { PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while (rs.next()) { AreaFormacao areaformacao = new AreaFormacao(); areaformacao.setId(rs.getLong("id")); areaformacao.setNome(rs.getString("nome")); listaAreaFormacao.add(areaformacao); } rs.close(); } catch (SQLException e) { throw e; } return listaAreaFormacao; }
2
public void stop(){ stopping = true; }
0
public static Titulo sqlLeer(Titulo titulo){ String sql="SELECT * FROM titulo WHERE idtitulo = '"+titulo.getId()+"'"; if(!BD.getInstance().sqlSelect(sql)){ return null; } if(!BD.getInstance().sqlFetch()){ return null; } titulo.setId(BD.getInstance().getInt("id")); titulo.setNombre(BD.getInstance().getString("nombre")); return titulo; }
2
public AuthHeader getAuthHeaderByToken(String token){ AuthHeader ah=null; Connection con = null; Statement stmt = null; try { DBconnection dbCon = new DBconnection(); Class.forName(dbCon.getJDBC_DRIVER()); con = DriverManager.getConnection(dbCon.getDATABASE_URL(), dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD()); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select * From auth_tokens where auth_token='"+token+"'"); if (rs.next()) { ah = new AuthHeader(); ah.setCust_id(rs.getInt(1)); ah.setToken(rs.getString(2)); Timestamp timestamp=rs.getTimestamp(3); Date date=new Date(timestamp.getTime()); ah.setAuth_date(date); } } catch (SQLException | ClassNotFoundException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } } return ah; }
5
synchronized private void waitReady(DocumentsWriterThreadState state) { while (!closed && ((state != null && !state.isIdle) || pauseThreads != 0 || flushPending || aborting)) { try { wait(); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } } if (closed) throw new AlreadyClosedException("this IndexWriter is closed"); }
8
public ListNode removeNthFromEnd(ListNode head, int n) { ListNode p1,p2; if (n <=0 ) return head; int k = n; p1 = head; while (k > 0 && p1 != null) { k--; p1 = p1.next; } if (k ==0 && p1 ==null) { head = head.next; return head; } if (p1 != null) { p1 = p1.next; p2 = head; while (p1 != null) { p1= p1.next; p2 =p2.next; } p2.next = p2.next.next; } return head; }
7
@Override public void actionPerformed(ActionEvent arg0) { if (colorGain) colorN += 3; else colorN -= 5; if (colorN >= 200) colorGain = false; else if (colorN <= 30) colorGain = true; if (!seen) { tutorial = true; hero.setPaused(true); if (tutorialX > 0) { tutorialX -= 15; tutorialEnd = true; } if (tutorialMoved) { tutorialX -= 15; if (tutorialX < -930) { tutorial = false; hero.setPaused(false); } } } if (!tutorial) { setRunning(true); } else { setRunning(false); } super.actionPerformed(arg0); }
8
public static Collection getAllTasks(){ Session session = HibernateUtil.getSessionFactory().openSession(); List answer = new ArrayList<Task>(); try { session = HibernateUtil.getSessionFactory().openSession(); answer = session.createCriteria(Task.class).list(); System.out.println("all tasks got!"); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка", JOptionPane.OK_OPTION); } finally { if (session != null && session.isOpen()) { session.close(); } } return answer; }
3
private void compute_pcm_samples15(Obuffer buffer) { final float[] vp = actual_v; //int inc = v_inc; final float[] tmpOut = _tmpOut; int dvp =0; // fat chance of having this loop unroll for( int i=0; i<32; i++) { float pcm_sample; final float dp[] = d16[i]; pcm_sample = (float)(((vp[15 + dvp] * dp[0]) + (vp[14 + dvp] * dp[1]) + (vp[13 + dvp] * dp[2]) + (vp[12 + dvp] * dp[3]) + (vp[11 + dvp] * dp[4]) + (vp[10 + dvp] * dp[5]) + (vp[9 + dvp] * dp[6]) + (vp[8 + dvp] * dp[7]) + (vp[7 + dvp] * dp[8]) + (vp[6 + dvp] * dp[9]) + (vp[5 + dvp] * dp[10]) + (vp[4 + dvp] * dp[11]) + (vp[3 + dvp] * dp[12]) + (vp[2 + dvp] * dp[13]) + (vp[1 + dvp] * dp[14]) + (vp[0 + dvp] * dp[15]) ) * scalefactor); tmpOut[i] = pcm_sample; dvp += 16; } // for }
1
public void play() { pause = false; timer = new Timer(); timer.scheduleAtFixedRate(new Timing(this), 0, (int) (50.0f / vitesseBase)); }
0
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Library library = new Library(); ResultPage<Patron> patrons = library.getPatronList( Integer.parseInt(request.getParameter("offset"))); JSONObject result = new JSONObject(); JSONArray results = new JSONArray(); for (Patron patron : patrons.getResults()) { results.put(patron.asJSONObject()); } result.put("results", results); result.put("pageNumber", patrons.getPageNumber()); result.put("isBeginning", patrons.getIsBeginning()); result.put("isEnd", patrons.getIsEnd()); response.setContentType("application/json"); response.getWriter().print(result); response.getWriter().close(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } }
4
public PointGame getLeftNeighbor() { int x0 = x; int y0 = y; while (x0 > MINX) { // check if x=4 and y=3, we cannot go to the left. if(x0==4 && y0==3) break; x0--; if (Board.validPoints.contains(new PointGame(x0,y0))) { return new PointGame(x0,y0); } } return null; }
4
private void checkForPrompt() { // Text has been entered, remove the prompt if (document.getLength() > 0) { setVisible( false ); return; } else if(show == Show.EMPTY) { //Show always parent text is empty setVisible(true); return; } // Prompt has already been shown once, remove it if (showPromptOnce && focusLost > 0) { setVisible(false); return; } // Check the Show property and component focus to determine if the // prompt should be displayed. if (component.hasFocus()) { if (show == Show.ALWAYS || show == Show.FOCUS_GAINED) setVisible( true ); else setVisible( false ); } else { if (show == Show.ALWAYS || show == Show.FOCUS_LOST) setVisible( true ); else setVisible( false ); } }
9
@Override public boolean show() { if (!tab.open()) return false; WidgetChild window = Widgets.get(BOOK_WIDGET, CLICK_WINDOW); WidgetChild wc = getChild(); WidgetChild scrollbar = Widgets.get(BOOK_WIDGET, SCROLLBAR); if (wc == null || window == null || scrollbar == null || !wc.visible() || !window.visible()) return false; if (window.getBoundingRectangle().contains(wc.getBoundingRectangle())) return isVisible(); if (!Widgets.scroll(wc, scrollbar)) return false; return isVisible(); }
8
public void keyPressed(KeyEvent arg0) { if(arg0.getKeyCode() == KeyEvent.VK_ESCAPE) { frame.setVisible(false); } }
1
public void chargeProvinceRent(Player player) { String playerName = player.getName(); String worldName = player.getWorld().getName(); String query = "SELECT * FROM `Monarchy_Provinces` WHERE `player` = ? AND `world` = ? ORDER BY `time` ASC;"; Connection con = getSQLConnection(); try { PreparedStatement statement = con.prepareStatement(query); statement.setString(1, playerName); statement.setString(2, worldName); ResultSet result = statement.executeQuery(); double lastPaid, secondsSince; double rentTime; int rentDue; int totalDue = 0; int totalPaid = 0; List<provinceInfo> paidProvinces = new ArrayList<provinceInfo>(); List<provinceInfo> lateProvinces = new ArrayList<provinceInfo>(); int x, z; provinceInfo province; while (result.next()) { lastPaid = result.getTimestamp(8).getTime() / 1000D; secondsSince = (Monarchy.getUnixTime() - lastPaid); rentTime = (secondsSince / (Config.provinceRentTime * 60 * 60)); rentDue = (int) Math.floor(rentTime * Config.provinceRentFee); totalDue += rentDue; // x = result.getInt(4); // z = result.getInt(5); // plugin.info("x:"+x+",z:"+z+", seconds: " + secondsSince + // ", rentTime:" +rentTime + ", rentDue:"+rentDue); // provinceRentFee province = new provinceInfo(result.getInt(1), // id result.getString(2),// player result.getString(3),// world result.getInt(4),// x result.getInt(5),// z result.getInt(6),// parent //result.getInt(7),// permitted result.getString(7),// invited (result.getTimestamp(8).getTime() / 1000D) // time ); if (rentDue > 0) { if (Monarchy.getTotalExperience(player) >= rentDue) { totalPaid += rentDue; Monarchy.takeExp(player, rentDue); paidProvinces.add(province); } else { lateProvinces.add(province); } } } if (totalPaid > 0) plugin.sendMessage(player, F("stPaidProvinceFees", totalPaid)); // plugin.info(playerName + " owes " + totalDue + " exp."); /**/ int success; query = "UPDATE `Monarchy_Provinces` SET `time` = CURRENT_TIMESTAMP WHERE `id` = ?;"; statement = con.prepareStatement(query); for (int i = 0; i < paidProvinces.size(); i++) { statement.setInt(1, paidProvinces.get(i).id); success = statement.executeUpdate(); // plugin.info("Updated " + paidProvinces.get(i).id + // " to current date."); } query = "DELETE FROM `Monarchy_Provinces` WHERE `id` = ?;"; statement = con.prepareStatement(query); for (int i = lateProvinces.size() - 1; i >= 0; i--) { lastPaid = lateProvinces.get(i).time; secondsSince = (Monarchy.getUnixTime() - lastPaid); if (secondsSince > (Config.provinceRentExpire * 60 * 60)) { statement.setInt(1, lateProvinces.get(i).id); success = statement.executeUpdate(); // plugin.info("Removed " + lateProvinces.get(i) + // " from db."); plugin.sendMessage(player, F("stLostProvinceClaim", worldName, lateProvinces.get(i).x * 16, lateProvinces.get(i).z * 16)); } else { int due = (int) ((Config.provinceRentExpire * 60 * 60) - secondsSince) / 60 / 60; plugin.sendMessage(player, F("stProvinceRentIsLate", worldName, lateProvinces.get(i).x * 16, lateProvinces.get(i).z * 16, due)); } } statement.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } }
8
public int balance () { org.omg.CORBA.portable.InputStream $in = null; try { org.omg.CORBA.portable.OutputStream $out = _request ("balance", true); $in = _invoke ($out); int $result = $in.read_long (); return $result; } catch (org.omg.CORBA.portable.ApplicationException $ex) { $in = $ex.getInputStream (); String _id = $ex.getId (); throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException $rm) { return balance ( ); } finally { _releaseReply ($in); } } // balance
2
public void keyReleased(KeyEvent e) { if (e.getKeyCode() == 10) { if (textWavelength.isFocusOwner()) { wavelength = (int) Double.parseDouble(textWavelength .getText().replaceAll(",", "")); loadExistingValues(); updateConsole(); } else if (textPower.isFocusOwner()) { power[i] = Double.parseDouble(textPower.getText() .replaceAll(",", "")); updateConsole(); if (i == 10) i = 0; else i++; labelPowerMesured.setText("Power mesured for point " + (i + 1) + " / 11 :"); textPower.setText("" + power[i]); actionManager.calibrationUp(); } } }
4
@Override public void draw() { StringBuilder s = new StringBuilder(); for (int i = 0; i < side; i++) { s.append("# "); } for (int i = 0; i < side; i++) { System.out.println(s); } }
2
@SuppressWarnings({ "unchecked", "rawtypes" }) public void SaveLevel() { System.out.println("Attempting level save."); new Thread(new Runnable() { public void run() { for(int i = 1; i<=Layers; i++) { File layer_file = new File(workingDir, ("Layer" + i + ".dat")); FileSystem.SaveDatFile(LayerList.get((i - 1)).tiles, layer_file); } if(colltype.equals(CollisionType.ADVANCED_COLLBOX)) { for(int e = 1; e<=Layers; e++) { File layer_file = new File(workingDir, ("Layer" + e + "_Collision.dat")); FileSystem.SaveDatFile(collisionLayers.get(e - 1).tiles, layer_file); } } File LevelConfig = new File(workingDir, "level.yml"); try { LevelConfig.createNewFile(); YamlConfig configYML = new YamlConfig(LevelConfig); Map config = configYML.getMap(); if(config == null) config = new HashMap(); config.put("WarPigionVersion", WPEngine1.Version); config.put("Name", name); config.put("Width", width); config.put("Height", height); config.put("Layers", Layers); config.put("CollisionType", colltype); configYML.setMap(config); configYML.save(); } catch (IOException e) { e.printStackTrace(); } } }).start(); System.out.println("Level save complete."); }
5
public synchronized void detectPulse(Record record) { if (this.lastRecord != null) { // check whether we have not found a peak after 166% of avg2 if so take the last peak as a signal peak // if that greater than half threshold. if ((record.getTime() - this.lastSPKTime) > 1.66 * this.qrsDetector.getAvg2()) { if (this.lastPeak > this.threshould2) { // then we consider this as a signal peak. this.spk = 0.25 * this.peak + 0.75 * this.spk; updateThresholds(); processQRS(new Record(this.lastPeakTime, this.lastPeak)); this.lastSPKTime = this.lastPeakTime; } } if (this.lastRecord.getValue() < record.getValue()) { isIncreasing = true; } else if (isIncreasing && (this.lastRecord.getValue() > record.getValue())) { //i.e we have found a peek. isIncreasing = false; // System.out.println("Peak found at " + this.lastRecord.getTime() + " value " + this.lastRecord.getValue() + " threshold " + this.threshould1); if (this.lastRecord.getTime() - this.lastSPKTime > 0.3) { // there can not be a signal peak before that. double peakValue = this.lastRecord.getValue(); if (peakValue > this.threshould1) { if (this.peak < peakValue) { this.peak = peakValue; } // this is a signal peak this.spk = 0.125 * this.peak + 0.875 * this.lastRecord.getValue(); updateThresholds(); processQRS(this.lastRecord); this.lastSPKTime = this.lastRecord.getTime(); } else { // if this is not a signal threshold then this is taken as a noise threshold this.nPeak = 0.125 * this.peak + 0.875 * this.lastRecord.getValue(); updateThresholds(); } this.lastPeakTime = this.lastRecord.getTime(); this.lastPeak = this.lastRecord.getValue(); } } } this.lastRecord = record; }
9
@Override protected void _processWalks(WalkArray walkArray, int[] atVertices) { long[] walks = ((LongWalkArray)walkArray).getArray(); long t1 = System.currentTimeMillis(); for(int i=0; i < walks.length; i++) { long w = walks[i]; int atVertex = atVertices[i]; int sourceIdx = manager.sourceIdx(w); if (atVertex == sourceVertexIds[sourceIdx]) { continue; } synchronized (buffers[sourceIdx]) { buffers[sourceIdx].add(atVertex); } } long tt = (System.currentTimeMillis() - t1); if (tt > 1000) { logger.info("Processing " + walks.length + " took " + tt + " ms."); } }
3
@Override public void run() { try { Thread.sleep(1000); System.out.println("here"); } catch (InterruptedException e) { e.printStackTrace(); } }
1
private void removeClientFromResourceMap(ClientInterface clientInterface){ synchronized(resourcesOfClients){ Set<String> list = resourcesOfClients.keySet(); Iterator<String> iter = list.iterator(); Vector<String> keysToBeDeleted = null; while(iter.hasNext()) { String key = iter.next(); resourcesOfClients.get(key).remove(clientInterface); if(resourcesOfClients.get(key).isEmpty()){ if(keysToBeDeleted != null) keysToBeDeleted.add(key); else{ keysToBeDeleted = new Vector<String>(); keysToBeDeleted.add(key); } } } for(String s : keysToBeDeleted) resourcesOfClients.remove(s); } }
4
private void divideSamples(Node node, SampleSet nodeSet){ /* * The first step is to assign the given set to the top node of the subtree. * If it is a leaf, we're done; else we have to divide the samples into the * correct subsets for the subtrees. */ node.setSampleSet(nodeSet); if(!node.isLeaf()){ InternalNode decisionNode = (InternalNode) node; Test nodeTest = decisionNode.getTest(); System.out.println("Dividing pruning set based on "+ decisionNode.getTest().printTest()); /* * For tests on continuous attributes, the division is always binary. * Therefore we can divide the set into the set for which the test is true * and the set for which it's false. This is obviously dependent on the * test of the node, which is always a comparison "<x" due to the construction implementation. */ if(nodeTest instanceof ContinuousTest){ SampleSet trueSet = new SampleSet(); trueSet.setAtrributes(nodeSet.getAttributes()); SampleSet falseSet = new SampleSet(); falseSet.setAtrributes(nodeSet.getAttributes()); for(Sample s: nodeSet.getSamples()){ if(s.getValue(nodeTest.getTestAttribute().getId()).doubleValue() < ((ContinuousTest) nodeTest).getSplitValue()){ trueSet.addSample(s); }else falseSet.addSample(s); } /* * After the determination of the true and false set dependent on the node's test * those sets are recursively distributed among the two subtrees starting with the node's children. */ for(Node child: decisionNode.getChildren()){ if (((ContinuousTestValue) child.getTestValue()).value == true){ divideSamples(child, trueSet); }else{ divideSamples(child, falseSet); } } } /* * For categorical Attributes the distribution is done per child. * For each child, all samples with the correct attribute value according * to the testValue of the child are assembled in a new set of samples. * Then the derived samples are distributed in the subtree of that child. */ else{ CategoricalAttribute decisionAttribute = (CategoricalAttribute) decisionNode.getTest().getTestAttribute(); for(Node child: decisionNode.getChildren()){ SampleSet childSet = new SampleSet(); childSet.setAtrributes(nodeSet.getAttributes()); String childValue = ((CategoricalTestValue) child.getTestValue()).getValue(); for(Sample s: nodeSet.getSamples()){ if(s.getValue(decisionAttribute.getId()).equals(decisionAttribute.addValue(childValue))){ childSet.addSample(s); } } divideSamples(child, childSet); } } } }
9
protected boolean checkCDATA(StringBuffer buf) throws IOException { char ch = this.readChar(); if (ch != '[') { this.unreadChar(ch); this.skipSpecialTag(0); return false; } else if (!this.checkLiteral("CDATA[")) { this.skipSpecialTag(1); // one [ has already been read return false; } else { int delimiterCharsSkipped = 0; while (delimiterCharsSkipped < 3) { ch = this.readChar(); switch (ch) { case ']': if (delimiterCharsSkipped < 2) { delimiterCharsSkipped += 1; } else { buf.append(']'); buf.append(']'); delimiterCharsSkipped = 0; } break; case '>': if (delimiterCharsSkipped < 2) { for (int i = 0; i < delimiterCharsSkipped; i++) { buf.append(']'); } delimiterCharsSkipped = 0; buf.append('>'); } else { delimiterCharsSkipped = 3; } break; default: for (int i = 0; i < delimiterCharsSkipped; i += 1) { buf.append(']'); } buf.append(ch); delimiterCharsSkipped = 0; } } return true; } }
9
public static String parseSpace(char[] s, int length) { // 1.check number of space in original array int count = 0; for (char c : s) { if (c == ' ') { ++count; } } int newLength = length + count * 2; int j = newLength - 1; for ( int i=length-1; i >=0; --i ){ if ( s[i] == ' ' ){ s[j--] = '0'; s[j--] = '2'; s[j--] = '%'; }else{ s[j--] = s[i]; } } return new String( s ); }
4
protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
9
int getCountCorrect() { int count = 0; for(int i=0;i<sudokuSize;i++) { for(int j=0;j<sudokuSize;j++) { if(cells[i][j].valueState == 1 || cells[i][j].valueState == 7) count++; } } return count; }
4
private HttpResponse processRequest() { try { // Read client Input and parse it. BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream())); RequestParser requestParser = new RequestParser(this); parsedHttpRequest = requestParser.getParsedRequest(inFromClient); // Check if connection was terminated by client. if (isTerminatedByClient) { isKeepAlive = false; return null; } // Get request parameters and request as string. httpRequestParams = requestParser.getParametersMap(); request = requestParser.getRequest(); httpResponseMaker = new HttpResponseMaker(this); // Print request to console System.out.println(request); // Validate if parse is OK. if (parsedHttpRequest == null) { return httpResponseMaker.makeErrorPageResponse(HttpResponse.RESPONSE_400_BAD_REQUEST, "Your browser sent a request that this server did not understand"); } /* * Check if head request (this check is here because even if response would be an error response, we will * return only the headers) */ isHeadRequest = (parsedHttpRequest.get(RequestParser.METHOD).equals(HTTP_METHOD_HEAD)); // Validate location if (!isValidLocation(parsedHttpRequest.get(RequestParser.LOCATION))) { return httpResponseMaker.makeErrorPageResponse(HttpResponse.RESPONSE_400_BAD_REQUEST, "Your browser sent a request that this server did not understand"); } // Validate HTTP Protocol else if (!isValidProtocol(parsedHttpRequest.get(RequestParser.PROTOCOL))) { return httpResponseMaker.makeErrorPageResponse(HttpResponse.RESPONSE_505_BAD_HTTP_VERSION, "Your browser sent a request with an HTTP version this server does not support"); } // Validations for HTTP 1.1 else if (parsedHttpRequest.get(RequestParser.PROTOCOL).equals(PROTOCOL_HTTP11) && !isValidHTTP11()) { return httpResponseMaker.makeErrorPageResponse(HttpResponse.RESPONSE_400_BAD_REQUEST, "Your browser sent a request that this server did not understand"); } else { isKeepAlive = checkKeepalive(); isChunked = checkChunked(); return processHttpResponse(); } } catch (SocketTimeoutException e) { return httpResponseMaker.makeErrorPageResponse(HttpResponse.RESPONSE_408_REQUEST_TIMEOUT, "The server timed out while waiting for the browser's request"); } catch (Exception e) { e.printStackTrace(); return httpResponseMaker.makeErrorPageResponse(HttpResponse.RESPONSE_500_INTERNAL_ERROR, "Internal Error"); } }
8
protected void doProtocolPings() { if(getClientTelnetMode(TELNET_MSDP)) { final byte[] msdpPingBuf=CMLib.protocol().pingMsdp(this, msdpReportables); if(msdpPingBuf!=null) { try { rawBytesOut(rawout, msdpPingBuf); } catch (final IOException e) { } if(CMSecurity.isDebugging(CMSecurity.DbgFlag.TELNET)) Log.debugOut("MSDP Reported: "+msdpPingBuf.length+" bytes"); } } if(getClientTelnetMode(TELNET_GMCP)) { final byte[] gmcpPingBuf=CMLib.protocol().pingGmcp(this, gmcpPings, gmcpSupports); if(gmcpPingBuf!=null) { try { rawBytesOut(rawout, gmcpPingBuf); } catch (final IOException e) { } } } }
7
private boolean isSwf(String filetype){ if(filetype.equals("doc") ||filetype.equals("docx") ||filetype.equals("ppt") ||filetype.equals("pptx") ||filetype.equals("xls") ||filetype.equals("xlsx")) { return true; }else{ return false; } }
6
private Dimension layoutSize(Container parent, boolean minimum) { Dimension dim = new Dimension(0, 0); Dimension d; synchronized (parent.getTreeLock()) { int n = parent.getComponentCount(); for (int i = 0; i < n; i++) { Component c = parent.getComponent(i); if (c.isVisible()) { d = minimum ? c.getMinimumSize() : c.getPreferredSize(); dim.width = Math.max(dim.width, d.width); dim.height += d.height; if (i > 0) { dim.height += this.vgap; } } } } Insets insets = parent.getInsets(); dim.width += insets.left + insets.right; dim.height += insets.top + insets.bottom + this.vgap + this.vgap; return dim; }
4
public Carte( String url, int i, String nomAnimal ) { this.url = url; this.nomAnimal = nomAnimal; ijk = i; telecharger(); initComponents(); label1.setIcon(new ImageIcon(nomImage)); }
0
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (args.length == 1 && "reload".equalsIgnoreCase(args[0]) && sender.hasPermission("orelog.reload")) { if (sender instanceof Player) { this.plugin.reload(sender.getName()); } this.plugin.reload(); } else { LogOre.communicate(sender, this.info); LogOre.communicate(sender, this.authors); } return true; }
4
public static void clientRemove(final Socket socket,DataInputStream datais,String basepath) { boolean success=false; DataOutputStream dataOutputStream=null; OutputStream outputStream=null; try { outputStream=socket.getOutputStream(); dataOutputStream = new DataOutputStream(outputStream); // 读取到请求的url String url = datais.readUTF(); Pattern regex = Pattern.compile("/[A-Z0-9]{2}/[A-Z0-9]{2}/[A-Za-z0-9-]+\\.[a-z]+"); Matcher matcher = regex.matcher(url); if (matcher.find()) { String storepath = basepath + matcher.group(); System.out.println("file disk store path:" + storepath); File file = new File(storepath); if (file.exists()) success = file.delete(); } dataOutputStream.writeBoolean(success); dataOutputStream.flush(); } catch (Exception e) { e.printStackTrace(); }finally{ if(dataOutputStream!=null){ try { dataOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if(outputStream!=null){ try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
9
public void setupButtons() { side_hud_panel.removeAll(); if (selected.size() > 0 && selected.getFirst() instanceof VillagerEntity) { VillagerEntity tower = ((VillagerEntity) selected.getFirst()); final JCheckBox build = new JCheckBox("Build: " + createCostString(VillagerEntity.MAKE_TOWER_COST)); side_hud_panel.add(build); pack(); build.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (build.isSelected()) { mode = BUILD_MODE; } else { mode = NORMAL_MODE; } } }); } if (selected.size() > 0 && selected.getFirst() instanceof TowerEntity) { TowerEntity tower = ((TowerEntity) selected.getFirst()); final JButton upgrade = new JButton("Upgrade: " + createCostString(TowerEntity.UPGRADE_COST[tower.level])); final JButton villager = new JButton("Make villager: " + createCostString(TowerEntity.MAKE_VILLAGER_COST)); side_hud_panel.add(upgrade); side_hud_panel.add(villager); pack(); upgrade.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { TowerEntity tower = ((TowerEntity) selected.getFirst()); if (canAfford(TowerEntity.UPGRADE_COST[tower.level])) { if (tower.upgrade()) { decrementResources(TowerEntity.UPGRADE_COST[tower.level - 1]); upgrade .setText("Upgrade: " + createCostString(TowerEntity.UPGRADE_COST[tower.level])); } } } }); villager.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { TowerEntity tower = ((TowerEntity) selected.getFirst()); if (canAfford(TowerEntity.MAKE_VILLAGER_COST)) { fireGlobalEvent(new AddEntity(this, ADD_VILLAGER, (int) tower.point.x, (int) tower.point.y)); decrementResources(TowerEntity.MAKE_VILLAGER_COST); } } }); } }
8
private void inviteNickHelper() { if (true) { return; } //TODO Fix this method if (!hasArgs || !(cmdArgs.split("\\s++").length > 0)) { // Min 1 Arg //@TODO Replace code with getHelp(cmd); //Overloaded method connection.msgChannel(config.getChannel(), "Usage: " + config.getCmdSymb() + "invite-nick {nick} [# of times]"); } else { connection.msgChannel(config.getChannel(), "Roger that."); String cmdArgsArr[] = cmdArgs.split("\\s++"); int numInvites = 50; // Default value if (cmdArgsArr.length < 1) { try { Thread.sleep(1500); numInvites = Integer.getInteger(cmdArgsArr[1]); //TODO replace with FileReader.getMaster() if (connection.recieveln().contains(":JRobo!~Tux@unaffiliated/robotcow QUIT :Excess Flood")) { // this.jRobo. } } catch (Exception ex) { //Find out exactly what exceptions are thrown Logger.getLogger(BotCommand.class.getName()).log(Level.SEVERE, null, ex); } } for (int x = 0; x < numInvites; x++) { connection.sendln("INVITE " + config.getChannel() + " " + cmdArgsArr[0]); } } }
7
public static boolean isPowerProviderOrWire(IBlockAccess var0, int var1, int var2, int var3, int var4) { int var5 = var0.getBlockId(var1, var2, var3); if(var5 == Block.redstoneWire.blockID) { return true; } else if(var5 == 0) { return false; } else if(Block.blocksList[var5].canProvidePower()) { return true; } else if(var5 != Block.redstoneRepeaterIdle.blockID && var5 != Block.redstoneRepeaterActive.blockID) { return false; } else { int var6 = var0.getBlockMetadata(var1, var2, var3); return var4 == ModelBed.footInvisibleFaceRemap[var6 & 3]; } }
5
@Override @Command public MessageResponse getProxyPublicKey() throws IOException { if(initRMI()) { ProxyPublicKeyResponse response = proxyRMI.getProxyPublicKey(); if(!response.hasKey()) return new MessageResponse(response.toString()); else { String pathToPublicKey = keysDir+"/proxy.pub.pem"; PEMWriter out = new PEMWriter(new FileWriter(pathToPublicKey)); out.writeObject(response.getKey()); out.close(); return new MessageResponse("Successfully received public key of Proxy."); } } else return new MessageResponse("Cannot connect to Proxy via RMI"); }
2
public <VT> List<VertexIdValue<VT>> queryWithValues(int vertexId, BytesToValueConverter<VT> conv) throws IOException { List<VertexIdValue<VT>> results = new ArrayList<VertexIdValue<VT>>(); ShardIndex.IndexEntry entry = index.lookup(vertexId); int curvid = entry.vertex; int adjOffset = entry.fileOffset; int edgeOffset = entry.edgePointer; String edataShardName = ChiFilenames.getFilenameShardEdata(fileName, conv, shardNum, numShards); int fileSize = ChiFilenames.getShardEdataSize(edataShardName); adjFile.seek(adjOffset); /* Edge data block*/ int blockSize = ChiFilenames.getBlocksize(conv.sizeOf()); byte[] edgeDataBlock = new byte[blockSize]; int curBlockId = (-1); byte[] tmp = new byte[conv.sizeOf()]; while(curvid <= vertexId) { int n; int ns = adjFile.readUnsignedByte(); assert(ns >= 0); adjOffset++; if (ns == 0) { curvid++; int nz = adjFile.readUnsignedByte(); adjOffset++; assert(nz >= 0); curvid += nz; continue; } if (ns == 0xff) { n = adjFile.readInt(); adjOffset += 4; } else { n = ns; } if (curvid == vertexId) { while (--n >= 0) { int target = adjFile.readInt(); int blockId = edgeOffset * conv.sizeOf() / blockSize; if (blockId != curBlockId) { String blockFileName = ChiFilenames.getFilenameShardEdataBlock( edataShardName, blockId, blockSize); curBlockId = blockId; int len = Math.min(blockSize, fileSize - blockId * blockSize); CompressedIO.readCompressed(new File(blockFileName), edgeDataBlock, len); } System.arraycopy(edgeDataBlock, (edgeOffset * conv.sizeOf()) % blockSize, tmp, 0, conv.sizeOf()); VT value = conv.getValue(tmp); results.add(new VertexIdValue<VT>(target, value)); edgeOffset++; } } else { adjFile.skipBytes(n * 4); edgeOffset += n; } curvid++; } return results; }
6
public static void setOutputParams(String failedUrlsFileName, String succedUrlsFileName, String postsFileName, String postsParamsFileName, WriteToCsvDiscussionsFile writeToCsvDiscussionsFile) { OutputParams.failedUrlsFileName = failedUrlsFileName; OutputParams.succedUrlsFileName = succedUrlsFileName; OutputParams.writeToCsvDiscussionsFile = writeToCsvDiscussionsFile; File failedUrlsFile =new File(failedUrlsFileName); if (!failedUrlsFile.exists()) { try { failedUrlsFile.createNewFile(); } catch (IOException e) { Logger.getLogger(OutputParams.class).debug("Execption while creating failed Urls file : "+ e.getMessage()); } } File succedUrlsFile =new File(succedUrlsFileName); if (!succedUrlsFile.exists()) { try { succedUrlsFile.createNewFile(); } catch (IOException e) { Logger.getLogger(OutputParams.class).debug("Execption while creating failed Urls file : "+ e.getMessage()); } } }
4
public void handleAnnounceResponse(Map<String, BEValue> answer) { try { if (answer != null && answer.containsKey("interval")) { this.interval = answer.get("interval").getInt(); this.initial = false; } } catch (InvalidBEncodingException ibee) { this.stop(true); } }
3
public Rectangle2D.Float getBounds() { if (bounds == null) { // increase bounds as glyphs are detected. for (GlyphText glyph : glyphs) { if (bounds == null) { bounds = new Rectangle2D.Float(); bounds.setRect(glyph.getBounds()); } else { bounds.add(glyph.getBounds()); } } } return bounds; }
3
private void createUser() { if(userType.equalsIgnoreCase("guest")) user = new GuestUser(); else if(userType.equalsIgnoreCase("handicap")) user = new HandicappedUser(); else { searchFiu(userID); if(userType.equalsIgnoreCase("student")) user = new StudentUser(userID, userName); else if(userType.equalsIgnoreCase("faculty")) user = new FacultyUser(userID, userName); else if(userType.equalsIgnoreCase("handicapped")) user = new HandicappedUser(); else user = new GuestUser(); } }
5
public void analyze(int minWalkId, int maxWalkId, int maxHops) throws IOException { int numberOfWalks = maxWalkId - minWalkId + 1; Walk[] paths = new Walk[numberOfWalks]; for(int i=0; i < paths.length; i++) { paths[i] = new Walk(maxHops); } String[] walkFiles = directory.list(new FilenameFilter() { @Override public boolean accept(File file, String s) { return s.startsWith("walks_"); } }); for(String walkFile : walkFiles) { System.out.println("Analyze: " + walkFile); long walksInFile = new File(directory, walkFile).length() / 10; DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream( new File(directory, walkFile)), 1024 * 1024 * 50)); try { long i = 0; while(i < walksInFile) { if (i % 1000000 == 0) System.out.println(i + " / " + walksInFile); i++; int walkId = dis.readInt(); short hop = dis.readShort(); int atVertex = dis.readInt(); if (walkId >= minWalkId && walkId <= maxWalkId) { paths[walkId - minWalkId].addWalk(hop, atVertex); } } } catch (EOFException ioe) { continue; } dis.close(); } for(Walk w : paths) { w.sort(); } /* Analyze the walks */ groupBySourceAndAnalyze(paths); output.close(); }
8
@Override public boolean equals(Object o) { LightRabin tmpLIFRTA = (LightRabin) o; return tmpLIFRTA.states.equals(states) && tmpLIFRTA.initialState.equals(initialState) && tmpLIFRTA.liveStates.equals(liveStates); }
2
public void render() { System.out.println("RenderLoopBegin"); try { g = bi.createGraphics(); g.setColor(background); g.fillRect(0, 0, frameW, frameH); /************/ for (int i = 0; i < tasks.size(); ) { tmpTask = tasks.get(i); tmpTask.executeTask(); if (tmpTask.getTaskDone() ) { tasks.remove(tmpTask); //System.out.println("TASK DONE"); } else { i++; } } for (Layer L : gameLayers) { for (Entity e : L.getEntList() ) { e.draw(g); } } for (LayerConnection lc : collisionConnections) { lc.processConnection(); } /************/ graphics = strategy.getDrawGraphics(); graphics.drawImage(bi, 0, 0, null); if (!strategy.contentsLost() ) strategy.show(); System.out.println("RenderLoopStop"); } finally { if (graphics != null) { graphics.dispose(); } if (g != null) { g.dispose(); } } }
8
public void acquireLog() { synchronized (fLogLengthTable) { String ip = null; String logKey = null; int logLength = 0; Integer lengthValue = null; fLogAcquired = false; MeetingProtocol.getInstance().logLengthRequest(fInternalRoomName); try { fLogLengthTable.wait(4 * 1000); // 4 seconds } catch (InterruptedException e) {} while (fLogLengthTable.size() > 0 && !fLogAcquired) { // // Find the longest log. // Enumeration<String> keys = fLogLengthTable.keys(); ip = null; logKey = null; logLength = 0; while (keys.hasMoreElements()) { logKey = keys.nextElement(); lengthValue = fLogLengthTable.get(logKey); if (ip == null) { ip = logKey; logLength = lengthValue.intValue(); } else if (logLength < lengthValue.intValue()) { ip = logKey; logLength = lengthValue.intValue(); } } // // Ask the log only if the logLength is greater than the length of // my log. In the near future, acquireLog() could be called anytime. [V1.75] // if (logLength > fLogText.length()) { MiscProtocol.getInstance().logRequest(fInternalRoomName, ip); try { fLogLengthTable.wait(3 * 1000); // wait 3 seconds } catch (InterruptedException e) {} if (fLogAcquired) { fLogArea.clear(); fLogArea.appendText(fLogText.toString()); } } fLogLengthTable.remove(ip); } fLogAcquired = true; } }
9
public static String getCoastlineCoding(Game game, Position center) { char[] coding = {'0','0','0','0' }; int row = center.getRow(), col = center.getColumn(); Position p; int offsetRow[] = { -1,0,+1,0 }; int offsetCol[] = { 0,+1,0,-1 }; // iterate over the four compas directions // for each find the proper tile p and // check if there is a coastline for ( int i = 0; i < 4; i++ ) { p = new Position( row+offsetRow[i], col+offsetCol[i]); if ( p.getRow() >= 0 && p.getRow() < GameConstants.WORLDSIZE && p.getColumn() >= 0 && p.getColumn() < GameConstants.WORLDSIZE && game.getTileAt(p).getTypeString() != GameConstants.OCEANS ) { coding[i] = '1'; } } String s = new String(coding); return s; }
6
private Image unmarshalImage(Node t, String baseDir) throws IOException { Image img = null; String source = getAttributeValue(t, "source"); if (source != null) { if (checkRoot(source)) { source = makeUrl(source); } else { source = makeUrl(baseDir + source); } img = ImageIO.read(new URL(source)); } else { NodeList nl = t.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if ("data".equals(node.getNodeName())) { Node cdata = node.getFirstChild(); if (cdata != null) { String sdata = cdata.getNodeValue(); char[] charArray = sdata.trim().toCharArray(); byte[] imageData = Base64.decode(charArray); img = ImageHelper.bytesToImage(imageData); // Deriving a scaled instance, even if it has the same // size, somehow makes drawing of the tiles a lot // faster on various systems (seen on Linux, Windows // and MacOS X). img = img.getScaledInstance( img.getWidth(null), img.getHeight(null), Image.SCALE_FAST); } break; } } } return img; }
5
static boolean parseArguments(String args[]) { if (args.length < 2) { System.out .println("Syntax: java Snoop <server_name> <port_number> [optional args]"); System.out.println("\nPossible values for [optional args]:"); System.out .println(" -snoopPort <local port number>"); System.out .println(" -showAscii <true|false> default=true"); System.out .println(" -showEbcdic <true|false> default=false"); System.out.println(" -traceFilePrefix <prefix>"); System.out .println(" -lineSize <line size value> default=8"); System.out .println(" -maxBytesInTraceFile <max trace file size>"); System.out .println(" -showTimestamps <true|false> default=false"); return false; } serverName = args[0]; serverPort = Integer.parseInt(args[1]); snoopPort = serverPort; traceFilePrefix = null; for (int index = 2; index < args.length; index++) { String curArg = args[index]; index++; if (curArg.equalsIgnoreCase("-showAscii")) { showAscii = Boolean.valueOf(args[index]).booleanValue(); continue; } if (curArg.equalsIgnoreCase("-showEbcdic")) { showEbcdic = Boolean.valueOf(args[index]).booleanValue(); continue; } if (curArg.equalsIgnoreCase("-lineSize")) { lineSize = Integer.parseInt(args[index]); continue; } if (curArg.equalsIgnoreCase("-snoopPort")) { snoopPort = Integer.parseInt(args[index]); continue; } if (curArg.equalsIgnoreCase("-traceFilePrefix")) { traceFilePrefix = args[index]; continue; } if (curArg.equalsIgnoreCase("-maxBytesInTraceFile")) { maxBytesInTraceFile = Integer.parseInt(args[index]); continue; } if (curArg.equalsIgnoreCase("-showTimestamps")) showTimestamps = Boolean.valueOf(args[index]).booleanValue(); } return true; }
9
@Override public int getVendidosSecao(Secao secao, Evento evento) { try { conn = ConnectionFactory.getConnection(); String sql = "SELECT COUNT(ingresso.id) AS vendidos " + "FROM ingresso " + "JOIN secao on ingresso.idsecao = secao.id " + "JOIN evento on secao.idevento = evento.id " + "WHERE idcompra IS NOT NULL " + "AND evento.nome LIKE ?" + "AND secao.nome LIKE ?"; ps = conn.prepareStatement(sql); ps.setString(1, evento.getNome()); ps.setString(2, secao.getNome()); rs = ps.executeQuery(); if (rs.next()){ int count = rs.getInt("vendidos"); return count; } else { close(); throw new RuntimeException("Não existem ingressos vendidos para a secao do evento!"); } } catch (SQLException e){ throw new RuntimeException("Erro " + e.getSQLState() + " ao atualizar o objeto: " + e.getLocalizedMessage()); } catch (ClassNotFoundException e){ throw new RuntimeException("Erro ao conectar ao banco: " + e.getMessage()); } finally { close(); } }
3
public static EventDetailInfo getEventDetail(int eventId) throws HibernateException { EventDetailInfo eventDetail = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); try { // Begin unit of work session.beginTransaction(); // get the event EventInfo eventInfo = getEventInfoById(eventId); if (eventInfo != null) { eventDetail = new EventDetailInfo(); eventDetail.setEventInfo(eventInfo); int ownerId = eventInfo.getOwnerId(); eventDetail.setOnwerInfo(getEventOwnerInfo(ownerId)); eventDetail.setEventGroup(getEventGroupInfo(eventId)); eventDetail.setShopInfo(getEventShopInfo(eventId)); List<UserInfo> eventUserList = getEventMemebers(eventId); eventDetail.setTotalMemeberCount(eventUserList == null ? 0 : eventUserList.size()); } } catch (HibernateException hex) { logger.error(hex.toString()); HibernateUtil.getSessionFactory().getCurrentSession() .getTransaction().rollback(); } catch (Exception ex) { logger.error(ex.toString()); HibernateUtil.getSessionFactory().getCurrentSession() .getTransaction().rollback(); } return eventDetail; }
4
@Override public boolean onPointerMove(int mX, int mY, int mDX, int mDY) { Iterator<IGameScreen> it = screens.iterator(); while(it.hasNext()) { IGameScreen screen = it.next(); if(screen.onPointerMove(mX, mY, mDX, mDY)) { return true; } } if(camera.onPointerMove(mX, mY, mDX, mDY)) { return true; } // to change mouse coordinates to "world" coordinates, we must take camera location into accord mX = (int)(mX + camera.getX()); mY = (int)(mY + camera.getY()); Application.get().getEventManager().queueEvent(new PointerMoveEvent(mX, mY, mDX, mDY)); return false; }
3
private boolean isEqual(char[] c, String s) { if (c.length != s.length()) return false; for (int i = 0; i < c.length; i++) if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(c[i])) return false; return true; }
3
public static void update(float delta) { if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)) { if (abilityRequesting != null) { abilityRequesting.fireAction(Camera.getRealWorldX(), Camera.getRealWorldY()); } Gdx.input.setCursorCatched(true); } else if (Gdx.input.isKeyPressed(Input.Keys.ESCAPE)) { Gdx.input.setCursorCatched(false); } if (Gdx.input.isCursorCatched()) { Gdx.input.setCursorPosition(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2); x += Gdx.input.getDeltaX(); y += Gdx.input.getDeltaY(); } if (x < 0) { x = 0; } else if (x > Gdx.graphics.getWidth()) { x = Gdx.graphics.getWidth(); } if (y < 0) { y = 0; } else if (y > Gdx.graphics.getHeight()) { y = Gdx.graphics.getHeight(); } }
8
private boolean r_un_accent() { int v_3; // (, line 215 // atleast, line 216 { int v_1 = 1; // atleast, line 216 replab0: while(true) { lab1: do { if (!(out_grouping_b(g_v, 97, 251))) { break lab1; } v_1--; continue replab0; } while (false); break replab0; } if (v_1 > 0) { return false; } } // [, line 217 ket = cursor; // or, line 217 lab2: do { v_3 = limit - cursor; lab3: do { // literal, line 217 if (!(eq_s_b(1, "\u00E9"))) { break lab3; } break lab2; } while (false); cursor = limit - v_3; // literal, line 217 if (!(eq_s_b(1, "\u00E8"))) { return false; } } while (false); // ], line 217 bra = cursor; // <-, line 217 slice_from("e"); return true; }
8
public boolean addSheet(String sheetname){ FileOutputStream fileOut; try { workbook.createSheet(sheetname); fileOut = new FileOutputStream(path); workbook.write(fileOut); fileOut.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
1
public void actionPerformed(ActionEvent e) { Object o = e.getSource(); Debug.print("Action performed on: " + o); if(o == okButton) { // create a new Ferm object Fermentable i = new Fermentable(); i.setName(txtName.getText()); try { NumberFormat format = NumberFormat.getInstance(Locale.getDefault()); Number number = format.parse(txtYield.getText().trim()); i.setPppg(number.doubleValue()); } catch (ParseException m) { Debug.print("Could not read txtYield as double"); } try { NumberFormat format = NumberFormat.getInstance(Locale.getDefault()); Number number = format.parse(txtLov.getText().trim()); i.setLov(number.doubleValue()); } catch (ParseException m) { Debug.print("Could not read txtLov as double"); } i.setCost(txtCost.getText()); try { NumberFormat format = NumberFormat.getInstance(Locale.getDefault()); Number number = format.parse(txtStock.getText().trim()); i.setStock(number.doubleValue()); } catch (ParseException m) { Debug.print("Could not read txtStock as double"); } i.setUnits(cUnits.getSelectedItem().toString()); i.setMashed(bMash.isSelected()); i.setDescription(txtDescr.getText()); i.setModified(bModified.isSelected()); i.setSteep(bSteep.isSelected()); i.ferments(bFerments.isSelected()); int result = 1; int found = 0; // check to see if we have this fermentable already in the db if((found = db.find(i)) >= 0){ // This already exists, do we want to overwrite? result = JOptionPane.showConfirmDialog((Component) null, "This ingredient exists, overwrite original?","alert", JOptionPane.YES_NO_CANCEL_OPTION); switch(result) { case JOptionPane.NO_OPTION: setVisible(false); dispose(); return; case JOptionPane.YES_OPTION: db.fermDB.remove(found); break; case JOptionPane.CANCEL_OPTION: return; } } db.fermDB.add(i); db.writeFermentables(); setVisible(false); dispose(); } else if(o == cancelButton) { dispose(); } }
9
private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage) { String eol = System.getProperty("line.separator", "\n"); StringBuffer expected = new StringBuffer(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected.append("..."); } expected.append(eol).append(" "); } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += " " + tokenImage[tok.kind]; retval += " \""; retval += add_escapes(tok.image); retval += " \""; tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected.toString(); return retval; }
8
public ArrayList getSolutionsRunningOnSpecificPlatform(int tmpClassID, String tmpPlatformName) { ArrayList result = new ArrayList<Solution>(); int tmpCounter = 0; ArrayList<Solution> allSolutionInstances = getInstances(tmpClassID); if(allSolutionInstances != null) { for(int i=0; i<allSolutionInstances.size(); i++) { Solution tmpSolution = allSolutionInstances.get(i); if(tmpSolution.runsOnPlatform != null && tmpSolution.runsOnPlatform.toLowerCase().indexOf(tmpPlatformName.toLowerCase()) != -1) { result.add(tmpSolution); tmpCounter++; if(printDebugInfo) System.out.println("\t\t" + Integer.toString(tmpCounter) + ") " + tmpSolution.hasSolutionName); } } } return result; }
5
public static boolean isVowel(String str, int index, int depth) throws java.io.IOException { if (index < str.length() && index >= 0) { char letter = str.charAt(index); if (inList(VOWELS, letter) > -1) { return true; } else if (letter == 'y') { if (depth > MAXYS - 1) throw new java.io.IOException("Too many 'y's. Char " + index); // avoid infinite recursion return !isVowel(str, index + 1, depth + 1) && !isVowel(str, index - 1, depth + 1); } } return false; }
6
protected void sortIntoMap() { outputMap = new TreeMap<Object, ArrayList<CalendarEvent>>(); int conflictNum = 1; for (int i = 0; i < outputList.size(); i++) { for (int j = 0; j < outputList.size(); j++) { if (j > i) { CalendarEvent event1 = outputList.get(i); long start1 = event1.getmyStartTime().getMillis(); long end1 = event1.getmyEndTime().getMillis(); CalendarEvent event2 = outputList.get(j); long start2 = event2.getmyStartTime().getMillis(); long end2 = event2.getmyEndTime().getMillis(); if ((start2 >= start1 && start2 <= end1) || (end2 >= start1 && end2 <= end1)) { ArrayList<CalendarEvent> pair = new ArrayList<CalendarEvent>(); pair.add(event1); pair.add(event2); outputMap.put("Conflict #" + conflictNum, pair); } } } } }
7
public static NoOpenStartTagException makeNoOpenStartTagException( int nodeKind, String name, int hostLanguage, boolean parentIsDocument, boolean isSerializing) { String message; String errorCode; if (parentIsDocument) { if (isSerializing) { String kind = (nodeKind == Type.ATTRIBUTE ? "attribute" : "namespace"); String article = (nodeKind == Type.ATTRIBUTE ? "an " : "a "); if (hostLanguage == Configuration.XSLT ) { message = "Cannot have " + article + kind + " node (" + name + ") whose parent is a document node"; errorCode = "XTDE0420"; } else { message = "Cannot serialize a free-standing " + kind + " node (" + name + ')'; errorCode = "SENR0001"; } } else { String kind = (nodeKind == Type.ATTRIBUTE ? "an attribute" : "a namespace"); message = "Cannot create " + kind + " node (" + name + ") whose parent is a document node"; errorCode = (hostLanguage == Configuration.XSLT ? "XTDE0420" : "XPTY0004"); } } else { String kind = (nodeKind == Type.ATTRIBUTE ? "An attribute" : "A namespace"); message = kind + " node (" + name + ") cannot be created after the children of the containing element"; errorCode = (hostLanguage == Configuration.XSLT ? "XTDE0410" : "XQTY0024"); } NoOpenStartTagException err = new NoOpenStartTagException(message); err.setErrorCode(errorCode); return err; }
9
public static void removeIfCaptured(Board board, int player, int x, int y) { if (board.intersections[x][y] == player) { List<Intersection> group = getGroup(board, x, y); if (countLiberties(board, group) == 0) { board.captures.addAll(group); for (Intersection intersection : group) { board.intersections[intersection.x][intersection.y] = Board.UNPLAYED; } } } }
3
static public Matricula instancia() { if (UnicaInstancia == null) { UnicaInstancia = new Matricula(); } return UnicaInstancia; }
1
public void traverse(ASTVisitor visitor, ClassScope classScope) { if (visitor.visit(this, classScope)) { if (this.javadoc != null) { this.javadoc.traverse(visitor, this.scope); } if (this.arguments != null) { int argumentLength = this.arguments.length; for (int i = 0; i < argumentLength; i++) this.arguments[i].traverse(visitor, this.scope); } if (this.constructorCall != null) this.constructorCall.traverse(visitor, this.scope); if (this.statements != null) { int statementsLength = this.statements.length; for (int i = 0; i < statementsLength; i++) this.statements[i].traverse(visitor, this.scope); } } visitor.endVisit(this, classScope); }
7
public MultipleCYKParseAction(GrammarEnvironment environment) { super("Multiple CYK Parse", environment); this.environment = environment; this.frame = Universe.frameForEnvironment(environment); }
0
@Override public Connection crearConexion() { try { InitialContext initialContext = new InitialContext(); DataSource dataSource = (DataSource) initialContext.lookup("java:comp/env/jdbc/ausiasyield"); Connection connection = dataSource.getConnection(); return connection; } catch (NamingException ex) { throw new RuntimeException(ex); } catch (SQLException ex) { throw new RuntimeException(ex); } }
2
public void mouseClicked(int clickX, int clickY) { clickY = (int)APPLET_HEIGHT - clickY; Point pnt = new Point(clickX, clickY); Point selection = new Point(); Card clickCard; if (pnt.x>offsetX && pnt.x<maxX && pnt.y>offsetY && pnt.y<maxY) { selection.x = (pnt.x-offsetX)/cardSize; selection.y = (pnt.y-offsetY)/cardSize; clickCard = grid[selection.x][selection.y]; }else{ return; } //first card if (firstCard == null){ firstCard = clickCard; SoundEffect.SELECT.play(); //card too far away }else if(!isAdjacent(firstCard,clickCard)){ firstCard = clickCard; SoundEffect.BAD.play(); //same card }else if(firstCard == clickCard){ firstCard = null; SoundEffect.BAD.play(); //swap cards }else if(isAdjacent(firstCard, clickCard)){ isSwapping=true; SwapCards(firstCard, clickCard); //make sure a match is performed if(CheckForMatches().size()<1){ SwapCards(firstCard, clickCard); firstCard = null; SoundEffect.BAD.play(); //if there is a match }else{ firstCard = null; SoundEffect.SWAP.play(); } } }
9
TreeNode next() { TreeNode head = queue.poll(); if (head == null) { if (!queue.isEmpty()) queue.offer(null); return null; } if (head.left != null) queue.offer(head.left); if (head.right != null) queue.offer(head.right); return head; }
4