Example usage for java.util ArrayDeque ArrayDeque

List of usage examples for java.util ArrayDeque ArrayDeque

Introduction

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

Prototype

public ArrayDeque() 

Source Link

Document

Constructs an empty array deque with an initial capacity sufficient to hold 16 elements.

Usage

From source file:alluxio.underfs.swift.SwiftUnderFileSystem.java

/**
 * Lists the files or folders which match the given prefix using pagination.
 *
 * @param prefix the prefix to match/* w  ww . j a v a2  s.c  o m*/
 * @param recursive whether to do a recursive listing
 * @return a collection of the files or folders matching the prefix, or null if not found
 * @throws IOException if path is not accessible, e.g. network issues
 */
private Collection<DirectoryOrObject> listInternal(final String prefix, boolean recursive) throws IOException {
    // TODO(adit): UnderFileSystem interface should be changed to support pagination
    ArrayDeque<DirectoryOrObject> results = new ArrayDeque<>();
    Container container = mAccount.getContainer(mContainerName);
    PaginationMap paginationMap = container.getPaginationMap(prefix, LISTING_LENGTH);
    for (int page = 0; page < paginationMap.getNumberOfPages(); page++) {
        if (!recursive) {
            // If not recursive, use delimiter to limit results fetched
            results.addAll(container.listDirectory(paginationMap.getPrefix(), PATH_SEPARATOR_CHAR,
                    paginationMap.getMarker(page), paginationMap.getPageSize()));
        } else {
            results.addAll(container.list(paginationMap, page));
        }
    }
    return results;
}

From source file:com.datastax.loader.CqlDelimLoad.java

public boolean run(String[] args)
        throws IOException, ParseException, InterruptedException, ExecutionException, KeyStoreException,
        NoSuchAlgorithmException, KeyManagementException, CertificateException, UnrecoverableKeyException {
    if (false == parseArgs(args)) {
        System.err.println("Bad arguments");
        System.err.println(usage());
        return false;
    }/*from ww  w .j  av a 2  s. c o  m*/

    // Setup
    if (false == setup())
        return false;

    // open file
    Deque<File> fileList = new ArrayDeque<File>();
    File infile = null;
    File[] inFileList = null;
    boolean onefile = true;
    if (STDIN.equalsIgnoreCase(filename)) {
        infile = null;
    } else {
        infile = new File(filename);
        if (infile.isFile()) {
        } else {
            inFileList = infile.listFiles();
            if (inFileList.length < 1)
                throw new IOException("directory is empty");
            onefile = false;
            Arrays.sort(inFileList, new Comparator<File>() {
                public int compare(File f1, File f2) {
                    return f1.getName().compareTo(f2.getName());
                }
            });
            for (int i = 0; i < inFileList.length; i++)
                fileList.push(inFileList[i]);
        }
    }

    // Launch Threads
    ExecutorService executor;
    long total = 0;
    if (onefile) {
        // One file/stdin to process
        executor = Executors.newSingleThreadExecutor();
        Callable<Long> worker = new CqlDelimLoadTask(cqlSchema, delimiter, charsPerColumn, nullString,
                commentString, dateFormatString, localDateFormatString, boolStyle, locale, maxErrors, skipRows,
                skipCols, maxRows, badDir, infile, session, consistencyLevel, numFutures, batchSize, numRetries,
                queryTimeout, maxInsertErrors, successDir, failureDir, nullsUnset, format, keyspace, table);
        Future<Long> res = executor.submit(worker);
        total = res.get();
        executor.shutdown();
    } else {
        executor = Executors.newFixedThreadPool(numThreads);
        Set<Future<Long>> results = new HashSet<Future<Long>>();
        while (!fileList.isEmpty()) {
            File tFile = fileList.pop();
            Callable<Long> worker = new CqlDelimLoadTask(cqlSchema, delimiter, charsPerColumn, nullString,
                    commentString, dateFormatString, localDateFormatString, boolStyle, locale, maxErrors,
                    skipRows, skipCols, maxRows, badDir, tFile, session, consistencyLevel, numFutures,
                    batchSize, numRetries, queryTimeout, maxInsertErrors, successDir, failureDir, nullsUnset,
                    format, keyspace, table);
            results.add(executor.submit(worker));
        }
        executor.shutdown();
        for (Future<Long> res : results)
            total += res.get();
    }

    // Cleanup
    cleanup();
    //System.err.println("Total rows inserted: " + total);

    return true;
}

