List of usage examples for java.util LinkedList size
int size
To view the source code for java.util LinkedList size.
Click Source Link
From source file:org.testng.spring.test.AbstractDependencyInjectionSpringContextTests.java
private void initManagedVariableNames() throws IllegalAccessException { LinkedList managedVarNames = new LinkedList(); Class clazz = getClass();/*w ww . ja va 2s . c o m*/ do { Field[] fields = clazz.getDeclaredFields(); if (logger.isDebugEnabled()) { logger.debug("Found " + fields.length + " fields on " + clazz); } for (int i = 0; i < fields.length; i++) { Field field = fields[i]; field.setAccessible(true); if (logger.isDebugEnabled()) { logger.debug("Candidate field: " + field); } if (isProtectedInstanceField(field)) { Object oldValue = field.get(this); if (oldValue == null) { managedVarNames.add(field.getName()); if (logger.isDebugEnabled()) { logger.debug("Added managed variable '" + field.getName() + "'"); } } else { if (logger.isDebugEnabled()) { logger.debug("Rejected managed variable '" + field.getName() + "'"); } } } } clazz = clazz.getSuperclass(); } while (!clazz.equals(AbstractDependencyInjectionSpringContextTests.class)); this.managedVariableNames = (String[]) managedVarNames.toArray(new String[managedVarNames.size()]); }
From source file:com.commander4j.db.JDBDespatch.java
public boolean delete() { PreparedStatement stmtupdate; boolean result = false; setErrorMessage(""); logger.debug("delete [" + getDespatchNo() + "]"); LinkedList<String> assignedList = new LinkedList<String>(); JDBPallet pal = new JDBPallet(getHostID(), getSessionID()); if (isValid(false) == true) { String journeyRef = getJourneyRef(); assignedList.clear();/*from w ww . j a va2 s . c o m*/ assignedList.addAll(getAssignedSSCCs()); if (assignedList.size() > 0) { for (int j = 0; j < assignedList.size(); j++) { if (pal.getPalletProperties(assignedList.get(j))) { pal.setDespatchNo(""); pal.update(); } } } try { stmtupdate = Common.hostList.getHost(getHostID()).getConnection(getSessionID()).prepareStatement( Common.hostList.getHost(getHostID()).getSqlstatements().getSQL("JDBDespatch.delete")); stmtupdate.setString(1, getDespatchNo()); stmtupdate.execute(); stmtupdate.clearParameters(); Common.hostList.getHost(getHostID()).getConnection(getSessionID()).commit(); stmtupdate.close(); if (journeyRef.equals("") == false) { JDBJourney jrny = new JDBJourney(getHostID(), getSessionID()); if (jrny.getJourneyRefProperties(journeyRef)) { jrny.setStatus("Unassigned"); jrny.setDespatchNo(""); jrny.update(); } } result = true; } catch (SQLException e) { setErrorMessage(e.getMessage()); } } return result; }
From source file:ch.randelshofer.cubetwister.HTMLExporter.java
/** * Reads the content of the input stream into a list of token. * If a token start with "${", its a placeholder. * If a token doesn't start with "${" its a literal text. *///from www. ja v a 2s .c o m private String[] toTokens(String filename, InputStream in) throws IOException { InputStreamReader reader = new InputStreamReader(in, "UTF8"); StringBuilder buf = new StringBuilder(); char[] cbuf = new char[256]; int len; while (-1 != (len = reader.read(cbuf, 0, cbuf.length))) { buf.append(cbuf, 0, len); } int p1 = 0; int p2 = 0; LinkedList<String> tokens = new LinkedList<String>(); while (true) { p1 = buf.indexOf("${", p2); if (p1 == -1) { break; } tokens.add(buf.substring(p2, p1)); p2 = buf.indexOf("}", p1 + 2); if (p2 == -1) { throw new IOException("Closing curly bracket missing in " + filename + " after position " + p1); } p2++; tokens.add(buf.substring(p1, p2)); } if (p2 != buf.length()) { tokens.add(buf.substring(p2)); } return tokens.toArray(new String[tokens.size()]); }
From source file:org.openscience.cdk.applications.taverna.basicutilities.ChartTool.java
/** * Creates a residue plot./* ww w . j ava 2 s. c o m*/ * * @param yValues * @param header * @param xAxis * @param yAxis * @param seriesNames * @return */ public JFreeChart createResiduePlot(List<Double[]> yValues, String header, String xAxis, String yAxis, List<String> seriesNames) { LinkedList<XYLineAnnotation> lines = new LinkedList<XYLineAnnotation>(); DefaultXYDataset xyDataSet = new DefaultXYDataset(); for (int j = 0; j < yValues.size(); j++) { XYSeries series = new XYSeries(seriesNames.get(j)); for (int i = 0; i < yValues.get(j).length; i++) { series.add(i + 1, yValues.get(j)[i]); float dash[] = { 10.0f }; BasicStroke stroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f); XYLineAnnotation annotation = new XYLineAnnotation(i + 1, 0, i + 1, yValues.get(j)[i], stroke, Color.BLUE); lines.add(annotation); } xyDataSet.addSeries(seriesNames.get(j), series.toArray()); } JFreeChart chart = ChartFactory.createScatterPlot(header, xAxis, yAxis, xyDataSet, PlotOrientation.VERTICAL, true, false, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setNoDataMessage("NO DATA"); plot.setDomainZeroBaselineVisible(true); plot.setRangeZeroBaselineVisible(true); for (int i = 0; i < lines.size(); i++) { plot.addAnnotation(lines.get(i)); } XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); renderer.setSeriesOutlinePaint(0, Color.black); renderer.setUseOutlinePaint(true); NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis(); domainAxis.setAutoRangeIncludesZero(false); domainAxis.setTickMarkInsideLength(2.0f); domainAxis.setTickMarkOutsideLength(0.0f); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setTickMarkInsideLength(2.0f); rangeAxis.setTickMarkOutsideLength(0.0f); return chart; }
From source file:gdsc.smlm.engine.FitWorker.java
/** * Get an estimate of the background level using the fitted peaks. If no fits available then estimate background * using mean of image.//from ww w. j a va2 s .co m * * @param peakResults * @param width * @param height * @return */ @SuppressWarnings("unused") private float estimateBackground(LinkedList<PeakResult> peakResults, int width, int height) { if (peakResults.size() > 0) { // Compute average background of the fitted peaks double sum = 0; for (PeakResult result : peakResults) sum += result.params[Gaussian2DFunction.BACKGROUND]; float av = (float) sum / peakResults.size(); if (logger != null) logger.info("Average background %f", av); return av; } else { // Compute average of the entire image double sum = 0; for (int i = width * height; i-- > 0;) sum += data[i]; float av = (float) sum / (width * height); if (logger != null) logger.info("Image background %f", av); return av; } }
From source file:com.ibm.jaggr.core.impl.deps.DepTree.java
/** * Object constructor. Attempts to de-serialize the cached dependency lists * from disk and then validates the dependency lists based on last-modified * dates, looking for any new or removed files. If the cached dependency * list data cannot be de-serialized, new lists are constructed. Once the * dependency lists have been validated, the list data is serialized back * out to disk./* w w w . j a v a 2 s .c om*/ * * @param paths * Collection of URIs which specify the target resources * to be scanned for javascript files. * @param aggregator * The servlet instance for this object * @param stamp * timestamp associated with external override/customization * resources that are check on every server restart * @param clean * If true, then the dependency lists are generated from scratch * rather than by de-serializing and then validating the cached * dependency lists. * @param validateDeps * If true, then validate existing cached dependencies using * file last-modified times. * @throws IOException */ public DepTree(Collection<URI> paths, IAggregator aggregator, long stamp, boolean clean, boolean validateDeps) throws IOException { final String sourceMethod = "<ctor>"; //$NON-NLS-1$ boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(DepTree.class.getName(), sourceMethod, new Object[] { paths, aggregator, stamp, clean, validateDeps }); } this.stamp = stamp; IConfig config = aggregator.getConfig(); rawConfig = config.toString(); cacheBust = AggregatorUtil.getCacheBust(aggregator); File cacheDir = new File(aggregator.getWorkingDirectory(), DEPCACHE_DIRNAME); File cacheFile = new File(cacheDir, CACHE_FILE); /* * The de-serialized dependency map. If we have a cached dependency map, * then it will be validated against the last-modified dates of the * current files and only the files that have changed will need to be * re-parsed to update the dependency lists. */ DepTree cached = null; if (!clean) { // If we're not starting clean, try to de-serialize the map from // cache try { ObjectInputStream is = new ObjectInputStream(new FileInputStream(cacheFile)); try { if (isTraceLogging) { log.finer("Attempting to read cached dependencies from " + cacheFile.toString()); //$NON-NLS-1$ } cached = (DepTree) is.readObject(); } finally { try { is.close(); } catch (Exception ignore) { } } } catch (FileNotFoundException e) { /* * Not an error. Just means that the cache file hasn't been * written yet or else it's been deleted. */ if (log.isLoggable(Level.INFO)) log.log(Level.INFO, Messages.DepTree_1); } catch (Exception e) { if (log.isLoggable(Level.SEVERE)) log.log(Level.SEVERE, e.getMessage(), e); } } // If the cacheBust config param has changed, then do a clean build // of the dependencies. if (cached != null) { if (stamp == 0) { // no init stamp provided. Preserve the cached one. stamp = cached.stamp; } if (stamp > cached.stamp) { // init stamp has been updated. Validate dependencies. validateDeps = true; } if (!StringUtils.equals(cacheBust, cached.cacheBust)) { if (isTraceLogging) { log.finer("Current cacheBust = " + cacheBust + ", cached cacheBust = " + cached.cacheBust); //$NON-NLS-1$//$NON-NLS-2$ } if (log.isLoggable(Level.INFO)) { log.info(Messages.DepTree_2); } cached = null; } if (cached != null && !StringUtils.equals(rawConfig, cached.rawConfig)) { if (isTraceLogging) { log.finer("Current config = " + rawConfig); //$NON-NLS-1$ log.finer("Cached config = " + cached.rawConfig); //$NON-NLS-1$ } validateDeps = true; } } /* * If we de-serialized a previously saved dependency map, then go with * that. */ if (cached != null && !validateDeps && !clean) { depMap = cached.depMap; fromCache = true; return; } else if (isTraceLogging) { log.finer("Building/validating deps: cached = " + cached + ", validateDeps = " + validateDeps //$NON-NLS-1$//$NON-NLS-2$ + ", clean = " + clean); //$NON-NLS-1$ } // Initialize the dependency map depMap = new ConcurrentHashMap<URI, DepTreeNode>(); // This can take a while, so print something to the console String msg = MessageFormat.format(Messages.DepTree_3, new Object[] { aggregator.getName() }); ConsoleService cs = new ConsoleService(); cs.println(msg); if (log.isLoggable(Level.INFO)) { log.info(msg); } // Make sure that all the paths are unique and orthogonal paths = DepUtils.removeRedundantPaths(paths); /* * Create the thread pools, one for the tree builders and one for the * parsers. Since a tree builder thread will wait for all the outstanding * parser threads started by that builder to complete, we need to use two * independent thread pools to guard against the possibility of deadlock * caused by all the threads in the pool being consumed by tree builders * and leaving none available to service the parsers. */ final ThreadGroup treeBuilderTG = new ThreadGroup(TREEBUILDER_TGNAME), parserTG = new ThreadGroup(JSPARSER_TGNAME); ExecutorService treeBuilderExc = Executors.newFixedThreadPool(10, new ThreadFactory() { public Thread newThread(Runnable r) { return new Thread(treeBuilderTG, r, MessageFormat.format(THREADNAME, new Object[] { treeBuilderTG.getName(), treeBuilderTG.activeCount() })); } }), parserExc = Executors.newFixedThreadPool(20, new ThreadFactory() { public Thread newThread(Runnable r) { return new Thread(parserTG, r, MessageFormat.format(THREADNAME, new Object[] { parserTG.getName(), parserTG.activeCount() })); } }); // Counter to keep track of number of tree builder threads started AtomicInteger treeBuilderCount = new AtomicInteger(0); // The completion services for the thread pools final CompletionService<URI> parserCs = new ExecutorCompletionService<URI>(parserExc); CompletionService<DepTreeBuilder.Result> treeBuilderCs = new ExecutorCompletionService<DepTreeBuilder.Result>( treeBuilderExc); Set<String> nonJSExtensions = Collections.unmodifiableSet(getNonJSExtensions(aggregator)); // Start the tree builder threads to process the paths for (final URI path : paths) { /* * Create or get from cache the root node for this path and * add it to the new map. */ DepTreeNode root = new DepTreeNode("", path); //$NON-NLS-1$ DepTreeNode cachedNode = null; if (cached != null) { cachedNode = cached.depMap.get(path); if (log.isLoggable(Level.INFO)) { log.info(MessageFormat.format(Messages.DepTree_4, new Object[] { path })); } } else { if (log.isLoggable(Level.INFO)) { log.info(MessageFormat.format(Messages.DepTree_5, new Object[] { path })); } } depMap.put(path, root); treeBuilderCount.incrementAndGet(); treeBuilderCs.submit(new DepTreeBuilder(aggregator, parserCs, path, root, cachedNode, nonJSExtensions)); } // List of parser exceptions LinkedList<Exception> parserExceptions = new LinkedList<Exception>(); /* * Pull the completed tree builder tasks from the completion queue until * all the paths have been processed */ while (treeBuilderCount.decrementAndGet() >= 0) { try { DepTreeBuilder.Result result = treeBuilderCs.take().get(); if (log.isLoggable(Level.INFO)) { log.info(MessageFormat.format(Messages.DepTree_6, new Object[] { result.parseCount, result.dirName })); } } catch (Exception e) { if (log.isLoggable(Level.SEVERE)) log.log(Level.SEVERE, e.getMessage(), e); parserExceptions.add(e); } } // shutdown the thread pools now that we're done with them parserExc.shutdown(); treeBuilderExc.shutdown(); // If parser exceptions occurred, then rethrow the first one if (parserExceptions.size() > 0) { throw new RuntimeException(parserExceptions.get(0)); } // Prune dead nodes (folder nodes with no children) for (Map.Entry<URI, DepTreeNode> entry : depMap.entrySet()) { entry.getValue().prune(); } /* * Make sure the cache directory exists before we try to serialize the * dependency map. */ if (!cacheDir.exists()) if (!cacheDir.mkdirs()) { throw new IOException( MessageFormat.format(Messages.DepTree_0, new Object[] { cacheDir.getAbsolutePath() })); } // Serialize the map to the cache directory ObjectOutputStream os; os = new ObjectOutputStream(new FileOutputStream(cacheFile)); try { if (isTraceLogging) { log.finer("Writing cached dependencies to " + cacheFile.toString()); //$NON-NLS-1$ } os.writeObject(this); } finally { try { os.close(); } catch (Exception ignore) { } } msg = MessageFormat.format(Messages.DepTree_7, new Object[] { aggregator.getName() }); // Output that we're done. cs.println(msg); if (log.isLoggable(Level.INFO)) { log.info(msg); } if (isTraceLogging) { log.exiting(DepTree.class.getName(), sourceMethod); } }
From source file:com.oltpbenchmark.benchmarks.auctionmark.AuctionMarkProfile.java
private boolean addItem(LinkedList<ItemInfo> items, ItemInfo itemInfo) { boolean added = false; int idx = items.indexOf(itemInfo); if (idx != -1) { // HACK: Always swap existing ItemInfos with our new one, since it will // more up-to-date information ItemInfo existing = items.set(idx, itemInfo); assert (existing != null); return (true); }/* w w w . ja va2s.c om*/ if (itemInfo.hasCurrentPrice()) assert (itemInfo.getCurrentPrice() > 0) : "Negative current price for " + itemInfo; // If we have room, shove it right in // We'll throw it in the back because we know it hasn't been used yet if (items.size() < AuctionMarkConstants.ITEM_ID_CACHE_SIZE) { items.addLast(itemInfo); added = true; // Otherwise, we can will randomly decide whether to pop one out } else if (this.rng.nextBoolean()) { items.pop(); items.addLast(itemInfo); added = true; } return (added); }
From source file:Interfaces.EstadisticaConocioGui.java
/** * Creates new form EstadisticaConocioGui *//* w ww.j a v a2 s.c o m*/ public EstadisticaConocioGui(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); abrirBase(); LazyList<Socio> socios = Socio.findAll(); Iterator<Socio> it = socios.iterator(); Socio s; String nosConocio; Boolean activo; Integer[] nosConocioSuma = { 0, 0, 0, 0, 0, 0 }; LinkedList<Pair<Integer, Integer>> actividadesRealizan = new LinkedList<>(); LazyList<Arancel> aranceles = Arancel.findAll(); Iterator<Arancel> itArancel = aranceles.iterator(); while (itArancel.hasNext()) { Pair<Integer, Integer> par = new Pair<>(itArancel.next().getInteger("id"), 0); actividadesRealizan.add(par); } while (it.hasNext()) { s = it.next(); nosConocio = s.getString("NOSCONOCIOPOR"); activo = s.getBoolean("ACTIVO"); switch (nosConocio) { case "NO ESPECIFICA": nosConocioSuma[0]++; break; case "VIO EL GIMNASIO": nosConocioSuma[1]++; break; case "POR RADIO": nosConocioSuma[2]++; break; case "POR TV": nosConocioSuma[3]++; break; case "REDES SOCIALES": nosConocioSuma[4]++; break; case "UN AMIGO/A": nosConocioSuma[5]++; break; } if (activo) { LazyList<Socioarancel> arancelesSocio = Socioarancel.where("id_socio = ?", s.getId()); Iterator<Socioarancel> itAr = arancelesSocio.iterator(); while (itAr.hasNext()) { Socioarancel ar = itAr.next(); boolean sume = false; int i = 0; while (i < actividadesRealizan.size() && !sume) { if (actividadesRealizan.get(i).first() == ar.getInteger("id_arancel")) { Pair<Integer, Integer> aux = new Pair<>(actividadesRealizan.get(i).first(), actividadesRealizan.get(i).second() + 1); actividadesRealizan.remove(i); actividadesRealizan.add(i, aux); sume = true; } i++; } } } } DefaultCategoryDataset datasetConocio = new DefaultCategoryDataset(); datasetConocio.setValue(nosConocioSuma[0], "nos conocieron", "NO ESPECIFICA"); datasetConocio.setValue(nosConocioSuma[1], "nos conocieron", "VIO EL GIMNASIO"); datasetConocio.setValue(nosConocioSuma[2], "nos conocieron", "POR RADIO"); datasetConocio.setValue(nosConocioSuma[3], "nos conocieron", "POR TV"); datasetConocio.setValue(nosConocioSuma[4], "nos conocieron", "REDES SOCIALES"); datasetConocio.setValue(nosConocioSuma[5], "nos conocieron", "UN AMIGO/A"); JFreeChart chart = ChartFactory.createBarChart3D("Estadisticas por donde nos conocieron", "donde", "cantidad de personas", datasetConocio, PlotOrientation.VERTICAL, true, true, false); // Creacin del panel con el grfico ChartPanel panelGrafico = new ChartPanel(chart); pnlConocio.add(panelGrafico); DefaultCategoryDataset datasetAct = new DefaultCategoryDataset(); for (int i = 0; i < actividadesRealizan.size(); i++) { String nombreAct = Arancel.findById(actividadesRealizan.get(i).first()).getString("nombre"); datasetAct.setValue(actividadesRealizan.get(i).second(), "actividad", nombreAct); } JFreeChart chartAct = ChartFactory.createBarChart3D("Estadisticas que actividad realizan", "actividad", "cantidad de personas", datasetAct, PlotOrientation.VERTICAL, true, true, false); // Creacin del panel con el grfico ChartPanel panelGraficoAc = new ChartPanel(chartAct); pnlAct.add(panelGraficoAc); }
From source file:net.semanticmetadata.lire.filters.LsaFilter.java
/** * @param results/*from w w w . ja va 2 s . c o m*/ * @param query * @return the filtered results or null if error occurs. */ public ImageSearchHits filter(ImageSearchHits results, IndexReader reader, Document query) { // create a double[items][histogram] tempFeature = null; LinkedList<double[]> features = new LinkedList<double[]>(); try { tempFeature = (LireFeature) featureClass.newInstance(); } catch (Exception e) { logger.severe("Could not create feature " + featureClass.getName() + " (" + e.getMessage() + ")."); return null; } // get all features from the result set, take care of those that do not have the respective field. for (int i = 0; i < results.length(); i++) { Document d = null; try { d = reader.document(results.documentID(i)); } catch (IOException e) { e.printStackTrace(); } if (d.getField(fieldName) != null) { tempFeature.setByteArrayRepresentation(d.getField(fieldName).binaryValue().bytes, d.getField(fieldName).binaryValue().offset, d.getField(fieldName).binaryValue().length); features.add(tempFeature.getFeatureVector()); } } // now go for the query if (query.getField(fieldName) != null) { tempFeature.setByteArrayRepresentation(query.getField(fieldName).binaryValue().bytes, query.getField(fieldName).binaryValue().offset, query.getField(fieldName).binaryValue().length); } else { logger.severe("Query document is missing the given feature " + featureClass.getName() + "."); return null; } double[][] matrixData = new double[features.size() + 1][tempFeature.getFeatureVector().length]; System.arraycopy(tempFeature.getFeatureVector(), 0, matrixData[0], 0, tempFeature.getFeatureVector().length); int count = 1; for (Iterator<double[]> iterator = features.iterator(); iterator.hasNext();) { double[] next = iterator.next(); System.arraycopy(next, 0, matrixData[count], 0, next.length); count++; } for (int i = 0; i < matrixData.length; i++) { double[] doubles = matrixData[i]; for (int j = 0; j < doubles.length; j++) { if (Double.isNaN(doubles[j])) System.err.println("Value is NaN"); ; } } // create a matrix object and do the magic Array2DRowRealMatrix m = new Array2DRowRealMatrix(matrixData); long ms = System.currentTimeMillis(); SingularValueDecomposition svd = new SingularValueDecomposition(m); ms = System.currentTimeMillis() - ms; double[] singularValues = svd.getSingularValues(); RealMatrix s = svd.getS(); // if no number of dimensions is given reduce to a tenth. if (numberOfDimensions < 1) numberOfDimensions = singularValues.length / 10; for (int i = numberOfDimensions; i < singularValues.length; i++) { s.setEntry(i, i, 0); } RealMatrix mNew = svd.getU().multiply(s).multiply(svd.getVT()); double[][] data = mNew.getData(); // create the new result set TreeSet<SimpleResult> result = new TreeSet<SimpleResult>(); double maxDistance = 0; double[] queryData = data[0]; for (int i = 1; i < data.length; i++) { double[] doubles = data[i]; double distance = MetricsUtils.distL1(doubles, queryData); result.add(new SimpleResult((float) distance, results.documentID(i - 1))); maxDistance = Math.max(maxDistance, distance); } ImageSearchHits hits; hits = new SimpleImageSearchHits(result, (float) maxDistance); return hits; }
From source file:lob.VisualisationGUI.java
public void updateLabels(GUIUpdatePackage GUP) { jLabel15.setText(Integer.toString(this.time)); LinkedList<Trade> newTrades = this.broker.getNewTrades(); float mid = GUP.getMidpriceHistory().getLast(); this.midPrice = mid; long above = 0; long below = 0; long exact = 0; //Add up trade metrics for (int i = 0; i < newTrades.size(); i++) { Trade trade = newTrades.get(i);/*from w ww.j ava 2 s . co m*/ if (trade.getTradePrice() > mid) above = above + trade.getTradeVolume(); else if (trade.getTradePrice() < mid) below = below + trade.getTradeVolume(); else exact = exact + trade.getTradeVolume(); } long tot = above + below + exact; this.totalTraded = this.totalTraded + tot; this.averageTradeVolume = this.totalTraded / this.time; jLabel21.setText(Long.toString(tot)); jLabel22.setText(Long.toString(this.averageTradeVolume)); jLabel23.setText(Long.toString(above)); jLabel24.setText(Long.toString(below)); }