List of usage examples for com.google.common.collect Iterables getOnlyElement
public static <T> T getOnlyElement(Iterable<T> iterable)
From source file:com.opengamma.financial.analytics.model.forex.forward.FXForwardPointsMethodYCNSFunction.java
@Override protected Set<ComputedValue> getResult(final Forex fxForward, final YieldCurveBundle data, final DoublesCurve forwardPoints, final ComputationTarget target, final Set<ValueRequirement> desiredValues, final FunctionInputs inputs, final FunctionExecutionContext executionContext, final FXForwardCurveDefinition fxForwardCurveDefinition) { final InterpolatedYieldCurveSpecificationWithSecurities curveSpec = (InterpolatedYieldCurveSpecificationWithSecurities) inputs .getValue(ValueRequirementNames.YIELD_CURVE_SPEC); final MultipleCurrencyInterestRateCurveSensitivity sensitivities = CALCULATOR .presentValueCurveSensitivity(fxForward, data, forwardPoints); final String currency = ((FinancialSecurity) target.getSecurity()) .accept(ForexVisitors.getReceiveCurrencyVisitor()).getCode(); final ValueProperties properties = getResultProperties(Iterables.getOnlyElement(desiredValues), currency) .get();/*w ww.j a va 2 s . c om*/ final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.YIELD_CURVE_NODE_SENSITIVITIES, target.toSpecification(), properties); final String curveName = Iterables.getOnlyElement(properties.getValues(ValuePropertyNames.CURVE)); return null; //return YieldCurveNodeSensitivitiesHelper.getInstrumentLabelledSensitivitiesForCurve(curveName, data, properties, curveSpec, spec); }
From source file:com.cloudera.oryx.als.computation.iterate.row.RowReduceFn.java
@Override public MatrixRow map(Pair<Long, Iterable<LongFloatMap>> input) { LongFloatMap values = Iterables.getOnlyElement(input.second()); LongObjectMap<float[]> Y = yState.getY(); RealMatrix YTY = yState.getYTY();//from ww w .j a v a2 s. co m // Start computing Wu = (YT*Cu*Y + lambda*I) = (YT*Y + YT*(Cu-I)*Y + lambda*I), // by first starting with a copy of YT * Y. Or, a variant on YT * Y, if LOSS_IGNORES_UNSPECIFIED is set RealMatrix Wu; if (lossIgnoresUnspecified) { Wu = partialTransposeTimesSelf(Y, YTY.getRowDimension(), values.entrySet()); } else { Wu = YTY.copy(); } double[][] WuData = MatrixUtils.accessMatrixDataDirectly(Wu); int features = Wu.getRowDimension(); double[] YTCupu = new double[features]; for (LongFloatMap.MapEntry entry : values.entrySet()) { double xu = entry.getValue(); long itemID = entry.getKey(); float[] vector = Y.get(itemID); Preconditions.checkNotNull(vector, "No feature vector for %s", itemID); // Wu and YTCupu if (reconstructRMatrix) { for (int row = 0; row < features; row++) { YTCupu[row] += xu * vector[row]; } } else { double cu = 1.0 + alpha * FastMath.abs(xu); for (int row = 0; row < features; row++) { float vectorAtRow = vector[row]; double rowValue = vectorAtRow * (cu - 1.0); double[] WuDataRow = WuData[row]; for (int col = 0; col < features; col++) { WuDataRow[col] += rowValue * vector[col]; //Wu.addToEntry(row, col, rowValue * vector[col]); } if (xu > 0.0) { YTCupu[row] += vectorAtRow * cu; } } } } Preconditions.checkState(!values.isEmpty(), "No values for user {}?", input.first()); double lambdaTimesCount = lambda * values.size(); for (int x = 0; x < features; x++) { WuData[x][x] += lambdaTimesCount; //Wu.addToEntry(x, x, lambdaTimesCount); } float[] xu = MatrixUtils.getSolver(Wu).solveDToF(YTCupu); return new MatrixRow(input.first(), xu); }
From source file:com.google.errorprone.bugpatterns.time.JodaDurationConstructor.java
@Override public Description matchNewClass(NewClassTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return Description.NO_MATCH; }/*from w w w . ja v a 2 s . c o m*/ ExpressionTree millisArg = Iterables.getOnlyElement(tree.getArguments()); SuggestedFix fix = SuggestedFix.replace(((JCTree) tree).getStartPosition(), ((JCTree) millisArg).getStartPosition(), state.getSourceForNode(tree.getIdentifier()) + ".millis("); return describeMatch(tree, fix); }
From source file:io.prestosql.sql.planner.plan.MarkDistinctNode.java
@Override public PlanNode replaceChildren(List<PlanNode> newChildren) { return new MarkDistinctNode(getId(), Iterables.getOnlyElement(newChildren), markerSymbol, distinctSymbols, hashSymbol);/*from w w w .j av a 2 s. c om*/ }
From source file:eu.interedition.text.xml.module.TEIAwareAnnotationXMLTransformerModule.java
@Override public void end(XMLTransformer transformer) { final long textOffset = transformer.getTextOffset(); for (Name milestoneUnit : milestones.keySet()) { final Annotation last = milestones.get(milestoneUnit); Iterables.getOnlyElement(last.getTargets()).setEnd(textOffset); add(transformer, last);//from www. j av a2 s.c o m } this.milestones = null; this.spanning = null; super.end(transformer); }
From source file:com.palantir.example.profile.ProfileStore.java
public UserProfile getUserData(UUID userId) { UserProfileTable table = tables.getUserProfileTable(t); Map<UserProfileRow, UserProfile> result = table.getMetadatas(ImmutableSet.of(UserProfileRow.of(userId))); if (result.isEmpty()) { return null; } else {/* www . j a va 2 s.co m*/ return Iterables.getOnlyElement(result.values()); } }
From source file:com.opengamma.financial.analytics.model.forex.option.black.FXOptionBlackThetaFunction.java
@Override protected Set<ComputedValue> getResult(final InstrumentDerivative forex, final ForexOptionDataBundle<?> data, final ComputationTarget target, final Set<ValueRequirement> desiredValues, final FunctionInputs inputs, final ValueSpecification spec, final FunctionExecutionContext executionContext) { final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues); final ValueProperties constraints = desiredValue.getConstraints(); final ValueProperties.Builder resultProperties = constraints.copy(); final double scale; final Set<String> scaleFactors = constraints.getValues(PROPERTY_DAYS_PER_YEAR); if (scaleFactors.isEmpty()) { scale = DEFAULT_DAYS_PER_YEAR;//from w w w . j ava 2 s . c o m resultProperties.withoutAny(PROPERTY_DAYS_PER_YEAR).with(PROPERTY_DAYS_PER_YEAR, Double.toString(DEFAULT_DAYS_PER_YEAR)); } else { scale = Double.parseDouble(scaleFactors.iterator().next()); } if (data instanceof SmileDeltaTermStructureDataBundle) { final CurrencyAmount result = forex.accept(CALCULATOR, data); return Collections.singleton(new ComputedValue(spec, result.getAmount() / scale)); } throw new OpenGammaRuntimeException("Can only calculate theta for surfaces with smiles"); }
From source file:org.jclouds.trmk.vcloudexpress.suppliers.TerremarkVCloudExpressInternetServiceAndPublicIpAddressSupplier.java
@Override public Entry<InternetService, PublicIpAddress> getNewInternetServiceAndIp(VApp vApp, int port, Protocol protocol) {/*from w w w . jav a 2 s.c o m*/ logger.debug(">> creating InternetService in vDC %s:%s:%d", vApp.getVDC().getHref(), protocol, port); InternetService is = client.addInternetServiceToVDC(vApp.getVDC().getHref(), vApp.getName() + "-" + port, protocol, port, withDescription(String.format("port %d access to serverId: %s name: %s", port, vApp.getName(), vApp.getName()))); PublicIpAddress ip = is.getPublicIpAddress(); Map<InternetService, PublicIpAddress> result = ImmutableMap.<InternetService, PublicIpAddress>of(is, ip); Entry<InternetService, PublicIpAddress> entry = Iterables.getOnlyElement(result.entrySet()); return entry; }
From source file:org.apache.brooklyn.util.yaml.Yamls.java
/** returns the given (yaml-parsed) object as the given yaml type. * <p>/* w w w.j a v a 2 s. c o m*/ * if the object is an iterable or iterator this method will fully expand it as a list. * if the requested type is not an iterable or iterator, and the list contains a single item, this will take that single item. * <p> * in other cases this method simply does a type-check and cast (no other type coercion). * <p> * @throws IllegalArgumentException if the input is an iterable not containing a single element, * and the cast is requested to a non-iterable type * @throws ClassCastException if cannot be casted */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> T getAs(Object x, Class<T> type) { if (x == null) return null; if (x instanceof Iterable || x instanceof Iterator) { List result = new ArrayList(); Iterator xi; if (Iterator.class.isAssignableFrom(x.getClass())) { xi = (Iterator) x; } else { xi = ((Iterable) x).iterator(); } while (xi.hasNext()) { result.add(xi.next()); } if (type.isAssignableFrom(List.class)) return (T) result; if (type.isAssignableFrom(Iterator.class)) return (T) result.iterator(); x = Iterables.getOnlyElement(result); } if (type.isInstance(x)) return (T) x; throw new ClassCastException("Cannot convert " + x + " (" + x.getClass() + ") to " + type); }
From source file:com.b2international.index.mapping.Mappings.java
public DocumentMapping getByType(String className) { final Collection<DocumentMapping> mappings = Lists.newArrayList(); for (DocumentMapping mapping : mappingsByType.values()) { if (mapping.type().getName().equals(className)) { mappings.add(mapping);/*from www . ja v a 2s . com*/ } } return Iterables.getOnlyElement(mappings); }