text
stringlengths
14
410k
label
int32
0
9
public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.black); g2.fillRect(0, 0, WIDTH, HEIGHT); if(menu==null){ if(story==null){ lvl.draw(g2); }else{ story.draw(g2); } }else{ menu.draw(g2); } }
2
public static ArrayList<Book> getAllBooks() { try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ArrayList<Book> bookList = new ArrayList<Book>(); try { Statement stmnt = conn.createStatement(); String sql = "SELECT * FROM Books"; ResultSet res = stmnt.executeQuery(sql); while(res.next()) { Book b = new Book(res.getDate("year"), res.getString("place_of_publication"), res.getString("title"), res.getString("genre"), res.getString("author"), res.getString("isbn"), res.getString("publisher"), res.getInt("book_id")); bookList.add(b); } } catch(SQLException e) { System.out.println(e); } return bookList; }
5
static private boolean jj_3R_15() { if (jj_scan_token(ON)) return true; if (jj_3R_18()) return true; if (jj_scan_token(LBRACE)) return true; Token xsp; while (true) { xsp = jj_scanpos; if (jj_3_8()) { jj_scanpos = xsp; break; } } while (true) { xsp = jj_scanpos; if (jj_3_9()) { jj_scanpos = xsp; break; } } xsp = jj_scanpos; if (jj_3_10()) jj_scanpos = xsp; if (jj_scan_token(RBRACE)) return true; return false; }
9
@Override public boolean equals( Object that ) { if ( this == that ) return true; if ( that == null || !getClass().equals( that.getClass() ) ) return false; OptionSet other = (OptionSet) that; Map<AbstractOptionSpec<?>, List<String>> thisOptionsToArguments = new HashMap<AbstractOptionSpec<?>, List<String>>( optionsToArguments ); Map<AbstractOptionSpec<?>, List<String>> otherOptionsToArguments = new HashMap<AbstractOptionSpec<?>, List<String>>( other.optionsToArguments ); return detectedOptions.equals( other.detectedOptions ) && thisOptionsToArguments.equals( otherOptionsToArguments ); }
8
public static void setVals(double[] val, Param p) { Object o = p.getValue(); if (o.getClass() == double[].class) { p.setValue(val); } else if (o.getClass() == Double.class) { p.setValue(val[0]); } throw new IllegalArgumentException(p.toString()); }
2
@After public void tearDown() throws Exception { this.terminal=null; }
0
public int[][] zeroSet(int[][] matrix){ int m = matrix.length; int n = matrix[0].length; HashSet<Integer> column=new HashSet<Integer>(); HashSet<Integer> row=new HashSet<Integer>(); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(matrix[i][j]==0){ column.add(i); row.add(j); } } } for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(column.contains(i)||row.contains(j)){ matrix[i][j]=0; } } } return matrix; }
7
public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { case '"': case '\'': return this.nextString(c); case '{': this.back(); return new JSONObject(this); case '[': this.back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = this.next(); } this.back(); string = sb.toString().trim(); if ("".equals(string)) { throw this.syntaxError("Missing value"); } return JSONObject.stringToValue(string); }
7
private boolean checkDownRight(int _row, int _column, int _player) { boolean keepGoing = true; int nbAligned = 0; while (keepGoing == true && nbAligned < nbToAlign) { if (_row + nbAligned >= row || _column + nbAligned >= column) { keepGoing = false; } else if (gameGrid[_row + nbAligned][_column + nbAligned] != _player) { keepGoing = false; } nbAligned = nbAligned + 1; } return keepGoing; }
5
public T getInternal() { return internal; }
0
private static void configureGrid() { String rejilla = configuration.getProperty("NadgridsPath"); if (StringUtils.isBlank(rejilla)){ rejilla = "auto:peninsula"; } if (!rejilla.startsWith("auto")){ return; } File homeDir = new File(System.getProperty("user.home") + File.separator + ".cat2osm"); File archivoRejilla = null; String nombreRecursoRejilla = ""; if ("auto:peninsula".equals(rejilla) || "auto:peninsula.gsb".equals(rejilla)){ archivoRejilla = new File(homeDir, "peninsula.gsb"); nombreRecursoRejilla = "peninsula.gsb"; } else if ("auto:baleares".equals(rejilla) || "auto:baleares.gsb".equals(rejilla)){ archivoRejilla = new File(homeDir, "baleares.gsb"); nombreRecursoRejilla = "baleares.gsb"; } configuration.setProperty("NadgridsPath", archivoRejilla.getAbsolutePath()); try { extractGrid(nombreRecursoRejilla, archivoRejilla); } catch (IOException e) { e.printStackTrace(); } }
7
public static boolean reverseByteOrder(Class<?> libraryClass) { if (libraryClass == null) { errorMessage("Parameter 'libraryClass' null in method" + "'reverseByteOrder'"); return false; } if (!Library.class.isAssignableFrom(libraryClass)) { errorMessage("The specified class does not extend class " + "'Library' in method 'reverseByteOrder'"); return false; } Object o = runMethod(libraryClass, "reversByteOrder", new Class[0], new Object[0]); if (o == null) { errorMessage("Method 'Library.reverseByteOrder' returned " + "'null' in method 'getLibraryDescription'"); return false; } return (((Boolean) o).booleanValue()); }
4
public void wordMakeSets(){ System.out.println(">> AGRUPANDO PALAVRAS POR SEMELHANCA... AGUARDE."); TreeMap<Integer, ArrayList<String>> tree = new TreeMap<Integer, ArrayList<String>>(); for (Map.Entry<String, DisjointSet> entry : this.entrySet()) { if (tree.get(entry.getKey().length()) == null) { tree.put(entry.getKey().length(), new ArrayList<String>()); } tree.get(entry.getKey().length()).add(entry.getKey()); } for (Map.Entry<Integer, ArrayList<String>> entry : tree.entrySet()) { ArrayList<String> possibleSimilarities= new ArrayList<String>(); if (tree.get(entry.getKey() -1) != null) { possibleSimilarities.addAll(tree.get(entry.getKey() - 1)); } if (tree.get(entry.getKey() + 1 ) != null) { possibleSimilarities.addAll(tree.get(entry.getKey() + 1)); } for (String s : entry.getValue()) { for (String possible : possibleSimilarities) { if (WordSimilarity.isSimilar(s, possible)) { if (!(this.get(possible).getReference() == this.get(s).getReference())) { // this.get(possible).setReference(this.get(s)); this.get(possible).union(this.get(s)); // System.out.println(s + " " + possible); } } } } } }
9
public int mac() { long ac = -1; // Do we have it annotated as AF or MAF? if (hasField("MAC")) return (int) getInfoInt("MAC"); else if (hasField("AC")) ac = getInfoInt("AC"); else { // No annotations, we have to calculate ac = 0; for (VcfGenotype gen : this) { int genCode = gen.getGenotypeCode(); if (genCode > 0) ac += genCode; } } // How many samples (alleles) do we have? int numSamples = 0; List<String> sampleNames = vcfFileIterator.getVcfHeader().getSampleNames(); if (sampleNames != null) numSamples = sampleNames.size(); else numSamples = getVcfGenotypes().size(); // Always use the Minor Allele Count if ((numSamples > 1) && (ac > numSamples)) ac = 2 * numSamples - ac; return (int) ac; }
7
public double[] sweepPseudoRehearsalSerialLearning(double[][] baseinputs, double[][] baseoutputs, double[][] serialinputs, double[][] serialoutputs, double maxerror, int popSize, int bufferSize, boolean reals, double minrange, double maxrange) { double[] outputs = new double[serialinputs.length + 1];// new double[2];/////////////////// double error = maxerror + 1; // train base population int cutoff = 0; while (maxerror < error && cutoff++ < quitCounter) { for (int i = 0; i < baseinputs.length; i++) { Pattern trial = new Pattern(baseinputs[i], baseoutputs[i]); pass(trial); updateAllWeights(trial); } error = populationError(outputs(baseinputs), baseoutputs); } outputs[0] = error; /////////////////// if (cutoff>=quitCounter) { /*System.err.println("counter exceeded PS");*/ } else { //System.out.println("Learned within " + cutoff + " epochs."); } //outputs[0] = cutoff;/////////////////// double[][] pseudoinputs = new double[popSize][baseinputs[0].length]; double[][] pseudooutputs = new double[popSize][baseoutputs[0].length]; makepseudopop(pseudoinputs, pseudooutputs, reals, minrange, maxrange); for (int i = 0; i < serialinputs.length; i++) { double[][] rehearseinputs = new double[bufferSize + 1][serialinputs[i].length]; double[][] rehearseoutputs = new double[bufferSize + 1][serialoutputs[i].length]; rehearseinputs[rehearseinputs.length-1] = serialinputs[i]; rehearseoutputs[rehearseoutputs.length-1] = serialoutputs[i]; error = maxerror + 1; cutoff = 0; while (maxerror < error && cutoff++ < quitCounter) { selectpop(rehearseinputs, rehearseoutputs, rehearseinputs.length-1, pseudoinputs, pseudooutputs); for (int j = 0; j < rehearseinputs.length; j++) { Pattern trial = new Pattern(rehearseinputs[j], rehearseoutputs[j]); pass(trial); updateAllWeights(trial); } error = patternError(getCurrentOutput(), rehearseoutputs[rehearseoutputs.length-1]); //CHANGED!!! CHANGED!!!! } double poperror = populationError(outputs(baseinputs), baseoutputs); outputs[i+1] = poperror; /////////////////// } if (cutoff>=quitCounter) { /*System.err.println("counter exceeded quitCounter PS");*/ } else { //System.out.println("Learned within " + cutoff + " epochs."); } //outputs[1] = cutoff;/////////////////// return outputs; }
9
public void setTimeout(int millis) { if (socket != null) try { socket.setSoTimeout(millis); } catch (IOException exc) { exc.printStackTrace(); } timeout = millis; }
2
public String getThumbnailImageURI() { String tumbImage = ""; if(getImagesList() != null && getImagesList().get(0) !=null ){ tumbImage = getImagesList().get(0).getImgURL(); } return tumbImage ; }
2
@Override public int getBorderCount() { int bcnt = 0; if (hasTopBorder()) bcnt++; if (hasBottomBorder()) bcnt++; if (hasLeftBorder()) bcnt++; if (hasRightBorder()) bcnt++; return bcnt; }
4
private void initialize(Header header) throws DecoderException { // REVIEW: allow customizable scale factor float scalefactor = 32700.0f; int mode = header.mode(); int layer = header.layer(); int channels = mode==Header.SINGLE_CHANNEL ? 1 : 2; // set up output buffer if not set up by client. if (output==null) output = new SampleBuffer(header.frequency(), channels); float[] factors = equalizer.getBandFactors(); filter1 = new SynthesisFilter(0, scalefactor, factors); // REVIEW: allow mono output for stereo if (channels==2) filter2 = new SynthesisFilter(1, scalefactor, factors); outputChannels = channels; outputFrequency = header.frequency(); initialized = true; }
3
private void SqueezeWrap() { double total = 0; for (int i = 1; i < HistogramWidth; i++) total += bins[i]; int a = 1; int b = HistogramWidth; int n = 0; while (true){ n++; a++; int subtotal_a = 0; for (int i = a; i < b; i++) subtotal_a += bins[i]; a--; b--; int subtotal_b = 0; for (int i = a; i < b; i++) try { subtotal_b += bins[i]; } catch (Exception e){} b++; if (subtotal_a / total > subtotal_b / total){ a++; if (subtotal_a / total < SqueezeWrapPercent) break; } else { //less than or equals (benefit of the doubt we should shrink the higher values) b--; if (subtotal_b / total < SqueezeWrapPercent) break; } if (n > MAX_ITERATIONS){ break; } } imagelist.setIntensityA(wave_name, a); imagelist.setIntensityB(wave_name, b); }
9
@FXML protected void login(ActionEvent event) { loginButton.setDisable(true); progressIndicator.setVisible(true); progressIndicator.setProgress(ProgressIndicator.INDETERMINATE_PROGRESS); LoginService loginService = new LoginService(); loginService.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent t) { if (t.getSource().getValue().equals(Boolean.TRUE)) { Stage stage = new Stage(); stage.setTitle("Music Vim"); Pane myPane = null; FXMLLoader myLoader = new FXMLLoader(getClass().getResource("/Views/MusicVim.fxml")); try { myPane = (Pane)myLoader.load(); } catch (IOException e) { e.printStackTrace(); } MusicVimController musicVimController = (MusicVimController)myLoader.getController(); Scene scene = new Scene(myPane); stage.setScene(scene); prevStage.close(); musicVimController.setStage(stage); stage.show(); } else { loginButton.setDisable(false); } } }); loginService.start(); System.out.println("login service started"); }
2
public RealDistribution openDemand(int t, int k) throws ConvolutionNotDefinedException{ //check if k is lower or equal than t-l_max, then all orders will be open if (k <= t-getMaxOrderLeadTime()) return totalDemand(); //check if k is bigger than t, then all orders will be realised if (k > t) return new RealSinglePointDistribution(0.0); //in all other cases, get the corresponding sub array and fold it int numberOfOpenOrders = t-k+1; RealDistribution[] orderDistributions = getOrderDistributions(); RealDistribution[] ordersToConvolute = new RealDistribution[numberOfOpenOrders]; for (int i = 0; i < numberOfOpenOrders; i++){ ordersToConvolute[i] = orderDistributions[i]; } return Convoluter.convolute(ordersToConvolute); }
3
public CMemLruCache(int maxSize) { super(maxSize); }
0
private static void playAgainstSelfOnServer(int gameId) { PlayChess whiteTeam = new PlayChess(Board.white, gameId, 1, "32c68cae"); PlayChess blackTeam = new PlayChess(Board.black, gameId, 2, "1a77594c"); while (true) { System.out.println("POLLING AND MOVING FOR WHITE"); Response r = whiteTeam.poll(); System.out.println(r); if (whiteTeam.board.gameIsOver()) { break; } if (r.ready) { if (r.lastmove != null && r.lastmove.length() > 0) { MoveHandler.handleMove(whiteTeam.board, r); } Node nextNode = MiniMax.performMiniMax(whiteTeam.board, whiteTeam.color, PlayChess.plyLookhead, r); whiteTeam.move(MoveHandler.convertMoveToServerNotation(whiteTeam.board, nextNode.m)); whiteTeam.board.handleMove(nextNode.m); } System.out.println("POLLING AND MOVING FOR BLACK"); r = blackTeam.poll(); System.out.println(r); if (blackTeam.board.gameIsOver()) { break; } if (r.ready) { if (r.lastmove != null && r.lastmove.length() > 0) { MoveHandler.handleMove(blackTeam.board, r); } Node nextNode = MiniMax.performMiniMax(blackTeam.board, blackTeam.color, PlayChess.plyLookhead, r); System.out.println(nextNode); blackTeam.move(MoveHandler.convertMoveToServerNotation(blackTeam.board, nextNode.m)); blackTeam.board.handleMove(nextNode.m); } } }
9
public void cargarPedHas() { String sql = "SELECT t1.productos_idproductos, t2.nombre_producto, t2.proveedor, t1.cantidad_pedido,t2.precio * t1.cantidad_pedido " + "FROM productos_has_pedidos AS t1, productos AS t2 " + "WHERE t1.Productos_idProductos = t2.idProductos " + "AND t1.Pedidos_idPedidos = ? " + "ORDER BY Productos_idProductos"; try { Connection connPedHas = Conexion.GetConnection(); String[] columnspedHas = {"id Producto", "Producto", "Proveedor", "Cantidad", "Precio"}; DefaultTableModel tmPedHas = new DefaultTableModel(null, columnspedHas) { @Override public boolean isCellEditable(int rowIndex, int colIndex) { if (colIndex == 3) { return true; } return false; } }; PreparedStatement ps = connPedHas.prepareStatement(sql); String idped = (String) jTablePedidos.getValueAt(jTablePedidos.getSelectedRow(), 0); ps.setString(1, idped); this.PedidosHas = ps.executeQuery(); while (PedidosHas.next()) { String[] row = {PedidosHas.getString(1), PedidosHas.getString(2), PedidosHas.getString(3), PedidosHas.getString(4), PedidosHas.getString(5)}; tmPedHas.addRow(row); } jTablePedHas.setModel(tmPedHas); } catch (SQLException e) { System.out.println(e.getMessage()); } }
3
public boolean hasBusyDoc(){ for(boolean b : this.docStates_IsBusy) if(b) return true; return false; }
2
public void checkOperation (String operation, org.omg.CORBA.Any[] args) throws RTT.corba.CNoSuchNameException, RTT.corba.CWrongNumbArgException, RTT.corba.CWrongTypeArgException { org.omg.CORBA.portable.InputStream $in = null; try { org.omg.CORBA.portable.OutputStream $out = _request ("checkOperation", true); $out.write_string (operation); RTT.corba.CAnyArgumentsHelper.write ($out, args); $in = _invoke ($out); return; } catch (org.omg.CORBA.portable.ApplicationException $ex) { $in = $ex.getInputStream (); String _id = $ex.getId (); if (_id.equals ("IDL:RTT/corba/CNoSuchNameException:1.0")) throw RTT.corba.CNoSuchNameExceptionHelper.read ($in); else if (_id.equals ("IDL:RTT/corba/CWrongNumbArgException:1.0")) throw RTT.corba.CWrongNumbArgExceptionHelper.read ($in); else if (_id.equals ("IDL:RTT/corba/CWrongTypeArgException:1.0")) throw RTT.corba.CWrongTypeArgExceptionHelper.read ($in); else throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException $rm) { checkOperation (operation, args ); } finally { _releaseReply ($in); } } // checkOperation
5
public static void setNativesLocation() { String libraryPath; if (new File("lib").exists()) { if(System.getProperty("os.name").toLowerCase().contains("linux")) { libraryPath = new File("lib").getAbsolutePath() + File.separator + "linux"; } else if(System.getProperty("os.name").toLowerCase().contains("mac")){ libraryPath = new File("lib").getAbsolutePath() + File.separator + "osx"; } else { libraryPath = new File("lib").getAbsolutePath() + File.separator + System.getProperty("sun.desktop"); } } else { log("Running inside IDE"); Game.setRunningInIdea(); if(System.getProperty("os.name").toLowerCase().contains("linux")){ libraryPath = new File("target").getAbsolutePath() + File.separator + "build" + File.separator + "lib" + File.separator + "linux"; } else if(System.getProperty("os.name").toLowerCase().contains("mac")){ libraryPath = new File("target").getAbsolutePath() + File.separator + "build" + File.separator + "lib" + File.separator + "osx"; } else { libraryPath = new File("target").getAbsolutePath() + File.separator + "build" + File.separator + "lib" + File.separator + System.getProperty("sun.desktop"); } } try { addLibraryPath(libraryPath); } catch (Exception e) { e.printStackTrace(); } }
6
public String toString() { StringBuffer sbuf = new StringBuffer(); sbuf.append("(<"); sbuf.append(getTag()); sbuf.append('>'); ASTList list = this; while (list != null) { sbuf.append(' '); ASTree a = list.left; sbuf.append(a == null ? "<null>" : a.toString()); list = list.right; } sbuf.append(')'); return sbuf.toString(); }
2
public void run() { int numChanged = 0; boolean examineAll = true; while (numChanged > 0 || examineAll) { numChanged = 0; if (examineAll) { // loop I over all training examples for (int i = 0; i < model.getLength(); i++) { numChanged += examineExample(i); } } else { // loop I over examples where alpha is not 0 & not C // if (model.alpha[i] > 0 && model.alpha[i] < 0) { for (int i = 0; i < model.getLength(); i++) { if (alpha[i] != 0 && alpha[i] != C) { numChanged += examineExample(i); } } } if (examineAll) examineAll = false; else if (numChanged == 0) examineAll = true; } }
9
private void reconcileStates(Connection conn) { PointList points1 = (PointList) Animation.getInitialState(this, conn); PointList points2 = (PointList) Animation.getFinalState(this, conn); if (points1 != null && points1.size() != points2.size()) { Point p = new Point(), q = new Point(); int size1 = points1.size() - 1; int size2 = points2.size() - 1; int i1 = size1; int i2 = size2; double current1 = 1.0; double current2 = 1.0; double prev1 = 1.0; double prev2 = 1.0; while (i1 > 0 || i2 > 0) { if (Math.abs(current1 - current2) < 0.1 && i1 > 0 && i2 > 0) { // Both points are the same, use them and go on; prev1 = current1; prev2 = current2; i1--; i2--; current1 = (double) i1 / size1; current2 = (double) i2 / size2; } else if (current1 < current2) { // 2 needs to catch up // current1 < current2 < prev1 points1.getPoint(p, i1); points1.getPoint(q, i1 + 1); p.x = (int) (((q.x * (current2 - current1) + p.x * (prev1 - current2)) / (prev1 - current1))); p.y = (int) (((q.y * (current2 - current1) + p.y * (prev1 - current2)) / (prev1 - current1))); points1.insertPoint(p, i1 + 1); prev1 = prev2 = current2; i2--; current2 = (double) i2 / size2; } else { // 1 needs to catch up // current2< current1 < prev2 points2.getPoint(p, i2); points2.getPoint(q, i2 + 1); p.x = (int) (((q.x * (current1 - current2) + p.x * (prev2 - current1)) / (prev2 - current2))); p.y = (int) (((q.y * (current1 - current2) + p.y * (prev2 - current1)) / (prev2 - current2))); points2.insertPoint(p, i2 + 1); prev2 = prev1 = current1; i1--; current1 = (double) i1 / size1; } } } }
8
public static void main(String[] args) { System.out.println(true); // true System.out.println(false); // false System.out.println(1 < 2); // true System.out.println('A' == 'B'); // false }
0
public boolean isEmpty() { boolean retVal = false; if (backPtr == -1) { retVal = true; } return retVal; }
1
@Override public void update() { super.update(); if(this.moveTime == 0) { this.x = this.nx; this.y = this.ny; if((this.world.player.x-this.x)*(this.world.player.x-this.x)+(this.world.player.y-this.y)*(this.world.player.y-this.y) > 3*3) { if(this.looking) { this.world.player.hasChild = false; this.looking = false; } this.move(); } else if(!this.world.player.hasChild) { this.world.player.hasChild = true; this.looking = true; } else if(!this.looking) { this.move(); } } }
5
private static TwitterResponseWrapper sendRequestAppAuthPost(String baseUrl, Hashtable<String, String> httpParams, String authHeader) { HttpURLConnection conn = null; InputStream is = null; TwitterResponseWrapper response = new TwitterResponseWrapper(); try { String stringifiedParams = httpParams.size() > 0 ? GenericUtils.httpStringifyHashtable(httpParams) : ""; URL u = new URL(baseUrl); conn = (HttpURLConnection) u.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Host", HOST); conn.setRequestProperty("User-Agent", USER_AGENT); conn.setRequestProperty("Authorization", authHeader); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";" + CHARSET); conn.setRequestProperty("Content-Length", "" + stringifiedParams.getBytes("UTF-8").length); conn.setRequestProperty("Accept-Encoding", "gzip"); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(stringifiedParams); wr.flush(); wr.close(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); is = conn.getInputStream(); byte[] buffer = new byte[2048]; int bytes_read; while((bytes_read = is.read(buffer)) != -1) { baos.write(buffer, 0, bytes_read); } baos.close(); response.setResponseCode(200); response.setSuccess(true); response.setResponse(GenericUtils.decompressGZIPData(baos.toByteArray())); return response; } catch(IOException ioExp) { response.setSuccess(false); if(conn != null) { response.setResponse(getResponseFromGZIPErrorStream(conn.getErrorStream())); try { response.setResponseCode(conn.getResponseCode()); response.setResponseMessage(conn.getResponseMessage()); } catch(IOException exp) {} } return response; } catch(Exception exp) { response.setResponseCode(0); response.setResponseMessage(exp.getMessage()); return response; } finally { if(is != null) { try{ is.close(); }catch(Exception exp){} } } }
8
public void rainHard() throws RainedOut { }
0
public static void encode(Object object, ByteBuffer enc) { if (object == null) { enc.put((byte) 0x00); return; } if (object.getClass().isArray()) { enc.put((byte) 0x03); enc.putInt(Array.getLength(object)); for (int i = 0; i < Array.getLength(object); i++) { encode(Array.get(object, i), enc); } return; } switch (object.getClass().getName()) { case "java.lang.Integer": enc.put((byte) 0x01); enc.putInt((Integer) object); break; case "java.lang.Boolean": enc.put((byte) 0x02); enc.put((byte) (((Boolean) object).booleanValue() ? 1 : 0)); break; case "java.lang.String": enc.put((byte) 0x04); String local = (String) object; enc.putInt(local.length()); enc.put(local.getBytes()); break; default: enc.put((byte) 0x00); Logger.severe("Unhandlable object type: " + object.getClass()); break; } }
7
public void mouseClicked(MouseEvent e) { x = e.getX(); y = e.getY(); boolean interactableClicked = false; for(Interactable i: ScreenManager.getInstance().getCurrentScreen().getInteractables()) { if(i.contains(x, y)) { i.onClick(); ScreenManager.getInstance().getCurrentScreen().onClicked(i); interactableClicked = true; } } for(SubScreen ss: ScreenManager.getInstance().getCurrentScreen().getVisibleSubScreens()) { for(Interactable i: ss.getIneteractables()) { if(i.contains(x - ss.getX(), y - ss.getY())) { i.onClick(); ss.onClicked(i); interactableClicked = true; } } } if(!interactableClicked) { ScreenManager.getInstance().getCurrentScreen().setSelectedInteractable(null); } }
6
private static boolean updateJoinCardinality(Join j, Map<String, Integer> tableAliasToId, Map<String, TableStats> tableStats) { DbIterator[] children = j.getChildren(); DbIterator child1 = children[0]; DbIterator child2 = children[1]; int child1Card = 1; int child2Card = 1; String[] tmp1 = j.getJoinField1Name().split("[.]"); String tableAlias1 = tmp1[0]; String pureFieldName1 = tmp1[1]; String[] tmp2 = j.getJoinField2Name().split("[.]"); String tableAlias2 = tmp2[0]; String pureFieldName2 = tmp2[1]; boolean child1HasJoinPK = Database.getCatalog() .getPrimaryKey(tableAliasToId.get(tableAlias1)) .equals(pureFieldName1); boolean child2HasJoinPK = Database.getCatalog() .getPrimaryKey(tableAliasToId.get(tableAlias2)) .equals(pureFieldName2); if (child1 instanceof Operator) { Operator child1O = (Operator) child1; boolean pk = updateOperatorCardinality(child1O, tableAliasToId, tableStats); child1HasJoinPK = pk || child1HasJoinPK; child1Card = child1O.getEstimatedCardinality(); child1Card = child1Card > 0 ? child1Card : 1; } else if (child1 instanceof SeqScan) { child1Card = (int) (tableStats.get(((SeqScan) child1) .getTableName()).estimateTableCardinality(1.0)); } if (child2 instanceof Operator) { Operator child2O = (Operator) child2; boolean pk = updateOperatorCardinality(child2O, tableAliasToId, tableStats); child2HasJoinPK = pk || child2HasJoinPK; child2Card = child2O.getEstimatedCardinality(); child2Card = child2Card > 0 ? child2Card : 1; } else if (child2 instanceof SeqScan) { child2Card = (int) (tableStats.get(((SeqScan) child2) .getTableName()).estimateTableCardinality(1.0)); } j.setEstimatedCardinality(JoinOptimizer.estimateTableJoinCardinality(j .getJoinPredicate().getOperator(), tableAlias1, tableAlias2, pureFieldName1, pureFieldName2, child1Card, child2Card, child1HasJoinPK, child2HasJoinPK, tableStats, tableAliasToId)); return child1HasJoinPK || child2HasJoinPK; }
9
static public void action(final Player p, final Main Main) { String act = Main.getConfig().getString("action"); if (act.equals("warn")) { p.sendMessage("" + ChatColor.LIGHT_PURPLE + Lang.PREFIX + ChatColor.YELLOW + " " + Main.getConfig().getString("warn-msg")); Main.broadcastAbuse(p); } else if (act.equals("kick")) { Bukkit.getScheduler().runTask(Main, new Runnable() { public void run() { p.kickPlayer("" + ChatColor.GOLD + Lang.KICK_MSG + ChatColor.RESET + " " + Main.getConfig().getString("kick-msg")); } }); Main.broadcastAbuse(p); } else if (act.equals("ban")) { Bukkit.getScheduler().runTask(Main, new Runnable() { public void run() { p.kickPlayer("" + ChatColor.GOLD + Lang.BAN_MSG + ChatColor.RESET + " " + Main.getConfig().getString("ban-msg")); } }); p.setBanned(true); Main.broadcastAbuse(p); } else if (act.equals("custom")) { int listlength = Main.getConfig().getList("custom-commands").toArray().length; Object[] list = Main.getConfig().getList("custom-commands").toArray(); for (int i = 0; i < listlength; i++) { String curlist = list[i].toString().replaceFirst("/", ""); Bukkit.dispatchCommand(Bukkit.getConsoleSender(), curlist); } Main.broadcastAbuse(p); } }
5
public void render(Graphics g) { if (World.gameMode == World.GameMode.CLASSIC) { g.setFont(font); g.setColor(Color.BLACK); g.drawString("SCORE: " + World.SCORE, 15, 45); g.drawString("HIGHSCORE: " + World.HIGHSCORE, 15, 65); } else if (World.gameMode != World.GameMode.CLASSIC) { for (int i = 0; i < World.totalSnakes; i++) { g.setFont(font); g.setColor(World.colors[i]); if (World.snakes.get(i).lives > 0) { g.drawString( "" + World.snakes.get(i).lives, (Window.width / 2) + (40 * ((int) Math.ceil((double) i / 2)) * ((int) Math .pow(-1, i))), 50); } if (World.snakes.get(i).lives == 0 && World.snakes.get(i).dead) { g.drawString( "Dead", (Window.width / 2) + (40 * ((int) Math.ceil((double) i / 2)) * ((int) Math .pow(-1, i))) - 20, 50); } if (World.snakes.get(i).dead && World.snakes.get(i).lives > 0) { g.drawString( "" + (5 - (World.snakes.get(i).deathTimer / 10)), (Window.width / 2) + (40 * ((int) Math.ceil((double) i / 2)) * ((int) Math .pow(-1, i))), 70); } } } }
8
private void paivitaMinX(){ double minX = Double.POSITIVE_INFINITY; for (KentallaOlija osa : osat){ if (osa.getMinX() < minX){ minX = osa.getMinX(); } } if (getSuojakilpi()){ if (getX()-getSuojakilvenHalkaisija()/2 < minX){ minX = getX()-getSuojakilvenHalkaisija()/2; } } setMinX(minX); }
4
private void analyzeTextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_analyzeTextButtonActionPerformed // TODO add your handling code here: JFileChooser fileChooser = new JFileChooser(); javax.swing.filechooser.FileFilter textFilter = new javax.swing.filechooser.FileFilter() { @Override public String getDescription() { return null; } @Override public boolean accept(File f) { if (f.getName().toLowerCase().endsWith("txt") || f.isDirectory()) { return true; } return false; } }; fileChooser.setFileFilter(textFilter); int actionSelected = fileChooser.showOpenDialog(logTextArea); if (actionSelected == JFileChooser.APPROVE_OPTION) { if (useHashMapRadioButton.isSelected()) { textAnalyzer = new TextAnalyzer("hashmap"); } else { textAnalyzer = new TextAnalyzer("treemap"); } long startTime = System.nanoTime(); long endTime = 0; try { textAnalyzer.analyzeText(fileChooser.getSelectedFile().getPath()); endTime = System.nanoTime(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } logTextArea.append("File name: " + fileChooser.getSelectedFile().getName() + "\n"); logTextArea.append("Number of unique words: " + textAnalyzer.getUniqueWordCount() + "\n"); logTextArea.append("Total number of words: " + textAnalyzer.getWordCount() + "\n"); logTextArea.append("Time taken to analyze the file: " + TimeUnit.NANOSECONDS.toMillis(endTime - startTime) + " milliseconds\n"); } }//GEN-LAST:event_analyzeTextButtonActionPerformed
6
@Override public void setKey(String key) throws Exception { byte[] keyB = key.getBytes(); if (keyB == null) { throw new RuntimeException("Invalid key: Key was null"); } if (keyB.length < 16) { throw new RuntimeException("Invalid key: Length was less than 16 bytes"); } for (int off = 0, i = 0; i < 4; i++) { S[i] = ((keyB[off++] & 0xff)) | ((keyB[off++] & 0xff) << 8) | ((keyB[off++] & 0xff) << 16) | ((keyB[off++] & 0xff) << 24); } }
3
@Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(FILE_EXIT)) { System.exit(0); } else if(e.getActionCommand().equals(VIEW_PLAYERS)){ AllPlayersGui playerGui = new AllPlayersGui("Players", "Players", desktop); playerGui.setVisible(true); desktop.add(playerGui); } else if( e.getActionCommand().equals(ADD_PLAYER)){ try { AddPlayerGui addPlayerGui = new AddPlayerGui("Add New Player", "New Player", "Add"); addPlayerGui.setVisible(true); desktop.add(addPlayerGui); } catch (Exception e1) { e1.printStackTrace(); } } else if(e.getActionCommand().equals(VIEW_TEAMS)){ AllTeamsGui allTeamsGui = new AllTeamsGui("Teams", "All Teams", desktop); allTeamsGui.setVisible(true); desktop.add(allTeamsGui); } else if(e.getActionCommand().equals(VIEW_PEOPLE)){ AllPeopleGui allPeopleGui = new AllPeopleGui("People", "People", desktop); allPeopleGui.setVisible(true); desktop.add(allPeopleGui); } else if(e.getActionCommand().equals(ADD_PERSON)){ } else if(e.getActionCommand().equals(ADD_PERSON_PLAYER)){ try{ AddPersonPlayerGui app = new AddPersonPlayerGui("Add Parent and Player", "Player and Parent", desktop); app.setVisible(true); desktop.add(app); } catch (Exception e1) { e1.printStackTrace(); } } }
9
public CaseVue(int idCase) { super(); switch (idCase) { case 0: setBackground(Color.white); break; case 1: setBackground(Color.cyan); break; case 2: setBackground(Color.yellow); break; case 3: setBackground(Color.magenta); break; case 4: setBackground(Color.orange); break; case 5: setBackground(Color.blue); break; case 6: setBackground(Color.red); break; case 7: setBackground(Color.green); break; default: setBackground(Color.white); ; } }
8
public void onAnalog(String name, float value, float tpf) { if(InputBitArray.AXIS_X_POS.equalsIgnoreCase(name)) { player.yaw(value*player.getMouseSensitivity()*tpf); return; } if(InputBitArray.AXIS_X_NEG.equalsIgnoreCase(name)) { player.yaw(-value*player.getMouseSensitivity()*tpf); return; } if(InputBitArray.AXIS_Y_POS.equalsIgnoreCase(name)) { player.pitch(value*player.getMouseSensitivity()*tpf); return; } if(InputBitArray.AXIS_Y_NEG.equalsIgnoreCase(name)) { player.pitch(-value*player.getMouseSensitivity()*tpf); return; } }
4
public ClassNode getClass(String name) { if (name == null) { return null; } ClassNode c = getClasses().get(name); if (c == null) { c = cachedExternalClasses.get(new ID(name)); if (c == null) { c = new ClassNode(); ClassReader cr; try { cr = new ClassReader(name); } catch (IOException e) { return null; } cr.accept(c, 0); cachedExternalClasses.put(new ID(name), c); } } return c; }
4
public static void main(String[] args) { if (args.length != 9) { System.out.println("{͂Ă"); System.exit(1); } else { File datFile = new File(ConstansBook.DAT_URL); File oldFile = new File(ConstansBook.OLD_DAT_URL); // oldt@ĈȂĂB if (oldFile.exists()) { OldBookDeleter del = new OldBookDeleter(); del.delete(); }if (datFile.exists()) { // Ńt@Cǂݍ BookReader bookRead = new BookReader(); try{ //OABookReaderOBŎ󂯎B bookRead.reader(ConstansBook.DAT_URL); }catch(IOException e){ System.out.println("t@C‚܂"); } // R}h1ԖڂuMv̂Ƃ if (args[0].equals(ConstansBook.MAGAZINE)) { //悭悭lbeanӖȂEEEPƂ͐悤ɂ܂ BookBean bb = new BookBean(); bb.setArgument(args[0]); bb.setmName(args[1]); bb.setmCompany(args[2]); bb.setmPrice(args[3]); // t̏BCłEEE String year = args[4]; String month = args[5]; String day = args[6]; StringBuilder sb = new StringBuilder(); sb.append(year); sb.append(ConstansBook.SLASH); sb.append(month); sb.append(ConstansBook.SLASH); sb.append(day); String perfectDay = new String(sb); bb.setmDay(perfectDay); bb.setmCode(args[7]); bb.setmNumber(args[8]); StringBuilder plusColon = new StringBuilder(); String name = bb.getmName(); String company = bb.getmCompany(); String price = bb.getmPrice(); String perfectday = bb.getmDay(); String code = bb.getmCode(); String number = bb.getmNumber(); // u:vƁu vljĂB̏ȂƂEEE plusColon.append(ConstansBook.NAME); plusColon.append(ConstansBook.COLON); plusColon.append(name); plusColon.append(ConstansBook.SPACE); plusColon.append(ConstansBook.COMPANY); plusColon.append(ConstansBook.COLON); plusColon.append(company); plusColon.append(ConstansBook.SPACE); plusColon.append(ConstansBook.PRICE); plusColon.append(ConstansBook.COLON); plusColon.append(price); plusColon.append(ConstansBook.SPACE); plusColon.append(ConstansBook.PUBLISH_DAY); plusColon.append(ConstansBook.COLON); plusColon.append(perfectday); plusColon.append(ConstansBook.SPACE); plusColon.append(ConstansBook.MAGAZINE_CODE); plusColon.append(ConstansBook.COLON); plusColon.append(code); plusColon.append(ConstansBook.SPACE); plusColon.append(ConstansBook.MAGAZINE_NUMBER); plusColon.append(ConstansBook.COLON); plusColon.append(number); plusColon.append(ConstansBook.SPACE); String inputBookData = new String(plusColon); bb.setCommandLineMagazine(inputBookData); BookInput input = new BookInput(); try{ input.input(bb.getCommandLineMagazine()); }catch(IOException e){ System.out.println("t@C‚܂ł"); } // R}h1ԖڂuBv̂Ƃ } else if (args[0].equals(ConstansBook.BOOK)){ BookBean bb = new BookBean(); bb.setArgument(args[0]); bb.setbName(args[1]); bb.setbCompany(args[2]); bb.setbPrice(args[3]); // t̏BCłEEE String year = args[4]; String month = args[5]; String day = args[6]; StringBuilder sb = new StringBuilder(); sb.append(year); sb.append(ConstansBook.SLASH); sb.append(month); sb.append(ConstansBook.SLASH); sb.append(day); String perfectDay = new String(sb); bb.setbDay(perfectDay); bb.setbAuthor(args[7]); bb.setbISBN(args[8]); StringBuilder plusColon = new StringBuilder(); String name = bb.getbName(); String company = bb.getbCompany(); String price = bb.getbPrice(); String perfectday = bb.getbDay(); String author = bb.getbAuthor(); String isbn = bb.getbISBN(); // u:vƁu vljĂB̏ȂƂEEE plusColon.append(ConstansBook.NAME); plusColon.append(ConstansBook.COLON); plusColon.append(name); plusColon.append(ConstansBook.SPACE); plusColon.append(ConstansBook.COMPANY); plusColon.append(ConstansBook.COLON); plusColon.append(company); plusColon.append(ConstansBook.SPACE); plusColon.append(ConstansBook.PRICE); plusColon.append(ConstansBook.COLON); plusColon.append(price); plusColon.append(ConstansBook.SPACE); plusColon.append(ConstansBook.PUBLISH_DAY); plusColon.append(ConstansBook.COLON); plusColon.append(perfectday); plusColon.append(ConstansBook.SPACE); plusColon.append(ConstansBook.BOOK_AUTHOR); plusColon.append(ConstansBook.COLON); plusColon.append(author); plusColon.append(ConstansBook.SPACE); plusColon.append(ConstansBook.BOOK_ISBN); plusColon.append(ConstansBook.COLON); plusColon.append(isbn); plusColon.append(ConstansBook.SPACE); String inputBookData = new String(plusColon); bb.setCommandLineBook(inputBookData); BookInput input = new BookInput(); try{ input.input(bb.getCommandLineBook()); }catch(IOException e){ System.out.println("t@C‚܂ł"); } } } } }
8
public void log(int verbosity, String... args) { if (frame != null) frame.log(verbosity, args); if (( verbosity == 0 ) && !silent ) { String message = new String(); for (int i = 0; i < args.length; i++) { if(i == 0) continue; message += args[i]; } System.out.print(message); System.out.flush(); queue.offer(args); } else if ( verbosity <= this.verbose_level ) queue.offer(args); }
6
private void deleteRoom(JSONObject obj) { RoomInfo roomInfo = roomMap.remove(obj.get("id_room")); if(roomInfo!=null) { for(Team team : roomInfo.getTeams().values()) { for(User user : team.getMembers()) { clientMap.remove(user.getId()); } } } }
3
private static Map<Character, String> toCharacterKey(Map<String, Character> inMap) { Map<Character, String> outMap = new HashMap<Character, String>(); for (Map.Entry<String, Character> entry: inMap.entrySet()) { Character character = entry.getValue(); String name = entry.getKey(); if (outMap.containsKey(character)) { // dupe, prefer the lower case version if (name.toLowerCase().equals(name)) outMap.put(character, name); } else { outMap.put(character, name); } } return outMap; }
3
public void paintComponent(Graphics g) { super.paintComponent(g); if(rectangles != null && process_repaint) { ModelInstance model = ModelInstance.getInstance(); Iterator<Map.Entry<Integer, Point>> it = rectangles.entrySet().iterator(); while(it.hasNext()) { Map.Entry<Integer, Point> entry = it.next(); Point p = entry.getValue(); g.drawRect(p.x - 5, p.y - 5, 200, 30); int id = entry.getKey(); ClassInstance i = model.instanced_classes.get(id); g.drawRect(p.x - 5, p.y + 25, 200, 30*(i.attributes.size()+i.enums.size())); } } if(lines != null) { for(Point[] p : lines.values()) { //getGraphics().drawLine(p[0].x, p[0].y, p[1].x, p[1].y); drawArrow(g, p[0].x, p[0].y, p[1].x, p[1].y); } } }
5
private void fixedPointSimplestCaseNonCyclicFillRaster(int[] pixels, int off, int adjust, int x, int y, int w, int h) { float iSq = 0; // Square distance index final float indexFactor = fastGradientArraySize / radius; //constant part of X and Y coordinates for the entire raster final float constX = (a00 * x) + (a01 * y) + constA; final float constY = (a10 * x) + (a11 * y) + constB; final float deltaX = indexFactor * a00; //incremental change in dX final float deltaY = indexFactor * a10; //incremental change in dY float dX, dY; //the current distance from center final int fixedArraySizeSq = (fastGradientArraySize * fastGradientArraySize); float g, gDelta, gDeltaDelta, temp; //gradient square value int gIndex; // integer number used to index gradient array int iSqInt; // Square distance index int end, j; //indexing variables int indexer = off;//used to index pixels array temp = ((deltaX * deltaX) + (deltaY * deltaY)); gDeltaDelta = ((temp * 2)); if (temp > fixedArraySizeSq) { // This combination of scale and circle radius means // essentially no pixels will be anything but the end // stop color. This also avoids math problems. final int val = gradientOverflow; for (j = 0; j < h; j++) { //for every row //for every column (inner loop begins here) for (end = indexer + w; indexer < end; indexer++) pixels[indexer] = val; indexer += adjust; } return; } // For every point in the raster, calculate the color at that point for (j = 0; j < h; j++) { //for every row //x and y (in user space) of the first pixel of this row dX = indexFactor * ((a01 * j) + constX); dY = indexFactor * ((a11 * j) + constY); // these values below here allow for an incremental calculation // of dX^2 + dY^2 //initialize to be equal to distance squared g = (((dY * dY) + (dX * dX))); gDelta = (deltaY * dY + deltaX * dX) * 2 + temp; //for every column (inner loop begins here) for (end = indexer + w; indexer < end; indexer++) { //determine the distance to the center //since this is a non cyclic fill raster, crop at "1" and 0 if (g >= fixedArraySizeSq) { pixels[indexer] = gradientOverflow; } // This should not happen as gIndex is a square // quantity. Code commented out on purpose, can't underflow. // else if (g < 0) { // gIndex = 0; // } else { iSq = (g * invSqStepFloat); iSqInt = (int) iSq; //chop off fractional part iSq -= iSqInt; gIndex = sqrtLutFixed[iSqInt]; gIndex += (int) (iSq * (sqrtLutFixed[iSqInt + 1] - gIndex)); pixels[indexer] = gradient[gIndex]; } //incremental calculation g += gDelta; gDelta += gDeltaDelta; } indexer += adjust; } }
6
public static int partition(Comparable[] a, int lo, int hi) { Comparable v = a[lo]; int i = lo; int j = hi + 1; while (true) { while (less(a[++i], v)) { if (i == hi) { break; } } while (less(v, a[--j])) { if (j == lo) { break; } } if (i >= j) { break; } exch(a, i, j); } exch(a, lo, j); return j; }
6
public String getExpressionString() { if( ((expression == null) || (expression.size() == 0)) && (getCachedOOXMLExpression() != null) ) { return "=" + getCachedOOXMLExpression(); } if( expression != null ) { return FormulaParser.getExpressionString( expression ); } return "="; }
4
@Override public void execute(CommandExecutor player, String[] args) { if(args.length == 1){ if(BanHandler.isBanned(args[0])) { BanHandler.unban(args[0]); player.sendMessage("You unbanned " + args[0]); }else{ player.sendMessage(args[0] + " is not banned."); } }else{ help(player); } }
2
private void initGrid(){ gridPanel = new JPanel(new GridLayout(4, 4,1,1)); gridPanel.setBackground(Color.WHITE); gridPanel.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 10)); gridPanel.add(new JLabel("Name:")); gridPanel.add(new JLabel(character.getName())); gridPanel.add(new JLabel("Corp:")); gridPanel.add(new JLabel(character.getCorpName())); gridPanel.add(new JLabel("Account paid:")); Account charAcc = MainFrame.dp.getAccountByCharacterID(character.getId()); JLabel accExpires = new JLabel("Unknown account"); if( charAcc != null ){ accExpires.setText(charAcc.getExpires()); } gridPanel.add(accExpires); gridPanel.add(new JLabel("Skills / clone:")); gridPanel.add((lbSP = new JLabel(Utils.formatInt(character.getSkillpoints())+" / "+Utils.formatInt(character.getCloneSkillpoints())))); if( character.getCloneSkillpoints() <= character.getSkillpoints() ){ Msg.warningMsg(character.getName()+" needs clone upgrade!"); } SkillInTraining currSkill = character.getSkillInTraining(); if( currSkill == null ){ character.setTraining(false); } if( character.isTraining() && currSkill != null ){ gridPanel.add(new JLabel("Training:")); lbTaining = new JLabel(currSkill.getType().getName()+" lvl "+currSkill.getSkillLevel()); lbTaining.setForeground(GREEN); gridPanel.add(lbTaining); gridPanel.add(new JLabel("Finishes:")); Date now = Utils.getNowUTC(); Date fin = Utils.getUTC(currSkill.getEndTime()); int s = (int)((fin.getTime()-now.getTime())/1000); gridPanel.add((lbFinishes = new JLabel(Utils.formatTime(s)))); gridPanel.add(new JLabel("Queue:")); if( !character.getTrainingQueue().isEmpty() ){ fin = Utils.getUTC(character.getTrainingQueue().get(character.getTrainingQueue().size()-1).getEndTime()); s = (int)((fin.getTime()-now.getTime())/1000); lbQueue = new JLabel(Utils.formatTime(s)); if(Utils.formatTime(s).startsWith("0")){ lbQueue.setForeground(RED); Msg.infoMsg("Skill queue low: "+character.getName()); }else{ lbQueue.setForeground(GREEN); } gridPanel.add(lbQueue); String tooltip = "<html>"; for(int i=0;i<character.getTrainingQueue().size();i++){ fin = Utils.getUTC(character.getTrainingQueue().get(i).getEndTime()); if(fin.after(now)){ tooltip+=character.getTrainingQueue().get(i).getType().getName()+" "+character.getTrainingQueue().get(i).getSkillLevel()+"<br />"; } } tooltip+="</html>"; lbQueue.setToolTipText(tooltip); }else{ lbQueue = new JLabel("Queue is empty."); gridPanel.add(lbQueue); } }else{ gridPanel.add(new JLabel("Training:")); lbTaining = new JLabel("Inactive"); lbTaining.setForeground(RED); gridPanel.add(lbTaining); gridPanel.add(new JLabel("Finishes:")); gridPanel.add((lbFinishes = new JLabel("-"))); gridPanel.add(new JLabel("Queue:")); lbQueue = new JLabel("-"); gridPanel.add(lbQueue); } gridPanel.add(new JLabel("Balance:")); gridPanel.add(lbISK); add(gridPanel,BorderLayout.CENTER); }
9
public static void load() { scripts.clear(); File file = new File("./scripts/"); try { URLClassLoader loader = new URLClassLoader(new URL[] { file.toURI().toURL() }); for(String s : file.list()) { if(s.contains(".class")) { Class<?> clazz = loader.loadClass(s.replace(".class", "")); if(clazz.getSuperclass() == Script.class) { Script script = (Script) clazz.newInstance(); scripts.put(script.getName(), script); } /*if(clazz instanceof Script.) { Script script = (Script) clazz; scripts.put(script.getName(), script); }*/ } } loader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Bot.getSingleton().getBotMenu().updateScriptMenu(scripts); }
9
protected void processVotingResult(String data) { String[] splits = data.split(" "); Integer nodeId = Integer.parseInt(splits[0]); String operation = splits[1]; String resource = splits[2]; if(operation.compareTo("LOCK") == 0){ if(resources.containsKey(resource)){ ResourceState resState = resources.get(resource); if(resState.lockStatus == LockStatus.Free){ resState.lockStatus = LockStatus.Taken; resState.owner = nodeId; notifyLockClient(nodeId, Status.SUCCESS); } else { resState.waitList.add(nodeId); } } else { ResourceState resState = new ResourceState(resource); resState.lockStatus = LockStatus.Taken; resState.owner = nodeId; resources.put(resource, resState); notifyLockClient(nodeId, Status.SUCCESS); } } else { // UNLOCK // unlock does nothing if the releasing node did not hold the lock if(resources.containsKey(resource)){ ResourceState resState = resources.get(resource); if(resState.lockStatus == LockStatus.Taken && resState.owner == nodeId){ if(resState.waitList.size()>0){ // lock transitions ownership resState.owner = resState.waitList.remove(0); // if this node is the new owner tell the client that // it has the lock now notifyLockClient(resState.owner, Status.SUCCESS); // tell the releasing node that it succeeded notifyLockClient(nodeId, Status.SUCCESS); } else { resState.lockStatus = LockStatus.Free; resState.owner = -1; notifyLockClient(nodeId, Status.SUCCESS); } } else { notifyLockClient(nodeId, Status.LockNotHeld); } } } }
7
public void run(){ BufferedImage img = new BufferedImage(f.getContentPane().getWidth(),f.getContentPane().getHeight(),BufferedImage.TYPE_INT_RGB); Graphics g = img.getGraphics(); f.getContentPane().printAll(g); try { FTPConfig config = FTPConfig.getConfig(); ImageIO.write(img,"png", new File("items.png")); FTPClient ftp = new FTPClient(); ftp.connect(config.getServer()); System.out.println(config.getServer()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { System.out.println(reply + " err"); ftp.disconnect(); } //TODO: check those booleans boolean login = ftp.login(config.getUserName(), config.getPassword()); ftp.setFileType(FTP.BINARY_FILE_TYPE); InputStream input = new FileInputStream(new File("items.png")); boolean stored = ftp.storeFile(config.getDirectory() + "items.png", input); ftp.logout(); ftp.disconnect(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
2
public int getSize() { /* * maxStack: 2 maxLocals: 2 code: 4 + codeLength exc count: 2 * exceptions: n * 8 attributes: lvt_name: 2 lvt_length: 4 lvt_count: 2 * lvt_entries: n * 10 attributes: lnt_name: 2 lnt_length: 4 lnt_count: * 2 lnt_entries: n * 4 */ int size = 0; if (lvt != null) size += 8 + lvt.length * 10; if (lnt != null) size += 8 + lnt.length * 4; return 10 + instructions.getCodeLength() + exceptionHandlers.length * 8 + getAttributeSize() + size; }
2
public void layout() { if (table == null || table.isDisposed()) return; if (item == null || item.isDisposed()) return; int columnCount = table.getColumnCount(); if (columnCount == 0 && column != 0) return; if (columnCount > 0 && (column < 0 || column >= columnCount)) return; super.layout(); }
9
public void draw(Game game, Graphics2D g2d) { // Gets Actual screen dimensions. Dimension res = game.getSize(); // Fill it black. g2d.setBackground(COLORS[0]); g2d.setColor(COLORS[0]); g2d.fillRect(0,0,res.width,res.height); // Virtual Screen dimensions. (This will always be 16:9 ratio) int screen[] = new int[2]; screen[0] = res.width; screen[1] = (screen[0]/16)*9; if(screen[1] > res.height) { screen[1] = res.height; screen[0] = (screen[1]/9)*16; } // Get the size of the padding on the edge of the screen after 16:9 ratio has been achieved. // Used for letterboxing. int margin[] = new int[2]; margin[0] = (res.width-screen[0])/2; margin[1] = (res.height-screen[1])/2; // Draw screen. // g2d.setColor(COLORS[2]); // g2d.fillRect(margin[0],margin[1],screen[0],screen[1]); // Translate to the screen's position g2d.translate(margin[0],margin[1]); if(game.state == 0) { g2d.translate(screen[0]/8,0); drawGrid(game,g2d,screen); g2d.translate(-(screen[0]/8),0); } else if (game.state == 1) { g2d.translate(screen[0]/8,0); drawBullets(g2d,game.level.bullets,screen); drawEnemies(g2d,game.level.enemies,screen); drawGrid(game,g2d,screen); g2d.translate(-(screen[0]/8),0); drawGrid(game,g2d,screen); } else if(game.state == 2) { g2d.translate(screen[0]/8,0); //g2d.setColor(COLORS[3]); //g2d.fillRect(0,0,screen[1],screen[1]); //g2d.setColor(COLORS[3]); //g2d.drawRect(0,0,screen[1],screen[1]); drawBullets(g2d,game.level.bullets,screen); drawEnemies(g2d,game.level.enemies,screen); drawPowerups(g2d,game.level.powerups,screen); game.player.draw(g2d,screen,this); //gmae.level.draw(g2d,screen,game); drawGrid(game,g2d,screen); g2d.translate(-(screen[0]/8),0); } else if(game.state == 3) { g2d.translate(screen[0]/8,0); g2d.setColor(COLORS[3]); g2d.fillRect(0,0,screen[1],screen[1]); drawCenteredString("Insert Credits here",screen[1],screen[1],g2d); g2d.translate(-(screen[0]/8),0); } // Draw letterbox g2d.translate(-margin[0],-margin[1]); g2d.setColor(COLORS[0]); g2d.fillRect(0,0,margin[0],screen[1]); g2d.fillRect(0,0,screen[0],margin[1]); g2d.translate(res.width,res.height); g2d.fillRect(0,0,-margin[0],-screen[1]); g2d.fillRect(0,0,-screen[0],-margin[1]); // Draw Bullets // Draw Enemies // Draw Player // Draw Overlay }
5
public Stmt Statement() throws ParseException { Stmt s; switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case LOCAL: s = LocalDecl(); break; case IF: s = IfStatement(); break; default: jj_la1[36] = jj_gen; if (jj_2_3(2147483647)) { s = Assignment(); } else { switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case IDENTIFIER: s = CallStmt(); break; case RETURN: s = ReturnStmt(); break; case WRITE: s = WriteStmt(); break; default: jj_la1[37] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } } return s; }
8
public void setLid(Lid lid) { this.lid = lid; }
0
@Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < getFileServerInfo().size(); i++) { sb.append(i + 1).append(". ").append(getFileServerInfo().get(i)).append("\n"); } return sb.length() > 0 ? sb.toString() : "No file servers connected\n"; }
2
@Override public Ticket in(Car car, List<Park> parkList) { int no = -1; int num = -1; for(int i = 0; i < parkList.size(); i ++) { Park park = parkList.get(i); if(park.isFull()) { continue; } if(num < 0) { num = park.getTotalNum() - park.getEmptyNum(); no = i; } if((park.getTotalNum() - park.getEmptyNum()) < num) { num = park.getTotalNum() - park.getEmptyNum(); no = i; } } if(no > -1) { return parkList.get(no).in(car); } throw new ParkException("没有空的停车位!"); }
5
public static void main(String[] args) throws FileNotFoundException { final String USERFILE = "userItineraries.txt"; final String FLIGHTFILE = "allFlights.txt"; boolean done = false; //Initialize USERFILE for first time user try { getPassengers(USERFILE); } catch (FileNotFoundException except) { PrintWriter out = new PrintWriter(USERFILE); out.close(); } try { new Flight(FLIGHTFILE); } catch (FileNotFoundException except) { System.out.println(FLIGHTFILE+" does not exist. Please ensure " +FLIGHTFILE+" is in the proper directory."); System.exit(1); } System.out.println("Welcome to the Flight Planner"); while (!done) { printOptions(); // Print menu of options available to the user char userSelection = menuInput(); // Read in user selection from menu options if (userSelection == 'Q') { done = true; } else { ArrayList<Passenger> passengers = new ArrayList<Passenger>(); passengers = getPassengers(USERFILE); if (userSelection == 'N') { Nmethod(passengers, FLIGHTFILE, USERFILE); } else if (userSelection == 'S') { Smethod(USERFILE); } else if (userSelection == 'U') { Umethod(USERFILE); } else if (userSelection == 'B') { Bmethod(USERFILE,FLIGHTFILE); } System.out.print("\nWhat would you like to do next?\n\n"); } } }
8
@Override public Object parseClass(Class<?> c, Object o, MainView view) { Method methods[] = c.getMethods(); for(int i = 0; i < methods.length; i++){ try{ if(methods[i].isAnnotationPresent(GetDatabase.class)){ if(o == null){ o = c.newInstance(); Log.getLogger().log(Level.INFO, "Initializing plugin with class: " + o.getClass().getSimpleName()); } Log.getLogger().log(Level.INFO, "Setting DB..."); Method panel = c.getMethod(methods[i].getName(), methods[i].getParameterTypes()); if(panel.getReturnType() == void.class){ panel.invoke(o, DatabaseHandler.getInstance()); } else { Log.getLogger().log(Level.SEVERE, "@GetDatabase invalid return type!"); } break; } }catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e){ Log.getLogger().log(Level.SEVERE, "Exception", e); } } return o; }
6
public float [][] calcEnergy(InputStream is, int fStart, int fEnd){ Manager manager = new Manager(is); int cont = 0; int bytes = 0; final int opt = Constants.DEQUANTIZED_DOMAIN; float [][] E = new float [2][fEnd - fStart]; float [][] energy = {{0f, 0f}, {0f, 0f}}; do{ try{ fd = (FrameDataDequantized) manager.decodeFrame(opt); } catch (Exception e){ LOGGER.info("End of file" ); break; } if((cont >= fStart) && (cont < fEnd)){ for(int ch = 0; ch < fd.getChannels(); ch++) for(int gr = 0; gr < fd.getMaxGr(); gr++){ float [] ro = fd.getRo(ch, gr); for(int line = 0; line < Constants.FREQ_LINES; line++) energy[gr][ch] += (float)((ro[line]) * (ro[line])); } E[0][cont - fStart] = energy[0][0] + energy[1][0]; E[1][cont - fStart] = energy[0][1] + energy[1][1]; energy[0][1] = 0f; energy[1][1] = 0f; energy[0][0] = 0f; energy[1][0] = 0f; } if (cont > fEnd) break; cont++; } while (true); return E; }
8
private void t5CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_t5CaretUpdate jScrollPane1.setVisible(false); jScrollPane2.setVisible(true); DefaultTableModel model1 = (DefaultTableModel) jTable2.getModel(); int bookcode = 0; int n = 0; String query; try { bookcode = Integer.parseInt(t5.getText()); } catch (NumberFormatException e) { n = 1; } try { if (!(n == 1)) { query = "SELECT * FROM books where bookcode like '" + bookcode + "%';"; ResultSet rs = MyQueries.excQuery(query); model1.setRowCount(0); while (rs.next()) { int Bookid = rs.getInt("Bookcode"); String Bookname = rs.getString("Bookname"); String author = rs.getString("author"); String genre = rs.getString("genre"); model1.addRow(new Object[]{Bookid, Bookname, author, genre}); } } else { query = "SELECT * FROM books;"; ResultSet rs = MyQueries.excQuery(query); model1.setRowCount(0); while (rs.next()) { int Bookid = rs.getInt("Bookcode"); String Bookname = rs.getString("Bookname"); String author = rs.getString("author"); String genre = rs.getString("genre"); model1.addRow(new Object[]{Bookid, Bookname, author, genre}); } } } catch (Exception e) { logger.error("Error Description:", e); } myClasses.Connections.close(); // Close connection to prevent Database lock }//GEN-LAST:event_t5CaretUpdate
5
@Override public int run(String[] args) throws Exception { if (args.length != 4) { System.err.println("Usage: PageRank <input path> <output path> <iterations> <tolerance>") ; return -1 ; } FileSystem fs = FileSystem.get(getConf()) ; String input = args[1] + File.separator + "previous-pageranks"; String output = args[1] + File.separator + "current-pageranks" ; ToolRunner.run(getConf(), new CheckingData(), new String[] { args[0], output } ) ; ToolRunner.run(getConf(), new CountPages(), new String[] { output, args[1] + File.separator + "count" } ) ; String count = read (fs, args[1] + File.separator + "count") ; ToolRunner.run(getConf(), new InitializePageRanks(), new String[] { output, input, count } ) ; int i = 0 ; while ( i < Integer.parseInt(args[2]) ) { ToolRunner.run(getConf(), new DanglingPages(), new String[] { input, args[1] + File.separator + "dangling" } ) ; String dangling = read (fs, args[1] + File.separator + "dangling") ; ToolRunner.run(getConf(), new UpdatePageRanks(), new String[] { input, output, count, dangling } ) ; swap ( fs, new Path(output), new Path(input) ) ; if ( ( i > CHECK_CONVERGENCE_FREQUENCY) && ( i % CHECK_CONVERGENCE_FREQUENCY == 0 ) ) { ToolRunner.run(getConf(), new CheckConvergence(), new String[] { input, args[1] + File.separator + "convergence" } ) ; double tolerance = Double.parseDouble(read (fs, args[1] + File.separator + "convergence")) ; if ( tolerance <= Double.parseDouble(args[3]) ) { break ; } } if (HTML_TABLE) { ToolRunner.run(getConf(), new SortPageRanks(), new String[] { input, args[1] + File.separator + "sorted-pageranks" } ) ; BufferedReader in = new BufferedReader(new InputStreamReader(fs.open(new Path(args[1] + File.separator + "sorted-pageranks" + File.separator + "part-00000")))) ; PrintWriter out = new PrintWriter(fs.create(new Path(args[1] + File.separator + "sorted-pageranks-" + i + ".dat")).getWrappedStream()) ; for (int j = 0 ; j < HTML_TABLE_ROWS ; j++ ) { StringTokenizer st = new StringTokenizer(in.readLine()) ; out.write(st.nextToken() + "\n") ; } in.close() ; out.close() ; } i++ ; } ToolRunner.run(getConf(), new SortPageRanks(), new String[] { input, args[1] + File.separator + "sorted-pageranks" } ) ; if (HTML_TABLE) { ToolRunner.run(getConf(), new HTMLTable(), new String[] { args[1], Integer.toString(HTML_TABLE_ROWS), Integer.toString(i) } ) ; } return 0; }
8
private void jBAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBAddActionPerformed JDNuevaTarea jdnt = new JDNuevaTarea(this, true); jdnt.setVisible(true); //Si ha pulsado aceptar se añadirá la tarea creada al estado actual if (jdnt.haPulsadoAceptar()) { switch (jCBEstado.getSelectedIndex()) { case 1: this.proyectos.get(index).addProximo(jdnt.getTarea()); break; case 2: this.proyectos.get(index).addHaciendo(jdnt.getTarea()); break; case 3: this.proyectos.get(index).addHecho(jdnt.getTarea()); break; default: this.proyectos.get(index).addEspera(jdnt.getTarea()); break; } } jTabla.updateUI(); }//GEN-LAST:event_jBAddActionPerformed
4
private void jackpot(String msg, String ttl) { if (JOptionPane.showConfirmDialog(this, msg, ttl, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) reset(); else { parent.dispose(); System.exit(0); } }
1
public boolean Update() { //System.out.println("Running Control Update"); //run the sweepers through CParams::iNumTicks amount of cycles. During //this loop each sweepers NN is constantly updated with the appropriate //information from its surroundings. The output from the NN is obtained //and the sweeper is moved. If it encounters a mine its fitness is //updated appropriately, if(m_iTicks % 1000 == 0) { System.out.println("Ticks: " + m_iTicks); } if (m_iTicks++ < CParams.iNumTicks) { for (int i = 0; i < sweeperPositions.size(); i++) { if (!sweeperPositions.get(i).Update(minePositions)) { //error in processing the neural net System.out.println("Wrong amount of NN inputs!"); return false; } int GrabHit = sweeperPositions.get(i).CheckForMine(minePositions, CParams.dMineScale); if (GrabHit >= 0) { sweeperPositions.get(i).incFit(); minePositions.get(GrabHit).setX(Utils.RandDouble() * cxClient); minePositions.get(GrabHit).setY(Utils.RandDouble() * cyClient); } } } else { System.out.println("Time to update the brains"); int bestFit = 0; int bestFitPos = 0; for(int i = 0; i < sweeperPositions.size(); i++) { if(sweeperPositions.get(i).getIncFit() > bestFit) { bestFitPos = i; bestFit = sweeperPositions.get(i).getIncFit(); } } System.out.println("Best Fit Index: " + bestFitPos); System.out.println("Updating everyone brain"); for(int i = 0; i < sweeperPositions.size(); i++) { if(i != bestFitPos) { sweeperPositions.get(i).updateBrain(sweeperPositions.get(bestFitPos)); } sweeperPositions.get(i).incFit = 0; } // See who has the highest Fit and take their brain and give it to the rest m_iTicks = 0; } return true; }
9
private SharingPeer getOrCreatePeer(byte[] peerId, String ip, int port) { Peer search = new Peer(ip, port, (peerId != null ? ByteBuffer.wrap(peerId) : (ByteBuffer)null)); SharingPeer peer = null; synchronized (this.peers) { peer = this.peers.get(search.hasPeerId() ? search.getHexPeerId() : search.getHostIdentifier()); if (peer != null) { return peer; } if (search.hasPeerId()) { peer = this.peers.get(search.getHostIdentifier()); if (peer != null) { // Set peer ID for previously known peer. peer.setPeerId(search.getPeerId()); this.peers.remove(peer.getHostIdentifier()); this.peers.putIfAbsent(peer.getHexPeerId(), peer); return peer; } } peer = new SharingPeer(ip, port, search.getPeerId(), this.torrent); this.peers.putIfAbsent(peer.hasPeerId() ? peer.getHexPeerId() : peer.getHostIdentifier(), peer); logger.trace("Created new peer " + peer + "."); } return peer; }
6
public synchronized void addPoints(MapleClient c, int points, long expiration, String reason) { // if (c.getPlayer().isJounin()) return; int acc = c.getPlayer().getAccountID(); List<String> reasonList; if (this.points.containsKey(acc)) { if (this.points.get(acc) >= AUTOBAN_POINTS) return; this.points.put(acc, this.points.get(acc) + points); reasonList = this.reasons.get(acc); reasonList.add(reason); } else { this.points.put(acc, points); reasonList = new LinkedList<String>(); reasonList.add(reason); this.reasons.put(acc, reasonList); } if (this.points.get(acc) >= AUTOBAN_POINTS) { String name = c.getPlayer().getName(); StringBuilder banReason = new StringBuilder("Autoban for char "); banReason.append(name); banReason.append(" (IP "); banReason.append(c.getSessionIPAddress()); banReason.append("): "); for (String s : reasons.get(acc)) { banReason.append(s); banReason.append(", "); } if (c.getPlayer().isJounin()) { log.warn("[h4x] Trying to a/b gm - something fishy going on: {}", banReason.toString()); } else { c.getPlayer().ban(banReason.toString()); c.getChannelServer().broadcastPacket(MaplePacketCreator.serverNotice(0, "[Autoban] " + name + " banned by the system (Reason: " + reason + ")")); MainIRC.getInstance().sendGlobalMessage("[Autoban] " + name + " banned by the system (Reason: " + reason + ")"); //log.warn("[h4x] Autobanned player {} (accountid {})", name, acc); } return; } if (expiration > 0) { expirations.add(new ExpirationEntry(System.currentTimeMillis() + expiration, acc, points)); } }
6
public int getChildCount() { return canHaveChildren() ? mChildren.size() : 0; }
1
@Override public boolean equals(Object y) { if (y == null) return false; if (y.getClass() != this.getClass()) { return false; } Board that = (Board) y; if (this.N != that.N) return false; if (this.io != that.io || this.jo != that.jo) return false; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) { if (this.board[i][j] != that.board[i][j]) return false; } if (y == this) return true; return true; // does this board equal y? }
9
private Object handlePrimitive(JsonPrimitive json) { if (json.isBoolean()) { return json.getAsBoolean(); } else if (json.isString()) { return json.getAsString(); } else { BigDecimal bigDec = json.getAsBigDecimal(); // Find out if it is an int type try { bigDec.toBigIntegerExact(); try { return bigDec.intValueExact(); } catch (ArithmeticException e) { } return bigDec.longValue(); } catch (ArithmeticException e) { } // Just return it as a double return bigDec.doubleValue(); } }
4
static byte[] unpackArchive(byte[] is, int i) { anInt7046++; ByteBuffer class348_sub49 = new ByteBuffer(is); int i_37_ = class348_sub49.getUByte(); if (i > -74) method3156(true, null); int i_38_ = class348_sub49.getDword(); if (i_38_ < 0 || (HandshakePacket.anInt401 != 0 && (HandshakePacket.anInt401 ^ 0xffffffff) > (i_38_ ^ 0xffffffff))) throw new RuntimeException(); if (i_37_ != 0) { int i_39_ = class348_sub49.getDword(); if (i_39_ < 0 || ((HandshakePacket.anInt401 ^ 0xffffffff) != -1 && (HandshakePacket.anInt401 ^ 0xffffffff) > (i_39_ ^ 0xffffffff))) throw new RuntimeException(); byte[] is_40_ = new byte[i_39_]; if (i_37_ == 1) Class212.method1547(is_40_, i_39_, is, i_38_, 9); else { synchronized (Class348_Sub33.aClass152_6955) { Class348_Sub33.aClass152_6955.method1218(is_40_, 29123, class348_sub49); } } return is_40_; } byte[] is_41_ = new byte[i_38_]; class348_sub49.getBytes(is_41_, 0, i_38_); return is_41_; }
9
public boolean checkParticipant(String Participant) { // TODO: Clean up if (victim.getPilot().getCharacterName().equalsIgnoreCase(Participant)) { return true; } if (attackers != null) { for (ShipAndChar attacker : attackers) { try { if (attacker.getPilot().getCharacterName() .equalsIgnoreCase(Participant)) { return true; } } catch (Exception e) { } } } return false; }
5
public Partner findPartnerById(final Long id) { return new Partner(); }
0
public static Config readFile(String path) { Config result = new Config(); try { FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(null); String line = br.readLine(); KeyValue kv = null; while(line != null) { kv = KeyValueFactory.fromString(line); result.lines.add(kv); } } catch (FileNotFoundException e) { logger.error(e); } catch (IOException e) { logger.error(e); } return result; }
3
public ControlPanel(SelectTreeDrawer treeDrawer, MinimizeController controller) { super(); this.treeDrawer = treeDrawer; this.controller = controller; initView(); }
0
public Game() { addKeyListener(new KeyInput(this)); setFocusable(true); setDoubleBuffered(true); requestFocusInWindow(); magnus = new Magnus(); platform = new Platform(); //Game Timer timer = new Timer(5, this); timer.start(); //Animation Timer Right Timer animationTimerRight = new Timer(200, new ActionListener(){ public void actionPerformed(ActionEvent e) { movingRight = !movingRight; Magnus.frameRight = movingRight ? Magnus.magnusRight : Magnus.magnusStillRight; repaint(); } }); animationTimerRight.setRepeats(true); animationTimerRight.setCoalesce(true); animationTimerRight.start(); //Animation Timer Left Timer animationTimerLeft = new Timer(250, new ActionListener(){ public void actionPerformed(ActionEvent e) { movingLeft = !movingLeft; Magnus.frameLeft = movingLeft ? Magnus.magnusLeft : Magnus.magnusStillLeft; repaint(); } }); animationTimerLeft.setRepeats(true); animationTimerLeft.setCoalesce(true); animationTimerLeft.start(); System.out.println("Game Intialized"); }
2
public Tool(types type, String path) { this.path = path; switch(type) { case CHALCEUS: duration = 25; path += "Chalceus.png"; break; case ARGNTUM: duration = 40; path += "Argentum.png"; break; case AURAIRUS: duration = 60; path += "Aurairus.png"; break; case AETHERIUM: duration = 100; path += "Aetherium.png"; break; } try { item = new Image(path); } catch (SlickException e) { e.printStackTrace(); } }
5
public void updateID() { if(ID == 0) { int x = 1; while(Spell.validID(x)) { x++; } IDText.setText(x + ""); } }
2
public static void setGrid() { Color color; for (int y = 0; y < 4; y++) { for (int x = 0; x < 4; x++) { color = getColor(x, y); for (int c = 0; c < 12; c++) { if (colors[c].equals(color)) { Calculate.scenarios[0].grid[x][y] = (int) Math.pow(2, c); } } } } }
4
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // CHANGE: The EJB is instantiated automatically // CourseModel model = CourseModelImpl.getInstance(); String path = request.getServletPath(); if (path.equals("/StudentController")) { String id = request.getParameter("studentId"); String name = request.getParameter("studentName"); String address = request.getParameter("studentAddress"); // ADD version parameter int version = Integer.parseInt(request.getParameter("version")); String submit = request.getParameter("submit"); try { // MODIFY add version parameter if (submit.equals("Get Student")) { Student stud = model.getStudent(id); request.setAttribute("student", stud); } else if (submit.equals("Update Student")) { model.updateStudent(new Student(id, name, address,version)); Student stud = model.getStudent(id); request.setAttribute("student", stud); } else if (submit.equals("Add Student")) { model.addStudent(new Student(id, name, address, version)); Student stud = model.getStudent(id); request.setAttribute("student", stud); } else if (submit.equals("Delete Student")) { model.deleteStudent(new Student(id, name, address, version)); } } catch (CourseException ex) { request.setAttribute("message", ex.getMessage()); } RequestDispatcher dispatcher = request.getRequestDispatcher("StudentDetails"); dispatcher.forward(request, response); } else if (path.equals("/AllStudents")) { try { Student[] students = model.getAllStudents(); request.setAttribute("students", students); } catch (CourseException ex) { request.setAttribute("message", ex.getMessage()); } RequestDispatcher dispatcher = request.getRequestDispatcher("AllStudents.jsp"); dispatcher.forward(request, response); } }
8
@Override public double findCustomersBalance(int id) { double customersBalance = 0; String sql = "SELECT balance FROM customer WHERE customer_id='" + id + "';"; Connection con = null; try { con = getConnection(); PreparedStatement statement = con.prepareStatement(sql); ResultSet resultSet = statement.executeQuery(); if(resultSet.next()) { customersBalance = resultSet.getDouble("balance"); } } catch (SQLException e) { e.printStackTrace(); } finally { if (con != null) closeConnection(con); } return customersBalance; }
3
private static String escapeJSON(String text) { StringBuilder builder = new StringBuilder(); builder.append('"'); for (int index = 0; index < text.length(); index++) { char chr = text.charAt(index); switch (chr) { case '"': case '\\': builder.append('\\'); builder.append(chr); break; case '\b': builder.append("\\b"); break; case '\t': builder.append("\\t"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; default: if (chr < ' ') { String t = "000" + Integer.toHexString(chr); builder.append("\\u" + t.substring(t.length() - 4)); } else { builder.append(chr); } break; } } builder.append('"'); return builder.toString(); }
8
@Override public void keyPressed(KeyEvent e) { if(selectedIndex != -1) { String chr = KeyEvent.getKeyText(e.getKeyCode()); if(frame.buttons[selectedIndex].getText().indexOf(chr+" + ") == -1) frame.buttons[selectedIndex].setText(frame.buttons[selectedIndex].getText()+chr+" + "); if(e.getKeyCode() < 16 || e.getKeyCode() > 18) { keyString = (Boolean.toString(e.isShiftDown())+Boolean.toString(e.isControlDown())+Boolean.toString(e.isAltDown())).replace("true", "1").replace("false", "0")+keyString+e.getKeyCode(); values[selectedIndex] = keyString; String lValue = frame.buttons[selectedIndex].getText(); frame.buttons[selectedIndex].setText(lValue.substring(0, lValue.length()-3)); frame.buttons[selectedIndex].setSelected(false); selectedIndex = -1; } } }
4
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target==null) return false; if(target.fetchEffect(ID())!=null) { mob.tell(target,null,null,L("<S-NAME> already <S-HAS-HAVE> the strength of a bull.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { invoker=mob; final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<S-NAME> gain(s) the strength of a bull!"):L("^S<S-NAME> chant(s) for the strength of a bull!^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,target,L("<S-NAME> chant(s), but nothing more happens.")); // return whether it worked return success; }
9
private void func_31010_a(float var1, float var2) { if(!this.extending) { --var1; } else { var1 = 1.0F - var1; } AxisAlignedBB var3 = Block.pistonMoving.func_31035_a(this.worldObj, this.xCoord, this.yCoord, this.zCoord, this.storedBlockID, var1, this.storedOrientation); if(var3 != null) { List var4 = this.worldObj.getEntitiesWithinAABBExcludingEntity((Entity)null, var3); if(!var4.isEmpty()) { field_31018_m.addAll(var4); Iterator var5 = field_31018_m.iterator(); while(var5.hasNext()) { Entity var6 = (Entity)var5.next(); var6.moveEntity((double)(var2 * (float)PistonBlockTextures.offsetsXForSide[this.storedOrientation]), (double)(var2 * (float)PistonBlockTextures.offsetsYForSide[this.storedOrientation]), (double)(var2 * (float)PistonBlockTextures.offsetsZForSide[this.storedOrientation])); } field_31018_m.clear(); } } }
4
private void groupBySourceAndAnalyze(Walk[] paths) { int curSource = -1; ArrayList<Walk> curSet = new ArrayList<Walk>(); for(int j=0; j < paths.length; j++) { Walk w = paths[j]; if (w.getSource() != curSource) { if (curSource != -1) processWalksFromSource(curSource, curSet); curSource = w.getSource(); curSet = new ArrayList<Walk>(); } curSet.add(w); } // Last processWalksFromSource(curSource, curSet); }
3
public Collection<LineUp> getLineUps() { if (lineUps == null || lineUps.size() == 0) fillLineUp(); return lineUps; }
2
public void moveStep() { switch(dir){ case EAST: this.x++; break; case NORTH: this.y--; break; case SOUTH: this.y++; break; case WEST: this.x--; break; default: break; } }
4
public Bittorrent(Object bo) { Logger.getInstance().debug("Creating Bittorrent with Obj: " + bo.toString()); try { HashMap<String, Object> raw = (HashMap<String, Object>) bo; if (raw.containsKey("announceList")) { Object[] announceArray = (Object[]) raw.get("announceList"); for (Object o : announceArray) { Object[] n = (Object[]) o; announceList.add((String) n[0]); } } if (raw.containsKey("comment")) comment = raw.get("comment").toString(); if (raw.containsKey("creationDate")) creationDate = new Date((Long) raw.get("creationDate")); if (raw.containsKey("mode")) mode = getMode(raw.get("mode").toString()); if (raw.containsKey("info")) { try { // TODO: if there would not be error, remake all // raw-to-struct conversions info = (HashMap<String, String>) raw.get("info"); } catch (Exception e) { Logger.getInstance().error("Error parsing info while creating Bittorrent struct", e); } } } catch (ClassCastException e) { throw new RuntimeException("Cannot parse download state", e); } }
8