Example usage for java.util TreeMap get

List of usage examples for java.util TreeMap get

Introduction

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

Prototype

public V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.sfs.whichdoctor.analysis.AgedDebtorsAnalysisDAOImpl.java

/**
 * Load groupings./*  ww w.j ava 2 s  .  com*/
 *
 * @param analysis the analysis
 * @return the aged debtors analysis bean
 */
private AgedDebtorsAnalysisBean loadGroupings(final AgedDebtorsAnalysisBean analysis) {

    HashMap<Integer, AgedDebtorsRecord> records = buildRecordMap(analysis);

    HashMap<Integer, ReceiptBean> lastReceipts = loadLastReceipts(analysis);

    TreeMap<String, AgedDebtorsGrouping> groupings = new TreeMap<String, AgedDebtorsGrouping>();

    // If there are no records then there is no need to perform any searches
    if (records.size() > 0) {
        // Loop through these for the different periods and in total
        for (Integer periodId : analysis.getPeriods().keySet()) {

            AgedDebtorsPeriod period = analysis.getPeriods().get(periodId);

            for (String type : types) {

                dataLogger.debug("Performing lookup for " + type);

                Collection<AgedDebtorsRecord> results = performLookup(analysis, period, type);

                for (AgedDebtorsRecord result : results) {

                    int guid = result.getPersonGUID();
                    if (result.getOrganisationGUID() > 0) {
                        guid = result.getOrganisationGUID();
                    }

                    String groupName = analysis.getGroupName(guid);

                    AgedDebtorsGrouping grouping = new AgedDebtorsGrouping();
                    grouping.setName(groupName);
                    if (groupings.containsKey(groupName)) {
                        grouping = groupings.get(groupName);
                    }

                    dataLogger.debug("Processing result for GUID: " + guid + ", "
                            + Formatter.toCurrency(result.getOutstandingDebitValue()));

                    AgedDebtorsRecord record = records.get(guid);

                    AgedDebtorsPeriod periodResult = new AgedDebtorsPeriod(period);
                    if (record.getPeriodBreakdown().containsKey(periodId)) {
                        periodResult = record.getPeriodBreakdown().get(periodId);
                    }

                    if (StringUtils.equalsIgnoreCase(type, "debit")) {
                        periodResult.setOutstandingDebitValue(result.getOutstandingDebitValue());

                        // Update the running total for the record
                        record.setOutstandingDebitValue(
                                record.getOutstandingDebitValue() + result.getOutstandingDebitValue());

                        // Update the running total for the period
                        period.setOutstandingDebitValue(
                                period.getOutstandingDebitValue() + result.getOutstandingDebitValue());
                    }
                    if (StringUtils.equalsIgnoreCase(type, "credit")) {
                        periodResult.setUnallocatedCreditValue(result.getOutstandingDebitValue());

                        // Update the running total for the record
                        record.setUnallocatedCreditValue(
                                record.getUnallocatedCreditValue() + result.getOutstandingDebitValue());

                        // Update the running total for the period
                        period.setUnallocatedCreditValue(
                                period.getUnallocatedCreditValue() + result.getOutstandingDebitValue());
                    }
                    if (StringUtils.equalsIgnoreCase(type, "refund")) {
                        periodResult.setUnallocatedRefundValue(result.getOutstandingDebitValue());

                        // Update the running total for the record
                        record.setUnallocatedRefundValue(
                                record.getUnallocatedRefundValue() + result.getOutstandingDebitValue());

                        // Update the running total for the period
                        period.setUnallocatedRefundValue(
                                period.getUnallocatedRefundValue() + result.getOutstandingDebitValue());
                    }
                    if (StringUtils.equalsIgnoreCase(type, "receipt")) {
                        periodResult.setUnallocatedReceiptValue(result.getOutstandingDebitValue());

                        // Update the running total for the record
                        record.setUnallocatedReceiptValue(
                                record.getUnallocatedReceiptValue() + result.getOutstandingDebitValue());

                        // Update the running total for the period
                        period.setUnallocatedReceiptValue(
                                period.getUnallocatedReceiptValue() + result.getOutstandingDebitValue());
                    }

                    // Set the last receipt if one exists for this record
                    if (lastReceipts.containsKey(guid)) {
                        record.setLastReceipt(lastReceipts.get(guid));
                    }

                    record.getPeriodBreakdown().put(periodId, periodResult);
                    grouping.getRecords().put(analysis.getOrderKey(guid), record);
                    groupings.put(groupName, grouping);
                }
            }
            analysis.getPeriods().put(periodId, period);
        }
    }
    analysis.setGroupings(processGroups(groupings, analysis.getShowZeroBalances()));

    return analysis;
}

From source file:net.pms.dlna.MapFile.java

@Override
public void discoverChildren(String str) {
    if (discoverable == null) {
        discoverable = new ArrayList<>();
    } else {// www . java 2 s . c  o  m
        return;
    }

    int sm = configuration.getSortMethod(getPath());

    List<File> files = getFileList();

    // ATZ handling
    if (files.size() > configuration.getATZLimit() && StringUtils.isEmpty(forcedName)) {
        /*
         * Too many files to display at once, add A-Z folders
         * instead and let the filters begin
         *
         * Note: If we done this at the level directly above we don't do it again
         * since all files start with the same letter then
         */
        TreeMap<String, ArrayList<File>> map = new TreeMap<>();
        for (File f : files) {
            if ((!f.isFile() && !f.isDirectory()) || f.isHidden()) {
                // skip these
                continue;
            }
            if (f.isDirectory() && configuration.isHideEmptyFolders()
                    && !FileUtil.isFolderRelevant(f, configuration)) {
                LOGGER.debug("Ignoring empty/non-relevant directory: " + f.getName());
                // Keep track of the fact that we have empty folders, so when we're asked if we should refresh,
                // we can re-scan the folders in this list to see if they contain something relevant
                if (emptyFoldersToRescan == null) {
                    emptyFoldersToRescan = new ArrayList<>();
                }
                if (!emptyFoldersToRescan.contains(f)) {
                    emptyFoldersToRescan.add(f);
                }
                continue;
            }

            String filenameToSort = FileUtil.renameForSorting(f.getName());

            char c = filenameToSort.toUpperCase().charAt(0);

            if (!(c >= 'A' && c <= 'Z')) {
                // "other char"
                c = '#';
            }
            ArrayList<File> l = map.get(String.valueOf(c));
            if (l == null) {
                // new letter
                l = new ArrayList<>();
            }
            l.add(f);
            map.put(String.valueOf(c), l);
        }

        for (String letter : map.keySet()) {
            // loop over all letters, this avoids adding
            // empty letters
            ArrayList<File> l = map.get(letter);
            UMSUtils.sort(l, sm);
            MapFile mf = new MapFile(getConf(), l);
            mf.forcedName = letter;
            addChild(mf);
        }
        return;
    }

    UMSUtils.sort(files, (sm == UMSUtils.SORT_RANDOM ? UMSUtils.SORT_LOC_NAT : sm));

    for (File f : files) {
        if (f.isDirectory()) {
            discoverable.add(f); // manageFile(f);
        }
    }

    // For random sorting, we only randomize file entries
    if (sm == UMSUtils.SORT_RANDOM) {
        UMSUtils.sort(files, sm);
    }

    for (File f : files) {
        if (f.isFile()) {
            discoverable.add(f); // manageFile(f);
        }
    }
}

