Example usage for java.util LinkedList addLast

List of usage examples for java.util LinkedList addLast

Introduction

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

Prototype

public void addLast(E e) 

Source Link

Document

Appends the specified element to the end of this list.

Usage

From source file:com.github.jknack.amd4j.Amd4j.java

/**
 * Resolve a candidate uri to an existing uri. We need this bc, dependencies might or mightn't
 * have a file extension, or they might have a '.' in the file's name.
 *
 * @param loader The resource loader./*from w w w  .  j a  va 2  s.  c  o m*/
 * @param uri The candidate uri.
 * @return An existing uri for the candidate uri.
 * @throws IOException If the uri can't be resolved.
 */
private static ResourceURI resolve(final ResourceLoader loader, final ResourceURI uri) throws IOException {
    String path = uri.getPath();
    LinkedList<ResourceURI> candidates = new LinkedList<ResourceURI>();
    candidates.add(uri);
    ResourceURI alternative = ResourceURI.create(uri.toString() + ".js");
    if (isEmpty(getExtension(path))) {
        candidates.addFirst(alternative);
    } else {
        candidates.addLast(alternative);
    }
    for (ResourceURI candidate : candidates) {
        if (loader.exists(candidate)) {
            return candidate;
        }
    }
    // force a file not found exception
    throw new FileNotFoundException(uri.toString());
}

From source file:uniol.apt.analysis.cycles.lts.AllSmallCyclesHavePVOne.java

/**
 * Recursive implementation of the depth-first search that looks for cycles with a Parikh vector of at most all
 * ones.//w  w w .  j a  v a 2  s . c  o  m
 * @param ts The transition system to examine
 * @param state The next state that should be followed.
 * @param firedEvents Set of events which were already fired on the path from the initial state.
 * @param arcsFollowed List of arcs that were followed from the initial state to this state.
 * @return A pair were the first element is true if a cycle with Parikh vector 1 was found and the second
 * element is either null or a cycle with a smaller Parikh vector.
 */
static private Pair<Boolean, List<Arc>> checkPhase1(TransitionSystem ts, State state, Set<String> firedEvents,
        LinkedList<Arc> arcsFollowed) {
    boolean success = false;
    for (Arc arc : state.getPostsetEdges()) {
        if (firedEvents.contains(arc.getLabel()))
            continue;

        firedEvents.add(arc.getLabel());
        arcsFollowed.addLast(arc);

        State target = arc.getTarget();
        if (target.equals(ts.getInitialState())) {
            if (firedEvents.containsAll(ts.getAlphabet())) {
                // Found a suitable cycle!
                success = true;
            } else {
                // Found a counter-example
                return new Pair<Boolean, List<Arc>>(false, arcsFollowed);
            }
        } else {
            // Recurse to this new state
            Pair<Boolean, List<Arc>> result = checkPhase1(ts, target, firedEvents, arcsFollowed);
            if (result.getSecond() != null)
                return result;
            success = success || result.getFirst();
        }

        // Undo the modifications done above
        boolean r = firedEvents.remove(arc.getLabel());
        assert r == true;
        Arc last = arcsFollowed.removeLast();
        assert last == arc;
    }
    return new Pair<>(success, null);
}

From source file:Main.java

/**
 * Takes a number of tags of name 'name' that are children of 'root', and
 * looks for attributes of 'attrib' on them.  Converts attributes to an
 * int and returns in an array.//from  w w  w .java  2 s.com
 */
public static int[] getElementArrayInt(Element root, String name, String attrib) {
    if (root == null)
        return null;

    NodeList nl = root.getChildNodes();
    LinkedList<Integer> elementCache = new LinkedList<Integer>();
    int size = nl.getLength();

    for (int i = 0; i < size; i++) {
        Node node = nl.item(i);
        if (!(node instanceof Element))
            continue;
        Element ele = (Element) node;
        if (!ele.getTagName().equals(name))
            continue;

        String valS = ele.getAttribute(attrib);
        int eleVal = 0;
        try {
            eleVal = Integer.parseInt(valS);
        } catch (Exception e) {
        }

        elementCache.addLast(new Integer(eleVal));
    }

    int[] retArr = new int[elementCache.size()];
    Iterator<Integer> it = elementCache.iterator();
    int idx = 0;
    while (it.hasNext()) {
        retArr[idx++] = it.next().intValue();
    }

    return retArr;
}

