Java Code Examples for com.google.common.collect.Maps#filterKeys()

The following examples show how to use com.google.common.collect.Maps#filterKeys() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SummarizeDocScores2016.java    From tac-kbp-eal with MIT License 6 votes vote down vote up
private void writeSummaryArgScores(
    final Collection<String> focusTeamSubmissionNames,
    final ImmutableMap<String, SystemScores> systemNameToScores,
    final ImmutableSetMultimap<String, String> teamsToSystems, final Writer out)
    throws IOException {
  out.write("Document Level Argument Summary Score:\n\n");

  final Map<String, SystemScores> teamScores =
      Maps.filterKeys(systemNameToScores, in(focusTeamSubmissionNames));

  final ImmutableMap.Builder<String, SystemScores> argScoresToPrint = ImmutableMap.builder();
  argScoresToPrint.putAll(teamScores);
  final Optional<Map<Integer, PercentileComputer.Percentiles>> medianScores;
  if (teamsToSystems.keySet().size() > 3) {
    medianScores = Optional.of(Maps.transformValues(
        findMedianSystemsBy(systemNameToScores, teamsToSystems, EXTRACT_ARG_BOOTSTRAP_MEDIAN),
        EXTRACT_ARG_BOOTSTRAP_SCORES));
  } else {
    medianScores = Optional.absent();
  }

  argScoresToPrint.put("Max", BY_BOOTSTRAP_MEDIAN_ARG_SCORE.max(systemNameToScores.values()));
  printBootstrapScoresChart(argScoresToPrint.build(), EXTRACT_ARG_BOOTSTRAP_SCORES, medianScores, out);

  out.write("The argument score is described in section 7.1 of the task guidelines.\n\n");
}
 
Example 2
Source File: PlanFragmenter.java    From presto with Apache License 2.0 6 votes vote down vote up
private SubPlan buildFragment(PlanNode root, FragmentProperties properties, PlanFragmentId fragmentId)
{
    Set<Symbol> dependencies = SymbolsExtractor.extractOutputSymbols(root);

    List<PlanNodeId> schedulingOrder = scheduleOrder(root);
    boolean equals = properties.getPartitionedSources().equals(ImmutableSet.copyOf(schedulingOrder));
    checkArgument(equals, "Expected scheduling order (%s) to contain an entry for all partitioned sources (%s)", schedulingOrder, properties.getPartitionedSources());

    Map<Symbol, Type> symbols = Maps.filterKeys(types.allTypes(), in(dependencies));

    PlanFragment fragment = new PlanFragment(
            fragmentId,
            root,
            symbols,
            properties.getPartitioningHandle(),
            schedulingOrder,
            properties.getPartitioningScheme(),
            ungroupedExecution(),
            statsAndCosts.getForSubplan(root),
            Optional.of(jsonFragmentPlan(root, symbols, metadata, session)));

    return new SubPlan(fragment, properties.getChildren());
}
 
Example 3
Source File: TestEffectivePredicateExtractor.java    From presto with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp()
{
    scanAssignments = ImmutableMap.<Symbol, ColumnHandle>builder()
            .put(A, new TestingColumnHandle("a"))
            .put(B, new TestingColumnHandle("b"))
            .put(C, new TestingColumnHandle("c"))
            .put(D, new TestingColumnHandle("d"))
            .put(E, new TestingColumnHandle("e"))
            .put(F, new TestingColumnHandle("f"))
            .build();

    Map<Symbol, ColumnHandle> assignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(A, B, C, D, E, F)));
    baseTableScan = TableScanNode.newInstance(
            newId(),
            makeTableHandle(TupleDomain.all()),
            ImmutableList.copyOf(assignments.keySet()),
            assignments);

    expressionNormalizer = new ExpressionIdentityNormalizer();
}
 
Example 4
Source File: Closure_112_TypeInference_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * For functions with function(this: T, ...) and T as parameters, type
 * inference will set the type of this on a function literal argument to the
 * the actual type of T.
 */