From source file:chatbot.Chatbot.java

/*****************************************************************************************************
 *
 * @param input/*from ww w.  j a v a2s .c  om*/
 * @return
 */
public String matchBestInput(String input) {

    ArrayList<String> result = new ArrayList<>();
    TreeMap<Float, ArrayList<Integer>> sortedSim = matchInputFull(input);
    if (sortedSim == null || sortedSim.keySet().size() < 1 || sortedSim.lastKey() < .1) {
        return "I don't know";
    }
    Object[] floats = sortedSim.keySet().toArray();
    int numClusters = 3;
    if (floats.length < numClusters)
        numClusters = floats.length;
    float[] floatarray = new float[floats.length];
    for (int i = 0; i < floats.length; i++)
        floatarray[i] = (float) floats[i];
    ArrayList<ArrayList<Float>> res = KMeans.run(floatarray.length, floatarray, numClusters);
    ArrayList<Float> topCluster = res.get(res.size() - 2);
    while (res.get(res.size() - 2).size() > 3 && numClusters < floats.length) {
        numClusters++;
        res = KMeans.run(floatarray.length, floatarray, numClusters);
        topCluster = res.get(res.size() - 2);
        //System.out.println("Info in TFIDF.matchBestInput(): " + res);
        //System.out.println("Info in TFIDF.matchBestInput(): " + topCluster);
    }
    for (int i = 0; i < topCluster.size(); i++) {
        ArrayList<Integer> temp = sortedSim.get(topCluster.get(i));
        for (int j = 0; j < temp.size(); j++)
            result.add(lines.get(temp.get(j).intValue()));
    }

    ArrayList<String> resultNoProfanity = profanityFilter(result);

    ArrayList<String> rankedResponses = rankResponses(resultNoProfanity, input);

    return chooseBestResponse(rankedResponses);
}

From source file:gsn.wrappers.general.CSVHandler.java

public TreeMap<String, Serializable> convertTo(String[] formats, String[] fields, String nullValues[],
        String[] values, char separator) {
    TreeMap<String, Serializable> streamElement = new TreeMap<String, Serializable>(
            new CaseInsensitiveComparator());
    for (String field : fields)
        streamElement.put(field, null);/*  www  .  java 2s  . c o m*/
    HashMap<String, String> timeStampFormats = new HashMap<String, String>();
    for (int i = 0; i < Math.min(fields.length, values.length); i++) {
        if (isNull(nullValues, values[i])) {
            continue;
        } else if (formats[i].equalsIgnoreCase("numeric")) {
            try {
                streamElement.put(fields[i], Double.parseDouble(values[i]));
            } catch (java.lang.NumberFormatException e) {
                logger.error("Parsing to Numeric failed: Value to parse=" + values[i]);
                throw e;
            }
        } else if (formats[i].equalsIgnoreCase("string")) {
            streamElement.put(fields[i], values[i]);
        } else if (formats[i].equalsIgnoreCase("bigint")) {
            try {
                streamElement.put(fields[i], Long.parseLong(values[i]));
            } catch (java.lang.NumberFormatException e) {
                logger.error("Parsing to BigInt failed: Value to parse=" + values[i]);
                throw e;
            }
        } else if (isTimeStampFormat(formats[i])) {
            String value = "";
            String format = "";
            if (streamElement.get(fields[i]) != null) {
                value = (String) streamElement.get(fields[i]);
                format = timeStampFormats.get(fields[i]);
                value += separator;
                format += separator;
            }
            if (isTimeStampLeftPaddedFormat(formats[i]))
                values[i] = StringUtils.leftPad(values[i], getTimeStampFormat(formats[i]).length(), '0');

            value += values[i];
            format += getTimeStampFormat(formats[i]);

            streamElement.put(fields[i], value);
            timeStampFormats.put(fields[i], format);
        }
    }
    for (String timeField : timeStampFormats.keySet()) {
        String timeFormat = timeStampFormats.get(timeField);
        String timeValue = (String) streamElement.get(timeField);
        try {
            DateTime x = DateTimeFormat.forPattern(timeFormat).withZone(getTimeZone()).parseDateTime(timeValue);
            streamElement.put(timeField, x.getMillis());
        } catch (IllegalArgumentException e) {
            logger.error("Parsing error: TimeFormat=" + timeFormat + " , TimeValue=" + timeValue);
            logger.error(e.getMessage(), e);
            throw e;
        }
    }

    return streamElement;
}

From source file:com.termmed.reconciliation.RelationshipReconciliation.java

