private static Multimap<Long, SignPostPath> spFile(TomtomFolder folder) { File file = new File(folder.getFile("sp.dbf")); Multimap<Long, SignPostPath> result = TreeMultimap.create(); if (!file.exists()) { return result; } log.info("Reading SP {}", file); try (DbfReader reader = new DbfReader(file)) { DbfRow row; while ((row = reader.nextRow()) != null) { SignPostPath path = SignPostPath.fromRow(row); result.put(path.getId(), path); } } log.info("Loaded {} sign paths", result.size()); return result; }
/** * Binarize embeddings as described in "Revisiting Embedding Features for Simple Semi-supervised Learning" (Guo et al. 2014). * Output is a map of indices, where negative-valued indices are negative, and positive-valued indices are positive. Indices * start at 1, so as to avoid loss of information on 0. * * @param embeddings map from identifiers onto corresponding vectors * @return map from identifiers onto indices */ public static Multimap<String, Integer> binarize(Map<String, float[]> embeddings) { float[] posMean = filteredMean(embeddings.values(), v -> v >= 0); float[] negMean = filteredMean(embeddings.values(), v -> v < 0); Multimap<String, Integer> binarizedEmbeddings = HashMultimap.create(); for (Map.Entry<String, float[]> embedding : embeddings.entrySet()) { int index = 0; for (float val : embedding.getValue()) { if (val > posMean[index]) { binarizedEmbeddings.put(embedding.getKey(), -(index + 1)); } else if (val < negMean[index]) { binarizedEmbeddings.put(embedding.getKey(), index + 1); } ++index; } } return binarizedEmbeddings; }
/** * Generates a coverage multimap from split key to Regions that start with the * split key. * * @return coverage multimap */ public Multimap<byte[], R> calcCoverage() { // This needs to be sorted to force the use of the comparator on the values, // otherwise byte array comparison isn't used Multimap<byte[], R> regions = TreeMultimap.create(BYTES_COMPARATOR, rangeCmp); // march through all splits from the start points for (Entry<byte[], Collection<R>> start : starts.asMap().entrySet()) { byte[] key = start.getKey(); for (R r : start.getValue()) { regions.put(key, r); for (byte[] coveredSplit : splits.subSet(r.getStartKey(), specialEndKey(r))) { regions.put(coveredSplit, r); } } } return regions; }
/** * Bouwt het MetaObject. * @param parentObject het parent meta object * @return het MetaObject */ MetaObject build(final MetaObject parentObject) { final MetaObject gebouwdObject = new MetaObject(); gebouwdObject.parentObject = parentObject; gebouwdObject.objectsleutel = objectsleutel; gebouwdObject.objectElement = objectElement; final Multimap<ObjectElement, MetaObject> tempObjectenMap = HashMultimap.create(); for (final Builder builder : objectBuilderList) { final MetaObject object = builder.build(gebouwdObject); tempObjectenMap.put(object.getObjectElement(), object); } gebouwdObject.elementObjectMap = ImmutableMultimap.copyOf(tempObjectenMap); gebouwdObject.objecten = ImmutableSet.copyOf(tempObjectenMap.values()); final Map<GroepElement, MetaGroep> tempGroepenMap = Maps.newHashMap(); for (final MetaGroep.Builder groepBuilder : groepBuilderList) { final MetaGroep groep = groepBuilder.build(gebouwdObject); tempGroepenMap.put(groep.getGroepElement(), groep); } gebouwdObject.elementGroepMap = ImmutableMap.copyOf(tempGroepenMap); gebouwdObject.groepen = ImmutableSet.copyOf(tempGroepenMap.values()); return gebouwdObject; }
private static RemotePkgInfo findUpdate(@NonNull LocalPkgInfo local, @NonNull Multimap<PkgType, RemotePkgInfo> remotePkgs, @NonNull UpdateResult result) { RemotePkgInfo currUpdatePkg = null; IPkgDesc currUpdateDesc = null; IPkgDesc localDesc = local.getDesc(); for (RemotePkgInfo remote: remotePkgs.get(localDesc.getType())) { IPkgDesc remoteDesc = remote.getDesc(); if ((currUpdateDesc == null && remoteDesc.isUpdateFor(localDesc)) || (currUpdateDesc != null && remoteDesc.isUpdateFor(currUpdateDesc))) { currUpdatePkg = remote; currUpdateDesc = remoteDesc; } } local.setUpdate(currUpdatePkg); if (currUpdatePkg != null) { result.addUpdatedPkgs(local); } return currUpdatePkg; }
/** * Registers all subscriber methods on the given listener object. */ void register(Object listener) { Multimap<Class<?>, Subscriber> listenerMethods = findAllSubscribers(listener); for (Map.Entry<Class<?>, Collection<Subscriber>> entry : listenerMethods.asMap().entrySet()) { Class<?> eventType = entry.getKey(); Collection<Subscriber> eventMethodsInListener = entry.getValue(); CopyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType); if (eventSubscribers == null) { CopyOnWriteArraySet<Subscriber> newSet = new CopyOnWriteArraySet<Subscriber>(); eventSubscribers = MoreObjects.firstNonNull(subscribers.putIfAbsent(eventType, newSet), newSet); } eventSubscribers.addAll(eventMethodsInListener); } }
private void handleMisssingInstancesOnTransaction(final ConfigTransactionClient ta, final ConfigExecution execution) throws DocumentedException { for (Multimap<String, ModuleElementDefinition> modulesToResolved : execution.getModulesDefinition(ta) .values()) { for (Map.Entry<String, ModuleElementDefinition> moduleToResolved : modulesToResolved.entries()) { String moduleName = moduleToResolved.getKey(); ModuleElementDefinition moduleElementDefinition = moduleToResolved.getValue(); EditConfigStrategy strategy = moduleElementDefinition.getEditStrategy(); strategy.executeConfiguration(moduleName, moduleElementDefinition.getInstanceName(), null, ta, execution.getServiceRegistryWrapper(ta)); } } }
/** * A recursive approach to dependency resolution * * @param parentDependency * @param resolvedDependenciesMap */ private void addResolvedDependencyInfo(ResolvedDependencyInfo parentDependency, Multimap<ModuleVersionIdentifier, ResolvedDependencyInfo> resolvedDependenciesMap) { int indent = parentDependency.getIndent(); ModuleVersionIdentifier identifier = parentDependency.getModuleVersionIdentifier(); Collection<ResolvedDependencyInfo> childDependencies = resolvedDependenciesMap.get(identifier); //TODO here for (ResolvedDependencyInfo childDependency : childDependencies) { if (childDependency.getIndent() > indent) { // System.out.println(parentDependency + " indent " + indent + "->" + childDependency // + " indent " + childDependency.getIndent()); parentDependency.getChildren().add(childDependency); if (childDependency.getIndent() <= 1) { addResolvedDependencyInfo(childDependency, resolvedDependenciesMap); } } } }
/** * merges this and other together into a new result object * @param other * @return the resulting merge */ public ScanResult merge(ScanResult other) { final Multimap<String, ChildClassDescriptor> newImpls = HashMultimap.create(); for (Collection<ParentClassDescriptor> impls : asList(implementations, other.implementations)) { for (ParentClassDescriptor c : impls) { newImpls.putAll(c.getName(), c.getChildren()); } } List<ParentClassDescriptor> newImplementations = new ArrayList<>(); for (Entry<String, Collection<ChildClassDescriptor>> entry : newImpls.asMap().entrySet()) { newImplementations.add(new ParentClassDescriptor(entry.getKey(), new ArrayList<>(entry.getValue()))); } return new ScanResult( merge(scannedPackages, other.scannedPackages), merge(scannedClasses, other.scannedClasses), merge(scannedAnnotations, other.scannedAnnotations), merge(annotatedClasses, other.annotatedClasses), newImplementations); }
@Override public void institutionEvent(final InstitutionEvent event) { switch( event.getEventType() ) { case AVAILABLE: Multimap<Long, Institution> schema2inst = event.getChanges(); Set<Long> schemas = schema2inst.keySet(); for( Long schemaId : schemas ) { backgroundIndexers.getUnchecked(schemaId).synchronizeFull(schema2inst.get(schemaId)); } break; default: break; } }
private Intent createIntent(Key key, long mac, NodeId node, Multimap<NodeId, Device> devices) { // choose a random device for which this node is master List<Device> deviceList = devices.get(node).stream().collect(Collectors.toList()); Device device = deviceList.get(RandomUtils.nextInt(deviceList.size())); //FIXME we currently ignore the path length and always use the same device TrafficSelector selector = DefaultTrafficSelector.builder() .matchEthDst(MacAddress.valueOf(mac)).build(); TrafficTreatment treatment = DefaultTrafficTreatment.emptyTreatment(); ConnectPoint ingress = new ConnectPoint(device.id(), PortNumber.portNumber(1)); ConnectPoint egress = new ConnectPoint(device.id(), PortNumber.portNumber(2)); return PointToPointIntent.builder() .appId(appId) .key(key) .selector(selector) .treatment(treatment) .ingressPoint(ingress) .egressPoint(egress) .build(); }
/** * Recursive part of {@link #computeBuildOrderDepthFirst(Map, Multimap, Multimap, Collection)}. If all dependencies * of the given project have already been processed, it is added to the build order. Then, all projects that depend * on the given project are processed recursively. * * @param project * the project to process * @param markedProjects * the marked projects * @param pendencies * maps projects to the projects that depend on them * @param dependencies * maps projects to the projects they depend on * @param result * the build order being computed */ private static void computeBuildOrderDepthFirst(IN4JSProject project, Map<IN4JSProject, MarkedProject> markedProjects, Multimap<IN4JSProject, IN4JSProject> pendencies, Multimap<IN4JSProject, IN4JSProject> dependencies, List<MarkedProject> result) { // once all dependencies of the current project have been processed, we can add it to the build and // process its children. if (dependencies.get(project).isEmpty()) { // The current project is ready to be processed. result.add(markedProjects.get(project)); // Remove this project from the dependencies of all pending projects. for (IN4JSProject dependentProject : pendencies.get(project)) { dependencies.get(dependentProject).remove(project); // Now process the pending project itself. computeBuildOrderDepthFirst(dependentProject, markedProjects, pendencies, dependencies, result); } } }
/** * Sugar for collecting {@link IWorkspace Eclipse workspace} projects that have any direct dependency to any * external projects. Same as {@link #collectExternalProjectDependents()} but does not consider all the available * projects but only those that are given as the argument. * * @param externalProjects * the external projects that has to be considered as a possible dependency of an Eclipse workspace based * project. * @return a map where each entry maps an external project to the workspace projects that depend on it. */ public Map<IProject, Collection<IProject>> collectExternalProjectDependents( final Iterable<? extends IProject> externalProjects) { final Multimap<IProject, IProject> mapping = Multimaps2.newLinkedHashListMultimap(); if (Platform.isRunning()) { final Map<String, IProject> externalsMapping = new HashMap<>(); externalProjects.forEach(p -> externalsMapping.put(p.getName(), p)); asList(getWorkspace().getRoot().getProjects()).forEach(p -> { getDirectExternalDependencyIds(p).forEach(eID -> { IProject externalDependency = externalsMapping.get(eID); if (externalDependency != null) { mapping.put(externalDependency, p); } }); }); } return mapping.asMap(); }
/** * Create SampleResult in XML format. * @param context * @param isError * @param statusCode * @param statusMessage * @param columnsForEachSqlStatement * @param valuesForEachColumn * @param includeQueryResults * @return */ private static SampleResult newResult(final Context context, final boolean isError, final String statusCode, final String statusMessage, final Multimap<String, String> columnsForEachSqlStatement, final Multimap<String, String> valuesForEachColumn, boolean includeQueryResults, final Optional<Long> duration) { final SampleResult result = new SampleResult(); result.setStatusCode(statusCode); result.setError(isError); if(duration.isPresent()) result.setDuration(duration.get()); context.getLogger().debug("SQL Action execution finished with status code: " + statusCode + " (" + statusMessage + ")"); final State state = isError ? State.ERROR : State.OK; try { result.setResponseContent(generateXMLOutput(state, statusMessage, columnsForEachSqlStatement, valuesForEachColumn, includeQueryResults)); } catch (TransformerException e) { result.setError(true); context.getLogger().error("An error occurred while creating XML output: " + e.toString()); } return result; }
private Multimap<Long, TimeDomains> loadTimeDomains(String filename) { Multimap<Long, TimeDomains> times = TreeMultimap.create(); File file = new File(filename); if (!file.exists()) { log.info("File not found : {}", file.getAbsolutePath()); return times; } log.info("Reading TD {}", file); processDbf(file, row -> { TimeDomains restriction = new TimeDomains(((Double)row[0]).longValue(), new String((byte[]) row[3]).trim()); times.put(restriction.getId(), restriction); }); log.info("Loaded {} times domains", times.size()); return times; }
/** * Construct a sparse tensor with indices and values * * @param dims * dimensions of a tensor * @param nds * n-dimensional keys * @param vals * entry values */ @SuppressWarnings("unchecked") public SparseTensor(int[] dims, List<Integer>[] nds, List<Double> vals) { if (dims.length < 3) throw new Error("The dimension of a tensor cannot be smaller than 3!"); numDimensions = dims.length; dimensions = new int[numDimensions]; ndKeys = (List<Integer>[]) new List<?>[numDimensions]; keyIndices = (Multimap<Integer, Integer>[]) new Multimap<?, ?>[numDimensions]; for (int d = 0; d < numDimensions; d++) { dimensions[d] = dims[d]; ndKeys[d] = nds == null ? new ArrayList<Integer>() : new ArrayList<Integer>(nds[d]); keyIndices[d] = HashMultimap.create(); } values = vals == null ? new ArrayList<Double>() : new ArrayList<>(vals); indexedDimensions = new ArrayList<>(numDimensions); }
/** * Assemble watch keys for the given appId, cluster, namespaces, dataCenter combination * * @return a multimap with namespace as the key and watch keys as the value */ public Multimap<String, String> assembleAllWatchKeys(String appId, String clusterName, Set<String> namespaces, String dataCenter) { Multimap<String, String> watchedKeysMap = assembleWatchKeys(appId, clusterName, namespaces, dataCenter); //Every app has an 'application' namespace if (!(namespaces.size() == 1 && namespaces.contains(ConfigConsts.NAMESPACE_APPLICATION))) { Set<String> namespacesBelongToAppId = namespacesBelongToAppId(appId, namespaces); Set<String> publicNamespaces = Sets.difference(namespaces, namespacesBelongToAppId); //Listen on more namespaces if it's a public namespace if (!publicNamespaces.isEmpty()) { watchedKeysMap .putAll(findPublicConfigWatchKeys(appId, clusterName, publicNamespaces, dataCenter)); } } return watchedKeysMap; }
/** * Get a unique column label for variables and remove invalid XML characters. * @param multimap * @param label * @return unique label */ static String uniqueColumnName(Multimap<String, String> multimap, String label) { final String columnLabel = getValidXmlName(label); if (!multimap.values().contains(columnLabel)) { return columnLabel; } int index = columnLabel.length() - 1; while (index >= 0 && Character.isDigit(columnLabel.charAt(index))) { index--; } String base = columnLabel; if (index >= 0 && columnLabel.charAt(index) == '_') { base = columnLabel.substring(0, index); } int j = 1; String newLabel = base + "_" + j; while (multimap.values().contains(newLabel)) { j++; newLabel = base + "_" + j; } return newLabel; }
private EventArgScoringAlignment(final Symbol docID, final ArgumentOutput argumentOutput, final AnswerKey answerKey, final Iterable<EquivClassType> truePositiveECs, final Iterable<EquivClassType> falsePositiveECs, final Iterable<EquivClassType> falseNegativeECs, final Iterable<EquivClassType> unassessed, final Multimap<EquivClassType, AssessedResponse> ecsToAnswerKey, final Multimap<EquivClassType, Response> ecsToSystem) { this.docID = checkNotNull(docID); this.argumentOutput = checkNotNull(argumentOutput); this.answerKey = checkNotNull(answerKey); this.truePositiveECs = ImmutableSet.copyOf(truePositiveECs); this.falsePositiveECs = ImmutableSet.copyOf(falsePositiveECs); this.falseNegativeECs = ImmutableSet.copyOf(falseNegativeECs); this.unassessed = ImmutableSet.copyOf(unassessed); this.ecsToAnswerKey = ImmutableSetMultimap.copyOf(ecsToAnswerKey); this.ecsToSystem = ImmutableSetMultimap.copyOf(ecsToSystem); }
public static void loadData(ASMDataTable data) { FMLLog.fine("Loading @Config anotation data"); for (ASMData target : data.getAll(Config.class.getName())) { String modid = (String)target.getAnnotationInfo().get("modid"); Multimap<Config.Type, ASMData> map = asm_data.get(modid); if (map == null) { map = ArrayListMultimap.create(); asm_data.put(modid, map); } EnumHolder tholder = (EnumHolder)target.getAnnotationInfo().get("type"); Config.Type type = tholder == null ? Config.Type.INSTANCE : Config.Type.valueOf(tholder.getValue()); map.put(type, target); } }
private ResponseLinking linkResponses(final Symbol docId, final Iterable<Response> responses) { final Predicate<Response> HasRelevantRealis = compose(in(realisesWhichMustBeAligned), ResponseFunctions.realis()); final ImmutableSet<Response> systemResponsesAlignedRealis = FluentIterable.from(responses).filter(HasRelevantRealis).toSet(); final Multimap<Symbol, Response> responsesByEventType = Multimaps.index(systemResponsesAlignedRealis, ResponseFunctions.type()); final ImmutableSet.Builder<ResponseSet> ret = ImmutableSet.builder(); for (final Collection<Response> responseSet : responsesByEventType.asMap().values()) { ret.add(ResponseSet.from(responseSet)); } return ResponseLinking.builder().docID(docId).addAllResponseSets(ret.build()).build(); }
/** * Create permissions, note that permissionType + targetId should be unique */ @Transactional public Set<Permission> createPermissions(Set<Permission> permissions) { Multimap<String, String> targetIdPermissionTypes = HashMultimap.create(); for (Permission permission : permissions) { targetIdPermissionTypes.put(permission.getTargetId(), permission.getPermissionType()); } for (String targetId : targetIdPermissionTypes.keySet()) { Collection<String> permissionTypes = targetIdPermissionTypes.get(targetId); List<Permission> current = permissionRepository.findByPermissionTypeInAndTargetId(permissionTypes, targetId); Preconditions.checkState(CollectionUtils.isEmpty(current), "Permission with permissionType %s targetId %s already exists!", permissionTypes, targetId); } Iterable<Permission> results = permissionRepository.save(permissions); return FluentIterable.from(results).toSet(); }
@Override public void execute() { if( !httpService.canAccessInternet() ) { // Nothing we can do... return; } Multimap<Long, Institution> schemaToInsts = institutionService.getAvailableMap(); for( final Map.Entry<Long, Collection<Institution>> entry : schemaToInsts.asMap().entrySet() ) { schemaDataSourceService.executeWithSchema(entry.getKey(), new Callable<Object>() { @Override public Object call() throws Exception { executeForInstitutions(entry.getValue()); return null; } }); } }
public SetMultimap<String,ASMData> getAnnotationsFor(ModContainer container) { if (containerAnnotationData == null) { ImmutableMap.Builder<ModContainer, SetMultimap<String, ASMData>> mapBuilder = ImmutableMap.builder(); for (ModContainer cont : containers) { Multimap<String, ASMData> values = Multimaps.filterValues(globalAnnotationData, new ModContainerPredicate(cont)); mapBuilder.put(cont, ImmutableSetMultimap.copyOf(values)); } containerAnnotationData = mapBuilder.build(); } return containerAnnotationData.get(container); }
public static DiagMatrix eye(int n) { Table<Integer, Integer, Double> vals = HashBasedTable.create(); Multimap<Integer, Integer> colMap = HashMultimap.create(); for (int i = 0; i < n; i++) { vals.put(i, i, 1.0); colMap.put(i, i); } return new DiagMatrix(n, n, vals, colMap); }
/** * Replace a modifier in the {@link Multimap} with a copy that's had {@code multiplier} applied to its value. * * @param modifierMultimap The MultiMap * @param attribute The attribute being modified * @param id The ID of the modifier * @param multiplier The multiplier to apply */ private void replaceModifier(Multimap<String, AttributeModifier> modifierMultimap, IAttribute attribute, UUID id, double multiplier) { // Get the modifiers for the specified attribute final Collection<AttributeModifier> modifiers = modifierMultimap.get(attribute.getName()); // Find the modifier with the specified ID, if any final Optional<AttributeModifier> modifierOptional = modifiers.stream().filter(attributeModifier -> attributeModifier.getID().equals(id)).findFirst(); if (modifierOptional.isPresent()) // If it exists, { final AttributeModifier modifier = modifierOptional.get(); modifiers.remove(modifier); // Remove it modifiers.add(new AttributeModifier(modifier.getID(), modifier.getName(), modifier.getAmount() * multiplier, modifier.getOperation())); // Add the new modifier } }
@Test public void testGlob() { Multimap<String, String> pattern2Candidates = generate(); for (Map.Entry<String, Collection<String>> pattern2CandidatesMap : pattern2Candidates.asMap().entrySet()) { String glob = pattern2CandidatesMap.getKey(); Pattern pattern = createPattern(glob); if (pattern == null) { System.out.println("Wrong pattern " + glob); continue; } for (String node : pattern2CandidatesMap.getValue()) { System.out.println(String.format("%40s\t%40s\t%s", glob, node, pattern.matcher(node).matches())); } } }
@Override protected UnmodifiableAttachments loadAttachments() { Multimap<Item, Attachment> attachmentsForItems = listSettings.getAttribute(KEY_ALLATTACHMENTS); if( attachmentsForItems == null ) { List<ItemListEntry> entries2 = (List<ItemListEntry>) listSettings.getEntries(); attachmentsForItems = itemService .getAttachmentsForItems(AbstractItemlikeListEntry.<Item>getItems(entries2)); listSettings.setAttribute(KEY_ALLATTACHMENTS, attachmentsForItems); } return new UnmodifiableAttachments(Lists.<IAttachment>newArrayList(attachmentsForItems.get(getItem()))); }
public Multimap<String, AttributeModifier> getItemAttributeModifiers(EntityEquipmentSlot equipmentSlot) { Multimap<String, AttributeModifier> multimap = super.getItemAttributeModifiers(equipmentSlot); if (equipmentSlot == EntityEquipmentSlot.MAINHAND) { multimap.put(SharedMonsterAttributes.ATTACK_DAMAGE.getAttributeUnlocalizedName(), new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Weapon modifier", 0.0D, 0)); multimap.put(SharedMonsterAttributes.ATTACK_SPEED.getAttributeUnlocalizedName(), new AttributeModifier(ATTACK_SPEED_MODIFIER, "Weapon modifier", (double)(this.speed - 4.0F), 0)); } return multimap; }
@Override protected Multimap<State, State> getStateTransitions() { Multimap<State, State> result = MultimapBuilder.enumKeys(State.class).arrayListValues().build(); result.put(State.UNINITIALISED, State.NEW); result.put(State.UNINITIALISED, State.READY); result.put(State.NEW, State.SAVE_STATE_IN_WALLET); result.put(State.SAVE_STATE_IN_WALLET, State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER); result.put(State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER, State.READY); result.put(State.READY, State.EXPIRED); result.put(State.READY, State.CLOSED); return result; }
/** * If you have an article-supporting language, it makes sense to keep an enum map around. */ public static <A extends AdjectiveForm> EnumMap<LanguageArticle,ModifierFormMap<A>> getArticleSpecificMap(Collection<? extends A> forms) { Multimap<LanguageArticle,A> mm = ArrayListMultimap.create(); for (A form : forms) { mm.put(form.getArticle(), form); } EnumMap<LanguageArticle,ModifierFormMap<A>> result = new EnumMap<LanguageArticle,ModifierFormMap<A>>(LanguageArticle.class); for (LanguageArticle article : LanguageArticle.values()) { result.put(article, new ModifierFormMap<A>(mm.get(article))); } return result; }
/** * A simplified implementation of matrixSearch() that only works on a single * field, and currently only returns the count per term. It could easily be * extended to return a list of ItemIds per term, it simply wasn't necessary * when I was writing it! * <p> * This simplified implementation was written to overcome the memory * pressures that matrixSearch() creates when you have over half a million * terms for a field. MatrixSearch() creates *many* BitSets that it holds on * to to reuse as it recurse through a list of fields. Since we only care * about a single field in this implementation, we can avoid generating and * holding onto BitSets. */ public Multimap<String, Pair<String, Integer>> facetCount(@Nullable final Search searchreq, final Collection<String> fields) { return search(new Searcher<Multimap<String, Pair<String, Integer>>>() { @Override public Multimap<String, Pair<String, Integer>> search(IndexSearcher searcher) throws IOException { final IndexReader reader = searcher.getIndexReader(); final OpenBitSet filteredBits = searchRequestToBitSet(searchreq, searcher, reader); final Multimap<String, Pair<String, Integer>> rv = ArrayListMultimap.create(); for( String field : fields ) { for( Term term : new XPathFieldIterator(reader, field, "") ) { int count = 0; TermDocs docs = reader.termDocs(term); while( docs.next() ) { if( filteredBits.get(docs.doc()) ) { count++; } } docs.close(); if( count > 0 ) { rv.put(field, new Pair<String, Integer>(term.text(), count)); } } } return rv; } }); }
public Element toXml(Set<ObjectName> instancesToMap, Set<ObjectName> configBeans, Document document, final EnumResolver enumResolver) { Element root = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY, Optional.<String>absent()); Element modulesElement = XmlUtil.createElement(document, XmlMappingConstants.MODULES_KEY, Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG)); root.appendChild(modulesElement); Map<String, Multimap<String, ObjectName>> moduleToRuntimeInstance = mapInstancesToModules(instancesToMap); Map<String, Map<String, Collection<ObjectName>>> moduleToConfigInstance = Config.getMappedInstances(configBeans, moduleConfigs); for (String localNamespace : moduleConfigs.keySet()) { Map<String, Collection<ObjectName>> instanceToMbe = moduleToConfigInstance.get(localNamespace); for (String moduleName : moduleConfigs.get(localNamespace).keySet()) { Multimap<String, ObjectName> instanceToRbe = moduleToRuntimeInstance.get(moduleName); for (ObjectName instanceON : instanceToMbe.get(moduleName)) { String instanceName = ObjectNameUtil.getInstanceName(instanceON); Element runtimeXml; ModuleConfig moduleConfig = moduleConfigs.get(localNamespace).get(moduleName); if (instanceToRbe == null || !instanceToRbe.containsKey(instanceName)) { runtimeXml = moduleConfig.toXml(instanceON, document, localNamespace, enumResolver); } else { ModuleRuntime moduleRuntime = moduleRuntimes.get(localNamespace).get(moduleName); runtimeXml = moduleRuntime.toXml(localNamespace, instanceToRbe.get(instanceName), document, moduleConfig, instanceON, enumResolver); } modulesElement.appendChild(runtimeXml); } } } return root; }
private static List<NlpFocus<DepNode, DepTree>> filterPolysemous( List<NlpFocus<DepNode, DepTree>> data) { Multimap<String, String> labelMap = HashMultimap.create(); for (NlpFocus<DepNode, DepTree> instance : data) { String predicate = instance.focus().feature(FeatureType.Predicate); labelMap.put(predicate, instance.feature(FeatureType.Gold)); } return data.stream() .filter(instance -> labelMap.get(instance.focus().feature(FeatureType.Predicate)).size() > 1) .collect(Collectors.toList()); }
private static Multimap<Class<? extends Annotation>, Class<? extends Annotation>> collectAnnotationOverrides(Iterable<PropertyAnnotationHandler> allAnnotationHandlers) { ImmutableSetMultimap.Builder<Class<? extends Annotation>, Class<? extends Annotation>> builder = ImmutableSetMultimap.builder(); for (PropertyAnnotationHandler handler : allAnnotationHandlers) { if (handler instanceof OverridingPropertyAnnotationHandler) { builder.put(((OverridingPropertyAnnotationHandler) handler).getOverriddenAnnotationType(), handler.getAnnotationType()); } } return builder.build(); }
@Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { for (Entry<? extends K, ? extends V> e : multimap.entries()) { value2key.put(e.getValue(), e.getKey()); } return key2Value.putAll(multimap); }
public void run() { File file = new File(filename); Stopwatch stopwatch = Stopwatch.createStarted(); Multimap<Long, Long> wayByRelations = ArrayListMultimap.create(); Multimap<Long, Integer> borderNodeTargets = ArrayListMultimap.create(); firstPass(file, wayByRelations, borderNodeTargets); finalPass(wayByRelations, borderNodeTargets, file); kml.close(); log.info("time: {}s", stopwatch.elapsed(SECONDS)); }
private void add31Migrators(Multimap<String, String> xmlMigs) { xmlMigs.put("3.1", "com.tle.core.institution.migration.RemoveDeprecatedFedSearches"); xmlMigs.put("3.1", "com.tle.core.institution.migration.TleUserSuspendedRemover"); xmlMigs.put("3.1", "com.tle.core.institution.migration.SetEmailTemplateUuidsChange"); xmlMigs.put("3.1", "com.tle.core.institution.migration.RemoveDeprecatedItemDefinitionParts"); xmlMigs.put("3.1", "com.tle.core.institution.migration.LanguageBundleMigration"); }
/** * Re-ordering entries of a tensor into a matrix * * @param n * mode or dimension * @return an unfolded or flatten matrix */ public SparseMatrix matricization(int n) { int numRows = dimensions[n]; int numCols = 1; for (int d = 0; d < numDimensions; d++) { if (d != n) numCols *= dimensions[d]; } Table<Integer, Integer, Double> dataTable = HashBasedTable.create(); Multimap<Integer, Integer> colMap = HashMultimap.create(); for (TensorEntry te : this) { int[] keys = te.keys(); int i = keys[n]; int j = 0; for (int k = 0; k < numDimensions; k++) { if (k == n) continue; int ik = keys[k]; int jk = 1; for (int m = 0; m < k; m++) { if (m == n) continue; jk *= dimensions[m]; } j += ik * jk; } dataTable.put(i, j, te.get()); colMap.put(j, i); } return new SparseMatrix(numRows, numCols, dataTable, colMap); }