private boolean inferTemplatedTypesForCall(
    Node n, FunctionType fnType) {
  final ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap()
      .getTemplateKeys();
  if (keys.isEmpty()) {
    return false;
  }

  // Try to infer the template types
  Map<TemplateType, JSType> inferred = Maps.filterKeys(
      inferTemplateTypesFromParameters(fnType, n),
      new Predicate<TemplateType>() {

        @Override
        public boolean apply(TemplateType key) {
          return keys.contains(key);
        }}
      );

  // Replace all template types. If we couldn't find a replacement, we
  // replace it with UNKNOWN.
  TemplateTypeReplacer replacer = new TemplateTypeReplacer(
      registry, inferred);
  Node callTarget = n.getFirstChild();

  FunctionType replacementFnType = fnType.visit(replacer)
      .toMaybeFunctionType();
  Preconditions.checkNotNull(replacementFnType);

  callTarget.setJSType(replacementFnType);
  n.setJSType(replacementFnType.getReturnType());

  return replacer.madeChanges;
}
 
Example 5
Source File: BlobStoreContextFactoryImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public BlobStoreContext newBlobStoreContext(Location location) {
    String rawProvider = checkNotNull(location.getConfig(LocationConfigKeys.CLOUD_PROVIDER), "provider must not be null");
    String provider = DeserializingJcloudsRenamesProvider.INSTANCE.applyJcloudsRenames(rawProvider);
    String identity = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_IDENTITY), "identity must not be null");
    String credential = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_CREDENTIAL), "credential must not be null");
    String endpoint = location.getConfig(CloudLocationConfig.CLOUD_ENDPOINT);

    Properties overrides = new Properties();
    // * Java 7,8 bug workaround - sockets closed by GC break the internal bookkeeping
    //   of HttpUrlConnection, leading to invalid handling of the "HTTP/1.1 100 Continue"
    //   response. Coupled with a bug when using SSL sockets reads will block
    //   indefinitely even though a read timeout is explicitly set.
    // * Java 6 ignores the header anyways as it is included in its restricted headers black list.
    // * Also there's a bug in SL object store which still expects Content-Length bytes
    //   even when it responds with a 408 timeout response, leading to incorrectly
    //   interpreting the next request (triggered by above problem).
    overrides.setProperty(Constants.PROPERTY_STRIP_EXPECT_HEADER, "true");

    // Add extra jclouds-specific configuration
    Map<String, Object> extra = Maps.filterKeys(((LocationInternal)location).config().getBag().getAllConfig(), Predicates.containsPattern("^jclouds\\."));
    if (extra.size() > 0) {
        LOG.debug("Configuring custom jclouds property overrides for {}: {}", provider, Sanitizer.sanitize(extra));
    }
    overrides.putAll(Maps.filterValues(extra, Predicates.notNull()));

    ContextBuilder contextBuilder = ContextBuilder.newBuilder(provider).credentials(identity, credential);
    contextBuilder.modules(MutableList.copyOf(getCommonModules()));
    if (!org.apache.brooklyn.util.text.Strings.isBlank(endpoint)) {
        contextBuilder.endpoint(endpoint);
    }
    contextBuilder.overrides(overrides);
    BlobStoreContext context = contextBuilder.buildView(BlobStoreContext.class);
    return context;
}
 
Example 6
Source File: JavaDriver.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private static Capabilities dropCapabilities(Capabilities capabilities, String... keysToRemove) {
    if (capabilities == null) {
        return new DesiredCapabilities();
    }
    final Set<String> toRemove = Sets.newHashSet(keysToRemove);
    DesiredCapabilities caps = new DesiredCapabilities(Maps.filterKeys(capabilities.asMap(), new Predicate<String>() {
        @Override
        public boolean apply(String key) {
            return !toRemove.contains(key);
        }
    }));

    return caps;
}
 
Example 7
Source File: ObjectStorageBlobConfigurationTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(RequiredParameters.class)
void shouldThrowWhenRequiredParameterOmitted(String toOmit) {
    Map<String, Object> configurationWithFilteredKey = Maps.filterKeys(VALID_CONFIGURATION, key -> !toOmit.equals(key));

    assertThat(configurationWithFilteredKey).doesNotContainKeys(toOmit);
    assertThatThrownBy(() -> ObjectStorageBlobConfiguration.from(new MapConfiguration(configurationWithFilteredKey)))
        .isInstanceOf(ConfigurationException.class);
}
 
Example 8
Source File: ArgumentOutput.java    From tac-kbp-eal with MIT License 5 votes vote down vote up
/**
 * retains only metadata pertaining to responses for which we have a score.
 */
public static ArgumentOutput from(final Symbol docId,
    final Iterable<Scored<Response>> scoredResponses, final Map<Response, String> metadata) {
  ImmutableSet<Response> responses =
      ImmutableSet.copyOf(transform(scoredResponses, Scoreds.<Response>itemsOnly()));
  return new ArgumentOutput(docId, responses, Scoreds.asMapKeepingHigestScore(scoredResponses),
      Maps.filterKeys(metadata, Predicates.in(responses)));
}
 
