Example usage for java.util SortedSet add

List of usage examples for java.util SortedSet add

Introduction

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

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (optional operation).

Usage

From source file:net.sourceforge.fenixedu.domain.organizationalStructure.Unit.java

public SortedSet<Unit> getSortedExternalChilds() {
    final SortedSet<Unit> result = new TreeSet<Unit>(Unit.COMPARATOR_BY_NAME_AND_ID);
    for (final Unit unit : getSubUnits()) {
        if (!unit.isInternal()) {
            result.add(unit);
        }//from ww w.j  a  v  a  2 s  .  c o  m
    }
    return result;
}

From source file:com.jjoe64.graphview.series.BarGraphSeries.java

/**
 * draws the bars on the canvas//from  w  w w.java  2 s.co m
 *
 * @param graphView corresponding graphview
 * @param canvas canvas
 * @param isSecondScale whether we are plotting the second scale or not
 */
@Override
public void draw(GraphView graphView, Canvas canvas, boolean isSecondScale) {
    mPaint.setTextAlign(Paint.Align.CENTER);
    if (mValuesOnTopSize == 0) {
        mValuesOnTopSize = graphView.getGridLabelRenderer().getTextSize();
    }
    mPaint.setTextSize(mValuesOnTopSize);

    resetDataPoints();

    // get data
    double maxX = graphView.getViewport().getMaxX(false);
    double minX = graphView.getViewport().getMinX(false);

    double maxY;
    double minY;
    if (isSecondScale) {
        maxY = graphView.getSecondScale().getMaxY(false);
        minY = graphView.getSecondScale().getMinY(false);
    } else {
        maxY = graphView.getViewport().getMaxY(false);
        minY = graphView.getViewport().getMinY(false);
    }

    // Iterate through all bar graph series
    // so we know how wide to make our bar,
    // and in what position to put it in
    int numBarSeries = 0;
    int currentSeriesOrder = 0;
    int numValues = 0;
    boolean isCurrentSeries;
    SortedSet<Double> xVals = new TreeSet<Double>();
    for (Series inspectedSeries : graphView.getSeries()) {
        if (inspectedSeries instanceof BarGraphSeries) {
            isCurrentSeries = (inspectedSeries == this);
            if (isCurrentSeries) {
                currentSeriesOrder = numBarSeries;
            }
            numBarSeries++;

            // calculate the number of slots for bars based on the minimum distance between
            // x coordinates in the series.  This is divided into the range to find
            // the placement and width of bar slots
            // (sections of the x axis for each bar or set of bars)
            // TODO: Move this somewhere more general and cache it, so we don't recalculate it for each series
            Iterator<E> curValues = inspectedSeries.getValues(minX, maxX);
            if (curValues.hasNext()) {
                xVals.add(curValues.next().getX());
                if (isCurrentSeries) {
                    numValues++;
                }
                while (curValues.hasNext()) {
                    xVals.add(curValues.next().getX());
                    if (isCurrentSeries) {
                        numValues++;
                    }
                }
            }
        }
    }
    if (numValues == 0) {
        return;
    }

    double minGap = 0;

    if (mDataWidth > 0.0) {
        minGap = mDataWidth;
    } else {
        Double lastVal = null;

        for (Double curVal : xVals) {
            if (lastVal != null) {
                double curGap = Math.abs(curVal - lastVal);
                if (minGap == 0 || (curGap > 0 && curGap < minGap)) {
                    minGap = curGap;
                }
            }
            lastVal = curVal;
        }
    }

    int numBarSlots = (minGap == 0) ? 1 : (int) Math.round((maxX - minX) / minGap) + 1;

    Iterator<E> values = getValues(minX, maxX);

    // Calculate the overall bar slot width - this includes all bars across
    // all series, and any spacing between sets of bars
    int barSlotWidth = numBarSlots == 1 ? graphView.getGraphContentWidth()
            : graphView.getGraphContentWidth() / (numBarSlots - 1);

    // Total spacing (both sides) between sets of bars
    double spacing = Math.min(barSlotWidth * mSpacing / 100, barSlotWidth * 0.98f);
    // Width of an individual bar
    double barWidth = (barSlotWidth - spacing) / numBarSeries;
    // Offset from the center of a given bar to start drawing
    double offset = barSlotWidth / 2;

    double diffY = maxY - minY;
    double diffX = maxX - minX;
    double contentHeight = graphView.getGraphContentHeight();
    double contentWidth = graphView.getGraphContentWidth();
    double contentLeft = graphView.getGraphContentLeft();
    double contentTop = graphView.getGraphContentTop();

    // draw data
    int i = 0;
    while (values.hasNext()) {
        E value = values.next();

        double valY = value.getY() - minY;
        double ratY = valY / diffY;
        double y = contentHeight * ratY;

        double valY0 = 0 - minY;
        double ratY0 = valY0 / diffY;
        double y0 = contentHeight * ratY0;

        double valueX = value.getX();
        double valX = valueX - minX;
        double ratX = valX / diffX;
        double x = contentWidth * ratX;

        // hook for value dependent color
        if (getValueDependentColor() != null) {
            mPaint.setColor(getValueDependentColor().get(value));
        } else {
            mPaint.setColor(getColor());
        }

        double left = x + contentLeft - offset + spacing / 2 + currentSeriesOrder * barWidth;
        double top = (contentTop - y) + contentHeight;
        double right = left + barWidth;
        double bottom = (contentTop - y0) + contentHeight
                - (graphView.getGridLabelRenderer().isHighlightZeroLines() ? 4 : 1);

        boolean reverse = top > bottom;

        if (mAnimated) {
            if ((Double.isNaN(mLastAnimatedValue) || mLastAnimatedValue < valueX)) {
                long currentTime = System.currentTimeMillis();
                if (mAnimationStart == 0) {
                    // start animation
                    mAnimationStart = currentTime;
                    mAnimationStartFrameNo = 0;
                } else {
                    // anti-lag: wait a few frames
                    if (mAnimationStartFrameNo < 15) {
                        // second time
                        mAnimationStart = currentTime;
                        mAnimationStartFrameNo++;
                    }
                }
                float timeFactor = (float) (currentTime - mAnimationStart) / ANIMATION_DURATION;
                float factor = mAnimationInterpolator.getInterpolation(timeFactor);
                if (timeFactor <= 1.0) {
                    double barHeight = bottom - top;
                    barHeight = barHeight * factor;
                    top = bottom - barHeight;
                    ViewCompat.postInvalidateOnAnimation(graphView);
                } else {
                    // animation finished
                    mLastAnimatedValue = valueX;
                }
            }
        }

        if (reverse) {
            double tmp = top;
            top = bottom + (graphView.getGridLabelRenderer().isHighlightZeroLines() ? 4 : 1);
            bottom = tmp;
        }

        // overdraw
        left = Math.max(left, contentLeft);
        right = Math.min(right, contentLeft + contentWidth);
        bottom = Math.min(bottom, contentTop + contentHeight);
        top = Math.max(top, contentTop);

        mDataPoints.put(new RectD(left, top, right, bottom), value);

        Paint p;
        if (mCustomPaint != null) {
            p = mCustomPaint;
        } else {
            p = mPaint;
        }
        canvas.drawRect((float) left, (float) top, (float) right, (float) bottom, p);

        // set values on top of graph
        if (mDrawValuesOnTop) {
            if (reverse) {
                top = bottom + mValuesOnTopSize + 4;
                if (top > contentTop + contentHeight)
                    top = contentTop + contentHeight;
            } else {
                top -= 4;
                if (top <= contentTop)
                    top += contentTop + 4;
            }

            mPaint.setColor(mValuesOnTopColor);
            canvas.drawText(
                    graphView.getGridLabelRenderer().getLabelFormatter().formatLabel(value.getY(), false),
                    (float) (left + right) / 2, (float) top, mPaint);
        }

        i++;
    }
}

