Example usage for java.util LinkedList removeFirst

List of usage examples for java.util LinkedList removeFirst

Introduction

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

Prototype

public E removeFirst() 

Source Link

Document

Removes and returns the first element from this list.

Usage

From source file:com.offbynull.voip.kademlia.GraphHelper.java

private ArrayList<BitString> removePrefixesForNextLevel(LinkedList<BitString> sortedPrefixes) {
    ArrayList<BitString> ret = new ArrayList<>();

    if (sortedPrefixes.isEmpty()) {
        return ret;
    }/*from   w w w .  j  a  v a 2s .c om*/

    int hitCount = sortedPrefixes.peekFirst().getBitLength();

    while (!sortedPrefixes.isEmpty()) {
        if (sortedPrefixes.peekFirst().getBitLength() == hitCount) {
            ret.add(sortedPrefixes.removeFirst());
        } else {
            break;
        }
    }

    return ret;
}

From source file:org.apache.drill.exec.compile.ClassTransformer.java

public Class<?> getImplementationClass(final QueryClassLoader classLoader,
        final TemplateClassDefinition<?> templateDefinition, final String entireClass,
        final String materializedClassName) throws ClassTransformationException {
    // unfortunately, this hasn't been set up at construction time, so we have to do it here
    final ScalarReplacementOption scalarReplacementOption = ScalarReplacementOption
            .fromString(optionManager.getOption(SCALAR_REPLACEMENT_VALIDATOR));

    try {//from ww  w .jav  a 2  s.com
        final long t1 = System.nanoTime();
        final ClassSet set = new ClassSet(null, templateDefinition.getTemplateClassName(),
                materializedClassName);
        final byte[][] implementationClasses = classLoader.getClassByteCode(set.generated, entireClass);

        long totalBytecodeSize = 0;
        Map<String, Pair<byte[], ClassNode>> classesToMerge = Maps.newHashMap();
        for (byte[] clazz : implementationClasses) {
            totalBytecodeSize += clazz.length;
            final ClassNode node = AsmUtil.classFromBytes(clazz, ClassReader.EXPAND_FRAMES);
            if (!AsmUtil.isClassOk(logger, "implementationClasses", node)) {
                throw new IllegalStateException("Problem found with implementationClasses");
            }
            classesToMerge.put(node.name, Pair.of(clazz, node));
        }

        final LinkedList<ClassSet> names = Lists.newLinkedList();
        final Set<ClassSet> namesCompleted = Sets.newHashSet();
        names.add(set);

        while (!names.isEmpty()) {
            final ClassSet nextSet = names.removeFirst();
            if (namesCompleted.contains(nextSet)) {
                continue;
            }
            final ClassNames nextPrecompiled = nextSet.precompiled;
            final byte[] precompiledBytes = byteCodeLoader.getClassByteCodeFromPath(nextPrecompiled.clazz);
            final ClassNames nextGenerated = nextSet.generated;
            // keeps only classes that have not be merged
            Pair<byte[], ClassNode> classNodePair = classesToMerge.remove(nextGenerated.slash);
            final ClassNode generatedNode;
            if (classNodePair != null) {
                generatedNode = classNodePair.getValue();
            } else {
                generatedNode = null;
            }

            /*
             * TODO
             * We're having a problem with some cases of scalar replacement, but we want to get
             * the code in so it doesn't rot anymore.
             *
             *  Here, we use the specified replacement option. The loop will allow us to retry if
             *  we're using TRY.
             */
            MergedClassResult result = null;
            boolean scalarReplace = scalarReplacementOption != ScalarReplacementOption.OFF
                    && entireClass.length() < MAX_SCALAR_REPLACE_CODE_SIZE;
            while (true) {
                try {
                    result = MergeAdapter.getMergedClass(nextSet, precompiledBytes, generatedNode,
                            scalarReplace);
                    break;
                } catch (RuntimeException e) {
                    // if we had a problem without using scalar replacement, then rethrow
                    if (!scalarReplace) {
                        throw e;
                    }

                    // if we did try to use scalar replacement, decide if we need to retry or not
                    if (scalarReplacementOption == ScalarReplacementOption.ON) {
                        // option is forced on, so this is a hard error
                        throw e;
                    }

                    /*
                     * We tried to use scalar replacement, with the option to fall back to not using it.
                     * Log this failure before trying again without scalar replacement.
                     */
                    logger.info("scalar replacement failure (retrying)\n", e);
                    scalarReplace = false;
                }
            }

            for (String s : result.innerClasses) {
                s = s.replace(DrillFileUtils.SEPARATOR_CHAR, '.');
                names.add(nextSet.getChild(s));
            }
            classLoader.injectByteCode(nextGenerated.dot, result.bytes);
            namesCompleted.add(nextSet);
        }

        // adds byte code of the classes that have not been merged to make them accessible for outer class
        for (Map.Entry<String, Pair<byte[], ClassNode>> clazz : classesToMerge.entrySet()) {
            classLoader.injectByteCode(clazz.getKey().replace(DrillFileUtils.SEPARATOR_CHAR, '.'),
                    clazz.getValue().getKey());
        }
        Class<?> c = classLoader.findClass(set.generated.dot);
        if (templateDefinition.getExternalInterface().isAssignableFrom(c)) {
            logger.debug("Compiled and merged {}: bytecode size = {}, time = {} ms.", c.getSimpleName(),
                    DrillStringUtils.readable(totalBytecodeSize),
                    (System.nanoTime() - t1 + 500_000) / 1_000_000);
            return c;
        }

        throw new ClassTransformationException("The requested class did not implement the expected interface.");
    } catch (CompileException | IOException | ClassNotFoundException e) {
        throw new ClassTransformationException(
                String.format("Failure generating transformation classes for value: \n %s", entireClass), e);
    }
}