Example 9
Source File: CacheManagerTest.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public Map<Object, Object> loadInitialData()
{
  return Maps.filterKeys(backupMap, new Predicate<Object>()
  {
    @Override
    public boolean apply(@Nullable Object key)
    {
      return key != null && (Integer)key <= 5;
    }
  });
}
 
Example 10
Source File: HttpExecutorFactoryImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public HttpExecutor getHttpExecutor(Map<?, ?> props) {
    HttpExecutor httpExecutor;

    String httpExecutorClass = (String) props.get(HTTP_EXECUTOR_CLASS_CONFIG);
    if (httpExecutorClass != null) {
        Map<String,Object> httpExecutorProps = MutableMap.of();
        Map<?, ?> executorProps = Maps.filterKeys(props, StringPredicates.isStringStartingWith(HTTP_EXECUTOR_CLASS_CONFIG_PREFIX));
        if (executorProps.size() > 0) {
            for (Entry<?, ?> entry: executorProps.entrySet()) {
                String keyName = Strings.removeFromStart((String)entry.getKey(), HTTP_EXECUTOR_CLASS_CONFIG_PREFIX);
                httpExecutorProps.put(keyName, entry.getValue());
            }
        }
        try {
            httpExecutor = (HttpExecutor) new ClassLoaderUtils(getClass()).loadClass(httpExecutorClass).getConstructor(Map.class).newInstance(httpExecutorProps);
        } catch (Exception e) {
            throw Exceptions.propagate(e);
        }

    } else {
        LOG.info(HTTP_EXECUTOR_CLASS_CONFIG + " parameter not provided. Using the default implementation " + HttpExecutorImpl.class.getName());
        httpExecutor = HttpExecutorImpl.newInstance();
    }

    return httpExecutor;
}
 
Example 11
Source File: AbstractShardingSphereDataSourceForMasterSlaveTest.java    From shardingsphere with Apache License 2.0 4 votes vote down vote up
private static Map<String, DataSource> getDataSources() {
    return Maps.filterKeys(getDatabaseTypeMap().values().iterator().next(), MASTER_SLAVE_DB_NAMES::contains);
}
 
Example 12
Source File: NodeColoredSchedule.java    From batfish with Apache License 2.0 4 votes vote down vote up
/**
 * Get the next set of nodes that are allowed to be run in parallel during a dataplane iteration
 *
 * @return a map of nodes keyed by name, containing a subset of all network nodes
 */
@Override
public Map<String, Node> next() {
  Set<String> nodeNames = _iterator.next();
  return Maps.filterKeys(_nodes, nodeNames::contains);
}
 
Example 13
Source File: TestEffectivePredicateExtractor.java    From presto with Apache License 2.0 4 votes vote down vote up
@Test
public void testRightJoin()
{
    ImmutableList.Builder<JoinNode.EquiJoinClause> criteriaBuilder = ImmutableList.builder();
    criteriaBuilder.add(new JoinNode.EquiJoinClause(A, D));
    criteriaBuilder.add(new JoinNode.EquiJoinClause(B, E));
    List<JoinNode.EquiJoinClause> criteria = criteriaBuilder.build();

    Map<Symbol, ColumnHandle> leftAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(A, B, C)));
    TableScanNode leftScan = tableScanNode(leftAssignments);

    Map<Symbol, ColumnHandle> rightAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(D, E, F)));
    TableScanNode rightScan = tableScanNode(rightAssignments);

    FilterNode left = filter(
            leftScan,
            and(
                    lessThan(BE, AE),
                    lessThan(CE, bigintLiteral(10)),
                    equals(GE, bigintLiteral(10))));
    FilterNode right = filter(
            rightScan,
            and(
                    equals(DE, EE),
                    lessThan(FE, bigintLiteral(100))));
    PlanNode node = new JoinNode(
            newId(),
            JoinNode.Type.RIGHT,
            left,
            right,
            criteria,
            left.getOutputSymbols(),
            right.getOutputSymbols(),
            Optional.empty(),
            Optional.empty(),
            Optional.empty(),
            Optional.empty(),
            Optional.empty(),
            ImmutableMap.of(),
            Optional.empty());

    Expression effectivePredicate = effectivePredicateExtractor.extract(SESSION, node, TypeProvider.empty(), typeAnalyzer);

    // All left side symbols should be checked against NULL
    assertEquals(
            normalizeConjuncts(effectivePredicate),
            normalizeConjuncts(
                    or(lessThan(BE, AE), and(isNull(BE), isNull(AE))),
                    or(lessThan(CE, bigintLiteral(10)), isNull(CE)),
                    equals(DE, EE),
                    lessThan(FE, bigintLiteral(100)),
                    or(equals(AE, DE), isNull(AE)),
                    or(equals(BE, EE), isNull(BE))));
}
 
