Java Code Examples for java.util.TreeSet#isEmpty()

The following examples show how to use java.util.TreeSet#isEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Schedule.java    From fosstrak-epcis with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Sets the specified field of the given callendar to the next scheduled
 * value. Returns whether the new value has been set and is valid.
 * 
 * @param cal
 *            Calendar to adjust.
 * @param field
 *            Field to adjust.
 * @return Returns whether the new value has been set and is valid.
 * @throws ImplementationException
 *             Almost any error.
 */
private boolean setToNextScheduledValue(final GregorianCalendar cal, final int field)
        throws ImplementationExceptionResponse {
    int next;
    TreeSet<Integer> vals = getValues(field);
    if (vals.isEmpty()) {
        next = cal.get(field) + 1;
    } else {
        try {
            // get next scheduled value which is bigger than current
            int incrValue = cal.get(field) + 1;
            next = vals.tailSet(new Integer(incrValue)).first().intValue();
        } catch (NoSuchElementException nse) {
            // there is no bigger scheduled value
            return false;
        }
    }
    if (next > cal.getActualMaximum(field) || next < cal.getActualMinimum(field)) {
        return false;
    }
    // all is well, set it to next
    cal.set(field, next);
    return true;
}
 
Example 2
Source File: GatewaySenderAdvisor.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Find out if this sender is the eldest in the DS. Returns true if: 1. No
 * other sender is running 2. At least one sender is running in the system
 * apart from this sender AND this sender's start time is lesser of all (i.e.
 * this sender is oldest)
 * 
 * @return boolean true if this eldest sender; false otherwise
 */
private boolean adviseEldestGatewaySender() {
  Profile[] snapshot = this.profiles;

  // sender with minimum startTime is eldest. Find out the minimum start time
  // of remote senders.
  TreeSet<Long> senderStartTimes = new TreeSet<Long>();
  for (Profile profile : snapshot) {
    GatewaySenderProfile sp = (GatewaySenderProfile)profile;
    if (!sp.isParallel && sp.isRunning) {
      senderStartTimes.add(sp.startTime);
    }
  }

  // if none of the remote senders is running, then this sender should
  // volunteer for primary
  // if there are remote senders running and this sender is not running then
  // it should give up
  // and allow existing running senders to volunteer
  return (senderStartTimes.isEmpty())
      || (this.sender.isRunning() && (this.sender.startTime <= senderStartTimes
          .first()));
}
 
Example 3
Source File: MultipleCourseEnrollmentsAuditReport.java    From unitime with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected List getAuditResults(TreeSet<SubjectArea> subjectAreas){
	TreeSet<SubjectArea> subjects = new TreeSet<SubjectArea>();
	if (subjectAreas != null && !subjectAreas.isEmpty()){
		subjects.addAll(subjectAreas);
	} else {
		subjects.addAll(SubjectArea.getSubjectAreaList(getSession().getUniqueId()));
	}

	String query = createQueryString(subjects);
	Vector results = new Vector();
	for (SubjectArea sa : subjects){
		Debug.info(getTitle() + " - Checking Subject Area:  " + sa.getSubjectAreaAbbreviation());
		results.addAll(StudentClassEnrollmentDAO.getInstance()
			 .getQuery(query)
			 .setLong("sessId", getSession().getUniqueId().longValue())
			 .setLong("subjectId", sa.getUniqueId().longValue())
			 .list());
	}
	return(results);
}
 