From source file:org.apache.camel.impl.MainSupport.java

/**
 * Parses the command line arguments/* w  ww  .ja  v  a 2 s  .  c  o  m*/
 */
public void parseArguments(String[] arguments) {
    LinkedList<String> args = new LinkedList<String>(Arrays.asList(arguments));

    boolean valid = true;
    while (!args.isEmpty()) {
        String arg = args.removeFirst();

        boolean handled = false;
        for (Option option : options) {
            if (option.processOption(arg, args)) {
                handled = true;
                break;
            }
        }
        if (!handled) {
            System.out.println("Unknown option: " + arg);
            System.out.println();
            valid = false;
            break;
        }
    }
    if (!valid) {
        showOptions();
        completed();
    }
}

From source file:com.rapidminer.operator.preprocessing.discretization.MinimalEntropyDiscretization.java

private ArrayList<Double> getSplitpoints(LinkedList<double[]> startPartition, Attribute label) {
    LinkedList<LinkedList<double[]>> border = new LinkedList<LinkedList<double[]>>();
    ArrayList<Double> result = new ArrayList<Double>();
    border.addLast(startPartition);// ww w  .  j  ava  2s . co  m
    while (!border.isEmpty()) {
        LinkedList<double[]> currentPartition = border.removeFirst();
        Double splitpoint = this.getMinEntropySplitpoint(currentPartition, label);
        if (splitpoint != null) {
            result.add(splitpoint);
            double splitValue = splitpoint.doubleValue();
            LinkedList<double[]> newPartition1 = new LinkedList<double[]>();
            LinkedList<double[]> newPartition2 = new LinkedList<double[]>();
            Iterator<double[]> it = currentPartition.iterator();
            while (it.hasNext()) { // Create new partitions.
                double[] attributeLabelPair = it.next();
                if (attributeLabelPair[0] <= splitValue) {
                    newPartition1.addLast(attributeLabelPair);
                } else {
                    newPartition2.addLast(attributeLabelPair);
                }
            }
            border.addLast(newPartition1);
            border.addLast(newPartition2);
        }
    }
    return result; // Empty ArrayList if no Splitpoint could be found.

}

From source file:com.hp.alm.ali.idea.progress.IndicatingOutputStreamTest.java

