Example usage for java.util TreeMap size

List of usage examples for java.util TreeMap size

Introduction

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

Prototype

int size

To view the source code for java.util TreeMap size.

Click Source Link

Document

The number of entries in the tree

Usage

From source file:chibi.gemmaanalysis.CoexpressionAnalysisService.java

/**
 * Calculates all pairwise correlations between the query and target composite sequences and then takes the median
 * correlation//from w w  w  .j a  va2 s  .com
 * 
 * @param queryCss
 * @param targetCss
 * @param dataMatrix
 * @return
 */
private CorrelationSampleSize calculateCorrelation(Collection<CompositeSequence> queryCss,
        Collection<CompositeSequence> targetCss, ExpressionDataDoubleMatrix dataMatrix,
        CorrelationMethod method) {
    TreeMap<Double, Double> correlNumUsedMap = new TreeMap<Double, Double>();
    // calculate all pairwise correlations between cs groups
    for (CompositeSequence queryCs : queryCss) {
        for (CompositeSequence targetCs : targetCss) {
            Double[] queryVals = dataMatrix.getRow(queryCs);
            Double[] targetVals = dataMatrix.getRow(targetCs);
            if (queryVals != null && targetVals != null) {
                double[] v1 = new double[queryVals.length];
                double[] v2 = new double[targetVals.length];
                for (int i = 0; i < queryVals.length; i++) {
                    if (queryVals[i] != null)
                        v1[i] = queryVals[i];
                    else
                        v1[i] = Double.NaN;
                }
                for (int i = 0; i < targetVals.length; i++) {
                    if (targetVals[i] != null)
                        v2[i] = targetVals[i];
                    else
                        v2[i] = Double.NaN;
                }

                int numUsed = 0;
                for (int i = 0; i < v1.length && i < v2.length; i++)
                    if (!Double.isNaN(v1[i]) && !Double.isNaN(v2[i]))
                        numUsed++;
                if (numUsed > MIN_NUM_USED) {
                    double correlation;
                    switch (method) {
                    case SPEARMAN:
                        correlation = Distance.spearmanRankCorrelation(new DoubleArrayList(v1),
                                new DoubleArrayList(v2));
                        break;
                    case PEARSON:
                    default:
                        correlation = CorrelationStats.correl(v1, v2);

                    }
                    correlNumUsedMap.put(correlation, (double) numUsed);
                }
            }
        }
    }
    if (correlNumUsedMap.size() == 0) {
        return null;
    }
    List<Double> correlations = new ArrayList<Double>(correlNumUsedMap.keySet());
    // take the median correlation
    Double correlation = correlations.get(correlations.size() / 2);
    Double sampleSize = correlNumUsedMap.get(correlation);
    CorrelationSampleSize c = new CorrelationSampleSize();
    c.correlation = correlation;
    c.sampleSize = sampleSize;
    return c;

}

From source file:org.opencms.workplace.explorer.CmsNewResourceXmlPage.java

/**
 * Returns a sorted Map of all available elements in the specified subfolder of the OpenCms modules.<p>
 * //from   w w w  .  j  a  v a  2s . c  om
 * @param cms the current cms object
 * @param elementFolder the module subfolder to search for elements
 * @param currWpPath the current path in the OpenCms workplace
 * @param emptyMap flag indicating if it is OK to return a filtered empty Map
 * 
 * @return a sorted map with the element title as key and absolute path to the element as value
 * 
 * @throws CmsException if reading a folder or file fails
 */