/**
 * Compare prev inact.//from   ww  w. ja v a  2  s  .  co m
 *
 * @param step the step
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
private String comparePrevInact(int step) throws IOException {
    // STATISTICS COUNTERS
    int countSameISA = 0;
    int countA_Diff = 0;
    int countB_Diff = 0;
    int countB_DiffISA = 0;
    int countB_Total = 0;
    int sumPrevInact = 0;
    int sumNewNoRec = 0;
    long startTime = System.currentTimeMillis();

    StringBuilder s = new StringBuilder();
    s.append(
            "\r\n::: [Reconciliation by previous inactives vs current actives, without grouping comparation - step:"
                    + step + "]");

    boolean reconciled = false;
    for (Long conceptId : newNoRec.keySet()) {
        TreeMap<String, Relationship> relsPrev = prevInact.get(conceptId);
        ArrayList<Relationship> relsCurr = newNoRec.get(conceptId);
        sumNewNoRec += relsCurr.size();
        if (relsPrev != null) {
            sumPrevInact += relsPrev.size();
            for (Relationship relC : relsCurr) {
                reconciled = false;
                for (String key : relsPrev.descendingKeySet()) {
                    Relationship relP = relsPrev.get(key);
                    if (compareRelsStep(relC, relP, step)) {
                        writeReconciled(bw, relC, relP);

                        countB_Total++;
                        if (relC.typeId == isa) {
                            countSameISA++;
                        }
                        reconciled = true;
                        relsPrev.remove(key);
                        break;
                    }
                }
                if (!reconciled) {
                    countB_Diff++;
                    if (relC.typeId == isa) {
                        countB_DiffISA++;
                    }
                    writeNewNoRec(relC);
                }
            }
            prevInact.put(conceptId, relsPrev);
        } else {
            for (Relationship relC : relsCurr) {
                countB_Diff++;
                if (relC.typeId == isa) {
                    countB_DiffISA++;
                }
                writeNewNoRec(relC);

            }
        }

    }

    s.append("\r\n::: Current active relationships to reconcile = \t" + sumNewNoRec);
    s.append("\r\n::: Candidate previous inactive relationships to match = \t" + sumPrevInact);

    s.append("\r\n::: Partial process statistics:");
    s.append("\r\n::: Reconciled relationships:  \t").append(countB_Total);
    s.append("\r\n::: Reconciled Isa's relationships:  \t").append(countSameISA);
    s.append("\r\n::: Previous relationships without match :   \t").append(countA_Diff);
    s.append("\r\n::: Current relationships without match:   \t").append(countB_Diff);
    s.append("\r\n::: Current Isa's relationships without match:\t").append(countB_DiffISA);
    s.append("\r\n::: ");

    long lapseTime = System.currentTimeMillis() - startTime;
    s.append("\r\n::: [Partial time] Sort/Compare Input & Output: \t").append(lapseTime);
    s.append("\t(mS)\t");
    s.append("\r\n");

    sumB_Total += countB_Total;
    sumSameISA += countSameISA;
    sumA_Diff = countA_Diff;
    sumB_Diff = countB_Diff;
    sumB_DiffISA = countB_DiffISA;

    return s.toString();
}

From source file:com.att.aro.core.packetanalysis.impl.VideoUsageAnalysisImpl.java

/**
 * Extract a video from traffic data//from  w w w  .ja v a2 s.  com
 *
 * @param request
 * @param session
 * @param vManifest
 * @param fileName
 */
public void extractVideo(HttpRequestResponseInfo request, AROManifest vManifest, String fileName) {
    HttpRequestResponseInfo response = request.getAssocReqResp();
    log.info("-------");
    log.info(request.getObjUri().toString());
    log.info(request.getAllHeaders());
    log.info(request.getAssocReqResp().getAllHeaders());
    log.elevatedInfo(String.format("extractVideo %.4f", request.getTimeStamp()));
    String quality = "";
    ArrayList<ByteRange> rangeList = new ArrayList<>();
    double bitrate = 0;
    double segment = 0;
    double duration = 0;

    String fullName = extractFullNameFromRRInfo(request);
    byte[] content = null;
    String fullpath;

    VideoEventData ved = parseRequestResponse(request);
    if (ved.getSegment() == null && ved.getSegmentReference() == null) {
        log.elevatedInfo("parse failure :" + request.getObjUri().toString() + ved);
        ved.setSegment(-4);
    }
    VideoFormat vFormat = findVideoFormat(ved.getExtension());

    log.debug("aroManifest :" + vManifest);

    try {
        content = extractContent(request);
        if (content.length == 0) {
            return;
        }
        vManifest = matchManifest(request, vManifest, ved, vFormat);
        vManifest.adhocSegment(ved);
    } catch (Exception e) {
        videoUsage.addFailedRequestMap(request);
        log.debug("Failed to extract " + getTimeString(response) + fileName + ", range: " + ved.getByteRange()
                + ", error: " + e.getMessage());
        return;
    }
    quality = ved.getQuality() == null ? "unknown" : ved.getQuality();
    rangeList.add(ved.getByteRange());
    segment = ved.getSegment() != null && ved.getSegment() >= 0 ? ved.getSegment()
            : vManifest.parseSegment(fullName, ved);
    // set format handled by aroManifest
    if (VideoFormat.UNKNOWN.equals(vManifest.getVideoFormat())) {
        vManifest.setVideoFormat(vFormat);
    }
    double segmentStartTime = 0;
    if (vManifest instanceof ManifestDash) {
        bitrate = ((ManifestDash) vManifest).getBandwith(truncateString(fullName, "_"));
        timeScale = vManifest.getTimeScale();
    } else if (vManifest instanceof ManifestDashPlayReady) {
        if (segment > 0) {
            bitrate = vManifest.getBitrate(ved.getQuality());
            timeScale = vManifest.getTimeScale();
        }
    } else if (vManifest instanceof ManifestHLS) {
        if (ved.getDuration() != null) {
            try {
                duration = Double.valueOf(ved.getDuration());
            } catch (NumberFormatException e) {
                duration = 0;
            }
        }
        if (duration == 0) {
            try {
                duration = Double.valueOf(vManifest.getDuration((int) segment));
            } catch (NumberFormatException e) {
                duration = 0;
            }
            if (duration == 0) {
                duration = vManifest.getDuration();
            }
        }
        timeScale = 1;
        try {
            Double temp = vManifest.getBitrate(quality);
            if (temp == null) {
                temp = vManifest.getBitrate("HLS" + quality);
            }
            bitrate = temp != null ? temp : 0D;
        } catch (Exception e) {
            log.info("invalid quality :" + quality);
        }
    } else {
        // TODO some other way
    }
    log.debug("trunk " + fileName + ", getTimeString(response) :" + getTimeString(response));
    byte[] thumbnail = null;
    Integer[] segmentMetaData = new Integer[2];
    String segName = null;
    segmentMetaData[0] = content.length;
    if (vManifest instanceof ManifestDash) {
        segmentMetaData = parsePayload(content);
    } else if (vManifest instanceof ManifestHLS) {
        segmentStartTime = 0;
    }
    if (segment < 0 && segmentMetaData[1] != null) {
        segment = segmentMetaData[1];
    }
    fullpath = constructDebugName(request, ved);
    log.debug(fileName + ", content.length :" + content.length);
    if (segment == 0 && vManifest.isVideoType(VideoType.DASH)) {
        VideoData vData = new VideoData(vManifest.getEventType(), quality, content);
        vManifest.addVData(vData);
    } else {
        String seg = String.format("%08d", ((Double) segment).intValue());
        segName = getDebugPath() + seg + '_' + ved.getId() + '.' + ved.getExtension();
        thumbnail = extractThumbnail(vManifest, content, ved);
    }
    try {
        filemanager.saveFile(new ByteArrayInputStream(content), fullpath);
    } catch (IOException e) {
        log.error("Failed to save segment " + getTimeString(response) + fileName + ", range: "
                + ved.getByteRange() + ", error: " + e.getMessage());
        return;
    }
    TreeMap<String, Double> metaData = null;
    if (thumbnail != null) {
        metaData = extractMetadata(segName);
        if (metaData != null) {
            Double val = metaData.get("bitrate");
            if (val != null) {
                bitrate = val;
            }
            val = metaData.get("Duration");
            if (val != null) {
                duration = val;
            }
            val = metaData.get("SegmentStart");
            if (val != null) {
                segmentStartTime = val;
            }
        }
    }
    if (segment > 0) {
        segmentStartTime = segmentMetaData[1] != null ? segmentMetaData[1].doubleValue() / timeScale : 0;
    }
    // a negative value indicates segment startTime
    // later will scan over segments & set times based on next segmentStartTime
    if (vManifest instanceof ManifestDash || duration == 0) {
        duration -= segmentStartTime;
    }
    if (thumbnail == null) {
        thumbnail = altImage;
    }
    VideoEvent vEvent = new VideoEvent(ved, thumbnail, vManifest, segment, quality, rangeList, bitrate,
            duration, segmentStartTime, segmentMetaData[0], response);
    vManifest.addVideoEvent(segment, response.getTimeStamp(), vEvent);

    aroManifest = vManifest;
}

