List of usage examples for com.google.common.collect Table rowKeySet
Set<R> rowKeySet();
From source file:org.clueminer.eval.external.AdjustedRandCorrected.java
/** * Count number of classes in each cluster when we don't know how many * classes we have.//from w w w . j a v a 2 s.co m * * * @param clust * @return */ public int[][] countMutual(Clustering<E, C> clust) { //SortedSet klasses = dataset.getClasses(); //Table<String, String, Integer> table = counting.contingencyTable(clust); Table<String, String, Integer> table = contingencyTable(clust); //String[] klassLabels = (String[]) klasses.toArray(new String[klasses.size()]); Set<String> rows = table.rowKeySet(); String[] rowLabels = rows.toArray(new String[rows.size()]); int[][] conf = new int[rowLabels.length + 1][clust.size() + 1]; int k = 0; //Dump.array(rowLabels, "classes"); for (Cluster c : clust) { Map<String, Integer> col = table.column(c.getName()); for (int i = 0; i < rowLabels.length; i++) { if (col.containsKey(rowLabels[i])) { conf[i][k] = col.get(rowLabels[i]); conf[i][clust.size()] += conf[i][k]; } conf[rows.size()][k] += conf[i][k]; } k++; } //Dump.matrix(conf, "conf mat", 0); return conf; }
From source file:com.netflix.spinnaker.fiat.permissions.RedisPermissionsRepository.java
@Override public Map<String, UserPermission> getAllById() { Table<String, ResourceType, Response<Map<String, String>>> responseTable = getAllFromRedis(); if (responseTable == null) { return new HashMap<>(0); }//from www. ja va2 s.c om Map<String, UserPermission> allById = new HashMap<>(responseTable.rowKeySet().size()); RawUserPermission rawUnrestricted = new RawUserPermission(responseTable.row(UNRESTRICTED)); UserPermission unrestrictedUser = getUserPermission(UNRESTRICTED, rawUnrestricted); for (String userId : responseTable.rowKeySet()) { RawUserPermission rawUser = new RawUserPermission(responseTable.row(userId)); UserPermission permission = getUserPermission(userId, rawUser); allById.put(userId, permission.merge(unrestrictedUser)); } return allById; }
From source file:org.dishevelled.analysis.AnalysisUtils.java
/** * Convert the specified table to a graph, adding edges for values accepted * by the specified predicate. The row key value will be the source node and the column * key value the target node in edges in the returned graph. * * @param <N> table row and column key type and graph node type * @param <E> table value type and graph edge type * @param table table to convert, must not be null * @param predicate table value predicate, must not be null * @return the specified table converted to a graph *///from w ww. j a v a 2 s .c o m public static <N, E> Graph<N, E> toGraph(final Table<N, N, E> table, final UnaryPredicate<E> predicate) { if (table == null) { throw new IllegalArgumentException("table must not be null"); } if (predicate == null) { throw new IllegalArgumentException("predicate must not be null"); } int n = Math.max(DEFAULT_SIZE, Math.max(table.columnKeySet().size(), table.rowKeySet().size())); int e = Math.max(DEFAULT_SIZE, table.size()); Map<N, Node<N, E>> nodes = createMap(n); Graph<N, E> graph = createGraph(n, e); for (Table.Cell<N, N, E> cell : table.cellSet()) { N sourceValue = cell.getRowKey(); N targetValue = cell.getColumnKey(); E value = cell.getValue(); if (!nodes.containsKey(sourceValue)) { nodes.put(sourceValue, graph.createNode(sourceValue)); } if (!nodes.containsKey(targetValue)) { nodes.put(targetValue, graph.createNode(targetValue)); } if (value != null && predicate.test(value)) { graph.createEdge(nodes.get(sourceValue), nodes.get(targetValue), value); } } return graph; }
From source file:es.upm.dit.xsdinferencer.datastructures.Schema.java
/** * This method tries to guess the main namespace of this schema if no one is configured or * returns the configured one, if any. // w w w . j av a 2 s . c o m * That namespace will be the one which has more elements in the schema and is not skipped. * If more than one namespace has the greatest number of elements, then the one with most attributes * is chosen. If there also is more than one namespace in that situation, one of them is chosen. * @param configuration the inference configuration * @return a namespace URI of the main namespace */ public String guessMainNamespace(XSDInferenceConfiguration configuration) { String configurationMainNamespace = configuration.getMainNamespace(); if (configurationMainNamespace != null) return configurationMainNamespace; String namespaceCandidate = null; int elementMaxCount = Integer.MIN_VALUE; int attributeMaxCount = Integer.MIN_VALUE; Table<String, String, SchemaElement> schemaElements = this.getElements(); Table<String, String, SchemaAttribute> schemaAttributes = this.getAttributes(); for (String namespace : schemaElements.rowKeySet()) { Map<String, SchemaElement> elementsOfCurrentNamespace = schemaElements.row(namespace); Map<String, SchemaAttribute> attributesOfCurrentNamespace = schemaAttributes.row(namespace); if (elementsOfCurrentNamespace.keySet().size() > elementMaxCount || (elementsOfCurrentNamespace.keySet().size() == elementMaxCount && attributesOfCurrentNamespace.keySet().size() > attributeMaxCount)) { namespaceCandidate = namespace; elementMaxCount = elementsOfCurrentNamespace.keySet().size(); attributeMaxCount = attributesOfCurrentNamespace.keySet().size(); } } return namespaceCandidate; }
From source file:com.rackspacecloud.blueflood.io.astyanax.AstyanaxWriter.java
public void writeMetadata(Table<Locator, String, String> metaTable) throws ConnectionException { ColumnFamily cf = CassandraModel.CF_METRICS_METADATA; Timer.Context ctx = Instrumentation.getBatchWriteTimerContext(CassandraModel.CF_METRICS_METADATA_NAME); MutationBatch batch = keyspace.prepareMutationBatch(); try {/*from w w w. j av a 2s . c o m*/ for (Locator locator : metaTable.rowKeySet()) { Map<String, String> metaRow = metaTable.row(locator); ColumnListMutation<String> mutation = batch.withRow(cf, locator); for (Map.Entry<String, String> meta : metaRow.entrySet()) { mutation.putColumn(meta.getKey(), meta.getValue(), StringMetadataSerializer.get(), null); } } try { batch.execute(); } catch (ConnectionException e) { Instrumentation.markWriteError(e); log.error("Connection exception persisting metadata", e); throw e; } } finally { ctx.stop(); } }
From source file:org.apache.sentry.cli.tools.SentryConfigToolIndexer.java
private void convertINIToSentryServiceCmds(String component, String service, String requestorName, Configuration conf, SentryGenericServiceClient client, String policyFile, boolean validate, boolean importPolicy, boolean checkCompat) throws Exception { //instantiate a file providerBackend for parsing LOGGER.info("Reading policy file at: " + policyFile); SimpleFileProviderBackend policyFileBackend = new SimpleFileProviderBackend(conf, policyFile); ProviderBackendContext context = new ProviderBackendContext(); context.setValidators(IndexerPrivilegeModel.getInstance().getPrivilegeValidators()); policyFileBackend.initialize(context); if (validate) { validatePolicy(policyFileBackend); }//from www . jav a 2s . c o m if (checkCompat) { checkCompat(policyFileBackend); } //import the relations about group,role and privilege into the DB store Set<String> roles = Sets.newHashSet(); Table<String, String, Set<String>> groupRolePrivilegeTable = policyFileBackend.getGroupRolePrivilegeTable(); GenericPrivilegeConverter converter = new GenericPrivilegeConverter(component, service, false); for (String groupName : groupRolePrivilegeTable.rowKeySet()) { for (String roleName : groupRolePrivilegeTable.columnKeySet()) { if (!roles.contains(roleName)) { LOGGER.info(dryRunMessage(importPolicy) + "Creating role: " + roleName.toLowerCase(Locale.US)); if (importPolicy) { client.createRoleIfNotExist(requestorName, roleName, component); } roles.add(roleName); } Set<String> privileges = groupRolePrivilegeTable.get(groupName, roleName); if (privileges == null) { continue; } LOGGER.info(dryRunMessage(importPolicy) + "Adding role: " + roleName.toLowerCase(Locale.US) + " to group: " + groupName); if (importPolicy) { client.grantRoleToGroups(requestorName, roleName, component, Sets.newHashSet(groupName)); } for (String permission : privileges) { String action = null; for (String authorizable : AUTHORIZABLE_SPLITTER.trimResults().split(permission)) { KeyValue kv = new KeyValue(authorizable); String key = kv.getKey(); String value = kv.getValue(); if ("action".equalsIgnoreCase(key)) { action = value; } } // Service doesn't support not specifying action if (action == null) { permission += "->action=" + Action.ALL; } LOGGER.info(dryRunMessage(importPolicy) + "Adding permission: " + permission + " to role: " + roleName.toLowerCase(Locale.US)); if (importPolicy) { client.grantPrivilege(requestorName, roleName, component, converter.fromString(permission)); } } } } }
From source file:org.apache.sentry.cli.tools.PermissionsMigrationToolCommon.java
private void migratePolicyFile() throws Exception { Configuration conf = getSentryConf(); Path sourceFile = new Path(policyFile.get()); SimpleFileProviderBackend policyFileBackend = new SimpleFileProviderBackend(conf, sourceFile); ProviderBackendContext ctx = new ProviderBackendContext(); policyFileBackend.initialize(ctx);/*from w w w .j a va 2s.c om*/ Set<String> roles = Sets.newHashSet(); Table<String, String, Set<String>> groupRolePrivilegeTable = policyFileBackend.getGroupRolePrivilegeTable(); Ini output = PolicyFiles.loadFromPath(sourceFile.getFileSystem(conf), sourceFile); Ini.Section rolesSection = output.get(PolicyFileConstants.ROLES); for (String groupName : groupRolePrivilegeTable.rowKeySet()) { for (String roleName : policyFileBackend.getRoles(Collections.singleton(groupName), ActiveRoleSet.ALL)) { if (!roles.contains(roleName)) { // Do the actual migration Set<String> privileges = groupRolePrivilegeTable.get(groupName, roleName); Collection<String> migrated = transformPrivileges(privileges); if (!migrated.isEmpty()) { LOGGER.info("{} For role {} migrating privileges from {} to {}", getDryRunMessage(), roleName, privileges, migrated); if (!dryRun) { rolesSection.put(roleName, PrivilegeUtils.fromPrivilegeStrings(migrated)); } } roles.add(roleName); } } } if (!dryRun) { Path targetFile = new Path(outputFile.get()); PolicyFiles.writeToPath(output, targetFile.getFileSystem(conf), targetFile); LOGGER.info("Successfully saved migrated Sentry policy file at {}", outputFile.get()); } }
From source file:Model.Agents.Brains.Intersection_Brain.java
/** * Reasonning methods use to find a trajectory for the new vehicle. * /*from ww w . ja v a 2 s .co m*/ * @param pos postion of the new vehicle in the intersection. * @param goal destination of the new vehicle. * * @return the trajectory of the vehicle. */ private Trajectory findTrajectory(Cell pos, CardinalPoint goal) { //Get the good trajectory. Intersection_Body i_body = (Intersection_Body) this.body; Intersection inter = (Intersection) i_body.getInfrastructure(); Table<CardinalPoint, Integer, Trajectory> ways = inter.getTrajectories(); Trajectory trajectory = null; int t_id = -1; CardinalPoint t_cp = null; boolean ok = false; for (CardinalPoint c : ways.rowKeySet()) { for (Entry<Integer, Trajectory> entry : ways.row(c).entrySet()) { int _id = entry.getKey(); Trajectory w = entry.getValue(); //If the trajectory contains the position if (w.getCells().contains(pos)) { if (_id >= 0 && _id < inter.getNb_ways().get(Flow.IN, c)) { if (c.getFront() == goal) { trajectory = w; t_id = _id; t_cp = c; ok = true; } } else if (_id == inter.getNb_ways().get(Flow.IN, c)) { if (c.getRight() == goal) { trajectory = w; t_id = _id; t_cp = c; ok = true; } } else { if (c.getLeft() == goal) { trajectory = w; t_id = _id; t_cp = c; ok = true; } } } } if (ok) break; } if (ok) { //Get the first cell of the neighbor. //* if (i_body.getNeighbors().containsKey(goal)) { Infrastructure neighbor = i_body.getNeighbors().get(goal).getInfrastructure(); Trajectory w = neighbor.getTrajectories().get(goal.getFront(), t_id); if (w != null && !w.isEmpty()) { Cell next = w.getCells().get(0); if (next != null && trajectory != null) trajectory.addCell(next); } } //*/ //Determine the cell where the vehicle will wait Cell whereStop = null; if (t_cp != null) { Intersection i = (Intersection) i_body.getInfrastructure(); if (trajectory != null && trajectory.getCells() != null && !trajectory.getCells().isEmpty()) whereStop = trajectory.getCells().get(i.getWays_size().get(Flow.IN, t_cp) - 1); } if (trajectory != null) trajectory.setWhereToStop(whereStop); } return trajectory; }
From source file:org.pau.assetmanager.viewmodel.stocks.HistoricalStocksValuesDownloader.java
private static Table<Integer, Integer, Double> getYearToMonthToValueTable(String symbol, Integer startYear, Integer finalYear) {/*from w w w . ja va 2 s .c o m*/ try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Calendar calendar = GregorianCalendar.getInstance(); Table<Integer, Integer, Double> yearMonthValueTable = HashBasedTable.<Integer, Integer, Double>create(); Table<Integer, Integer, Integer> yearMonthTimesTable = HashBasedTable .<Integer, Integer, Integer>create(); List<Map<String, String>> csvContents = getContents(symbol, startYear, finalYear); for (Map<String, String> fieldToValueMap : csvContents) { Double open = Double.parseDouble(fieldToValueMap.get(OPEN)); Double close = Double.parseDouble(fieldToValueMap.get(OPEN)); Double averagePrice = (open + close) / 2.0; Date date = simpleDateFormat.parse(fieldToValueMap.get(DATE)); calendar.setTime(date); Integer year = calendar.get(Calendar.YEAR); Integer month = calendar.get(Calendar.MONTH); Integer day = calendar.get(Calendar.DAY_OF_MONTH); Double currentPrice = yearMonthValueTable.get(year, month); if (currentPrice == null) { currentPrice = averagePrice; } else { currentPrice += averagePrice; } yearMonthValueTable.put(year, month, currentPrice); Integer times = yearMonthTimesTable.get(year, month); if (times == null) { times = 1; } else { times++; } yearMonthTimesTable.put(year, month, times); } for (Integer year : yearMonthTimesTable.rowKeySet()) { for (Integer month : yearMonthTimesTable.row(year).keySet()) { yearMonthValueTable.put(year, month, yearMonthValueTable.get(year, month) / yearMonthTimesTable.get(year, month).doubleValue()); } } return yearMonthValueTable; } catch (ParseException e) { throw new AssetManagerRuntimeException("Error parsing date from CSV file for '" + symbol + "' between '" + startYear + "' and '" + finalYear + "'.", e); } }
From source file:org.dishevelled.analysis.AnalysisUtils.java
/** * Convert the specified table to a bit matrix. The row key value will be * used to look up the row index and the column key value the column index in the returned bit matrix. * * @param <N> table row and column key type * @param <E> table value type//w w w. ja v a 2 s . co m * @param table table to convert, must not be null * @param keyIndices mapping of key indices by key, must not be null * @param predicate table value predicate, must not be null * @return the specified table converted to a bit matrix */ public static <N, E> BitMatrix2D toBitMatrix(final Table<N, N, E> table, final UnaryFunction<N, Long> keyIndices, final UnaryPredicate<E> predicate) { if (table == null) { throw new IllegalArgumentException("table must not be null"); } if (keyIndices == null) { throw new IllegalArgumentException("keyIndices must not be null"); } if (predicate == null) { throw new IllegalArgumentException("predicate must not be null"); } // is combining row and column keys necessary? Set<N> uniqueKeys = createSet(table.rowKeySet().size(), table.columnKeySet().size()); uniqueKeys.addAll(table.rowKeySet()); uniqueKeys.addAll(table.columnKeySet()); long n = uniqueKeys.size(); BitMatrix2D bitMatrix = new BitMatrix2D(n, n); for (Table.Cell<N, N, E> cell : table.cellSet()) { if (predicate.test(cell.getValue())) { N source = cell.getRowKey(); N target = cell.getColumnKey(); Long sourceIndex = keyIndices.evaluate(source); Long targetIndex = keyIndices.evaluate(target); if (sourceIndex != null && targetIndex != null) { bitMatrix.set(sourceIndex, targetIndex, true); } } } return bitMatrix; }