Example 4
Source File: ExamSolver.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public ExamSuggestionsInfo getSuggestions(long examId, ExamProposedChange change, String filter, int depth, int limit, long timeOut) {
	Lock lock = currentSolution().getLock().writeLock();
	lock.lock();
    try {
        Exam exam = getExam(examId);
        if (exam==null) return null;
        ExamSuggestions s = new ExamSuggestions(this);
        s.setDepth(depth);
        s.setFilter(filter);
        s.setLimit(limit);
        s.setTimeOut(timeOut);
        TreeSet<ExamProposedChange> suggestions = s.computeSuggestions(exam, (change==null?null:change.getAssignments()));
        String message = null;
        if (s.wasTimeoutReached()) {
            message = "("+(timeOut/1000l)+"s timeout reached, "+s.getNrCombinationsConsidered()+" possibilities up to "+depth+" changes were considered, ";
        } else {
            message = "(all "+s.getNrCombinationsConsidered()+" possibilities up to "+depth+" changes were considered, ";
        }
        if (suggestions.isEmpty()) {
            message += "no suggestion found)";
        } else if (s.getNrSolutions()>suggestions.size()) {
            message += "top "+suggestions.size()+" of "+s.getNrSolutions()+" suggestions displayed)";
        } else {
            message += suggestions.size()+" suggestions displayed)";
        }
        return new ExamSuggestionsInfo(suggestions, message, s.wasTimeoutReached());
    } finally {
    	lock.unlock();
    }
}
 
Example 5
Source File: PersistentOplogSet.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void setFirstChild(TreeSet<Oplog> oplogSet, boolean force) {
  if (parent.isOffline() && !parent.isOfflineCompacting()) return;
  if (!oplogSet.isEmpty()) {
    Oplog first = oplogSet.first();
    DirectoryHolder dh = first.getDirectoryHolder();
    dirCounter = dh.getArrayIndex();
    dirCounter = (++dirCounter) % parent.dirLength;
    // we want the first child to go in the directory after the directory
    // used by the existing oplog with the max id.
    // This fixes bug 41822.
  }
  if (force || maxRecoveredOplogId > 0) {
    setChild(new Oplog(maxRecoveredOplogId + 1, this, getNextDir()));
  }
}
 
Example 6
Source File: PersonalizedExamReportAction.java    From unitime with Apache License 2.0 5 votes vote down vote up
protected long getMeetingComparable(ExamSectionInfo section) {
    if (section.getOwner().getOwnerObject() instanceof Class_) {
        Class_ clazz = (Class_)section.getOwner().getOwnerObject();
        Assignment assignment = clazz.getCommittedAssignment();
        TreeSet meetings = (clazz.getEvent()==null?null:new TreeSet(clazz.getEvent().getMeetings()));
        if (meetings!=null && !meetings.isEmpty()) {
            return ((Meeting)meetings.first()).getMeetingDate().getTime();
        } else if (assignment!=null) {
            return assignment.getTimeLocation().getStartSlot();
        }
    }
    return -1;
}
 
Example 7
Source File: AlertsEngineImpl.java    From hawkular-alerts with Apache License 2.0 5 votes vote down vote up
@Override
public void sendEvents(TreeSet<Event> events) {
    if (events == null) {
        throw new IllegalArgumentException("Events must be not null");
    }
    if (events.isEmpty()) {
        return;
    }

    addEvents(events);

    if (distributed) {
        partitionManager.notifyEvents(new ArrayList<>(events));
    }
}
 
Example 8
Source File: Iadem3.java    From moa with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void createVirtualNodes(IademNumericAttributeObserver numericAttClassObserver,
        boolean onlyMultiwayTest,
        boolean onlyBinaryTest,
        Instance instance) {
    ArrayList<Integer> nominalUsed = nominalAttUsed(instance);
    TreeSet<Integer> sort = new TreeSet<>(nominalUsed);
    for (int i = 0; i < instance.numAttributes(); i++) {
        if (instance.classIndex() != i
                && instance.attribute(i).isNominal()) {
            if ((!sort.isEmpty()) && (i == sort.first())) {
                sort.remove(new Integer(sort.first()));
                virtualChildren.set(i, null);
            } else {
                virtualChildren.set(i, new AdaptiveNominalVirtualNode((Iadem3) tree,
                        this,
                        i,
                        onlyMultiwayTest,
                        onlyBinaryTest));
            }
        } else if (instance.classIndex() != i
                && instance.attribute(i).isNumeric()) {
            virtualChildren.set(i, new AdaptiveNumericVirtualNode((Iadem3) tree,
                    this,
                    i,
                    numericAttClassObserver));
        } else {
            virtualChildren.set(i, null);
        }
    }
}
 