From source file:org.opendatakit.database.data.ColumnDefinitionTest.java

@SuppressWarnings("unchecked")
@Test/*w  ww . jav a  2s . c o m*/
public void testBuildExtendedJson() {
    List<Column> columns = new ArrayList<Column>();

    // arbitrary type derived from integer
    columns.add(new Column("col0", "col0", "myothertype:integer", "[]"));
    // primitive types
    columns.add(new Column("col1", "col1", "boolean", "[]"));
    columns.add(new Column("col2", "col2", "integer", "[]"));
    columns.add(new Column("col3", "col3", "number", "[]"));
    columns.add(new Column("col4", "col4", "string", "[]"));
    // string with 500 varchars allocated to it
    columns.add(new Column("col5", "col5", "string(500)", "[]"));
    columns.add(new Column("col6", "col6", "configpath", "[]"));
    columns.add(new Column("col7", "col7", "rowpath", "[]"));
    // object type (geopoint)
    columns.add(new Column("col8", "col8", "geopoint",
            "[\"col8_accuracy\",\"col8_altitude\",\"col8_latitude\",\"col8_longitude\"]"));
    columns.add(new Column("col8_accuracy", "accuracy", "number", "[]"));
    columns.add(new Column("col8_altitude", "altitude", "number", "[]"));
    columns.add(new Column("col8_latitude", "latitude", "number", "[]"));
    columns.add(new Column("col8_longitude", "longitude", "number", "[]"));
    // arbitrary type derived from string
    columns.add(new Column("col9", "col9", "mytype", "[]"));

    // arrays
    columns.add(new Column("col12", "col12", "array", "[\"col12_items\"]"));
    columns.add(new Column("col12_items", "items", "integer", "[]"));
    // array with 500 varchars allocated to it
    columns.add(new Column("col14", "col14", "array(400)", "[\"col14_items\"]"));
    columns.add(new Column("col14_items", "items", "string", "[]"));

    columns.add(new Column("col1a", "col1a", "geolist:array(500)", "[\"col1a_items\"]"));
    columns.add(new Column("col1a_items", "items", "geopoint",
            "[\"col1a_items_accuracy\",\"col1a_items_altitude\",\"col1a_items_latitude\","
                    + "\"col1a_items_longitude\"]"));
    columns.add(new Column("col1a_items_accuracy", "accuracy", "number", "[]"));
    columns.add(new Column("col1a_items_altitude", "altitude", "number", "[]"));
    columns.add(new Column("col1a_items_latitude", "latitude", "number", "[]"));
    columns.add(new Column("col1a_items_longitude", "longitude", "number", "[]"));

    ArrayList<ColumnDefinition> colDefs = ColumnDefinition.buildColumnDefinitions("appName", "testTable",
            columns);

    String equivalentXLSXConverterDataTableModel = "{" + "\"col0\": {" + "\"type\": \"integer\","
            + "\"_defn\": [" + "{" + "\"_row_num\": 2," + "\"section_name\": \"model\"" + "}" + "],"
            + "\"elementType\": \"myothertype:integer\"," + "\"elementKey\": \"col0\","
            + "\"elementName\": \"col0\"," + "\"elementSet\": \"data\"," + "\"elementPath\": \"col0\"" + "},"
            + "\"col1\": {" + "\"type\": \"boolean\"," + "\"_defn\": [" + "{" + "\"_row_num\": 3,"
            + "\"section_name\": \"model\"" + "}" + "]," + "\"elementKey\": \"col1\","
            + "\"elementName\": \"col1\"," + "\"elementSet\": \"data\"," + "\"elementPath\": \"col1\"" + "},"
            + "\"col2\": {" + "\"type\": \"integer\"," + "\"_defn\": [" + "{" + "\"_row_num\": 4,"
            + "\"section_name\": \"model\"" + "}" + "]," + "\"elementKey\": \"col2\","
            + "\"elementName\": \"col2\"," + "\"elementSet\": \"data\"," + "\"elementPath\": \"col2\"" + "},"
            + "\"col3\": {" + "\"type\": \"number\"," + "\"_defn\": [" + "{" + "\"_row_num\": 5,"
            + "\"section_name\": \"model\"" + "}" + "]," + "\"elementKey\": \"col3\","
            + "\"elementName\": \"col3\"," + "\"elementSet\": \"data\"," + "\"elementPath\": \"col3\"" + "},"
            + "\"col4\": {" + "\"type\": \"string\"," + "\"_defn\": [" + "{" + "\"_row_num\": 6,"
            + "\"section_name\": \"model\"" + "}" + "]," + "\"elementKey\": \"col4\","
            + "\"elementName\": \"col4\"," + "\"elementSet\": \"data\"," + "\"elementPath\": \"col4\"" + "},"
            + "\"col5\": {" + "\"type\": \"string\"," + "\"_defn\": [" + "{" + "\"_row_num\": 7,"
            + "\"section_name\": \"model\"" + "}" + "]," + "\"elementType\": \"string(500)\","
            + "\"elementKey\": \"col5\"," + "\"elementName\": \"col5\"," + "\"elementSet\": \"data\","
            + "\"elementPath\": \"col5\"" + "}," + "\"col6\": {" + "\"type\": \"string\"," + "\"_defn\": ["
            + "{" + "\"_row_num\": 8," + "\"section_name\": \"model\"" + "}" + "],"
            + "\"elementType\": \"configpath\"," + "\"elementKey\": \"col6\"," + "\"elementName\": \"col6\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col6\"" + "}," + "\"col7\": {"
            + "\"type\": \"string\"," + "\"_defn\": [" + "{" + "\"_row_num\": 9,"
            + "\"section_name\": \"model\"" + "}" + "]," + "\"elementType\": \"rowpath\","
            + "\"elementKey\": \"col7\"," + "\"elementName\": \"col7\"," + "\"elementSet\": \"data\","
            + "\"elementPath\": \"col7\"" + "}," + "\"col8\": {" + "\"type\": \"object\","
            + "\"elementType\": \"geopoint\"," + "\"properties\": {" + "\"latitude\": {"
            + "\"type\": \"number\"," + "\"elementKey\": \"col8_latitude\"," + "\"elementName\": \"latitude\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col8.latitude\"" + "}," + "\"longitude\": {"
            + "\"type\": \"number\"," + "\"elementKey\": \"col8_longitude\","
            + "\"elementName\": \"longitude\"," + "\"elementSet\": \"data\","
            + "\"elementPath\": \"col8.longitude\"" + "}," + "\"altitude\": {" + "\"type\": \"number\","
            + "\"elementKey\": \"col8_altitude\"," + "\"elementName\": \"altitude\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col8.altitude\"" + "}," + "\"accuracy\": {"
            + "\"type\": \"number\"," + "\"elementKey\": \"col8_accuracy\"," + "\"elementName\": \"accuracy\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col8.accuracy\"" + "}" + "}," + "\"_defn\": ["
            + "{" + "\"_row_num\": 10," + "\"section_name\": \"model\"" + "}" + "],"
            + "\"elementKey\": \"col8\"," + "\"elementName\": \"col8\"," + "\"elementSet\": \"data\","
            + "\"elementPath\": \"col8\"," + "\"listChildElementKeys\": [" + "\"col8_accuracy\","
            + "\"col8_altitude\"," + "\"col8_latitude\"," + "\"col8_longitude\"" + "],"
            + "\"notUnitOfRetention\": true" + "}," + "\"col9\": {" + "\"type\": \"string\"," + "\"_defn\": ["
            + "{" + "\"_row_num\": 11," + "\"section_name\": \"model\"" + "}" + "],"
            + "\"elementType\": \"mytype\"," + "\"elementKey\": \"col9\"," + "\"elementName\": \"col9\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col9\"" + "}," + "\"col12\": {"
            + "\"type\": \"array\"," + "\"_defn\": [" + "{" + "\"_row_num\": 12,"
            + "\"section_name\": \"model\"" + "}" + "]," + "\"items\": {" + "\"type\": \"integer\","
            + "\"elementKey\": \"col12_items\"," + "\"elementName\": \"items\"," + "\"elementSet\": \"data\","
            + "\"elementPath\": \"col12.items\"," + "\"notUnitOfRetention\": true" + "},"
            + "\"elementKey\": \"col12\"," + "\"elementName\": \"col12\"," + "\"elementSet\": \"data\","
            + "\"elementPath\": \"col12\"," + "\"listChildElementKeys\": [" + "\"col12_items\"" + "]" + "},"
            + "\"col14\": {" + "\"type\": \"array\"," + "\"_defn\": [" + "{" + "\"_row_num\": 13,"
            + "\"section_name\": \"model\"" + "}" + "]," + "\"elementType\": \"array(400)\"," + "\"items\": {"
            + "\"type\": \"string\"," + "\"elementKey\": \"col14_items\"," + "\"elementName\": \"items\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col14.items\"," + "\"notUnitOfRetention\": true"
            + "}," + "\"elementKey\": \"col14\"," + "\"elementName\": \"col14\"," + "\"elementSet\": \"data\","
            + "\"elementPath\": \"col14\"," + "\"listChildElementKeys\": [" + "\"col14_items\"" + "]" + "},"
            + "\"col1a\": {" + "\"type\": \"array\"," + "\"_defn\": [" + "{" + "\"_row_num\": 14,"
            + "\"section_name\": \"model\"" + "}" + "]," + "\"elementType\": \"geolist:array(500)\","
            + "\"items\": {" + "\"type\": \"object\"," + "\"elementType\": \"geopoint\"," + "\"properties\": {"
            + "\"latitude\": {" + "\"type\": \"number\"," + "\"elementName\": \"latitude\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col1a.items.latitude\","
            + "\"elementKey\": \"col1a_items_latitude\"," + "\"notUnitOfRetention\": true" + "},"
            + "\"longitude\": {" + "\"type\": \"number\"," + "\"elementName\": \"longitude\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col1a.items.longitude\","
            + "\"elementKey\": \"col1a_items_longitude\"," + "\"notUnitOfRetention\": true" + "},"
            + "\"altitude\": {" + "\"type\": \"number\"," + "\"elementName\": \"altitude\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col1a.items.altitude\","
            + "\"elementKey\": \"col1a_items_altitude\"," + "\"notUnitOfRetention\": true" + "},"
            + "\"accuracy\": {" + "\"type\": \"number\"," + "\"elementName\": \"accuracy\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col1a.items.accuracy\","
            + "\"elementKey\": \"col1a_items_accuracy\"," + "\"notUnitOfRetention\": true" + "}" + "},"
            + "\"elementKey\": \"col1a_items\"," + "\"elementName\": \"items\"," + "\"elementSet\": \"data\","
            + "\"elementPath\": \"col1a.items\"," + "\"listChildElementKeys\": [" + "\"col1a_items_accuracy\","
            + "\"col1a_items_altitude\"," + "\"col1a_items_latitude\"," + "\"col1a_items_longitude\"" + "],"
            + "\"notUnitOfRetention\": true" + "}," + "\"elementKey\": \"col1a\","
            + "\"elementName\": \"col1a\"," + "\"elementSet\": \"data\"," + "\"elementPath\": \"col1a\","
            + "\"listChildElementKeys\": [" + "\"col1a_items\"" + "]" + "}," + "\"col8_latitude\": {"
            + "\"type\": \"number\"," + "\"elementKey\": \"col8_latitude\"," + "\"elementName\": \"latitude\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col8.latitude\"" + "},"
            + "\"col8_longitude\": {" + "\"type\": \"number\"," + "\"elementKey\": \"col8_longitude\","
            + "\"elementName\": \"longitude\"," + "\"elementSet\": \"data\","
            + "\"elementPath\": \"col8.longitude\"" + "}," + "\"col8_altitude\": {" + "\"type\": \"number\","
            + "\"elementKey\": \"col8_altitude\"," + "\"elementName\": \"altitude\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col8.altitude\"" + "}," + "\"col8_accuracy\": {"
            + "\"type\": \"number\"," + "\"elementKey\": \"col8_accuracy\"," + "\"elementName\": \"accuracy\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col8.accuracy\"" + "}," + "\"col12_items\": {"
            + "\"type\": \"integer\"," + "\"elementKey\": \"col12_items\"," + "\"elementName\": \"items\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col12.items\"," + "\"notUnitOfRetention\": true"
            + "}," + "\"col14_items\": {" + "\"type\": \"string\"," + "\"elementKey\": \"col14_items\","
            + "\"elementName\": \"items\"," + "\"elementSet\": \"data\"," + "\"elementPath\": \"col14.items\","
            + "\"notUnitOfRetention\": true" + "}," + "\"col1a_items\": {" + "\"type\": \"object\","
            + "\"elementType\": \"geopoint\"," + "\"properties\": {" + "\"latitude\": {"
            + "\"type\": \"number\"," + "\"elementName\": \"latitude\"," + "\"elementSet\": \"data\","
            + "\"elementPath\": \"col1a.items.latitude\"," + "\"elementKey\": \"col1a_items_latitude\","
            + "\"notUnitOfRetention\": true" + "}," + "\"longitude\": {" + "\"type\": \"number\","
            + "\"elementName\": \"longitude\"," + "\"elementSet\": \"data\","
            + "\"elementPath\": \"col1a.items.longitude\"," + "\"elementKey\": \"col1a_items_longitude\","
            + "\"notUnitOfRetention\": true" + "}," + "\"altitude\": {" + "\"type\": \"number\","
            + "\"elementName\": \"altitude\"," + "\"elementSet\": \"data\","
            + "\"elementPath\": \"col1a.items.altitude\"," + "\"elementKey\": \"col1a_items_altitude\","
            + "\"notUnitOfRetention\": true" + "}," + "\"accuracy\": {" + "\"type\": \"number\","
            + "\"elementName\": \"accuracy\"," + "\"elementSet\": \"data\","
            + "\"elementPath\": \"col1a.items.accuracy\"," + "\"elementKey\": \"col1a_items_accuracy\","
            + "\"notUnitOfRetention\": true" + "}" + "}," + "\"elementKey\": \"col1a_items\","
            + "\"elementName\": \"items\"," + "\"elementSet\": \"data\"," + "\"elementPath\": \"col1a.items\","
            + "\"listChildElementKeys\": [" + "\"col1a_items_accuracy\"," + "\"col1a_items_altitude\","
            + "\"col1a_items_latitude\"," + "\"col1a_items_longitude\"" + "]," + "\"notUnitOfRetention\": true"
            + "}," + "\"col1a_items_latitude\": {" + "\"type\": \"number\"," + "\"elementName\": \"latitude\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col1a.items.latitude\","
            + "\"elementKey\": \"col1a_items_latitude\"," + "\"notUnitOfRetention\": true" + "},"
            + "\"col1a_items_longitude\": {" + "\"type\": \"number\"," + "\"elementName\": \"longitude\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col1a.items.longitude\","
            + "\"elementKey\": \"col1a_items_longitude\"," + "\"notUnitOfRetention\": true" + "},"
            + "\"col1a_items_altitude\": {" + "\"type\": \"number\"," + "\"elementName\": \"altitude\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col1a.items.altitude\","
            + "\"elementKey\": \"col1a_items_altitude\"," + "\"notUnitOfRetention\": true" + "},"
            + "\"col1a_items_accuracy\": {" + "\"type\": \"number\"," + "\"elementName\": \"accuracy\","
            + "\"elementSet\": \"data\"," + "\"elementPath\": \"col1a.items.accuracy\","
            + "\"elementKey\": \"col1a_items_accuracy\"," + "\"notUnitOfRetention\": true" + "}," + "\"_id\": {"
            + "\"type\": \"string\"," + "\"isNotNullable\": true," + "\"elementKey\": \"_id\","
            + "\"elementName\": \"_id\"," + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_id\""
            + "}," + "\"_row_etag\": {" + "\"type\": \"string\"," + "\"isNotNullable\": false,"
            + "\"elementKey\": \"_row_etag\"," + "\"elementName\": \"_row_etag\","
            + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_row_etag\"" + "},"
            + "\"_sync_state\": {" + "\"type\": \"string\"," + "\"isNotNullable\": true,"
            + "\"elementKey\": \"_sync_state\"," + "\"elementName\": \"_sync_state\","
            + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_sync_state\"" + "},"
            + "\"_conflict_type\": {" + "\"type\": \"integer\"," + "\"isNotNullable\": false,"
            + "\"elementKey\": \"_conflict_type\"," + "\"elementName\": \"_conflict_type\","
            + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_conflict_type\"" + "},"
            + "\"_default_access\": {" + "\"type\": \"string\"," + "\"isNotNullable\": false,"
            + "\"elementKey\": \"_default_access\"," + "\"elementName\": \"_default_access\","
            + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_default_access\"" + "},"
            + "\"_row_owner\": {" + "\"type\": \"string\"," + "\"isNotNullable\": false,"
            + "\"elementKey\": \"_row_owner\"," + "\"elementName\": \"_row_owner\","
            + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_row_owner\"" + "},"
            + "\"_group_read_only\": {" + "\"type\": \"string\"," + "\"isNotNullable\": false,"
            + "\"elementKey\": \"_group_read_only\"," + "\"elementName\": \"_group_read_only\","
            + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_group_read_only\"" + "},"
            + "\"_group_modify\": {" + "\"type\": \"string\"," + "\"isNotNullable\": false,"
            + "\"elementKey\": \"_group_modify\"," + "\"elementName\": \"_group_modify\","
            + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_group_modify\"" + "},"
            + "\"_group_privileged\": {" + "\"type\": \"string\"," + "\"isNotNullable\": false,"
            + "\"elementKey\": \"_group_privileged\"," + "\"elementName\": \"_group_privileged\","
            + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_group_privileged\"" + "},"
            + "\"_form_id\": {" + "\"type\": \"string\"," + "\"isNotNullable\": false,"
            + "\"elementKey\": \"_form_id\"," + "\"elementName\": \"_form_id\","
            + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_form_id\"" + "},"
            + "\"_locale\": {" + "\"type\": \"string\"," + "\"isNotNullable\": false,"
            + "\"elementKey\": \"_locale\"," + "\"elementName\": \"_locale\","
            + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_locale\"" + "},"
            + "\"_savepoint_type\": {" + "\"type\": \"string\"," + "\"isNotNullable\": false,"
            + "\"elementKey\": \"_savepoint_type\"," + "\"elementName\": \"_savepoint_type\","
            + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_savepoint_type\"" + "},"
            + "\"_savepoint_timestamp\": {" + "\"type\": \"string\"," + "\"isNotNullable\": true,"
            + "\"elementKey\": \"_savepoint_timestamp\"," + "\"elementName\": \"_savepoint_timestamp\","
            + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_savepoint_timestamp\"" + "},"
            + "\"_savepoint_creator\": {" + "\"type\": \"string\"," + "\"isNotNullable\": false,"
            + "\"elementKey\": \"_savepoint_creator\"," + "\"elementName\": \"_savepoint_creator\","
            + "\"elementSet\": \"instanceMetadata\"," + "\"elementPath\": \"_savepoint_creator\"" + "}" + "}";
    int metaCount = 0;
    TreeMap<String, Object> model = ColumnDefinition.getExtendedDataModel(colDefs);
    TypeReference<TreeMap<String, Object>> refType = new TypeReference<TreeMap<String, Object>>() {
    };
    TreeMap<String, Object> xlsxModel;
    try {
        xlsxModel = ODKFileUtils.mapper.readValue(equivalentXLSXConverterDataTableModel, refType);
    } catch (IOException e) {
        assertFalse("failed to parse XLSXConverter version", true);
        return;
    }

    for (String elementKey : model.keySet()) {
        TreeMap<String, Object> value = (TreeMap<String, Object>) model.get(elementKey);
        assert (xlsxModel.containsKey(elementKey));
        Map<String, Object> xlsxValue = (Map<String, Object>) xlsxModel.get(elementKey);
        List<String> ignoredKeys = new ArrayList<String>();
        for (String key : xlsxValue.keySet()) {
            if (key.startsWith("_")) {
                ignoredKeys.add(key);
            }
            if (key.equals("prompt_type_name")) {
                ignoredKeys.add(key);
            }
        }
        for (String key : ignoredKeys) {
            xlsxValue.remove(key);
        }
        assertEquals("Investigating: " + elementKey, value.size(), xlsxValue.size());
        recursiveMatch(elementKey, value, xlsxValue);

        ColumnDefinition def = null;
        try {
            def = ColumnDefinition.find(colDefs, elementKey);
        } catch (IllegalArgumentException e) {
            // ignore
        }
        if (def == null) {
            assertEquals(value.get("elementSet"), "instanceMetadata");
            assertEquals(value.get("elementKey"), elementKey);
            assertEquals(value.get("elementName"), elementKey);
            assertEquals(value.get("elementPath"), elementKey);
            assertEquals(value.containsKey("notUnitOfRetention"), false);

            if (elementKey.equals(TableConstants.ID)) {
                metaCount++;
                assertEquals(value.get("type"), "string");
                assertEquals(value.get("isNotNullable"), true);
            } else if (elementKey.equals(TableConstants.ROW_ETAG)) {
                metaCount++;
                assertEquals(value.get("type"), "string");
                assertEquals(value.get("isNotNullable"), false);
            } else if (elementKey.equals(TableConstants.SYNC_STATE)) {
                metaCount++;
                assertEquals(value.get("type"), "string");
                assertEquals(value.get("isNotNullable"), true);
            } else if (elementKey.equals(TableConstants.CONFLICT_TYPE)) {
                metaCount++;
                assertEquals(value.get("type"), "integer");
                assertEquals(value.get("isNotNullable"), false);
            } else if (elementKey.equals(TableConstants.DEFAULT_ACCESS)) {
                metaCount++;
                assertEquals(value.get("type"), "string");
                assertEquals(value.get("isNotNullable"), false);
            } else if (elementKey.equals(TableConstants.ROW_OWNER)) {
                metaCount++;
                assertEquals(value.get("type"), "string");
                assertEquals(value.get("isNotNullable"), false);
            } else if (elementKey.equals(TableConstants.GROUP_READ_ONLY)) {
                metaCount++;
                assertEquals(value.get("type"), "string");
                assertEquals(value.get("isNotNullable"), false);
            } else if (elementKey.equals(TableConstants.GROUP_MODIFY)) {
                metaCount++;
                assertEquals(value.get("type"), "string");
                assertEquals(value.get("isNotNullable"), false);
            } else if (elementKey.equals(TableConstants.GROUP_PRIVILEGED)) {
                metaCount++;
                assertEquals(value.get("type"), "string");
                assertEquals(value.get("isNotNullable"), false);
            } else if (elementKey.equals(TableConstants.SAVEPOINT_TIMESTAMP)) {
                metaCount++;
                assertEquals(value.get("type"), "string");
                assertEquals(value.get("isNotNullable"), true);
            } else if (elementKey.equals(TableConstants.SAVEPOINT_TYPE)) {
                metaCount++;
                assertEquals(value.get("type"), "string");
                assertEquals(value.get("isNotNullable"), false);
            } else if (elementKey.equals(TableConstants.SAVEPOINT_CREATOR)) {
                metaCount++;
                assertEquals(value.get("type"), "string");
                assertEquals(value.get("isNotNullable"), false);
            } else if (elementKey.equals(TableConstants.FORM_ID)) {
                metaCount++;
                assertEquals(value.get("type"), "string");
                assertEquals(value.get("isNotNullable"), false);
            } else if (elementKey.equals(TableConstants.LOCALE)) {
                metaCount++;
                assertEquals(value.get("type"), "string");
                assertEquals(value.get("isNotNullable"), false);
            } else {
                throw new IllegalStateException("Unexpected non-user column");
            }
        } else {
            assertEquals(value.get("elementPath"), def.getElementName());
            assertEquals(value.get("elementSet"), "data");
            assertEquals(value.get("elementName"), def.getElementName());
            assertEquals(value.get("elementKey"), def.getElementKey());
            if (!def.isUnitOfRetention()) {
                assertEquals(value.get("notUnitOfRetention"), true);
            }
            // TODO: there are a lot more paths to verify here...
            assertEquals(value.containsKey("isNotNullable"), false);
        }
    }
    assertEquals(metaCount, 14);
}

