List of usage examples for com.google.common.collect BiMap values
@Override Set<V> values();
Because a bimap has unique values, this method returns a Set , instead of the java.util.Collection specified in the Map interface.
From source file:com.publictransitanalytics.scoregenerator.Main.java
private static <S extends ScoreCard> BiMap<OperationDescription, Calculation<S>> runComparison( final OperationDescription baseDescription, final ScoreCardFactory scoreCardFactory, final Set<Center> centers, final Duration samplingInterval, final Duration span, final boolean backward, final TimeTracker timeTracker, final Grid grid, final Map<String, ServiceDataDirectory> serviceDirectoriesMap, final Duration longestDuration, final OperationDescription comparisonDescription, final NetworkConsoleFactory consoleFactory) throws InterruptedException, IOException, ExecutionException { final ImmutableBiMap.Builder<OperationDescription, Calculation<S>> resultBuilder = ImmutableBiMap.builder(); final Calculation<S> calculation = buildCalculation(baseDescription, serviceDirectoriesMap, grid, centers, longestDuration, backward, span, samplingInterval, timeTracker, scoreCardFactory); final NetworkConsole console = consoleFactory.getConsole(calculation.getTransitNetwork(), calculation.getStopIdMap()); console.enterConsole();/*from w ww .ja v a 2s . c o m*/ resultBuilder.put(baseDescription, calculation); final Environment environment = new Environment(grid, longestDuration); if (comparisonDescription != null) { final Calculation trialCalculation = buildCalculation(comparisonDescription, serviceDirectoriesMap, grid, centers, longestDuration, backward, span, samplingInterval, timeTracker, scoreCardFactory); final NetworkConsole trialConsole = consoleFactory.getConsole(trialCalculation.getTransitNetwork(), trialCalculation.getStopIdMap()); trialConsole.enterConsole(); log.info("Trial in service time = {}; original in service time = {}.", trialCalculation.getTransitNetwork().getInServiceTime(), calculation.getTransitNetwork().getInServiceTime()); resultBuilder.put(comparisonDescription, trialCalculation); } final BiMap<OperationDescription, Calculation<S>> calculations = resultBuilder.build(); final Workflow workflow = new ParallelTaskExecutor( new ProgressiveRangeExecutor(new DynamicProgrammingAlgorithm(), environment)); workflow.calculate(calculations.values()); return calculations; }
From source file:pl.asie.foamfix.ProxyCommon.java
private void optimizeForgeRegistries() { // BitSets scale dynamically, you really don't need to preallocate 8MB for 64 million IDs... *yawn* try {// ww w . j a v a2 s.c om int optimizedRegs = 0; int optimizedSavings = 0; Class persistentRegistryClass = Class .forName("net.minecraftforge.fml.common.registry.PersistentRegistryManager$PersistentRegistry"); Class controlledRegistryClass = Class .forName("net.minecraftforge.fml.common.registry.FMLControlledNamespacedRegistry"); Field biMapField = persistentRegistryClass.getDeclaredField("registries"); Field availMapField = controlledRegistryClass.getDeclaredField("availabilityMap"); Field sizeStickyField = BitSet.class.getDeclaredField("sizeIsSticky"); Method trimToSizeMethod = BitSet.class.getDeclaredMethod("trimToSize"); biMapField.setAccessible(true); availMapField.setAccessible(true); sizeStickyField.setAccessible(true); trimToSizeMethod.setAccessible(true); for (Object registryHolder : persistentRegistryClass.getEnumConstants()) { BiMap biMap = (BiMap) biMapField.get(registryHolder); for (Object registry : biMap.values()) { BitSet availMap = (BitSet) availMapField.get(registry); int size = availMap.size(); if (size > 65536) { sizeStickyField.set(availMap, false); trimToSizeMethod.invoke(availMap); optimizedRegs++; optimizedSavings += ((size - availMap.size()) >> 3); } } } FoamFixShared.ramSaved += optimizedSavings; FoamFix.logger .info("Optimized " + optimizedRegs + " FML registries, saving " + optimizedSavings + " bytes."); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.hpcloud.mon.app.AlarmService.java
/** * Returns an entry containing Maps of old, changed, and new sub expressions by comparing the * {@code alarmExpression} to the existing sub expressions for the {@code alarmId}. *///from w w w . j a v a2 s .c o m SubExpressions subExpressionsFor(String alarmId, AlarmExpression alarmExpression) { BiMap<String, AlarmSubExpression> oldExpressions = HashBiMap.create(repo.findSubExpressions(alarmId)); Set<AlarmSubExpression> oldSet = oldExpressions.inverse().keySet(); Set<AlarmSubExpression> newSet = new HashSet<>(alarmExpression.getSubExpressions()); // Identify old or changed expressions Set<AlarmSubExpression> oldOrChangedExpressions = new HashSet<>(Sets.difference(oldSet, newSet)); // Identify new or changed expressions Set<AlarmSubExpression> newOrChangedExpressions = new HashSet<>(Sets.difference(newSet, oldSet)); // Find changed expressions Map<String, AlarmSubExpression> changedExpressions = new HashMap<>(); for (Iterator<AlarmSubExpression> oldIt = oldOrChangedExpressions.iterator(); oldIt.hasNext();) { AlarmSubExpression oldExpr = oldIt.next(); for (Iterator<AlarmSubExpression> newIt = newOrChangedExpressions.iterator(); newIt.hasNext();) { AlarmSubExpression newExpr = newIt.next(); if (sameKeyFields(oldExpr, newExpr)) { oldIt.remove(); newIt.remove(); changedExpressions.put(oldExpressions.inverse().get(oldExpr), newExpr); } } } // Create the list of unchanged expressions BiMap<String, AlarmSubExpression> unchangedExpressions = HashBiMap.create(oldExpressions); unchangedExpressions.values().removeAll(oldOrChangedExpressions); unchangedExpressions.keySet().removeAll(changedExpressions.keySet()); // Remove old sub expressions oldExpressions.values().retainAll(oldOrChangedExpressions); // Create IDs for new expressions Map<String, AlarmSubExpression> newExpressions = new HashMap<>(); for (AlarmSubExpression expression : newOrChangedExpressions) newExpressions.put(UUID.randomUUID().toString(), expression); SubExpressions subExpressions = new SubExpressions(); subExpressions.oldAlarmSubExpressions = oldExpressions; subExpressions.changedSubExpressions = changedExpressions; subExpressions.unchangedSubExpressions = unchangedExpressions; subExpressions.newAlarmSubExpressions = newExpressions; return subExpressions; }
From source file:monasca.api.app.AlarmDefinitionService.java
/** * Returns an entry containing Maps of old, changed, and new sub expressions by comparing the * {@code alarmExpression} to the existing sub expressions for the {@code alarmDefId}. *//*from w ww . ja v a 2s . c o m*/ SubExpressions subExpressionsFor(final Map<String, AlarmSubExpression> initialSubExpressions, AlarmExpression alarmExpression) { BiMap<String, AlarmSubExpression> oldExpressions = HashBiMap.create(initialSubExpressions); Set<AlarmSubExpression> oldSet = oldExpressions.inverse().keySet(); Set<AlarmSubExpression> newSet = new HashSet<>(alarmExpression.getSubExpressions()); // Identify old or changed expressions Set<AlarmSubExpression> oldOrChangedExpressions = new HashSet<>(Sets.difference(oldSet, newSet)); // Identify new or changed expressions Set<AlarmSubExpression> newOrChangedExpressions = new HashSet<>(Sets.difference(newSet, oldSet)); // Find changed expressions Map<String, AlarmSubExpression> changedExpressions = new HashMap<>(); for (Iterator<AlarmSubExpression> oldIt = oldOrChangedExpressions.iterator(); oldIt.hasNext();) { AlarmSubExpression oldExpr = oldIt.next(); for (Iterator<AlarmSubExpression> newIt = newOrChangedExpressions.iterator(); newIt.hasNext();) { AlarmSubExpression newExpr = newIt.next(); if (sameKeyFields(oldExpr, newExpr)) { oldIt.remove(); newIt.remove(); changedExpressions.put(oldExpressions.inverse().get(oldExpr), newExpr); } } } // Create the list of unchanged expressions BiMap<String, AlarmSubExpression> unchangedExpressions = HashBiMap.create(oldExpressions); unchangedExpressions.values().removeAll(oldOrChangedExpressions); unchangedExpressions.keySet().removeAll(changedExpressions.keySet()); // Remove old sub expressions oldExpressions.values().retainAll(oldOrChangedExpressions); // Create IDs for new expressions Map<String, AlarmSubExpression> newExpressions = new HashMap<>(); for (AlarmSubExpression expression : newOrChangedExpressions) newExpressions.put(UUID.randomUUID().toString(), expression); SubExpressions subExpressions = new SubExpressions(); subExpressions.oldAlarmSubExpressions = oldExpressions; subExpressions.changedSubExpressions = changedExpressions; subExpressions.unchangedSubExpressions = unchangedExpressions; subExpressions.newAlarmSubExpressions = newExpressions; return subExpressions; }
From source file:com.ning.arecibo.collector.resources.HostDataResource.java
@GET @Path("/hosts") @Produces(MediaType.APPLICATION_JSON)//from www. j av a 2 s . c o m @TimedResource public StreamingOutput getHosts(@QueryParam("pretty") @DefaultValue("false") final boolean pretty) { try { final BiMap<Integer, String> hosts = dao.getHosts(); return streamResponse(hosts.values(), pretty); } catch (CacheLoader.InvalidCacheLoadException e) { throw new WebApplicationException(e, Response.Status.NOT_FOUND); } catch (RuntimeException e) { // JDBI exception throw new WebApplicationException(e, buildServiceUnavailableResponse()); } }
From source file:org.cloudsmith.geppetto.pp.dsl.ui.container.PPWorkspaceProjectsStateHelper.java
/** * Returns the best matching project (or null if there is no match) among the projects in the * workspace.//from w w w . ja v a2 s .com * A translation is made from "/" to "-" in the separators in dependencies. (Should be checked elsewhere). * * @param d * @return */ protected IProject getBestMatchingProject(Dependency d) { ModuleName name = d.getName(); if (name == null) return null; // Names with "/" are not allowed name = name.withSeparator('-'); String namepart = name + "-"; BiMap<IProject, Version> candidates = HashBiMap.create(); int len = namepart.length(); for (IProject p : getWorkspaceRoot().getProjects()) { String n = p.getName(); if (n.startsWith(namepart) && n.length() > len && isAccessibleXtextProject(p)) { try { candidates.put(p, Version.create(p.getName().substring(len))); } catch (IllegalArgumentException e) { // Project name does not end with a valid version. Just skip it } } } if (candidates.isEmpty()) return null; VersionRange vr = d.getVersionRequirement(); if (vr == null) vr = VersionRange.ALL_INCLUSIVE; Version best = vr.findBestMatch(candidates.values()); return candidates.inverse().get(best); }
From source file:com.puppetlabs.geppetto.pp.dsl.ui.container.PPWorkspaceProjectsStateHelper.java
/** * Returns the best matching project (or null if there is no match) among the projects in the * workspace.// www. j a v a 2 s. c o m * A translation is made from "/" to "-" in the separators in dependencies. (Should be checked elsewhere). * * @param d * @return */ protected IProject getBestMatchingProject(Dependency d) { ModuleName name = d.getName(); if (name == null) return null; String namepart = name + "-"; BiMap<IProject, Version> candidates = HashBiMap.create(); int len = namepart.length(); for (IProject p : getWorkspaceRoot().getProjects()) { String n = p.getName(); if (n.startsWith(namepart) && n.length() > len && isAccessibleXtextProject(p)) { try { candidates.put(p, Version.fromString(p.getName().substring(len))); } catch (IllegalArgumentException e) { // Project name does not end with a valid version. Just skip it } } } if (candidates.isEmpty()) return null; VersionRange vr = d.getVersionRequirement(); if (vr == null) vr = VersionRange.ALL_INCLUSIVE; Version best = vr.findBestMatch(candidates.values()); return candidates.inverse().get(best); }
From source file:com.publictransitanalytics.scoregenerator.workflow.Calculation.java
public Calculation(final Grid grid, final Set<Center> centers, final Duration longestDuration, final boolean backward, final Duration span, final Duration samplingInterval, final double walkingMetersPerSecond, final TimeTracker timeTracker, final Map<String, ServiceDataDirectory> serviceDirectoriesMap, final ScoreCardFactory<S> scoreCardFactory, final LocalDateTime startTime, final ServiceDataDirectory serviceDirectory, final List<Patch> patches, final Set<TransitStop> addedStops, final Set<TransitStop> deletedStops, final BiMap<String, TransitStop> stopIdMap) throws InterruptedException { final LocalDateTime endTime = (span != null) ? startTime.plus(span) : null; this.walkingMetersPerSecond = walkingMetersPerSecond; this.longestDuration = longestDuration; this.backward = backward; this.timeTracker = timeTracker; this.stopIdMap = stopIdMap; gridPoints = grid.getGridPoints();//from www.ja v a 2 s .c o m final LocalDateTime earliestTime = getEarliestTime(startTime, longestDuration, backward); final LocalDateTime latestTime = getLatestTime(startTime, endTime, longestDuration, backward); final TransitNetwork baseTransitNetwork = buildTransitNetwork(serviceDirectory, earliestTime, latestTime, stopIdMap); pointSectorMap = buildPointSectorMap(grid, stopIdMap.values()); final PointSequencerFactory pointSequencerFactory; final RiderFactory baseRiderFactory; if (!backward) { baseRiderFactory = new ForwardRiderFactory(baseTransitNetwork); pointSequencerFactory = (origin, destinations) -> new ForwardPointSequencer(origin, destinations); } else { baseRiderFactory = new RetrospectiveRiderFactory(baseTransitNetwork); pointSequencerFactory = (destination, origins) -> new ForwardPointSequencer(destination, origins); } final DistanceClient distanceClient = buildOsrmDistanceClient(pointSequencerFactory, 1000); final Set<PointLocation> centerPoints = centers.stream().map(Center::getPhysicalCenters) .flatMap(Collection::stream).collect(Collectors.toSet()); final BiMap<String, PointLocation> basePointIdMap = buildPointIdMap(centerPoints, stopIdMap, grid); taskGroups = getTaskGroups(centers); times = getTaskTimes(startTime, endTime, samplingInterval); final DistanceClient estimator = new EstimatingDistanceClient(walkingMetersPerSecond); final DistanceStoreManager storeManager = new StoreBackedDistanceStoreManager( serviceDirectory.getWalkingTimeStore(), serviceDirectory.getMaxWalkingTimeStore(), basePointIdMap); final ReachabilityClient baseReachabilityClient = new RangedCachingReachabilityClient(storeManager, basePointIdMap.values(), timeTracker, distanceClient, estimator); allowedModes = ImmutableSet.of(ModeType.TRANSIT, ModeType.WALKING); final Transformer transformer = new Transformer(timeTracker, baseTransitNetwork, backward, longestDuration, walkingMetersPerSecond, distanceClient, estimator, basePointIdMap, baseReachabilityClient, storeManager, baseRiderFactory); for (final Patch patch : patches) { transformer.addTripPatch(patch); } for (final TransitStop stop : addedStops) { transformer.addStop(stop); } for (final TransitStop stop : deletedStops) { transformer.deleteStop(stop); } final Set<LogicalCenter> logicalCenters = centers.stream().map(Center::getLogicalCenter) .collect(Collectors.toSet()); scoreCard = scoreCardFactory.makeScoreCard(times.size() * logicalCenters.size(), pointSectorMap); transitNetwork = transformer.getTransitNetwork(); riderFactory = transformer.getRiderFactory(); reachabilityClient = transformer.getReachabilityClient(); }
From source file:org.jpmml.evaluator.GeneralRegressionModelEvaluator.java
private Map<FieldName, FieldValue> getArguments(EvaluationContext context) { BiMap<FieldName, Predictor> factors = getFactorRegistry(); BiMap<FieldName, Predictor> covariates = getCovariateRegistry(); Map<FieldName, FieldValue> result = Maps.newLinkedHashMap(); Iterable<Predictor> predictors = Iterables.concat(factors.values(), covariates.values()); for (Predictor predictor : predictors) { FieldName name = predictor.getName(); result.put(name, ExpressionUtil.evaluate(name, context)); }//from w w w . j a va 2 s .c om return result; }
From source file:org.terasology.world.biomes.BiomeManager.java
/** * Create a BiomeManager from known state such as a world save, that already contains * a mapping between Biome URIs and their short ids. * * @param knownBiomeIdMap A mapping between Biome URIs (combination of module id + biome id) and * their short ids that are applicable to this world save. *///w w w . j a v a2 s . c om public BiomeManager(ModuleEnvironment moduleEnvironment, Map<String, Short> knownBiomeIdMap) { for (Class<?> biomeRegistrator : moduleEnvironment.getSubtypesOf(BiomeRegistrator.class)) { BiomeRegistrator registrator; try { registrator = (BiomeRegistrator) biomeRegistrator.newInstance(); } catch (InstantiationException | IllegalAccessException e) { logger.error("Cannot call biome registrator {} because it cannot be instantiated.", biomeRegistrator, e); continue; } registrator.registerBiomes(this); } BiMap<Short, Biome> currentIdMap = HashBiMap.create(biomeShortIdMap); // Make a copy before we start modifying it biomeShortIdMap.clear(); // Always register the unknown biome first, so it gets id 0, which is the default for all chunks registerBiome(UnknownBiome.INSTANCE); for (Map.Entry<String, Short> entry : knownBiomeIdMap.entrySet()) { if (entry.getKey().equals(getUnknownBiome().getId())) { continue; // The unknown biome is handled internally } Biome biome = biomeIdMap.get(entry.getKey()); if (biome == null) { throw new IllegalStateException( "Save game references biome " + entry.getKey() + " which is no " + "longer available."); } if (biomeShortIdMap.put(entry.getValue(), biome) != null) { throw new IllegalStateException("Biome short id " + entry.getValue() + " is present multiple times " + "in the save game (latest is mapped to " + biome.getId() + "."); } logger.info("Restored biome {} with short id {} from save game.", entry.getKey(), entry.getValue()); currentIdMap.values().remove(biome); } // Handle all new biomes that weren't present in the save game for (Biome biome : currentIdMap.values()) { short freeBiomeId = getFreeBiomeId(); biomeShortIdMap.put(freeBiomeId, biome); logger.info("Registered new biome {} with id {} that wasn't present in the save game.", biome.getId(), freeBiomeId); } }