From source file:com.vgi.mafscaling.OpenLoop.java

protected void loadLogFile() {
    fileChooser.setMultiSelectionEnabled(true);
    if (JFileChooser.APPROVE_OPTION != fileChooser.showOpenDialog(this))
        return;//from   w ww.  j  av  a 2  s .  c o m
    boolean isPolSet = polfTable.isSet();
    File[] files = fileChooser.getSelectedFiles();
    for (File file : files) {
        BufferedReader br = null;
        ArrayDeque<String[]> buffer = new ArrayDeque<String[]>();
        try {
            br = new BufferedReader(new FileReader(file.getAbsoluteFile()));
            String line = br.readLine();
            if (line != null) {
                String[] elements = line.split("(\\s*)?,(\\s*)?", -1);
                getColumnsFilters(elements, false);

                boolean resetColumns = false;
                if (logThtlAngleColIdx >= 0 || logAfLearningColIdx >= 0 || logAfCorrectionColIdx >= 0
                        || logMafvColIdx >= 0 || logAfrColIdx >= 0 || logRpmColIdx >= 0 || logLoadColIdx >= 0
                        || logCommandedAfrCol >= 0) {
                    if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null,
                            "Would you like to reset column names or filter values?", "Columns/Filters Reset",
                            JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE))
                        resetColumns = true;
                }

                if (resetColumns || logThtlAngleColIdx < 0 || logAfLearningColIdx < 0
                        || logAfCorrectionColIdx < 0 || logMafvColIdx < 0 || logAfrColIdx < 0
                        || logRpmColIdx < 0 || logLoadColIdx < 0 || (logCommandedAfrCol < 0 && !isPolSet)) {
                    ColumnsFiltersSelection selectionWindow = new OLColumnsFiltersSelection(isPolSet);
                    if (!selectionWindow.getUserSettings(elements) || !getColumnsFilters(elements, isPolSet))
                        return;
                }

                String[] flds;
                String[] afrflds;
                boolean wotFlag = true;
                boolean foundWot = false;
                double throttle;
                double stft;
                double ltft;
                double afr;
                double rpm;
                double load;
                double mafv;
                double cmdafr = 0;
                double afrErr = 0;
                int skipRowCount = 0;
                int row = 0;
                int i = 0;
                int j = 0;
                for (; i < runTables.length; ++i) {
                    if (runTables[i].getValueAt(0, 0).toString().isEmpty())
                        break;
                }
                if (i == runTables.length)
                    return;
                setCursor(new Cursor(Cursor.WAIT_CURSOR));
                for (int k = 0; k <= afrRowOffset && line != null; ++k) {
                    line = br.readLine();
                    if (line != null)
                        buffer.addFirst(line.split(",", -1));
                }
                while (line != null && buffer.size() > afrRowOffset) {
                    afrflds = buffer.getFirst();
                    flds = buffer.removeLast();
                    line = br.readLine();
                    if (line != null)
                        buffer.addFirst(line.split(",", -1));

                    try {
                        throttle = Double.valueOf(flds[logThtlAngleColIdx]);
                        if (row == 0 && throttle < 99)
                            wotFlag = false;
                        if (throttle < wotPoint) {
                            if (wotFlag == true) {
                                wotFlag = false;
                                skipRowCount = 0;
                                j -= 1;
                                while (j > 0 && skipRowCount < skipRowsOnTransition) {
                                    runTables[i].setValueAt("", j, 0);
                                    runTables[i].setValueAt("", j, 1);
                                    runTables[i].setValueAt("", j, 2);
                                    skipRowCount += 1;
                                    j -= 1;
                                }
                                skipRowCount = 0;
                            }
                        } else {
                            if (wotFlag == false) {
                                wotFlag = true;
                                skipRowCount = 0;
                                if (foundWot) {
                                    i += 1;
                                    if (i == runTables.length)
                                        return;
                                }
                                if (row > 0)
                                    j = 0;
                            }
                            if (skipRowCount >= skipRowsOnTransition) {
                                mafv = Double.valueOf(flds[logMafvColIdx]);
                                if (minMafV <= mafv) {
                                    foundWot = true;
                                    stft = Double.valueOf(flds[logAfCorrectionColIdx]);
                                    ltft = Double.valueOf(flds[logAfLearningColIdx]);
                                    afr = Double.valueOf(afrflds[logAfrColIdx]);
                                    rpm = Double.valueOf(flds[logRpmColIdx]);
                                    load = Double.valueOf(flds[logLoadColIdx]);

                                    afr = afr / ((100.0 - (ltft + stft)) / 100.0);

                                    if (logCommandedAfrCol >= 0)
                                        cmdafr = Double.valueOf(flds[logCommandedAfrCol]);
                                    else if (isPolSet)
                                        cmdafr = Utils.calculateCommandedAfr(rpm, load, minWotEnrichment,
                                                polfTable);
                                    else {
                                        JOptionPane.showMessageDialog(null,
                                                "Please set either \"Commanded AFR\" column or \"Primary Open Loop Fueling\" table",
                                                "Error", JOptionPane.ERROR_MESSAGE);
                                        return;
                                    }

                                    afrErr = (afr - cmdafr) / cmdafr * 100.0;
                                    if (Math.abs(afrErr) <= afrErrPrct) {
                                        Utils.ensureRowCount(j + 1, runTables[i]);
                                        runTables[i].setValueAt(rpm, j, 0);
                                        runTables[i].setValueAt(mafv, j, 1);
                                        runTables[i].setValueAt(afrErr, j, 2);
                                        j += 1;
                                    }
                                }
                            }
                            skipRowCount += 1;
                        }
                    } catch (NumberFormatException e) {
                        logger.error(e);
                        JOptionPane.showMessageDialog(null,
                                "Error parsing number at " + file.getName() + " line " + (row + 1) + ": " + e,
                                "Error processing file", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    row += 1;
                }

                if (!foundWot) {
                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                    JOptionPane.showMessageDialog(null, "Sorry, no WOT pulls were found in the log file",
                            "No WOT data", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        } catch (Exception e) {
            logger.error(e);
            JOptionPane.showMessageDialog(null, e, "Error opening file", JOptionPane.ERROR_MESSAGE);
        } finally {
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        }
    }
}

From source file:sadl.models.pdrta.PDRTA.java

@Override
public int getTransitionCount() {
    int result = 0;
    final Queue<PDRTAState> q = new ArrayDeque<>();
    final Set<PDRTAState> found = new HashSet<>();
    q.add(root);/*  ww  w  . j  a  va  2 s. c  o  m*/
    found.add(root);
    while (!q.isEmpty()) {
        final PDRTAState s = q.remove();
        for (int i = 0; i < input.getAlphSize(); i++) {
            final Set<Entry<Integer, Interval>> ins = s.getIntervals(i).entrySet();
            for (final Entry<Integer, Interval> eIn : ins) {
                final Interval in = eIn.getValue();
                final PDRTAState t = in.getTarget();
                if (t != null) {
                    result++;
                }
            }
        }
    }
    return result;
}

From source file:org.apache.metron.stellar.common.StellarCompiler.java

private void exitLambda(boolean hasArgs) {
    final FrameContext.Context context = getArgContext();
    Token<?> t = expression.tokenDeque.pop();
    final Deque<Token<?>> instanceDeque = new ArrayDeque<>();
    for (; !expression.tokenDeque.isEmpty() && t != EXPRESSION_REFERENCE; t = expression.tokenDeque.pop()) {
        instanceDeque.addLast(t);//from w  ww . j  a va  2  s .  c om
    }
    final List<String> variables = hasArgs ? (List<String>) instanceDeque.removeLast().getValue()
            : new ArrayList<>();
    expression.tokenDeque.push(new Token<>((tokenDeque, state) -> {
        LambdaExpression expr = new LambdaExpression(variables, instanceDeque, state);
        tokenDeque.push(new Token<>(expr, Object.class, context));
    }, DeferredFunction.class, context));
}

From source file:nl.knaw.huc.di.tag.tagml.importer.TAGMLListener.java

private TAGMarkup removeFromOpenMarkup(MarkupNameContext ctx) {
    String markupName = ctx.name().getText();
    String extendedMarkupName = markupName;
    extendedMarkupName = withPrefix(ctx, extendedMarkupName);
    extendedMarkupName = withSuffix(ctx, extendedMarkupName);

    boolean isSuspend = ctx.prefix() != null && ctx.prefix().getText().equals(TAGML.SUSPEND_PREFIX);

    Set<String> layers = deduceLayers(ctx, markupName, extendedMarkupName);

    boolean layerSuffixNeeded = !(layers.size() == 1 && layers.iterator().next().equals(TAGML.DEFAULT_LAYER));
    String foundLayerSuffix = layerSuffixNeeded
            ? TAGML.DIVIDER/*  w  w w  . j  av  a 2 s  . c om*/
                    + layers.stream().filter(l -> !TAGML.DEFAULT_LAYER.equals(l)).sorted().collect(joining(","))
            : "";

    extendedMarkupName += foundLayerSuffix;
    removeFromMarkupStack2(extendedMarkupName, state.allOpenMarkup);
    TAGMarkup markup = null;
    for (String l : layers) {
        state.openMarkup.putIfAbsent(l, new ArrayDeque<>());
        Deque<TAGMarkup> markupStack = state.openMarkup.get(l);
        markup = removeFromMarkupStack(extendedMarkupName, markupStack);
        if (markup == null) {
            AtomicReference<String> emn = new AtomicReference<>(extendedMarkupName);
            boolean markupIsOpen = markupStack.stream().map(TAGMarkup::getExtendedTag)
                    .anyMatch(et -> emn.get().equals(et));
            if (!markupIsOpen) {
                errorListener.addError("%s Close tag <%s] found without corresponding open tag.",
                        errorPrefix(ctx), extendedMarkupName);
                return null;
            } else if (!isSuspend) {
                TAGMarkup expected = markupStack.peek();
                if (expected.hasTag(BRANCH)) {
                    errorListener.addBreakingError(
                            "%s Markup [%s> opened before branch %s, should not be closed in a branch.",
                            errorPrefix(ctx), extendedMarkupName, currentTextVariationState().branch + 1);
                }
                String hint = l.isEmpty() ? " Use separate layers to allow for overlap." : "";
                errorListener.addBreakingError("%s Close tag <%s] found, expected %s.%s", errorPrefix(ctx),
                        extendedMarkupName, closeTag(expected), hint);
                return null;
            } else {
                markup = removeFromMarkupStack2(extendedMarkupName, markupStack);
            }
        }
        document.closeMarkupInLayer(markup, l);
    }
    // for the last closing tag, close the markup for the default layer
    if (!layers.contains(DEFAULT_LAYER) && markup.getLayers().contains(DEFAULT_LAYER)) {
        Deque<TAGMarkup> markupDeque = state.openMarkup.get(DEFAULT_LAYER);
        removeFromMarkupStack(extendedMarkupName, markupDeque);
        document.closeMarkupInLayer(markup, DEFAULT_LAYER);
    }

    PrefixContext prefixNode = ctx.prefix();
    if (prefixNode != null) {
        String prefixNodeText = prefixNode.getText();
        if (prefixNodeText.equals(OPTIONAL_PREFIX)) {
            // optional
            // TODO

        } else if (prefixNodeText.equals(SUSPEND_PREFIX)) {
            // suspend
            for (String l : layers) {
                state.suspendedMarkup.putIfAbsent(l, new ArrayDeque<>());
                state.suspendedMarkup.get(l).add(markup);
            }
        }
    }
    state.eof = (markup.getDbId().equals(state.rootMarkupId));
    if (isSuspend && state.eof) {
        TAGMarkup rootMarkup = store.getMarkup(state.rootMarkupId);
        errorListener.addBreakingError("%s The root markup %s cannot be suspended.", errorPrefix(ctx),
                rootMarkup);
    }
    return markup;
}

From source file:com.facebook.litho.ComponentsPools.java

public static <E> ArrayDeque<E> acquireArrayDeque() {
    ArrayDeque<E> deque = ComponentsConfiguration.usePooling ? sArrayDequePool.acquire() : null;
    if (deque == null) {
        deque = new ArrayDeque<>();
    }/*from ww  w .j av  a2  s.  c o m*/
    return deque;
}

From source file:org.teavm.flavour.templates.parsing.Parser.java

private void pushVar(String name, ValueType type) {
    Deque<ValueType> stack = variables.get(name);
    if (stack == null) {
        stack = new ArrayDeque<>();
        variables.put(name, stack);/* w  w w  .  j a va 2 s. c o  m*/
    }
    stack.push(type);
}

From source file:alluxio.proxy.s3.S3RestServiceHandler.java

private List<URIStatus> listObjects(AlluxioURI uri, ListBucketOptions listBucketOptions)
        throws FileDoesNotExistException, IOException, AlluxioException {
    List<URIStatus> objects = new ArrayList<>();
    Queue<URIStatus> traverseQueue = new ArrayDeque<>();

    List<URIStatus> children;
    String prefix = listBucketOptions.getPrefix();
    if (prefix != null && prefix.contains(AlluxioURI.SEPARATOR)) {
        AlluxioURI prefixDirUri = new AlluxioURI(uri.getPath() + AlluxioURI.SEPARATOR
                + prefix.substring(0, prefix.lastIndexOf(AlluxioURI.SEPARATOR)));
        children = mFileSystem.listStatus(prefixDirUri);
    } else {//from w  w w. ja  v a  2s  .  com
        children = mFileSystem.listStatus(uri);
    }
    traverseQueue.addAll(children);
    while (!traverseQueue.isEmpty()) {
        URIStatus cur = traverseQueue.remove();
        if (!cur.isFolder()) {
            // Alluxio file is an object.
            objects.add(cur);
        } else if (!cur.getName().endsWith(Constants.S3_MULTIPART_TEMPORARY_DIR_SUFFIX)) {
            // The directory is not a temporary directory of multipart upload, list recursively.
            List<URIStatus> curChildren = mFileSystem.listStatus(new AlluxioURI(cur.getPath()));
            if (curChildren.isEmpty()) {
                // An empty Alluxio directory is considered as a valid object.
                objects.add(cur);
            } else {
                traverseQueue.addAll(curChildren);
            }
        }
    }
    return objects;
}

From source file:com.yangtsaosoftware.pebblemessenger.services.PebbleCenter.java

private List<PebbleMessage> splitPages(PebbleMessage tmpPM) {
    List<PebbleMessage> pmPages = new ArrayList<PebbleMessage>();
    String[] splitString = tmpPM.getAscMsg().split("\n");
    Constants.log(TAG_NAME, tmpPM.getAscMsg());
    for (String str : splitString) {
        Constants.log(TAG_NAME, "splitPages, deal:" + str);
    }//from www  .j av a  2 s  . c  om
    int pageCount = bigInt((float) splitString.length / (float) fLines);
    for (int page = 1; page <= pageCount; page++) {
        PebbleMessage itemPm = new PebbleMessage();
        itemPm.set_id(tmpPM.get_id());
        StringBuilder tmpSB = new StringBuilder();
        for (int line = (page - 1) * fLines; line < (page * fLines > splitString.length ? splitString.length
                : page * fLines); line++) {
            tmpSB.append(splitString[line]);
            tmpSB.append('\n');
        }
        itemPm.setAscMsg(tmpSB.toString());
        Deque<CharacterMatrix> itemDqCM = new ArrayDeque<CharacterMatrix>();
        while (!tmpPM.getCharacterQueue().isEmpty()) {
            CharacterMatrix tmpCM = tmpPM.getCharacterQueue().pollFirst();
            if (tmpCM.getPos()[0] >= (page - 1) * fLines && tmpCM.getPos()[0] <= page * fLines) {
                itemDqCM.add(tmpCM);
            } else {
                tmpPM.getCharacterQueue().addFirst(tmpCM);
                break;
            }
        }
        itemPm.setCharacterQueue(itemDqCM);
        pmPages.add(page - 1, itemPm);
    }
    return pmPages;
}