From source file:ubic.pubmedgate.GateInterface.java

public static List<ConnectionsDocument> getDocuments(Corpus sourceCorp) {
    LinkedList<ConnectionsDocument> result = new LinkedList<ConnectionsDocument>();
    int count = 0;
    for (Object o : sourceCorp) {
        if (count++ % 500 == 0)
            log.info(count + " of " + sourceCorp.getName() + " loaded");
        Document doc = (Document) (o);
        result.addLast(new ConnectionsDocument(doc));
    }/*from w  w  w. j  a va  2 s . co  m*/
    return result;
}

From source file:com.github.jknack.handlebars.internal.TemplateBuilder.java

/**
 * Creates a {@link Template} that detects recursively calls.
 *
 * @param source The template source.//  w  w  w .  j av a2s  .com
 * @param template The original template.
 * @return A new {@link Template} that detects recursively calls.
 */
private static Template infiniteLoop(final TemplateSource source, final BaseTemplate template) {
    return new ForwardingTemplate(template) {
        @Override
        protected void beforeApply(final Context context) {
            LinkedList<TemplateSource> invocationStack = context.data(Context.INVOCATION_STACK);
            invocationStack.addLast(source);
        }

        @Override
        protected void afterApply(final Context context) {
            LinkedList<TemplateSource> invocationStack = context.data(Context.INVOCATION_STACK);
            if (!invocationStack.isEmpty()) {
                invocationStack.removeLast();
            }
        }
    };
}

From source file:edu.cmu.sv.modelinference.eventtool.classification.Clusterer1D.java

private static ClassificationResult buildResult(List<? extends Cluster<DataWrapper>> results) {
    LinkedList<EventClass> clusters = new LinkedList<>();
    for (int i = 0; i < results.size(); i++) {
        TreeMultiset<Event> clusterDataPoints = TreeMultiset.create(new Comparator<Event>() {
            @Override/*from w w  w. j  ava  2s  . c  om*/
            public int compare(Event o1, Event o2) {
                return Double.compare(o1.getFeature().getData(), o2.getFeature().getData());
            }
        });
        for (DataWrapper dataWrapper : results.get(i).getPoints()) {
            clusterDataPoints.add(dataWrapper.getWrappedData());
        }
        clusters.addLast(new EventClass(clusterDataPoints));
    }
    return new ClassificationResult(clusters);
}

From source file:org.nuxeo.ecm.platform.sync.utils.ImportUtils.java

/**
 * Returns the list of transition names to follow to go from one particular state to another.
 *
 * @param lifeCycle - the lifecycle//from  ww w .ja  v a2  s . c  o  m
 * @param origState - the origin state
 * @param destState - the destination state
 * @return the list of transition names
 */
public static List<String> getLifeCycleTransitions(LifeCycle lifeCycle, String origState, String destState)
        throws LifeCycleException {
    List<String> path = new ArrayList<String>();
    LinkedList<List<String>> paths = new LinkedList<List<String>>();
    paths.add(path);

    LinkedList<String> fifo = new LinkedList<String>();
    fifo.add(origState);

    ArrayList<String> marked = new ArrayList<String>();
    marked.add(origState);

    while (!fifo.isEmpty()) {
        String state = fifo.removeFirst();
        path = paths.removeFirst();
        if (state.equals(destState)) {
            break;
        }
        for (String transitionName : lifeCycle.getAllowedStateTransitionsFrom(state)) {
            LifeCycleTransition transition = lifeCycle.getTransitionByName(transitionName);
            String nextState = transition.getDestinationStateName();
            if (!marked.contains(nextState)) {
                marked.add(nextState);
                fifo.addLast(nextState);
                List<String> nextPath = new ArrayList<String>(path);
                nextPath.add(transitionName);
                paths.addLast(nextPath);
            }
        }
    }

    return path;
}

From source file:hr.fer.tel.rovkp.homework03.task01.JokesCollection.java

