Example usage for java.util Deque getFirst

List of usage examples for java.util Deque getFirst

Introduction

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

Prototype

E getFirst();

Source Link

Document

Retrieves, but does not remove, the first element of this deque.

Usage

From source file:ocr.sapphire.image.EdgeBasedImagePreprocessor.java

/**
 * <p>Rotate the component so that the first point is the leftmost.</p>
 * <p>Normalization doesnot make difference when reverse the Fourier series
 * but neuron networks may "feel" easier to recorgnize normalized series.</p>
 * @param points//from w w w . j  a  v  a  2 s. c  o m
 * @return
 */
private static Deque<Point> normalize(Deque<Point> c) {
    double leftmost = Double.MAX_VALUE;
    for (Point p : c) {
        if (p.x < leftmost) {
            leftmost = p.x;
        }
    }
    while (c.getFirst().x > leftmost) {
        c.addLast(c.removeFirst());
    }
    return c;
}

From source file:ocr.sapphire.image.EdgeBasedImagePreprocessor.java

private Point[][] findEdgePoints(int[] edgeData) {
    List<Deque<Point>> components = new ArrayList<Deque<Point>>();
    // find close paths
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            if (edgeData[x + y * width] == BLACK && isBridge(edgeData, x, y)) {
                edgeData[x + y * width] = WHITE;
                Deque<Point> firstPart = null, secondPart = null;
                for (int k = 0; k < DX.length; k++) {
                    int x2 = x + DX[k];
                    int y2 = y + DY[k];
                    if (x2 < 0 || x2 >= width || y2 < 0 || y2 >= height) {
                        continue;
                    }/*from   w w w . jav a  2 s .  c om*/
                    if (edgeData[x2 + y2 * width] == BLACK) {
                        Deque<Point> points = findConnectedComponent(edgeData, x2, y2);
                        if (firstPart == null) {
                            firstPart = points;
                        } else {
                            secondPart = points;
                        }
                    }
                }
                firstPart.addFirst(new Point(x, y));
                if (secondPart != null) { // the path is not closed
                    join(firstPart, true, secondPart, true);
                }
                components.add(firstPart);
            }
        }
    }

    // remove contained components
    for (int i = 0; i < components.size() - 1; i++) {
        Rectangle r1 = getBounds(components.get(i));
        for (int j = i + 1; j < components.size();) {
            Rectangle r2 = getBounds(components.get(j));
            if (r1.contains(r2)) {
                components.remove(j);
            } else if (r2.contains(r1)) {
                components.set(i, components.get(j));
                components.remove(j);
            } else {
                j++;
            }
        }
    }

    // try to connect some paths
    int connectedCount;
    do {
        connectedCount = 0;
        for (int i = 0; i < components.size() - 1; i++) {
            for (int j = i + 1; j < components.size(); j++) {
                Deque<Point> a = components.get(i);
                Deque<Point> b = components.get(j);

                double d0 = d(a.getFirst(), a.getLast()) + d(b.getFirst(), b.getLast());
                double d1 = d(a.getFirst(), b.getFirst()) + d(a.getLast(), b.getLast());
                double d2 = d(a.getFirst(), b.getLast()) + d(a.getLast(), b.getFirst());
                double d3 = d(a.getFirst(), b.getFirst());
                double d4 = d(a.getFirst(), b.getLast());
                double d5 = d(a.getLast(), b.getFirst());
                double d6 = d(a.getLast(), b.getLast());

                if (d3 <= CLOSE_THRESHOLD && d3 <= d4) {
                    join(a, true, b, true);
                    components.remove(j);
                    connectedCount++;
                } else if (d4 <= CLOSE_THRESHOLD && d4 <= d3) {
                    join(a, true, b, false);
                    components.remove(j);
                    connectedCount++;
                } else if (d5 <= CLOSE_THRESHOLD && d5 <= d6) {
                    join(a, false, b, true);
                    components.remove(j);
                    connectedCount++;
                } else if (d6 <= CLOSE_THRESHOLD && d6 <= d5) {
                    join(a, false, b, false);
                    components.remove(j);
                    connectedCount++;
                } else if (d1 <= d0 && d1 <= d2) {
                    if (d3 < d6) {
                        join(a, true, b, true);
                    } else {
                        join(a, false, b, false);
                    }
                    components.remove(j);
                    connectedCount++;
                } else if (d2 <= d0 && d2 <= d1) {
                    if (d4 < d5) {
                        join(a, true, b, false);
                    } else {
                        join(a, false, b, true);
                    }
                    components.remove(j);
                    connectedCount++;
                }
            } // end of for j
        } // end of for i
    } while (connectedCount > 0);

    // choose (componentCount) biggest components
    SortedMap<Integer, Deque<Point>> componentMap = new TreeMap<Integer, Deque<Point>>();
    for (Deque<Point> c : components) {
        componentMap.put(-c.size(), c);
    }

    // remove noise
    boolean firstPoint = true;
    for (Iterator<Entry<Integer, Deque<Point>>> iterator = componentMap.entrySet().iterator(); iterator
            .hasNext();) {
        Entry<Integer, Deque<Point>> entry = iterator.next();
        Rectangle r = getBounds(entry.getValue());
        if (r.width <= 10 && r.height <= 10) {
            if (firstPoint) {
                firstPoint = false;
            } else {
                iterator.remove();
            }
        }
    }

    // convert components: normalize points, to array
    int foundComponentCount = Math.min(componentCount, componentMap.size());
    componentArr = new Point[foundComponentCount][];
    Rectangle r = getBounds(componentMap.get(componentMap.firstKey()));
    for (int c = 0; c < foundComponentCount; c++) {
        int key = componentMap.firstKey();
        componentArr[c] = new Point[componentMap.get(key).size()];
        normalize(componentMap.get(key)).toArray(componentArr[c]);
        componentMap.remove(key);

        for (int i = 0; i < componentArr[c].length; i++) {
            componentArr[c][i].x = (componentArr[c][i].x - r.x) / r.width;
            componentArr[c][i].y = (componentArr[c][i].y - r.y) / r.height;
        }
    }
    return componentArr;
}