From source file:com.google.gwt.resources.rg.GssResourceGenerator.java

private SortedSet<JClassType> computeOperableTypes(ResourceContext context) {
    TypeOracle typeOracle = context.getGeneratorContext().getTypeOracle();
    JClassType baseInterface = typeOracle.findType(CssResource.class.getCanonicalName());

    SortedSet<JClassType> toReturn = new TreeSet<>(new JClassOrderComparator());

    JClassType[] cssResourceSubtypes = baseInterface.getSubtypes();
    for (JClassType type : cssResourceSubtypes) {
        if (type.isInterface() != null) {
            toReturn.add(type);
        }// www  . j  a v  a2s .  co m
    }

    return toReturn;
}

From source file:com.jd.survey.service.settings.SurveySettingsService.java

@Transactional(readOnly = false)
public QuestionOption questionOption_merge(QuestionOption questionOption) {
    SortedSet<QuestionOption> updatedQuestionOptions = new TreeSet<QuestionOption>();
    Long questionId = questionOption.getQuestion().getId();
    Question question = questionDAO.findById(questionId);
    questionOption.setQuestion(question);
    Short order = question.updateSet(question.getOptions(), questionOption).getOrder();
    for (QuestionOption qo : question.getOptions()) {
        updatedQuestionOptions.add(questionOptionDAO.merge(qo));
    }//from   w w  w.  ja  v  a 2s.  c om
    question.setOptions(updatedQuestionOptions);
    question = questionDAO.merge(question);
    return question.getElement(question.getOptions(), order);
}