public static Map<Integer, String> parseInputFile(String file) throws IOException {
    Path filePath = Paths.get(file);
    Map<Integer, String> results = new HashMap<>();

    List<String> currentJoke = new LinkedList<>();
    LinkedList<Integer> ids = new LinkedList<>();

    try (Stream<String> stream = Files.lines(filePath)) {
        stream.forEach(line -> {//from   w w  w  . j a  v  a  2s .c om
            if (line == null)
                return;
            line = line.trim();

            if (line.isEmpty() && !currentJoke.isEmpty()) {
                int currentId = ids.getLast();
                String jokeText = StringUtils.join(currentJoke, "\n");
                jokeText = StringEscapeUtils.unescapeXml(jokeText.toLowerCase().replaceAll("\\<.*?\\>", ""));
                if (results.putIfAbsent(currentId, jokeText) != null)
                    System.err.println("Joke with id " + currentId + "already exists. Not overwriting.");
            } else if (line.matches("^[0-9]+:$")) {
                ids.addLast(Integer.parseInt(line.substring(0, line.length() - 1)));
                currentJoke.clear();
            } else {
                currentJoke.add(line);
            }
        });
    }

    return results;
}

From source file:org.squale.squaleweb.util.SqualeWebActionUtils.java

/**
 * Retourne une liste htrogne sous la forme d'une liste de String.
 * //  w  w  w  . j av  a  2  s . c o m
 * @param pList la liste  transformer.
 * @return une liste de String.
 */
public static List getAsStringsList(final List pList) {
    LinkedList result = null;
    if (null != pList) {
        result = new LinkedList();
        Iterator it = pList.iterator();
        Object value = null;
        // Parcours de la collection et conversion de chaque valeur
        while (it.hasNext()) {
            value = it.next();
            if (null != value) {
                // Conversion spcifique pour un nombre flottant
                if (value.getClass().equals(Float.class)) {
                    result.addLast(formatFloat((Float) value));
                } else {
                    result.addLast(value.toString());
                }
            } else {
                // On conserve la valeur null initiale
                result.addLast(null);
            }
        }
    }
    return result;
}

From source file:com.ibm.bi.dml.runtime.controlprogram.context.SparkExecutionContext.java

/**
 * Utility method for creating an RDD out of an in-memory matrix block.
 * /*from   w w  w. j a v a2 s .  c  o m*/
 * @param sc
 * @param block
 * @return
 * @throws DMLUnsupportedOperationException 
 * @throws DMLRuntimeException 
 */
public static JavaPairRDD<MatrixIndexes, MatrixBlock> toJavaPairRDD(JavaSparkContext sc, MatrixBlock src,
        int brlen, int bclen) throws DMLRuntimeException, DMLUnsupportedOperationException {
    LinkedList<Tuple2<MatrixIndexes, MatrixBlock>> list = new LinkedList<Tuple2<MatrixIndexes, MatrixBlock>>();

    if (src.getNumRows() <= brlen && src.getNumColumns() <= bclen) {
        list.addLast(new Tuple2<MatrixIndexes, MatrixBlock>(new MatrixIndexes(1, 1), src));
    } else {
        boolean sparse = src.isInSparseFormat();

        //create and write subblocks of matrix
        for (int blockRow = 0; blockRow < (int) Math.ceil(src.getNumRows() / (double) brlen); blockRow++)
            for (int blockCol = 0; blockCol < (int) Math
                    .ceil(src.getNumColumns() / (double) bclen); blockCol++) {
                int maxRow = (blockRow * brlen + brlen < src.getNumRows()) ? brlen
                        : src.getNumRows() - blockRow * brlen;
                int maxCol = (blockCol * bclen + bclen < src.getNumColumns()) ? bclen
                        : src.getNumColumns() - blockCol * bclen;

                MatrixBlock block = new MatrixBlock(maxRow, maxCol, sparse);

                int row_offset = blockRow * brlen;
                int col_offset = blockCol * bclen;

                //copy submatrix to block
                src.sliceOperations(row_offset, row_offset + maxRow - 1, col_offset, col_offset + maxCol - 1,
                        block);

                //append block to sequence file
                MatrixIndexes indexes = new MatrixIndexes(blockRow + 1, blockCol + 1);
                list.addLast(new Tuple2<MatrixIndexes, MatrixBlock>(indexes, block));
            }
    }

    return sc.parallelizePairs(list);
}