List of usage examples for com.google.common.collect Multimap entries
Collection<Map.Entry<K, V>> entries();
From source file:com.b2international.snowowl.snomed.core.ecl.SnomedEclRefinementEvaluator.java
/** * Handles attribute refinements inside attribute group refinements. *//*from w w w. j a v a2s .co m*/ protected Promise<Collection<Property>> evalGroup(final BranchContext context, final Range<Long> groupCardinality, final AttributeConstraint refinement) { if (refinement.isReversed()) { throw new BadRequestException("Reversed attributes are not supported in group refinements"); } else { return evalRefinement(context, refinement, true, groupCardinality).thenWith(input -> { final Cardinality cardinality = refinement.getCardinality(); // two cases here, one is the [1..x] the other is [0..x] if (cardinality != null && cardinality.getMin() == 0 && cardinality.getMax() != UNBOUNDED_CARDINALITY) { // XXX internal evaluation returns negative matches, that should be excluded from the focusConcept set final Function<Property, Object> idProvider = refinement.isReversed() ? Property::getValue : Property::getObjectId; final Set<String> matchingIds = FluentIterable.from(input).transform(idProvider) .filter(String.class).toSet(); return focusConcepts.resolveToConceptsWithGroups(context) .then(new Function<Multimap<String, Integer>, Collection<Property>>() { @Override public Collection<Property> apply(Multimap<String, Integer> groupsById) { if (groupsById.isEmpty()) { return Sets.newHashSet(); } else { final Collection<Property> matchingProperties = newHashSetWithExpectedSize( groupsById.size() - matchingIds.size()); for (Entry<String, Integer> entry : groupsById.entries()) { final String id = entry.getKey(); if (!matchingIds.contains(id)) { matchingProperties.add(new Property(id, entry.getValue())); } } return matchingProperties; } } }); } else { return Promise.immediate(input); } }).failWith(throwable -> { if (throwable instanceof MatchAll) { return focusConcepts.resolveToConceptsWithGroups(context) .then(new Function<Multimap<String, Integer>, Collection<Property>>() { @Override public Collection<Property> apply(Multimap<String, Integer> groupsById) { final Collection<Property> matchingProperties = newHashSetWithExpectedSize( groupsById.size()); for (Entry<String, Integer> entry : groupsById.entries()) { matchingProperties.add(new Property(entry.getKey(), entry.getValue())); } return matchingProperties; } }); } throw new SnowowlRuntimeException(throwable); }); } }
From source file:org.jclouds.cleanup.doclet.ClassDocParser.java
private Collection<String> extractComment(String defaultCommentText, Multimap<String, String> defaultTags, ProgramElementDoc... elements) { String commentText = null;/* www .j a v a 2 s . c o m*/ for (ProgramElementDoc element : elements) { if (element != null && element.commentText() != null && !element.commentText().trim().isEmpty()) { commentText = element.commentText(); break; } } if (commentText == null) { commentText = defaultCommentText; } Multimap<String, String> tagsToOutput = LinkedListMultimap.create(); if (defaultTags != null) tagsToOutput.putAll(defaultTags); for (ProgramElementDoc element : elements) { if (element != null) { for (Tag tag : element.tags()) { tagsToOutput.put(tag.name(), tag.text()); } } } if (commentText == null && tagsToOutput.isEmpty()) return ImmutableList.of(); List<String> result = Lists.newArrayList(); if (commentText != null) { for (String line : commentText.split("\n")) { result.add(line.trim()); } if (!tagsToOutput.isEmpty()) { result.add(""); } } for (Map.Entry<String, String> tag : tagsToOutput.entries()) { result.add(tag.getKey() + " " + tag.getValue()); } return result; }
From source file:org.opentestsystem.authoring.testauth.publish.BasePublisherHelper.java
private List<ItemReferenceGroup> buildItemReferenceGroups(final String bankKey, final Map<String, Segment> segmentMap, final Assessment assessment, final List<Item> itemList, final String locationId, final boolean processSegmentLevel) { // find any/all existing itemGroups by segmentId/formPartitionId, build into multimap keyed by itemGroupId final List<ItemGroup> itemGroupList = processSegmentLevel ? this.itemGroupService.getItemGroupsBySegment(locationId) : this.itemGroupService.getItemGroupsFormPartition(locationId); final ListMultimap<String, ItemGroup> existingItemGroupMap = Multimaps.index(itemGroupList, ITEMGROUPID_KEY_TRANSFORMER); // returns map w/ key of segmentId/formPartitionId and value of item list final Map<String, List<Item>> itemsMap = processSegmentLevel ? retrieveScopedItems(assessment.getId(), itemList, locationId, false) : retrieveScopedItems(assessment.getId(), itemList, null, true); // scope by just location Id (instead of summed partitions per segment) final List<Item> flattenedItemList = processSegmentLevel ? Lists.newArrayList(Iterables.concat(itemsMap.values())) : itemsMap.get(locationId);//from ww w .j a v a2 s.c o m // item can belong to more than one group or 'NO_GROUP'; attempt to invert the relationship to construct // a) map w/ key of item group & value of list of items // b) list of lone-wolf 'NO_GROUP' items for which an ItemReferenceGroup will be later fabricated final Multimap<List<String>, Item> groupedMultiMap = Multimaps.index(flattenedItemList, ITEM_ITEMGROUPIDLIST_TRANSFORMER); final Map<ItemGroup, List<Item>> groupedItemMap = Maps.newHashMap(); final Set<Item> ungroupedItemSet = Sets.newHashSet(); for (final Entry<List<String>, Item> itemGrouping : groupedMultiMap.entries()) { for (final String itemGroupingKey : itemGrouping.getKey()) { if (StringUtils.equals(itemGroupingKey, Item.SKIP_GROUP_KEY)) { } else if (!StringUtils.equals(itemGroupingKey, Item.NO_GROUP_KEY)) { ItemGroup itemGroup = null; if (!CollectionUtils.isEmpty(existingItemGroupMap.get(itemGroupingKey))) { itemGroup = existingItemGroupMap.get(itemGroupingKey).get(0); } if (itemGroup != null) { if (CollectionUtils.isEmpty(groupedItemMap.get(itemGroup))) { final List<Item> itemsPerItemGroupList = Lists.newArrayList(); groupedItemMap.put(itemGroup, itemsPerItemGroupList); } groupedItemMap.get(itemGroup).add(itemGrouping.getValue()); } } else if (Iterables.any(itemGrouping.getValue().getAdaptiveAndFixedItemLocations(), PublisherUtil.ITEM_LOCATION_MATCHER.getInstance(Item.NO_GROUP_KEY, locationId, processSegmentLevel ? ItemGroupLocationType.SEGMENT : ItemGroupLocationType.FORM_PARTITION))) { ungroupedItemSet.add(itemGrouping.getValue()); } } } // transform grouped // note that segmentMap parameter is null in case processSegmentLevel parameter was true final List<ItemReferenceGroup> groupedItems = nullsafeListTransform(groupedItemMap.entrySet(), ITEMLIST_ITEMGROUP_TRANSFORMER.getInstance(bankKey, segmentMap, this.serverUniqueNumber, assessment.getVersion())); // transform ungrouped final List<ItemReferenceGroup> ungroupedItems = nullsafeListTransform(ungroupedItemSet, ITEM_ITEMGROUP_TRANSFORMER.getInstance(processSegmentLevel, locationId, bankKey, this.serverUniqueNumber, assessment.getVersion())); return Lists.newArrayList(Iterables.concat(ungroupedItems, groupedItems)); }
From source file:org.eclipse.xtext.ide.serializer.impl.EObjectDescriptionProvider.java
@Override public Iterable<IEObjectDescription> getEObjectDescriptions(Resource resource) { Multimap<EObject, IEObjectDescription> map = HashMultimap.create(); IResourceDescription description = resourceDescriptionManager.getResourceDescription(resource); for (IEObjectDescription desc : description.getExportedObjects()) { EObject object = EcoreUtil.resolve(desc.getEObjectOrProxy(), resource); map.put(object, desc);//from w w w.ja v a2s. co m } if (!resource.getContents().isEmpty()) { TreeIterator<EObject> it = EcoreUtil2.eAll(resource.getContents().get(0)); while (it.hasNext()) { EObject next = it.next(); if (map.containsKey(next)) { continue; } QualifiedName name = qualifiedNameProvider.getFullyQualifiedName(next); if (name != null) { IEObjectDescription desc = EObjectDescription.create(name, next); map.put(next, desc); } } } List<IEObjectDescription> result = Lists.newArrayList(); for (Map.Entry<EObject, IEObjectDescription> entry : map.entries()) { QualifiedName name = computeSimpleName(map, entry.getValue()); SimpleNameDescription copy = new SimpleNameDescription(name, entry.getKey(), entry.getValue()); result.add(copy); } return result; }
From source file:de.hzi.helmholtz.Compare.PathwayComparisonUsingModules.java
public double Calculations4SubsetBitScore(Map<String, Map<String, Double>> bestResultMappings) { SmithWaterman_b sw = new SmithWaterman_b(); int MatchingSubstrateCount = 0; int MismatchSubstrateCount = 0; int MatchingFunctionCount = 0; int MismatchFunctionCount = 0; Multiset<String> qfunction = LinkedHashMultiset.create(); Multiset<String> tfunction = LinkedHashMultiset.create(); List<Set<String>> qsubstrate = new ArrayList<Set<String>>(); List<Set<String>> tsubstrate = new ArrayList<Set<String>>(); String GeneKey = ""; int FunctionMatch = 0, StatusMatch = 0, SubstrateMatch = 0; int FunctionMisMatch = 0, StatusMisMatch = 0, SubstrateMisMatch = 0; int TranspositionDomains = 0; for (Map.Entry<String, Map<String, Double>> i : bestResultMappings.entrySet()) { for (Map.Entry<String, Double> j : i.getValue().entrySet()) { GeneKey = i.getKey() + "->" + j.getKey(); }// w ww .j a va 2s .c om Collection<Multimap<String, Integer>> Function = ScoreFunctionMatchMisMatch.get(GeneKey); for (Multimap<String, Integer> GetFunction : Function) { for (Map.Entry<String, Integer> Get : GetFunction.entries()) { String[] points = Get.getKey().split("-"); FunctionMatch += Integer.parseInt(points[0].trim()); FunctionMisMatch += Integer.parseInt(points[1].trim()); TranspositionDomains += Get.getValue(); break; } break; } Collection<Multimap<String, Integer>> Status = ScoreStatusMatchMisMatch.get(GeneKey); for (Multimap<String, Integer> GetFunction : Status) { for (Map.Entry<String, Integer> Get : GetFunction.entries()) { String[] points = Get.getKey().split("-"); StatusMatch += Integer.parseInt(points[0].trim()); StatusMisMatch += Integer.parseInt(points[1].trim()); break; } break; } Collection<Multimap<String, Integer>> Substrate = ScoreSubstrateMatchMisMatch.get(GeneKey); for (Multimap<String, Integer> GetFunction : Substrate) { for (Map.Entry<String, Integer> Get : GetFunction.entries()) { String[] points = Get.getKey().split("-"); SubstrateMatch += Integer.parseInt(points[0].trim()); SubstrateMisMatch += Integer.parseInt(points[1].trim()); break; } break; } } if (FunctionMisMatch == 0) { } ////////System.out.println(MismatchCount + " " + MatchingCount); int rawFunctionScore = ((FunctionMatch * 3) - (FunctionMisMatch * 2) - TranspositionDomains); int rawStatusScore = (StatusMatch * 3) - (StatusMisMatch * 2); int rawSubstrateScore = (SubstrateMatch * 3) - (SubstrateMisMatch * 2); double SubstrateBitScore = (((lambda * rawSubstrateScore) + Math.log(kscore)) / Math.log(2)); double StatusBitScore = (((lambda * rawStatusScore) + Math.log(kscore)) / Math.log(2)); double FunctionBitScore = (((lambda * rawFunctionScore) + Math.log(kscore)) / Math.log(2)); Double BitScore = SubstrateBitScore + StatusBitScore + FunctionBitScore; //////System.out.println(rawFunctionScore + " " + MatchingSubstrateCount + " " + BitScore); ScoreFunctionMatchMisMatch.clear(); ScoreStatusMatchMisMatch.clear(); ScoreSubstrateMatchMisMatch.clear(); return BitScore; }
From source file:com.twitter.aurora.scheduler.thrift.SchedulerThriftInterface.java
private Optional<String> rewriteConfig(ConfigRewrite command, MutableStoreProvider storeProvider) { Optional<String> error = Optional.absent(); switch (command.getSetField()) { case JOB_REWRITE: JobConfigRewrite jobRewrite = command.getJobRewrite(); IJobConfiguration existingJob = IJobConfiguration.build(jobRewrite.getOldJob()); IJobConfiguration rewrittenJob;//from ww w . j ava 2 s. c om try { rewrittenJob = ConfigurationManager .validateAndPopulate(IJobConfiguration.build(jobRewrite.getRewrittenJob())); } catch (TaskDescriptionException e) { // We could add an error here, but this is probably a hint of something wrong in // the client that's causing a bad configuration to be applied. throw Throwables.propagate(e); } if (!existingJob.getKey().equals(rewrittenJob.getKey())) { error = Optional.of("Disallowing rewrite attempting to change job key."); } else if (!existingJob.getOwner().equals(rewrittenJob.getOwner())) { error = Optional.of("Disallowing rewrite attempting to change job owner."); } else { JobStore.Mutable jobStore = storeProvider.getJobStore(); Multimap<String, IJobConfiguration> matches = jobsByKey(jobStore, existingJob.getKey()); switch (matches.size()) { case 0: error = Optional.of("No jobs found for key " + JobKeys.toPath(existingJob)); break; case 1: Map.Entry<String, IJobConfiguration> match = Iterables.getOnlyElement(matches.entries()); IJobConfiguration storedJob = match.getValue(); if (!storedJob.equals(existingJob)) { error = Optional.of("CAS compare failed for " + JobKeys.toPath(storedJob)); } else { jobStore.saveAcceptedJob(match.getKey(), rewrittenJob); } break; default: error = Optional.of("Multiple jobs found for key " + JobKeys.toPath(existingJob)); } } break; case INSTANCE_REWRITE: InstanceConfigRewrite instanceRewrite = command.getInstanceRewrite(); InstanceKey instanceKey = instanceRewrite.getInstanceKey(); Iterable<IScheduledTask> tasks = storeProvider.getTaskStore().fetchTasks(Query .instanceScoped(IJobKey.build(instanceKey.getJobKey()), instanceKey.getInstanceId()).active()); Optional<IAssignedTask> task = Optional.fromNullable(Iterables.getOnlyElement(tasks, null)) .transform(Tasks.SCHEDULED_TO_ASSIGNED); if (!task.isPresent()) { error = Optional.of("No active task found for " + instanceKey); } else if (!task.get().getTask().newBuilder().equals(instanceRewrite.getOldTask())) { error = Optional.of("CAS compare failed for " + instanceKey); } else { ITaskConfig newConfiguration = ITaskConfig .build(ConfigurationManager.applyDefaultsIfUnset(instanceRewrite.getRewrittenTask())); boolean changed = storeProvider.getUnsafeTaskStore().unsafeModifyInPlace(task.get().getTaskId(), newConfiguration); if (!changed) { error = Optional.of("Did not change " + task.get().getTaskId()); } } break; default: throw new IllegalArgumentException("Unhandled command type " + command.getSetField()); } return error; }
From source file:com.palantir.atlasdb.keyvalue.partition.PartitionedKeyValueService.java
@Override @Idempotent// w ww. ja v a 2 s. c o m public void delete(final String tableName, final Multimap<Cell, Long> keys) { runWithPartitionMapRetryable(new Function<DynamicPartitionMap, Void>() { @Override public Void apply(DynamicPartitionMap input) { final EndpointRequestCompletionService<Void> execSvc = EndpointRequestExecutor.newService(executor); final QuorumTracker<Void, Map.Entry<Cell, Long>> tracker = QuorumTracker.of(keys.entries(), input.getWriteEntriesParameters(keys)); input.runForCellsWrite(tableName, keys, new Function<Pair<KeyValueService, Multimap<Cell, Long>>, Void>() { @Override public Void apply(final Pair<KeyValueService, Multimap<Cell, Long>> e) { final Future<Void> future = execSvc.submit(new Callable<Void>() { @Override public Void call() throws Exception { e.lhSide.delete(tableName, e.rhSide); return null; } }, e.lhSide); tracker.registerRef(future, e.rhSide.entries()); return null; } }); completeWriteRequest(tracker, execSvc); return null; } }); }
From source file:com.google.devtools.build.lib.analysis.BuildView.java
/** * <p>If {@link BuildConfiguration.Options#trimConfigurations()} is true, transforms a collection * of <Target, Configuration> pairs by trimming each target's * configuration to only the fragments the target and its transitive dependencies need. * * <p>Else returns configurations that unconditionally include all fragments. * * <p>Preserves the original input order. Uses original (untrimmed) configurations for targets * that can't be evaluated (e.g. due to loading phase errors). * * <p>This is suitable for feeding {@link ConfiguredTargetValue} keys: as general principle * {@link ConfiguredTarget}s should have exactly as much information in their configurations as * they need to evaluate and no more (e.g. there's no need for Android settings in a C++ * configured target)./*from w ww. j av a 2s. c om*/ */ // TODO(bazel-team): error out early for targets that fail - untrimmed configurations should // never make it through analysis (and especially not seed ConfiguredTargetValues) private List<TargetAndConfiguration> getDynamicConfigurations(Iterable<TargetAndConfiguration> inputs, EventHandler eventHandler) throws InterruptedException { Map<Label, Target> labelsToTargets = new LinkedHashMap<>(); // We'll get the configs from SkyframeExecutor#getConfigurations, which gets configurations // for deps including transitions. So to satisfy its API we repackage each target as a // Dependency with a NONE transition. Multimap<BuildConfiguration, Dependency> asDeps = ArrayListMultimap .<BuildConfiguration, Dependency>create(); for (TargetAndConfiguration targetAndConfig : inputs) { labelsToTargets.put(targetAndConfig.getLabel(), targetAndConfig.getTarget()); if (targetAndConfig.getConfiguration() != null) { asDeps.put(targetAndConfig.getConfiguration(), Dependency.withTransitionAndAspects(targetAndConfig.getLabel(), Attribute.ConfigurationTransition.NONE, // TODO(bazel-team): support top-level aspects ImmutableSet.<AspectDescriptor>of())); } } // Maps <target, originalConfig> pairs to <target, dynamicConfig> pairs for targets that // could be successfully Skyframe-evaluated. Map<TargetAndConfiguration, TargetAndConfiguration> successfullyEvaluatedTargets = new LinkedHashMap<>(); if (!asDeps.isEmpty()) { for (BuildConfiguration fromConfig : asDeps.keySet()) { Multimap<Dependency, BuildConfiguration> trimmedTargets = skyframeExecutor .getConfigurations(eventHandler, fromConfig.getOptions(), asDeps.get(fromConfig)); for (Map.Entry<Dependency, BuildConfiguration> trimmedTarget : trimmedTargets.entries()) { Target target = labelsToTargets.get(trimmedTarget.getKey().getLabel()); successfullyEvaluatedTargets.put(new TargetAndConfiguration(target, fromConfig), new TargetAndConfiguration(target, trimmedTarget.getValue())); } } } ImmutableList.Builder<TargetAndConfiguration> result = ImmutableList.<TargetAndConfiguration>builder(); for (TargetAndConfiguration originalInput : inputs) { if (successfullyEvaluatedTargets.containsKey(originalInput)) { // The configuration was successfully trimmed. result.add(successfullyEvaluatedTargets.get(originalInput)); } else { // Either the configuration couldn't be determined (e.g. loading phase error) or it's null. result.add(originalInput); } } return result.build(); }
From source file:com.palantir.atlasdb.keyvalue.jdbc.JdbcKeyValueService.java
@Override public void delete(final String tableName, final Multimap<Cell, Long> keys) { if (keys.isEmpty()) { return;// w w w.j a v a 2 s.c o m } run(new Function<DSLContext, Void>() { @Override public Void apply(DSLContext ctx) { Collection<Row3<byte[], byte[], Long>> rows = Lists.newArrayListWithCapacity(keys.size()); for (Entry<Cell, Long> entry : keys.entries()) { rows.add(row(entry.getKey().getRowName(), entry.getKey().getColumnName(), entry.getValue())); } ctx.deleteFrom(atlasTable(tableName).as(ATLAS_TABLE)) .where(row(A_ROW_NAME, A_COL_NAME, A_TIMESTAMP).in(rows)).execute(); return null; } }); }
From source file:uk.ac.ebi.apps.benchmark.ChemicalNameSearch.java
public void testMultiple() { System.out.println("Testing multiple"); Map<Class, NameService> services = new LinkedHashMap<Class, NameService>(); StringBuilder sb = new StringBuilder("Combined: "); for (String serviceName : getCommandLine().getOptionValues("service")) { sb.append(serviceName).append(", "); NameService service = getNameService(serviceName); service.startup();/*from w w w .java 2 s .co m*/ services.put(service.getIdentifier().getClass(), service); } boolean greedy = has("g"); Multimap<String, Identifier> results = ArrayListMultimap.create(); long searchStart = System.currentTimeMillis(); for (String name : names) { boolean foundHit = false; for (NameService service : services.values()) { Collection hits = service.searchName(name, has("a")); results.putAll(name, hits); if (!hits.isEmpty()) { if (!foundHit) { found++; foundHit = true; } if (!greedy) break; } } } long searchEnd = System.currentTimeMillis(); Long searchTime = (searchEnd - searchStart); Multimap<String, Set<String>> nameResults = ArrayListMultimap.create(); long resolveStart = System.currentTimeMillis(); for (Map.Entry<String, Identifier> e : results.entries()) { Identifier id = e.getValue(); nameResults.put(e.getKey(), new HashSet<String>(services.get(id.getClass()).getNames(id))); } long resolveEnd = System.currentTimeMillis(); Long resolveTime = resolveEnd - resolveStart; int trueFound = getRealScore(nameResults, new ChemicalFingerprintEncoder(), null); SummaryStatistics statistics = getHitIndices(nameResults, new ChemicalFingerprintEncoder()); String[] row = new String[] { sb.toString(), searchTime.toString(), resolveTime.toString(), Integer.toString(found), Integer.toString(trueFound), Double.toString(statistics.getMax()), Double.toString(statistics.getMean()), Double.toString(statistics.getStandardDeviation()) }; System.out.println(Joiner.on("\t").join(row)); }