From source file:com.itemanalysis.jmetrik.graph.density.DensityAnalysis.java

public XYSeriesCollection summarize() throws SQLException, IllegalArgumentException {
    Statement stmt = null;//from w w w  .j a  v  a 2  s.  c om
    ResultSet rs = null;
    TreeMap<String, ResizableDoubleArray> data = new TreeMap<String, ResizableDoubleArray>();

    //set progress bar information
    int nrow = 0;
    JmetrikPreferencesManager pref = new JmetrikPreferencesManager();
    String dbType = pref.getDatabaseType();
    if (DatabaseType.APACHE_DERBY.toString().equals(dbType)) {
        JmetrikDatabaseFactory dbFactory = new JmetrikDatabaseFactory(DatabaseType.APACHE_DERBY);
        nrow = dao.getRowCount(conn, tableName);
    } else {
        //add other databases here when functionality is added
    }
    maxProgress = (double) nrow;

    Table sqlTable = new Table(tableName.getNameForDatabase());
    SelectQuery select = new SelectQuery();
    select.addColumn(sqlTable, variable.getName().nameForDatabase());
    if (hasGroupingVariable)
        select.addColumn(sqlTable, groupVar.getName().nameForDatabase());
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery(select.toString());

    String conditionalName = "";
    ResizableDoubleArray cData = null;
    double value = Double.NaN;

    while (rs.next()) {
        if (groupVar != null) {
            String groupName = rs.getString(groupVar.getName().nameForDatabase());
            if (rs.wasNull()) {
                groupName = "";
            }
            conditionalName = groupName;
        } else {
            conditionalName = "Series 1";
        }

        cData = data.get(conditionalName);
        if (cData == null) {
            cData = new ResizableDoubleArray((int) maxProgress);
            data.put(conditionalName, cData);
        }
        value = rs.getDouble(variable.getName().nameForDatabase());
        if (!rs.wasNull()) {
            cData.addElement(value);
        }
        updateProgress();
    }
    rs.close();
    stmt.close();

    String kType = command.getSelectOneOption("kernel").getSelectedArgument();
    double adjustment = command.getFreeOption("adjust").getDouble();
    KernelFactory kernelFactory = new KernelFactory(kType);

    KernelFunction kernelFunction = kernelFactory.getKernelFunction();
    Bandwidth bandwidth = null;
    KernelDensity density = null;
    UniformDistributionApproximation uniform = null;
    Min min = new Min();
    Max max = new Max();
    double[] x = null;

    this.firePropertyChange("progress-ind-on", null, null);

    XYSeriesCollection seriesCollection = new XYSeriesCollection();
    XYSeries series = null;
    for (String s : data.keySet()) {
        series = new XYSeries(s);
        x = data.get(s).getElements();
        bandwidth = new ScottsBandwidth(x, adjustment);
        uniform = new UniformDistributionApproximation(min.evaluate(x), max.evaluate(x), KERNEL_POINTS);
        density = new KernelDensity(kernelFunction, bandwidth, uniform);

        double[] dens = density.evaluate(x);
        double[] points = density.getPoints();
        for (int i = 0; i < dens.length; i++) {
            series.add(points[i], dens[i]);
        }
        seriesCollection.addSeries(series);
    }
    return seriesCollection;

}