Example 9
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public boolean isPossibleDivide(int[] nums, int k) {
    int len = nums.length;
    if (len % k != 0) {
        return false;
    }

    // TreeSet 不可以
    TreeSet<Integer> treeSet = new TreeSet<>();
    for (int num : nums) {
        treeSet.add(num);
    }

    while (!treeSet.isEmpty()) {
        Integer top = treeSet.first();
        treeSet.remove(top);

        for (int i = 1; i < k; i++) {
            // 从 1 开始,正好需要移除 k - 1 个元素
            // i 正好就是相对于 top 的偏移
            if (!treeSet.remove(top + i)) {
                // 如果移除失败,说明划分不存在,直接返回 false 即可
                return false;
            }
        }
    }
    return true;
}
 
Example 10
Source File: FilterPipeline.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
private Graph<FilterDataEntry> eraseSubTreeData(final Graph<FilterDataEntry> graph, final FilterDataEntry parent) {
	TreeSet<FilterDataEntry> nextSuccs = new TreeSet<>(graph.getSuccessors(parent));

	// Relies on tree structure of the graph
	while (!nextSuccs.isEmpty()) {
		FilterDataEntry succ = nextSuccs.pollFirst();
		if (succ != null && succ.dataset != null) {
			succ.dataset = null;
			nextSuccs.addAll(graph.getSuccessors(succ));
		}
	}
	return graph;
}
 
Example 11
Source File: CFSA2Serializer.java    From morfologik-stemming with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Compute a set of labels to be integrated with the flags field.
 */
private void computeLabelsIndex(final FSA fsa) {
  // Compute labels count.
  final int[] countByValue = new int[256];

  fsa.visitAllStates(new StateVisitor() {
    public boolean accept(int state) {
      for (int arc = fsa.getFirstArc(state); arc != 0; arc = fsa.getNextArc(arc))
        countByValue[fsa.getArcLabel(arc) & 0xff]++;
      return true;
    }
  });

  // Order by descending frequency of counts and increasing label value.
  Comparator<IntIntHolder> comparator = new Comparator<IntIntHolder>() {
    public int compare(IntIntHolder o1, IntIntHolder o2) {
      int countDiff = o2.b - o1.b;
      if (countDiff == 0) {
        countDiff = o1.a - o2.a;
      }
      return countDiff;
    }
  };

  TreeSet<IntIntHolder> labelAndCount = new TreeSet<IntIntHolder>(comparator);
  for (int label = 0; label < countByValue.length; label++) {
    if (countByValue[label] > 0) {
      labelAndCount.add(new IntIntHolder(label, countByValue[label]));
    }
  }

  labelsIndex = new byte[1 + Math.min(labelAndCount.size(), CFSA2.LABEL_INDEX_SIZE)];
  labelsInvIndex = new int[256];
  for (int i = labelsIndex.length - 1; i > 0 && !labelAndCount.isEmpty(); i--) {
    IntIntHolder p = labelAndCount.first();
    labelAndCount.remove(p);
    labelsInvIndex[p.a] = i;
    labelsIndex[i] = (byte) p.a;
  }
}
 
Example 12
Source File: InputOutputManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to find free Output Window tab for the given name.
 *
 * @param name the name of the free tab. Other free tabs are ignored.
 * @return free tab and its current display name or <tt>null</tt>
 */
