Example usage for java.util TreeMap remove

List of usage examples for java.util TreeMap remove

Introduction

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

Prototype

public V remove(Object key) 

Source Link

Document

Removes the mapping for this key from this TreeMap if present.

Usage

From source file:statistic.ca.gui.JCAStatisticPanel.java

private void showDiagramm(String diagrammName) {
    if (diagrammName.equals("Grundinformationen")) {
        String[] columnNames = { "Bezeichnung", "Wert" };
        EvacuationCellularAutomaton tmpCA;
        int nrOfInd = 0;
        double evacSec = 0.0;
        double evacCAStep = 0;
        double notEvac = 0;
        double evac = 0;
        double notEvacNoExit = 0;
        double notEvacNoTime = 0;
        int bestEvacIndex = 0;
        int aveEvacIndex = 0;
        int worseEvacIndex = 0;
        TreeMap<Double, Integer> findMedian = new TreeMap<>();
        for (int i = 0; i < selectedBatchResultEntry.getCa().length; i++) {
            tmpCA = selectedBatchResultEntry.getCa()[i];
            nrOfInd += tmpCA.getInitialIndividualCount();
            evacSec += tmpCA.getSecondsPerStep() * tmpCA.getTimeStep();
            evacCAStep += tmpCA.getTimeStep();
            evac += tmpCA.getInitialIndividualCount() - tmpCA.deadIndividualsCount();
            notEvac += tmpCA.deadIndividualsCount();
            notEvacNoExit += tmpCA.getDeadIndividualCount(DeathCause.ExitUnreachable);// getNrOfExitUnreachableDeadIndividuals();
            notEvacNoTime += tmpCA.getDeadIndividualCount(DeathCause.NotEnoughTime);// getNrOfNotEnoughTimeDeadIndividuals();
            findMedian.put(tmpCA.getTimeStep() * tmpCA.getSecondsPerStep(), i);
        }//from  w w  w  .  j av a2 s .c  o m
        bestEvacIndex = findMedian.firstEntry().getValue();
        for (int j = 0; j < findMedian.size() / 2; j++)
            findMedian.remove(findMedian.firstKey());
        aveEvacIndex = findMedian.get(findMedian.firstKey());
        worseEvacIndex = findMedian.get(findMedian.lastKey());
        Object[][] data = { { "Informationen fr Modell", selectedBatchResultEntry.getName() },
                { "Evakuierungszeit in Sekunden", evacSec / selectedBatchResultEntry.getCa().length },
                { "Evakuierungszeit in ZA-Schritten", evacCAStep / selectedBatchResultEntry.getCa().length },
                { "Anzahl Individuen", (double) nrOfInd / selectedBatchResultEntry.getCa().length },
                { "evakuiert", evac / selectedBatchResultEntry.getCa().length },
                { "nicht evakuiert", notEvac / selectedBatchResultEntry.getCa().length },
                { "nicht evakuiert weil kein Ausgang erreichbar",
                        notEvacNoExit / selectedBatchResultEntry.getCa().length },
                { "nicht evakuiert weil die Zeit nicht gereicht hat",
                        notEvacNoTime / selectedBatchResultEntry.getCa().length },
                { "beste Evakuierungszeit (Durchlaufindex,Zeit)", ("(" + (bestEvacIndex + 1) + " - "
                        + (selectedBatchResultEntry.getCa()[bestEvacIndex].getTimeStep()
                                / selectedBatchResultEntry.getCa()[bestEvacIndex].getStepsPerSecond())
                        + ")") },
                { "durchschnit. Evakuierungszeit (Durchlaufindex,Zeit)", ("(" + (aveEvacIndex + 1) + " - "
                        + (selectedBatchResultEntry.getCa()[aveEvacIndex].getTimeStep()
                                / selectedBatchResultEntry.getCa()[bestEvacIndex].getStepsPerSecond())
                        + ")") },
                { "schlechteste Evakuierungszeit (Durchlaufindex,Zeit)",
                        ("(" + (worseEvacIndex + 1) + " - "
                                + (selectedBatchResultEntry.getCa()[worseEvacIndex].getTimeStep()
                                        / selectedBatchResultEntry.getCa()[bestEvacIndex].getStepsPerSecond())
                                + ")") } };
        basicInformationTable = new JTable(data, columnNames);
        basicInformationScrollPane = new JScrollPane(basicInformationTable);
        diagrams.addTable(diagrammName, basicInformationScrollPane, west);
    }

    if ((noIndividualsInAtLeastOneAssignmentIndex) && !(diagrammName.equals("Grundinformationen"))) {
        chartData = new ChartData("bar", "NO INDIVIDUALS in at least one of the choosed dataset(s)", "",
                new ArrayList<>(), new ArrayList<>());
        evakuierungsdauer = ChartFactory.createBarChart(
                "NO INDIVIDUALS in at least one of the choosed dataset(s)", "", chartData.getYAxisLabel(),
                chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
        diagrams.addChart("NO INDIVIDUALS in at least one of the choosed dataset(s)", evakuierungsdauer, west);
    } else {

        if (diagrammName.equals("Ausgangsverteilung")) {
            chartData = new ChartData("pie",
                    diagrammName + ":" + selectedBatchResultEntry.getName() + "-"
                            + assignmentGroups.get(assignmentIndexToShow.get(0)).toString(),
                    "Ausgnge", categoryDatasetValues, categoryDatasetAssignments);
            ausgangsverteilung = ChartFactory.createPieChart(
                    diagrammName + ":" + selectedBatchResultEntry.getName() + "-"
                            + assignmentGroups.get(assignmentIndexToShow.get(0)).toString(),
                    ChartData.getPieDataSet(), false, true, false);
            diagrams.addChart(diagrammName, ausgangsverteilung, west);
        }

        if (diagrammName.equals("Ankunftskurve")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            ankunftskurve = ChartFactory.createXYLineChart(diagrammName, chartData.getYAxisLabel(),
                    "Individuen", (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true, true, false);
            diagrams.addChart(diagrammName, ankunftskurve, west);
        }

        if (diagrammName.equals("Evakuierungsdauer")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            evakuierungsdauer = ChartFactory.createBarChart(diagrammName, "Belegungen",
                    chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true,
                    false);
            diagrams.addChart(diagrammName, evakuierungsdauer, west);
        }

        if (diagrammName.equals("evakuierte Individuen in Prozent")) {
            chartData = new ChartData("pie",
                    diagrammName + ":" + selectedBatchResultEntry.getName() + "-"
                            + assignmentGroups.get(assignmentIndexToShow.get(0)).toString(),
                    "Individuen", categoryDatasetValues, categoryDatasetAssignments);
            evakuierteIndividueninProzent = ChartFactory.createPieChart(
                    diagrammName + ":" + selectedBatchResultEntry.getName() + "-"
                            + assignmentGroups.get(assignmentIndexToShow.get(0)).toString(),
                    ChartData.getPieDataSet(), false, true, false);
            diagrams.addChart(diagrammName, evakuierteIndividueninProzent, west);
        }

        if (diagrammName.equals("maximale Blockadezeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            maxblockadezeit = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(),
                    chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
            diagrams.addChart(diagrammName, maxblockadezeit, west);
        }

        if (diagrammName.equals("durchschnittliche Blockadezeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            aveblockadezeit = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(),
                    chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
            diagrams.addChart(diagrammName, aveblockadezeit, west);
        }

        if (diagrammName.equals("minimale Blockadezeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            minblockadezeit = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(),
                    chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
            diagrams.addChart(diagrammName, minblockadezeit, west);
        }

        if (diagrammName.equals("zurckgelegte Distanz")) {
            chartData = new ChartData("bar", diagrammName, "Meter [m]", categoryDatasetValues,
                    categoryDatasetAssignments);
            zurueckgelegteDistanz = ChartFactory.createBarChart(diagrammName, "Belegungen",
                    chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true,
                    false);
            diagrams.addChart(diagrammName, zurueckgelegteDistanz, west);
        }

        if (diagrammName.equals("minimale Distanz zum initialen Ausgang")) {
            chartData = new ChartData("bar", diagrammName, "Meter [m]", categoryDatasetValues,
                    categoryDatasetAssignments);
            minimaleDistanzzuminitialenAusgang = ChartFactory.createBarChart(diagrammName, "Belegungen",
                    chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true,
                    false);
            diagrams.addChart(diagrammName, minimaleDistanzzuminitialenAusgang, west);
        }

        if (diagrammName.equals("minimale Distanz zum nchsten Ausgang")) {
            chartData = new ChartData("bar", diagrammName, "Meter [m]", categoryDatasetValues,
                    categoryDatasetAssignments);
            minimaleDistanzzumnaechstenAusgang = ChartFactory.createBarChart(diagrammName, "Belegungen",
                    chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true,
                    false);
            diagrams.addChart(diagrammName, minimaleDistanzzumnaechstenAusgang, west);
        }

        if (diagrammName.equals("maximale Zeit bis Safe")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            maxZeitBisSafe = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(),
                    chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
            diagrams.addChart(diagrammName, maxZeitBisSafe, west);
        }

        if (diagrammName.equals("durchschnittliche Zeit bis Safe")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            aveZeitBisSafe = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(),
                    chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
            diagrams.addChart(diagrammName, aveZeitBisSafe, west);
        }

        if (diagrammName.equals("minimale Zeit bis Safe")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            minZeitBisSafe = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(),
                    chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
            diagrams.addChart(diagrammName, minZeitBisSafe, west);
        }

        if (diagrammName.equals("Distanz ber Zeit")) {
            chartData = new ChartData("bar", diagrammName, "Meter [m]", categoryDatasetValues,
                    categoryDatasetAssignments);
            distanzueberZeit = ChartFactory.createXYLineChart(diagrammName, "Zeit [s]",
                    chartData.getYAxisLabel(), (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true,
                    true, false);
            diagrams.addChart(diagrammName, distanzueberZeit, west);
        }

        if (diagrammName.equals("maximale Geschwindigkeit ber Zeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            maximaleGeschwindigkeitueberZeit = ChartFactory.createXYLineChart(diagrammName,
                    chartData.getYAxisLabel(), "Meter pro Sekunde [m/s]", (XYDataset) datasetCollection,
                    PlotOrientation.VERTICAL, true, true, false);
            diagrams.addChart(diagrammName, maximaleGeschwindigkeitueberZeit, west);
        }

        if (diagrammName.equals("durschnittliche Geschwindigkeit ber Zeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            durschnittlicheGeschwindigkeitueberZeit = ChartFactory.createXYLineChart(diagrammName,
                    chartData.getYAxisLabel(), "Meter pro Sekunde [m/s]", (XYDataset) datasetCollection,
                    PlotOrientation.VERTICAL, true, true, false);
            diagrams.addChart(diagrammName, durschnittlicheGeschwindigkeitueberZeit, west);
        }

        if (diagrammName.equals("maximale Geschwindigkeit")) {
            chartData = new ChartData("bar", diagrammName, "Meter pro Sekunde [m/s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            maximaleGeschwindigkeit = ChartFactory.createBarChart(diagrammName, "Belegungen",
                    chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true,
                    false);
            diagrams.addChart(diagrammName, maximaleGeschwindigkeit, west);
        }

        if (diagrammName.equals("durchschnittliche Geschwindigkeit")) {
            chartData = new ChartData("bar", diagrammName, "Meter pro Sekunde [m/s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            durchschnittlicheGeschwindigkeit = ChartFactory.createBarChart(diagrammName, "Belegungen",
                    chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true,
                    false);
            diagrams.addChart(diagrammName, durchschnittlicheGeschwindigkeit, west);
        }

        if (diagrammName.equals("Panik ber Zeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            panik = ChartFactory.createXYLineChart(diagrammName, chartData.getYAxisLabel(), "Panik",
                    (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true, true, false);
            diagrams.addChart(diagrammName, panik, west);
        }

        if (diagrammName.equals("Erschpfung ber Zeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            erschoepfung = ChartFactory.createXYLineChart(diagrammName, chartData.getYAxisLabel(),
                    "Erschpfung", (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true, true, false);
            diagrams.addChart(diagrammName, erschoepfung, west);
        }

    } //end else

    categoryDatasetValues = new ArrayList<>();
    categoryDatasetAssignments = new ArrayList<>();
    //dataset = new XYSeries("");
    datasetCollection = new XYSeriesCollection();
    diagrams.validate();
}

From source file:org.opendatakit.common.persistence.engine.gae.TaskLockImpl.java

/**
 * Update the MemCache for (formId, taskType) to record the given timestamp as
 * the expire-time of the lockId. The lockId with the earliest in-the-future
 * expire-time wins as long as there are no other lockIds within
 * SHORTEST_ALLOWABLE_GAIN_LOCK_SEPARATION of it.
 * /*from  w w w. j a va2s.c  om*/
 * @param lockId
 * @param formId
 * @param taskType
 * @param timestamp
 * @throws ODKTaskLockException
 */
private synchronized void updateLockIdTimestampMemCache(String lockId, String formId, ITaskLockType taskType,
        Long timestamp) throws ODKTaskLockException {
    if (syncCache != null) {
        int i;
        try {
            String formTask = ((formId == null) ? "" : formId) + "@" + taskType.getName();
            for (i = 0; i < 10; i++) {
                IdentifiableValue v = syncCache.contains(formTask) ? syncCache.getIdentifiable(formTask) : null;
                if (v == null || v.getValue() == null) {
                    TreeMap<Long, String> tm = new TreeMap<Long, String>();
                    tm.put(timestamp, lockId);
                    if (syncCache.put(formTask, tm, null, SetPolicy.ADD_ONLY_IF_NOT_PRESENT)) {
                        break;
                    }
                } else {
                    @SuppressWarnings("unchecked")
                    TreeMap<Long, String> tmOrig = (TreeMap<Long, String>) v.getValue();
                    TreeMap<Long, String> tm = new TreeMap<Long, String>(tmOrig);

                    // remove any old entries for lockId and any that are very old
                    Long currentTimestamp = System.currentTimeMillis();
                    Long oldTimestamp;
                    do {
                        oldTimestamp = null;
                        for (Map.Entry<Long, String> entry : tm.entrySet()) {
                            if (entry.getKey() + 300000L < currentTimestamp) {
                                // more than 5 minutes old -- remove it
                                oldTimestamp = entry.getKey();
                                break;
                            }
                            if (entry.getValue().equals(lockId)) {
                                oldTimestamp = entry.getKey();
                                break;
                            }
                        }
                        if (oldTimestamp != null) {
                            tm.remove(oldTimestamp);
                        }
                    } while (oldTimestamp != null);

                    // update with new timestamp
                    if (tm.put(timestamp, lockId) != null) {
                        // some other thread gained the lock first for this timestamp
                        throw new ODKTaskLockException(MULTIPLE_MEMCACHE_RESULTS_ERROR);
                    }

                    // try to update the Memcache with these changes.
                    if (syncCache.putIfUntouched(formTask, v, tm)) {
                        break;
                    }
                }
            }
        } catch (ODKTaskLockException e) {
            throw e;
        } catch (Throwable t) {
            t.printStackTrace();
            throw new ODKTaskLockException(OTHER_ERROR, t);
        }

        if (i == 10) {
            // crazy contention
            throw new ODKTaskLockException(HOT_MEMCACHE_ENTRY_ERROR);
        }
    }
}

From source file:org.ecocean.MarkedIndividual.java

public void setDynamicProperty(String name, String value) {
    name = name.replaceAll(";", "_").trim().replaceAll("%20", " ");
    value = value.replaceAll(";", "_").trim();

    if (dynamicProperties == null) {
        dynamicProperties = name + "=" + value + ";";
    } else {//from ww  w  .  j  ava 2s . c  o  m

        //let's create a TreeMap of the properties
        TreeMap<String, String> tm = new TreeMap<String, String>();
        StringTokenizer st = new StringTokenizer(dynamicProperties, ";");
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            int equalPlace = token.indexOf("=");
            tm.put(token.substring(0, equalPlace), token.substring(equalPlace + 1));
        }
        if (tm.containsKey(name)) {
            tm.remove(name);
            tm.put(name, value);

            //now let's recreate the dynamicProperties String
            String newProps = tm.toString();
            int stringSize = newProps.length();
            dynamicProperties = newProps.substring(1, (stringSize - 1)).replaceAll(", ", ";") + ";";
        } else {
            dynamicProperties = dynamicProperties + name + "=" + value + ";";
        }
    }
}

From source file:tw.com.geminihsu.app01.camera2raw.Camera2RawFragment.java

/**
 * Retrieve the next {@link Image} from a reference counted {@link ImageReader}, retaining
 * that {@link ImageReader} until that {@link Image} is no longer in use, and set this
 * {@link Image} as the result for the next request in the queue of pending requests.  If
 * all necessary information is available, begin saving the image to a file in a background
 * thread./*from   ww  w.j  ava 2  s  .co m*/
 *
 * @param pendingQueue the currently active requests.
 * @param reader       a reference counted wrapper containing an {@link ImageReader} from which
 *                     to acquire an image.
 */
private void dequeueAndSaveImage(TreeMap<Integer, ImageSaver.ImageSaverBuilder> pendingQueue,
        RefCountedAutoCloseable<ImageReader> reader) {
    synchronized (mCameraStateLock) {
        Map.Entry<Integer, ImageSaver.ImageSaverBuilder> entry = pendingQueue.firstEntry();
        ImageSaver.ImageSaverBuilder builder = entry.getValue();

        // Increment reference count to prevent ImageReader from being closed while we
        // are saving its Images in a background thread (otherwise their resources may
        // be freed while we are writing to a file).
        if (reader == null || reader.getAndRetain() == null) {
            Log.e(TAG, "Paused the activity before we could save the image," + " ImageReader already closed.");
            pendingQueue.remove(entry.getKey());
            return;
        }

        Image image;
        try {
            image = reader.get().acquireNextImage();
        } catch (IllegalStateException e) {
            Log.e(TAG, "Too many images queued for saving, dropping image for request: " + entry.getKey());
            pendingQueue.remove(entry.getKey());
            return;
        }

        builder.setRefCountedReader(reader).setImage(image);

        handleCompletionLocked(entry.getKey(), builder, pendingQueue);

        //back Activity
        getActivity().finish();
    }
}

From source file:com.espertech.esper.rowregex.EventRowRegexNFAView.java

private List<RegexNFAStateEntry> rankEndStatesWithinPartitionByStart(List<RegexNFAStateEntry> endStates) {
    if (endStates.isEmpty()) {
        return endStates;
    }//from ww w  . j a  va2s. c om
    if (endStates.size() == 1) {
        return endStates;
    }

    TreeMap<Integer, Object> endStatesPerBeginEvent = new TreeMap<Integer, Object>();
    for (RegexNFAStateEntry entry : endStates) {
        Integer endNum = entry.getMatchBeginEventSeqNo();
        Object value = endStatesPerBeginEvent.get(endNum);
        if (value == null) {
            endStatesPerBeginEvent.put(endNum, entry);
        } else if (value instanceof List) {
            List<RegexNFAStateEntry> entries = (List<RegexNFAStateEntry>) value;
            entries.add(entry);
        } else {
            List<RegexNFAStateEntry> entries = new ArrayList<RegexNFAStateEntry>();
            entries.add((RegexNFAStateEntry) value);
            entries.add(entry);
            endStatesPerBeginEvent.put(endNum, entries);
        }
    }

    if (endStatesPerBeginEvent.size() == 1) {
        List<RegexNFAStateEntry> endStatesUnranked = (List<RegexNFAStateEntry>) endStatesPerBeginEvent.values()
                .iterator().next();
        if (matchRecognizeSpec.isAllMatches()) {
            return endStatesUnranked;
        }
        RegexNFAStateEntry chosen = rankEndStates(endStatesUnranked);
        return Collections.singletonList(chosen);
    }

    List<RegexNFAStateEntry> endStatesRanked = new ArrayList<RegexNFAStateEntry>();
    Set<Integer> keyset = endStatesPerBeginEvent.keySet();
    Integer[] keys = keyset.toArray(new Integer[keyset.size()]);
    for (Integer key : keys) {
        Object value = endStatesPerBeginEvent.remove(key);
        if (value == null) {
            continue;
        }

        RegexNFAStateEntry entryTaken;
        if (value instanceof List) {
            List<RegexNFAStateEntry> endStatesUnranked = (List<RegexNFAStateEntry>) value;
            if (endStatesUnranked.isEmpty()) {
                continue;
            }
            entryTaken = rankEndStates(endStatesUnranked);

            if (matchRecognizeSpec.isAllMatches()) {
                endStatesRanked.addAll(endStatesUnranked); // we take all matches and don't rank except to determine skip-past
            } else {
                endStatesRanked.add(entryTaken);
            }
        } else {
            entryTaken = (RegexNFAStateEntry) value;
            endStatesRanked.add(entryTaken);
        }
        // could be null as removals take place

        if (entryTaken != null) {
            if (matchRecognizeSpec.getSkip().getSkip() == MatchRecognizeSkipEnum.PAST_LAST_ROW) {
                int skipPastRow = entryTaken.getMatchEndEventSeqNo();
                removeSkippedEndStates(endStatesPerBeginEvent, skipPastRow);
            } else if (matchRecognizeSpec.getSkip().getSkip() == MatchRecognizeSkipEnum.TO_NEXT_ROW) {
                int skipPastRow = entryTaken.getMatchBeginEventSeqNo();
                removeSkippedEndStates(endStatesPerBeginEvent, skipPastRow);
            }
        }
    }

    return endStatesRanked;
}

From source file:com.ape.camera2raw.Camera2RawFragment.java

/**
 * Retrieve the next {@link Image} from a reference counted {@link ImageReader}, retaining
 * that {@link ImageReader} until that {@link Image} is no longer in use, and set this
 * {@link Image} as the result for the next request in the queue of pending requests.  If
 * all necessary information is available, begin saving the image to a file in a background
 * thread./*from  ww  w.ja  va 2  s .  c om*/
 *
 * @param pendingQueue the currently active requests.
 * @param reader       a reference counted wrapper containing an {@link ImageReader} from which
 *                     to acquire an image.
 */
private void dequeueAndSaveImage(TreeMap<Integer, ImageSaver.ImageSaverBuilder> pendingQueue,
        RefCountedAutoCloseable<ImageReader> reader) {
    synchronized (mCameraStateLock) {
        Map.Entry<Integer, ImageSaver.ImageSaverBuilder> entry = pendingQueue.firstEntry();
        ImageSaver.ImageSaverBuilder builder = entry.getValue();

        // Increment reference count to prevent ImageReader from being closed while we
        // are saving its Images in a background thread (otherwise their resources may
        // be freed while we are writing to a file).
        if (reader == null || reader.getAndRetain() == null) {
            Log.e(TAG, "Paused the activity before we could save the image," + " ImageReader already closed.");
            pendingQueue.remove(entry.getKey());
            return;
        }

        Image image;
        try {
            image = reader.get().acquireNextImage();
        } catch (IllegalStateException e) {
            Log.e(TAG, "Too many images queued for saving, dropping image for request: " + entry.getKey());
            pendingQueue.remove(entry.getKey());
            return;
        }

        builder.setRefCountedReader(reader).setImage(image);

        handleCompletionLocked(entry.getKey(), builder, pendingQueue);
    }
}

From source file:org.mahasen.node.MahasenPropertyPastContent.java

/**
 * @param id/*ww w.jav  a  2  s .  c  o m*/
 * @param existingContent
 * @return
 * @throws PastException
 */
@Override
public PastContent checkInsert(rice.p2p.commonapi.Id id, PastContent existingContent) throws PastException {
    if (existingContent != null) {

        if (((MahasenPropertyPastContent) existingContent).getTreeType()
                .equals(MahasenConstants.STRING_PROPERTY_TREE)
                && this.treeType.endsWith(MahasenConstants.STRING_PROPERTY_TREE)) {
            TreeMap<String, Vector<Id>> existingTree = ((MahasenPropertyPastContent) existingContent)
                    .getPropertyTree();

            log.debug("EXISTING TREE " + existingTree);
            log.debug("NEW TREE " + stringPropertyTree);

            if (existingTree != null && stringPropertyTree != null) {
                Iterator keys = stringPropertyTree.keySet().iterator();
                while (keys.hasNext()) {

                    String propertyValue = keys.next().toString();
                    log.debug("property value " + propertyValue);

                    if (existingTree.containsKey(propertyValue)) {
                        log.debug("existing tree contains the property value " + propertyValue);
                        log.debug("get node for existing property value " + existingTree.get(propertyValue));

                        log.debug("node is to delete " + (this.isToDelete));
                        // this will update the Id vector for the existing property value in the exsisting TreeMap node
                        if (!this.isToDelete) {
                            log.debug("adding resource id to " + propertyValue);
                            if (!existingTree.get(propertyValue)
                                    .contains(stringPropertyTree.get(propertyValue).get(0))) {
                                existingTree.get(propertyValue)
                                        .add(stringPropertyTree.get(propertyValue).get(0));
                            }
                        } else {
                            if (existingTree.get(propertyValue)
                                    .contains(stringPropertyTree.get(propertyValue).get(0))) {
                                log.debug("removing resource id from " + propertyValue);
                                boolean removed = existingTree.get(propertyValue)
                                        .remove(stringPropertyTree.get(propertyValue).get(0));
                                log.debug("deleted " + removed);
                                if (existingTree.get(propertyValue).size() == 0) {
                                    existingTree.remove(propertyValue);
                                }

                            }

                        }

                    } else {
                        log.debug("existing tree does not contain the property value " + propertyValue);
                        // this will add the new property value and the resource id to the TreeMap
                        existingTree.put(propertyValue, stringPropertyTree.get(propertyValue));
                    }

                    log.debug("Tree after modifications " + existingTree.toString());

                }
            }

        } else if (((MahasenPropertyPastContent) existingContent).getTreeType()
                .equals(MahasenConstants.INTEGER_PROPERTY_TREE)
                && this.treeType.equals(MahasenConstants.INTEGER_PROPERTY_TREE)) {

            TreeMap<Integer, Vector<Id>> existingTree = ((MahasenPropertyPastContent) existingContent)
                    .getPropertyTree();

            log.debug("EXISTING TREE " + existingTree);
            log.debug("NEW TREE " + intPropertyTree);
            //for(String propertyValue:propertyTree.keySet())  {

            if (existingTree != null && intPropertyTree != null) {
                Iterator keys = intPropertyTree.keySet().iterator();
                while (keys.hasNext()) {

                    Integer propertyValue = Integer.valueOf(keys.next().toString());
                    log.debug("property value " + propertyValue);

                    if (existingTree.containsKey(propertyValue)) {
                        log.debug("existing tree contains the property value " + propertyValue);
                        log.debug("get node for existing property value " + existingTree.get(propertyValue));
                        log.debug("node is to delete " + (this.isToDelete));

                        // this will update the Id vector for the existing property value in the exsisting TreeMap node
                        if (!this.isToDelete) {
                            if (!existingTree.get(propertyValue)
                                    .contains(intPropertyTree.get(propertyValue).get(0))) {
                                existingTree.get(propertyValue).add(intPropertyTree.get(propertyValue).get(0));
                            }
                        } else {
                            if (existingTree.get(propertyValue)
                                    .contains(intPropertyTree.get(propertyValue).get(0))) {
                                existingTree.get(propertyValue)
                                        .remove(intPropertyTree.get(propertyValue).get(0));
                                if (existingTree.get(propertyValue).size() == 0) {
                                    existingTree.remove(propertyValue);
                                }
                            }

                        }
                    } else {
                        log.debug("existing tree does not contain the property value " + propertyValue);
                        // this will add the new property value and the resource id to the TreeMap
                        existingTree.put(propertyValue, intPropertyTree.get(propertyValue));
                    }

                    log.debug("Existing PropertyTree" + existingTree.toString());

                }
            }
        }
        return existingContent;
    } else {
        log.debug("===== crate a new property tree====");
        log.debug("Existing PropertyTree" + this.treeType);
        return this;
    }
}

From source file:com.almende.dht.rpc.DHT.java

/**
 * Iterative_node_lookup./* w  w w  .j  a  va 2s. c o m*/
 *
 * @param near
 *            the near
 * @return the list
 */
public List<Node> iterative_node_lookup(final Key near) {
    final TreeMap<Key, Node> shortList = new TreeMap<Key, Node>();
    final Set<Node> tried = new HashSet<Node>();

    insert(shortList, near, rt.getClosestNodes(near, Constants.A));

    final int[] noInFlight = new int[1];
    noInFlight[0] = 0;
    boolean keepGoing = true;
    while (keepGoing) {
        while (noInFlight[0] > 0) {
            synchronized (shortList) {
                try {
                    shortList.wait(100);
                } catch (InterruptedException e) {
                }
            }
        }

        List<Node> copy = Arrays.asList(shortList.values().toArray(new Node[0]));
        Collections.sort(copy);
        final Iterator<Node> iter = copy.iterator();
        int count = 0;
        while (iter.hasNext() && count < Constants.A) {
            final Node next = iter.next();
            if (tried.contains(next)) {
                continue;
            }
            count++;
            tried.add(next);
            try {
                ObjectNode params = JOM.createObjectNode();
                params.set("me", JOM.getInstance().valueToTree(rt.getMyKey()));
                params.set("near", JOM.getInstance().valueToTree(near));

                AsyncCallback<ObjectNode> callback = new AsyncCallback<ObjectNode>() {

                    @Override
                    public void onSuccess(ObjectNode res) {
                        List<Node> result = NODELIST.inject(res.get("nodes"));
                        rt.seenNode(next);
                        synchronized (shortList) {
                            insert(shortList, near, result);
                            noInFlight[0]--;
                            shortList.notifyAll();
                        }
                    }

                    @Override
                    public void onFailure(Exception exception) {
                        synchronized (shortList) {
                            shortList.remove(near.dist(next.getKey()));
                            noInFlight[0]--;
                            shortList.notifyAll();
                            LOG.log(Level.WARNING, noInFlight[0] + ":OnFailure called:" + next.getUri(),
                                    exception);
                        }
                    }

                };
                caller.call(next.getUri(), "dht.find_close_nodes", params, callback);
                synchronized (shortList) {
                    noInFlight[0]++;
                }
            } catch (IOException e) {
                synchronized (shortList) {
                    shortList.remove(near.dist(next.getKey()));
                }
                continue;
            }
        }
        if (count == 0) {
            keepGoing = false;
        }
    }
    synchronized (shortList) {
        return new ArrayList<Node>(shortList.values());
    }
}

From source file:it.imtech.metadata.MetaUtility.java

private void metadata_reader_metadatas(Element iENode, TreeMap<Object, Metadata> metadatas, boolean forceAdd,
        TreeMap forceAddMID, String sLang) {
    try {/*from  ww w.j  a va 2  s  . c om*/
        if (iENode.getTagName().equals("metadatas")) {
            NodeList nList = iENode.getChildNodes();

            for (int s = 0; s < nList.getLength(); s++) {

                if (nList.item(s).getNodeType() == Node.ELEMENT_NODE) {
                    Element iInnerNode = (Element) nList.item(s);

                    if (iInnerNode.getTagName().equals("metadata")) {
                        String MID = iInnerNode.getAttribute("ID");

                        //Se  hidden rimuovo l'elemento dai forzati
                        String hidden = "0";

                        if (iInnerNode.hasAttribute("hidden")) {
                            hidden = iInnerNode.getAttribute("hidden");
                            forceAddMID.remove(iInnerNode.getAttribute("ID"));
                        }

                        if (forceAddMID.containsKey(MID)) {
                            forceAdd = true;
                        }

                        String MID_parent = iInnerNode.getAttribute("mid_parent");
                        String mandatory = iInnerNode.getAttribute("mandatory");
                        String datatype = iInnerNode.getAttribute("datatype");
                        String editable = iInnerNode.getAttribute("editable");
                        String foxmlname = iInnerNode.getAttribute("forxmlname");
                        String sequence = iInnerNode.getAttribute("sequence");

                        String sequencemulti = "";

                        if (MID_parent.equals("22") || MID_parent.equals("45")) {
                            Node searchparent = iInnerNode;
                            boolean found = false;

                            while (!found) {
                                Element x = (Element) searchparent.getParentNode();
                                if (x.getAttribute("ID").equals("22")) {
                                    sequencemulti = x.getAttribute("sequence");
                                    found = true;
                                } else {
                                    searchparent = searchparent.getParentNode();
                                }
                            }
                        }

                        //Add contributors management
                        if (MID_parent.equals("11") || MID_parent.equals("13")) {
                            Node searchparent = iInnerNode;
                            boolean found = false;

                            while (!found) {
                                Element x = (Element) searchparent.getParentNode();
                                if (x.getAttribute("ID").equals("11")) {
                                    sequencemulti = x.getAttribute("sequence");
                                    found = true;
                                } else {
                                    searchparent = searchparent.getParentNode();
                                }
                            }
                        }

                        if (MID.equals("11")) {
                            Element x = (Element) iInnerNode;
                            sequencemulti = x.getAttribute("sequence");
                        }

                        String foxmlnamespace = iInnerNode.getAttribute("fornamespace");

                        if (!metadata_namespaces.containsValue(foxmlnamespace)) {
                            int count = metadata_namespaces.size();
                            count++;
                            metadata_namespaces.put("ns" + count, foxmlnamespace);
                        }

                        String description = null;
                        String DESCRIPTION_DE = null;

                        TreeMap<Object, Metadata> submetadatas = new TreeMap<Object, Metadata>();

                        NodeList innerList = iInnerNode.getChildNodes();
                        for (int z = 0; z < innerList.getLength(); z++) {
                            if (innerList.item(z).getNodeType() == Node.ELEMENT_NODE) {
                                Element iDescrNode = (Element) innerList.item(z);

                                if (iDescrNode.getAttribute("isocode").equals(sLang)) {
                                    description = iDescrNode.getTextContent();
                                } else if (iDescrNode.getAttribute("isocode").equals("de")) {
                                    DESCRIPTION_DE = iDescrNode.getTextContent();
                                }

                                if (iDescrNode.getTagName().equals("metadatas")) {
                                    if (MID.equals("98")) {
                                        metadata_reader_metadatas(iDescrNode, submetadatas, true, forceAddMID,
                                                sLang);
                                    } else {
                                        metadata_reader_metadatas(iDescrNode, submetadatas, false, forceAddMID,
                                                sLang);
                                    }
                                }
                            }
                        }

                        //Fallback DE
                        if (description == null) {
                            description = DESCRIPTION_DE;
                        }
                        if (description == null && !iInnerNode.getTagName().equals("metadata")) {
                            throw new Exception(
                                    "Can't find description for metadata " + iInnerNode.getTagName());
                        }

                        if ((mandatory.equals("Y") || forceAdd == true)) {
                            int mid_parent = 0;
                            if (!MID_parent.equals("")) {
                                mid_parent = Integer.parseInt(MID_parent);
                            }

                            Metadata t = new Metadata(Integer.parseInt(MID), mid_parent, description, datatype,
                                    editable, foxmlname, null, foxmlnamespace, mandatory, hidden,
                                    sequencemulti);
                            t.submetadatas = submetadatas;

                            String index = sequence;

                            if (index == null || index.equals("")) {
                                index = MID;
                            }
                            int param = Integer.parseInt(index);
                            metadatas.put(param, t);
                        }

                        if (forceAddMID.containsKey(MID.toString())) {
                            forceAdd = false;
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }
}

From source file:com.almende.dht.rpc.DHT.java

/**
 * Iterative_find_value./*from   w w w . ja  va2 s. c  om*/
 *
 * @param key
 *            the key
 * @param multiple
 *            the multiple
 * @return the object node
 */
public JsonNode iterative_find_value(final Key key, final boolean multiple) {
    final JsonNode[] result = new JsonNode[1];

    final TreeMap<Key, Node> shortList = new TreeMap<Key, Node>();
    final Set<Node> tried = new HashSet<Node>();

    insert(shortList, key, rt.getClosestNodes(key, Constants.A));
    final int[] noInFlight = new int[1];
    noInFlight[0] = 0;
    boolean keepGoing = true;
    while (keepGoing) {
        while (noInFlight[0] > 0 && result[0] == null) {
            synchronized (shortList) {
                try {
                    shortList.wait(100);
                } catch (InterruptedException e) {
                }
            }
        }

        List<Node> copy = Arrays.asList(shortList.values().toArray(new Node[0]));
        Collections.sort(copy);
        final Iterator<Node> iter = copy.iterator();
        int count = 0;
        while (iter.hasNext() && count < Constants.A) {
            final Node next = iter.next();
            if (tried.contains(next)) {
                continue;
            }
            count++;
            tried.add(next);
            try {
                ObjectNode params = JOM.createObjectNode();
                params.set("me", JOM.getInstance().valueToTree(rt.getMyKey()));
                params.set("key", JOM.getInstance().valueToTree(key));
                params.put("multiple", multiple);

                AsyncCallback<ObjectNode> callback = new AsyncCallback<ObjectNode>() {

                    @Override
                    public void onSuccess(ObjectNode res) {
                        if (res.has("value")) {
                            result[0] = (ObjectNode) res.get("value");
                        } else if (res.has("values")) {
                            result[0] = (ArrayNode) res.get("values");
                        } else {
                            List<Node> nodes = NODELIST.inject(res.get("nodes"));
                            synchronized (shortList) {
                                insert(shortList, key, nodes);
                            }
                        }
                        rt.seenNode(next);
                        synchronized (shortList) {
                            noInFlight[0]--;
                            shortList.notifyAll();
                        }
                    }

                    @Override
                    public void onFailure(Exception exception) {
                        synchronized (shortList) {
                            shortList.remove(key.dist(next.getKey()));
                            noInFlight[0]--;
                            shortList.notifyAll();
                            LOG.log(Level.WARNING, noInFlight[0] + ":OnFailure called:" + next.getUri(),
                                    exception);
                        }
                    }

                };
                caller.call(next.getUri(), "dht.find_value", params, callback);
                synchronized (shortList) {
                    noInFlight[0]++;
                }
            } catch (IOException e) {
                synchronized (shortList) {
                    shortList.remove(key.dist(next.getKey()));
                }
                continue;
            }
        }
        if (count == 0) {
            keepGoing = false;
        }
    }
    if (result[0] == null) {
        return JOM.createNullNode();
    } else {
        return result[0];
    }
}