@Test
public void testReporting() throws IOException {
    final LinkedList<Double> fractions = new LinkedList<Double>();
    fractions.add(0.25);/*  w  w w  .  j  a va 2 s  .  c o m*/
    fractions.add(0.75);
    fractions.add(0.80);
    fractions.add(1.0);

    handler.async(4);
    IndicatingOutputStream ios = new IndicatingOutputStream(file, 20, new ProgressIndicatorBase() {
        @Override
        public void setFraction(final double fraction) {
            handler.done(new Runnable() {
                @Override
                public void run() {
                    Assert.assertEquals(fractions.removeFirst(), (Double) fraction);
                }
            });
        }
    });
    byte[] buf0 = "1234\n".getBytes();
    byte[] buf1 = "123456789\n".getBytes();
    byte[] buf2 = "678\n".getBytes();

    ios.write(buf0);
    ios.write(buf1);
    ios.write('5');
    ios.write(buf2);
    ios.close();

    Assert.assertEquals("1234\n123456789\n5678\n", FileUtils.readFileToString(file));
}

From source file:com.kse.bigdata.file.SequenceSampler.java

public LinkedList<Sequence> getRandomSample() {
    System.out.println("Sampling Start...");
    System.out.println("Sample Size is  " + SAMPLE_SIZE);

    try {/* w  ww . j  a  v  a2  s  .  c  om*/
        FileSystem fs = FileSystem.get(new Configuration());
        BufferedReader fileReader = new BufferedReader(new InputStreamReader(fs.open(sampleFile)));
        LinkedList<Double> deque = new LinkedList<Double>();
        String line;
        int[] sampleIndexes = getRandomSampleIndexArray();
        int counter = -1;

        while ((line = fileReader.readLine()) != null) {
            counter++;

            deque.add(extractValidInformation(line));

            if (deque.size() == Sequence.SIZE_OF_SEQUENCE) {

                for (int sampleIndex : sampleIndexes)
                    if (sampleIndex == counter)
                        randomSamples.add(new Sequence(deque));

                deque.removeFirst();
            }

            if (randomSamples.size() == SAMPLE_SIZE)
                return randomSamples;

        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return this.randomSamples;
}

From source file:org.apache.metron.profiler.client.window.WindowProcessor.java

/**
 * Read the specifier params off the stack in FIFO order until we get to the specifier marker.  Now we can
 * construct the specifier, which is a Function which constructs a Selector Predicate based on the args
 * passed to the selector e.g. holidays:us:nyc would have 2 args us and nyc.
 *
 * @param ctx//from   w  w  w  .j  a  v  a2 s  .  co  m
 */
@Override
public void exitSpecifier(WindowParser.SpecifierContext ctx) {
    LinkedList<String> args = new LinkedList<>();

    while (true) {
        Token<?> token = stack.pop();
        if (token == SPECIFIER_MARKER) {
            break;
        } else {
            args.addFirst((String) token.getValue());
        }
    }
    String specifier = args.removeFirst();
    List<String> arg = args.size() > 0 ? args : new ArrayList<>();
    Function<Long, Predicate<Long>> predicate = null;
    try {
        if (specifier.equals("THIS DAY OF THE WEEK") || specifier.equals("THIS DAY OF WEEK")) {
            predicate = now -> DayPredicates.dayOfWeekPredicate(DayPredicates.getDayOfWeek(now));
        } else {
            final Predicate<Long> dayOfWeekPredicate = DayPredicates.create(specifier, arg);
            predicate = now -> dayOfWeekPredicate;
        }
        stack.push(new Token<>(predicate, Function.class));
    } catch (Throwable t) {
        throwable = t;
    }
}

From source file:com.espertech.esper.example.stockticker.TestStockTickerMultithreaded.java

public void performTest(int numberOfThreads, int numberOfTicksToSend, int ratioPriceOutOfLimit,
        int numberOfSecondsWaitForCompletion) {
    final int totalNumTicks = numberOfTicksToSend + 2 * TestStockTickerGenerator.NUM_STOCK_NAMES;

    log.info(".performTest Generating data, numberOfTicksToSend=" + numberOfTicksToSend
            + "  ratioPriceOutOfLimit=" + ratioPriceOutOfLimit);

    StockTickerEventGenerator generator = new StockTickerEventGenerator();
    LinkedList stream = generator.makeEventStream(numberOfTicksToSend, ratioPriceOutOfLimit,
            TestStockTickerGenerator.NUM_STOCK_NAMES,
            StockTickerRegressionConstants.PRICE_LIMIT_PCT_LOWER_LIMIT,
            StockTickerRegressionConstants.PRICE_LIMIT_PCT_UPPER_LIMIT,
            StockTickerRegressionConstants.PRICE_LOWER_LIMIT, StockTickerRegressionConstants.PRICE_UPPER_LIMIT,
            true);/*from  w ww  . j  ava2 s .c om*/

    log.info(".performTest Send limit and initial tick events - singlethreaded");
    for (int i = 0; i < TestStockTickerGenerator.NUM_STOCK_NAMES * 2; i++) {
        Object theEvent = stream.removeFirst();
        epService.getEPRuntime().sendEvent(theEvent);
    }

    log.info(".performTest Loading thread pool work queue, numberOfRunnables=" + stream.size());

    ThreadPoolExecutor pool = new ThreadPoolExecutor(0, numberOfThreads, 99999, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());
    for (Object theEvent : stream) {
        SendEventRunnable runnable = new SendEventRunnable(epService, theEvent);
        pool.execute(runnable);
    }

    log.info(".performTest Starting thread pool, threads=" + numberOfThreads);
    pool.setCorePoolSize(numberOfThreads);

    log.info(".performTest Listening for completion");
    EPRuntimeUtil.awaitCompletion(epService.getEPRuntime(), totalNumTicks, numberOfSecondsWaitForCompletion, 1,
            10);

    pool.shutdown();

    // Check results : make sure the given ratio of out-of-limit stock prices was reported
    int expectedNumEmitted = (numberOfTicksToSend / ratioPriceOutOfLimit) + 1;
    assertTrue(listener.getSize() == expectedNumEmitted);

    log.info(".performTest Done test");
}

From source file:org.openanzo.glitter.query.Projection.java

private void initialize() throws UnnamedProjectionException {
    // determine if this is an aggregate
    if (!this.groupByVars.isEmpty()) {
        this.isAggregate = true;
    } else {/*from ww  w. j a v a2 s .  c o m*/
        // see if any aggregate functions are involved, which means we're grouping in one big (happy) group
        LinkedList<Expression> expressions = new LinkedList<Expression>(this.projectedExpressions);
        while (!expressions.isEmpty()) {
            Expression e = expressions.removeFirst();
            if (e instanceof FunctionCall) {
                FunctionCall fc = (FunctionCall) e;
                if (fc.getFunction() instanceof AggregateFunction) {
                    this.isAggregate = true;
                    break;
                }
                expressions.addAll(fc.getArguments());
            }
        }
    }
    // check that we have an output name for every projected expression
    if (this.projectedAs.size() < this.projectedExpressions.size())
        throw new UnnamedProjectionException(this.projectedExpressions.get(this.projectedAs.size()));
    if (this.projectedAs.size() > this.projectedExpressions.size())
        throw new GlitterRuntimeException(ExceptionConstants.GLITTER.MORE_NAMES);
    int i;
    if ((i = this.projectedAs.indexOf(null)) != -1)
        throw new UnnamedProjectionException(this.projectedExpressions.get(i));
    for (i = 0; i < this.projectedAs.size(); i++)
        this.aliasMap.put(this.projectedAs.get(i), this.projectedExpressions.get(i));
}

From source file:org.xchain.namespaces.jsl.AbstractTemplateCommand.java

private final void popElementOutputState() {
    // get the stack for the current thread.
    LinkedList<ElementOutputState[]> stack = elementOutputStateStackTL.get();

    // if there was not a stack, then we are in an illegal state.
    if (stack == null) {
        throw new IllegalStateException("popElementOutputState() called when there was not a current stack.");
    }/*from   w ww .  j  a  v  a2  s . c o  m*/

    // remove the state array from the stack.
    stack.removeFirst();

    // if the stack is now empty, clean the thread local up.
    if (stack.isEmpty()) {
        elementOutputStateStackTL.remove();
    }

}