List of usage examples for com.google.common.collect ImmutableList size
int size();
From source file:org.summer.dsl.builder.impl.RegistryBuilderParticipant.java
public void build(IBuildContext buildContext, IProgressMonitor monitor) throws CoreException { ImmutableList<IXtextBuilderParticipant> participants = getParticipants(); if (participants.isEmpty()) return;/*from ww w.j a v a 2 s. c o m*/ SubMonitor progress = SubMonitor.convert(monitor, participants.size()); progress.subTask(Messages.RegistryBuilderParticipant_InvokingBuildParticipants); for (IXtextBuilderParticipant participant : participants) { if (progress.isCanceled()) throw new OperationCanceledException(); participant.build(buildContext, progress.newChild(1)); } }
From source file:com.opengamma.strata.pricer.bond.DiscountingBondFutureProductPricer.java
/** * Calculates the price sensitivity of the bond future product. * <p>/*from w ww .j ava 2s . c o m*/ * The price sensitivity of the product is the sensitivity of the price to the underlying curves. * <p> * Note that the price sensitivity should be no currency. * * @param future the future * @param discountingProvider the discounting provider * @return the price curve sensitivity of the product */ public PointSensitivities priceSensitivity(ResolvedBondFuture future, LegalEntityDiscountingProvider discountingProvider) { ImmutableList<ResolvedFixedCouponBond> basket = future.getDeliveryBasket(); int size = basket.size(); double[] priceBonds = new double[size]; int indexCTD = 0; double priceMin = 2d; for (int i = 0; i < size; i++) { ResolvedFixedCouponBond bond = basket.get(i); double dirtyPrice = bondPricer.dirtyPriceFromCurves(bond, discountingProvider, future.getLastDeliveryDate()); priceBonds[i] = bondPricer.cleanPriceFromDirtyPrice(bond, future.getLastDeliveryDate(), dirtyPrice) / future.getConversionFactors().get(i); if (priceBonds[i] < priceMin) { priceMin = priceBonds[i]; indexCTD = i; } } ResolvedFixedCouponBond bond = basket.get(indexCTD); PointSensitivityBuilder pointSensi = bondPricer.dirtyPriceSensitivity(bond, discountingProvider, future.getLastDeliveryDate()); return pointSensi.multipliedBy(1d / future.getConversionFactors().get(indexCTD)).build(); }
From source file:com.google.api.codegen.php.PhpGapicContext.java
public Method getFirstMethod(Interface service) { ImmutableList<Method> methods = service.getMethods(); if (methods.size() > 0) { return methods.get(0); }//from ww w.j a va2s. c om throw new RuntimeException("No methods available."); }
From source file:com.opengamma.strata.pricer.bond.DiscountingBondFutureProductPricer.java
/** * Calculates the price sensitivity of the bond future product with z-spread. * <p>/* w ww .ja v a2 s. c om*/ * The price sensitivity of the product is the sensitivity of the price to the underlying curves. * <p> * The z-spread is a parallel shift applied to continuously compounded rates or periodic compounded rates * of the issuer discounting curve. * <p> * Note that the price sensitivity should be no currency. * * @param future the future * @param discountingProvider the discounting provider * @param zSpread the z-spread * @param compoundedRateType the compounded rate type * @param periodPerYear the number of periods per year * @return the price curve sensitivity of the product */ public PointSensitivities priceSensitivityWithZSpread(ResolvedBondFuture future, LegalEntityDiscountingProvider discountingProvider, double zSpread, CompoundedRateType compoundedRateType, int periodPerYear) { ImmutableList<ResolvedFixedCouponBond> basket = future.getDeliveryBasket(); int size = basket.size(); double[] priceBonds = new double[size]; int indexCTD = 0; double priceMin = 2d; for (int i = 0; i < size; i++) { ResolvedFixedCouponBond bond = basket.get(i); double dirtyPrice = bondPricer.dirtyPriceFromCurvesWithZSpread(bond, discountingProvider, zSpread, compoundedRateType, periodPerYear, future.getLastDeliveryDate()); priceBonds[i] = bondPricer.cleanPriceFromDirtyPrice(bond, future.getLastDeliveryDate(), dirtyPrice) / future.getConversionFactors().get(i); if (priceBonds[i] < priceMin) { priceMin = priceBonds[i]; indexCTD = i; } } ResolvedFixedCouponBond bond = basket.get(indexCTD); PointSensitivityBuilder pointSensi = bondPricer.dirtyPriceSensitivityWithZspread(bond, discountingProvider, zSpread, compoundedRateType, periodPerYear, future.getLastDeliveryDate()); return pointSensi.multipliedBy(1d / future.getConversionFactors().get(indexCTD)).build(); }
From source file:com.google.template.soy.pysrc.internal.PySrcMain.java
/** * Generates Python source files given a Soy parse tree, an options object, and information on * where to put the output files./*from w w w . ja v a2 s . c o m*/ * * @param soyTree The Soy parse tree to generate Python source code for. * @param pySrcOptions The compilation options relevant to this backend. * @param outputPathFormat The format string defining how to build the output file path * corresponding to an input file path. * @param inputPathsPrefix The input path prefix, or empty string if none. * @throws SoySyntaxException If a syntax error is found. * @throws IOException If there is an error in opening/writing an output Python file. */ public void genPyFiles(SoyFileSetNode soyTree, SoyPySrcOptions pySrcOptions, String outputPathFormat, String inputPathsPrefix) throws SoySyntaxException, IOException { List<String> pyFileContents = genPySrc(soyTree, pySrcOptions); ImmutableList<SoyFileNode> srcsToCompile = ImmutableList .copyOf(Iterables.filter(soyTree.getChildren(), SoyFileNode.MATCH_SRC_FILENODE)); if (srcsToCompile.size() != pyFileContents.size()) { throw new AssertionError(String.format("Expected to generate %d code chunk(s), got %d", srcsToCompile.size(), pyFileContents.size())); } Multimap<String, Integer> outputs = MainEntryPointUtils.mapOutputsToSrcs(null, outputPathFormat, inputPathsPrefix, srcsToCompile); for (String outputFilePath : outputs.keySet()) { Writer out = Files.newWriter(new File(outputFilePath), Charsets.UTF_8); try { for (int inputFileIndex : outputs.get(outputFilePath)) { out.write(pyFileContents.get(inputFileIndex)); } } finally { out.close(); } } }
From source file:com.facebook.buck.remoteexecution.grpc.GrpcCasBlobUploader.java
@Override public ImmutableList<UploadResult> batchUpdateBlobs(ImmutableList<UploadData> blobs) throws IOException { long totalBlobSizeBytes = blobs.stream().mapToLong(blob -> blob.digest.getSize()).sum(); try (Scope unused = CasBlobUploadEvent.sendEvent(buckEventBus, blobs.size(), totalBlobSizeBytes)) { BatchUpdateBlobsRequest.Builder requestBuilder = BatchUpdateBlobsRequest.newBuilder(); for (UploadData blob : blobs) { try (InputStream dataStream = blob.data.get()) { requestBuilder.addRequests(BatchUpdateBlobsRequest.Request.newBuilder() .setDigest(GrpcProtocol.get(blob.digest)).setData(ByteString.readFrom(dataStream))); }/*from w ww .j a v a 2 s .co m*/ } BatchUpdateBlobsResponse batchUpdateBlobsResponse = storageStub.batchUpdateBlobs(requestBuilder.build()) .get(); ImmutableList.Builder<UploadResult> resultBuilder = ImmutableList.builder(); for (Response response : batchUpdateBlobsResponse.getResponsesList()) { resultBuilder.add(new UploadResult(new GrpcDigest(response.getDigest()), response.getStatus().getCode(), response.getStatus().getMessage())); } return resultBuilder.build(); } catch (InterruptedException | ExecutionException e) { MoreThrowables.throwIfInitialCauseInstanceOf(e, IOException.class); throw new BuckUncheckedExecutionException(e, "When uploading a batch of blobs: <%s>. Digests: %s.", blobs.stream().map(b -> b.data.describe()).collect(Collectors.joining(">, <")), blobs.stream().map(b -> b.digest.toString()).collect(Collectors.joining(" "))); } }
From source file:org.waveprotocol.box.server.persistence.blocks.impl.SegmentOperationImpl.java
public SegmentOperationImpl(WaveletOperation... operations) { ImmutableList.Builder<WaveletOperation> operationsListBuilder = ImmutableList.builder(); Preconditions.checkArgument(operations.length != 0, "No operations"); for (WaveletOperation operation : operations) { operationsListBuilder.add(operation); }/*w w w .j a v a2 s . c o m*/ ImmutableList<WaveletOperation> operationsList = operationsListBuilder.build(); rawOperation = new RawOperation(GsonSerializer.OPERATION_SERIALIZER, operationsList, operationsList.get(operationsList.size() - 1).getContext()); }
From source file:com.github.rinde.rinsim.central.Solvers.java
/** * Computes a {@link StatisticsDTO} instance for the given * {@link GlobalStateObject} and routes. For each vehicle in the state the * specified route is used and its arrival times, tardiness and travel times * are computed. The resulting {@link StatisticsDTO} has the same properties * as performing a simulation with the same state. However, since the current * state may be half-way a simulation, it is possible that the returned * statistics describe only a partial simulation. As a result * {@link StatisticsDTO#totalDeliveries} does not necessarily equal * {@link StatisticsDTO#totalPickups}.//w w w . jav a2 s. com * @param state The state which represents a simulation. * @param routes Specifies the route the vehicles are currently following, * must be of same size as the number of vehicles (one route per * vehicle). If this is <code>null</code> the * {@link VehicleStateObject#getRoute()} field must be set instead * for <b>each</b> vehicle. * @return The statistics that will be generated when executing this * simulation. */ public static ExtendedStats computeStats(GlobalStateObject state, @Nullable ImmutableList<ImmutableList<Parcel>> routes) { final Optional<ImmutableList<ImmutableList<Parcel>>> r = Optional.fromNullable(routes); if (r.isPresent()) { checkArgument(state.getVehicles().size() == r.get().size(), "Exactly one route should be supplied for every vehicle in state. %s " + "vehicle(s) in state, received %s route(s).", state.getVehicles().size(), r.get().size()); } double totalDistance = 0; int totalDeliveries = 0; int totalPickups = 0; long pickupTardiness = 0; long deliveryTardiness = 0; long overTime = 0; final long startTime = state.getTime(); long maxTime = 0; int movedVehicles = 0; final Set<Parcel> parcels = newHashSet(); final ImmutableList.Builder<ImmutableList<Long>> arrivalTimesBuilder = ImmutableList.builder(); for (int i = 0; i < state.getVehicles().size(); i++) { final VehicleStateObject vso = state.getVehicles().get(i); checkArgument(r.isPresent() || vso.getRoute().isPresent(), "Vehicle routes must either be specified as an argument or must be part" + " of the state object."); final ImmutableList.Builder<Long> truckArrivalTimesBuilder = ImmutableList.builder(); truckArrivalTimesBuilder.add(state.getTime()); ImmutableList<Parcel> route; if (r.isPresent()) { route = r.get().get(i); } else { route = vso.getRoute().get(); } parcels.addAll(route); long time = state.getTime(); Point vehicleLocation = vso.getLocation(); final Measure<Double, Velocity> speed = Measure.valueOf(vso.getDto().getSpeed(), state.getSpeedUnit()); final Set<Parcel> seen = newHashSet(); for (int j = 0; j < route.size(); j++) { final Parcel cur = route.get(j); final boolean inCargo = vso.getContents().contains(cur) || seen.contains(cur); seen.add(cur); if (vso.getDestination().isPresent() && j == 0) { checkArgument(vso.getDestination().asSet().contains(cur), "If a vehicle has a destination, the first position in the route " + "must equal this. Expected %s, is %s.", vso.getDestination().get(), cur); } boolean firstAndServicing = false; if (j == 0 && vso.getRemainingServiceTime() > 0) { // we are already at the service location firstAndServicing = true; truckArrivalTimesBuilder.add(time); time += vso.getRemainingServiceTime(); } else { // vehicle is not there yet, go there first, then service final Point nextLoc = inCargo ? cur.getDeliveryLocation() : cur.getPickupLocation(); final Measure<Double, Length> distance = Measure .valueOf(Point.distance(vehicleLocation, nextLoc), state.getDistUnit()); totalDistance += distance.getValue(); vehicleLocation = nextLoc; final long tt = DoubleMath.roundToLong( RoadModels.computeTravelTime(speed, distance, state.getTimeUnit()), RoundingMode.CEILING); time += tt; } if (inCargo) { // check if we are early if (cur.getDeliveryTimeWindow().isBeforeStart(time)) { time = cur.getDeliveryTimeWindow().begin(); } if (!firstAndServicing) { truckArrivalTimesBuilder.add(time); time += cur.getDeliveryDuration(); } // delivering if (cur.getDeliveryTimeWindow().isAfterEnd(time)) { final long tardiness = time - cur.getDeliveryTimeWindow().end(); deliveryTardiness += tardiness; } totalDeliveries++; } else { // check if we are early if (cur.getPickupTimeWindow().isBeforeStart(time)) { time = cur.getPickupTimeWindow().begin(); } if (!firstAndServicing) { truckArrivalTimesBuilder.add(time); time += cur.getPickupDuration(); } // picking up if (cur.getPickupTimeWindow().isAfterEnd(time)) { final long tardiness = time - cur.getPickupTimeWindow().end(); pickupTardiness += tardiness; } totalPickups++; } } // go to depot final Measure<Double, Length> distance = Measure .valueOf(Point.distance(vehicleLocation, vso.getDto().getStartPosition()), state.getDistUnit()); totalDistance += distance.getValue(); final long tt = DoubleMath.roundToLong( RoadModels.computeTravelTime(speed, distance, state.getTimeUnit()), RoundingMode.CEILING); time += tt; // check overtime if (vso.getDto().getAvailabilityTimeWindow().isAfterEnd(time)) { overTime += time - vso.getDto().getAvailabilityTimeWindow().end(); } maxTime = Math.max(maxTime, time); truckArrivalTimesBuilder.add(time); arrivalTimesBuilder.add(truckArrivalTimesBuilder.build()); if (time > startTime) { // time has progressed -> the vehicle has moved movedVehicles++; } } final int totalParcels = parcels.size(); final int totalVehicles = state.getVehicles().size(); final long simulationTime = maxTime - startTime; return new ExtendedStats(totalDistance, totalPickups, totalDeliveries, totalParcels, totalParcels, pickupTardiness, deliveryTardiness, 0, simulationTime, true, totalVehicles, overTime, totalVehicles, movedVehicles, state.getTimeUnit(), state.getDistUnit(), state.getSpeedUnit(), arrivalTimesBuilder.build()); }
From source file:blockplus.transport.BlockplusGame.java
@Override public IGame<Context> connect(final IClient newClient) { final ImmutableList<IClient> clients = new ImmutableList.Builder<IClient>().addAll(this.getClients()) .add(newClient).build();/*from w ww . j a v a2 s . c om*/ BlockplusGame newGame = null; if (clients.size() == this.getCapacity()) { newGame = new BlockplusGame(this.ordinal, clients, new Builder().build(), this.isPaused); } else { newGame = new BlockplusGame(this.ordinal, clients, this.context, this.isPaused); } return newGame; }
From source file:org.cyclop.service.importer.intern.ParallelQueryImporter.java
private List<Future<Void>> startWorkers(ImmutableList<CqlQuery> queries, ResultWriter resultWriter, StatsCollector status, ImportConfig iconfig, QueryHistory history) { final int queriesSize = queries.size(); final int proThread = Math.max(1, queriesSize / conf.queryImport.maxThreadsProImport); LOG.debug("Starting parallel import for {} queries, {} pro thread", queriesSize, proThread); Session cassSession = session.getSession(); List<Future<Void>> futures = new ArrayList<>(); int startIndex = 0; int remaining = queriesSize; while (remaining > 0) { remaining -= proThread;//from w ww .j a va 2 s. co m int amount = remaining > 0 ? proThread : remaining + proThread; LOG.debug("Starting thread with start index: {} and amount: {}, remaining: {}", startIndex, amount, remaining); ImportWorker task = new ImportWorker(startIndex, amount, queries, status, iconfig, resultWriter, cassSession, history); Future<Void> future = executor.submit(task); futures.add(future); startIndex += amount; } return futures; }