Java Code Examples for java.util.TreeMap#get()

The following examples show how to use java.util.TreeMap#get() . 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: Solution.java    From java-technology-stack with MIT License 6 votes vote down vote up
public List<Integer> topKFrequent(int[] nums, int k) {

        TreeMap<Integer, Integer> map = new TreeMap<>();
        for(int num: nums){
            if(map.containsKey(num))
                map.put(num, map.get(num) + 1);
            else
                map.put(num, 1);
        }

        MaxHeap<Freq> maxHeap = new MaxHeap<>();
        for(int key: map.keySet()){
            if(maxHeap.size() < k)
                maxHeap.add(new Freq(key, map.get(key)));
            else if(map.get(key) > maxHeap.findMax().freq)
                maxHeap.replace(new Freq(key, map.get(key)));
        }

        LinkedList<Integer> res = new LinkedList<>();
        while(!maxHeap.isEmpty())
            res.add(maxHeap.extractMax().e);
        return res;
    }
 
Example 2
Source File: AlarmDAOImpl.java    From monasca-thresh with Apache License 2.0 6 votes vote down vote up
private byte[] calculateDimensionSHA1(final Map<String, String> dimensions) {
  // Calculate dimensions sha1 hash id.
  final StringBuilder dimensionIdStringToHash = new StringBuilder("");
  if (dimensions != null) {
    // Sort the dimensions on name and value.
    TreeMap<String, String> dimensionTreeMap = new TreeMap<>(dimensions);
    for (String dimensionName : dimensionTreeMap.keySet()) {
      if (dimensionName != null && !dimensionName.isEmpty()) {
        String dimensionValue = dimensionTreeMap.get(dimensionName);
        if (dimensionValue != null && !dimensionValue.isEmpty()) {
          dimensionIdStringToHash.append(trunc(dimensionName, MAX_COLUMN_LENGTH));
          dimensionIdStringToHash.append(trunc(dimensionValue, MAX_COLUMN_LENGTH));
        }
      }
    }
  }

  final byte[] dimensionIdSha1Hash = DigestUtils.sha(dimensionIdStringToHash.toString());
  return dimensionIdSha1Hash;
}
 
Example 3
Source File: Solution.java    From java-technology-stack with MIT License 6 votes vote down vote up
public List<Integer> topKFrequent(int[] nums, int k) {

        TreeMap<Integer, Integer> map = new TreeMap<>();
        for(int num: nums){
            if(map.containsKey(num))
                map.put(num, map.get(num) + 1);
            else
                map.put(num, 1);
        }

        PriorityQueue<Freq> pq = new PriorityQueue<>();
        for(int key: map.keySet()){
            if(pq.getSize() < k)
                pq.enqueue(new Freq(key, map.get(key)));
            else if(map.get(key) > pq.getFront().freq){
                pq.dequeue();
                pq.enqueue(new Freq(key, map.get(key)));
            }
        }

        LinkedList<Integer> res = new LinkedList<>();
        while(!pq.isEmpty())
            res.add(pq.dequeue().e);
        return res;
    }
 
Example 4
Source File: LinkDocHandler.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * コンストラクタ.
 * @param srcHandler OEntityDocHandler
 * @param targetSetName ターゲット側のEntitySet名
 * @param targetEntityTypeId ターゲット側のEntityTypeID
 */
public NtoNQueryParameter(
        final EntitySetDocHandler srcHandler,
        final String targetSetName,
        final String targetEntityTypeId) {
    String srcSetName = srcHandler.getType();
    String srcId = srcHandler.getId();

    TreeMap<String, String> tm = new TreeMap<String, String>();
    if (srcSetName.equals(UserDataODataProducer.USER_ODATA_NAMESPACE)) {
        tm.put(srcHandler.getEntityTypeId(), srcId);
        tm.put(targetEntityTypeId, "");
    } else {
        tm.put(srcSetName, srcId);
        tm.put(targetSetName, "");
    }
    this.t1 = tm.firstKey();
    this.t2 = tm.lastKey();
    this.k1 = tm.get(t1);
    this.k2 = tm.get(t2);
}
 