From source file:org.alfresco.repo.content.transform.TransformerDebug.java

/**
 * Called to identify a transformer that cannot be used during working out
 * available transformers./*from  w w  w.ja va  2s.  c  o  m*/
 */
public void unavailableTransformer(ContentTransformer transformer, String sourceMimetype, String targetMimetype,
        long maxSourceSizeKBytes) {
    if (isEnabled()) {
        Deque<Frame> ourStack = ThreadInfo.getStack();
        Frame frame = ourStack.peek();

        if (frame != null) {
            Deque<String> isTransformableStack = ThreadInfo.getIsTransformableStack();
            String name = (!isTransformableStack.isEmpty()) ? isTransformableStack.getFirst()
                    : getName(transformer);
            boolean debug = (maxSourceSizeKBytes != 0);
            if (frame.unavailableTransformers == null) {
                frame.unavailableTransformers = new TreeSet<UnavailableTransformer>();
            }
            String priority = gePriority(transformer, sourceMimetype, targetMimetype);
            frame.unavailableTransformers
                    .add(new UnavailableTransformer(name, priority, maxSourceSizeKBytes, debug));
        }
    }
}

From source file:org.gdms.source.DefaultSourceManager.java

private void removeFromSchema(String name) {
    if (name.isEmpty()) {
        throw new IllegalArgumentException("Empty table name!");
    }/* www  .j  av  a  2  s .c o  m*/

    // split on the dots '.' into
    // schema1.schema2.schema3.table1

    String[] l = DOT.split(name);

    if (l.length <= 1) {
        // just a table, we remove it from the root schema
        schema.removeTable(name);
    } else {
        Deque<Schema> path = new ArrayDeque<Schema>();
        path.add(schema);
        // we get down
        // to the last schema before the table
        for (int i = 0; i < l.length - 1; i++) {
            final Schema n = path.getFirst().getSubSchemaByName(l[i]);
            path.addFirst(n);
        }

        boolean stop = false;
        while (!path.isEmpty() && !stop) {
            // take the last schema in the path (top of the pile)
            final Schema n = path.pollFirst();
            n.removeTable(l[l.length - 1]);
            if (n.getTableCount() != 0 || n.getSubSchemaNames().length != 0) {
                // the schema is still needed, we must not remove it
                stop = true;
            } else {
                Schema p = n.getParentSchema();
                if (p != null) {
                    p.removeSubSchema(n.getName());
                } else {
                    // we have reached root, it stays were it is...
                    stop = true;
                }
            }
        }
    }
}

From source file:org.jasig.resource.aggr.ResourcesAggregatorImpl.java