public static InputOutputData getInputOutput(String name, boolean actions, String optionsPath) {
    InputOutputData result = null;

    TreeSet<InputOutputData> candidates = new TreeSet<InputOutputData>(InputOutputData.DISPLAY_NAME_COMPARATOR);

    synchronized (InputOutputManager.class) {
        for (Iterator<Entry<InputOutput, InputOutputData>> it = AVAILABLE.entrySet().iterator(); it.hasNext();) {
            Entry<InputOutput, InputOutputData> entry = it.next();

            final InputOutput free = entry.getKey();
            final InputOutputData data = entry.getValue();

            if (free.isClosed()) {
                it.remove();
                continue;
            }

            if (isAppropriateName(name, data.displayName)) {
                if ((actions && data.rerunAction != null && data.stopAction != null)
                        || !actions && data.rerunAction == null && data.stopAction == null) {
                    if (optionsPath != null && data.optionsAction != null && data.optionsAction.getOptionsPath().equals(optionsPath)
                            || optionsPath == null && data.optionsAction == null) {
                        // Reuse it.
                        candidates.add(data);
                    }
                } // continue to remove all closed tabs
            }

            LOGGER.log(Level.FINEST, "InputOutputManager pool: {0}", data.getDisplayName());
        }

        if (!candidates.isEmpty()) {
            result = candidates.first();
            AVAILABLE.remove(result.inputOutput);
            ACTIVE_DISPLAY_NAMES.add(result.displayName);
        }
    }
    return result;
}
 
Example 13
Source File: UMLModelDiff.java    From RefactoringMiner with MIT License 4 votes vote down vote up
public void checkForMovedClasses(Map<String, String> renamedFileHints, Set<String> repositoryDirectories, UMLClassMatcher matcher) throws RefactoringMinerTimedOutException {
 for(Iterator<UMLClass> removedClassIterator = removedClasses.iterator(); removedClassIterator.hasNext();) {
  UMLClass removedClass = removedClassIterator.next();
  TreeSet<UMLClassMoveDiff> diffSet = new TreeSet<UMLClassMoveDiff>(new ClassMoveComparator());
  for(Iterator<UMLClass> addedClassIterator = addedClasses.iterator(); addedClassIterator.hasNext();) {
   UMLClass addedClass = addedClassIterator.next();
   String removedClassSourceFile = removedClass.getSourceFile();
   String renamedFile =  renamedFileHints.get(removedClassSourceFile);
   String removedClassSourceFolder = "";
   if(removedClassSourceFile.contains("/")) {
	   removedClassSourceFolder = removedClassSourceFile.substring(0, removedClassSourceFile.lastIndexOf("/"));
   }
   if(!repositoryDirectories.contains(removedClassSourceFolder)) {
	   deletedFolderPaths.add(removedClassSourceFolder);
	   //add deleted sub-directories
	   String subDirectory = new String(removedClassSourceFolder);
	   while(subDirectory.contains("/")) {
		   subDirectory = subDirectory.substring(0, subDirectory.lastIndexOf("/"));
		   if(!repositoryDirectories.contains(subDirectory)) {
			   deletedFolderPaths.add(subDirectory);
		   }
	   }
   }
   if(matcher.match(removedClass, addedClass, renamedFile)) {
	   if(!conflictingMoveOfTopLevelClass(removedClass, addedClass)) {
		   UMLClassMoveDiff classMoveDiff = new UMLClassMoveDiff(removedClass, addedClass, this);
		   diffSet.add(classMoveDiff);
	   }
   }
  }
  if(!diffSet.isEmpty()) {
   UMLClassMoveDiff minClassMoveDiff = diffSet.first();
   minClassMoveDiff.process();
   classMoveDiffList.add(minClassMoveDiff);
   addedClasses.remove(minClassMoveDiff.getMovedClass());
   removedClassIterator.remove();
  }
 }

 List<UMLClassMoveDiff> allClassMoves = new ArrayList<UMLClassMoveDiff>(this.classMoveDiffList);
 Collections.sort(allClassMoves);

 for(int i=0; i<allClassMoves.size(); i++) {
  UMLClassMoveDiff classMoveI = allClassMoves.get(i);
  for(int j=i+1; j<allClassMoves.size(); j++) {
   UMLClassMoveDiff classMoveJ = allClassMoves.get(j);
   if(classMoveI.isInnerClassMove(classMoveJ)) {
	   innerClassMoveDiffList.add(classMoveJ);
   }
  }
 }
 this.classMoveDiffList.removeAll(innerClassMoveDiffList);
}
 
Example 14
Source File: DestructionAwareDestinationPathfinder.java    From megamek with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Uses an A* search to find the "optimal" path to the destination coordinates.
 * Ignores move cost and makes note of hexes that need to be cleared for the path to
 * be viable.
 */