From source file:com.migratebird.script.repository.impl.ArchiveScriptLocation.java

protected SortedSet<Script> loadScriptsFromJar(final JarFile jarFile, String subPath) {
    SortedSet<Script> scripts = new TreeSet<Script>();
    for (Enumeration<JarEntry> jarEntries = jarFile.entries(); jarEntries.hasMoreElements();) {
        final JarEntry jarEntry = jarEntries.nextElement();
        String fileName = jarEntry.getName();
        if (LOCATION_PROPERTIES_FILENAME.equals(fileName) || !isScriptFileName(fileName)) {
            continue;
        }//  ww  w.  j a  va 2  s.c om

        String relativeScriptName = jarEntry.getName();
        if (subPath != null) {
            if (!fileName.startsWith(subPath)) {
                continue;
            }
            relativeScriptName = relativeScriptName.substring(subPath.length());
        }
        ScriptContentHandle scriptContentHandle = new ScriptContentHandle(scriptEncoding,
                ignoreCarriageReturnsWhenCalculatingCheckSum) {
            @Override
            protected InputStream getScriptInputStream() {
                try {
                    return jarFile.getInputStream(jarEntry);
                } catch (IOException e) {
                    throw new MigrateBirdException("Error while reading jar entry " + jarEntry, e);
                }
            }
        };
        Long fileLastModifiedAt = jarEntry.getTime();
        Script script = scriptFactory.createScriptWithContent(relativeScriptName, fileLastModifiedAt,
                scriptContentHandle);
        scripts.add(script);
    }
    return scripts;
}

From source file:com.aurel.track.exchange.excel.ExcelImportBL.java

/**
 * Add the error in the map/*from   www.ja va  2  s .  c o m*/
 * 
 * @param errorsMap
 * @param errorType
 * @param rowIndex
 */
private static void addRowError(Map<Integer, SortedSet<Integer>> errorsMap, Integer errorType, int rowIndex) {
    SortedSet<Integer> errorsOfType = errorsMap.get(errorType);
    if (errorsOfType == null) {
        errorsOfType = new TreeSet<Integer>();
        errorsMap.put(errorType, errorsOfType);
    }
    errorsOfType.add(Integer.valueOf(rowIndex + 1));
}

From source file:com.devnexus.ting.core.service.impl.BusinessServiceImpl.java

