Example usage for java.util LinkedList pop

List of usage examples for java.util LinkedList pop

Introduction

In this page you can find the example usage for java.util LinkedList pop.

Prototype

public E pop() 

Source Link

Document

Pops an element from the stack represented by this list.

Usage

From source file:Main.java

public static void main(String[] args) {

    // create a LinkedList
    LinkedList<String> list = new LinkedList<String>();

    // add some elements
    list.add("Hello");
    list.add("from java2s.com");
    list.add("10");

    // print the list
    System.out.println("LinkedList:" + list);

    // pop the list
    System.out.println("Pop element in the list:" + list.pop());

    // print the list
    System.out.println("LinkedList:" + list);
}

From source file:com.act.lcms.v2.MZCollisionCounter.java

public static void main(String[] args) throws Exception {
    CLIUtil cliUtil = new CLIUtil(MassChargeCalculator.class, HELP_MESSAGE, OPTION_BUILDERS);
    CommandLine cl = cliUtil.parseCommandLine(args);

    File inputFile = new File(cl.getOptionValue(OPTION_INPUT_INCHI_LIST));
    if (!inputFile.exists()) {
        cliUtil.failWithMessage("Input file at does not exist at %s", inputFile.getAbsolutePath());
    }/*from   w w  w  .j  ava 2  s .c o m*/

    List<MassChargeCalculator.MZSource> sources = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            sources.add(new MassChargeCalculator.MZSource(line));
            if (sources.size() % 1000 == 0) {
                LOGGER.info("Loaded %d sources from input file", sources.size());
            }
        }
    }

    Set<String> considerIons = Collections.emptySet();
    if (cl.hasOption(OPTION_ONLY_CONSIDER_IONS)) {
        List<String> ions = Arrays.asList(cl.getOptionValues(OPTION_ONLY_CONSIDER_IONS));
        LOGGER.info("Only considering ions for m/z calculation: %s", StringUtils.join(ions, ", "));
        considerIons = new HashSet<>(ions);
    }

    TSVWriter<String, Long> tsvWriter = new TSVWriter<>(Arrays.asList("collisions", "count"));
    tsvWriter.open(new File(cl.getOptionValue(OPTION_OUTPUT_FILE)));

    try {
        LOGGER.info("Loaded %d sources in total from input file", sources.size());

        MassChargeCalculator.MassChargeMap mzMap = MassChargeCalculator.makeMassChargeMap(sources,
                considerIons);

        if (!cl.hasOption(OPTION_COUNT_WINDOW_INTERSECTIONS)) {
            // Do an exact analysis of the m/z collisions if windowing is not specified.

            LOGGER.info("Computing precise collision histogram.");
            Iterable<Double> mzs = mzMap.ionMZIter();
            Map<Integer, Long> collisionHistogram = histogram(
                    StreamSupport.stream(mzs.spliterator(), false).map(mz -> { // See comment about Iterable below.
                        try {
                            return mzMap.ionMZToMZSources(mz).size();
                        } catch (NoSuchElementException e) {
                            LOGGER.error("Caught no such element exception for mz %f: %s", mz, e.getMessage());
                            throw e;
                        }
                    }));
            List<Integer> sortedCollisions = new ArrayList<>(collisionHistogram.keySet());
            Collections.sort(sortedCollisions);
            for (Integer collision : sortedCollisions) {
                tsvWriter.append(new HashMap<String, Long>() {
                    {
                        put("collisions", collision.longValue());
                        put("count", collisionHistogram.get(collision));
                    }
                });
            }
        } else {
            /* After some deliberation (thanks Gil!), the windowed variant of this calculation counts the number of
             * structures whose 0.01 Da m/z windows (for some set of ions) overlap with each other.
             *
             * For example, let's assume we have five total input structures, and are only searching for one ion.  Let's
             * also assume that three of those structures have m/z A and the remaining two have m/z B.  The windows might
             * look like this in the m/z domain:
             * |----A----|
             *        |----B----|
             * Because A represents three structures and overlaps with B, which represents two, we assign A a count of 5--
             * this is the number of structures we believe could fall into the range of A given our current peak calling
             * approach.  Similarly, B is assigned a count of 5, as the possibility for collision/confusion is symmetric.
             *
             * Note that this is an over-approximation of collisions, as we could more precisely only consider intersections
             * when the exact m/z of B falls within the window around A and vice versa.  However, because we have observed
             * cases where the MS sensor doesn't report structures at exactly the m/z we predict, we employ this weaker
             * definition of intersection to give a slightly pessimistic view of what confusions might be possible. */
            // Compute windows for every m/z.  We don't care about the original mz values since we just want the count.
            List<Double> mzs = mzMap.ionMZsSorted();

            final Double windowHalfWidth;
            if (cl.hasOption(OPTION_WINDOW_HALFWIDTH)) {
                // Don't use get with default for this option, as we want the exact FP value of the default tolerance.
                windowHalfWidth = Double.valueOf(cl.getOptionValue(OPTION_WINDOW_HALFWIDTH));
            } else {
                windowHalfWidth = DEFAULT_WINDOW_TOLERANCE;
            }

            /* Window = (lower bound, upper bound), counter of represented m/z's that collide with this window, and number
             * of representative structures (which will be used in counting collisions). */
            LinkedList<CollisionWindow> allWindows = new LinkedList<CollisionWindow>() {
                {
                    for (Double mz : mzs) {
                        // CPU for memory trade-off: don't re-compute the window bounds over and over and over and over and over.
                        try {
                            add(new CollisionWindow(mz, windowHalfWidth, mzMap.ionMZToMZSources(mz).size()));
                        } catch (NoSuchElementException e) {
                            LOGGER.error("Caught no such element exception for mz %f: %s", mz, e.getMessage());
                            throw e;
                        }
                    }
                }
            };

            // Sweep line time!  The window ranges are the interesting points.  We just accumulate overlap counts as we go.
            LinkedList<CollisionWindow> workingSet = new LinkedList<>();
            List<CollisionWindow> finished = new LinkedList<>();

            while (allWindows.size() > 0) {
                CollisionWindow thisWindow = allWindows.pop();
                // Remove any windows from the working set that don't overlap with the next window.
                while (workingSet.size() > 0 && workingSet.peekFirst().getMaxMZ() < thisWindow.getMinMZ()) {
                    finished.add(workingSet.pop());
                }

                for (CollisionWindow w : workingSet) {
                    /* Add the size of the new overlapping window's structure count to each of the windows in the working set,
                     * which represents the number of possible confused structures that fall within the overlapping region.
                     * We exclude the window itself as it should already have counted the colliding structures it represents. */
                    w.getAccumulator().add(thisWindow.getStructureCount());

                    /* Reciprocally, add the structure counts of all windows with which the current window overlaps to it. */
                    thisWindow.getAccumulator().add(w.getStructureCount());
                }

                // Now that accumulation is complete, we can safely add the current window.
                workingSet.add(thisWindow);
            }

            // All the interesting events are done, so drop the remaining windows into the finished set.
            finished.addAll(workingSet);

            Map<Long, Long> collisionHistogram = histogram(
                    finished.stream().map(w -> w.getAccumulator().longValue()));
            List<Long> sortedCollisions = new ArrayList<>(collisionHistogram.keySet());
            Collections.sort(sortedCollisions);
            for (Long collision : sortedCollisions) {
                tsvWriter.append(new HashMap<String, Long>() {
                    {
                        put("collisions", collision);
                        put("count", collisionHistogram.get(collision));
                    }
                });
            }
        }
    } finally {
        if (tsvWriter != null) {
            tsvWriter.close();
        }
    }
}