Example 5
Source File: StatsBridgeVirtualSensor.java    From gsn with GNU General Public License v3.0 6 votes vote down vote up
public boolean initialize() {

        TreeMap<String, String> params = getVirtualSensorConfiguration().getMainClassInitialParams();

        String logging_interval_str = params.get(PARAM_LOGGING_INTERVAL);
        if (logging_interval_str != null) {
            logging_timestamps = true;
            try {
                logging_interval = Integer.parseInt(logging_interval_str.trim());
            } catch (NumberFormatException e) {
                logger.warn("Parameter \"" + PARAM_LOGGING_INTERVAL + "\" incorrect in Virtual Sensor file");
                logging_timestamps = false;
            }
        }

        vsname = getVirtualSensorConfiguration().getName();

        return true;
    }
 
Example 6
Source File: HdfsFilePathGenerator.java    From DataLink with Apache License 2.0 6 votes vote down vote up
public FileSplitMode getFileSplitMode(MediaMappingInfo mappingInfo) {
    HdfsMappingParameter hdfsMappingParameter = JSONObject.toJavaObject(mappingInfo.getParameterObj(), HdfsMappingParameter.class);
    if (hdfsMappingParameter != null) {
        List<FileSplitStrategy> fileSplitStrategieList = hdfsMappingParameter.getFileSplitStrategieList();
        if (fileSplitStrategieList != null && fileSplitStrategieList.size() > 0) {
            Date current = new Date();
            TreeMap<Date, FileSplitMode> treeMap = new TreeMap<>();
            for (FileSplitStrategy fileSplitStrategy : fileSplitStrategieList) {
                treeMap.put(fileSplitStrategy.getEffectiveDate(), fileSplitStrategy.getFileSplitMode());
            }
            Date greatest = treeMap.floorKey(current);
            if (greatest != null) {
                return treeMap.get(greatest);
            } else {
                return FileSplitMode.DAY;
            }
        } else {
            return FileSplitMode.DAY;
        }
    } else {
        return FileSplitMode.DAY;// 没有明确配置的话,一天一个文件
    }
}
 
Example 7
Source File: JMXAccessControlList.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public List<String> getRolesForObject(ObjectName objectName, String methodName) {
   TreeMap<String, Access> domainMap = domainAccess.get(objectName.getDomain());
   if (domainMap != null) {
      Hashtable<String, String> keyPropertyList = objectName.getKeyPropertyList();
      for (Map.Entry<String, String> keyEntry : keyPropertyList.entrySet()) {
         String key = normalizeKey(keyEntry.getKey() + "=" + keyEntry.getValue());
         for (Access accessEntry : domainMap.values()) {
            if (accessEntry.getKeyPattern().matcher(key).matches()) {
               return accessEntry.getMatchingRolesForMethod(methodName);
            }
         }
      }

      Access access = domainMap.get("");
      if (access != null) {
         return access.getMatchingRolesForMethod(methodName);
      }
   }

   return defaultAccess.getMatchingRolesForMethod(methodName);
}
 
Example 8
Source File: ModuleDependencies.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void registerModuleInKit(ModuleInfo module, String kit, TreeMap<String, TreeSet<String>> allKits) {
    TreeSet<String> modules = allKits.get(kit);
    if (modules == null) {
        modules = new TreeSet<>();
        allKits.put(kit, modules);
    }
    modules.add(module.getName(false));
}
 
Example 9
Source File: SyncService.java    From btrbck with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Determines the ancestors of the given snapshot which are available on the
 * target
 */
Set<Integer> calculateAncestorNrs(Snapshot snapshot,
        VersionHistory versionHistory,
        TreeSet<Integer> availableCloneSources) {
    Set<Integer> result = new HashSet<>();
    TreeMap<Integer, HistoryNode> nodes = versionHistory.calculateNodes();
    // log.debug("Node Map: " + nodes);
    HistoryNode node = nodes.get(snapshot.nr);

    fillAvailableAncestors(node, result, availableCloneSources);
    return result;
}
 
Example 10
Source File: TreeMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * get(null) of nonempty map throws NPE
 */