/**
 * Iterate over the list of {@link BasicInclude} sub-classes using the {@link AggregatorCallback#willAggregate(BasicInclude, BasicInclude)}
 * and {@link AggregatorCallback#aggregate(Deque)} to generate an aggregated list of {@link BasicInclude} sub-classes.
 *///ww  w  . j  av  a  2  s  .  c om
protected <T extends BasicInclude> List<T> aggregateBasicIncludes(List<T> original,
        AggregatorCallback<T> callback) throws IOException {
    final List<T> result = new LinkedList<T>();
    final Deque<T> currentAggregateList = new LinkedList<T>();
    for (final T originalElement : original) {
        // handle first loop iteration
        if (currentAggregateList.isEmpty()) {
            currentAggregateList.add(originalElement);
        } else {
            // test if 'originalElement' will aggregate with head element in currentAggregate 
            final T baseElement = currentAggregateList.getFirst();
            if (callback.willAggregate(originalElement, baseElement)) {
                // matches current criteria, add to currentAggregate
                currentAggregateList.add(originalElement);
            } else {
                // doesn't match criteria
                // generate new single aggregate from currentAggregateList
                final T aggregate = callback.aggregate(currentAggregateList);
                if (null != aggregate) {
                    // push result
                    result.add(aggregate);
                } else {
                    this.logger
                            .warn("Generated 0 byte aggregate from: " + generatePathList(currentAggregateList));
                }

                // zero out currentAggregateList
                currentAggregateList.clear();

                // add originalElement to empty list
                currentAggregateList.add(originalElement);
            }
        }
    }

    // flush the currentAggregateList
    if (currentAggregateList.size() > 0) {
        final T aggregate = callback.aggregate(currentAggregateList);
        if (null != aggregate) {
            result.add(aggregate);
        } else {
            this.logger.warn("Generated 0 byte aggregate from: " + generatePathList(currentAggregateList));
        }
    }

    return result;
}

From source file:org.jasig.resource.aggr.ResourcesAggregatorImpl.java

/**
 * Aggregate the specified Deque of elements into a single element. The provided MessageDigest is used for
 * building the file name based on the hash of the file contents. The callback is used for type specific
 * operations./*from  w w w.  j a va 2  s  . c  o m*/
 */
protected <T extends BasicInclude> T aggregateList(final MessageDigest digest, final Deque<T> elements,
        final List<File> skinDirectories, final File outputRoot, final File alternateOutput,
        final String extension, final AggregatorCallback<T> callback) throws IOException {

    if (null == elements || elements.size() == 0) {
        return null;
    }

    // reference to the head of the list
    final T headElement = elements.getFirst();
    if (elements.size() == 1 && this.resourcesDao.isAbsolute(headElement)) {
        return headElement;
    }

    final File tempFile = File.createTempFile("working.", extension);
    final File aggregateOutputFile;
    try {
        //Make sure we're working with a clean MessageDigest
        digest.reset();
        TrimmingWriter trimmingWriter = null;
        try {
            final BufferedOutputStream bufferedFileStream = new BufferedOutputStream(
                    new FileOutputStream(tempFile));
            final MessageDigestOutputStream digestStream = new MessageDigestOutputStream(bufferedFileStream,
                    digest);
            final OutputStreamWriter aggregateWriter = new OutputStreamWriter(digestStream, this.encoding);
            trimmingWriter = new TrimmingWriter(aggregateWriter);

            for (final T element : elements) {
                final File resourceFile = this.findFile(skinDirectories, element.getValue());

                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(resourceFile);
                    final BOMInputStream bomIs = new BOMInputStream(new BufferedInputStream(fis));
                    if (bomIs.hasBOM()) {
                        logger.debug("Stripping UTF-8 BOM from: " + resourceFile);
                    }
                    final Reader resourceIn = new InputStreamReader(bomIs, this.encoding);
                    if (element.isCompressed()) {
                        IOUtils.copy(resourceIn, trimmingWriter);
                    } else {
                        callback.compress(resourceIn, trimmingWriter);
                    }
                } catch (IOException e) {
                    throw new IOException(
                            "Failed to read '" + resourceFile + "' for skin: " + skinDirectories.get(0), e);
                } finally {
                    IOUtils.closeQuietly(fis);
                }
                trimmingWriter.write(SystemUtils.LINE_SEPARATOR);
            }
        } finally {
            IOUtils.closeQuietly(trimmingWriter);
        }

        if (trimmingWriter.getCharCount() == 0) {
            return null;
        }

        // temp file is created, get checksum
        final String checksum = Base64.encodeBase64URLSafeString(digest.digest());
        digest.reset();

        // create a new file name
        final String newFileName = checksum + extension;

        // Build the new file name and path
        if (alternateOutput == null) {
            final String elementRelativePath = FilenameUtils.getFullPath(headElement.getValue());
            final File directoryInOutputRoot = new File(outputRoot, elementRelativePath);
            // create the same directory structure in the output root
            directoryInOutputRoot.mkdirs();

            aggregateOutputFile = new File(directoryInOutputRoot, newFileName).getCanonicalFile();
        } else {
            aggregateOutputFile = new File(alternateOutput, newFileName).getCanonicalFile();
        }

        //Move the aggregate file into the correct location
        FileUtils.deleteQuietly(aggregateOutputFile);
        FileUtils.moveFile(tempFile, aggregateOutputFile);
    } finally {
        //Make sure the temp file gets deleted
        FileUtils.deleteQuietly(tempFile);
    }

    final String newResultValue = RelativePath.getRelativePath(outputRoot, aggregateOutputFile);

    this.logAggregation(elements, newResultValue);

    return callback.getAggregateElement(newResultValue, elements);
}

