List of usage examples for com.google.common.collect Multimap put
boolean put(@Nullable K key, @Nullable V value);
From source file:org.apache.gobblin.data.management.copy.publisher.CopyDataPublisher.java
/** * Create a {@link Multimap} that maps a {@link CopyableDataset} to all {@link WorkUnitState}s that belong to this * {@link CopyableDataset}. This mapping is used to set WorkingState of all {@link WorkUnitState}s to * {@link WorkUnitState.WorkingState#COMMITTED} after a {@link CopyableDataset} is successfully published. *///from w ww . j a v a 2 s.co m private static Multimap<CopyEntity.DatasetAndPartition, WorkUnitState> groupByFileSet( Collection<? extends WorkUnitState> states) { Multimap<CopyEntity.DatasetAndPartition, WorkUnitState> datasetRoots = ArrayListMultimap.create(); for (WorkUnitState workUnitState : states) { CopyEntity file = CopySource.deserializeCopyEntity(workUnitState); CopyEntity.DatasetAndPartition datasetAndPartition = file.getDatasetAndPartition(CopyableDatasetMetadata .deserialize(workUnitState.getProp(CopySource.SERIALIZED_COPYABLE_DATASET))); datasetRoots.put(datasetAndPartition, workUnitState); } return datasetRoots; }
From source file:org.apache.beam.sdk.io.FileSystems.java
@VisibleForTesting static Map<String, FileSystem> verifySchemesAreUnique(PipelineOptions options, Set<FileSystemRegistrar> registrars) { Multimap<String, FileSystem> fileSystemsBySchemes = TreeMultimap.create(Ordering.<String>natural(), Ordering.arbitrary());/*from ww w. j a v a2 s. c o m*/ for (FileSystemRegistrar registrar : registrars) { for (FileSystem fileSystem : registrar.fromOptions(options)) { fileSystemsBySchemes.put(fileSystem.getScheme(), fileSystem); } } for (Entry<String, Collection<FileSystem>> entry : fileSystemsBySchemes.asMap().entrySet()) { if (entry.getValue().size() > 1) { String conflictingFileSystems = Joiner.on(", ") .join(FluentIterable.from(entry.getValue()).transform(new Function<FileSystem, String>() { @Override public String apply(@Nonnull FileSystem input) { return input.getClass().getName(); } }).toSortedList(Ordering.<String>natural())); throw new IllegalStateException(String.format("Scheme: [%s] has conflicting filesystems: [%s]", entry.getKey(), conflictingFileSystems)); } } ImmutableMap.Builder<String, FileSystem> schemeToFileSystem = ImmutableMap.builder(); for (Entry<String, FileSystem> entry : fileSystemsBySchemes.entries()) { schemeToFileSystem.put(entry.getKey(), entry.getValue()); } return schemeToFileSystem.build(); }
From source file:org.jboss.errai.otec.client.atomizer.Atomizer.java
public static AtomizerSession syncWidgetWith(final OTEngine engine, final OTEntity entity, final ValueBoxBase widget) { logger.info("NEW ATOMIZER SESSION (engine:" + engine.getId() + ", widget=" + widget + ")"); final Multimap<Object, HandlerRegistration> HANDLER_REGISTRATION_MAP = HashMultimap.create(); final EntityChangeStreamImpl entityChangeStream = new EntityChangeStreamImpl(engine, entity); final EntityStreamRegistration entityStreamRegistration = engine.getPeerState() .addEntityStream(entityChangeStream); widget.setValue(entity.getState().get()); HANDLER_REGISTRATION_MAP.put(widget, widget.addKeyDownHandler(new KeyDownHandler() { @Override//w w w . java2 s. c om public void onKeyDown(final KeyDownEvent event) { if (shouldIgnoreKeyPress(event)) { return; } if (widget.getSelectedText().length() > 0) { stopEvents(); entityChangeStream.notifyDelete(widget.getCursorPos(), widget.getSelectedText()); startEvents(); } else if (event.getNativeKeyCode() == KeyCodes.KEY_BACKSPACE) { stopEvents(); final int index = widget.getCursorPos() - 1; entityChangeStream.notifyDelete(index, " "); startEvents(); } else if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { stopEvents(); entityChangeStream.notifyInsert(widget.getCursorPos(), "\n"); startEvents(); } } })); HANDLER_REGISTRATION_MAP.put(widget, widget.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(final KeyPressEvent event) { if (event.getUnicodeCharCode() != 13 && event.getUnicodeCharCode() != 0) { stopEvents(); entityChangeStream.notifyInsert(widget.getCursorPos(), String.valueOf(event.getCharCode())); startEvents(); } } })); DOM.setEventListener(widget.getElement(), new EventListener() { @Override public void onBrowserEvent(Event event) { if (event.getTypeInt() == Event.ONPASTE) { final String before = (String) entity.getState().get(); new Timer() { @Override public void run() { final String after = (String) widget.getValue(); final DiffUtil.Delta diff = DiffUtil.diff(before, after); stopEvents(); entityChangeStream.notifyInsert(diff.getCursor(), diff.getDeltaText()); startEvents(); } }.schedule(1); } widget.onBrowserEvent(event); } }); attachCutHandler(widget.getElement(), new Runnable() { @Override public void run() { stopEvents(); entityChangeStream.notifyDelete(widget.getCursorPos(), widget.getSelectedText()); startEvents(); } }); attachTextDragHandler(widget.getElement(), new Runnable() { @Override public void run() { stopEvents(); entityChangeStream.notifyDelete(widget.getCursorPos(), widget.getSelectedText()); entityChangeStream.flush(); startEvents(); } }, new Runnable() { @Override public void run() { final String old = (String) entity.getState().get(); new Timer() { @Override public void run() { final DiffUtil.Delta diff = DiffUtil.diff(old, (String) widget.getValue()); if (diff.getDeltaText().length() > 0) { stopEvents(); entityChangeStream.notifyInsert(diff.getCursor(), diff.getDeltaText()); startEvents(); } } }.schedule(1); } }); final ListenerRegistration listenerRegistration = entity.getState() .addStateChangeListener(new StateChangeListener() { @Override public int getCursorPos() { return widget.getCursorPos(); } @Override public void onStateChange(final int newCursorPos, final Object newValue) { if (NO_PROPAGATE_STATE_CHANGE) { return; } widget.setValue(newValue, false); widget.setCursorPos(newCursorPos); } }); DOM.sinkEvents(widget.getElement(), DOM.getEventsSunk(widget.getElement()) | Event.ONPASTE); final Timer timer = new Timer() { @Override public void run() { entityChangeStream.flush(); } }; timer.scheduleRepeating(500); return new AtomizerSession() { @Override public void end() { entityChangeStream.close(); timer.cancel(); logger.info("END ATOMIZER SESSION"); entityStreamRegistration.remove(); listenerRegistration.remove(); final Collection<HandlerRegistration> values = HANDLER_REGISTRATION_MAP.values(); for (final HandlerRegistration value : values) { value.removeHandler(); } } }; }
From source file:moa2014.MOAH42014.java
public static int principal(int[][] matrizatual, double c1, double c2, double c3) { long startTime = System.currentTimeMillis(); Multimap<Double, String> open_list = TreeMultimap.create(); HashMap<String, Estado> processados = new HashMap(); double h1 = c1 * h1(matrizatual); double h2 = c2 * h2(matrizatual); double h3 = c3 * h3(matrizatual); double difmatrizatual = h1 + h2 + h3; String stringmatriz = transformaMatrizString(matrizatual); open_list.put(difmatrizatual, stringmatriz); Estado estadoatual = new Estado(matrizatual, 0); processados.put(stringmatriz, estadoatual); int arvoresgeradas = 0; int arvoresprocessadas = 0; while (!open_list.isEmpty()) { Iterator iterator = open_list.keySet().iterator(); Double key = (Double) iterator.next(); String matrizatualx1 = open_list.asMap().get(key).iterator().next(); Estado estadomenor = processados.get(matrizatualx1); int altura = estadomenor.getCusto(); //LOCALIZA O ZERO int[] zerot = localizazero(estadomenor.getMatriz()); int x = zerot[0]; int y = zerot[1]; int x0 = x - 1; int x1 = x + 1; int y0 = y - 1; int y1 = y + 1; int difmatrizatualx = h1(estadomenor.getMatriz()); if (difmatrizatualx == 0) { long endTime = System.currentTimeMillis(); System.out.println("---------------------------------------"); System.out.println("Arvores Geradas: " + arvoresgeradas); System.out.println("Arvores Processadas: " + arvoresprocessadas); System.out.println("Quantidade de Movimentos: " + estadomenor.getCusto()); System.out.println("Tempo de processamento " + (endTime - startTime) + " ms"); System.out.println("---------------------------------------\n\n"); return 0; }/*from w ww.j av a 2 s .c o m*/ arvoresprocessadas++; int[][] matrizatualx = estadomenor.getMatriz(); if (x0 >= 0) { int[][] matriz; matriz = copyarray(matrizatualx); matriz[x][y] = matrizatualx[x0][y]; matriz[x0][y] = matrizatualx[x][y]; String stringmatriz1 = transformaMatrizString(matriz); if (!(processados.containsKey(stringmatriz1))) { arvoresgeradas++; h1 = c1 * h1(matriz); h2 = c2 * h2(matriz); h3 = c3 * h3(matriz); double diferencamatriz = h1 + h2 + h3; double custototal = diferencamatriz + altura + 1; Estado estadonovo = new Estado(matriz, altura + 1); open_list.put(custototal, stringmatriz1); processados.put(stringmatriz1, estadonovo); } } if (x1 <= 3) { int[][] matriz; matriz = copyarray(matrizatualx); matriz[x][y] = matrizatualx[x1][y]; matriz[x1][y] = matrizatualx[x][y]; String stringmatriz2 = transformaMatrizString(matriz); if (!(processados.containsKey(stringmatriz2))) { arvoresgeradas++; h1 = c1 * h1(matriz); h2 = c2 * h2(matriz); h3 = c3 * h3(matriz); double diferencamatriz = h1 + h2 + h3; double custototal = diferencamatriz + altura + 1; Estado estadonovo = new Estado(matriz, altura + 1); open_list.put(custototal, stringmatriz2); processados.put(stringmatriz2, estadonovo); } } if (y0 >= 0) { int[][] matriz; matriz = copyarray(matrizatualx); matriz[x][y] = matrizatualx[x][y0]; matriz[x][y0] = matrizatualx[x][y]; String stringmatriz3 = transformaMatrizString(matriz); if (!(processados.containsKey(stringmatriz3))) { arvoresgeradas++; h1 = c1 * h1(matriz); h2 = c2 * h2(matriz); h3 = c3 * h3(matriz); double diferencamatriz = h1 + h2 + h3; double custototal = diferencamatriz + altura + 1; Estado estadonovo = new Estado(matriz, altura + 1); open_list.put(custototal, stringmatriz3); processados.put(stringmatriz3, estadonovo); } } if (y1 <= 3) { int[][] matriz; matriz = copyarray(matrizatualx); matriz[x][y] = matrizatualx[x][y1]; matriz[x][y1] = matrizatualx[x][y]; String stringmatriz4 = transformaMatrizString(matriz); if (!(processados.containsKey(stringmatriz4))) { arvoresgeradas++; h1 = c1 * h1(matriz); h2 = c2 * h2(matriz); h3 = c3 * h3(matriz); double diferencamatriz = h1 + h2 + h3; double custototal = diferencamatriz + altura + 1; Estado estadonovo = new Estado(matriz, altura + 1); open_list.put(custototal, stringmatriz4); processados.put(stringmatriz4, estadonovo); } } open_list.remove(key, matrizatualx1); } return 0; }
From source file:org.apache.bigtop.itest.hbase.system.Scanner.java
public static int doScan(HTable table, int val) throws IOException, InterruptedException { Scan s = new Scan(); byte[] start = {}; byte[] stop = {}; byte[] value = Bytes.toBytes(String.format("%010d", val)); s.setStartRow(start);//from w ww .j a va 2 s . c om s.setStopRow(stop); SingleColumnValueFilter filter = new SingleColumnValueFilter(Bytes.toBytes("f1"), Bytes.toBytes("qual"), CompareOp.EQUAL, value); s.setFilter(filter); // Keep track of gathered elements. Multimap<String, String> mm = ArrayListMultimap.create(); // Counts int cnt = 0; long i = 0; ResultScanner rs = table.getScanner(s); for (Result r : rs) { if (r.getRow() == null) { continue; } NavigableMap<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> columnFamilyMap = r.getMap(); // Output time to show if flush related. String k = Bytes.toStringBinary(r.getRow()); if (mm.get(k).size() >= 1) { System.out.println("Duplicate rowkey " + k); LOG.error("Duplicate rowkey " + k); } mm.put(Bytes.toStringBinary(r.getRow()), i + ": " + r); cnt++; i++; } System.out.println("scan items counted: " + cnt + " for scan " + s.toString() + " with filter f1:qual == " + Bytes.toString(value)); // Print out dupes. int dupes = 0; for (Entry<String, Collection<String>> e : mm.asMap().entrySet()) { if (e.getValue().size() > 1) { dupes++; System.out.print("Row " + e.getKey() + " had time stamps: "); String[] tss = e.getValue().toArray(new String[0]); System.out.println(Arrays.toString(tss)); } } return dupes; }
From source file:com.android.tools.idea.templates.GradleFilePsiMerger.java
/** * Looks for statements adding dependencies to different configurations (which look like 'configurationName "dependencyCoordinate"') * and tries to parse them into Gradle coordinates. If successful, adds the new coordinate to the map and removes the corresponding * PsiElement from the tree./*from w ww . j a v a2s . c o m*/ * * @return true if new items were added to the map */ private static boolean pullDependenciesIntoMap(@NotNull PsiElement root, @NotNull Map<String, Multimap<String, GradleCoordinate>> allConfigurations, @Nullable List<String> unparsedDependencies) { boolean wasMapUpdated = false; for (PsiElement existingElem : root.getChildren()) { if (existingElem instanceof GrCall) { PsiElement reference = existingElem.getFirstChild(); if (reference instanceof GrReferenceExpression) { final String configurationName = reference.getText(); boolean parsed = false; GrCall call = (GrCall) existingElem; GrArgumentList arguments = call.getArgumentList(); // Don't try merging dependencies if one of them has a closure block attached. if (arguments != null && call.getClosureArguments().length == 0) { GrExpression[] expressionArguments = arguments.getExpressionArguments(); if (expressionArguments.length == 1 && expressionArguments[0] instanceof GrLiteral) { Object value = ((GrLiteral) expressionArguments[0]).getValue(); if (value instanceof String) { String coordinateText = (String) value; GradleCoordinate coordinate = GradleCoordinate .parseCoordinateString(coordinateText); if (coordinate != null) { parsed = true; Multimap<String, GradleCoordinate> map = allConfigurations .get(configurationName); if (map == null) { map = LinkedListMultimap.create(); allConfigurations.put(configurationName, map); } if (!map.get(coordinate.getId()).contains(coordinate)) { map.put(coordinate.getId(), coordinate); existingElem.delete(); wasMapUpdated = true; } } } } if (!parsed && unparsedDependencies != null) { unparsedDependencies.add(existingElem.getText()); } } } } } return wasMapUpdated; }
From source file:com.liveramp.hank.storage.cueball.Cueball.java
public static DiskPartitionAssignment getDataDirectoryAssignments(DataDirectoriesConfigurator configurator, Collection<Integer> partitionNumbers) { ArrayList<String> sortedDataDirectories = new ArrayList<String>(configurator.getDataDirectories()); Collections.sort(sortedDataDirectories); LinkedList<Integer> sortedPartitions = new LinkedList<>(partitionNumbers); Collections.sort(sortedPartitions); // TODO we can make this dynamic based on disk size, but not urgent double numPartitionsPerDisk = (double) partitionNumbers.size() / sortedDataDirectories.size(); Multimap<String, Integer> partitionsPerDisk = HashMultimap.create(); for (String dataDirectory : sortedDataDirectories) { int numToAssign = (int) Math.ceil(numPartitionsPerDisk * (partitionsPerDisk.keySet().size() + 1)) - partitionsPerDisk.values().size(); for (int i = 0; i < numToAssign && !sortedPartitions.isEmpty(); i++) { partitionsPerDisk.put(dataDirectory, sortedPartitions.pop()); }//from www .j av a 2s. c o m } Map<Integer, String> inverse = Maps.newHashMap(); for (Map.Entry<String, Integer> entry : partitionsPerDisk.entries()) { inverse.put(entry.getValue(), entry.getKey()); } return new DiskPartitionAssignment(inverse); }
From source file:com.googlecode.blaisemath.graph.GraphUtils.java
/** * Generates connected components from an adjacency map. * @param <V> graph node type//from w ww. j a va 2 s. c om * @param adj an adjacency map * @return set of components, as a set of sets */ public static <V> Collection<Set<V>> components(Table<V, V, ?> adj) { Multimap<V, V> multimap = LinkedHashMultimap.create(); for (Cell<V, V, ?> cell : adj.cellSet()) { multimap.put(cell.getRowKey(), cell.getColumnKey()); } return components(multimap); }
From source file:com.foundationdb.util.Strings.java
public static List<String> stringAndSort(Map<?, ?> inputs) { // step 1: get the key-value pairs into a multimap. We need a multimap because multiple keys may have the // same toString. For instance, { 1 : "int", 1L : "long" } would become a multimap { "1" : ["int", "long"] } Multimap<String, String> multiMap = ArrayListMultimap.create(); for (Map.Entry<?, ?> inputEntry : inputs.entrySet()) { String keyString = stringAndSort(inputEntry.getKey()); String valueString = stringAndSort(inputEntry.getValue()); multiMap.put(keyString, valueString); }//ww w .j a va2s . c om // step 2: Flatten the multimap into a Map<String,String>, sorting by keys as you go. Map<String, String> sortedAndFlattened = new TreeMap<>(); for (Entry<String, Collection<String>> multiMapEntry : multiMap.asMap().entrySet()) { String keyString = multiMapEntry.getKey(); String valueString = stringAndSort(multiMapEntry.getValue()).toString(); String duplicate = sortedAndFlattened.put(keyString, valueString); assert duplicate == null : duplicate; } // step 3: Flatten the map into a List<String> List<String> results = new ArrayList<>(inputs.size()); for (Entry<String, String> entry : sortedAndFlattened.entrySet()) { results.add(entry.toString()); } return results; }
From source file:org.opentripplanner.routing.edgetype.TripPattern.java
/** * Patterns do not have unique IDs in GTFS, so we make some by concatenating agency id, route id, and an integer. * We impose our assumption that all trips in the same pattern are on the same route. * This only works if the Collection of TripPattern includes every TripPattern for the agency. *//*from ww w. j av a 2 s. c om*/ public static void generateUniqueIds(Collection<TripPattern> tripPatterns) { Multimap<Route, TripPattern> patternsForRoute = HashMultimap.create(); for (TripPattern pattern : tripPatterns) { AgencyAndId routeId = pattern.route.getId(); patternsForRoute.put(pattern.route, pattern); int count = patternsForRoute.get(pattern.route).size(); // OBA library uses underscore as separator, we're moving toward colon. String id = String.format("%s:%s:%02d", routeId.getAgencyId(), routeId.getId(), count); pattern.code = (id); } }