public BulldozerMovePath findPathToCoords(Entity entity, Set<Coords> destinationCoords, boolean jump, BoardClusterTracker clusterTracker) {
    BulldozerMovePath startPath = new BulldozerMovePath(entity.getGame(), entity);
    
    // if we're calculating a jump path and the entity has jump mp and can jump, start off with a jump
    // if we're trying to calc a jump path and the entity does not have jump mp, we're done
    if(jump && (startPath.getCachedEntityState().getJumpMPWithTerrain() > 0) &&
            !entity.isProne() && !entity.isHullDown() && 
            (entity.getGame().getPlanetaryConditions().getWindStrength() != PlanetaryConditions.WI_TORNADO_F4)) {
        startPath.addStep(MoveStepType.START_JUMP);
    // if we specified a jump path, but can't actually jump
    } else if (jump) {
        return null;
    // can't "climb into" anything while jumping
    } else { 
        if(entity.hasETypeFlag(Entity.ETYPE_INFANTRY)) {
            startPath.addStep(MoveStepType.CLIMB_MODE_OFF);
        } else {
            startPath.addStep(MoveStepType.CLIMB_MODE_ON);
        }
    }
    
    // if we're on the ground, let's try to get up first before moving 
    if(entity.isProne() || entity.isHullDown()) {
        startPath.addStep(MoveStepType.GET_UP);
        
        // if we can't even get up, no need to do anything else
        if(!startPath.isMoveLegal()) {
            return null;
        }
    }

    Coords closest = getClosestCoords(destinationCoords, entity);
    // if we can't at all get to the coordinates with this entity, don't bother with the rest 
    if (closest == null) {
        return null;
    }
    
    movePathComparator = new AStarComparator(closest);
    maximumCost = Integer.MAX_VALUE;
    
    TreeSet<BulldozerMovePath> candidates = new TreeSet<>(movePathComparator);
    candidates.add(startPath);

    // a collection of coordinates we've already visited, so we don't loop back.
    Map<Coords, BulldozerMovePath> shortestPathsToCoords = new HashMap<>();
    shortestPathsToCoords.put(startPath.getFinalCoords(), startPath);
    BulldozerMovePath bestPath = null;

    while(!candidates.isEmpty()) {
        BulldozerMovePath currentPath = candidates.pollFirst();
        
        candidates.addAll(generateChildNodes(currentPath, shortestPathsToCoords, clusterTracker, closest));      
        
        if(destinationCoords.contains(currentPath.getFinalCoords()) &&
                ((bestPath == null) || (movePathComparator.compare(bestPath, currentPath) > 0))) {
            bestPath = currentPath;
            maximumCost = bestPath.getMpUsed() + bestPath.getLevelingCost();
        }
    }
  
    return bestPath;
}
 
Example 15
Source File: AutoRebalanceLiveInstanceChangeListener.java    From uReplicator with Apache License 2.0 4 votes vote down vote up
/**
 * Move stuck partitions to other instances.
 *
 * @param instances non-empty set of current instances
 * @return the partitions that have been moved. Null if no movement happens.
 */