From source file:org.jboss.as.test.integration.logging.profiles.CommonsLoggingServiceActivator.java

private String getFirstValue(final Map<String, Deque<String>> params, final String key) {
    if (params.containsKey(key)) {
        final Deque<String> values = params.get(key);
        if (values != null && !values.isEmpty()) {
            return values.getFirst();
        }//from  w  w  w . j  a va2s .  co m
    }
    return null;
}

From source file:org.onehippo.cms7.essentials.dashboard.instruction.FileInstruction.java

private void processDirectories(final Deque<String> directories) throws IOException {
    if (!directories.isEmpty()) {
        folderMessage = directories.size() > 1 ? directories.size() - 1 + " directories" : "directory";
        createdFolders = directories.getLast().substring(directories.getFirst().length());
        createdFoldersTarget = directories.getLast();
        Files.createDirectories(new File(directories.getLast()).toPath());
        eventBus.post(new InstructionEvent(messageFolderCreate));
    }/*from   www. j  a  v a 2s.co  m*/
}

From source file:ro.hasna.ts.math.ml.distance.DynamicTimeWarpingDistance.java

/**
 * <p>/*from   www .  j a  v a2 s. c  o m*/
 * Reference:
 * Daniel Lemire (2008)
 * <i>Faster Sequential Search with a Two-Pass Dynamic-Time-Warping Lower Bound</i>
 * </p>
 *
 * @param v      the vector
 * @param n      the length of the vector
 * @param radius the Sakoe-Chiba band radius
 * @return time series envelope
 */
protected Envelope computeLemireEnvelope(double[] v, int n, int radius) {
    int w = 2 * radius + 1;
    double[] upper = new double[n];
    double[] lower = new double[n];
    int i;

    Deque<Integer> upperList = new LinkedList<>();
    Deque<Integer> lowerList = new LinkedList<>();
    upperList.addLast(0);
    lowerList.addLast(0);
    for (i = 1; i < n; i++) {
        if (i >= w) {
            upper[i - w] = v[upperList.getFirst()];
            lower[i - w] = v[lowerList.getFirst()];
        }
        if (v[i] > v[i - 1]) {
            upperList.removeLast();
            while (!upperList.isEmpty() && v[i] > v[upperList.getLast()]) {
                upperList.removeLast();
            }
        } else {
            lowerList.removeLast();
            while (!lowerList.isEmpty() && v[i] < v[lowerList.getLast()]) {
                lowerList.removeLast();
            }
        }
        upperList.addLast(i);
        lowerList.addLast(i);
        if (i == 2 * w + upperList.getFirst()) {
            upperList.removeFirst();
        } else if (i == 2 * w + lowerList.getFirst()) {
            lowerList.removeFirst();
        }
    }

    for (i = n; i < n + w; i++) {
        upper[i - w] = v[upperList.getFirst()];
        lower[i - w] = v[lowerList.getFirst()];
        if (i - upperList.getFirst() >= 2 * w) {
            upperList.removeFirst();
        }
        if (i - lowerList.getFirst() >= 2 * w) {
            lowerList.removeFirst();
        }
    }

    return new Envelope(lower, upper);
}