protected static TreeMap getElements(CmsObject cms, String elementFolder, String currWpPath, boolean emptyMap)
        throws CmsException {

    TreeMap elements = new TreeMap();
    TreeMap allElements = new TreeMap();

    if (CmsStringUtil.isNotEmpty(currWpPath)) {
        // add site root to current workplace path
        currWpPath = cms.getRequestContext().addSiteRoot(currWpPath);
    }

    // get all visible template elements in the module folders
    List modules = cms.getSubFolders(CmsWorkplace.VFS_PATH_MODULES, CmsResourceFilter.IGNORE_EXPIRATION);
    for (int i = 0; i < modules.size(); i++) {
        List moduleTemplateFiles = new ArrayList();
        String folder = cms.getSitePath((CmsFolder) modules.get(i));
        try {
            moduleTemplateFiles = cms.getFilesInFolder(folder + elementFolder,
                    CmsResourceFilter.DEFAULT.addRequireVisible());
        } catch (CmsException e) {
            // folder not available, list will be empty
            if (LOG.isDebugEnabled()) {
                LOG.debug(e.getMessage(), e);
            }
        }
        for (int j = 0; j < moduleTemplateFiles.size(); j++) {
            // get the current template file
            CmsFile templateFile = (CmsFile) moduleTemplateFiles.get(j);
            String title = null;
            String folderProp = null;
            try {
                title = cms.readPropertyObject(cms.getSitePath(templateFile),
                        CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();
                folderProp = cms.readPropertyObject(templateFile,
                        CmsPropertyDefinition.PROPERTY_FOLDERS_AVAILABLE, false).getValue();
            } catch (CmsException e) {
                // property not available, will be null
                if (LOG.isInfoEnabled()) {
                    LOG.info(e);
                }
            }

            boolean isInFolder = false;
            // check template folders property value
            if (CmsStringUtil.isNotEmpty(currWpPath) && CmsStringUtil.isNotEmpty(folderProp)) {
                // property value set on template, check if current workplace path fits
                List folders = CmsStringUtil.splitAsList(folderProp, DELIM_PROPERTYVALUES);
                for (int k = 0; k < folders.size(); k++) {
                    String checkFolder = (String) folders.get(k);
                    if (currWpPath.startsWith(checkFolder)) {
                        isInFolder = true;
                        break;
                    }
                }
            } else {
                isInFolder = true;
            }

            if (title == null) {
                // no title property found, display the file name
                title = templateFile.getName();
            }
            String path = cms.getSitePath(templateFile);
            if (isInFolder) {
                // element is valid, add it to result
                elements.put(title, path);
            }
            // also put element to overall result
            allElements.put(title, path);
        }
    }
    if (!emptyMap && (elements.size() < 1)) {
        // empty Map should not be returned, return all collected elements
        return allElements;
    }
    // return the filtered elements sorted by title
    return elements;
}

From source file:ukhas.Habitat_interface.java

private boolean getPayloadDataSince(long timestampStart, long timestampStop, int limit, String payloadID,
        String callsign) {/*from ww w. j a v a  2 s . co m*/
    double prevAltitude = -99999999;
    double maxAltitude = -99999999;
    long prevtime = -1;
    try {

        //open DB connection
        if (s == null) {
            s = new Session(_habitat_url, 80);
            db = s.getDatabase(_habitat_db);// + "/_design/payload_telemetry/_update/add_listener");
        } else if (db == null)
            db = s.getDatabase(_habitat_db);

        View v = new View("payload_telemetry/payload_time");

        long starttime;
        if (timestampStart > 0)
            starttime = timestampStart;
        else
            starttime = (System.currentTimeMillis() / 1000L) - _prev_query_time;

        v.setStartKey("[%22" + payloadID + "%22," + Long.toString(starttime) + "]");
        v.setEndKey("[%22" + payloadID + "%22," + Long.toString(timestampStop) + "]");

        v.setWithDocs(true);
        v.setLimit(limit);

        System.out.println("DEBUG: DATABASE GOT QUERY");

        TreeMap<Long, Telemetry_string> out = new TreeMap<Long, Telemetry_string>();

        JsonFactory fac = new JsonFactory();
        InputStream is = db.view_dont_parse(v);
        long lasttime = 0;

        if (is != null) {

            JsonParser jp = fac.createJsonParser(is);

            String str, str1;
            boolean gotkey = false;
            boolean keypt1 = false;

            TelemetryConfig tc = null;
            if (telem_configs.containsKey(callsign)) {
                tc = telem_configs.get(callsign);
            }

            while (jp.nextToken() != null)// || (jp.getCurrentLocation().getCharOffset() < body.length()-50)) && nullcount < 20) //100000 > out.size())
            {
                //jp.nextToken();

                str = jp.getCurrentName();
                str1 = jp.getText();
                if (str == "key" && str1 == "[")
                    gotkey = true;
                else if (gotkey) {
                    keypt1 = true;
                    gotkey = false;
                } else if (keypt1) {
                    keypt1 = false;
                    try {
                        lasttime = Long.parseLong(str1);
                    } catch (NumberFormatException e) {
                        System.out.println("ERROR PARSING - NUMBER FORMAT EXCEPTION!!!");
                    }

                }
                if (str != null && str1 != null) {
                    if (str.equals("_sentence") && !str1.equals("_sentence")) {
                        Telemetry_string ts = new Telemetry_string(str1, lasttime, tc);
                        if (!ts.isZeroGPS() && ts.time != null) {
                            if (out.size() > 0) {
                                if (out.lastEntry().getValue().coords.alt_valid) {
                                    prevAltitude = out.lastEntry().getValue().coords.altitude;
                                    prevtime = out.lastEntry().getValue().time.getTime();
                                }
                            }
                            out.put(new Long(ts.time.getTime()), ts);
                            if (ts.coords.alt_valid)
                                maxAltitude = Math.max(ts.coords.altitude, maxAltitude);
                        }
                    }

                    //nullcount = 0;
                }
                //else
                //   nullcount++;
            }
            jp.close();
            is.close();

        }
        s.clearCouchResponse();

        System.out.println("DEBUG: DATABASE PROCESSING DONE");

        AscentRate as = new AscentRate();

        if (out.size() >= 2 && prevAltitude > -9999) {
            as = new AscentRate();
            as.addData(prevtime, prevAltitude);
            if (out.lastEntry().getValue().coords.alt_valid) {
                as.addData(out.lastEntry().getValue().time.getTime(),
                        out.lastEntry().getValue().coords.altitude);

            } else
                as = new AscentRate();
        }
        lasttime += 1000;
        if (lasttime >= timestampStart && lasttime <= timestampStop)
            fireDataReceived(out, true, callsign, timestampStart, lasttime, as, maxAltitude);
        else
            fireDataReceived(out, true, callsign, timestampStart, timestampStop, as, maxAltitude);

        return true;
    }

    catch (Exception e) {
        fireDataReceived(null, false, e.toString(), timestampStart, timestampStop, null, -99999999);
        return false;
    }
}

From source file:org.xwiki.contrib.mailarchive.timeline.internal.TimeLineGenerator.java

/**
 * {@inheritDoc}//from   w  ww .ja va2 s  .com
 * 
 * @see org.xwiki.contrib.mailarchive.timeline.ITimeLineGenerator#compute()
 */
@Override
public String compute(int maxItems) {
    try {
        config.reloadConfiguration();
    } catch (MailArchiveException e) {
        logger.error("Could not load mail archive configuration", e);
        return null;
    }
    Map<String, IMailingList> mailingLists = config.getMailingLists();
    Map<String, IType> types = config.getMailTypes();

    try {
        this.userStatsUrl = xwiki.getDocument(docResolver.resolve("MailArchive.ViewUserMessages"), context)
                .getURL("view", context);
    } catch (XWikiException e1) {
        logger.warn("Could not retrieve user stats url {}", ExceptionUtils.getRootCauseMessage(e1));
    }

    TreeMap<Long, TimeLineEvent> sortedEvents = new TreeMap<Long, TimeLineEvent>();

    // Set loading user in context (for rights)
    String loadingUser = config.getLoadingUser();
    context.setUserReference(docResolver.resolve(loadingUser));

    try {
        // Search topics
        String xwql = "select doc.fullName, topic.author, topic.subject, topic.topicid, topic.startdate, topic.lastupdatedate from Document doc, doc.object("
                + XWikiPersistence.CLASS_TOPICS + ") as topic order by topic.lastupdatedate desc";
        List<Object[]> result = queryManager.createQuery(xwql, Query.XWQL).setLimit(maxItems).execute();

        for (Object[] item : result) {
            XWikiDocument doc = null;
            try {
                String docurl = (String) item[0];
                String author = (String) item[1];
                String subject = (String) item[2];
                String topicId = (String) item[3];
                Date date = (Date) item[4];
                Date end = (Date) item[5];

                String action = "";

                // Retrieve associated emails
                TreeMap<Long, TopicEventBubble> emails = getTopicMails(topicId, subject);

                if (emails == null || emails.isEmpty()) {
                    // Invalid topic, not emails attached, do not show it
                    logger.warn("Invalid topic, no emails attached " + doc);
                } else {
                    if (date != null && end != null && date.equals(end)) {
                        // Add 10 min just to see the tape
                        end.setTime(end.getTime() + 600000);
                    }

                    doc = xwiki.getDocument(docResolver.resolve(docurl), context);
                    final List<String> tagsList = doc.getTagsList(context);
                    List<String> topicTypes = doc.getListValue(XWikiPersistence.CLASS_TOPICS, "type");

                    // Email type icon
                    List<String> icons = new ArrayList<String>();
                    for (String topicType : topicTypes) {
                        IType type = types.get(topicType);
                        if (type != null && !StringUtils.isEmpty(type.getIcon())) {
                            icons.add(xwiki.getSkinFile("icons/silk/" + type.getIcon() + ".png", context));
                            // http://localhost:8080/xwiki/skins/colibri/icons/silk/bell
                            // http://localhost:8080/xwiki/resources/icons/silk/bell.png

                        }
                    }

                    // Author and avatar
                    final IMAUser wikiUser = mailUtils.parseUser(author, config.isMatchLdap());
                    final String authorAvatar = getAuthorAvatar(wikiUser.getWikiProfile());

                    final TimeLineEvent timelineEvent = new TimeLineEvent();
                    TimeLineEvent additionalEvent = null;
                    timelineEvent.beginDate = date;
                    timelineEvent.title = subject;
                    timelineEvent.icons = icons;
                    timelineEvent.lists = doc.getListValue(XWikiPersistence.CLASS_TOPICS, "list");
                    timelineEvent.author = wikiUser.getDisplayName();
                    timelineEvent.authorAvatar = authorAvatar;
                    timelineEvent.extract = getExtract(topicId);

                    if (emails.size() == 1) {
                        logger.debug("Adding instant event for email '" + subject + "'");
                        // Unique email, we show a punctual email event
                        timelineEvent.url = emails.firstEntry().getValue().link;
                        timelineEvent.action = "New Email ";

                    } else {
                        // For email with specific type icon, and a duration, both a band and a point should be added (so 2 events)
                        // because no icon is displayed for duration events.
                        if (CollectionUtils.isNotEmpty(icons)) {
                            logger.debug(
                                    "Adding additional instant event to display type icon for first email in topic");
                            additionalEvent = new TimeLineEvent(timelineEvent);
                            additionalEvent.url = emails.firstEntry().getValue().link;
                            additionalEvent.action = "New Email ";
                        }

                        // Email thread, we show a topic event (a range)
                        logger.debug("Adding duration event for topic '" + subject + "'");
                        timelineEvent.endDate = end;
                        timelineEvent.url = doc.getURL("view", context);
                        timelineEvent.action = "New Topic ";
                        timelineEvent.messages = emails;
                    }

                    // Add the generated Event to the list
                    if (sortedEvents.containsKey(date.getTime())) {
                        // Avoid having more than 1 event at exactly the same time, because some timeline don't like it
                        date.setTime(date.getTime() + 1);
                    }
                    sortedEvents.put(date.getTime(), timelineEvent);
                    if (additionalEvent != null) {
                        sortedEvents.put(date.getTime() + 1, additionalEvent);
                    }
                }

            } catch (Throwable t) {
                logger.warn("Exception for " + doc, t);
            }

        }

    } catch (Throwable e) {
        logger.warn("could not compute timeline data", e);
    }

    return printEvents(sortedEvents);

}

From source file:org.esa.nest.gpf.SliceAssemblyOp.java

private Product[] determineSliceProducts() throws Exception {
    if (sourceProducts.length < 2) {
        throw new Exception("Slice assembly requires at least two consecutive slice products");
    }//  w  ww  .  j  av  a 2 s. c  om

    final TreeMap<Integer, Product> productSet = new TreeMap<>();
    for (Product srcProduct : sourceProducts) {
        final MetadataElement origMetaRoot = AbstractMetadata.getOriginalProductMetadata(srcProduct);
        final MetadataElement generalProductInformation = getGeneralProductInformation(origMetaRoot);
        if (!isSliceProduct(generalProductInformation)) {
            throw new Exception(srcProduct.getName() + " is not a slice product");
        }

        final int totalSlices = generalProductInformation.getAttributeInt("totalSlices");
        final int sliceNumber = generalProductInformation.getAttributeInt("sliceNumber");
        //System.out.println("SliceAssemblyOp.determineSliceProducts: totalSlices = " + totalSlices + "; slice product name = " + srcProduct.getName() + "; prod type = " + srcProduct.getProductType() + "; sliceNumber = " + sliceNumber);

        productSet.put(sliceNumber, srcProduct);
    }

    //check if consecutive
    Integer prev = productSet.firstKey();
    // Note that "The set's iterator returns the keys in ascending order".
    for (Integer i : productSet.keySet()) {
        if (!i.equals(prev)) {
            if (!prev.equals(i - 1)) {
                throw new Exception("Products are not consecutive slices");
            }
            prev = i;
        }
    }

    // Note that "If productSet makes any guarantees as to what order its elements
    // are returned by its iterator, toArray() must return the elements in
    // the same order".
    return productSet.values().toArray(new Product[productSet.size()]);
}

From source file:com.evolveum.midpoint.provisioning.impl.ResourceObjectConverter.java

private List<Collection<Operation>> sortOperationsIntoWaves(Collection<Operation> operations,
        RefinedObjectClassDefinition objectClassDefinition) {
    TreeMap<Integer, Collection<Operation>> waves = new TreeMap<>(); // operations indexed by priority
    List<Operation> others = new ArrayList<>(); // operations executed at the end (either non-priority ones or non-attribute modifications)
    for (Operation operation : operations) {
        RefinedAttributeDefinition rad = getRefinedAttributeDefinitionIfApplicable(operation,
                objectClassDefinition);//  w ww  .j av  a  2 s  .  c  om
        if (rad != null && rad.getModificationPriority() != null) {
            putIntoWaves(waves, rad.getModificationPriority(), operation);
            continue;
        }
        others.add(operation);
    }
    // computing the return value
    List<Collection<Operation>> retval = new ArrayList<>(waves.size() + 1);
    Map.Entry<Integer, Collection<Operation>> entry = waves.firstEntry();
    while (entry != null) {
        retval.add(entry.getValue());
        entry = waves.higherEntry(entry.getKey());
    }
    retval.add(others);
    return retval;
}

From source file:org.mule.devkit.doclet.ClassInfo.java

public MethodInfo[] methods() {
    if (mMethods == null) {
        TreeMap<String, MethodInfo> all = new TreeMap<String, MethodInfo>();

        ClassInfo[] ifaces = getInterfaces();
        for (ClassInfo iface : ifaces) {
            if (iface != null) {
                MethodInfo[] inhereted = iface.methods();
                for (MethodInfo method : inhereted) {
                    String key = method.getHashableName();
                    all.put(key, method);
                }/*w w  w  . java2 s  .com*/
            }
        }

        ClassInfo superclass = superclass();
        if (superclass != null) {
            MethodInfo[] inhereted = superclass.methods();
            for (MethodInfo method : inhereted) {
                String key = method.getHashableName();
                all.put(key, method);
            }
        }

        MethodInfo[] methods = selfMethods();
        for (MethodInfo method : methods) {
            String key = method.getHashableName();
            all.put(key, method);
        }

        mMethods = all.values().toArray(new MethodInfo[all.size()]);
        Arrays.sort(mMethods, MethodInfo.comparator);
    }
    return mMethods;
}

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

/**
 * Ctor.// ww w.  j a v a  2  s .  com
 * @param compositeEventType final event type
 * @param rowEventType event type for input rows
 * @param matchRecognizeSpec specification
 * @param variableStreams variables and their assigned stream number
 * @param streamsVariables stream number and the assigned variable
 * @param variablesSingle single variables
 * @param callbacksPerIndex  for handling the 'prev' function
 * @param aggregationService handles aggregations
 * @param isUnbound true if unbound stream
 * @param isIterateOnly true for iterate-only
 * @param isSelectAsksMultimatches if asking for multimatches
 */
public EventRowRegexNFAView(EventType compositeEventType, EventType rowEventType,
        MatchRecognizeSpec matchRecognizeSpec, LinkedHashMap<String, Pair<Integer, Boolean>> variableStreams,
        Map<Integer, String> streamsVariables, Set<String> variablesSingle,
        AgentInstanceContext agentInstanceContext,
        TreeMap<Integer, List<ExprPreviousMatchRecognizeNode>> callbacksPerIndex,
        AggregationServiceMatchRecognize aggregationService, boolean isUnbound, boolean isIterateOnly,
        boolean isSelectAsksMultimatches) {
    this.matchRecognizeSpec = matchRecognizeSpec;
    this.compositeEventType = compositeEventType;
    this.rowEventType = rowEventType;
    this.variableStreams = variableStreams;
    this.variablesArray = variableStreams.keySet().toArray(new String[variableStreams.keySet().size()]);
    this.streamsVariables = streamsVariables;
    this.variablesSingle = variablesSingle;
    this.aggregationService = aggregationService;
    this.isUnbound = isUnbound;
    this.isIterateOnly = isIterateOnly;
    this.agentInstanceContext = agentInstanceContext;
    this.isSelectAsksMultimatches = isSelectAsksMultimatches;

    if (matchRecognizeSpec.getInterval() != null) {
        scheduleSlot = agentInstanceContext.getStatementContext().getScheduleBucket().allocateSlot();
        ScheduleHandleCallback callback = new ScheduleHandleCallback() {
            public void scheduledTrigger(ExtensionServicesContext extensionServicesContext) {
                EventRowRegexNFAView.this.triggered();
            }
        };
        handle = new EPStatementHandleCallback(agentInstanceContext.getEpStatementAgentInstanceHandle(),
                callback);
        schedule = new TreeMap<Long, Object>();

        agentInstanceContext.addTerminationCallback(this);
    } else {
        scheduleSlot = null;
        handle = null;
        schedule = null;
    }

    this.windowMatchedEventset = new LinkedHashSet<EventBean>();

    // handle "previous" function nodes (performance-optimized for direct index access)
    RegexPartitionStateRandomAccessGetter randomAccessByIndexGetter;
    if (!callbacksPerIndex.isEmpty()) {
        // Build an array of indexes
        int[] randomAccessIndexesRequested = new int[callbacksPerIndex.size()];
        int count = 0;
        for (Map.Entry<Integer, List<ExprPreviousMatchRecognizeNode>> entry : callbacksPerIndex.entrySet()) {
            randomAccessIndexesRequested[count] = entry.getKey();
            count++;
        }
        randomAccessByIndexGetter = new RegexPartitionStateRandomAccessGetter(randomAccessIndexesRequested,
                isUnbound);

        // Since an expression such as "prior(2, price), prior(8, price)" translates into {2, 8} the relative index is {0, 1}.
        // Map the expression-supplied index to a relative index
        count = 0;
        for (Map.Entry<Integer, List<ExprPreviousMatchRecognizeNode>> entry : callbacksPerIndex.entrySet()) {
            for (ExprPreviousMatchRecognizeNode callback : entry.getValue()) {
                callback.setGetter(randomAccessByIndexGetter);
                callback.setAssignedIndex(count);
            }
            count++;
        }
    } else {
        randomAccessByIndexGetter = null;
    }

    Map<String, ExprNode> variableDefinitions = new LinkedHashMap<String, ExprNode>();
    for (MatchRecognizeDefineItem defineItem : matchRecognizeSpec.getDefines()) {
        variableDefinitions.put(defineItem.getIdentifier(), defineItem.getExpression());
    }

    // build states
    RegexNFAStrandResult strand = EventRowRegexHelper.recursiveBuildStartStates(matchRecognizeSpec.getPattern(),
            variableDefinitions, variableStreams);
    startStates = strand.getStartStates().toArray(new RegexNFAState[strand.getStartStates().size()]);
    allStates = strand.getAllStates().toArray(new RegexNFAState[strand.getAllStates().size()]);

    if (log.isDebugEnabled() || IS_DEBUG) {
        log.info("NFA tree:\n" + print(startStates));
    }

    // create evaluators
    columnNames = new String[matchRecognizeSpec.getMeasures().size()];
    columnEvaluators = new ExprEvaluator[matchRecognizeSpec.getMeasures().size()];
    int count = 0;
    for (MatchRecognizeMeasureItem measureItem : matchRecognizeSpec.getMeasures()) {
        columnNames[count] = measureItem.getName();
        columnEvaluators[count] = measureItem.getExpr().getExprEvaluator();
        count++;
    }

    // create state repository
    if (this.matchRecognizeSpec.getPartitionByExpressions().isEmpty()) {
        regexPartitionStateRepo = new RegexPartitionStateRepoNoGroup(randomAccessByIndexGetter,
                matchRecognizeSpec.getInterval() != null);
    } else {
        regexPartitionStateRepo = new RegexPartitionStateRepoGroup(randomAccessByIndexGetter,
                ExprNodeUtility.getEvaluators(matchRecognizeSpec.getPartitionByExpressions()),
                matchRecognizeSpec.getInterval() != null, agentInstanceContext);
    }
}

From source file:org.sakaiproject.tool.assessment.ui.bean.author.AssessmentSettingsBean.java

/**
 * Popluate the select item list of extended time targets
 * //  ww w .  j  ava 2s .c o m
 * @return
 */
public SelectItem[] initExtendedTimeTargets() {
    SelectItem[] extTimeSelectItems = null;
    Site site = null;

    try {
        site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
        Collection groups = site.getGroups();
        SectionAwareness sectionAwareness = PersistenceService.getInstance().getSectionAwareness();
        // List sections = sectionAwareness.getSections(site.getId());
        List enrollments = sectionAwareness.getSiteMembersInRole(site.getId(), Role.STUDENT);

        // Treemaps are used here because they auto-sort
        TreeMap SectionTargets = new TreeMap<String, String>();
        TreeMap groupTargets = new TreeMap<String, String>();
        TreeMap studentTargets = new TreeMap<String, String>();

        // Add groups to target set
        if (groups != null && groups.size() > 0) {
            Iterator groupIter = groups.iterator();
            while (groupIter.hasNext()) {
                Group group = (Group) groupIter.next();
                if (!group.getTitle().startsWith("Access: ")) // do not
                    // include
                    // Lessons
                    // groups
                    groupTargets.put("Group: " + group.getTitle(), group.getId());
            }
        }

        // Add students to target set
        if (enrollments != null && enrollments.size() > 0) {
            for (Iterator iter = enrollments.iterator(); iter.hasNext();) {
                EnrollmentRecord enrollmentRecord = (EnrollmentRecord) iter.next();
                String userId = enrollmentRecord.getUser().getUserUid();
                String userDisplayName = enrollmentRecord.getUser().getSortName();
                studentTargets.put(userDisplayName, userId);
            }
        }

        // Add targets to selectItem array. We put the alpha name in as the
        // key so it would
        // be alphabetized. Now we pull it out and build the select item
        // list.
        int listSize = 1 + groupTargets.size() + studentTargets.size();
        extTimeSelectItems = new SelectItem[listSize];
        extTimeSelectItems[0] = new SelectItem("1", "Select User/Group");
        int selectCount = 1;

        // Add in groups to select item list
        Set keySet = groupTargets.keySet();
        Iterator iter = keySet.iterator();
        while (iter.hasNext()) {
            String alphaName = (String) iter.next();
            String sakaiId = (String) groupTargets.get(alphaName);
            extTimeSelectItems[selectCount++] = new SelectItem(sakaiId, alphaName);
        }

        // Add in students to select item list
        keySet = studentTargets.keySet();
        iter = keySet.iterator();
        while (iter.hasNext()) {
            String alphaName = (String) iter.next();
            String sakaiId = (String) studentTargets.get(alphaName);
            extTimeSelectItems[selectCount++] = new SelectItem(sakaiId, alphaName);
        }

    } catch (IdUnusedException ex) {
        // No site available
    }
    return extTimeSelectItems;
}

From source file:com.irccloud.android.fragment.MessageViewFragment.java

private synchronized void refresh(MessageAdapter adapter, TreeMap<Long, EventsDataSource.Event> events) {
    synchronized (adapterLock) {
        hiddenMap = null;/* w ww .  ja  va  2  s .com*/
        expandMap = null;

        if (getActivity() != null)
            textSize = PreferenceManager.getDefaultSharedPreferences(getActivity()).getInt("textSize",
                    getActivity().getResources().getInteger(R.integer.default_text_size));
        timestamp_width = -1;
        if (conn.getReconnectTimestamp() == 0)
            conn.cancel_idle_timer(); //This may take a while...
        collapsedEvents.clear();
        currentCollapsedEid = -1;
        lastCollapsedDay = -1;

        if (events == null || (events.size() == 0 && buffer.min_eid > 0)) {
            if (buffer != null && conn != null && conn.getState() == NetworkConnection.STATE_CONNECTED) {
                requestingBacklog = true;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        conn.request_backlog(buffer.cid, buffer.bid, 0);
                    }
                });
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        headerView.setVisibility(View.GONE);
                        backlogFailed.setVisibility(View.GONE);
                        loadBacklogButton.setVisibility(View.GONE);
                    }
                });
            }
        } else if (events.size() > 0) {
            if (server != null) {
                ignore.setIgnores(server.ignores);
            } else {
                ignore.setIgnores(null);
            }
            collapsedEvents.setServer(server);
            earliest_eid = events.firstKey();
            if (events.firstKey() > buffer.min_eid && buffer.min_eid > 0 && conn != null
                    && conn.getState() == NetworkConnection.STATE_CONNECTED) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        headerView.setVisibility(View.VISIBLE);
                        backlogFailed.setVisibility(View.GONE);
                        loadBacklogButton.setVisibility(View.GONE);
                    }
                });
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        headerView.setVisibility(View.GONE);
                        backlogFailed.setVisibility(View.GONE);
                        loadBacklogButton.setVisibility(View.GONE);
                    }
                });
            }
            if (events.size() > 0) {
                avgInsertTime = 0;
                //Debug.startMethodTracing("refresh");
                long start = System.currentTimeMillis();
                Iterator<EventsDataSource.Event> i = events.values().iterator();
                EventsDataSource.Event next = i.next();
                Calendar calendar = Calendar.getInstance();
                while (next != null) {
                    EventsDataSource.Event e = next;
                    next = i.hasNext() ? i.next() : null;
                    String type = (next == null) ? "" : next.type;

                    if (next != null && currentCollapsedEid != -1
                            && !expandedSectionEids.contains(currentCollapsedEid)
                            && (type.equalsIgnoreCase("joined_channel")
                                    || type.equalsIgnoreCase("parted_channel")
                                    || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit")
                                    || type.equalsIgnoreCase("user_channel_mode"))) {
                        calendar.setTimeInMillis(next.eid / 1000);
                        insertEvent(adapter, e, true, calendar.get(Calendar.DAY_OF_YEAR) == lastCollapsedDay);
                    } else {
                        insertEvent(adapter, e, true, false);
                    }
                }
                adapter.insertLastSeenEIDMarker();
                Log.i("IRCCloud", "Backlog rendering took: " + (System.currentTimeMillis() - start) + "ms");
                //Debug.stopMethodTracing();
                avgInsertTime = 0;
                //adapter.notifyDataSetChanged();
            }
        }
        if (conn.getReconnectTimestamp() == 0 && conn.getState() == NetworkConnection.STATE_CONNECTED)
            conn.schedule_idle_timer();
    }
}