private Set<TopicPartition> moveStuckPartitions(Set<InstanceTopicPartitionHolder> instances) {
  if (_maxStuckPartitionMovements <= 0 || _movePartitionAfterStuckMillis <= 0) {
    return null;
  }

  Set<TopicPartition> allStuckPartitions = getStuckTopicPartitions();
  if (allStuckPartitions.isEmpty()) {
    _movePartitionHistoryMap.clear();
    return null;
  }

  // clean up move history if the partition has progress
  Iterator<Entry<TopicPartition, List<Long>>> iter = _movePartitionHistoryMap.entrySet()
      .iterator();
  while (iter.hasNext()) {
    Entry<TopicPartition, List<Long>> entry = iter.next();
    if (!allStuckPartitions.contains(entry.getKey())) {
      iter.remove();
    }
  }

  // find the corresponding stuck instances
  Set<TopicPartition> stuckPartitionsToMove = new HashSet<>();
  TreeSet<InstanceTopicPartitionHolder> nonStuckInstances = new TreeSet<>(
      InstanceTopicPartitionHolder
          .perPartitionWorkloadComparator(_helixMirrorMakerManager.getWorkloadInfoRetriever(),
              null));
  long now = System.currentTimeMillis();
  for (InstanceTopicPartitionHolder itph : instances) {
    boolean isStuckInstance = false;
    for (TopicPartition tp : allStuckPartitions) {
      if (itph.getServingTopicPartitionSet().contains(tp)) {
        isStuckInstance = true;
        List<Long> moveHistory = _movePartitionHistoryMap.get(tp);
        if (moveHistory == null) {
          moveHistory = new ArrayList<>();
          _movePartitionHistoryMap.put(tp, moveHistory);
        } else if (moveHistory.size() >= _maxStuckPartitionMovements) {
          LOGGER.info("moveStuckPartitions: Skip moving stuck partition " + tp + " from "
              + itph.getInstanceName() + " because moving reaches upper bound of "
              + _maxStuckPartitionMovements);
          continue;
        } else if (!moveHistory.isEmpty()
            && moveHistory.get(moveHistory.size() - 1) + _movePartitionAfterStuckMillis > now) {
          LOGGER.info("moveStuckPartitions: Skip moving stuck partition " + tp + " from "
              + itph.getInstanceName() + " because it was moved recently");
          continue;
        }
        LOGGER.info("moveStuckPartitions: Trying to move stuck partition " + tp + " from " + itph
            .getInstanceName());
        moveHistory.add(now);
        itph.removeTopicPartition(tp);
        stuckPartitionsToMove.add(tp);
      }
    }
    if (!isStuckInstance) {
      nonStuckInstances.add(itph);
    }
  }

  if (stuckPartitionsToMove.isEmpty()) {
    LOGGER.info("moveStuckPartitions: No stuck partitions can be moved");
    return null;
  }

  // try to move the partitions to non-stuck instances
  if (nonStuckInstances.isEmpty()) {
    // No non-stuck instance. Shuffle the stuck partitions across all
    // instances but some partitions may still stay at the same instance
    LOGGER.info(
        "moveStuckPartitions: All instances are stuck. Shuffle the stuck partitions instead");
    nonStuckInstances.addAll(instances);
  }
  assignPartitions(nonStuckInstances, new ArrayList<>(stuckPartitionsToMove));

  return stuckPartitionsToMove;
}
 