From source file:Main.java

/**
 *  Retrieves the first value of a MultiMap index
 *  @param multiMap (Map<String,LinkedList<String>>)
 *  @param index (String)//from   w w  w .j a v a  2s.  c o m
 *  @return String
 **/
public static String popMultiMap(Map<String, LinkedList<String>> multiMap, String key) {
    if (multiMap == null)
        return (null);

    if (multiMap.containsKey(key)) {
        LinkedList<String> list = multiMap.get(key);
        if (list != null) {
            return (list.pop());
        } else {
            return (null);
        }
    } else {
        return (null);
    }
}

From source file:com.smallnn.input.FileUtil.java

public static List<File> find(File file, FileFilter filter) {
    List<File> result = new ArrayList<File>();
    LinkedList<File> stack = new LinkedList<File>();
    stack.push(file);//  w w w . ja  v a2 s .c o m
    while (!stack.isEmpty()) {
        File f = stack.pop();
        if (filter == null || filter.accept(f)) {
            result.add(f);
        }

        if (f.isDirectory() && f.exists()) {
            stack.addAll(Arrays.asList(f.listFiles()));
        }
    }
    return result;
}

From source file:com.thinkbiganalytics.metadata.jpa.support.QueryDslPathInspector.java

private static Object getFieldObject(BeanPath basePath, LinkedList<String> paths)
        throws IllegalAccessException {
    if (!paths.isEmpty()) {
        String currPath = paths.pop();
        Object o = getObjectForField(basePath, currPath);
        if (o != null && o instanceof BeanPath && !paths.isEmpty()) {
            return getFieldObject((BeanPath) o, paths);
        }//from  w ww .  j  a  v  a2  s.  com
        return o;
    }
    return null;
}

From source file:Main.java

public static int insertX(int numb, int random) {
    long result = 0;
    LinkedList<Integer> stack = new LinkedList<Integer>();
    while (numb > 0) {
        stack.push(numb % 10);/*from  w  w w  . j a va  2s  .  c  om*/
        numb = numb / 10;
    }

    while (!stack.isEmpty()) {
        result = (int) combinedTwoNumber(result, stack.pop());
        result = (int) combinedTwoNumber(result, random);
    }

    return (int) (result /= 10);
}

From source file:com.codenvy.commons.lang.TarUtils.java