Example 14
Source File: TestEffectivePredicateExtractor.java    From presto with Apache License 2.0 4 votes vote down vote up
@Test
public void testRightJoinWithFalseInner()
{
    List<JoinNode.EquiJoinClause> criteria = ImmutableList.of(new JoinNode.EquiJoinClause(A, D));

    Map<Symbol, ColumnHandle> leftAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(A, B, C)));
    TableScanNode leftScan = tableScanNode(leftAssignments);

    Map<Symbol, ColumnHandle> rightAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(D, E, F)));
    TableScanNode rightScan = tableScanNode(rightAssignments);

    FilterNode left = filter(leftScan, FALSE_LITERAL);
    FilterNode right = filter(
            rightScan,
            and(
                    equals(DE, EE),
                    lessThan(FE, bigintLiteral(100))));
    PlanNode node = new JoinNode(
            newId(),
            JoinNode.Type.RIGHT,
            left,
            right,
            criteria,
            left.getOutputSymbols(),
            right.getOutputSymbols(),
            Optional.empty(),
            Optional.empty(),
            Optional.empty(),
            Optional.empty(),
            Optional.empty(),
            ImmutableMap.of(),
            Optional.empty());

    Expression effectivePredicate = effectivePredicateExtractor.extract(SESSION, node, TypeProvider.empty(), typeAnalyzer);

    // False literal on the left side should be ignored
    assertEquals(
            normalizeConjuncts(effectivePredicate),
            normalizeConjuncts(
                    equals(DE, EE),
                    lessThan(FE, bigintLiteral(100)),
                    or(equals(AE, DE), isNull(AE))));
}
 
Example 15
Source File: WorkersConfig.java    From kafka-workers with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private static Map<String, Object> propertiesWithoutPrefix(Map<?,?> props, String prefix) {
    return (Map<String, Object>) Maps.filterKeys(props, key -> !((String) key).startsWith(prefix));
}
 
Example 16
Source File: HeaderImpl.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public Map<String, String> getValues() {
  return (Map) Maps.filterKeys(map, this);
}
 
Example 17
Source File: AbstractShardingSphereDataSourceForShardingTest.java    From shardingsphere with Apache License 2.0 4 votes vote down vote up
private static Map<String, DataSource> getDataSourceMap() {
    return Maps.filterKeys(getDatabaseTypeMap().values().iterator().next(), SHARDING_DB_NAMES::contains);
}
 
Example 18
Source File: Activatables.java    From arctic-sea with Apache License 2.0 4 votes vote down vote up
public static <K, T> Map<K, T> activatedMap(Map<K, T> map, ActivationProvider<? super K> provider) {
    return Maps.filterKeys(map, provider::isActive);
}
 
Example 19
Source File: MapExtensions.java    From xtext-lib with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Replies the elements of the given map except the pairs with the given keys.
 *
 * <p>
 * The replied map is a view on the given map. It means that any change
 * in the original map is reflected to the result of this operation.
 * </p>
 *
 * @param <K> type of the map keys.
 * @param <V> type of the map values.
 * @param map the map to update.
 * @param keys the keys of the pairs to remove.
 * @return the map with the content of the map except the pairs.
 * @since 2.15
 */
@Pure
public static <K, V> Map<K, V> operator_minus(Map<K, V> map, final Iterable<?> keys) {
	return Maps.filterKeys(map, new Predicate<K>() {
		@Override
		public boolean apply(K input) {
			return !Iterables.contains(keys, input);
		}
	});
}
 
Example 20
Source File: TargetUtils.java    From bazel with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the execution info. These include execution requirement tags ('block-*', 'requires-*',
 * 'no-*', 'supports-*', 'disable-*', 'local', and 'cpu:*') as keys with empty values.
 */
public static Map<String, String> filter(Map<String, String> executionInfo) {
  return Maps.filterKeys(executionInfo, TargetUtils::legalExecInfoKeys);
}