Example 16
Source File: ExamPeriodEditAction.java    From unitime with Apache License 2.0 4 votes vote down vote up
private void getExamPeriods(HttpServletRequest request) throws Exception {
WebTable.setOrder(sessionContext,"examPeriods.ord",request.getParameter("ord"),1);
// Create web table instance 
      WebTable webTable = new WebTable( 8,
	    null, "examPeriodEdit.do?ord=%%",
	    new String[] {"Type","Date", "Start Time", "End Time", "Length", "Event Start Offset", "Event Stop Offset", "Preference"},
	    new String[] {"left","left", "left", "left", "right", "right", "right", "left"},
	    null );
      
      TreeSet periods = ExamPeriod.findAll(sessionContext.getUser().getCurrentAcademicSessionId(), (Long)null);
if(periods.isEmpty()) {
    webTable.addLine(null, new String[] {"No examination periods defined for this session."}, null, null );			    
}

      Formats.Format<Date> sdf = Formats.getDateFormat(Formats.Pattern.DATE_MEETING);
      Formats.Format<Date> stf = Formats.getDateFormat(Formats.Pattern.TIME_SHORT);

      Set<ExamType> types = null;
      if (!sessionContext.hasPermission(Right.StatusIndependent) && sessionContext.getUser().getCurrentAuthority().hasRight(Right.ExaminationSolver)) {
          types = new HashSet<ExamType>();
          for (ExamType t: ExamType.findAll()) {
          	ExamStatus status = ExamStatus.findStatus(sessionContext.getUser().getCurrentAcademicSessionId(), t.getUniqueId());
          	if (status != null && !status.getManagers().isEmpty()) {
          		for (TimetableManager m: status.getManagers()) {
          			if (sessionContext.getUser().getCurrentAuthority().hasQualifier(m)) {
          				types.add(t);
          				break;
          			}
          		}
          	} else {
          		types.add(t);
          	}
          }
      }
      
      for (Iterator i=periods.iterator();i.hasNext();) {
      	ExamPeriod ep = (ExamPeriod)i.next();
      	if (types != null && !types.contains(ep.getExamType())) continue;
      	String onClick = "onClick=\"document.location='examPeriodEdit.do?op=Edit&id=" + ep.getUniqueId() + "';\"";
      	webTable.addLine(onClick, new String[] {
      			ep.getExamType().getLabel(),
      	        "<a name='"+ep.getUniqueId()+"'>"+sdf.format(ep.getStartDate())+"</a>",
      	        stf.format(ep.getStartTime()),
      	        stf.format(ep.getEndTime()),
      	        String.valueOf(Constants.SLOT_LENGTH_MIN*ep.getLength()),
      	        String.valueOf(Constants.SLOT_LENGTH_MIN*ep.getEventStartOffset()),
      	        String.valueOf(Constants.SLOT_LENGTH_MIN*ep.getEventStopOffset()),
      	        (PreferenceLevel.sNeutral.equals(ep.getPrefLevel().getPrefProlog())?"":
      	        "<font color='"+PreferenceLevel.prolog2color(ep.getPrefLevel().getPrefProlog())+"'>"+ep.getPrefLevel().getPrefName()+"</font>")},
      	        new Comparable[] {
      			ep.getExamType(),ep.getStartDate(), ep.getStartSlot(), ep.getStartSlot()+ep.getLength(), ep.getLength(), ep.getEventStartOffset(), ep.getEventStopOffset(), ep.getPrefLevel().getPrefId()});
      }
      
   request.setAttribute("ExamPeriods.table", webTable.printTable(WebTable.getOrder(sessionContext,"examPeriods.ord")));
  }
 
Example 17
Source File: MappedTreeSet.java    From jaamsim with Apache License 2.0 4 votes vote down vote up
public boolean isEmpty(K key) {
	TreeSet<V> subSet = subsetMap.get(key);
	return subSet == null || subSet.isEmpty();
}
 
Example 18
Source File: ClassInfo.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
private ClassInfo(Class<?> srcClass, boolean ignoreCase) {
  clazz = srcClass;
  this.ignoreCase = ignoreCase;
  Preconditions.checkArgument(
      !ignoreCase || !srcClass.isEnum(), "cannot ignore case on an enum: " + srcClass);
  // name set has a special comparator to keep null first
  TreeSet<String> nameSet =
      new TreeSet<String>(
          new Comparator<String>() {
            public int compare(String s0, String s1) {
              return Objects.equal(s0, s1)
                  ? 0
                  : s0 == null ? -1 : s1 == null ? 1 : s0.compareTo(s1);
            }
          });
  // iterate over declared fields
  for (Field field : srcClass.getDeclaredFields()) {
    FieldInfo fieldInfo = FieldInfo.of(field);
    if (fieldInfo == null) {
      continue;
    }
    String fieldName = fieldInfo.getName();
    if (ignoreCase) {
      fieldName = fieldName.toLowerCase(Locale.US).intern();
    }
    FieldInfo conflictingFieldInfo = nameToFieldInfoMap.get(fieldName);
    Preconditions.checkArgument(
        conflictingFieldInfo == null,
        "two fields have the same %sname <%s>: %s and %s",
        ignoreCase ? "case-insensitive " : "",
        fieldName,
        field,
        conflictingFieldInfo == null ? null : conflictingFieldInfo.getField());
    nameToFieldInfoMap.put(fieldName, fieldInfo);
    nameSet.add(fieldName);
  }
  // inherit from super class and add only fields not already in nameToFieldInfoMap
  Class<?> superClass = srcClass.getSuperclass();
  if (superClass != null) {
    ClassInfo superClassInfo = ClassInfo.of(superClass, ignoreCase);
    nameSet.addAll(superClassInfo.names);
    for (Map.Entry<String, FieldInfo> e : superClassInfo.nameToFieldInfoMap.entrySet()) {
      String name = e.getKey();
      if (!nameToFieldInfoMap.containsKey(name)) {
        nameToFieldInfoMap.put(name, e.getValue());
      }
    }
  }
  names =
      nameSet.isEmpty()
          ? Collections.<String>emptyList()
          : Collections.unmodifiableList(new ArrayList<String>(nameSet));
}
 