private static void addDirectoryRecursively(TarArchiveOutputStream tarOut, String parentPath, File dir,
        long modTime, FilenameFilter filter) throws IOException {
    final int parentPathLength = parentPath.length() + 1;
    final LinkedList<File> q = new LinkedList<>();
    q.add(dir);/*from   ww  w  .ja v a 2 s.  c o m*/
    while (!q.isEmpty()) {
        final File current = q.pop();
        final File[] list = current.listFiles();
        if (list != null) {
            for (File f : list) {
                if (filter.accept(current, f.getName())) {
                    final String entryName = f.getAbsolutePath().substring(parentPathLength).replace('\\', '/');
                    if (f.isDirectory()) {
                        addDirectoryEntry(tarOut, entryName, f, modTime);
                        q.push(f);
                    } else if (f.isFile()) {
                        addFileEntry(tarOut, entryName, f, modTime);
                    }
                }
            }
        }
    }
}

From source file:edu.tum.cs.vis.model.util.algorithm.ACCUM.java

/**
 * Diffuse a vector field at 1 vertex, weighted by a Gaussian of width 1/sqrt(invsigma2) Ported
 * from trimesh2 (2.12)/*from   w w w.j av  a 2 s  .c  om*/
 */
@SuppressWarnings("javadoc")
private static void diffuse_vert_field(final Model m, HashMap<Vertex, Curvature> curvatures,
        Map<Vertex, Long> flags, AtomicLong flag_curr, final ACCUM accum, int v, float invsigma2, Vertex flt) {
    Vertex vert = m.getVertices().get(v);
    if (vert.getNeighbors().size() == 0) {
        // flt.set(0, 0, 0);
        accum.a(m, curvatures, vert, flt, 1.0f, vert);
        return;
    }

    // flt.set(0, 0, 0);
    accum.a(m, curvatures, vert, flt, vert.getPointarea(), vert);
    float sum_w = vert.getPointarea();
    final Vector3f nv = vert.getNormalVector();

    long flag_curr_val = flag_curr.incrementAndGet();
    flags.put(vert, flag_curr_val);
    LinkedList<Vertex> boundary = new LinkedList<Vertex>();
    boundary.addAll(vert.getNeighbors());
    while (boundary.size() > 0) {
        Vertex n = boundary.pop();
        if (flags.get(n) != null && flags.get(n) == flag_curr_val)
            continue;
        flags.put(n, flag_curr_val);
        if (nv.dot(n.getNormalVector()) <= 0.0f)
            continue;
        // Gaussian weight
        float w = wt(n, vert, invsigma2);
        if (w == 0.0f)
            continue;
        // Downweight things pointing in different directions
        w *= nv.dot(n.getNormalVector());
        // Surface area "belonging" to each point
        w *= n.getPointarea();
        // Accumulate weight times field at neighbor
        accum.a(m, curvatures, vert, flt, w, n);
        sum_w += w;
        for (Vertex nn : n.getNeighbors()) {
            if (flags.get(nn) != null && flags.get(nn) == flag_curr_val)
                continue;
            boundary.push(nn);
        }
    }
    flt.scale(1 / sum_w);
}

From source file:org.opencastproject.videoeditor.impl.VideoEditorServiceImpl.java

private static List<VideoClip> sortSegments(List<VideoClip> edits) {
    LinkedList<VideoClip> ll = new LinkedList<VideoClip>();
    List<VideoClip> clips = new ArrayList<VideoClip>();
    Iterator<VideoClip> it = edits.iterator();
    VideoClip clip;/*from w  ww  .j a v  a 2  s.  c o m*/
    VideoClip nextclip;
    while (it.hasNext()) { // Check for legal durations
        clip = it.next();
        if (clip.getDuration() > 2) { // Keep segments at least 2 seconds long
            ll.add(clip);
        }
    }
    clip = ll.pop(); // initialize
    while (!ll.isEmpty()) { // Check that 2 consecutive segments from same src are at least 2 secs apart
        if (ll.peek() != null) {
            nextclip = ll.pop(); // check next consecutive segment
            if ((nextclip.getSrc() == clip.getSrc()) && (nextclip.getStart() - clip.getEnd()) < 2) { // collapse two segments into one
                clip.setEnd(nextclip.getEnd()); // by using inpt of seg 1 and outpoint of seg 2
            } else {
                clips.add(clip); // keep last segment
                clip = nextclip; // check next segment
            }
        }
    }
    clips.add(clip); // add last segment
    return clips;
}

From source file:tr.com.aliok.jsExperiments.service.WordService.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    final PrintWriter writer = resp.getWriter();

    final LinkedList<Word> shuffledWords = getShuffledWords(req);
    final Word word = shuffledWords.pop();

    writer.printf("{ \"word\" : \"%s\", \"translation\" : \"%s\", \"article\" : \"%s\" }", word.getWord(),
            word.getTranslation(), word.getArticle().getText());

    writer.flush();//from   ww  w.  j  av  a2s .  co  m
}