@Override
public ScheduleItemList getScheduleForEvent(Long eventId) {

    final List<ScheduleItem> scheduleItems = scheduleItemDao.getScheduleForEvent(eventId);

    final ScheduleItemList scheduleItemList = new ScheduleItemList();
    scheduleItemList.setScheduleItems(scheduleItems);

    ScheduleItem currentScheduleItem = null;

    String hourOfDay = null;//from   w  w  w.  j  av a2  s . co  m

    final SortedSet<Date> days = new TreeSet<Date>();

    int numberOfSessions = 0;
    int numberOfKeynoteSessions = 0;
    int numberOfBreakoutSessions = 0;
    int numberOfUnassignedSessions = 0;

    int numberOfBreaks = 0;

    Set<Long> speakerIds = new HashSet<Long>();
    Set<Long> roomIds = new HashSet<Long>();

    for (ScheduleItem scheduleItem : scheduleItems) {

        roomIds.add(scheduleItem.getRoom().getId());

        final Date fromTime = scheduleItem.getFromTime();
        final Date dayOfConference = CalendarUtils.getCalendarWithoutTime(fromTime).getTime();
        days.add(dayOfConference);

        if (ScheduleItemType.KEYNOTE.equals(scheduleItem.getScheduleItemType())
                || ScheduleItemType.SESSION.equals(scheduleItem.getScheduleItemType())) {

            numberOfSessions++;

            if (scheduleItem.getPresentation() != null) {
                for (Speaker speaker : scheduleItem.getPresentation().getSpeakers()) {
                    speakerIds.add(speaker.getId());
                }
            } else {
                numberOfUnassignedSessions++;
            }

            if (ScheduleItemType.KEYNOTE.equals(scheduleItem.getScheduleItemType())) {
                numberOfKeynoteSessions++;

            }

            if (ScheduleItemType.SESSION.equals(scheduleItem.getScheduleItemType())) {
                numberOfBreakoutSessions++;
            }

        }

        if (ScheduleItemType.BREAK.equals(scheduleItem.getScheduleItemType())) {
            numberOfBreaks++;
        }

        Calendar cal = Calendar.getInstance();
        cal.setTime(fromTime);

        String loopHour = cal.get(Calendar.HOUR_OF_DAY) + "_" + cal.get(Calendar.MINUTE);

        if (hourOfDay == null || !hourOfDay.equals(loopHour)) {
            currentScheduleItem = scheduleItem;
            hourOfDay = loopHour;
        } else {
            currentScheduleItem.setRowspan(currentScheduleItem.getRowspan() + 1);
        }

    }

    scheduleItemList.setDays(days);
    scheduleItemList.setNumberOfBreakoutSessions(numberOfBreakoutSessions);
    scheduleItemList.setNumberOfBreaks(numberOfBreaks);
    scheduleItemList.setNumberOfSessions(numberOfSessions);
    scheduleItemList.setNumberOfKeynoteSessions(numberOfKeynoteSessions);
    scheduleItemList.setNumberOfUnassignedSessions(numberOfUnassignedSessions);
    scheduleItemList.setNumberOfSpeakersAssigned(speakerIds.size());
    scheduleItemList.setNumberOfRooms(roomIds.size());
    return scheduleItemList;
}

From source file:com.jd.survey.service.settings.SurveySettingsService.java

@Transactional(readOnly = false)
public Question question_merge(Question question, SortedSet<QuestionOption> options) {
    //Clear data set field for non Dataset questions
    if (!question.getType().getIsDataSet()) {
        question.setDataSetId(null);/*from  ww  w .  j av  a  2 s . c  o m*/
    }
    //Deleting options from question that do not support options
    if (!question.getSuportsOptions()) {
        questionOptionDAO.deleteByQuestionId(question.getId());
    }

    SortedSet<Question> updatedQuestions = new TreeSet<Question>();
    Long pageId = question.getPage().getId();
    SurveyDefinitionPage surveyDefinitionPage = surveyDefinitionPageDAO.findById(pageId);
    question.setPage(surveyDefinitionPage);
    Short order = surveyDefinitionPage.updateSet(surveyDefinitionPage.getQuestions(), question).getOrder();
    for (Question q : surveyDefinitionPage.getQuestions()) {
        updatedQuestions.add(questionDAO.merge(q));
    }
    surveyDefinitionPage.setQuestions(updatedQuestions);
    surveyDefinitionPage = surveyDefinitionPageDAO.merge(surveyDefinitionPage);

    Question q = surveyDefinitionPage.getElement(surveyDefinitionPage.getQuestions(), order);

    for (QuestionOption questionOption : options) {
        questionOption.setQuestion(q);
        questionOption = questionOptionDAO.merge(questionOption);
    }
    q.setOptions(options);
    return q;

}