From source file:org.apache.hadoop.chukwa.inputtools.mdl.TorqueInfoProcessor.java

private void getHodJobInfo() throws IOException {
    StringBuffer sb = new StringBuffer();
    sb.append(torqueBinDir).append("/qstat -a");

    String[] getQueueInfoCommand = new String[3];
    getQueueInfoCommand[0] = "ssh";
    getQueueInfoCommand[1] = torqueServer;
    getQueueInfoCommand[2] = sb.toString();

    String command = getQueueInfoCommand[0] + " " + getQueueInfoCommand[1] + " " + getQueueInfoCommand[2];
    ProcessBuilder pb = new ProcessBuilder(getQueueInfoCommand);

    Process p = pb.start();//  w w  w.  ja  v  a2 s.  c o  m

    Timer timeout = new Timer();
    TorqueTimerTask torqueTimerTask = new TorqueTimerTask(p, command);
    timeout.schedule(torqueTimerTask, TorqueTimerTask.timeoutInterval * 1000);

    BufferedReader result = new BufferedReader(new InputStreamReader(p.getInputStream()));
    ErStreamHandler errorHandler = new ErStreamHandler(p.getErrorStream(), command, true);
    errorHandler.start();

    String line = null;
    boolean start = false;
    TreeSet<String> jobsInTorque = new TreeSet<String>();
    while ((line = result.readLine()) != null) {
        if (line.startsWith("---")) {
            start = true;
            continue;
        }

        if (start) {
            String[] items = line.split("\\s+");
            if (items.length >= 10) {
                String hodIdLong = items[0];
                String hodId = hodIdLong.split("[.]")[0];
                String userId = items[1];
                String numOfMachine = items[5];
                String status = items[9];
                jobsInTorque.add(hodId);
                if (!currentHodJobs.containsKey(hodId)) {
                    TreeMap<String, String> aJobData = new TreeMap<String, String>();

                    aJobData.put("userId", userId);
                    aJobData.put("numOfMachine", numOfMachine);
                    aJobData.put("traceCheckCount", "0");
                    aJobData.put("process", "0");
                    aJobData.put("status", status);
                    currentHodJobs.put(hodId, aJobData);
                } else {
                    TreeMap<String, String> aJobData = currentHodJobs.get(hodId);
                    aJobData.put("status", status);
                    currentHodJobs.put(hodId, aJobData);
                } // if..else
            }
        }
    } // while

    try {
        errorHandler.join();
    } catch (InterruptedException ie) {
        log.error(ie.getMessage());
    }
    timeout.cancel();

    Set<String> currentHodJobIds = currentHodJobs.keySet();
    Iterator<String> currentHodJobIdsIt = currentHodJobIds.iterator();
    TreeSet<String> finishedHodIds = new TreeSet<String>();
    while (currentHodJobIdsIt.hasNext()) {
        String hodId = currentHodJobIdsIt.next();
        if (!jobsInTorque.contains(hodId)) {
            TreeMap<String, String> aJobData = currentHodJobs.get(hodId);
            String process = aJobData.get("process");
            if (process.equals("0") || process.equals("1")) {
                aJobData.put("status", "C");
            } else {
                finishedHodIds.add(hodId);
            }
        }
    } // while

    Iterator<String> finishedHodIdsIt = finishedHodIds.iterator();
    while (finishedHodIdsIt.hasNext()) {
        String hodId = finishedHodIdsIt.next();
        currentHodJobs.remove(hodId);
    }

}

