protected XORAllocation<T> adaptMIPResult(IMIPResult mipResult) { Map<Bidder<T>, BidderAllocation<T>> trades = new HashMap<>(); for (Bidder<T> bidder : auction.getBidders()) { double totalValue = 0; Builder<Good> goodsBuilder = ImmutableSet.<Good>builder(); Builder<XORValue<T>> bundleBids = ImmutableSet.<XORValue<T>>builder(); for (XORValue<T> bundleBid : auction.getBid(bidder).getValues()) { if (DoubleMath.fuzzyEquals(mipResult.getValue(getBidVariable(bundleBid)), 1, 1e-3)) { goodsBuilder.addAll(bundleBid.getLicenses()); bundleBids.add(bundleBid); totalValue += bundleBid.value().doubleValue(); } } Set<Good> goods = goodsBuilder.build(); if (!goods.isEmpty()) { trades.put(bidder, new BidderAllocation<>(totalValue, new Bundle<>(goods), bundleBids.build())); } } return new XORAllocation<>(trades); }
private synchronized Collection<Class<?>> getClassesToCheck() { if( classesToCheck == null ) { Builder<Class<?>> builder = ImmutableSet.builder(); builder.addAll(STATIC_CLASSES_TO_CHECK); List<Extension> extensions = domainParamTracker.getExtensions(); for( Extension extension : extensions ) { Collection<Parameter> clazzes = extension.getParameters("class"); for( Parameter clazzParam : clazzes ) { builder.add(domainParamTracker.getClassForName(extension, clazzParam.valueAsString())); } } classesToCheck = builder.build(); } return classesToCheck; }
/** * Get a list of logical rules that can be turned on or off by session/system options. * * If a rule is intended to always be included with the logical set, it should be added * to the immutable list created in the getDrillBasicRules() method below. * * @param optimizerRulesContext - used to get the list of planner settings, other rules may * also in the future need to get other query state from this, * such as the available list of UDFs (as is used by the * DrillMergeProjectRule created in getDrillBasicRules()) * @return - a list of rules that have been filtered to leave out * rules that have been turned off by system or session settings */ public static RuleSet getDrillUserConfigurableLogicalRules(OptimizerRulesContext optimizerRulesContext) { final PlannerSettings ps = optimizerRulesContext.getPlannerSettings(); // This list is used to store rules that can be turned on an off // by user facing planning options final Builder<RelOptRule> userConfigurableRules = ImmutableSet.<RelOptRule>builder(); if (ps.isConstantFoldingEnabled()) { // TODO - DRILL-2218 userConfigurableRules.add(ReduceExpressionsRule.PROJECT_INSTANCE); userConfigurableRules.add(DrillReduceExpressionsRule.FILTER_INSTANCE_DRILL); userConfigurableRules.add(DrillReduceExpressionsRule.CALC_INSTANCE_DRILL); } return new DrillRuleSet(userConfigurableRules.build()); }
private static void propertiesOf(Builder<String> builder, Class<?> type) { if (!type.getPackage().getName().startsWith("java.lang")) { Method[] methods = type.getDeclaredMethods(); for (Method m : methods) { if (isVisibleMethod(m)) { System.out.println(type+"."+m.getName()); Maybe<String> propertyName=propertyNameOf(m); propertyName.ifPresent(name -> { builder.add(name); }); } } Class<?> superClass = type.getSuperclass(); if (superClass!=null && superClass!=Object.class) { propertiesOf(builder, superClass); } Class<?>[] interfaces = type.getInterfaces(); for (Class<?> i:interfaces) { propertiesOf(builder, i); } } }
@Override public Iterable<NodeMetadata> listNodesByIds(Iterable<String> ids) { List<Instance> instances = new ArrayList<Instance>(); for (String id : ids) { IAcsClient client = api.getAcsClient(api.decodeToRegion(id)); DescribeInstancesRequest req = new DescribeInstancesRequest(); Gson gson = new GsonBuilder().create(); String iids = gson.toJson(new String[] { api.decodeToId(id) }); req.setInstanceIds(iids); try { DescribeInstancesResponse resp = client.getAcsResponse(req); instances.addAll(resp.getInstances()); } catch (Exception e) { logger.warn(e.getMessage()); } } Builder<NodeMetadata> builder = ImmutableSet.builder(); builder.addAll(transform(instances, new InstanceToNodeMetadata(api, nodeStatus))); return builder.build(); }
@Override public Iterable<NodeMetadata> listNodes() { Builder<NodeMetadata> builder = ImmutableSet.builder(); Set<String> regions = api.getAvailableRegions(); for (String region : regions) { try { IAcsClient client = api.getAcsClient(region); DescribeInstancesRequest req = new DescribeInstancesRequest(); DescribeInstancesResponse resp = client.getAcsResponse(req); builder.addAll(transform(resp.getInstances(), new InstanceToNodeMetadata(api, nodeStatus))); } catch (Exception e) { logger.warn(e.getMessage()); } } return builder.build(); }
@Override public Iterable<Image> listImages() { Builder<Image> builder = ImmutableSet.builder(); Set<String> regions = api.getAvailableRegions(); for (String region : regions) { try { IAcsClient client = api.getAcsClient(region); DescribeImagesRequest req = new DescribeImagesRequest(); DescribeImagesResponse resp = client.getAcsResponse(req); builder.addAll(transform(resp.getImages(), new ImageToImage(api, region))); } catch (Exception e) { logger.warn(e.getMessage()); } } return builder.build(); }
public Set<String> getIncomingChannels(Plugin plugin) { if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null"); } synchronized (incomingLock) { Set<PluginMessageListenerRegistration> registrations = incomingByPlugin.get(plugin); if (registrations != null) { Builder<String> builder = ImmutableSet.builder(); for (PluginMessageListenerRegistration registration : registrations) { builder.add(registration.getChannel()); } return builder.build(); } else { return ImmutableSet.of(); } } }
public Set<PluginMessageListenerRegistration> getIncomingChannelRegistrations(Plugin plugin, String channel) { if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null"); } validateChannel(channel); synchronized (incomingLock) { Set<PluginMessageListenerRegistration> registrations = incomingByPlugin.get(plugin); if (registrations != null) { Builder<PluginMessageListenerRegistration> builder = ImmutableSet.builder(); for (PluginMessageListenerRegistration registration : registrations) { if (registration.getChannel().equals(channel)) { builder.add(registration); } } return builder.build(); } else { return ImmutableSet.of(); } } }
@Override protected ImmutableList<ValueAssignment> modelToList() { scala.collection.Map<ModelLocation, ModelValue> interpretation = model.interpretation(); // first get the addresses of arrays Map<IdealInt, ITerm> arrays = getArrayAddresses(interpretation); // then iterate over the model and generate the assignments Builder<ValueAssignment> assignments = ImmutableSet.builder(); Iterator<Tuple2<ModelLocation, ModelValue>> it2 = interpretation.iterator(); while (it2.hasNext()) { Tuple2<ModelLocation, ModelValue> entry = it2.next(); ValueAssignment assignment = getAssignment(entry._1, entry._2, arrays); if (assignment != null) { assignments.add(assignment); } } return assignments.build().asList(); }
@Override protected ImmutableList<ValueAssignment> modelToList() { Builder<ValueAssignment> assignments = ImmutableSet.builder(); for (Term t : assertedTerms) { creator.extractVariablesAndUFs( t, true, (name, f) -> { if (f.getSort().isArraySort()) { assignments.addAll(getArrayAssignment(name, f, f, Collections.emptyList())); } else { assignments.add(getAssignment(name, (ApplicationTerm) f)); } }); } return assignments.build().asList(); }
/** * Combines the both positions in such a way, that for each coordinate of the types given in the given set of * dimensions have to be * <ul> * <li>either present in both positions of the pair, and then have to be the same * <li>or be present in only one of the both positions * </ul> * * @param left the first of the two positions, whose dimensions should be united * @param right the second of the two positions whose dimensions should be combined * @param targetDimensions the dimension in which the positions shall be united * @return a new position, with the coordinates merged according to the above rules */ public static Position combineDimensions(Position left, Position right, Set<Class<?>> targetDimensions) { ImmutableSet.Builder<Object> builder = ImmutableSet.builder(); for (Class<?> dimension : targetDimensions) { Object leftCoordinate = left.coordinateFor(dimension); Object rightCoordinate = right.coordinateFor(dimension); if (Objects.equal(leftCoordinate, rightCoordinate) || oneIsNull(leftCoordinate, rightCoordinate)) { builder.add(MoreObjects.firstNonNull(leftCoordinate, rightCoordinate)); } else { throw new IllegalArgumentException( "Coordinates for dimension '" + dimension + "' are neither the same in both positions (" + left + " and " + right + "), nor present only in one. Cannot consistently combine."); } } return Position.of(builder.build()); }
@Test public void testUpdateEndpointGroup() throws Throwable { Set<Endpoint> expected = ImmutableSet.of(Endpoint.of("127.0.0.1", 8001, 2), Endpoint.of("127.0.0.1", 8002, 3)); switch (mode) { case IN_NODE_VALUE: setNodeValue(NodeValueCodec.DEFAULT.encodeAll(expected)); break; case IN_CHILD_NODES: //add two more node setNodeChild(expected); //construct the final expected node list Builder<Endpoint> builder = ImmutableSet.builder(); builder.addAll(sampleEndpoints).addAll(expected); expected = builder.build(); break; } try (CloseableZooKeeper zk = connection()) { zk.sync(zNode, (rc, path, ctx) -> { }, null); } final Set<Endpoint> finalExpected = expected; await().untilAsserted(() -> assertThat(endpointGroup.endpoints()).hasSameElementsAs(finalExpected)); }
public void solve() throws IloException{ long startms = System.currentTimeMillis(); cplex.solve(); long endms = System.currentTimeMillis(); this.solveTimeSeconds = (endms - startms)/1000.0; if(this.displayOutput){ System.out.println("objective: " + cplex.getObjValue()); } Builder<E> setBuilder = ImmutableSet.builder(); for(E edge: kepInstance.getGraph().getEdges()){ if(CplexUtil.doubleToBoolean(cplex.getValue(this.phaseOneProblem.indicatorEdgeSelected(edge)))){ setBuilder.add(edge); } } this.edgesInSolution = setBuilder.build(); }
ContainerEffectiveStatementImpl( final StmtContext<QName, ContainerStatement, EffectiveStatement<QName, ContainerStatement>> ctx) { super(ctx); this.original = (ContainerSchemaNode) ctx.getOriginalCtx().map(StmtContext::buildEffective).orElse(null); final ImmutableSet.Builder<ActionDefinition> actionsBuilder = ImmutableSet.builder(); final Builder<NotificationDefinition> notificationsBuilder = ImmutableSet.builder(); for (final EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements()) { if (effectiveStatement instanceof ActionDefinition) { actionsBuilder.add((ActionDefinition) effectiveStatement); } if (effectiveStatement instanceof NotificationDefinition) { notificationsBuilder.add((NotificationDefinition) effectiveStatement); } } this.actions = actionsBuilder.build(); this.notifications = notificationsBuilder.build(); presence = findFirstEffectiveSubstatement(PresenceEffectiveStatement.class).isPresent(); }
@Override public Collection<SchemaNodeIdentifier> adaptArgumentValue( final StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, EffectiveStatement<Collection<SchemaNodeIdentifier>, KeyStatement>> ctx, final QNameModule targetModule) { final Builder<SchemaNodeIdentifier> builder = ImmutableSet.builder(); boolean replaced = false; for (final SchemaNodeIdentifier arg : ctx.getStatementArgument()) { final QName qname = arg.getLastComponent(); if (!targetModule.equals(qname.getModule())) { final QName newQname = ctx.getFromNamespace(QNameCacheNamespace.class, QName.create(targetModule, qname.getLocalName())); builder.add(SchemaNodeIdentifier.SAME.createChild(newQname)); replaced = true; } else { builder.add(arg); } } // This makes sure we reuse the collection when a grouping is // instantiated in the same module return replaced ? builder.build() : ctx.getStatementArgument(); }
/** * Maps bitcode library files used by the LTO backends to the corresponding minimized bitcode file * used as input to the LTO indexing step. */ private static NestedSet<LibraryToLink> computeLtoIndexingUniqueLibraries( NestedSet<LibraryToLink> originalUniqueLibraries) { NestedSetBuilder<LibraryToLink> uniqueLibrariesBuilder = NestedSetBuilder.linkOrder(); for (LibraryToLink lib : originalUniqueLibraries) { if (!lib.containsObjectFiles()) { uniqueLibrariesBuilder.add(lib); continue; } ImmutableSet.Builder<Artifact> newObjectFilesBuilder = ImmutableSet.builder(); for (Artifact a : lib.getObjectFiles()) { newObjectFilesBuilder.add(lib.getLtoBitcodeFiles().getOrDefault(a, a)); } uniqueLibrariesBuilder.add( LinkerInputs.newInputLibrary( lib.getArtifact(), lib.getArtifactCategory(), lib.getLibraryIdentifier(), newObjectFilesBuilder.build(), lib.getLtoBitcodeFiles(), /* sharedNonLtoBackends= */ null)); } return uniqueLibrariesBuilder.build(); }
private Map<SkyKey, Collection<Target>> targetifyValues( Map<SkyKey, ? extends Iterable<SkyKey>> input, Multimap<SkyKey, SkyKey> packageKeyToTargetKeyMap) throws InterruptedException { ImmutableMap.Builder<SkyKey, Collection<Target>> result = ImmutableMap.builder(); Map<SkyKey, Target> allTargets = makeTargetsFromPackageKeyToTargetKeyMap(packageKeyToTargetKeyMap); for (Map.Entry<SkyKey, ? extends Iterable<SkyKey>> entry : input.entrySet()) { Iterable<SkyKey> skyKeys = entry.getValue(); Set<Target> targets = CompactHashSet.createWithExpectedSize(Iterables.size(skyKeys)); for (SkyKey key : skyKeys) { Target target = allTargets.get(key); if (target != null) { targets.add(target); } } result.put(entry.getKey(), targets); } return result.build(); }
@ThreadSafe public Map<SkyKey, Target> makeTargetsFromPackageKeyToTargetKeyMap( Multimap<SkyKey, SkyKey> packageKeyToTargetKeyMap) throws InterruptedException { ImmutableMap.Builder<SkyKey, Target> result = ImmutableMap.builder(); Set<SkyKey> processedTargets = new HashSet<>(); Map<SkyKey, SkyValue> packageMap = graph.getSuccessfulValues(packageKeyToTargetKeyMap.keySet()); for (Map.Entry<SkyKey, SkyValue> entry : packageMap.entrySet()) { for (SkyKey targetKey : packageKeyToTargetKeyMap.get(entry.getKey())) { if (processedTargets.add(targetKey)) { try { result.put( targetKey, ((PackageValue) entry.getValue()) .getPackage() .getTarget((SKYKEY_TO_LABEL.apply(targetKey)).getName())); } catch (NoSuchTargetException e) { // Skip missing target. } } } } return result.build(); }
ImmutableNegotiationResult(final ImmutableVariant variant, ImmutableQuality quality, final ImmutableVariant errorVariant, ImmutableAlternatives alternatives) { checkArgument( (variant==null && quality==null) || (variant!=null && quality!=null), "Variant and quality must be simultaneously defined or not (%s <--> %s)",variant,quality); checkNotNull(errorVariant,"Error variant cannot be null"); checkNotNull(alternatives,"Alternatives cannot be null"); this.variant=variant; this.quality=quality; this.errorVariant=errorVariant; this.alternatives=alternatives; Builder<MediaType> mtBuilder=ImmutableSet.<MediaType>builder(); Builder<CharacterEncoding> ceBuilder=ImmutableSet.<CharacterEncoding>builder(); Builder<Language> lBuilder=ImmutableSet.<Language>builder(); for(Alternative alternative:alternatives) { addEntityIfPresent(mtBuilder,alternative.type()); addEntityIfPresent(ceBuilder,alternative.charset()); addEntityIfPresent(lBuilder,alternative.language()); } this.mediaTypes=mtBuilder.build(); this.characterEncodings=ceBuilder.build(); this.languages=lBuilder.build(); }
private Map<String, String> readMetadataFromService() { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (MetadataLookup lookup : metadataLookups) { try { String value = readResource(lookup.getResourcePath()); if (!Strings.isNullOrEmpty(value)) { builder.put(lookup.getConfiglyKey(), value); } } catch (IOException e) { LOGGER.warn("Failed to read EC2 metadata from path " + lookup.getResourcePath(), e); } } return builder.build(); }
public void getTables(ImmutableSet.Builder<String> builder) { addTableOrSubquery(builder, mPendingTable); for (TableOrSubquery tableOrSubquery : mTables.keySet()) { addTableOrSubquery(builder, tableOrSubquery); } if (mPendingJoin != null) { addTableOrSubquery(builder, mPendingJoin.mJoinSource); } for (JoinSpec join : mJoins) { addTableOrSubquery(builder, join.mJoinSource); } builder.addAll(mTablesUsedInExpressions); }
@GET @Path("{id}/download") @RequiresRoles(UserRole.ROLE_ADMIN) @Produces(MediaType.TEXT_PLAIN) public Response download(@PathParam("id") long id) { Course course = courseDao.findById(id); Builder<String> setBuilder = ImmutableSet.builder(); if (course.getProjects().isEmpty()) { return Response.status(Status.NO_CONTENT).entity("This course doesn't have any projects").build(); } else { for (Project project : course.getProjects()) { if (project.getSourceCodeUrl() == null) { LOG.warn("This project doesnt have a source code URL: {}", project); } else { setBuilder.add(project.getSourceCodeUrl()); } } Set<String> sourceCodeurls = setBuilder.build(); return Response.ok(repoDownloader.prepareDownload(sourceCodeurls)).build(); } }
private ImmutableSet<CANDIDATE> allCandidatesThatReachedTheQuorum(BigFraction quorum, ImmutableCollection<VoteState<CANDIDATE>> voteStates, CandidateStates<CANDIDATE> candidateStates) { VoteDistribution<CANDIDATE> voteDistribution = new VoteDistribution<>(candidateStates.getHopefulCandidates(), voteStates); // We use a sorted set here, to provide Unit tests a predictable execution order. Builder<CANDIDATE> candidatesThatReachedTheQuorum = ImmutableSortedSet.orderedBy(comparing(o -> o.name)); voteDistribution.votesByCandidate.entrySet().stream() .filter(votesForCandidate -> quorumIsReached(quorum, votesForCandidate)) .forEach(votesForCandidate -> candidatesThatReachedTheQuorum.add(votesForCandidate.getKey())); return candidatesThatReachedTheQuorum.build(); }
ReflectiveDaoAdapter(Class<T> klass, ImmutableList<FieldAdapter> fieldAdapters, ImmutableList<EmbeddedFieldInitializer> fieldInitializers) { mClassFactory = ClassFactory.get(klass); mFieldAdapters = fieldAdapters; mFieldInitializers = fieldInitializers; ImmutableList.Builder<String> projectionBuilder = ImmutableList.builder(); ImmutableList.Builder<String> writableColumnsBuilder = ImmutableList.builder(); for (FieldAdapter fieldAdapter : fieldAdapters) { projectionBuilder.add(fieldAdapter.getColumnNames()); writableColumnsBuilder.add(fieldAdapter.getWritableColumnNames()); } mProjection = array(projectionBuilder.build()); mWritableColumns = array(writableColumnsBuilder.build()); mWritableDuplicates = findDuplicates(mWritableColumns); }
/** * It returns a list of trace files that corresponds to builds while respecting the maximum size * of the final zip file. * * @param entries the highlighted builds * @return a set of paths that points to the corresponding traces. */ private ImmutableSet<Path> getTracePathsOfBuilds(ImmutableSet<BuildLogEntry> entries) { ImmutableSet.Builder<Path> tracePaths = new ImmutableSet.Builder<>(); long reportSizeBytes = 0; for (BuildLogEntry entry : entries) { reportSizeBytes += entry.getSize(); if (entry.getTraceFile().isPresent()) { try { Path traceFile = filesystem.getPathForRelativeExistingPath(entry.getTraceFile().get()); long traceFileSizeBytes = Files.size(traceFile); if (doctorConfig.getReportMaxSizeBytes().isPresent()) { if (reportSizeBytes + traceFileSizeBytes < doctorConfig.getReportMaxSizeBytes().get()) { tracePaths.add(entry.getTraceFile().get()); reportSizeBytes += traceFileSizeBytes; } } else { tracePaths.add(entry.getTraceFile().get()); reportSizeBytes += traceFileSizeBytes; } } catch (IOException e) { LOG.info("Trace path %s wasn't valid, skipping it.", entry.getTraceFile().get()); } } } return tracePaths.build(); }