Example 19
Source File: Student.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
final public Enrolment getDissertationEnrolment(DegreeCurricularPlan degreeCurricularPlan) {
    TreeSet<Enrolment> enrolments = getDissertationEnrolments(degreeCurricularPlan);
    return enrolments.isEmpty() ? null : enrolments.last();
}
 
Example 20
Source File: GraphBronKerbosch.java    From ReactionDecoder with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 *
 * With pivoting The basic form of the algorithm, described above, is
 * inefficient in the case of graphs with many non-maximal cliques: it makes
 * a recursive call for every clique, maximal or not. To save time and allow
 * the algorithm to backtrack more quickly in branches of the search that
 * contain no maximal cliques, Bron and Kerbosch introduced a variant of the
 * algorithm involving a "pivot vertex" u, chosen from P (or more generally,
 * as later investigators realized,[4] from P ⋃ X). Any maximal clique must
 * include either u or one of its non-neighbors, for otherwise the clique
 * could be augmented by adding u to it. Therefore, only u and its
 * non-neighbors need to be tested as the choices for the vertex v that is
 * added to R in each recursive call to the algorithm. In pseudocode:
 *
 * https://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm#cite_note-1
 *
 * ``` BronKerboschPivoting(R,P,X):
 *
 * ----- if P and X are both empty:
 *
 * ---------- report R as a maximal clique
 *
 * ----- choose a pivot vertex u in P ⋃ X
 *
 * ----- for each vertex v in P \ N(u):
 *
 * ---------- BronKerbosch2(R ⋃ {v}, P ⋂ N(v), X ⋂ N(v))
 *
 * ---------- P := P \ {v}
 *
 * ---------- X := X ⋃ {v}'
 *
 * ```
 *
 * If the pivot is chosen to minimize the number of recursive calls made by
 * the algorithm, the savings in running time compared to the non-pivoting
 * version of the algorithm can be significant.[5]
 *
 *
 * R := is the set of nodes of a maximal clique. <potential clique>
 *
 * P := is the set of possible nodes in a maximal clique. <candidates>
 *
 * X := is the set of nodes that are excluded. <already found>
 *
 * @param R R := is the set of nodes of a maximal clique. (potential clique)
 * @param P P := is the set of possible nodes in a maximal clique
 * (candidates)
 * @param X X := is the set of nodes that are excluded. (already found)
 * @param printDepth
 */
private void BronKerboschWithoutPivot(
        TreeSet<Vertex> R,
        TreeSet<Vertex> P,
        TreeSet<Vertex> X,
        int printDepth) {

    if (DEBUG) {
        System.out.println("BronKerboschWithPivot called: R=" + toText(R, "{", "}")
                + ", P=" + toText(P, "{", "}") + ", X=" + toText(X, "{", "}"));
    }

    if ((P.isEmpty()) && (X.isEmpty())) {
        cliques.add(new HashSet<>(R));
        if (DEBUG) {
            printClique(R);
        }
        return;
    }

    /*
     * Find Pivot 
     */
    Vertex v = null;
    if (!P.isEmpty()) {
        v = P.first();
    }
    while (!P.isEmpty() && v != P.last()) {
        R.add(v);
        //Find neighbours
        List<Vertex> neighbors = new ArrayList<>(findNeighbors(v));
        BronKerboschWithoutPivot(R, new TreeSet<>(intersect(P, neighbors)),
                new TreeSet<>(intersect(X, neighbors)), printDepth + 1);
        P.remove(v);
        X.add(v);
        if (!P.isEmpty()) {
            v = P.first();
        }
    }
}