From source file:com.clust4j.algo.HDBSCAN.java

protected static int[] doLabeling(ArrayList<CompQuadTup<Integer, Integer, Double, Integer>> tree,
        ArrayList<Integer> clusters, TreeMap<Integer, Integer> clusterMap) {

    CompQuadTup<Integer, Integer, Double, Integer> quad;
    int rootCluster, parent, child, n = tree.size(), cluster, i;
    int[] resultArr, parentArr = new int[n], childArr = new int[n];
    UnifiedFinder unionFind;/*ww w .  j a v a2s .  co  m*/

    // [parent, child, lambda, size]
    int maxParent = Integer.MIN_VALUE;
    int minParent = Integer.MAX_VALUE;
    for (i = 0; i < n; i++) {
        quad = tree.get(i);
        parentArr[i] = quad.getFirst();
        childArr[i] = quad.getSecond();

        if (quad.getFirst() < minParent)
            minParent = quad.getFirst();
        if (quad.getFirst() > maxParent)
            maxParent = quad.getFirst();
    }

    rootCluster = minParent;
    resultArr = new int[rootCluster];
    unionFind = new TreeUnionFind(maxParent + 1);

    for (i = 0; i < n; i++) {
        child = childArr[i];
        parent = parentArr[i];
        if (!clusters.contains(child))
            unionFind.union(parent, child);
    }

    for (i = 0; i < rootCluster; i++) {
        cluster = unionFind.find(i);
        if (cluster <= rootCluster)
            resultArr[i] = NOISE_CLASS;
        else
            resultArr[i] = clusterMap.get(cluster);
    }

    return resultArr;
}