From source file:net.sourceforge.fenixedu.domain.Lesson.java

public String getOccurrenceWeeksAsString() {
    final SortedSet<Integer> weeks = new TreeSet<Integer>();

    final ExecutionCourse executionCourse = getExecutionCourse();
    final YearMonthDay firstPossibleLessonDay = executionCourse.getMaxLessonsPeriod().getLeft();
    final YearMonthDay lastPossibleLessonDay = executionCourse.getMaxLessonsPeriod().getRight();
    for (final Interval interval : getAllLessonIntervals()) {
        final Integer week = Weeks.weeksBetween(firstPossibleLessonDay, interval.getStart().toLocalDate())
                .getWeeks() + 1;//from   w w w  .j  a  v  a  2  s.  c om
        weeks.add(week);
    }

    final StringBuilder builder = new StringBuilder();
    final Integer[] weeksA = weeks.toArray(new Integer[0]);
    for (int i = 0; i < weeksA.length; i++) {
        if (i == 0) {
            builder.append(weeksA[i]);
        } else if (i == weeksA.length - 1 || (weeksA[i]) + 1 != (weeksA[i + 1])) {
            final String seperator = (weeksA[i - 1]) + 1 == (weeksA[i]) ? " - " : ", ";
            builder.append(seperator);
            builder.append(weeksA[i]);
        } else if ((weeksA[i - 1]) + 1 != weeksA[i]) {
            builder.append(", ");
            builder.append(weeksA[i]);
        }
    }
    return builder.toString();
}

From source file:com.tesora.dve.tools.aitemplatebuilder.AiTemplateBuilder.java

private void identifyCandidateModels(final Collection<TableStats> tables,
        final boolean isRowWidthWeightingEnabled) throws Exception {
    final SortedSet<Long> sortedCardinalities = new TreeSet<Long>();
    final SortedSet<Long> uniqueOperationFrequencies = new TreeSet<Long>();
    for (final TableStats table : tables) {
        sortedCardinalities.add(table.getPredictedFutureSize(isRowWidthWeightingEnabled));
        uniqueOperationFrequencies.add(table.getWriteStatementCount());
    }//from w w w.  j a v  a  2  s. c  o m

    for (final TableStats table : tables) {
        final TemplateModelItem baseModel = findBaseModel(table);
        if (baseModel != null) {
            table.setTableDistributionModel(baseModel);
            table.setDistributionModelFreezed(true);
            logTableDistributionModel(table, MessageSeverity.ALERT);
        } else {
            final double sortsWeight = BooleanUtils.toInteger(this.enableUsingSorts);
            final double writesWeight = BooleanUtils.toInteger(isUsingWrites(table, this.enableUsingWrites));
            final ImmutableMap<FlvName, Double> ruleWeights = ImmutableMap.<FlvName, Double>of(
                    FuzzyTableDistributionModel.Variables.SORTS_FLV_NAME, sortsWeight,
                    FuzzyTableDistributionModel.Variables.WRITES_FLV_NAME, writesWeight);
            final List<FuzzyTableDistributionModel> modelsSortedByScore = FuzzyLinguisticVariable
                    .evaluateDistributionModels(ruleWeights,
                            new Broadcast(table, uniqueOperationFrequencies, sortedCardinalities,
                                    isRowWidthWeightingEnabled),
                            new Range(table, uniqueOperationFrequencies, sortedCardinalities,
                                    isRowWidthWeightingEnabled));

            table.setTableDistributionModel(
                    Collections.max(modelsSortedByScore, FuzzyLinguisticVariable.getScoreComparator()));

            log(table.toString().concat(": ").concat(StringUtils.join(modelsSortedByScore, ", ")));
        }
    }
}