public void testGet_NullPointerException() {
    TreeMap c = map5();
    try {
        c.get(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 11
Source File: CSVWrapperTest.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testFieldConverting() throws IOException {
	String fields = "TIMED, air_temp , TIMED , AiR_TeMp2";
	String formats = "Timestamp(d.M.y ) , Numeric , timestamp(k:m) , numeric    ";
	String badFormat = "Timestamp(d.M.y k:m) , numeric , numeric, numeric,numeric,dollluble ";
	String badFormat2 ="Timestamp(d.Mjo0o.y k:m) , numeric, numeric, numeric";
	
	CSVHandler wrapper = new CSVHandler();
	assertEquals(false,wrapper.initialize("test.csv.csv", fields,badFormat,',','\"',0,"NaN,-1234,4321"));
	assertEquals(false,wrapper.initialize("test.csv.csv", fields,badFormat,',','\"',0,"NaN,-1234,4321"));
	assertEquals(false,wrapper.initialize("test.csv.csv", fields,badFormat2,',','\"',0,"NaN,-1234,4321"));
	
	assertEquals(true,wrapper.initialize("test.csv.csv", fields,formats,',','\"',0,"NaN,-1234,4321"));
	
	FileUtils.writeStringToFile(new File(wrapper.getCheckPointFile()),  "","UTF-8");
	String[] formatsParsed = wrapper.getFormats();
	String[] fieldsParsed =  wrapper.getFields();
	assertEquals(true,compare(fieldsParsed, new String[] {"timed","air_temp","timed","air_temp2"}));
	assertEquals(true,compare(formatsParsed, new String[] {"Timestamp(d.M.y )","Numeric","timestamp(k:m)","numeric"}));
	
	TreeMap<String, Serializable> se = wrapper.convertTo(wrapper.getFormats(),wrapper.getFields(),wrapper.getNulls(),new String[] {} , wrapper.getSeparator());
	assertEquals(wrapper.getFields().length-1, se.keySet().size());//timestamp is douplicated.
	assertEquals(null, se.get("timed"));
	se = wrapper.convertTo(wrapper.getFormats(),wrapper.getFields(),wrapper.getNulls(),new String[] {"","","","-1234","4321","NaN"} , wrapper.getSeparator());
	assertEquals(null, se.get("timed"));
	
	se = wrapper.convertTo(wrapper.getFormats(),wrapper.getFields(),wrapper.getNulls(),new String[] {"","","","-1234","4321","NaN"} , wrapper.getSeparator());
	assertEquals(null, se.get("timed"));
	
	se = wrapper.convertTo(wrapper.getFormats(),wrapper.getFields(),wrapper.getNulls(),new String[] {"01.01.2009","1234","","-4321","ignore-me","NaN"} , wrapper.getSeparator());
	long parsedTimestamp = (Long)se.get("timed");
	assertEquals(true,parsedTimestamp>0);
	assertEquals(1234.0, se.get("air_temp"));
	assertEquals(-4321.0, se.get("air_temp2"));
	
	se = wrapper.convertTo(wrapper.getFormats(),wrapper.getFields(),wrapper.getNulls(),new String[] {"01.01.2009","-1234","10:10","-4321","ignore-me","NaN"} , wrapper.getSeparator());
	assertEquals(true,((Long)se.get("timed"))>parsedTimestamp);
	assertNull(se.get("air_temp"));

}
 
Example 12
Source File: UIQueryServiceImpl.java    From lumongo with Apache License 2.0 5 votes vote down vote up
private List<IndexInfo> getIndexInfos() throws Exception {
	GetIndexesResult indexes = lumongoWorkPool.getIndexes();

	List<IndexInfo> indexInfoList = new ArrayList<>();
	for (String indexName : indexes.getIndexNames()) {
		IndexInfo indexInfo = new IndexInfo();
		indexInfo.setName(indexName);
		indexInfo.setSize(20L);
		indexInfo.setTotalDocs((int) lumongoWorkPool.getNumberOfDocs(indexName).getNumberOfDocs());

		TreeMap<String, FieldConfig> fieldConfigMap = lumongoWorkPool.getIndexConfig(new GetIndexConfig(indexName)).getIndexConfig().getFieldConfigMap();
		for (String fieldName : fieldConfigMap.keySet()) {
			indexInfo.getFlList().add(fieldName);
			FieldConfig fieldConfig = fieldConfigMap.get(fieldName);

			for (IndexAs indexAs : fieldConfig.getIndexAsList()) {
				indexInfo.getQfList().add(indexAs.getIndexFieldName());
			}

			for (FacetAs facetAs : fieldConfig.getFacetAsList()) {
				indexInfo.getFacetList().add(facetAs.getFacetName());
			}

		}

		indexInfoList.add(indexInfo);
	}
	return indexInfoList;
}
 
Example 13
Source File: BucketOwnershipAssignment.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public boolean hasBucketResponsibilities(final ClusterNodeAddress leavingAddress) {

      // Iterate storages
      for (final TreeMap<ClusterNodeAddress, BucketOwner> map : bucketOwners) {

         final BucketOwner bucketOwner = map.get(leavingAddress);
         if (bucketOwner.hasBucketResponsibilities()) {

            return true;
         }
      }

      return false;
   }
 
Example 14
Source File: VoipVirtualSensor.java    From gsn with GNU General Public License v3.0 4 votes vote down vote up
public boolean initialize()
{
  VSensorConfig vsensor = getVirtualSensorConfiguration();
  TreeMap<String, String> params = vsensor.getMainClassInitialParams();
  
  ManagerConnectionFactory factory = new ManagerConnectionFactory(params.get("host"), params.get("username"), params.get("password"));
  
  managerConnection = factory.createManagerConnection();
  
  // get the name of the virtual sensor from the vsd
  vs_name = new String(vsensor.getName());
  
  // generate a random extension number between 9000-10000
  Random random = new Random();    
  Integer ext =  (int)((long)(1001 * random.nextDouble()) + 9000);
  vs_ext = ext.toString();
  
  try
  {
    // connect to Asterisk and log in
    managerConnection.login();
    
    connected = true;
    
    // delete previous configuration, e.g. dial plan and config files
    cleanConfig();
    
    // create the text-to-speech ulaw file
    text2speech_low(params.get("message"));
    
    // create the dial plan in the asterisk server
    createDialPlan(vs_name, vs_ext);
    
    // settings for making the actual phone call
    originateAction = new OriginateAction();
    
    phone_no = new String(params.get("number"));
    
    originateAction.setChannel("SIP/" + phone_no + "@" + SIP_TRUNK);
    originateAction.setContext(vs_name);
    originateAction.setExten(vs_ext);
    
    originateAction.setPriority(new Integer(1));
    originateAction.setCallerId("GSN Notification");
    
  } catch (Exception e)
  {
    connected = false;
    logger.error("connection state is " + managerConnection.getState() + "    "+ e);
  }
  
  vs_counter++;
  
  logger.info("Virtual Sensor [" + vs_name + "]" + " added to GSN with extension " + vs_ext +  " running instance @" + vs_counter);
  
  return connected;
}
 
Example 15
Source File: HDBSCAN.java    From clust4j with Apache License 2.0 4 votes vote down vote up
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;
	
	// [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;
}
 
Example 16
Source File: AnomalyDetectorProfileRunner.java    From anomaly-detection with Apache License 2.0 4 votes vote down vote up
/**
 * Precondition:
 * 1. Index are rotated with name pattern ".opendistro-anomaly-results-history-{now/d}-1" and now is using UTC.
 * 2. Latest entry with error is recorded within enabled and disabled time.  Note disabled time can be null.
 *
 * Error is populated if error of the latest anomaly result is not empty.
 *
 * Two optimization to avoid scanning all anomaly result indices to get a detector's most recent error
 *
 * First, when a detector is running, we only need to scan the current index, not all of the rolled over ones
 *  since we are interested in the latest error.
 * Second, when a detector is disabled, we only need to scan the latest anomaly result indices created before the
 *  detector's enable time.
 *
 * @param detectorId detector id
 * @param enabledTimeMillis the time when AD job is enabled in milliseconds
 * @param listener listener to process the returned error or exception
 */
private void profileError(
    String detectorId,
    long enabledTimeMillis,
    Instant disabledTime,
    MultiResponsesDelegateActionListener<DetectorProfile> listener
) {
    String[] latestIndex = null;

    long disabledTimeMillis = 0;
    if (disabledTime != null) {
        disabledTimeMillis = disabledTime.toEpochMilli();
    }
    if (enabledTimeMillis > disabledTimeMillis) {
        // detector is still running
        latestIndex = new String[1];
        latestIndex[0] = AnomalyResult.ANOMALY_RESULT_INDEX;
    } else {
        String[] concreteIndices = indexNameExpressionResolver
            .concreteIndexNames(
                clusterService.state(),
                IndicesOptions.lenientExpandOpen(),
                AnomalyDetectionIndices.ALL_AD_RESULTS_INDEX_PATTERN
            );

        // find the latest from result indices such as .opendistro-anomaly-results-history-2020.04.06-1 and
        // /.opendistro-anomaly-results-history-2020.04.07-000002
        long maxTimestamp = -1;
        TreeMap<Long, List<String>> candidateIndices = new TreeMap<>();
        for (String indexName : concreteIndices) {
            Matcher m = Pattern.compile("\\.opendistro-anomaly-results-history-(\\d{4})\\.(\\d{2})\\.(\\d{2})-\\d+").matcher(indexName);
            if (m.matches()) {
                int year = Integer.parseInt(m.group(1));
                int month = Integer.parseInt(m.group(2));
                int date = Integer.parseInt(m.group(3));
                // month starts with 0
                calendar.clear();
                calendar.set(year, month - 1, date);
                // 2020.05.08 is translated to 1588896000000
                long timestamp = calendar.getTimeInMillis();

                // a candidate index can be created before or after enabled time, but the index is definitely created before disabled
                // time
                if (timestamp <= disabledTimeMillis && maxTimestamp <= timestamp) {
                    maxTimestamp = timestamp;
                    // we can have two rotations on the same day and we don't know which one has our data, so we keep all
                    List<String> indexList = candidateIndices.computeIfAbsent(timestamp, k -> new ArrayList<String>());
                    indexList.add(indexName);
                }
            }
        }
        List<String> candidates = new ArrayList<String>();
        List<String> latestCandidate = candidateIndices.get(maxTimestamp);

        if (latestCandidate != null) {
            candidates.addAll(latestCandidate);
        }

        // look back one more index for an edge case:
        // Suppose detector interval is 1 minute. Detector last run is at 2020-05-07, 11:59:50 PM,
        // then AD result indices rolled over as .opendistro-anomaly-results-history-2020.05.07-001
        // Detector next run will be 2020-05-08, 00:00:50 AM. If a user stop the detector at
        // 2020-05-08 00:00:10 AM, detector will not have AD result on 2020-05-08.
        // We check AD result indices one day earlier to make sure we can always get AD result.
        Map.Entry<Long, List<String>> earlierCandidate = candidateIndices.lowerEntry(maxTimestamp);
        if (earlierCandidate != null) {
            candidates.addAll(earlierCandidate.getValue());
        }
        latestIndex = candidates.toArray(new String[0]);
    }

    if (latestIndex == null || latestIndex.length == 0) {
        // no result index found: can be due to anomaly result is not created yet or result indices for the detector have been deleted.
        listener.onResponse(new DetectorProfile());
        return;
    }
    SearchRequest searchLatestResult = createLatestAnomalyResultRequest(detectorId, enabledTimeMillis, disabledTimeMillis, latestIndex);
    client.search(searchLatestResult, onGetLatestAnomalyResult(listener, detectorId));
}
 
Example 17
Source File: Acl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Create an instance of the ACL from its canonical string representation.
 * 
 * @param acl The string representation of the ACL as defined in OMA DM. If
 *        {@code null} or empty then it represents an empty list of
 *        principals with no permissions.
 * @throws IllegalArgumentException if acl is not a valid OMA DM ACL string
 */
public Acl(String acl) {
	if (acl == null || acl.equals("")) { // empty permission set
		principalPermissions = new TreeMap();
		globalPermissions = 0;
		return;
	}

	TreeMap tempPrincipalPermissions = new TreeMap();
	int tempGlobalPermissions = 0;

	String[] aclEntries = split(acl, '&', -1);
	for (int i = 0; i < aclEntries.length; i++) {
		if (aclEntries[i].length() == 0)
			throw new IllegalArgumentException("Invalid ACL string: empty ACL entry.");

		String[] entryParts = split(aclEntries[i], '=', 2);
		if (entryParts.length == 1)
			throw new IllegalArgumentException("Invalid ACL string: no '=' in ACL entry.");
		if (entryParts[1].length() == 0)
			throw new IllegalArgumentException("Invalid ACL string: no server identifiers in ACL entry.");

		int command = parseCommand(entryParts[0]);
		String[] serverIds = split(entryParts[1], '+', -1);
		for (int j = 0; j < serverIds.length; j++) {
			if (serverIds[j].length() == 0)
				throw new IllegalArgumentException("Invalid ACL string: empty server identifier.");

			if (serverIds[j].equals(ALL_PRINCIPALS))
				tempGlobalPermissions |= command;
			else {
				checkServerId(serverIds[j], "Invalid ACL string: " + "server ID contains illegal character");
				Integer n = (Integer) tempPrincipalPermissions.get(serverIds[j]);
				int oldPermission = (n != null) ? n.intValue() : 0;
				tempPrincipalPermissions.put(serverIds[j], new Integer(oldPermission | command));
			}
		}
	}

	principalPermissions = tempPrincipalPermissions;
	globalPermissions = tempGlobalPermissions;
}
 
Example 18
Source File: HDBSCAN.java    From clust4j with Apache License 2.0 4 votes vote down vote up
protected static int[] getLabels(ArrayList<CompQuadTup<Integer, Integer, Double, Integer>> condensed,
								TreeMap<Integer, Double> stability) {
	
	double subTreeStability;
	ArrayList<Integer> clusters = new ArrayList<Integer>();
	HSet<Integer> clusterSet;
	TreeMap<Integer, Integer> clusterMap = new TreeMap<>(), 
			reverseClusterMap = new TreeMap<>();
	
	// Get descending sorted key set
	ArrayList<Integer> nodeList = GetLabelUtils.descSortedKeySet(stability);
	
	// Get tuples where child size > 1
	EntryPair<ArrayList<double[]>, Integer> entry = GetLabelUtils.childSizeGtOneAndMaxChild(condensed);
	ArrayList<double[]> clusterTree = entry.getKey();
	
	// Map of nodes to whether it's a cluster
	TreeMap<Integer, Boolean> isCluster = GetLabelUtils.initNodeMap(nodeList);
	
	// Get num points
	//int numPoints = entry.getValue();
	
	// Iter over nodes
	for(Integer node: nodeList) {
		subTreeStability = GetLabelUtils.subTreeStability(clusterTree, node, stability);
		
		if(subTreeStability > stability.get(node)) {
			isCluster.put(node, false);
			stability.put(node, subTreeStability);
		} else {
			for(Integer subNode: GetLabelUtils.breadthFirstSearchFromClusterTree(clusterTree, node))
				if(subNode.intValue() != node)
					isCluster.put(subNode, false);
		}
		
	}
	
	// Now add to clusters
	for(Map.Entry<Integer, Boolean> c: isCluster.entrySet())
		if(c.getValue())
			clusters.add(c.getKey());
	clusterSet = new HSet<Integer>(clusters);
	
	// Build cluster map
	int n = 0;
	for(Integer clust: clusterSet) {
		clusterMap.put(clust, n);
		reverseClusterMap.put(n, clust);
		n++;
	}

	return doLabeling(condensed, clusters, clusterMap);
}
 
Example 19
Source File: AMRMClientImpl.java    From big-c with Apache License 2.0 4 votes vote down vote up
private void
    addResourceRequest(Priority priority, String resourceName,
        Resource capability, T req, boolean relaxLocality,
        String labelExpression) {
  Map<String, TreeMap<Resource, ResourceRequestInfo>> remoteRequests =
    this.remoteRequestsTable.get(priority);
  if (remoteRequests == null) {
    remoteRequests = 
        new HashMap<String, TreeMap<Resource, ResourceRequestInfo>>();
    this.remoteRequestsTable.put(priority, remoteRequests);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Added priority=" + priority);
    }
  }
  TreeMap<Resource, ResourceRequestInfo> reqMap = 
                                        remoteRequests.get(resourceName);
  if (reqMap == null) {
    // capabilities are stored in reverse sorted order. smallest last.
    reqMap = new TreeMap<Resource, ResourceRequestInfo>(
        new ResourceReverseMemoryThenCpuComparator());
    remoteRequests.put(resourceName, reqMap);
  }
  ResourceRequestInfo resourceRequestInfo = reqMap.get(capability);
  if (resourceRequestInfo == null) {
    resourceRequestInfo =
        new ResourceRequestInfo(priority, resourceName, capability,
            relaxLocality);
    reqMap.put(capability, resourceRequestInfo);
  }
  
  resourceRequestInfo.remoteRequest.setNumContainers(
       resourceRequestInfo.remoteRequest.getNumContainers() + 1);

  if (relaxLocality) {
    resourceRequestInfo.containerRequests.add(req);
  }
  
  if (ResourceRequest.ANY.equals(resourceName)) {
    resourceRequestInfo.remoteRequest.setNodeLabelExpression(labelExpression);
  }

  // Note this down for next interaction with ResourceManager
  addResourceRequestToAsk(resourceRequestInfo.remoteRequest);

  if (LOG.isDebugEnabled()) {
    LOG.debug("addResourceRequest:" + " applicationId="
        + " priority=" + priority.getPriority()
        + " resourceName=" + resourceName + " numContainers="
        + resourceRequestInfo.remoteRequest.getNumContainers() 
        + " #asks=" + ask.size());
  }
}
 
Example 20
Source File: SunFontManager.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Get a list of installed fonts in the requested {@link Locale}.
 * The list contains the fonts Family Names.
 * If Locale is null, the default locale is used.
 *
 * @param requestedLocale, if null the default locale is used.
 * @return list of installed fonts in the system.
 */
public String[] getInstalledFontFamilyNames(Locale requestedLocale) {
    if (requestedLocale == null) {
        requestedLocale = Locale.getDefault();
    }
    if (allFamilies != null && lastDefaultLocale != null &&
        requestedLocale.equals(lastDefaultLocale)) {
            String[] copyFamilies = new String[allFamilies.length];
            System.arraycopy(allFamilies, 0, copyFamilies,
                             0, allFamilies.length);
            return copyFamilies;
    }

    TreeMap<String,String> familyNames = new TreeMap<String,String>();
    //  these names are always there and aren't localised
    String str;
    str = Font.SERIF;         familyNames.put(str.toLowerCase(), str);
    str = Font.SANS_SERIF;    familyNames.put(str.toLowerCase(), str);
    str = Font.MONOSPACED;    familyNames.put(str.toLowerCase(), str);
    str = Font.DIALOG;        familyNames.put(str.toLowerCase(), str);
    str = Font.DIALOG_INPUT;  familyNames.put(str.toLowerCase(), str);

    /* Platform APIs may be used to get the set of available family
     * names for the current default locale so long as it is the same
     * as the start-up system locale, rather than loading all fonts.
     */
    if (requestedLocale.equals(getSystemStartupLocale()) &&
        getFamilyNamesFromPlatform(familyNames, requestedLocale)) {
        /* Augment platform names with JRE font family names */
        getJREFontFamilyNames(familyNames, requestedLocale);
    } else {
        loadFontFiles();
        Font2D[] physicalfonts = getPhysicalFonts();
        for (int i=0; i < physicalfonts.length; i++) {
            if (!(physicalfonts[i] instanceof NativeFont)) {
                String name =
                    physicalfonts[i].getFamilyName(requestedLocale);
                familyNames.put(name.toLowerCase(requestedLocale), name);
            }
        }
    }

    // Add any native font family names here
    addNativeFontFamilyNames(familyNames, requestedLocale);

    String[] retval =  new String[familyNames.size()];
    Object [] keyNames = familyNames.keySet().toArray();
    for (int i=0; i < keyNames.length; i++) {
        retval[i] = familyNames.get(keyNames[i]);
    }
    if (requestedLocale.equals(Locale.getDefault())) {
        lastDefaultLocale = requestedLocale;
        allFamilies = new String[retval.length];
        System.arraycopy(retval, 0, allFamilies, 0, allFamilies.length);
    }
    return retval;
}