id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
159,900
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/bond/Bond.java
Bond.getAccruedInterest
public double getAccruedInterest(LocalDate date, AnalyticModel model) { int periodIndex=schedule.getPeriodIndex(date); Period period=schedule.getPeriod(periodIndex); DayCountConvention dcc= schedule.getDaycountconvention(); double accruedInterest=getCouponPayment(periodIndex,model)*(dcc.getDaycountFraction(period.getPeriodStart(), date))/schedule.getPeriodLength(periodIndex); return accruedInterest; }
java
public double getAccruedInterest(LocalDate date, AnalyticModel model) { int periodIndex=schedule.getPeriodIndex(date); Period period=schedule.getPeriod(periodIndex); DayCountConvention dcc= schedule.getDaycountconvention(); double accruedInterest=getCouponPayment(periodIndex,model)*(dcc.getDaycountFraction(period.getPeriodStart(), date))/schedule.getPeriodLength(periodIndex); return accruedInterest; }
[ "public", "double", "getAccruedInterest", "(", "LocalDate", "date", ",", "AnalyticModel", "model", ")", "{", "int", "periodIndex", "=", "schedule", ".", "getPeriodIndex", "(", "date", ")", ";", "Period", "period", "=", "schedule", ".", "getPeriod", "(", "periodIndex", ")", ";", "DayCountConvention", "dcc", "=", "schedule", ".", "getDaycountconvention", "(", ")", ";", "double", "accruedInterest", "=", "getCouponPayment", "(", "periodIndex", ",", "model", ")", "*", "(", "dcc", ".", "getDaycountFraction", "(", "period", ".", "getPeriodStart", "(", ")", ",", "date", ")", ")", "/", "schedule", ".", "getPeriodLength", "(", "periodIndex", ")", ";", "return", "accruedInterest", ";", "}" ]
Returns the accrued interest of the bond for a given date. @param date The date of interest. @param model The model under which the product is valued. @return The accrued interest.
[ "Returns", "the", "accrued", "interest", "of", "the", "bond", "for", "a", "given", "date", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/bond/Bond.java#L309-L315
159,901
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/bond/Bond.java
Bond.getAccruedInterest
public double getAccruedInterest(double time, AnalyticModel model) { LocalDate date= FloatingpointDate.getDateFromFloatingPointDate(schedule.getReferenceDate(), time); return getAccruedInterest(date, model); }
java
public double getAccruedInterest(double time, AnalyticModel model) { LocalDate date= FloatingpointDate.getDateFromFloatingPointDate(schedule.getReferenceDate(), time); return getAccruedInterest(date, model); }
[ "public", "double", "getAccruedInterest", "(", "double", "time", ",", "AnalyticModel", "model", ")", "{", "LocalDate", "date", "=", "FloatingpointDate", ".", "getDateFromFloatingPointDate", "(", "schedule", ".", "getReferenceDate", "(", ")", ",", "time", ")", ";", "return", "getAccruedInterest", "(", "date", ",", "model", ")", ";", "}" ]
Returns the accrued interest of the bond for a given time. @param time The time of interest as double. @param model The model under which the product is valued. @return The accrued interest.
[ "Returns", "the", "accrued", "interest", "of", "the", "bond", "for", "a", "given", "time", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/bond/Bond.java#L324-L327
159,902
finmath/finmath-lib
src/main/java/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.blackScholesOptionTheta
public static double blackScholesOptionTheta( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate theta double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); double theta = volatility * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0 * Math.PI) / Math.sqrt(optionMaturity) / 2 * initialStockValue + riskFreeRate * optionStrike * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus); return theta; } }
java
public static double blackScholesOptionTheta( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate theta double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); double theta = volatility * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0 * Math.PI) / Math.sqrt(optionMaturity) / 2 * initialStockValue + riskFreeRate * optionStrike * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus); return theta; } }
[ "public", "static", "double", "blackScholesOptionTheta", "(", "double", "initialStockValue", ",", "double", "riskFreeRate", ",", "double", "volatility", ",", "double", "optionMaturity", ",", "double", "optionStrike", ")", "{", "if", "(", "optionStrike", "<=", "0.0", "||", "optionMaturity", "<=", "0.0", ")", "{", "// The Black-Scholes model does not consider it being an option", "return", "0.0", ";", "}", "else", "{", "// Calculate theta", "double", "dPlus", "=", "(", "Math", ".", "log", "(", "initialStockValue", "/", "optionStrike", ")", "+", "(", "riskFreeRate", "+", "0.5", "*", "volatility", "*", "volatility", ")", "*", "optionMaturity", ")", "/", "(", "volatility", "*", "Math", ".", "sqrt", "(", "optionMaturity", ")", ")", ";", "double", "dMinus", "=", "dPlus", "-", "volatility", "*", "Math", ".", "sqrt", "(", "optionMaturity", ")", ";", "double", "theta", "=", "volatility", "*", "Math", ".", "exp", "(", "-", "0.5", "*", "dPlus", "*", "dPlus", ")", "/", "Math", ".", "sqrt", "(", "2.0", "*", "Math", ".", "PI", ")", "/", "Math", ".", "sqrt", "(", "optionMaturity", ")", "/", "2", "*", "initialStockValue", "+", "riskFreeRate", "*", "optionStrike", "*", "Math", ".", "exp", "(", "-", "riskFreeRate", "*", "optionMaturity", ")", "*", "NormalDistribution", ".", "cumulativeDistribution", "(", "dMinus", ")", ";", "return", "theta", ";", "}", "}" ]
This static method calculated the vega of a call option under a Black-Scholes model @param initialStockValue The initial value of the underlying, i.e., the spot. @param riskFreeRate The risk free rate of the bank account numerarie. @param volatility The Black-Scholes volatility. @param optionMaturity The option maturity T. @param optionStrike The option strike. @return The vega of the option
[ "This", "static", "method", "calculated", "the", "vega", "of", "a", "call", "option", "under", "a", "Black", "-", "Scholes", "model" ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/functions/AnalyticFormulas.java#L439-L461
159,903
finmath/finmath-lib
src/main/java6/net/finmath/montecarlo/AbstractMonteCarloProduct.java
AbstractMonteCarloProduct.getValues
public Map<String, Object> getValues(double evaluationTime, MonteCarloSimulationInterface model) throws CalculationException { RandomVariableInterface values = getValue(evaluationTime, model); if(values == null) { return null; } // Sum up values on path double value = values.getAverage(); double error = values.getStandardError(); Map<String, Object> results = new HashMap<String, Object>(); results.put("value", value); results.put("error", error); return results; }
java
public Map<String, Object> getValues(double evaluationTime, MonteCarloSimulationInterface model) throws CalculationException { RandomVariableInterface values = getValue(evaluationTime, model); if(values == null) { return null; } // Sum up values on path double value = values.getAverage(); double error = values.getStandardError(); Map<String, Object> results = new HashMap<String, Object>(); results.put("value", value); results.put("error", error); return results; }
[ "public", "Map", "<", "String", ",", "Object", ">", "getValues", "(", "double", "evaluationTime", ",", "MonteCarloSimulationInterface", "model", ")", "throws", "CalculationException", "{", "RandomVariableInterface", "values", "=", "getValue", "(", "evaluationTime", ",", "model", ")", ";", "if", "(", "values", "==", "null", ")", "{", "return", "null", ";", "}", "// Sum up values on path", "double", "value", "=", "values", ".", "getAverage", "(", ")", ";", "double", "error", "=", "values", ".", "getStandardError", "(", ")", ";", "Map", "<", "String", ",", "Object", ">", "results", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "results", ".", "put", "(", "\"value\"", ",", "value", ")", ";", "results", ".", "put", "(", "\"error\"", ",", "error", ")", ";", "return", "results", ";", "}" ]
This method returns the value of the product under the specified model and other information in a key-value map. @param evaluationTime The time on which this products value should be observed. @param model A model used to evaluate the product. @return The values of the product. @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
[ "This", "method", "returns", "the", "value", "of", "the", "product", "under", "the", "specified", "model", "and", "other", "information", "in", "a", "key", "-", "value", "map", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/AbstractMonteCarloProduct.java#L113-L130
159,904
finmath/finmath-lib
src/main/java6/net/finmath/interpolation/RationalFunctionInterpolation.java
RationalFunctionInterpolation.getValue
public double getValue(double x) { synchronized(interpolatingRationalFunctionsLazyInitLock) { if(interpolatingRationalFunctions == null) { doCreateRationalFunctions(); } } // Get interpolating rational function for the given point x int pointIndex = java.util.Arrays.binarySearch(points, x); if(pointIndex >= 0) { return values[pointIndex]; } int intervallIndex = -pointIndex-2; // Check for extrapolation if(intervallIndex < 0) { // Extrapolation if(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) { return values[0]; } else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) { return values[0]+(values[1]-values[0])/(points[1]-points[0])*(x-points[0]); } else { intervallIndex = 0; } } else if(intervallIndex > points.length-2) { // Extrapolation if(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) { return values[points.length-1]; } else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) { return values[points.length-1]+(values[points.length-2]-values[points.length-1])/(points[points.length-2]-points[points.length-1])*(x-points[points.length-1]); } else { intervallIndex = points.length-2; } } RationalFunction rationalFunction = interpolatingRationalFunctions[intervallIndex]; // Calculate interpolating value return rationalFunction.getValue(x-points[intervallIndex]); }
java
public double getValue(double x) { synchronized(interpolatingRationalFunctionsLazyInitLock) { if(interpolatingRationalFunctions == null) { doCreateRationalFunctions(); } } // Get interpolating rational function for the given point x int pointIndex = java.util.Arrays.binarySearch(points, x); if(pointIndex >= 0) { return values[pointIndex]; } int intervallIndex = -pointIndex-2; // Check for extrapolation if(intervallIndex < 0) { // Extrapolation if(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) { return values[0]; } else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) { return values[0]+(values[1]-values[0])/(points[1]-points[0])*(x-points[0]); } else { intervallIndex = 0; } } else if(intervallIndex > points.length-2) { // Extrapolation if(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) { return values[points.length-1]; } else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) { return values[points.length-1]+(values[points.length-2]-values[points.length-1])/(points[points.length-2]-points[points.length-1])*(x-points[points.length-1]); } else { intervallIndex = points.length-2; } } RationalFunction rationalFunction = interpolatingRationalFunctions[intervallIndex]; // Calculate interpolating value return rationalFunction.getValue(x-points[intervallIndex]); }
[ "public", "double", "getValue", "(", "double", "x", ")", "{", "synchronized", "(", "interpolatingRationalFunctionsLazyInitLock", ")", "{", "if", "(", "interpolatingRationalFunctions", "==", "null", ")", "{", "doCreateRationalFunctions", "(", ")", ";", "}", "}", "// Get interpolating rational function for the given point x", "int", "pointIndex", "=", "java", ".", "util", ".", "Arrays", ".", "binarySearch", "(", "points", ",", "x", ")", ";", "if", "(", "pointIndex", ">=", "0", ")", "{", "return", "values", "[", "pointIndex", "]", ";", "}", "int", "intervallIndex", "=", "-", "pointIndex", "-", "2", ";", "// Check for extrapolation", "if", "(", "intervallIndex", "<", "0", ")", "{", "// Extrapolation", "if", "(", "this", ".", "extrapolationMethod", "==", "ExtrapolationMethod", ".", "CONSTANT", ")", "{", "return", "values", "[", "0", "]", ";", "}", "else", "if", "(", "this", ".", "extrapolationMethod", "==", "ExtrapolationMethod", ".", "LINEAR", ")", "{", "return", "values", "[", "0", "]", "+", "(", "values", "[", "1", "]", "-", "values", "[", "0", "]", ")", "/", "(", "points", "[", "1", "]", "-", "points", "[", "0", "]", ")", "*", "(", "x", "-", "points", "[", "0", "]", ")", ";", "}", "else", "{", "intervallIndex", "=", "0", ";", "}", "}", "else", "if", "(", "intervallIndex", ">", "points", ".", "length", "-", "2", ")", "{", "// Extrapolation", "if", "(", "this", ".", "extrapolationMethod", "==", "ExtrapolationMethod", ".", "CONSTANT", ")", "{", "return", "values", "[", "points", ".", "length", "-", "1", "]", ";", "}", "else", "if", "(", "this", ".", "extrapolationMethod", "==", "ExtrapolationMethod", ".", "LINEAR", ")", "{", "return", "values", "[", "points", ".", "length", "-", "1", "]", "+", "(", "values", "[", "points", ".", "length", "-", "2", "]", "-", "values", "[", "points", ".", "length", "-", "1", "]", ")", "/", "(", "points", "[", "points", ".", "length", "-", "2", "]", "-", "points", "[", "points", ".", "length", "-", "1", "]", ")", "*", "(", "x", "-", "points", "[", "points", ".", "length", "-", "1", "]", ")", ";", "}", "else", "{", "intervallIndex", "=", "points", ".", "length", "-", "2", ";", "}", "}", "RationalFunction", "rationalFunction", "=", "interpolatingRationalFunctions", "[", "intervallIndex", "]", ";", "// Calculate interpolating value", "return", "rationalFunction", ".", "getValue", "(", "x", "-", "points", "[", "intervallIndex", "]", ")", ";", "}" ]
Get an interpolated value for a given argument x. @param x The abscissa at which the interpolation should be performed. @return The interpolated value (ordinate).
[ "Get", "an", "interpolated", "value", "for", "a", "given", "argument", "x", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/interpolation/RationalFunctionInterpolation.java#L186-L228
159,905
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/automaticdifferentiation/backward/alternative/RandomVariableUniqueVariable.java
RandomVariableUniqueVariable.getGradient
public RandomVariable[] getGradient(){ // for now let us take the case for output-dimension equal to one! int numberOfVariables = getNumberOfVariablesInList(); int numberOfCalculationSteps = factory.getNumberOfEntriesInList(); RandomVariable[] omega_hat = new RandomVariable[numberOfCalculationSteps]; // first entry gets initialized omega_hat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0); /* * TODO: Find way that calculations form here on are not 'recorded' by the factory * IDEA: Let the calculation below run on {@link RandomVariableFromDoubleArray}, ie cast everything down! * */ for(int functionIndex = numberOfCalculationSteps - 2; functionIndex > 0; functionIndex--){ // apply chain rule omega_hat[functionIndex] = new RandomVariableFromDoubleArray(0.0); /*TODO: save all D_{i,j}*\omega_j in vector and sum up later */ for(RandomVariableUniqueVariable parent:parentsVariables){ int variableIndex = parent.getVariableID(); omega_hat[functionIndex] = omega_hat[functionIndex].add(getPartialDerivative(functionIndex, variableIndex).mult(omega_hat[variableIndex])); } } /* Due to the fact that we can still introduce 'new' true variables on the fly they are NOT the last couple of indices! * Thus save the indices of the true variables and recover them after finalizing all the calculations * IDEA: quit calculation after minimal true variable index is reached */ RandomVariable[] gradient = new RandomVariable[numberOfVariables]; /* TODO: sort array in correct manner! */ int[] indicesOfVariables = getIDsOfVariablesInList(); for(int i = 0; i < numberOfVariables; i++){ gradient[i] = omega_hat[numberOfCalculationSteps - numberOfVariables + indicesOfVariables[i]]; } return gradient; }
java
public RandomVariable[] getGradient(){ // for now let us take the case for output-dimension equal to one! int numberOfVariables = getNumberOfVariablesInList(); int numberOfCalculationSteps = factory.getNumberOfEntriesInList(); RandomVariable[] omega_hat = new RandomVariable[numberOfCalculationSteps]; // first entry gets initialized omega_hat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0); /* * TODO: Find way that calculations form here on are not 'recorded' by the factory * IDEA: Let the calculation below run on {@link RandomVariableFromDoubleArray}, ie cast everything down! * */ for(int functionIndex = numberOfCalculationSteps - 2; functionIndex > 0; functionIndex--){ // apply chain rule omega_hat[functionIndex] = new RandomVariableFromDoubleArray(0.0); /*TODO: save all D_{i,j}*\omega_j in vector and sum up later */ for(RandomVariableUniqueVariable parent:parentsVariables){ int variableIndex = parent.getVariableID(); omega_hat[functionIndex] = omega_hat[functionIndex].add(getPartialDerivative(functionIndex, variableIndex).mult(omega_hat[variableIndex])); } } /* Due to the fact that we can still introduce 'new' true variables on the fly they are NOT the last couple of indices! * Thus save the indices of the true variables and recover them after finalizing all the calculations * IDEA: quit calculation after minimal true variable index is reached */ RandomVariable[] gradient = new RandomVariable[numberOfVariables]; /* TODO: sort array in correct manner! */ int[] indicesOfVariables = getIDsOfVariablesInList(); for(int i = 0; i < numberOfVariables; i++){ gradient[i] = omega_hat[numberOfCalculationSteps - numberOfVariables + indicesOfVariables[i]]; } return gradient; }
[ "public", "RandomVariable", "[", "]", "getGradient", "(", ")", "{", "// for now let us take the case for output-dimension equal to one!\r", "int", "numberOfVariables", "=", "getNumberOfVariablesInList", "(", ")", ";", "int", "numberOfCalculationSteps", "=", "factory", ".", "getNumberOfEntriesInList", "(", ")", ";", "RandomVariable", "[", "]", "omega_hat", "=", "new", "RandomVariable", "[", "numberOfCalculationSteps", "]", ";", "// first entry gets initialized\r", "omega_hat", "[", "numberOfCalculationSteps", "-", "1", "]", "=", "new", "RandomVariableFromDoubleArray", "(", "1.0", ")", ";", "/*\r\n\t\t * TODO: Find way that calculations form here on are not 'recorded' by the factory\r\n\t\t * IDEA: Let the calculation below run on {@link RandomVariableFromDoubleArray}, ie cast everything down!\r\n\t\t * */", "for", "(", "int", "functionIndex", "=", "numberOfCalculationSteps", "-", "2", ";", "functionIndex", ">", "0", ";", "functionIndex", "--", ")", "{", "// apply chain rule\r", "omega_hat", "[", "functionIndex", "]", "=", "new", "RandomVariableFromDoubleArray", "(", "0.0", ")", ";", "/*TODO: save all D_{i,j}*\\omega_j in vector and sum up later */", "for", "(", "RandomVariableUniqueVariable", "parent", ":", "parentsVariables", ")", "{", "int", "variableIndex", "=", "parent", ".", "getVariableID", "(", ")", ";", "omega_hat", "[", "functionIndex", "]", "=", "omega_hat", "[", "functionIndex", "]", ".", "add", "(", "getPartialDerivative", "(", "functionIndex", ",", "variableIndex", ")", ".", "mult", "(", "omega_hat", "[", "variableIndex", "]", ")", ")", ";", "}", "}", "/* Due to the fact that we can still introduce 'new' true variables on the fly they are NOT the last couple of indices!\r\n\t\t * Thus save the indices of the true variables and recover them after finalizing all the calculations\r\n\t\t * IDEA: quit calculation after minimal true variable index is reached */", "RandomVariable", "[", "]", "gradient", "=", "new", "RandomVariable", "[", "numberOfVariables", "]", ";", "/* TODO: sort array in correct manner! */", "int", "[", "]", "indicesOfVariables", "=", "getIDsOfVariablesInList", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numberOfVariables", ";", "i", "++", ")", "{", "gradient", "[", "i", "]", "=", "omega_hat", "[", "numberOfCalculationSteps", "-", "numberOfVariables", "+", "indicesOfVariables", "[", "i", "]", "]", ";", "}", "return", "gradient", ";", "}" ]
Apply the AAD algorithm to this very variable NOTE: in this case it is indeed correct to assume that the output dimension is "one" meaning that there is only one {@link RandomVariableUniqueVariable} as an output. @return gradient for the built up function
[ "Apply", "the", "AAD", "algorithm", "to", "this", "very", "variable" ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/automaticdifferentiation/backward/alternative/RandomVariableUniqueVariable.java#L712-L754
159,906
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/volatilities/AbstractVolatilitySurfaceParametric.java
AbstractVolatilitySurfaceParametric.getCloneCalibrated
public AbstractVolatilitySurfaceParametric getCloneCalibrated(final AnalyticModel calibrationModel, final Vector<AnalyticProduct> calibrationProducts, final List<Double> calibrationTargetValues, Map<String,Object> calibrationParameters, final ParameterTransformation parameterTransformation, OptimizerFactory optimizerFactory) throws SolverException { if(calibrationParameters == null) { calibrationParameters = new HashMap<>(); } Integer maxIterationsParameter = (Integer)calibrationParameters.get("maxIterations"); Double accuracyParameter = (Double)calibrationParameters.get("accuracy"); Double evaluationTimeParameter = (Double)calibrationParameters.get("evaluationTime"); // @TODO currently ignored, we use the setting form the OptimizerFactory int maxIterations = maxIterationsParameter != null ? maxIterationsParameter.intValue() : 600; double accuracy = accuracyParameter != null ? accuracyParameter.doubleValue() : 1E-8; double evaluationTime = evaluationTimeParameter != null ? evaluationTimeParameter.doubleValue() : 0.0; AnalyticModel model = calibrationModel.addVolatilitySurfaces(this); Solver solver = new Solver(model, calibrationProducts, calibrationTargetValues, parameterTransformation, evaluationTime, optimizerFactory); Set<ParameterObject> objectsToCalibrate = new HashSet<>(); objectsToCalibrate.add(this); AnalyticModel modelCalibrated = solver.getCalibratedModel(objectsToCalibrate); // Diagnostic output if (logger.isLoggable(Level.FINE)) { double lastAccuracy = solver.getAccuracy(); int lastIterations = solver.getIterations(); logger.fine("The solver achieved an accuracy of " + lastAccuracy + " in " + lastIterations + "."); } return (AbstractVolatilitySurfaceParametric)modelCalibrated.getVolatilitySurface(this.getName()); }
java
public AbstractVolatilitySurfaceParametric getCloneCalibrated(final AnalyticModel calibrationModel, final Vector<AnalyticProduct> calibrationProducts, final List<Double> calibrationTargetValues, Map<String,Object> calibrationParameters, final ParameterTransformation parameterTransformation, OptimizerFactory optimizerFactory) throws SolverException { if(calibrationParameters == null) { calibrationParameters = new HashMap<>(); } Integer maxIterationsParameter = (Integer)calibrationParameters.get("maxIterations"); Double accuracyParameter = (Double)calibrationParameters.get("accuracy"); Double evaluationTimeParameter = (Double)calibrationParameters.get("evaluationTime"); // @TODO currently ignored, we use the setting form the OptimizerFactory int maxIterations = maxIterationsParameter != null ? maxIterationsParameter.intValue() : 600; double accuracy = accuracyParameter != null ? accuracyParameter.doubleValue() : 1E-8; double evaluationTime = evaluationTimeParameter != null ? evaluationTimeParameter.doubleValue() : 0.0; AnalyticModel model = calibrationModel.addVolatilitySurfaces(this); Solver solver = new Solver(model, calibrationProducts, calibrationTargetValues, parameterTransformation, evaluationTime, optimizerFactory); Set<ParameterObject> objectsToCalibrate = new HashSet<>(); objectsToCalibrate.add(this); AnalyticModel modelCalibrated = solver.getCalibratedModel(objectsToCalibrate); // Diagnostic output if (logger.isLoggable(Level.FINE)) { double lastAccuracy = solver.getAccuracy(); int lastIterations = solver.getIterations(); logger.fine("The solver achieved an accuracy of " + lastAccuracy + " in " + lastIterations + "."); } return (AbstractVolatilitySurfaceParametric)modelCalibrated.getVolatilitySurface(this.getName()); }
[ "public", "AbstractVolatilitySurfaceParametric", "getCloneCalibrated", "(", "final", "AnalyticModel", "calibrationModel", ",", "final", "Vector", "<", "AnalyticProduct", ">", "calibrationProducts", ",", "final", "List", "<", "Double", ">", "calibrationTargetValues", ",", "Map", "<", "String", ",", "Object", ">", "calibrationParameters", ",", "final", "ParameterTransformation", "parameterTransformation", ",", "OptimizerFactory", "optimizerFactory", ")", "throws", "SolverException", "{", "if", "(", "calibrationParameters", "==", "null", ")", "{", "calibrationParameters", "=", "new", "HashMap", "<>", "(", ")", ";", "}", "Integer", "maxIterationsParameter", "=", "(", "Integer", ")", "calibrationParameters", ".", "get", "(", "\"maxIterations\"", ")", ";", "Double", "accuracyParameter", "=", "(", "Double", ")", "calibrationParameters", ".", "get", "(", "\"accuracy\"", ")", ";", "Double", "evaluationTimeParameter", "=", "(", "Double", ")", "calibrationParameters", ".", "get", "(", "\"evaluationTime\"", ")", ";", "// @TODO currently ignored, we use the setting form the OptimizerFactory", "int", "maxIterations", "=", "maxIterationsParameter", "!=", "null", "?", "maxIterationsParameter", ".", "intValue", "(", ")", ":", "600", ";", "double", "accuracy", "=", "accuracyParameter", "!=", "null", "?", "accuracyParameter", ".", "doubleValue", "(", ")", ":", "1E-8", ";", "double", "evaluationTime", "=", "evaluationTimeParameter", "!=", "null", "?", "evaluationTimeParameter", ".", "doubleValue", "(", ")", ":", "0.0", ";", "AnalyticModel", "model", "=", "calibrationModel", ".", "addVolatilitySurfaces", "(", "this", ")", ";", "Solver", "solver", "=", "new", "Solver", "(", "model", ",", "calibrationProducts", ",", "calibrationTargetValues", ",", "parameterTransformation", ",", "evaluationTime", ",", "optimizerFactory", ")", ";", "Set", "<", "ParameterObject", ">", "objectsToCalibrate", "=", "new", "HashSet", "<>", "(", ")", ";", "objectsToCalibrate", ".", "add", "(", "this", ")", ";", "AnalyticModel", "modelCalibrated", "=", "solver", ".", "getCalibratedModel", "(", "objectsToCalibrate", ")", ";", "// Diagnostic output", "if", "(", "logger", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "double", "lastAccuracy", "=", "solver", ".", "getAccuracy", "(", ")", ";", "int", "lastIterations", "=", "solver", ".", "getIterations", "(", ")", ";", "logger", ".", "fine", "(", "\"The solver achieved an accuracy of \"", "+", "lastAccuracy", "+", "\" in \"", "+", "lastIterations", "+", "\".\"", ")", ";", "}", "return", "(", "AbstractVolatilitySurfaceParametric", ")", "modelCalibrated", ".", "getVolatilitySurface", "(", "this", ".", "getName", "(", ")", ")", ";", "}" ]
Create a clone of this volatility surface using a generic calibration of its parameters to given market data. @param calibrationModel The model used during calibration (contains additional objects required during valuation, e.g. curves). @param calibrationProducts The calibration products. @param calibrationTargetValues The target values of the calibration products. @param calibrationParameters A map containing additional settings like "evaluationTime" (Double). @param parameterTransformation An optional parameter transformation. @param optimizerFactory The factory providing the optimizer to be used during calibration. @return An object having the same type as this one, using (hopefully) calibrated parameters. @throws SolverException Exception thrown when solver fails.
[ "Create", "a", "clone", "of", "this", "volatility", "surface", "using", "a", "generic", "calibration", "of", "its", "parameters", "to", "given", "market", "data", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/AbstractVolatilitySurfaceParametric.java#L81-L110
159,907
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/curves/SeasonalCurve.java
SeasonalCurve.computeSeasonalAdjustments
public static double[] computeSeasonalAdjustments(double[] realizedCPIValues, int lastMonth, int numberOfYearsToAverage) { /* * Cacluate average log returns */ double[] averageLogReturn = new double[12]; Arrays.fill(averageLogReturn, 0.0); for(int arrayIndex = 0; arrayIndex < 12*numberOfYearsToAverage; arrayIndex++){ int month = (((((lastMonth-1 - arrayIndex) % 12) + 12) % 12)); double logReturn = Math.log(realizedCPIValues[realizedCPIValues.length - 1 - arrayIndex] / realizedCPIValues[realizedCPIValues.length - 2 - arrayIndex]); averageLogReturn[month] += logReturn/numberOfYearsToAverage; } /* * Normalize */ double sum = 0.0; for(int index = 0; index < averageLogReturn.length; index++){ sum += averageLogReturn[index]; } double averageSeasonal = sum / averageLogReturn.length; double[] seasonalAdjustments = new double[averageLogReturn.length]; for(int index = 0; index < seasonalAdjustments.length; index++){ seasonalAdjustments[index] = averageLogReturn[index] - averageSeasonal; } // Annualize seasonal adjustments for(int index = 0; index < seasonalAdjustments.length; index++){ seasonalAdjustments[index] = seasonalAdjustments[index] * 12; } return seasonalAdjustments; }
java
public static double[] computeSeasonalAdjustments(double[] realizedCPIValues, int lastMonth, int numberOfYearsToAverage) { /* * Cacluate average log returns */ double[] averageLogReturn = new double[12]; Arrays.fill(averageLogReturn, 0.0); for(int arrayIndex = 0; arrayIndex < 12*numberOfYearsToAverage; arrayIndex++){ int month = (((((lastMonth-1 - arrayIndex) % 12) + 12) % 12)); double logReturn = Math.log(realizedCPIValues[realizedCPIValues.length - 1 - arrayIndex] / realizedCPIValues[realizedCPIValues.length - 2 - arrayIndex]); averageLogReturn[month] += logReturn/numberOfYearsToAverage; } /* * Normalize */ double sum = 0.0; for(int index = 0; index < averageLogReturn.length; index++){ sum += averageLogReturn[index]; } double averageSeasonal = sum / averageLogReturn.length; double[] seasonalAdjustments = new double[averageLogReturn.length]; for(int index = 0; index < seasonalAdjustments.length; index++){ seasonalAdjustments[index] = averageLogReturn[index] - averageSeasonal; } // Annualize seasonal adjustments for(int index = 0; index < seasonalAdjustments.length; index++){ seasonalAdjustments[index] = seasonalAdjustments[index] * 12; } return seasonalAdjustments; }
[ "public", "static", "double", "[", "]", "computeSeasonalAdjustments", "(", "double", "[", "]", "realizedCPIValues", ",", "int", "lastMonth", ",", "int", "numberOfYearsToAverage", ")", "{", "/*\n\t\t * Cacluate average log returns\n\t\t */", "double", "[", "]", "averageLogReturn", "=", "new", "double", "[", "12", "]", ";", "Arrays", ".", "fill", "(", "averageLogReturn", ",", "0.0", ")", ";", "for", "(", "int", "arrayIndex", "=", "0", ";", "arrayIndex", "<", "12", "*", "numberOfYearsToAverage", ";", "arrayIndex", "++", ")", "{", "int", "month", "=", "(", "(", "(", "(", "(", "lastMonth", "-", "1", "-", "arrayIndex", ")", "%", "12", ")", "+", "12", ")", "%", "12", ")", ")", ";", "double", "logReturn", "=", "Math", ".", "log", "(", "realizedCPIValues", "[", "realizedCPIValues", ".", "length", "-", "1", "-", "arrayIndex", "]", "/", "realizedCPIValues", "[", "realizedCPIValues", ".", "length", "-", "2", "-", "arrayIndex", "]", ")", ";", "averageLogReturn", "[", "month", "]", "+=", "logReturn", "/", "numberOfYearsToAverage", ";", "}", "/*\n\t\t * Normalize\n\t\t */", "double", "sum", "=", "0.0", ";", "for", "(", "int", "index", "=", "0", ";", "index", "<", "averageLogReturn", ".", "length", ";", "index", "++", ")", "{", "sum", "+=", "averageLogReturn", "[", "index", "]", ";", "}", "double", "averageSeasonal", "=", "sum", "/", "averageLogReturn", ".", "length", ";", "double", "[", "]", "seasonalAdjustments", "=", "new", "double", "[", "averageLogReturn", ".", "length", "]", ";", "for", "(", "int", "index", "=", "0", ";", "index", "<", "seasonalAdjustments", ".", "length", ";", "index", "++", ")", "{", "seasonalAdjustments", "[", "index", "]", "=", "averageLogReturn", "[", "index", "]", "-", "averageSeasonal", ";", "}", "// Annualize seasonal adjustments", "for", "(", "int", "index", "=", "0", ";", "index", "<", "seasonalAdjustments", ".", "length", ";", "index", "++", ")", "{", "seasonalAdjustments", "[", "index", "]", "=", "seasonalAdjustments", "[", "index", "]", "*", "12", ";", "}", "return", "seasonalAdjustments", ";", "}" ]
Computes annualized seasonal adjustments from given monthly realized CPI values. @param realizedCPIValues An array of consecutive monthly CPI values (minimum size is 12*numberOfYearsToAverage)) @param lastMonth The index of the last month in the sequence of realizedCPIValues (corresponding to the enums in <code>{@link java.time.Month}</code>). @param numberOfYearsToAverage The number of years to go back in the array of realizedCPIValues. @return Array of annualized seasonal adjustments, where [0] corresponds to the adjustment for from December to January.
[ "Computes", "annualized", "seasonal", "adjustments", "from", "given", "monthly", "realized", "CPI", "values", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/curves/SeasonalCurve.java#L176-L211
159,908
finmath/finmath-lib
src/main/java/net/finmath/modelling/productfactory/ProductFactoryCascade.java
ProductFactoryCascade.addFactoryBefore
public ProductFactoryCascade<T> addFactoryBefore(ProductFactory<? extends T> factory) { ArrayList<ProductFactory<? extends T>> factories = new ArrayList<ProductFactory<? extends T>>(this.factories.size()+1); factories.addAll(this.factories); factories.add(0, factory); return new ProductFactoryCascade<>(factories); }
java
public ProductFactoryCascade<T> addFactoryBefore(ProductFactory<? extends T> factory) { ArrayList<ProductFactory<? extends T>> factories = new ArrayList<ProductFactory<? extends T>>(this.factories.size()+1); factories.addAll(this.factories); factories.add(0, factory); return new ProductFactoryCascade<>(factories); }
[ "public", "ProductFactoryCascade", "<", "T", ">", "addFactoryBefore", "(", "ProductFactory", "<", "?", "extends", "T", ">", "factory", ")", "{", "ArrayList", "<", "ProductFactory", "<", "?", "extends", "T", ">", ">", "factories", "=", "new", "ArrayList", "<", "ProductFactory", "<", "?", "extends", "T", ">", ">", "(", "this", ".", "factories", ".", "size", "(", ")", "+", "1", ")", ";", "factories", ".", "addAll", "(", "this", ".", "factories", ")", ";", "factories", ".", "add", "(", "0", ",", "factory", ")", ";", "return", "new", "ProductFactoryCascade", "<>", "(", "factories", ")", ";", "}" ]
Add a given factory to the list of factories at the BEGINNING. @param factory The factory to be added. @return Cascade with amended factory list.
[ "Add", "a", "given", "factory", "to", "the", "list", "of", "factories", "at", "the", "BEGINNING", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/modelling/productfactory/ProductFactoryCascade.java#L49-L54
159,909
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/interestrate/products/ForwardRateVolatilitySurfaceCurvature.java
ForwardRateVolatilitySurfaceCurvature.getValues
public RandomVariable getValues(double evaluationTime, LIBORMarketModel model) { if(evaluationTime > 0) { throw new RuntimeException("Forward start evaluation currently not supported."); } // Fetch the covariance model of the model LIBORCovarianceModel covarianceModel = model.getCovarianceModel(); // We sum over all forward rates int numberOfComponents = covarianceModel.getLiborPeriodDiscretization().getNumberOfTimeSteps(); // Accumulator RandomVariable integratedLIBORCurvature = new RandomVariableFromDoubleArray(0.0); for(int componentIndex = 0; componentIndex < numberOfComponents; componentIndex++) { // Integrate from 0 up to the fixing of the rate double timeEnd = covarianceModel.getLiborPeriodDiscretization().getTime(componentIndex); int timeEndIndex = covarianceModel.getTimeDiscretization().getTimeIndex(timeEnd); // If timeEnd is not in the time discretization we get timeEndIndex = -insertionPoint-1. In that case, we use the index prior to the insertionPoint if(timeEndIndex < 0) { timeEndIndex = -timeEndIndex - 2; } // Sum squared second derivative of the variance for all components at this time step RandomVariable integratedLIBORCurvatureCurrentRate = new RandomVariableFromDoubleArray(0.0); for(int timeIndex = 0; timeIndex < timeEndIndex-2; timeIndex++) { double timeStep1 = covarianceModel.getTimeDiscretization().getTimeStep(timeIndex); double timeStep2 = covarianceModel.getTimeDiscretization().getTimeStep(timeIndex+1); RandomVariable covarianceLeft = covarianceModel.getCovariance(timeIndex+0, componentIndex, componentIndex, null); RandomVariable covarianceCenter = covarianceModel.getCovariance(timeIndex+1, componentIndex, componentIndex, null); RandomVariable covarianceRight = covarianceModel.getCovariance(timeIndex+2, componentIndex, componentIndex, null); // Calculate second derivative RandomVariable curvatureSquared = covarianceRight.sub(covarianceCenter.mult(2.0)).add(covarianceLeft); curvatureSquared = curvatureSquared.div(timeStep1 * timeStep2); // Take square curvatureSquared = curvatureSquared.squared(); // Integrate over time integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.add(curvatureSquared.mult(timeStep1)); } // Empty intervall - skip if(timeEnd == 0) { continue; } // Average over time integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.div(timeEnd); // Take square root integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.sqrt(); // Take max over all forward rates integratedLIBORCurvature = integratedLIBORCurvature.add(integratedLIBORCurvatureCurrentRate); } integratedLIBORCurvature = integratedLIBORCurvature.div(numberOfComponents); return integratedLIBORCurvature.sub(tolerance).floor(0.0); }
java
public RandomVariable getValues(double evaluationTime, LIBORMarketModel model) { if(evaluationTime > 0) { throw new RuntimeException("Forward start evaluation currently not supported."); } // Fetch the covariance model of the model LIBORCovarianceModel covarianceModel = model.getCovarianceModel(); // We sum over all forward rates int numberOfComponents = covarianceModel.getLiborPeriodDiscretization().getNumberOfTimeSteps(); // Accumulator RandomVariable integratedLIBORCurvature = new RandomVariableFromDoubleArray(0.0); for(int componentIndex = 0; componentIndex < numberOfComponents; componentIndex++) { // Integrate from 0 up to the fixing of the rate double timeEnd = covarianceModel.getLiborPeriodDiscretization().getTime(componentIndex); int timeEndIndex = covarianceModel.getTimeDiscretization().getTimeIndex(timeEnd); // If timeEnd is not in the time discretization we get timeEndIndex = -insertionPoint-1. In that case, we use the index prior to the insertionPoint if(timeEndIndex < 0) { timeEndIndex = -timeEndIndex - 2; } // Sum squared second derivative of the variance for all components at this time step RandomVariable integratedLIBORCurvatureCurrentRate = new RandomVariableFromDoubleArray(0.0); for(int timeIndex = 0; timeIndex < timeEndIndex-2; timeIndex++) { double timeStep1 = covarianceModel.getTimeDiscretization().getTimeStep(timeIndex); double timeStep2 = covarianceModel.getTimeDiscretization().getTimeStep(timeIndex+1); RandomVariable covarianceLeft = covarianceModel.getCovariance(timeIndex+0, componentIndex, componentIndex, null); RandomVariable covarianceCenter = covarianceModel.getCovariance(timeIndex+1, componentIndex, componentIndex, null); RandomVariable covarianceRight = covarianceModel.getCovariance(timeIndex+2, componentIndex, componentIndex, null); // Calculate second derivative RandomVariable curvatureSquared = covarianceRight.sub(covarianceCenter.mult(2.0)).add(covarianceLeft); curvatureSquared = curvatureSquared.div(timeStep1 * timeStep2); // Take square curvatureSquared = curvatureSquared.squared(); // Integrate over time integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.add(curvatureSquared.mult(timeStep1)); } // Empty intervall - skip if(timeEnd == 0) { continue; } // Average over time integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.div(timeEnd); // Take square root integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.sqrt(); // Take max over all forward rates integratedLIBORCurvature = integratedLIBORCurvature.add(integratedLIBORCurvatureCurrentRate); } integratedLIBORCurvature = integratedLIBORCurvature.div(numberOfComponents); return integratedLIBORCurvature.sub(tolerance).floor(0.0); }
[ "public", "RandomVariable", "getValues", "(", "double", "evaluationTime", ",", "LIBORMarketModel", "model", ")", "{", "if", "(", "evaluationTime", ">", "0", ")", "{", "throw", "new", "RuntimeException", "(", "\"Forward start evaluation currently not supported.\"", ")", ";", "}", "// Fetch the covariance model of the model", "LIBORCovarianceModel", "covarianceModel", "=", "model", ".", "getCovarianceModel", "(", ")", ";", "// We sum over all forward rates", "int", "numberOfComponents", "=", "covarianceModel", ".", "getLiborPeriodDiscretization", "(", ")", ".", "getNumberOfTimeSteps", "(", ")", ";", "// Accumulator", "RandomVariable", "integratedLIBORCurvature", "=", "new", "RandomVariableFromDoubleArray", "(", "0.0", ")", ";", "for", "(", "int", "componentIndex", "=", "0", ";", "componentIndex", "<", "numberOfComponents", ";", "componentIndex", "++", ")", "{", "// Integrate from 0 up to the fixing of the rate", "double", "timeEnd", "=", "covarianceModel", ".", "getLiborPeriodDiscretization", "(", ")", ".", "getTime", "(", "componentIndex", ")", ";", "int", "timeEndIndex", "=", "covarianceModel", ".", "getTimeDiscretization", "(", ")", ".", "getTimeIndex", "(", "timeEnd", ")", ";", "// If timeEnd is not in the time discretization we get timeEndIndex = -insertionPoint-1. In that case, we use the index prior to the insertionPoint", "if", "(", "timeEndIndex", "<", "0", ")", "{", "timeEndIndex", "=", "-", "timeEndIndex", "-", "2", ";", "}", "// Sum squared second derivative of the variance for all components at this time step", "RandomVariable", "integratedLIBORCurvatureCurrentRate", "=", "new", "RandomVariableFromDoubleArray", "(", "0.0", ")", ";", "for", "(", "int", "timeIndex", "=", "0", ";", "timeIndex", "<", "timeEndIndex", "-", "2", ";", "timeIndex", "++", ")", "{", "double", "timeStep1", "=", "covarianceModel", ".", "getTimeDiscretization", "(", ")", ".", "getTimeStep", "(", "timeIndex", ")", ";", "double", "timeStep2", "=", "covarianceModel", ".", "getTimeDiscretization", "(", ")", ".", "getTimeStep", "(", "timeIndex", "+", "1", ")", ";", "RandomVariable", "covarianceLeft", "=", "covarianceModel", ".", "getCovariance", "(", "timeIndex", "+", "0", ",", "componentIndex", ",", "componentIndex", ",", "null", ")", ";", "RandomVariable", "covarianceCenter", "=", "covarianceModel", ".", "getCovariance", "(", "timeIndex", "+", "1", ",", "componentIndex", ",", "componentIndex", ",", "null", ")", ";", "RandomVariable", "covarianceRight", "=", "covarianceModel", ".", "getCovariance", "(", "timeIndex", "+", "2", ",", "componentIndex", ",", "componentIndex", ",", "null", ")", ";", "// Calculate second derivative", "RandomVariable", "curvatureSquared", "=", "covarianceRight", ".", "sub", "(", "covarianceCenter", ".", "mult", "(", "2.0", ")", ")", ".", "add", "(", "covarianceLeft", ")", ";", "curvatureSquared", "=", "curvatureSquared", ".", "div", "(", "timeStep1", "*", "timeStep2", ")", ";", "// Take square", "curvatureSquared", "=", "curvatureSquared", ".", "squared", "(", ")", ";", "// Integrate over time", "integratedLIBORCurvatureCurrentRate", "=", "integratedLIBORCurvatureCurrentRate", ".", "add", "(", "curvatureSquared", ".", "mult", "(", "timeStep1", ")", ")", ";", "}", "// Empty intervall - skip", "if", "(", "timeEnd", "==", "0", ")", "{", "continue", ";", "}", "// Average over time", "integratedLIBORCurvatureCurrentRate", "=", "integratedLIBORCurvatureCurrentRate", ".", "div", "(", "timeEnd", ")", ";", "// Take square root", "integratedLIBORCurvatureCurrentRate", "=", "integratedLIBORCurvatureCurrentRate", ".", "sqrt", "(", ")", ";", "// Take max over all forward rates", "integratedLIBORCurvature", "=", "integratedLIBORCurvature", ".", "add", "(", "integratedLIBORCurvatureCurrentRate", ")", ";", "}", "integratedLIBORCurvature", "=", "integratedLIBORCurvature", ".", "div", "(", "numberOfComponents", ")", ";", "return", "integratedLIBORCurvature", ".", "sub", "(", "tolerance", ")", ".", "floor", "(", "0.0", ")", ";", "}" ]
Calculates the squared curvature of the LIBOR instantaneous variance. @param evaluationTime Time at which the product is evaluated. @param model A model implementing the LIBORModelMonteCarloSimulationModel @return The squared curvature of the LIBOR instantaneous variance (reduced a possible tolerance). The return value is &ge; 0.
[ "Calculates", "the", "squared", "curvature", "of", "the", "LIBOR", "instantaneous", "variance", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/ForwardRateVolatilitySurfaceCurvature.java#L117-L179
159,910
finmath/finmath-lib
src/main/java6/net/finmath/montecarlo/interestrate/modelplugins/AbstractLIBORCovarianceModel.java
AbstractLIBORCovarianceModel.getFactorLoading
public RandomVariableInterface[] getFactorLoading(double time, double component, RandomVariableInterface[] realizationAtTimeIndex) { int componentIndex = liborPeriodDiscretization.getTimeIndex(component); if(componentIndex < 0) { componentIndex = -componentIndex - 2; } return getFactorLoading(time, componentIndex, realizationAtTimeIndex); }
java
public RandomVariableInterface[] getFactorLoading(double time, double component, RandomVariableInterface[] realizationAtTimeIndex) { int componentIndex = liborPeriodDiscretization.getTimeIndex(component); if(componentIndex < 0) { componentIndex = -componentIndex - 2; } return getFactorLoading(time, componentIndex, realizationAtTimeIndex); }
[ "public", "RandomVariableInterface", "[", "]", "getFactorLoading", "(", "double", "time", ",", "double", "component", ",", "RandomVariableInterface", "[", "]", "realizationAtTimeIndex", ")", "{", "int", "componentIndex", "=", "liborPeriodDiscretization", ".", "getTimeIndex", "(", "component", ")", ";", "if", "(", "componentIndex", "<", "0", ")", "{", "componentIndex", "=", "-", "componentIndex", "-", "2", ";", "}", "return", "getFactorLoading", "(", "time", ",", "componentIndex", ",", "realizationAtTimeIndex", ")", ";", "}" ]
Return the factor loading for a given time and a given component. The factor loading is the vector <i>f<sub>i</sub></i> such that the scalar product <br> <i>f<sub>j</sub>f<sub>k</sub> = f<sub>j,1</sub>f<sub>k,1</sub> + ... + f<sub>j,m</sub>f<sub>k,m</sub></i> <br> is the instantaneous covariance of the component <i>j</i> and <i>k</i>. With respect to simulation time <i>t</i>, this method uses a piece wise constant interpolation, i.e., it calculates <i>t_<sub>i</sub></i> such that <i>t_<sub>i</sub></i> is the largest point in <code>getTimeDiscretization</code> such that <i>t_<sub>i</sub> &le; t </i>. The component here, it given via a double <i>T</i> which may be associated with the LIBOR fixing date. With respect to component time <i>T</i>, this method uses a piece wise constant interpolation, i.e., it calculates <i>T_<sub>j</sub></i> such that <i>T_<sub>j</sub></i> is the largest point in <code>getTimeDiscretization</code> such that <i>T_<sub>j</sub> &le; T </i>. @param time The time <i>t</i> at which factor loading is requested. @param component The component time (as a double associated with the fixing of the forward rate) <i>T<sub>i</sub></i>. @param realizationAtTimeIndex The realization of the stochastic process (may be used to implement local volatility/covariance/correlation models). @return The factor loading <i>f<sub>i</sub>(t)</i>.
[ "Return", "the", "factor", "loading", "for", "a", "given", "time", "and", "a", "given", "component", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/interestrate/modelplugins/AbstractLIBORCovarianceModel.java#L63-L69
159,911
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaptionFromSwapSchedules.java
BermudanSwaptionFromSwapSchedules.getValueUnderlyingNumeraireRelative
private RandomVariable getValueUnderlyingNumeraireRelative(LIBORModelMonteCarloSimulationModel model, Schedule legSchedule, boolean paysFloat, double swaprate, double notional) throws CalculationException { RandomVariable value = model.getRandomVariableForConstant(0.0); for(int periodIndex = legSchedule.getNumberOfPeriods() - 1; periodIndex >= 0; periodIndex--) { double fixingTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getFixing()); double paymentTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getPayment()); double periodLength = legSchedule.getPeriodLength(periodIndex); RandomVariable numeraireAtPayment = model.getNumeraire(paymentTime); RandomVariable monteCarloProbabilitiesAtPayment = model.getMonteCarloWeights(paymentTime); if(swaprate != 0.0) { RandomVariable periodCashFlowFix = model.getRandomVariableForConstant(swaprate * periodLength * notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment); value = value.add(periodCashFlowFix); } if(paysFloat) { RandomVariable libor = model.getLIBOR(fixingTime, fixingTime, paymentTime); RandomVariable periodCashFlowFloat = libor.mult(periodLength).mult(notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment); value = value.add(periodCashFlowFloat); } } return value; }
java
private RandomVariable getValueUnderlyingNumeraireRelative(LIBORModelMonteCarloSimulationModel model, Schedule legSchedule, boolean paysFloat, double swaprate, double notional) throws CalculationException { RandomVariable value = model.getRandomVariableForConstant(0.0); for(int periodIndex = legSchedule.getNumberOfPeriods() - 1; periodIndex >= 0; periodIndex--) { double fixingTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getFixing()); double paymentTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getPayment()); double periodLength = legSchedule.getPeriodLength(periodIndex); RandomVariable numeraireAtPayment = model.getNumeraire(paymentTime); RandomVariable monteCarloProbabilitiesAtPayment = model.getMonteCarloWeights(paymentTime); if(swaprate != 0.0) { RandomVariable periodCashFlowFix = model.getRandomVariableForConstant(swaprate * periodLength * notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment); value = value.add(periodCashFlowFix); } if(paysFloat) { RandomVariable libor = model.getLIBOR(fixingTime, fixingTime, paymentTime); RandomVariable periodCashFlowFloat = libor.mult(periodLength).mult(notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment); value = value.add(periodCashFlowFloat); } } return value; }
[ "private", "RandomVariable", "getValueUnderlyingNumeraireRelative", "(", "LIBORModelMonteCarloSimulationModel", "model", ",", "Schedule", "legSchedule", ",", "boolean", "paysFloat", ",", "double", "swaprate", ",", "double", "notional", ")", "throws", "CalculationException", "{", "RandomVariable", "value", "=", "model", ".", "getRandomVariableForConstant", "(", "0.0", ")", ";", "for", "(", "int", "periodIndex", "=", "legSchedule", ".", "getNumberOfPeriods", "(", ")", "-", "1", ";", "periodIndex", ">=", "0", ";", "periodIndex", "--", ")", "{", "double", "fixingTime", "=", "FloatingpointDate", ".", "getFloatingPointDateFromDate", "(", "model", ".", "getReferenceDate", "(", ")", ".", "toLocalDate", "(", ")", ",", "legSchedule", ".", "getPeriod", "(", "periodIndex", ")", ".", "getFixing", "(", ")", ")", ";", "double", "paymentTime", "=", "FloatingpointDate", ".", "getFloatingPointDateFromDate", "(", "model", ".", "getReferenceDate", "(", ")", ".", "toLocalDate", "(", ")", ",", "legSchedule", ".", "getPeriod", "(", "periodIndex", ")", ".", "getPayment", "(", ")", ")", ";", "double", "periodLength", "=", "legSchedule", ".", "getPeriodLength", "(", "periodIndex", ")", ";", "RandomVariable", "numeraireAtPayment", "=", "model", ".", "getNumeraire", "(", "paymentTime", ")", ";", "RandomVariable", "monteCarloProbabilitiesAtPayment", "=", "model", ".", "getMonteCarloWeights", "(", "paymentTime", ")", ";", "if", "(", "swaprate", "!=", "0.0", ")", "{", "RandomVariable", "periodCashFlowFix", "=", "model", ".", "getRandomVariableForConstant", "(", "swaprate", "*", "periodLength", "*", "notional", ")", ".", "div", "(", "numeraireAtPayment", ")", ".", "mult", "(", "monteCarloProbabilitiesAtPayment", ")", ";", "value", "=", "value", ".", "add", "(", "periodCashFlowFix", ")", ";", "}", "if", "(", "paysFloat", ")", "{", "RandomVariable", "libor", "=", "model", ".", "getLIBOR", "(", "fixingTime", ",", "fixingTime", ",", "paymentTime", ")", ";", "RandomVariable", "periodCashFlowFloat", "=", "libor", ".", "mult", "(", "periodLength", ")", ".", "mult", "(", "notional", ")", ".", "div", "(", "numeraireAtPayment", ")", ".", "mult", "(", "monteCarloProbabilitiesAtPayment", ")", ";", "value", "=", "value", ".", "add", "(", "periodCashFlowFloat", ")", ";", "}", "}", "return", "value", ";", "}" ]
Calculated the numeraire relative value of an underlying swap leg. @param model The Monte Carlo model. @param legSchedule The schedule of the leg. @param paysFloat If true a floating rate is payed. @param swaprate The swaprate. May be 0.0 for pure floating leg. @param notional The notional. @return The sum of the numeraire relative cash flows. @throws CalculationException Thrown if underlying model failed to calculate stochastic process.
[ "Calculated", "the", "numeraire", "relative", "value", "of", "an", "underlying", "swap", "leg", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaptionFromSwapSchedules.java#L292-L314
159,912
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaptionFromSwapSchedules.java
BermudanSwaptionFromSwapSchedules.getConditionalExpectationEstimator
public ConditionalExpectationEstimator getConditionalExpectationEstimator(double exerciseTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException { RandomVariable[] regressionBasisFunctions = regressionBasisFunctionProvider.getBasisFunctions(exerciseTime, model); return conditionalExpectationRegressionFactory.getConditionalExpectationEstimator(regressionBasisFunctions, regressionBasisFunctions); }
java
public ConditionalExpectationEstimator getConditionalExpectationEstimator(double exerciseTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException { RandomVariable[] regressionBasisFunctions = regressionBasisFunctionProvider.getBasisFunctions(exerciseTime, model); return conditionalExpectationRegressionFactory.getConditionalExpectationEstimator(regressionBasisFunctions, regressionBasisFunctions); }
[ "public", "ConditionalExpectationEstimator", "getConditionalExpectationEstimator", "(", "double", "exerciseTime", ",", "LIBORModelMonteCarloSimulationModel", "model", ")", "throws", "CalculationException", "{", "RandomVariable", "[", "]", "regressionBasisFunctions", "=", "regressionBasisFunctionProvider", ".", "getBasisFunctions", "(", "exerciseTime", ",", "model", ")", ";", "return", "conditionalExpectationRegressionFactory", ".", "getConditionalExpectationEstimator", "(", "regressionBasisFunctions", ",", "regressionBasisFunctions", ")", ";", "}" ]
The conditional expectation is calculated using a Monte-Carlo regression technique. @param exerciseTime The exercise time @param model The valuation model @return The condition expectation estimator @throws CalculationException Thrown if underlying model failed to calculate stochastic process.
[ "The", "conditional", "expectation", "is", "calculated", "using", "a", "Monte", "-", "Carlo", "regression", "technique", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaptionFromSwapSchedules.java#L324-L327
159,913
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/interestrate/models/LIBORMarketModelStandard.java
LIBORMarketModelStandard.getNumeraire
@Override public RandomVariable getNumeraire(double time) throws CalculationException { int timeIndex = getLiborPeriodIndex(time); if(timeIndex < 0) { // Interpolation of Numeraire: linear interpolation of the reciprocal. int lowerIndex = -timeIndex -1; int upperIndex = -timeIndex; double alpha = (time-getLiborPeriod(lowerIndex)) / (getLiborPeriod(upperIndex) - getLiborPeriod(lowerIndex)); return getNumeraire(getLiborPeriod(upperIndex)).invert().mult(alpha).add(getNumeraire(getLiborPeriod(lowerIndex)).invert().mult(1.0-alpha)).invert(); } // Calculate the numeraire, when time is part of liborPeriodDiscretization // Get the start of the product int firstLiborIndex = getLiborPeriodIndex(time); if(firstLiborIndex < 0) { throw new CalculationException("Simulation time discretization not part of forward rate tenor discretization."); } // Get the end of the product int lastLiborIndex = liborPeriodDiscretization.getNumberOfTimeSteps()-1; if(measure == Measure.SPOT) { // Spot measure firstLiborIndex = 0; lastLiborIndex = getLiborPeriodIndex(time)-1; } /* * Calculation of the numeraire */ // Initialize to 1.0 RandomVariable numeraire = new RandomVariableFromDoubleArray(time, 1.0); // The product for(int liborIndex = firstLiborIndex; liborIndex<=lastLiborIndex; liborIndex++) { RandomVariable libor = getLIBOR(getTimeIndex(Math.min(time,liborPeriodDiscretization.getTime(liborIndex))), liborIndex); double periodLength = liborPeriodDiscretization.getTimeStep(liborIndex); if(measure == Measure.SPOT) { numeraire = numeraire.accrue(libor, periodLength); } else { numeraire = numeraire.discount(libor, periodLength); } } /* * Adjust for discounting */ if(discountCurve != null) { DiscountCurve discountcountCurveFromForwardPerformance = new DiscountCurveFromForwardCurve(forwardRateCurve); double deterministicNumeraireAdjustment = discountcountCurveFromForwardPerformance.getDiscountFactor(time) / discountCurve.getDiscountFactor(time); numeraire = numeraire.mult(deterministicNumeraireAdjustment); } return numeraire; }
java
@Override public RandomVariable getNumeraire(double time) throws CalculationException { int timeIndex = getLiborPeriodIndex(time); if(timeIndex < 0) { // Interpolation of Numeraire: linear interpolation of the reciprocal. int lowerIndex = -timeIndex -1; int upperIndex = -timeIndex; double alpha = (time-getLiborPeriod(lowerIndex)) / (getLiborPeriod(upperIndex) - getLiborPeriod(lowerIndex)); return getNumeraire(getLiborPeriod(upperIndex)).invert().mult(alpha).add(getNumeraire(getLiborPeriod(lowerIndex)).invert().mult(1.0-alpha)).invert(); } // Calculate the numeraire, when time is part of liborPeriodDiscretization // Get the start of the product int firstLiborIndex = getLiborPeriodIndex(time); if(firstLiborIndex < 0) { throw new CalculationException("Simulation time discretization not part of forward rate tenor discretization."); } // Get the end of the product int lastLiborIndex = liborPeriodDiscretization.getNumberOfTimeSteps()-1; if(measure == Measure.SPOT) { // Spot measure firstLiborIndex = 0; lastLiborIndex = getLiborPeriodIndex(time)-1; } /* * Calculation of the numeraire */ // Initialize to 1.0 RandomVariable numeraire = new RandomVariableFromDoubleArray(time, 1.0); // The product for(int liborIndex = firstLiborIndex; liborIndex<=lastLiborIndex; liborIndex++) { RandomVariable libor = getLIBOR(getTimeIndex(Math.min(time,liborPeriodDiscretization.getTime(liborIndex))), liborIndex); double periodLength = liborPeriodDiscretization.getTimeStep(liborIndex); if(measure == Measure.SPOT) { numeraire = numeraire.accrue(libor, periodLength); } else { numeraire = numeraire.discount(libor, periodLength); } } /* * Adjust for discounting */ if(discountCurve != null) { DiscountCurve discountcountCurveFromForwardPerformance = new DiscountCurveFromForwardCurve(forwardRateCurve); double deterministicNumeraireAdjustment = discountcountCurveFromForwardPerformance.getDiscountFactor(time) / discountCurve.getDiscountFactor(time); numeraire = numeraire.mult(deterministicNumeraireAdjustment); } return numeraire; }
[ "@", "Override", "public", "RandomVariable", "getNumeraire", "(", "double", "time", ")", "throws", "CalculationException", "{", "int", "timeIndex", "=", "getLiborPeriodIndex", "(", "time", ")", ";", "if", "(", "timeIndex", "<", "0", ")", "{", "// Interpolation of Numeraire: linear interpolation of the reciprocal.", "int", "lowerIndex", "=", "-", "timeIndex", "-", "1", ";", "int", "upperIndex", "=", "-", "timeIndex", ";", "double", "alpha", "=", "(", "time", "-", "getLiborPeriod", "(", "lowerIndex", ")", ")", "/", "(", "getLiborPeriod", "(", "upperIndex", ")", "-", "getLiborPeriod", "(", "lowerIndex", ")", ")", ";", "return", "getNumeraire", "(", "getLiborPeriod", "(", "upperIndex", ")", ")", ".", "invert", "(", ")", ".", "mult", "(", "alpha", ")", ".", "add", "(", "getNumeraire", "(", "getLiborPeriod", "(", "lowerIndex", ")", ")", ".", "invert", "(", ")", ".", "mult", "(", "1.0", "-", "alpha", ")", ")", ".", "invert", "(", ")", ";", "}", "// Calculate the numeraire, when time is part of liborPeriodDiscretization", "// Get the start of the product", "int", "firstLiborIndex", "=", "getLiborPeriodIndex", "(", "time", ")", ";", "if", "(", "firstLiborIndex", "<", "0", ")", "{", "throw", "new", "CalculationException", "(", "\"Simulation time discretization not part of forward rate tenor discretization.\"", ")", ";", "}", "// Get the end of the product", "int", "lastLiborIndex", "=", "liborPeriodDiscretization", ".", "getNumberOfTimeSteps", "(", ")", "-", "1", ";", "if", "(", "measure", "==", "Measure", ".", "SPOT", ")", "{", "// Spot measure", "firstLiborIndex", "=", "0", ";", "lastLiborIndex", "=", "getLiborPeriodIndex", "(", "time", ")", "-", "1", ";", "}", "/*\n\t\t * Calculation of the numeraire\n\t\t */", "// Initialize to 1.0", "RandomVariable", "numeraire", "=", "new", "RandomVariableFromDoubleArray", "(", "time", ",", "1.0", ")", ";", "// The product", "for", "(", "int", "liborIndex", "=", "firstLiborIndex", ";", "liborIndex", "<=", "lastLiborIndex", ";", "liborIndex", "++", ")", "{", "RandomVariable", "libor", "=", "getLIBOR", "(", "getTimeIndex", "(", "Math", ".", "min", "(", "time", ",", "liborPeriodDiscretization", ".", "getTime", "(", "liborIndex", ")", ")", ")", ",", "liborIndex", ")", ";", "double", "periodLength", "=", "liborPeriodDiscretization", ".", "getTimeStep", "(", "liborIndex", ")", ";", "if", "(", "measure", "==", "Measure", ".", "SPOT", ")", "{", "numeraire", "=", "numeraire", ".", "accrue", "(", "libor", ",", "periodLength", ")", ";", "}", "else", "{", "numeraire", "=", "numeraire", ".", "discount", "(", "libor", ",", "periodLength", ")", ";", "}", "}", "/*\n\t\t * Adjust for discounting\n\t\t */", "if", "(", "discountCurve", "!=", "null", ")", "{", "DiscountCurve", "discountcountCurveFromForwardPerformance", "=", "new", "DiscountCurveFromForwardCurve", "(", "forwardRateCurve", ")", ";", "double", "deterministicNumeraireAdjustment", "=", "discountcountCurveFromForwardPerformance", ".", "getDiscountFactor", "(", "time", ")", "/", "discountCurve", ".", "getDiscountFactor", "(", "time", ")", ";", "numeraire", "=", "numeraire", ".", "mult", "(", "deterministicNumeraireAdjustment", ")", ";", "}", "return", "numeraire", ";", "}" ]
Return the numeraire at a given time. The numeraire is provided for interpolated points. If requested on points which are not part of the tenor discretization, the numeraire uses a linear interpolation of the reciprocal value. See ISBN 0470047224 for details. @param time Time time <i>t</i> for which the numeraire should be returned <i>N(t)</i>. @return The numeraire at the specified time as <code>RandomVariableFromDoubleArray</code> @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
[ "Return", "the", "numeraire", "at", "a", "given", "time", ".", "The", "numeraire", "is", "provided", "for", "interpolated", "points", ".", "If", "requested", "on", "points", "which", "are", "not", "part", "of", "the", "tenor", "discretization", "the", "numeraire", "uses", "a", "linear", "interpolation", "of", "the", "reciprocal", "value", ".", "See", "ISBN", "0470047224", "for", "details", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/models/LIBORMarketModelStandard.java#L282-L341
159,914
finmath/finmath-lib
src/main/java/net/finmath/finitedifference/solvers/FDMThetaMethod.java
FDMThetaMethod.u_neg_inf
private double u_neg_inf(double x, double tau) { return f(boundaryCondition.getValueAtLowerBoundary(model, f_t(tau), f_s(x)), x, tau); }
java
private double u_neg_inf(double x, double tau) { return f(boundaryCondition.getValueAtLowerBoundary(model, f_t(tau), f_s(x)), x, tau); }
[ "private", "double", "u_neg_inf", "(", "double", "x", ",", "double", "tau", ")", "{", "return", "f", "(", "boundaryCondition", ".", "getValueAtLowerBoundary", "(", "model", ",", "f_t", "(", "tau", ")", ",", "f_s", "(", "x", ")", ")", ",", "x", ",", "tau", ")", ";", "}" ]
Heat Equation Boundary Conditions
[ "Heat", "Equation", "Boundary", "Conditions" ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/finitedifference/solvers/FDMThetaMethod.java#L150-L152
159,915
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/conditionalexpectation/LinearRegression.java
LinearRegression.getRegressionCoefficients
public double[] getRegressionCoefficients(RandomVariable value) { if(basisFunctions.length == 0) { return new double[] { }; } else if(basisFunctions.length == 1) { /* * Regression with one basis function is just a projection on that vector. <b,x>/<b,b> */ return new double[] { value.mult(basisFunctions[0]).getAverage() / basisFunctions[0].squared().getAverage() }; } else if(basisFunctions.length == 2) { /* * Regression with two basis functions can be solved explicitly if determinant != 0 (otherwise we will fallback to SVD) */ double a = basisFunctions[0].squared().getAverage(); double b = basisFunctions[0].mult(basisFunctions[1]).average().squared().doubleValue(); double c = b; double d = basisFunctions[1].squared().getAverage(); double determinant = (a * d - b * c); if(determinant != 0) { double x = value.mult(basisFunctions[0]).getAverage(); double y = value.mult(basisFunctions[1]).getAverage(); double alpha0 = (d * x - b * y) / determinant; double alpha1 = (a * y - c * x) / determinant; return new double[] { alpha0, alpha1 }; } } /* * General case */ // Build regression matrix double[][] BTB = new double[basisFunctions.length][basisFunctions.length]; for(int i=0; i<basisFunctions.length; i++) { for(int j=0; j<=i; j++) { double covariance = basisFunctions[i].mult(basisFunctions[j]).getAverage(); BTB[i][j] = covariance; BTB[j][i] = covariance; } } double[] BTX = new double[basisFunctions.length]; for(int i=0; i<basisFunctions.length; i++) { double covariance = basisFunctions[i].mult(value).getAverage(); BTX[i] = covariance; } return LinearAlgebra.solveLinearEquationLeastSquare(BTB, BTX); }
java
public double[] getRegressionCoefficients(RandomVariable value) { if(basisFunctions.length == 0) { return new double[] { }; } else if(basisFunctions.length == 1) { /* * Regression with one basis function is just a projection on that vector. <b,x>/<b,b> */ return new double[] { value.mult(basisFunctions[0]).getAverage() / basisFunctions[0].squared().getAverage() }; } else if(basisFunctions.length == 2) { /* * Regression with two basis functions can be solved explicitly if determinant != 0 (otherwise we will fallback to SVD) */ double a = basisFunctions[0].squared().getAverage(); double b = basisFunctions[0].mult(basisFunctions[1]).average().squared().doubleValue(); double c = b; double d = basisFunctions[1].squared().getAverage(); double determinant = (a * d - b * c); if(determinant != 0) { double x = value.mult(basisFunctions[0]).getAverage(); double y = value.mult(basisFunctions[1]).getAverage(); double alpha0 = (d * x - b * y) / determinant; double alpha1 = (a * y - c * x) / determinant; return new double[] { alpha0, alpha1 }; } } /* * General case */ // Build regression matrix double[][] BTB = new double[basisFunctions.length][basisFunctions.length]; for(int i=0; i<basisFunctions.length; i++) { for(int j=0; j<=i; j++) { double covariance = basisFunctions[i].mult(basisFunctions[j]).getAverage(); BTB[i][j] = covariance; BTB[j][i] = covariance; } } double[] BTX = new double[basisFunctions.length]; for(int i=0; i<basisFunctions.length; i++) { double covariance = basisFunctions[i].mult(value).getAverage(); BTX[i] = covariance; } return LinearAlgebra.solveLinearEquationLeastSquare(BTB, BTX); }
[ "public", "double", "[", "]", "getRegressionCoefficients", "(", "RandomVariable", "value", ")", "{", "if", "(", "basisFunctions", ".", "length", "==", "0", ")", "{", "return", "new", "double", "[", "]", "{", "}", ";", "}", "else", "if", "(", "basisFunctions", ".", "length", "==", "1", ")", "{", "/*\n\t\t\t * Regression with one basis function is just a projection on that vector. <b,x>/<b,b>\n\t\t\t */", "return", "new", "double", "[", "]", "{", "value", ".", "mult", "(", "basisFunctions", "[", "0", "]", ")", ".", "getAverage", "(", ")", "/", "basisFunctions", "[", "0", "]", ".", "squared", "(", ")", ".", "getAverage", "(", ")", "}", ";", "}", "else", "if", "(", "basisFunctions", ".", "length", "==", "2", ")", "{", "/*\n\t\t\t * Regression with two basis functions can be solved explicitly if determinant != 0 (otherwise we will fallback to SVD)\n\t\t\t */", "double", "a", "=", "basisFunctions", "[", "0", "]", ".", "squared", "(", ")", ".", "getAverage", "(", ")", ";", "double", "b", "=", "basisFunctions", "[", "0", "]", ".", "mult", "(", "basisFunctions", "[", "1", "]", ")", ".", "average", "(", ")", ".", "squared", "(", ")", ".", "doubleValue", "(", ")", ";", "double", "c", "=", "b", ";", "double", "d", "=", "basisFunctions", "[", "1", "]", ".", "squared", "(", ")", ".", "getAverage", "(", ")", ";", "double", "determinant", "=", "(", "a", "*", "d", "-", "b", "*", "c", ")", ";", "if", "(", "determinant", "!=", "0", ")", "{", "double", "x", "=", "value", ".", "mult", "(", "basisFunctions", "[", "0", "]", ")", ".", "getAverage", "(", ")", ";", "double", "y", "=", "value", ".", "mult", "(", "basisFunctions", "[", "1", "]", ")", ".", "getAverage", "(", ")", ";", "double", "alpha0", "=", "(", "d", "*", "x", "-", "b", "*", "y", ")", "/", "determinant", ";", "double", "alpha1", "=", "(", "a", "*", "y", "-", "c", "*", "x", ")", "/", "determinant", ";", "return", "new", "double", "[", "]", "{", "alpha0", ",", "alpha1", "}", ";", "}", "}", "/*\n\t\t * General case\n\t\t */", "// Build regression matrix", "double", "[", "]", "[", "]", "BTB", "=", "new", "double", "[", "basisFunctions", ".", "length", "]", "[", "basisFunctions", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "basisFunctions", ".", "length", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<=", "i", ";", "j", "++", ")", "{", "double", "covariance", "=", "basisFunctions", "[", "i", "]", ".", "mult", "(", "basisFunctions", "[", "j", "]", ")", ".", "getAverage", "(", ")", ";", "BTB", "[", "i", "]", "[", "j", "]", "=", "covariance", ";", "BTB", "[", "j", "]", "[", "i", "]", "=", "covariance", ";", "}", "}", "double", "[", "]", "BTX", "=", "new", "double", "[", "basisFunctions", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "basisFunctions", ".", "length", ";", "i", "++", ")", "{", "double", "covariance", "=", "basisFunctions", "[", "i", "]", ".", "mult", "(", "value", ")", ".", "getAverage", "(", ")", ";", "BTX", "[", "i", "]", "=", "covariance", ";", "}", "return", "LinearAlgebra", ".", "solveLinearEquationLeastSquare", "(", "BTB", ",", "BTX", ")", ";", "}" ]
Get the vector of regression coefficients. @param value The random variable to regress. @return The vector of regression coefficients.
[ "Get", "the", "vector", "of", "regression", "coefficients", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/conditionalexpectation/LinearRegression.java#L36-L88
159,916
finmath/finmath-lib
src/main/java/net/finmath/modelling/descriptor/xmlparser/FPMLParser.java
FPMLParser.getSwapProductDescriptor
private ProductDescriptor getSwapProductDescriptor(Element trade) { InterestRateSwapLegProductDescriptor legReceiver = null; InterestRateSwapLegProductDescriptor legPayer = null; NodeList legs = trade.getElementsByTagName("swapStream"); for(int legIndex = 0; legIndex < legs.getLength(); legIndex++) { Element leg = (Element) legs.item(legIndex); boolean isPayer = leg.getElementsByTagName("payerPartyReference").item(0).getAttributes().getNamedItem("href").getNodeValue().equals(homePartyId); if(isPayer) { legPayer = getSwapLegProductDescriptor(leg); } else { legReceiver = getSwapLegProductDescriptor(leg); } } return new InterestRateSwapProductDescriptor(legReceiver, legPayer); }
java
private ProductDescriptor getSwapProductDescriptor(Element trade) { InterestRateSwapLegProductDescriptor legReceiver = null; InterestRateSwapLegProductDescriptor legPayer = null; NodeList legs = trade.getElementsByTagName("swapStream"); for(int legIndex = 0; legIndex < legs.getLength(); legIndex++) { Element leg = (Element) legs.item(legIndex); boolean isPayer = leg.getElementsByTagName("payerPartyReference").item(0).getAttributes().getNamedItem("href").getNodeValue().equals(homePartyId); if(isPayer) { legPayer = getSwapLegProductDescriptor(leg); } else { legReceiver = getSwapLegProductDescriptor(leg); } } return new InterestRateSwapProductDescriptor(legReceiver, legPayer); }
[ "private", "ProductDescriptor", "getSwapProductDescriptor", "(", "Element", "trade", ")", "{", "InterestRateSwapLegProductDescriptor", "legReceiver", "=", "null", ";", "InterestRateSwapLegProductDescriptor", "legPayer", "=", "null", ";", "NodeList", "legs", "=", "trade", ".", "getElementsByTagName", "(", "\"swapStream\"", ")", ";", "for", "(", "int", "legIndex", "=", "0", ";", "legIndex", "<", "legs", ".", "getLength", "(", ")", ";", "legIndex", "++", ")", "{", "Element", "leg", "=", "(", "Element", ")", "legs", ".", "item", "(", "legIndex", ")", ";", "boolean", "isPayer", "=", "leg", ".", "getElementsByTagName", "(", "\"payerPartyReference\"", ")", ".", "item", "(", "0", ")", ".", "getAttributes", "(", ")", ".", "getNamedItem", "(", "\"href\"", ")", ".", "getNodeValue", "(", ")", ".", "equals", "(", "homePartyId", ")", ";", "if", "(", "isPayer", ")", "{", "legPayer", "=", "getSwapLegProductDescriptor", "(", "leg", ")", ";", "}", "else", "{", "legReceiver", "=", "getSwapLegProductDescriptor", "(", "leg", ")", ";", "}", "}", "return", "new", "InterestRateSwapProductDescriptor", "(", "legReceiver", ",", "legPayer", ")", ";", "}" ]
Construct an InterestRateSwapProductDescriptor from a node in a FpML file. @param trade The node containing the swap. @return Descriptor of the swap.
[ "Construct", "an", "InterestRateSwapProductDescriptor", "from", "a", "node", "in", "a", "FpML", "file", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/modelling/descriptor/xmlparser/FPMLParser.java#L101-L120
159,917
finmath/finmath-lib
src/main/java/net/finmath/information/Library.java
Library.getVersionString
public static String getVersionString() { String versionString = "UNKNOWN"; Properties propeties = getProperites(); if(propeties != null) { versionString = propeties.getProperty("finmath-lib.version"); } return versionString; }
java
public static String getVersionString() { String versionString = "UNKNOWN"; Properties propeties = getProperites(); if(propeties != null) { versionString = propeties.getProperty("finmath-lib.version"); } return versionString; }
[ "public", "static", "String", "getVersionString", "(", ")", "{", "String", "versionString", "=", "\"UNKNOWN\"", ";", "Properties", "propeties", "=", "getProperites", "(", ")", ";", "if", "(", "propeties", "!=", "null", ")", "{", "versionString", "=", "propeties", ".", "getProperty", "(", "\"finmath-lib.version\"", ")", ";", "}", "return", "versionString", ";", "}" ]
Return the version string of this instance of finmath-lib. @return The version string of this instance of finmath-lib.
[ "Return", "the", "version", "string", "of", "this", "instance", "of", "finmath", "-", "lib", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/information/Library.java#L40-L47
159,918
finmath/finmath-lib
src/main/java/net/finmath/information/Library.java
Library.getBuildString
public static String getBuildString() { String versionString = "UNKNOWN"; Properties propeties = getProperites(); if(propeties != null) { versionString = propeties.getProperty("finmath-lib.build"); } return versionString; }
java
public static String getBuildString() { String versionString = "UNKNOWN"; Properties propeties = getProperites(); if(propeties != null) { versionString = propeties.getProperty("finmath-lib.build"); } return versionString; }
[ "public", "static", "String", "getBuildString", "(", ")", "{", "String", "versionString", "=", "\"UNKNOWN\"", ";", "Properties", "propeties", "=", "getProperites", "(", ")", ";", "if", "(", "propeties", "!=", "null", ")", "{", "versionString", "=", "propeties", ".", "getProperty", "(", "\"finmath-lib.build\"", ")", ";", "}", "return", "versionString", ";", "}" ]
Return the build string of this instance of finmath-lib. Currently this is the Git commit hash. @return The build string of this instance of finmath-lib.
[ "Return", "the", "build", "string", "of", "this", "instance", "of", "finmath", "-", "lib", ".", "Currently", "this", "is", "the", "Git", "commit", "hash", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/information/Library.java#L55-L62
159,919
finmath/finmath-lib
src/main/java6/net/finmath/marketdata/model/curves/DiscountCurve.java
DiscountCurve.createDiscountCurveFromDiscountFactors
public static DiscountCurve createDiscountCurveFromDiscountFactors(String name, double[] times, double[] givenDiscountFactors) { DiscountCurve discountFactors = new DiscountCurve(name); for(int timeIndex=0; timeIndex<times.length;timeIndex++) { discountFactors.addDiscountFactor(times[timeIndex], givenDiscountFactors[timeIndex], times[timeIndex] > 0); } return discountFactors; }
java
public static DiscountCurve createDiscountCurveFromDiscountFactors(String name, double[] times, double[] givenDiscountFactors) { DiscountCurve discountFactors = new DiscountCurve(name); for(int timeIndex=0; timeIndex<times.length;timeIndex++) { discountFactors.addDiscountFactor(times[timeIndex], givenDiscountFactors[timeIndex], times[timeIndex] > 0); } return discountFactors; }
[ "public", "static", "DiscountCurve", "createDiscountCurveFromDiscountFactors", "(", "String", "name", ",", "double", "[", "]", "times", ",", "double", "[", "]", "givenDiscountFactors", ")", "{", "DiscountCurve", "discountFactors", "=", "new", "DiscountCurve", "(", "name", ")", ";", "for", "(", "int", "timeIndex", "=", "0", ";", "timeIndex", "<", "times", ".", "length", ";", "timeIndex", "++", ")", "{", "discountFactors", ".", "addDiscountFactor", "(", "times", "[", "timeIndex", "]", ",", "givenDiscountFactors", "[", "timeIndex", "]", ",", "times", "[", "timeIndex", "]", ">", "0", ")", ";", "}", "return", "discountFactors", ";", "}" ]
Create a discount curve from given times and given discount factors using default interpolation and extrapolation methods. @param name The name of this discount curve. @param times Array of times as doubles. @param givenDiscountFactors Array of corresponding discount factors. @return A new discount factor object.
[ "Create", "a", "discount", "curve", "from", "given", "times", "and", "given", "discount", "factors", "using", "default", "interpolation", "and", "extrapolation", "methods", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/marketdata/model/curves/DiscountCurve.java#L158-L166
159,920
finmath/finmath-lib
src/main/java/net/finmath/fouriermethod/products/smile/EuropeanOptionSmile.java
EuropeanOptionSmile.getDescriptors
public Map<Double, SingleAssetEuropeanOptionProductDescriptor> getDescriptors(LocalDate referenceDate){ int numberOfStrikes = strikes.length; HashMap<Double, SingleAssetEuropeanOptionProductDescriptor> descriptors = new HashMap<Double, SingleAssetEuropeanOptionProductDescriptor>(); LocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity); for(int i = 0; i< numberOfStrikes; i++) { descriptors.put(strikes[i], new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[i])); } return descriptors; }
java
public Map<Double, SingleAssetEuropeanOptionProductDescriptor> getDescriptors(LocalDate referenceDate){ int numberOfStrikes = strikes.length; HashMap<Double, SingleAssetEuropeanOptionProductDescriptor> descriptors = new HashMap<Double, SingleAssetEuropeanOptionProductDescriptor>(); LocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity); for(int i = 0; i< numberOfStrikes; i++) { descriptors.put(strikes[i], new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[i])); } return descriptors; }
[ "public", "Map", "<", "Double", ",", "SingleAssetEuropeanOptionProductDescriptor", ">", "getDescriptors", "(", "LocalDate", "referenceDate", ")", "{", "int", "numberOfStrikes", "=", "strikes", ".", "length", ";", "HashMap", "<", "Double", ",", "SingleAssetEuropeanOptionProductDescriptor", ">", "descriptors", "=", "new", "HashMap", "<", "Double", ",", "SingleAssetEuropeanOptionProductDescriptor", ">", "(", ")", ";", "LocalDate", "maturityDate", "=", "FloatingpointDate", ".", "getDateFromFloatingPointDate", "(", "referenceDate", ",", "maturity", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numberOfStrikes", ";", "i", "++", ")", "{", "descriptors", ".", "put", "(", "strikes", "[", "i", "]", ",", "new", "SingleAssetEuropeanOptionProductDescriptor", "(", "underlyingName", ",", "maturityDate", ",", "strikes", "[", "i", "]", ")", ")", ";", "}", "return", "descriptors", ";", "}" ]
Return a collection of product descriptors for each option in the smile. @param referenceDate The reference date (translating the maturity floating point date to dates. @return a collection of product descriptors for each option in the smile.
[ "Return", "a", "collection", "of", "product", "descriptors", "for", "each", "option", "in", "the", "smile", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/fouriermethod/products/smile/EuropeanOptionSmile.java#L88-L99
159,921
finmath/finmath-lib
src/main/java/net/finmath/fouriermethod/products/smile/EuropeanOptionSmile.java
EuropeanOptionSmile.getDescriptor
public SingleAssetEuropeanOptionProductDescriptor getDescriptor(LocalDate referenceDate, int index) throws ArrayIndexOutOfBoundsException{ LocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity); if(index >= strikes.length) { throw new ArrayIndexOutOfBoundsException("Strike index out of bounds"); }else { return new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[index]); } }
java
public SingleAssetEuropeanOptionProductDescriptor getDescriptor(LocalDate referenceDate, int index) throws ArrayIndexOutOfBoundsException{ LocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity); if(index >= strikes.length) { throw new ArrayIndexOutOfBoundsException("Strike index out of bounds"); }else { return new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[index]); } }
[ "public", "SingleAssetEuropeanOptionProductDescriptor", "getDescriptor", "(", "LocalDate", "referenceDate", ",", "int", "index", ")", "throws", "ArrayIndexOutOfBoundsException", "{", "LocalDate", "maturityDate", "=", "FloatingpointDate", ".", "getDateFromFloatingPointDate", "(", "referenceDate", ",", "maturity", ")", ";", "if", "(", "index", ">=", "strikes", ".", "length", ")", "{", "throw", "new", "ArrayIndexOutOfBoundsException", "(", "\"Strike index out of bounds\"", ")", ";", "}", "else", "{", "return", "new", "SingleAssetEuropeanOptionProductDescriptor", "(", "underlyingName", ",", "maturityDate", ",", "strikes", "[", "index", "]", ")", ";", "}", "}" ]
Return a product descriptor for a specific strike. @param referenceDate The reference date (translating the maturity floating point date to dates. @param index The index corresponding to the strike grid. @return a product descriptor for a specific strike. @throws ArrayIndexOutOfBoundsException Thrown if index is out of bound.
[ "Return", "a", "product", "descriptor", "for", "a", "specific", "strike", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/fouriermethod/products/smile/EuropeanOptionSmile.java#L109-L116
159,922
finmath/finmath-lib
src/main/java/net/finmath/marketdata2/model/curves/AbstractCurve.java
AbstractCurve.getValues
public RandomVariable[] getValues(double[] times) { RandomVariable[] values = new RandomVariable[times.length]; for(int i=0; i<times.length; i++) { values[i] = getValue(null, times[i]); } return values; }
java
public RandomVariable[] getValues(double[] times) { RandomVariable[] values = new RandomVariable[times.length]; for(int i=0; i<times.length; i++) { values[i] = getValue(null, times[i]); } return values; }
[ "public", "RandomVariable", "[", "]", "getValues", "(", "double", "[", "]", "times", ")", "{", "RandomVariable", "[", "]", "values", "=", "new", "RandomVariable", "[", "times", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "times", ".", "length", ";", "i", "++", ")", "{", "values", "[", "i", "]", "=", "getValue", "(", "null", ",", "times", "[", "i", "]", ")", ";", "}", "return", "values", ";", "}" ]
Return a vector of values corresponding to a given vector of times. @param times A given vector of times. @return A vector of values corresponding to the given vector of times.
[ "Return", "a", "vector", "of", "values", "corresponding", "to", "a", "given", "vector", "of", "times", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata2/model/curves/AbstractCurve.java#L60-L68
159,923
finmath/finmath-lib
src/main/java6/net/finmath/time/daycount/DayCountConventionFactory.java
DayCountConventionFactory.getDaycount
public static double getDaycount(LocalDate startDate, LocalDate endDate, String convention) { DayCountConventionInterface daycountConvention = getDayCountConvention(convention); return daycountConvention.getDaycount(startDate, endDate); }
java
public static double getDaycount(LocalDate startDate, LocalDate endDate, String convention) { DayCountConventionInterface daycountConvention = getDayCountConvention(convention); return daycountConvention.getDaycount(startDate, endDate); }
[ "public", "static", "double", "getDaycount", "(", "LocalDate", "startDate", ",", "LocalDate", "endDate", ",", "String", "convention", ")", "{", "DayCountConventionInterface", "daycountConvention", "=", "getDayCountConvention", "(", "convention", ")", ";", "return", "daycountConvention", ".", "getDaycount", "(", "startDate", ",", "endDate", ")", ";", "}" ]
Return the number of days between startDate and endDate given the specific daycount convention. @param startDate The start date given as a {@link org.threeten.bp.LocalDate}. @param endDate The end date given as a {@link org.threeten.bp.LocalDate}. @param convention A convention string. @return The number of days within the given period.
[ "Return", "the", "number", "of", "days", "between", "startDate", "and", "endDate", "given", "the", "specific", "daycount", "convention", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/time/daycount/DayCountConventionFactory.java#L76-L79
159,924
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/interestrate/products/CMSOption.java
CMSOption.getValue
public double getValue(ForwardCurve forwardCurve, double swaprateVolatility) { double[] swapTenor = new double[fixingDates.length+1]; System.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length); swapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1]; TimeDiscretization fixTenor = new TimeDiscretizationFromArray(swapTenor); TimeDiscretization floatTenor = new TimeDiscretizationFromArray(swapTenor); double forwardSwapRate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve); double swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve); double payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor[0], swapTenor[1]), forwardCurve) / (swapTenor[1] - swapTenor[0]); return AnalyticFormulas.huntKennedyCMSOptionValue(forwardSwapRate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit, strike) * (swapTenor[1] - swapTenor[0]); }
java
public double getValue(ForwardCurve forwardCurve, double swaprateVolatility) { double[] swapTenor = new double[fixingDates.length+1]; System.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length); swapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1]; TimeDiscretization fixTenor = new TimeDiscretizationFromArray(swapTenor); TimeDiscretization floatTenor = new TimeDiscretizationFromArray(swapTenor); double forwardSwapRate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve); double swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve); double payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor[0], swapTenor[1]), forwardCurve) / (swapTenor[1] - swapTenor[0]); return AnalyticFormulas.huntKennedyCMSOptionValue(forwardSwapRate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit, strike) * (swapTenor[1] - swapTenor[0]); }
[ "public", "double", "getValue", "(", "ForwardCurve", "forwardCurve", ",", "double", "swaprateVolatility", ")", "{", "double", "[", "]", "swapTenor", "=", "new", "double", "[", "fixingDates", ".", "length", "+", "1", "]", ";", "System", ".", "arraycopy", "(", "fixingDates", ",", "0", ",", "swapTenor", ",", "0", ",", "fixingDates", ".", "length", ")", ";", "swapTenor", "[", "swapTenor", ".", "length", "-", "1", "]", "=", "paymentDates", "[", "paymentDates", ".", "length", "-", "1", "]", ";", "TimeDiscretization", "fixTenor", "=", "new", "TimeDiscretizationFromArray", "(", "swapTenor", ")", ";", "TimeDiscretization", "floatTenor", "=", "new", "TimeDiscretizationFromArray", "(", "swapTenor", ")", ";", "double", "forwardSwapRate", "=", "Swap", ".", "getForwardSwapRate", "(", "fixTenor", ",", "floatTenor", ",", "forwardCurve", ")", ";", "double", "swapAnnuity", "=", "SwapAnnuity", ".", "getSwapAnnuity", "(", "fixTenor", ",", "forwardCurve", ")", ";", "double", "payoffUnit", "=", "SwapAnnuity", ".", "getSwapAnnuity", "(", "new", "TimeDiscretizationFromArray", "(", "swapTenor", "[", "0", "]", ",", "swapTenor", "[", "1", "]", ")", ",", "forwardCurve", ")", "/", "(", "swapTenor", "[", "1", "]", "-", "swapTenor", "[", "0", "]", ")", ";", "return", "AnalyticFormulas", ".", "huntKennedyCMSOptionValue", "(", "forwardSwapRate", ",", "swaprateVolatility", ",", "swapAnnuity", ",", "exerciseDate", ",", "swapTenor", "[", "swapTenor", ".", "length", "-", "1", "]", "-", "swapTenor", "[", "0", "]", ",", "payoffUnit", ",", "strike", ")", "*", "(", "swapTenor", "[", "1", "]", "-", "swapTenor", "[", "0", "]", ")", ";", "}" ]
This method returns the value of the product using a Black-Scholes model for the swap rate with the Hunt-Kennedy convexity adjustment. The model is determined by a discount factor curve and a swap rate volatility. @param forwardCurve The forward curve from which the swap rate is calculated. The discount curve, associated with this forward curve is used for discounting this option. @param swaprateVolatility The volatility of the log-swaprate. @return Value of this product
[ "This", "method", "returns", "the", "value", "of", "the", "product", "using", "a", "Black", "-", "Scholes", "model", "for", "the", "swap", "rate", "with", "the", "Hunt", "-", "Kennedy", "convexity", "adjustment", ".", "The", "model", "is", "determined", "by", "a", "discount", "factor", "curve", "and", "a", "swap", "rate", "volatility", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/CMSOption.java#L132-L143
159,925
finmath/finmath-lib
src/main/java6/net/finmath/marketdata/model/curves/DiscountCurveNelsonSiegelSvensson.java
DiscountCurveNelsonSiegelSvensson.getDiscountFactor
@Override public double getDiscountFactor(AnalyticModelInterface model, double maturity) { // Change time scale maturity *= timeScaling; double beta1 = parameter[0]; double beta2 = parameter[1]; double beta3 = parameter[2]; double beta4 = parameter[3]; double tau1 = parameter[4]; double tau2 = parameter[5]; double x1 = tau1 > 0 ? FastMath.exp(-maturity/tau1) : 0.0; double x2 = tau2 > 0 ? FastMath.exp(-maturity/tau2) : 0.0; double y1 = tau1 > 0 ? (maturity > 0.0 ? (1.0-x1)/maturity*tau1 : 1.0) : 0.0; double y2 = tau2 > 0 ? (maturity > 0.0 ? (1.0-x2)/maturity*tau2 : 1.0) : 0.0; double zeroRate = beta1 + beta2 * y1 + beta3 * (y1-x1) + beta4 * (y2-x2); return Math.exp(- zeroRate * maturity); }
java
@Override public double getDiscountFactor(AnalyticModelInterface model, double maturity) { // Change time scale maturity *= timeScaling; double beta1 = parameter[0]; double beta2 = parameter[1]; double beta3 = parameter[2]; double beta4 = parameter[3]; double tau1 = parameter[4]; double tau2 = parameter[5]; double x1 = tau1 > 0 ? FastMath.exp(-maturity/tau1) : 0.0; double x2 = tau2 > 0 ? FastMath.exp(-maturity/tau2) : 0.0; double y1 = tau1 > 0 ? (maturity > 0.0 ? (1.0-x1)/maturity*tau1 : 1.0) : 0.0; double y2 = tau2 > 0 ? (maturity > 0.0 ? (1.0-x2)/maturity*tau2 : 1.0) : 0.0; double zeroRate = beta1 + beta2 * y1 + beta3 * (y1-x1) + beta4 * (y2-x2); return Math.exp(- zeroRate * maturity); }
[ "@", "Override", "public", "double", "getDiscountFactor", "(", "AnalyticModelInterface", "model", ",", "double", "maturity", ")", "{", "// Change time scale", "maturity", "*=", "timeScaling", ";", "double", "beta1", "=", "parameter", "[", "0", "]", ";", "double", "beta2", "=", "parameter", "[", "1", "]", ";", "double", "beta3", "=", "parameter", "[", "2", "]", ";", "double", "beta4", "=", "parameter", "[", "3", "]", ";", "double", "tau1", "=", "parameter", "[", "4", "]", ";", "double", "tau2", "=", "parameter", "[", "5", "]", ";", "double", "x1", "=", "tau1", ">", "0", "?", "FastMath", ".", "exp", "(", "-", "maturity", "/", "tau1", ")", ":", "0.0", ";", "double", "x2", "=", "tau2", ">", "0", "?", "FastMath", ".", "exp", "(", "-", "maturity", "/", "tau2", ")", ":", "0.0", ";", "double", "y1", "=", "tau1", ">", "0", "?", "(", "maturity", ">", "0.0", "?", "(", "1.0", "-", "x1", ")", "/", "maturity", "*", "tau1", ":", "1.0", ")", ":", "0.0", ";", "double", "y2", "=", "tau2", ">", "0", "?", "(", "maturity", ">", "0.0", "?", "(", "1.0", "-", "x2", ")", "/", "maturity", "*", "tau2", ":", "1.0", ")", ":", "0.0", ";", "double", "zeroRate", "=", "beta1", "+", "beta2", "*", "y1", "+", "beta3", "*", "(", "y1", "-", "x1", ")", "+", "beta4", "*", "(", "y2", "-", "x2", ")", ";", "return", "Math", ".", "exp", "(", "-", "zeroRate", "*", "maturity", ")", ";", "}" ]
Return the discount factor within a given model context for a given maturity. @param model The model used as a context (not required for this class). @param maturity The maturity in terms of ACT/365 daycount form this curve reference date. Note that this parameter might get rescaled to a different time parameter. @see net.finmath.marketdata.model.curves.DiscountCurveInterface#getDiscountFactor(net.finmath.marketdata.model.AnalyticModelInterface, double)
[ "Return", "the", "discount", "factor", "within", "a", "given", "model", "context", "for", "a", "given", "maturity", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/marketdata/model/curves/DiscountCurveNelsonSiegelSvensson.java#L71-L93
159,926
finmath/finmath-lib
src/main/java/net/finmath/time/ScheduleGenerator.java
ScheduleGenerator.createScheduleFromConventions
@Deprecated public static Schedule createScheduleFromConventions( LocalDate referenceDate, LocalDate startDate, String frequency, double maturity, String daycountConvention, String shortPeriodConvention, String dateRollConvention, BusinessdayCalendar businessdayCalendar, int fixingOffsetDays, int paymentOffsetDays ) { LocalDate maturityDate = createDateFromDateAndOffset(startDate, maturity); return createScheduleFromConventions( referenceDate, startDate, maturityDate, Frequency.valueOf(frequency.toUpperCase()), DaycountConvention.getEnum(daycountConvention), ShortPeriodConvention.valueOf(shortPeriodConvention.toUpperCase()), DateRollConvention.getEnum(dateRollConvention), businessdayCalendar, fixingOffsetDays, paymentOffsetDays ); }
java
@Deprecated public static Schedule createScheduleFromConventions( LocalDate referenceDate, LocalDate startDate, String frequency, double maturity, String daycountConvention, String shortPeriodConvention, String dateRollConvention, BusinessdayCalendar businessdayCalendar, int fixingOffsetDays, int paymentOffsetDays ) { LocalDate maturityDate = createDateFromDateAndOffset(startDate, maturity); return createScheduleFromConventions( referenceDate, startDate, maturityDate, Frequency.valueOf(frequency.toUpperCase()), DaycountConvention.getEnum(daycountConvention), ShortPeriodConvention.valueOf(shortPeriodConvention.toUpperCase()), DateRollConvention.getEnum(dateRollConvention), businessdayCalendar, fixingOffsetDays, paymentOffsetDays ); }
[ "@", "Deprecated", "public", "static", "Schedule", "createScheduleFromConventions", "(", "LocalDate", "referenceDate", ",", "LocalDate", "startDate", ",", "String", "frequency", ",", "double", "maturity", ",", "String", "daycountConvention", ",", "String", "shortPeriodConvention", ",", "String", "dateRollConvention", ",", "BusinessdayCalendar", "businessdayCalendar", ",", "int", "fixingOffsetDays", ",", "int", "paymentOffsetDays", ")", "{", "LocalDate", "maturityDate", "=", "createDateFromDateAndOffset", "(", "startDate", ",", "maturity", ")", ";", "return", "createScheduleFromConventions", "(", "referenceDate", ",", "startDate", ",", "maturityDate", ",", "Frequency", ".", "valueOf", "(", "frequency", ".", "toUpperCase", "(", ")", ")", ",", "DaycountConvention", ".", "getEnum", "(", "daycountConvention", ")", ",", "ShortPeriodConvention", ".", "valueOf", "(", "shortPeriodConvention", ".", "toUpperCase", "(", ")", ")", ",", "DateRollConvention", ".", "getEnum", "(", "dateRollConvention", ")", ",", "businessdayCalendar", ",", "fixingOffsetDays", ",", "paymentOffsetDays", ")", ";", "}" ]
Generates a schedule based on some meta data. The schedule generation considers short periods. @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. @param startDate The start date of the first period. @param frequency The frequency. @param maturity The end date of the last period. @param daycountConvention The daycount convention. @param shortPeriodConvention If short period exists, have it first or last. @param dateRollConvention Adjustment to be applied to the all dates. @param businessdayCalendar Businessday calendar (holiday calendar) to be used for date roll adjustment. @param fixingOffsetDays Number of business days to be added to period start to get the fixing date. @param paymentOffsetDays Number of business days to be added to period end to get the payment date. @return The corresponding schedule @deprecated Will be removed in version 2.3
[ "Generates", "a", "schedule", "based", "on", "some", "meta", "data", ".", "The", "schedule", "generation", "considers", "short", "periods", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/time/ScheduleGenerator.java#L745-L774
159,927
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/curves/locallinearregression/CurveEstimation.java
CurveEstimation.getRegressionCurve
public Curve getRegressionCurve(){ // @TODO Add threadsafe lazy init. if(regressionCurve !=null) { return regressionCurve; } DoubleMatrix a = solveEquationSystem(); double[] curvePoints=new double[partition.getLength()]; curvePoints[0]=a.get(0); for(int i=1;i<curvePoints.length;i++) { curvePoints[i]=curvePoints[i-1]+a.get(i)*(partition.getIntervalLength(i-1)); } return new CurveInterpolation( "RegressionCurve", referenceDate, CurveInterpolation.InterpolationMethod.LINEAR, CurveInterpolation.ExtrapolationMethod.CONSTANT, CurveInterpolation.InterpolationEntity.VALUE, partition.getPoints(), curvePoints); }
java
public Curve getRegressionCurve(){ // @TODO Add threadsafe lazy init. if(regressionCurve !=null) { return regressionCurve; } DoubleMatrix a = solveEquationSystem(); double[] curvePoints=new double[partition.getLength()]; curvePoints[0]=a.get(0); for(int i=1;i<curvePoints.length;i++) { curvePoints[i]=curvePoints[i-1]+a.get(i)*(partition.getIntervalLength(i-1)); } return new CurveInterpolation( "RegressionCurve", referenceDate, CurveInterpolation.InterpolationMethod.LINEAR, CurveInterpolation.ExtrapolationMethod.CONSTANT, CurveInterpolation.InterpolationEntity.VALUE, partition.getPoints(), curvePoints); }
[ "public", "Curve", "getRegressionCurve", "(", ")", "{", "// @TODO Add threadsafe lazy init.", "if", "(", "regressionCurve", "!=", "null", ")", "{", "return", "regressionCurve", ";", "}", "DoubleMatrix", "a", "=", "solveEquationSystem", "(", ")", ";", "double", "[", "]", "curvePoints", "=", "new", "double", "[", "partition", ".", "getLength", "(", ")", "]", ";", "curvePoints", "[", "0", "]", "=", "a", ".", "get", "(", "0", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "curvePoints", ".", "length", ";", "i", "++", ")", "{", "curvePoints", "[", "i", "]", "=", "curvePoints", "[", "i", "-", "1", "]", "+", "a", ".", "get", "(", "i", ")", "*", "(", "partition", ".", "getIntervalLength", "(", "i", "-", "1", ")", ")", ";", "}", "return", "new", "CurveInterpolation", "(", "\"RegressionCurve\"", ",", "referenceDate", ",", "CurveInterpolation", ".", "InterpolationMethod", ".", "LINEAR", ",", "CurveInterpolation", ".", "ExtrapolationMethod", ".", "CONSTANT", ",", "CurveInterpolation", ".", "InterpolationEntity", ".", "VALUE", ",", "partition", ".", "getPoints", "(", ")", ",", "curvePoints", ")", ";", "}" ]
Returns the curve resulting from the local linear regression with discrete kernel. @return The regression curve.
[ "Returns", "the", "curve", "resulting", "from", "the", "local", "linear", "regression", "with", "discrete", "kernel", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/curves/locallinearregression/CurveEstimation.java#L123-L142
159,928
finmath/finmath-lib
src/main/java/net/finmath/marketdata/products/Cap.java
Cap.getValueAsPrice
public double getValueAsPrice(double evaluationTime, AnalyticModel model) { ForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName); DiscountCurve discountCurve = model.getDiscountCurve(discountCurveName); DiscountCurve discountCurveForForward = null; if(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) { // User might like to get forward from discount curve. discountCurveForForward = model.getDiscountCurve(forwardCurveName); if(discountCurveForForward == null) { // User specified a name for the forward curve, but no curve was found. throw new IllegalArgumentException("No curve of the name " + forwardCurveName + " was found in the model."); } } double value = 0.0; for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) { double fixingDate = schedule.getFixing(periodIndex); double paymentDate = schedule.getPayment(periodIndex); double periodLength = schedule.getPeriodLength(periodIndex); /* * We do not count empty periods. * Since empty periods are an indication for a ill-specified product, * it might be reasonable to throw an illegal argument exception instead. */ if(periodLength == 0) { continue; } double forward = 0.0; if(forwardCurve != null) { forward += forwardCurve.getForward(model, fixingDate, paymentDate-fixingDate); } else if(discountCurveForForward != null) { /* * Classical single curve case: using a discount curve as a forward curve. * This is only implemented for demonstration purposes (an exception would also be appropriate :-) */ if(fixingDate != paymentDate) { forward += (discountCurveForForward.getDiscountFactor(fixingDate) / discountCurveForForward.getDiscountFactor(paymentDate) - 1.0) / (paymentDate-fixingDate); } } double discountFactor = paymentDate > evaluationTime ? discountCurve.getDiscountFactor(model, paymentDate) : 0.0; double payoffUnit = discountFactor * periodLength; double effektiveStrike = strike; if(isStrikeMoneyness) { effektiveStrike += getATMForward(model, true); } VolatilitySurface volatilitySurface = model.getVolatilitySurface(volatiltiySufaceName); if(volatilitySurface == null) { throw new IllegalArgumentException("Volatility surface not found in model: " + volatiltiySufaceName); } if(volatilitySurface.getQuotingConvention() == QuotingConvention.VOLATILITYLOGNORMAL) { double volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYLOGNORMAL); value += AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit); } else { // Default to normal volatility as quoting convention double volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYNORMAL); value += AnalyticFormulas.bachelierOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit); } } return value / discountCurve.getDiscountFactor(model, evaluationTime); }
java
public double getValueAsPrice(double evaluationTime, AnalyticModel model) { ForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName); DiscountCurve discountCurve = model.getDiscountCurve(discountCurveName); DiscountCurve discountCurveForForward = null; if(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) { // User might like to get forward from discount curve. discountCurveForForward = model.getDiscountCurve(forwardCurveName); if(discountCurveForForward == null) { // User specified a name for the forward curve, but no curve was found. throw new IllegalArgumentException("No curve of the name " + forwardCurveName + " was found in the model."); } } double value = 0.0; for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) { double fixingDate = schedule.getFixing(periodIndex); double paymentDate = schedule.getPayment(periodIndex); double periodLength = schedule.getPeriodLength(periodIndex); /* * We do not count empty periods. * Since empty periods are an indication for a ill-specified product, * it might be reasonable to throw an illegal argument exception instead. */ if(periodLength == 0) { continue; } double forward = 0.0; if(forwardCurve != null) { forward += forwardCurve.getForward(model, fixingDate, paymentDate-fixingDate); } else if(discountCurveForForward != null) { /* * Classical single curve case: using a discount curve as a forward curve. * This is only implemented for demonstration purposes (an exception would also be appropriate :-) */ if(fixingDate != paymentDate) { forward += (discountCurveForForward.getDiscountFactor(fixingDate) / discountCurveForForward.getDiscountFactor(paymentDate) - 1.0) / (paymentDate-fixingDate); } } double discountFactor = paymentDate > evaluationTime ? discountCurve.getDiscountFactor(model, paymentDate) : 0.0; double payoffUnit = discountFactor * periodLength; double effektiveStrike = strike; if(isStrikeMoneyness) { effektiveStrike += getATMForward(model, true); } VolatilitySurface volatilitySurface = model.getVolatilitySurface(volatiltiySufaceName); if(volatilitySurface == null) { throw new IllegalArgumentException("Volatility surface not found in model: " + volatiltiySufaceName); } if(volatilitySurface.getQuotingConvention() == QuotingConvention.VOLATILITYLOGNORMAL) { double volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYLOGNORMAL); value += AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit); } else { // Default to normal volatility as quoting convention double volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYNORMAL); value += AnalyticFormulas.bachelierOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit); } } return value / discountCurve.getDiscountFactor(model, evaluationTime); }
[ "public", "double", "getValueAsPrice", "(", "double", "evaluationTime", ",", "AnalyticModel", "model", ")", "{", "ForwardCurve", "forwardCurve", "=", "model", ".", "getForwardCurve", "(", "forwardCurveName", ")", ";", "DiscountCurve", "discountCurve", "=", "model", ".", "getDiscountCurve", "(", "discountCurveName", ")", ";", "DiscountCurve", "discountCurveForForward", "=", "null", ";", "if", "(", "forwardCurve", "==", "null", "&&", "forwardCurveName", "!=", "null", "&&", "forwardCurveName", ".", "length", "(", ")", ">", "0", ")", "{", "// User might like to get forward from discount curve.", "discountCurveForForward", "=", "model", ".", "getDiscountCurve", "(", "forwardCurveName", ")", ";", "if", "(", "discountCurveForForward", "==", "null", ")", "{", "// User specified a name for the forward curve, but no curve was found.", "throw", "new", "IllegalArgumentException", "(", "\"No curve of the name \"", "+", "forwardCurveName", "+", "\" was found in the model.\"", ")", ";", "}", "}", "double", "value", "=", "0.0", ";", "for", "(", "int", "periodIndex", "=", "0", ";", "periodIndex", "<", "schedule", ".", "getNumberOfPeriods", "(", ")", ";", "periodIndex", "++", ")", "{", "double", "fixingDate", "=", "schedule", ".", "getFixing", "(", "periodIndex", ")", ";", "double", "paymentDate", "=", "schedule", ".", "getPayment", "(", "periodIndex", ")", ";", "double", "periodLength", "=", "schedule", ".", "getPeriodLength", "(", "periodIndex", ")", ";", "/*\n\t\t\t * We do not count empty periods.\n\t\t\t * Since empty periods are an indication for a ill-specified product,\n\t\t\t * it might be reasonable to throw an illegal argument exception instead.\n\t\t\t */", "if", "(", "periodLength", "==", "0", ")", "{", "continue", ";", "}", "double", "forward", "=", "0.0", ";", "if", "(", "forwardCurve", "!=", "null", ")", "{", "forward", "+=", "forwardCurve", ".", "getForward", "(", "model", ",", "fixingDate", ",", "paymentDate", "-", "fixingDate", ")", ";", "}", "else", "if", "(", "discountCurveForForward", "!=", "null", ")", "{", "/*\n\t\t\t\t * Classical single curve case: using a discount curve as a forward curve.\n\t\t\t\t * This is only implemented for demonstration purposes (an exception would also be appropriate :-)\n\t\t\t\t */", "if", "(", "fixingDate", "!=", "paymentDate", ")", "{", "forward", "+=", "(", "discountCurveForForward", ".", "getDiscountFactor", "(", "fixingDate", ")", "/", "discountCurveForForward", ".", "getDiscountFactor", "(", "paymentDate", ")", "-", "1.0", ")", "/", "(", "paymentDate", "-", "fixingDate", ")", ";", "}", "}", "double", "discountFactor", "=", "paymentDate", ">", "evaluationTime", "?", "discountCurve", ".", "getDiscountFactor", "(", "model", ",", "paymentDate", ")", ":", "0.0", ";", "double", "payoffUnit", "=", "discountFactor", "*", "periodLength", ";", "double", "effektiveStrike", "=", "strike", ";", "if", "(", "isStrikeMoneyness", ")", "{", "effektiveStrike", "+=", "getATMForward", "(", "model", ",", "true", ")", ";", "}", "VolatilitySurface", "volatilitySurface", "=", "model", ".", "getVolatilitySurface", "(", "volatiltiySufaceName", ")", ";", "if", "(", "volatilitySurface", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Volatility surface not found in model: \"", "+", "volatiltiySufaceName", ")", ";", "}", "if", "(", "volatilitySurface", ".", "getQuotingConvention", "(", ")", "==", "QuotingConvention", ".", "VOLATILITYLOGNORMAL", ")", "{", "double", "volatility", "=", "volatilitySurface", ".", "getValue", "(", "model", ",", "fixingDate", ",", "effektiveStrike", ",", "VolatilitySurface", ".", "QuotingConvention", ".", "VOLATILITYLOGNORMAL", ")", ";", "value", "+=", "AnalyticFormulas", ".", "blackScholesGeneralizedOptionValue", "(", "forward", ",", "volatility", ",", "fixingDate", ",", "effektiveStrike", ",", "payoffUnit", ")", ";", "}", "else", "{", "// Default to normal volatility as quoting convention", "double", "volatility", "=", "volatilitySurface", ".", "getValue", "(", "model", ",", "fixingDate", ",", "effektiveStrike", ",", "VolatilitySurface", ".", "QuotingConvention", ".", "VOLATILITYNORMAL", ")", ";", "value", "+=", "AnalyticFormulas", ".", "bachelierOptionValue", "(", "forward", ",", "volatility", ",", "fixingDate", ",", "effektiveStrike", ",", "payoffUnit", ")", ";", "}", "}", "return", "value", "/", "discountCurve", ".", "getDiscountFactor", "(", "model", ",", "evaluationTime", ")", ";", "}" ]
Returns the value of this product under the given model. @param evaluationTime Evaluation time. @param model The model. @return Value of this product und the given model.
[ "Returns", "the", "value", "of", "this", "product", "under", "the", "given", "model", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/products/Cap.java#L115-L183
159,929
finmath/finmath-lib
src/main/java6/net/finmath/optimizer/LevenbergMarquardt.java
LevenbergMarquardt.setDerivatives
public void setDerivatives(double[] parameters, double[][] derivatives) throws SolverException { // Calculate new derivatives. Note that this method is called only with // parameters = parameterCurrent, so we may use valueCurrent. Vector<Future<double[]>> valueFutures = new Vector<Future<double[]>>(parameterCurrent.length); for (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) { final double[] parametersNew = parameters.clone(); final double[] derivative = derivatives[parameterIndex]; final int workerParameterIndex = parameterIndex; Callable<double[]> worker = new Callable<double[]>() { public double[] call() { double parameterFiniteDifference; if(parameterSteps != null) { parameterFiniteDifference = parameterSteps[workerParameterIndex]; } else { /* * Try to adaptively set a parameter shift. Note that in some * applications it may be important to set parameterSteps. * appropriately. */ parameterFiniteDifference = (Math.abs(parametersNew[workerParameterIndex]) + 1) * 1E-8; } // Shift parameter value parametersNew[workerParameterIndex] += parameterFiniteDifference; // Calculate derivative as (valueUpShift - valueCurrent) / parameterFiniteDifference try { setValues(parametersNew, derivative); } catch (Exception e) { // We signal an exception to calculate the derivative as NaN Arrays.fill(derivative, Double.NaN); } for (int valueIndex = 0; valueIndex < valueCurrent.length; valueIndex++) { derivative[valueIndex] -= valueCurrent[valueIndex]; derivative[valueIndex] /= parameterFiniteDifference; if(Double.isNaN(derivative[valueIndex])) { derivative[valueIndex] = 0.0; } } return derivative; } }; if(executor != null) { Future<double[]> valueFuture = executor.submit(worker); valueFutures.add(parameterIndex, valueFuture); } else { FutureTask<double[]> valueFutureTask = new FutureTask<double[]>(worker); valueFutureTask.run(); valueFutures.add(parameterIndex, valueFutureTask); } } for (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) { try { derivatives[parameterIndex] = valueFutures.get(parameterIndex).get(); } catch (InterruptedException e) { throw new SolverException(e); } catch (ExecutionException e) { throw new SolverException(e); } } }
java
public void setDerivatives(double[] parameters, double[][] derivatives) throws SolverException { // Calculate new derivatives. Note that this method is called only with // parameters = parameterCurrent, so we may use valueCurrent. Vector<Future<double[]>> valueFutures = new Vector<Future<double[]>>(parameterCurrent.length); for (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) { final double[] parametersNew = parameters.clone(); final double[] derivative = derivatives[parameterIndex]; final int workerParameterIndex = parameterIndex; Callable<double[]> worker = new Callable<double[]>() { public double[] call() { double parameterFiniteDifference; if(parameterSteps != null) { parameterFiniteDifference = parameterSteps[workerParameterIndex]; } else { /* * Try to adaptively set a parameter shift. Note that in some * applications it may be important to set parameterSteps. * appropriately. */ parameterFiniteDifference = (Math.abs(parametersNew[workerParameterIndex]) + 1) * 1E-8; } // Shift parameter value parametersNew[workerParameterIndex] += parameterFiniteDifference; // Calculate derivative as (valueUpShift - valueCurrent) / parameterFiniteDifference try { setValues(parametersNew, derivative); } catch (Exception e) { // We signal an exception to calculate the derivative as NaN Arrays.fill(derivative, Double.NaN); } for (int valueIndex = 0; valueIndex < valueCurrent.length; valueIndex++) { derivative[valueIndex] -= valueCurrent[valueIndex]; derivative[valueIndex] /= parameterFiniteDifference; if(Double.isNaN(derivative[valueIndex])) { derivative[valueIndex] = 0.0; } } return derivative; } }; if(executor != null) { Future<double[]> valueFuture = executor.submit(worker); valueFutures.add(parameterIndex, valueFuture); } else { FutureTask<double[]> valueFutureTask = new FutureTask<double[]>(worker); valueFutureTask.run(); valueFutures.add(parameterIndex, valueFutureTask); } } for (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) { try { derivatives[parameterIndex] = valueFutures.get(parameterIndex).get(); } catch (InterruptedException e) { throw new SolverException(e); } catch (ExecutionException e) { throw new SolverException(e); } } }
[ "public", "void", "setDerivatives", "(", "double", "[", "]", "parameters", ",", "double", "[", "]", "[", "]", "derivatives", ")", "throws", "SolverException", "{", "// Calculate new derivatives. Note that this method is called only with", "// parameters = parameterCurrent, so we may use valueCurrent.", "Vector", "<", "Future", "<", "double", "[", "]", ">", ">", "valueFutures", "=", "new", "Vector", "<", "Future", "<", "double", "[", "]", ">", ">", "(", "parameterCurrent", ".", "length", ")", ";", "for", "(", "int", "parameterIndex", "=", "0", ";", "parameterIndex", "<", "parameterCurrent", ".", "length", ";", "parameterIndex", "++", ")", "{", "final", "double", "[", "]", "parametersNew", "=", "parameters", ".", "clone", "(", ")", ";", "final", "double", "[", "]", "derivative", "=", "derivatives", "[", "parameterIndex", "]", ";", "final", "int", "workerParameterIndex", "=", "parameterIndex", ";", "Callable", "<", "double", "[", "]", ">", "worker", "=", "new", "Callable", "<", "double", "[", "]", ">", "(", ")", "{", "public", "double", "[", "]", "call", "(", ")", "{", "double", "parameterFiniteDifference", ";", "if", "(", "parameterSteps", "!=", "null", ")", "{", "parameterFiniteDifference", "=", "parameterSteps", "[", "workerParameterIndex", "]", ";", "}", "else", "{", "/*\n\t\t\t\t\t\t * Try to adaptively set a parameter shift. Note that in some\n\t\t\t\t\t\t * applications it may be important to set parameterSteps.\n\t\t\t\t\t\t * appropriately.\n\t\t\t\t\t\t */", "parameterFiniteDifference", "=", "(", "Math", ".", "abs", "(", "parametersNew", "[", "workerParameterIndex", "]", ")", "+", "1", ")", "*", "1E-8", ";", "}", "// Shift parameter value", "parametersNew", "[", "workerParameterIndex", "]", "+=", "parameterFiniteDifference", ";", "// Calculate derivative as (valueUpShift - valueCurrent) / parameterFiniteDifference", "try", "{", "setValues", "(", "parametersNew", ",", "derivative", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// We signal an exception to calculate the derivative as NaN", "Arrays", ".", "fill", "(", "derivative", ",", "Double", ".", "NaN", ")", ";", "}", "for", "(", "int", "valueIndex", "=", "0", ";", "valueIndex", "<", "valueCurrent", ".", "length", ";", "valueIndex", "++", ")", "{", "derivative", "[", "valueIndex", "]", "-=", "valueCurrent", "[", "valueIndex", "]", ";", "derivative", "[", "valueIndex", "]", "/=", "parameterFiniteDifference", ";", "if", "(", "Double", ".", "isNaN", "(", "derivative", "[", "valueIndex", "]", ")", ")", "{", "derivative", "[", "valueIndex", "]", "=", "0.0", ";", "}", "}", "return", "derivative", ";", "}", "}", ";", "if", "(", "executor", "!=", "null", ")", "{", "Future", "<", "double", "[", "]", ">", "valueFuture", "=", "executor", ".", "submit", "(", "worker", ")", ";", "valueFutures", ".", "add", "(", "parameterIndex", ",", "valueFuture", ")", ";", "}", "else", "{", "FutureTask", "<", "double", "[", "]", ">", "valueFutureTask", "=", "new", "FutureTask", "<", "double", "[", "]", ">", "(", "worker", ")", ";", "valueFutureTask", ".", "run", "(", ")", ";", "valueFutures", ".", "add", "(", "parameterIndex", ",", "valueFutureTask", ")", ";", "}", "}", "for", "(", "int", "parameterIndex", "=", "0", ";", "parameterIndex", "<", "parameterCurrent", ".", "length", ";", "parameterIndex", "++", ")", "{", "try", "{", "derivatives", "[", "parameterIndex", "]", "=", "valueFutures", ".", "get", "(", "parameterIndex", ")", ".", "get", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "throw", "new", "SolverException", "(", "e", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "throw", "new", "SolverException", "(", "e", ")", ";", "}", "}", "}" ]
The derivative of the objective function. You may override this method if you like to implement your own derivative. @param parameters Input value. The parameter vector. @param derivatives Output value, where derivatives[i][j] is d(value(j)) / d(parameters(i) @throws SolverException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
[ "The", "derivative", "of", "the", "objective", "function", ".", "You", "may", "override", "this", "method", "if", "you", "like", "to", "implement", "your", "own", "derivative", "." ]
a3c067d52dd33feb97d851df6cab130e4116759f
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/optimizer/LevenbergMarquardt.java#L547-L613
159,930
spring-cloud/spring-cloud-stream-app-starters
processor/spring-cloud-starter-stream-processor-tasklaunchrequest-transform/src/main/java/org/springframework/cloud/stream/app/tasklaunchrequest/transform/processor/TasklaunchrequestTransformProcessorConfiguration.java
TasklaunchrequestTransformProcessorConfiguration.parseParams
private List<String> parseParams(String param) { Assert.hasText(param, "param must not be empty nor null"); List<String> paramsToUse = new ArrayList<>(); Matcher regexMatcher = DEPLOYMENT_PARAMS_PATTERN.matcher(param); int start = 0; while (regexMatcher.find()) { String p = removeQuoting(param.substring(start, regexMatcher.start()).trim()); if (StringUtils.hasText(p)) { paramsToUse.add(p); } start = regexMatcher.start(); } if (param != null && param.length() > 0) { String p = removeQuoting(param.substring(start, param.length()).trim()); if (StringUtils.hasText(p)) { paramsToUse.add(p); } } return paramsToUse; }
java
private List<String> parseParams(String param) { Assert.hasText(param, "param must not be empty nor null"); List<String> paramsToUse = new ArrayList<>(); Matcher regexMatcher = DEPLOYMENT_PARAMS_PATTERN.matcher(param); int start = 0; while (regexMatcher.find()) { String p = removeQuoting(param.substring(start, regexMatcher.start()).trim()); if (StringUtils.hasText(p)) { paramsToUse.add(p); } start = regexMatcher.start(); } if (param != null && param.length() > 0) { String p = removeQuoting(param.substring(start, param.length()).trim()); if (StringUtils.hasText(p)) { paramsToUse.add(p); } } return paramsToUse; }
[ "private", "List", "<", "String", ">", "parseParams", "(", "String", "param", ")", "{", "Assert", ".", "hasText", "(", "param", ",", "\"param must not be empty nor null\"", ")", ";", "List", "<", "String", ">", "paramsToUse", "=", "new", "ArrayList", "<>", "(", ")", ";", "Matcher", "regexMatcher", "=", "DEPLOYMENT_PARAMS_PATTERN", ".", "matcher", "(", "param", ")", ";", "int", "start", "=", "0", ";", "while", "(", "regexMatcher", ".", "find", "(", ")", ")", "{", "String", "p", "=", "removeQuoting", "(", "param", ".", "substring", "(", "start", ",", "regexMatcher", ".", "start", "(", ")", ")", ".", "trim", "(", ")", ")", ";", "if", "(", "StringUtils", ".", "hasText", "(", "p", ")", ")", "{", "paramsToUse", ".", "add", "(", "p", ")", ";", "}", "start", "=", "regexMatcher", ".", "start", "(", ")", ";", "}", "if", "(", "param", "!=", "null", "&&", "param", ".", "length", "(", ")", ">", "0", ")", "{", "String", "p", "=", "removeQuoting", "(", "param", ".", "substring", "(", "start", ",", "param", ".", "length", "(", ")", ")", ".", "trim", "(", ")", ")", ";", "if", "(", "StringUtils", ".", "hasText", "(", "p", ")", ")", "{", "paramsToUse", ".", "add", "(", "p", ")", ";", "}", "}", "return", "paramsToUse", ";", "}" ]
Parses a string of space delimited command line parameters and returns a list of parameters which doesn't contain any special quoting either for values or whole parameter. @param param string containing a list @return the list
[ "Parses", "a", "string", "of", "space", "delimited", "command", "line", "parameters", "and", "returns", "a", "list", "of", "parameters", "which", "doesn", "t", "contain", "any", "special", "quoting", "either", "for", "values", "or", "whole", "parameter", "." ]
c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9
https://github.com/spring-cloud/spring-cloud-stream-app-starters/blob/c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9/processor/spring-cloud-starter-stream-processor-tasklaunchrequest-transform/src/main/java/org/springframework/cloud/stream/app/tasklaunchrequest/transform/processor/TasklaunchrequestTransformProcessorConfiguration.java#L136-L155
159,931
spring-cloud/spring-cloud-stream-app-starters
gpfdist/spring-cloud-starter-stream-sink-gpfdist/src/main/java/org/springframework/cloud/stream/app/gpfdist/sink/support/SqlUtils.java
SqlUtils.load
public static String load(LoadConfiguration config, String prefix) { if (config.getMode() == Mode.INSERT) { return loadInsert(config, prefix); } else if (config.getMode() == Mode.UPDATE) { return loadUpdate(config, prefix); } throw new IllegalArgumentException("Unsupported mode " + config.getMode()); }
java
public static String load(LoadConfiguration config, String prefix) { if (config.getMode() == Mode.INSERT) { return loadInsert(config, prefix); } else if (config.getMode() == Mode.UPDATE) { return loadUpdate(config, prefix); } throw new IllegalArgumentException("Unsupported mode " + config.getMode()); }
[ "public", "static", "String", "load", "(", "LoadConfiguration", "config", ",", "String", "prefix", ")", "{", "if", "(", "config", ".", "getMode", "(", ")", "==", "Mode", ".", "INSERT", ")", "{", "return", "loadInsert", "(", "config", ",", "prefix", ")", ";", "}", "else", "if", "(", "config", ".", "getMode", "(", ")", "==", "Mode", ".", "UPDATE", ")", "{", "return", "loadUpdate", "(", "config", ",", "prefix", ")", ";", "}", "throw", "new", "IllegalArgumentException", "(", "\"Unsupported mode \"", "+", "config", ".", "getMode", "(", ")", ")", ";", "}" ]
Builds sql clause to load data into a database. @param config Load configuration. @param prefix Prefix for temporary resources. @return the load DDL
[ "Builds", "sql", "clause", "to", "load", "data", "into", "a", "database", "." ]
c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9
https://github.com/spring-cloud/spring-cloud-stream-app-starters/blob/c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9/gpfdist/spring-cloud-starter-stream-sink-gpfdist/src/main/java/org/springframework/cloud/stream/app/gpfdist/sink/support/SqlUtils.java#L158-L166
159,932
spring-cloud/spring-cloud-stream-app-starters
triggertask/spring-cloud-starter-stream-source-triggertask/src/main/java/org/springframework/cloud/stream/app/triggertask/source/TriggertaskSourceConfiguration.java
TriggertaskSourceConfiguration.parseProperties
public static Map<String, String> parseProperties(String s) { Map<String, String> properties = new HashMap<String, String>(); if (!StringUtils.isEmpty(s)) { Matcher matcher = PROPERTIES_PATTERN.matcher(s); int start = 0; while (matcher.find()) { addKeyValuePairAsProperty(s.substring(start, matcher.start()), properties); start = matcher.start() + 1; } addKeyValuePairAsProperty(s.substring(start), properties); } return properties; }
java
public static Map<String, String> parseProperties(String s) { Map<String, String> properties = new HashMap<String, String>(); if (!StringUtils.isEmpty(s)) { Matcher matcher = PROPERTIES_PATTERN.matcher(s); int start = 0; while (matcher.find()) { addKeyValuePairAsProperty(s.substring(start, matcher.start()), properties); start = matcher.start() + 1; } addKeyValuePairAsProperty(s.substring(start), properties); } return properties; }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "parseProperties", "(", "String", "s", ")", "{", "Map", "<", "String", ",", "String", ">", "properties", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "if", "(", "!", "StringUtils", ".", "isEmpty", "(", "s", ")", ")", "{", "Matcher", "matcher", "=", "PROPERTIES_PATTERN", ".", "matcher", "(", "s", ")", ";", "int", "start", "=", "0", ";", "while", "(", "matcher", ".", "find", "(", ")", ")", "{", "addKeyValuePairAsProperty", "(", "s", ".", "substring", "(", "start", ",", "matcher", ".", "start", "(", ")", ")", ",", "properties", ")", ";", "start", "=", "matcher", ".", "start", "(", ")", "+", "1", ";", "}", "addKeyValuePairAsProperty", "(", "s", ".", "substring", "(", "start", ")", ",", "properties", ")", ";", "}", "return", "properties", ";", "}" ]
Parses a String comprised of 0 or more comma-delimited key=value pairs. @param s the string to parse @return the Map of parsed key value pairs
[ "Parses", "a", "String", "comprised", "of", "0", "or", "more", "comma", "-", "delimited", "key", "=", "value", "pairs", "." ]
c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9
https://github.com/spring-cloud/spring-cloud-stream-app-starters/blob/c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9/triggertask/spring-cloud-starter-stream-source-triggertask/src/main/java/org/springframework/cloud/stream/app/triggertask/source/TriggertaskSourceConfiguration.java#L93-L105
159,933
spring-cloud/spring-cloud-stream-app-starters
gpfdist/spring-cloud-starter-stream-sink-gpfdist/src/main/java/org/springframework/cloud/stream/app/gpfdist/sink/GpfdistServer.java
GpfdistServer.start
public synchronized HttpServer<Buffer, Buffer> start() throws Exception { if (server == null) { server = createProtocolListener(); } return server; }
java
public synchronized HttpServer<Buffer, Buffer> start() throws Exception { if (server == null) { server = createProtocolListener(); } return server; }
[ "public", "synchronized", "HttpServer", "<", "Buffer", ",", "Buffer", ">", "start", "(", ")", "throws", "Exception", "{", "if", "(", "server", "==", "null", ")", "{", "server", "=", "createProtocolListener", "(", ")", ";", "}", "return", "server", ";", "}" ]
Start a server. @return the http server @throws Exception the exception
[ "Start", "a", "server", "." ]
c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9
https://github.com/spring-cloud/spring-cloud-stream-app-starters/blob/c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9/gpfdist/spring-cloud-starter-stream-sink-gpfdist/src/main/java/org/springframework/cloud/stream/app/gpfdist/sink/GpfdistServer.java#L82-L87
159,934
spring-cloud/spring-cloud-stream-app-starters
gpfdist/spring-cloud-starter-stream-sink-gpfdist/src/main/java/org/springframework/cloud/stream/app/gpfdist/sink/support/ReadableTableFactoryBean.java
ReadableTableFactoryBean.setSegmentReject
public void setSegmentReject(String reject) { if (!StringUtils.hasText(reject)) { return; } Integer parsedLimit = null; try { parsedLimit = Integer.parseInt(reject); segmentRejectType = SegmentRejectType.ROWS; } catch (NumberFormatException e) { } if (parsedLimit == null && reject.contains("%")) { try { parsedLimit = Integer.parseInt(reject.replace("%", "").trim()); segmentRejectType = SegmentRejectType.PERCENT; } catch (NumberFormatException e) { } } segmentRejectLimit = parsedLimit; }
java
public void setSegmentReject(String reject) { if (!StringUtils.hasText(reject)) { return; } Integer parsedLimit = null; try { parsedLimit = Integer.parseInt(reject); segmentRejectType = SegmentRejectType.ROWS; } catch (NumberFormatException e) { } if (parsedLimit == null && reject.contains("%")) { try { parsedLimit = Integer.parseInt(reject.replace("%", "").trim()); segmentRejectType = SegmentRejectType.PERCENT; } catch (NumberFormatException e) { } } segmentRejectLimit = parsedLimit; }
[ "public", "void", "setSegmentReject", "(", "String", "reject", ")", "{", "if", "(", "!", "StringUtils", ".", "hasText", "(", "reject", ")", ")", "{", "return", ";", "}", "Integer", "parsedLimit", "=", "null", ";", "try", "{", "parsedLimit", "=", "Integer", ".", "parseInt", "(", "reject", ")", ";", "segmentRejectType", "=", "SegmentRejectType", ".", "ROWS", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "}", "if", "(", "parsedLimit", "==", "null", "&&", "reject", ".", "contains", "(", "\"%\"", ")", ")", "{", "try", "{", "parsedLimit", "=", "Integer", ".", "parseInt", "(", "reject", ".", "replace", "(", "\"%\"", ",", "\"\"", ")", ".", "trim", "(", ")", ")", ";", "segmentRejectType", "=", "SegmentRejectType", ".", "PERCENT", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "}", "}", "segmentRejectLimit", "=", "parsedLimit", ";", "}" ]
Sets the segment reject as a string. This method is for convenience to be able to set percent reject type just by calling with '3%' and otherwise it uses rows. All this assuming that parsing finds '%' characher and is able to parse a raw reject number. @param reject the new segment reject
[ "Sets", "the", "segment", "reject", "as", "a", "string", ".", "This", "method", "is", "for", "convenience", "to", "be", "able", "to", "set", "percent", "reject", "type", "just", "by", "calling", "with", "3%", "and", "otherwise", "it", "uses", "rows", ".", "All", "this", "assuming", "that", "parsing", "finds", "%", "characher", "and", "is", "able", "to", "parse", "a", "raw", "reject", "number", "." ]
c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9
https://github.com/spring-cloud/spring-cloud-stream-app-starters/blob/c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9/gpfdist/spring-cloud-starter-stream-sink-gpfdist/src/main/java/org/springframework/cloud/stream/app/gpfdist/sink/support/ReadableTableFactoryBean.java#L133-L151
159,935
spring-cloud/spring-cloud-stream-app-starters
twitter/spring-cloud-starter-stream-source-twitterstream/src/main/java/org/springframework/cloud/stream/app/twitterstream/source/AbstractTwitterInboundChannelAdapter.java
AbstractTwitterInboundChannelAdapter.setReadTimeout
public void setReadTimeout(int millis) { // Hack to get round Spring's dynamic loading of http client stuff ClientHttpRequestFactory f = getRequestFactory(); if (f instanceof SimpleClientHttpRequestFactory) { ((SimpleClientHttpRequestFactory) f).setReadTimeout(millis); } else { ((HttpComponentsClientHttpRequestFactory) f).setReadTimeout(millis); } }
java
public void setReadTimeout(int millis) { // Hack to get round Spring's dynamic loading of http client stuff ClientHttpRequestFactory f = getRequestFactory(); if (f instanceof SimpleClientHttpRequestFactory) { ((SimpleClientHttpRequestFactory) f).setReadTimeout(millis); } else { ((HttpComponentsClientHttpRequestFactory) f).setReadTimeout(millis); } }
[ "public", "void", "setReadTimeout", "(", "int", "millis", ")", "{", "// Hack to get round Spring's dynamic loading of http client stuff", "ClientHttpRequestFactory", "f", "=", "getRequestFactory", "(", ")", ";", "if", "(", "f", "instanceof", "SimpleClientHttpRequestFactory", ")", "{", "(", "(", "SimpleClientHttpRequestFactory", ")", "f", ")", ".", "setReadTimeout", "(", "millis", ")", ";", "}", "else", "{", "(", "(", "HttpComponentsClientHttpRequestFactory", ")", "f", ")", ".", "setReadTimeout", "(", "millis", ")", ";", "}", "}" ]
The read timeout for the underlying URLConnection to the twitter stream.
[ "The", "read", "timeout", "for", "the", "underlying", "URLConnection", "to", "the", "twitter", "stream", "." ]
c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9
https://github.com/spring-cloud/spring-cloud-stream-app-starters/blob/c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9/twitter/spring-cloud-starter-stream-source-twitterstream/src/main/java/org/springframework/cloud/stream/app/twitterstream/source/AbstractTwitterInboundChannelAdapter.java#L83-L92
159,936
spring-cloud/spring-cloud-stream-app-starters
twitter/spring-cloud-starter-stream-source-twitterstream/src/main/java/org/springframework/cloud/stream/app/twitterstream/source/AbstractTwitterInboundChannelAdapter.java
AbstractTwitterInboundChannelAdapter.setConnectTimeout
public void setConnectTimeout(int millis) { ClientHttpRequestFactory f = getRequestFactory(); if (f instanceof SimpleClientHttpRequestFactory) { ((SimpleClientHttpRequestFactory) f).setConnectTimeout(millis); } else { ((HttpComponentsClientHttpRequestFactory) f).setConnectTimeout(millis); } }
java
public void setConnectTimeout(int millis) { ClientHttpRequestFactory f = getRequestFactory(); if (f instanceof SimpleClientHttpRequestFactory) { ((SimpleClientHttpRequestFactory) f).setConnectTimeout(millis); } else { ((HttpComponentsClientHttpRequestFactory) f).setConnectTimeout(millis); } }
[ "public", "void", "setConnectTimeout", "(", "int", "millis", ")", "{", "ClientHttpRequestFactory", "f", "=", "getRequestFactory", "(", ")", ";", "if", "(", "f", "instanceof", "SimpleClientHttpRequestFactory", ")", "{", "(", "(", "SimpleClientHttpRequestFactory", ")", "f", ")", ".", "setConnectTimeout", "(", "millis", ")", ";", "}", "else", "{", "(", "(", "HttpComponentsClientHttpRequestFactory", ")", "f", ")", ".", "setConnectTimeout", "(", "millis", ")", ";", "}", "}" ]
The connection timeout for making a connection to Twitter.
[ "The", "connection", "timeout", "for", "making", "a", "connection", "to", "Twitter", "." ]
c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9
https://github.com/spring-cloud/spring-cloud-stream-app-starters/blob/c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9/twitter/spring-cloud-starter-stream-source-twitterstream/src/main/java/org/springframework/cloud/stream/app/twitterstream/source/AbstractTwitterInboundChannelAdapter.java#L97-L105
159,937
spring-cloud/spring-cloud-stream-app-starters
websocket/spring-cloud-starter-stream-sink-websocket/src/main/java/org/springframework/cloud/stream/app/websocket/sink/WebsocketSinkServerHandler.java
WebsocketSinkServerHandler.handleTextWebSocketFrameInternal
private void handleTextWebSocketFrameInternal(TextWebSocketFrame frame, ChannelHandlerContext ctx) { if (logger.isTraceEnabled()) { logger.trace(String.format("%s received %s", ctx.channel(), frame.text())); } addTraceForFrame(frame, "text"); ctx.channel().write(new TextWebSocketFrame("Echo: " + frame.text())); }
java
private void handleTextWebSocketFrameInternal(TextWebSocketFrame frame, ChannelHandlerContext ctx) { if (logger.isTraceEnabled()) { logger.trace(String.format("%s received %s", ctx.channel(), frame.text())); } addTraceForFrame(frame, "text"); ctx.channel().write(new TextWebSocketFrame("Echo: " + frame.text())); }
[ "private", "void", "handleTextWebSocketFrameInternal", "(", "TextWebSocketFrame", "frame", ",", "ChannelHandlerContext", "ctx", ")", "{", "if", "(", "logger", ".", "isTraceEnabled", "(", ")", ")", "{", "logger", ".", "trace", "(", "String", ".", "format", "(", "\"%s received %s\"", ",", "ctx", ".", "channel", "(", ")", ",", "frame", ".", "text", "(", ")", ")", ")", ";", "}", "addTraceForFrame", "(", "frame", ",", "\"text\"", ")", ";", "ctx", ".", "channel", "(", ")", ".", "write", "(", "new", "TextWebSocketFrame", "(", "\"Echo: \"", "+", "frame", ".", "text", "(", ")", ")", ")", ";", "}" ]
simple echo implementation
[ "simple", "echo", "implementation" ]
c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9
https://github.com/spring-cloud/spring-cloud-stream-app-starters/blob/c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9/websocket/spring-cloud-starter-stream-sink-websocket/src/main/java/org/springframework/cloud/stream/app/websocket/sink/WebsocketSinkServerHandler.java#L157-L164
159,938
spring-cloud/spring-cloud-stream-app-starters
websocket/spring-cloud-starter-stream-sink-websocket/src/main/java/org/springframework/cloud/stream/app/websocket/sink/WebsocketSinkServerHandler.java
WebsocketSinkServerHandler.addTraceForFrame
private void addTraceForFrame(WebSocketFrame frame, String type) { Map<String, Object> trace = new LinkedHashMap<>(); trace.put("type", type); trace.put("direction", "in"); if (frame instanceof TextWebSocketFrame) { trace.put("payload", ((TextWebSocketFrame) frame).text()); } if (traceEnabled) { websocketTraceRepository.add(trace); } }
java
private void addTraceForFrame(WebSocketFrame frame, String type) { Map<String, Object> trace = new LinkedHashMap<>(); trace.put("type", type); trace.put("direction", "in"); if (frame instanceof TextWebSocketFrame) { trace.put("payload", ((TextWebSocketFrame) frame).text()); } if (traceEnabled) { websocketTraceRepository.add(trace); } }
[ "private", "void", "addTraceForFrame", "(", "WebSocketFrame", "frame", ",", "String", "type", ")", "{", "Map", "<", "String", ",", "Object", ">", "trace", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "trace", ".", "put", "(", "\"type\"", ",", "type", ")", ";", "trace", ".", "put", "(", "\"direction\"", ",", "\"in\"", ")", ";", "if", "(", "frame", "instanceof", "TextWebSocketFrame", ")", "{", "trace", ".", "put", "(", "\"payload\"", ",", "(", "(", "TextWebSocketFrame", ")", "frame", ")", ".", "text", "(", ")", ")", ";", "}", "if", "(", "traceEnabled", ")", "{", "websocketTraceRepository", ".", "add", "(", "trace", ")", ";", "}", "}" ]
add trace information for received frame
[ "add", "trace", "information", "for", "received", "frame" ]
c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9
https://github.com/spring-cloud/spring-cloud-stream-app-starters/blob/c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9/websocket/spring-cloud-starter-stream-sink-websocket/src/main/java/org/springframework/cloud/stream/app/websocket/sink/WebsocketSinkServerHandler.java#L167-L178
159,939
spring-cloud/spring-cloud-stream-app-starters
mail/spring-cloud-starter-stream-source-mail/src/main/java/org/springframework/cloud/stream/app/mail/source/MailSourceConfiguration.java
MailSourceConfiguration.getFlowBuilder
@SuppressWarnings({ "rawtypes", "unchecked" }) private IntegrationFlowBuilder getFlowBuilder() { IntegrationFlowBuilder flowBuilder; URLName urlName = this.properties.getUrl(); if (this.properties.isIdleImap()) { flowBuilder = getIdleImapFlow(urlName); } else { MailInboundChannelAdapterSpec adapterSpec; switch (urlName.getProtocol().toUpperCase()) { case "IMAP": case "IMAPS": adapterSpec = getImapFlowBuilder(urlName); break; case "POP3": case "POP3S": adapterSpec = getPop3FlowBuilder(urlName); break; default: throw new IllegalArgumentException( "Unsupported mail protocol: " + urlName.getProtocol()); } flowBuilder = IntegrationFlows.from( adapterSpec.javaMailProperties(getJavaMailProperties(urlName)) .selectorExpression(this.properties.getExpression()) .shouldDeleteMessages(this.properties.isDelete()), new Consumer<SourcePollingChannelAdapterSpec>() { @Override public void accept( SourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) { sourcePollingChannelAdapterSpec.poller(MailSourceConfiguration.this.defaultPoller); } }); } return flowBuilder; }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) private IntegrationFlowBuilder getFlowBuilder() { IntegrationFlowBuilder flowBuilder; URLName urlName = this.properties.getUrl(); if (this.properties.isIdleImap()) { flowBuilder = getIdleImapFlow(urlName); } else { MailInboundChannelAdapterSpec adapterSpec; switch (urlName.getProtocol().toUpperCase()) { case "IMAP": case "IMAPS": adapterSpec = getImapFlowBuilder(urlName); break; case "POP3": case "POP3S": adapterSpec = getPop3FlowBuilder(urlName); break; default: throw new IllegalArgumentException( "Unsupported mail protocol: " + urlName.getProtocol()); } flowBuilder = IntegrationFlows.from( adapterSpec.javaMailProperties(getJavaMailProperties(urlName)) .selectorExpression(this.properties.getExpression()) .shouldDeleteMessages(this.properties.isDelete()), new Consumer<SourcePollingChannelAdapterSpec>() { @Override public void accept( SourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) { sourcePollingChannelAdapterSpec.poller(MailSourceConfiguration.this.defaultPoller); } }); } return flowBuilder; }
[ "@", "SuppressWarnings", "(", "{", "\"rawtypes\"", ",", "\"unchecked\"", "}", ")", "private", "IntegrationFlowBuilder", "getFlowBuilder", "(", ")", "{", "IntegrationFlowBuilder", "flowBuilder", ";", "URLName", "urlName", "=", "this", ".", "properties", ".", "getUrl", "(", ")", ";", "if", "(", "this", ".", "properties", ".", "isIdleImap", "(", ")", ")", "{", "flowBuilder", "=", "getIdleImapFlow", "(", "urlName", ")", ";", "}", "else", "{", "MailInboundChannelAdapterSpec", "adapterSpec", ";", "switch", "(", "urlName", ".", "getProtocol", "(", ")", ".", "toUpperCase", "(", ")", ")", "{", "case", "\"IMAP\"", ":", "case", "\"IMAPS\"", ":", "adapterSpec", "=", "getImapFlowBuilder", "(", "urlName", ")", ";", "break", ";", "case", "\"POP3\"", ":", "case", "\"POP3S\"", ":", "adapterSpec", "=", "getPop3FlowBuilder", "(", "urlName", ")", ";", "break", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Unsupported mail protocol: \"", "+", "urlName", ".", "getProtocol", "(", ")", ")", ";", "}", "flowBuilder", "=", "IntegrationFlows", ".", "from", "(", "adapterSpec", ".", "javaMailProperties", "(", "getJavaMailProperties", "(", "urlName", ")", ")", ".", "selectorExpression", "(", "this", ".", "properties", ".", "getExpression", "(", ")", ")", ".", "shouldDeleteMessages", "(", "this", ".", "properties", ".", "isDelete", "(", ")", ")", ",", "new", "Consumer", "<", "SourcePollingChannelAdapterSpec", ">", "(", ")", "{", "@", "Override", "public", "void", "accept", "(", "SourcePollingChannelAdapterSpec", "sourcePollingChannelAdapterSpec", ")", "{", "sourcePollingChannelAdapterSpec", ".", "poller", "(", "MailSourceConfiguration", ".", "this", ".", "defaultPoller", ")", ";", "}", "}", ")", ";", "}", "return", "flowBuilder", ";", "}" ]
Method to build Integration Flow for Mail. Suppress Warnings for MailInboundChannelAdapterSpec. @return Integration Flow object for Mail Source
[ "Method", "to", "build", "Integration", "Flow", "for", "Mail", ".", "Suppress", "Warnings", "for", "MailInboundChannelAdapterSpec", "." ]
c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9
https://github.com/spring-cloud/spring-cloud-stream-app-starters/blob/c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9/mail/spring-cloud-starter-stream-source-mail/src/main/java/org/springframework/cloud/stream/app/mail/source/MailSourceConfiguration.java#L73-L114
159,940
spring-cloud/spring-cloud-stream-app-starters
mail/spring-cloud-starter-stream-source-mail/src/main/java/org/springframework/cloud/stream/app/mail/source/MailSourceConfiguration.java
MailSourceConfiguration.getIdleImapFlow
private IntegrationFlowBuilder getIdleImapFlow(URLName urlName) { return IntegrationFlows.from(Mail.imapIdleAdapter(urlName.toString()) .shouldDeleteMessages(this.properties.isDelete()) .javaMailProperties(getJavaMailProperties(urlName)) .selectorExpression(this.properties.getExpression()) .shouldMarkMessagesAsRead(this.properties.isMarkAsRead())); }
java
private IntegrationFlowBuilder getIdleImapFlow(URLName urlName) { return IntegrationFlows.from(Mail.imapIdleAdapter(urlName.toString()) .shouldDeleteMessages(this.properties.isDelete()) .javaMailProperties(getJavaMailProperties(urlName)) .selectorExpression(this.properties.getExpression()) .shouldMarkMessagesAsRead(this.properties.isMarkAsRead())); }
[ "private", "IntegrationFlowBuilder", "getIdleImapFlow", "(", "URLName", "urlName", ")", "{", "return", "IntegrationFlows", ".", "from", "(", "Mail", ".", "imapIdleAdapter", "(", "urlName", ".", "toString", "(", ")", ")", ".", "shouldDeleteMessages", "(", "this", ".", "properties", ".", "isDelete", "(", ")", ")", ".", "javaMailProperties", "(", "getJavaMailProperties", "(", "urlName", ")", ")", ".", "selectorExpression", "(", "this", ".", "properties", ".", "getExpression", "(", ")", ")", ".", "shouldMarkMessagesAsRead", "(", "this", ".", "properties", ".", "isMarkAsRead", "(", ")", ")", ")", ";", "}" ]
Method to build Integration flow for IMAP Idle configuration. @param urlName Mail source URL. @return Integration Flow object IMAP IDLE.
[ "Method", "to", "build", "Integration", "flow", "for", "IMAP", "Idle", "configuration", "." ]
c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9
https://github.com/spring-cloud/spring-cloud-stream-app-starters/blob/c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9/mail/spring-cloud-starter-stream-source-mail/src/main/java/org/springframework/cloud/stream/app/mail/source/MailSourceConfiguration.java#L121-L127
159,941
spring-cloud/spring-cloud-stream-app-starters
mail/spring-cloud-starter-stream-source-mail/src/main/java/org/springframework/cloud/stream/app/mail/source/MailSourceConfiguration.java
MailSourceConfiguration.getImapFlowBuilder
@SuppressWarnings("rawtypes") private MailInboundChannelAdapterSpec getImapFlowBuilder(URLName urlName) { return Mail.imapInboundAdapter(urlName.toString()) .shouldMarkMessagesAsRead(this.properties.isMarkAsRead()); }
java
@SuppressWarnings("rawtypes") private MailInboundChannelAdapterSpec getImapFlowBuilder(URLName urlName) { return Mail.imapInboundAdapter(urlName.toString()) .shouldMarkMessagesAsRead(this.properties.isMarkAsRead()); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "private", "MailInboundChannelAdapterSpec", "getImapFlowBuilder", "(", "URLName", "urlName", ")", "{", "return", "Mail", ".", "imapInboundAdapter", "(", "urlName", ".", "toString", "(", ")", ")", ".", "shouldMarkMessagesAsRead", "(", "this", ".", "properties", ".", "isMarkAsRead", "(", ")", ")", ";", "}" ]
Method to build Mail Channel Adapter for IMAP. @param urlName Mail source URL. @return Mail Channel for IMAP
[ "Method", "to", "build", "Mail", "Channel", "Adapter", "for", "IMAP", "." ]
c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9
https://github.com/spring-cloud/spring-cloud-stream-app-starters/blob/c82827a9b5a6eab78fe6a2d56a946b5f9fb0ead9/mail/spring-cloud-starter-stream-source-mail/src/main/java/org/springframework/cloud/stream/app/mail/source/MailSourceConfiguration.java#L144-L148
159,942
spring-projects/spring-social-facebook
spring-social-facebook-web/src/main/java/org/springframework/social/facebook/web/CanvasSignInController.java
CanvasSignInController.postDeclineView
protected View postDeclineView() { return new TopLevelWindowRedirect() { @Override protected String getRedirectUrl(Map<String, ?> model) { return postDeclineUrl; } }; }
java
protected View postDeclineView() { return new TopLevelWindowRedirect() { @Override protected String getRedirectUrl(Map<String, ?> model) { return postDeclineUrl; } }; }
[ "protected", "View", "postDeclineView", "(", ")", "{", "return", "new", "TopLevelWindowRedirect", "(", ")", "{", "@", "Override", "protected", "String", "getRedirectUrl", "(", "Map", "<", "String", ",", "?", ">", "model", ")", "{", "return", "postDeclineUrl", ";", "}", "}", ";", "}" ]
View that redirects the top level window to the URL defined in postDeclineUrl property after user declines to authorize application. May be overridden for custom views, particularly in the case where the post-decline view should be rendered in-canvas. @return a view to display after a user declines authoriation. Defaults as a redirect to postDeclineUrl
[ "View", "that", "redirects", "the", "top", "level", "window", "to", "the", "URL", "defined", "in", "postDeclineUrl", "property", "after", "user", "declines", "to", "authorize", "application", ".", "May", "be", "overridden", "for", "custom", "views", "particularly", "in", "the", "case", "where", "the", "post", "-", "decline", "view", "should", "be", "rendered", "in", "-", "canvas", "." ]
ae2234d94367eaa3adbba251ec7790d5ba7ffa41
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook-web/src/main/java/org/springframework/social/facebook/web/CanvasSignInController.java#L165-L172
159,943
spring-projects/spring-social-facebook
spring-social-facebook-web/src/main/java/org/springframework/social/facebook/web/SignedRequestDecoder.java
SignedRequestDecoder.decodeSignedRequest
@SuppressWarnings("unchecked") public Map<String, ?> decodeSignedRequest(String signedRequest) throws SignedRequestException { return decodeSignedRequest(signedRequest, Map.class); }
java
@SuppressWarnings("unchecked") public Map<String, ?> decodeSignedRequest(String signedRequest) throws SignedRequestException { return decodeSignedRequest(signedRequest, Map.class); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "Map", "<", "String", ",", "?", ">", "decodeSignedRequest", "(", "String", "signedRequest", ")", "throws", "SignedRequestException", "{", "return", "decodeSignedRequest", "(", "signedRequest", ",", "Map", ".", "class", ")", ";", "}" ]
Decodes a signed request, returning the payload of the signed request as a Map @param signedRequest the value of the signed_request parameter sent by Facebook. @return the payload of the signed request as a Map @throws SignedRequestException if there is an error decoding the signed request
[ "Decodes", "a", "signed", "request", "returning", "the", "payload", "of", "the", "signed", "request", "as", "a", "Map" ]
ae2234d94367eaa3adbba251ec7790d5ba7ffa41
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook-web/src/main/java/org/springframework/social/facebook/web/SignedRequestDecoder.java#L58-L61
159,944
spring-projects/spring-social-facebook
spring-social-facebook-web/src/main/java/org/springframework/social/facebook/web/SignedRequestDecoder.java
SignedRequestDecoder.decodeSignedRequest
public <T> T decodeSignedRequest(String signedRequest, Class<T> type) throws SignedRequestException { String[] split = signedRequest.split("\\."); String encodedSignature = split[0]; String payload = split[1]; String decoded = base64DecodeToString(payload); byte[] signature = base64DecodeToBytes(encodedSignature); try { T data = objectMapper.readValue(decoded, type); String algorithm = objectMapper.readTree(decoded).get("algorithm").textValue(); if (algorithm == null || !algorithm.equals("HMAC-SHA256")) { throw new SignedRequestException("Unknown encryption algorithm: " + algorithm); } byte[] expectedSignature = encrypt(payload, secret); if (!Arrays.equals(expectedSignature, signature)) { throw new SignedRequestException("Invalid signature."); } return data; } catch (IOException e) { throw new SignedRequestException("Error parsing payload.", e); } }
java
public <T> T decodeSignedRequest(String signedRequest, Class<T> type) throws SignedRequestException { String[] split = signedRequest.split("\\."); String encodedSignature = split[0]; String payload = split[1]; String decoded = base64DecodeToString(payload); byte[] signature = base64DecodeToBytes(encodedSignature); try { T data = objectMapper.readValue(decoded, type); String algorithm = objectMapper.readTree(decoded).get("algorithm").textValue(); if (algorithm == null || !algorithm.equals("HMAC-SHA256")) { throw new SignedRequestException("Unknown encryption algorithm: " + algorithm); } byte[] expectedSignature = encrypt(payload, secret); if (!Arrays.equals(expectedSignature, signature)) { throw new SignedRequestException("Invalid signature."); } return data; } catch (IOException e) { throw new SignedRequestException("Error parsing payload.", e); } }
[ "public", "<", "T", ">", "T", "decodeSignedRequest", "(", "String", "signedRequest", ",", "Class", "<", "T", ">", "type", ")", "throws", "SignedRequestException", "{", "String", "[", "]", "split", "=", "signedRequest", ".", "split", "(", "\"\\\\.\"", ")", ";", "String", "encodedSignature", "=", "split", "[", "0", "]", ";", "String", "payload", "=", "split", "[", "1", "]", ";", "String", "decoded", "=", "base64DecodeToString", "(", "payload", ")", ";", "byte", "[", "]", "signature", "=", "base64DecodeToBytes", "(", "encodedSignature", ")", ";", "try", "{", "T", "data", "=", "objectMapper", ".", "readValue", "(", "decoded", ",", "type", ")", ";", "String", "algorithm", "=", "objectMapper", ".", "readTree", "(", "decoded", ")", ".", "get", "(", "\"algorithm\"", ")", ".", "textValue", "(", ")", ";", "if", "(", "algorithm", "==", "null", "||", "!", "algorithm", ".", "equals", "(", "\"HMAC-SHA256\"", ")", ")", "{", "throw", "new", "SignedRequestException", "(", "\"Unknown encryption algorithm: \"", "+", "algorithm", ")", ";", "}", "byte", "[", "]", "expectedSignature", "=", "encrypt", "(", "payload", ",", "secret", ")", ";", "if", "(", "!", "Arrays", ".", "equals", "(", "expectedSignature", ",", "signature", ")", ")", "{", "throw", "new", "SignedRequestException", "(", "\"Invalid signature.\"", ")", ";", "}", "return", "data", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "SignedRequestException", "(", "\"Error parsing payload.\"", ",", "e", ")", ";", "}", "}" ]
Decodes a signed request, returning the payload of the signed request as a specified type. @param signedRequest the value of the signed_request parameter sent by Facebook. @param type the type to bind the signed_request to. @param <T> the Java type to bind the signed_request to. @return the payload of the signed request as an object @throws SignedRequestException if there is an error decoding the signed request
[ "Decodes", "a", "signed", "request", "returning", "the", "payload", "of", "the", "signed", "request", "as", "a", "specified", "type", "." ]
ae2234d94367eaa3adbba251ec7790d5ba7ffa41
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook-web/src/main/java/org/springframework/social/facebook/web/SignedRequestDecoder.java#L71-L91
159,945
spring-projects/spring-social-facebook
spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java
FqlResult.getString
public String getString(String fieldName) { return hasValue(fieldName) ? String.valueOf(resultMap.get(fieldName)) : null; }
java
public String getString(String fieldName) { return hasValue(fieldName) ? String.valueOf(resultMap.get(fieldName)) : null; }
[ "public", "String", "getString", "(", "String", "fieldName", ")", "{", "return", "hasValue", "(", "fieldName", ")", "?", "String", ".", "valueOf", "(", "resultMap", ".", "get", "(", "fieldName", ")", ")", ":", "null", ";", "}" ]
Returns the value of the identified field as a String. @param fieldName the name of the field @return the value of the field as a String
[ "Returns", "the", "value", "of", "the", "identified", "field", "as", "a", "String", "." ]
ae2234d94367eaa3adbba251ec7790d5ba7ffa41
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java#L45-L47
159,946
spring-projects/spring-social-facebook
spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java
FqlResult.getInteger
public Integer getInteger(String fieldName) { try { return hasValue(fieldName) ? Integer.valueOf(String.valueOf(resultMap.get(fieldName))) : null; } catch (NumberFormatException e) { throw new FqlException("Field '" + fieldName +"' is not a number.", e); } }
java
public Integer getInteger(String fieldName) { try { return hasValue(fieldName) ? Integer.valueOf(String.valueOf(resultMap.get(fieldName))) : null; } catch (NumberFormatException e) { throw new FqlException("Field '" + fieldName +"' is not a number.", e); } }
[ "public", "Integer", "getInteger", "(", "String", "fieldName", ")", "{", "try", "{", "return", "hasValue", "(", "fieldName", ")", "?", "Integer", ".", "valueOf", "(", "String", ".", "valueOf", "(", "resultMap", ".", "get", "(", "fieldName", ")", ")", ")", ":", "null", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "throw", "new", "FqlException", "(", "\"Field '\"", "+", "fieldName", "+", "\"' is not a number.\"", ",", "e", ")", ";", "}", "}" ]
Returns the value of the identified field as an Integer. @param fieldName the name of the field @return the value of the field as an Integer @throws FqlException if the field cannot be expressed as an Integer
[ "Returns", "the", "value", "of", "the", "identified", "field", "as", "an", "Integer", "." ]
ae2234d94367eaa3adbba251ec7790d5ba7ffa41
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java#L55-L61
159,947
spring-projects/spring-social-facebook
spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java
FqlResult.getLong
public Long getLong(String fieldName) { try { return hasValue(fieldName) ? Long.valueOf(String.valueOf(resultMap.get(fieldName))) : null; } catch (NumberFormatException e) { throw new FqlException("Field '" + fieldName +"' is not a number.", e); } }
java
public Long getLong(String fieldName) { try { return hasValue(fieldName) ? Long.valueOf(String.valueOf(resultMap.get(fieldName))) : null; } catch (NumberFormatException e) { throw new FqlException("Field '" + fieldName +"' is not a number.", e); } }
[ "public", "Long", "getLong", "(", "String", "fieldName", ")", "{", "try", "{", "return", "hasValue", "(", "fieldName", ")", "?", "Long", ".", "valueOf", "(", "String", ".", "valueOf", "(", "resultMap", ".", "get", "(", "fieldName", ")", ")", ")", ":", "null", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "throw", "new", "FqlException", "(", "\"Field '\"", "+", "fieldName", "+", "\"' is not a number.\"", ",", "e", ")", ";", "}", "}" ]
Returns the value of the identified field as a Long. @param fieldName the name of the field @return the value of the field as a Long @throws FqlException if the field cannot be expressed as an Long
[ "Returns", "the", "value", "of", "the", "identified", "field", "as", "a", "Long", "." ]
ae2234d94367eaa3adbba251ec7790d5ba7ffa41
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java#L69-L75
159,948
spring-projects/spring-social-facebook
spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java
FqlResult.getFloat
public Float getFloat(String fieldName) { try { return hasValue(fieldName) ? Float.valueOf(String.valueOf(resultMap.get(fieldName))) : null; } catch (NumberFormatException e) { throw new FqlException("Field '" + fieldName +"' is not a number.", e); } }
java
public Float getFloat(String fieldName) { try { return hasValue(fieldName) ? Float.valueOf(String.valueOf(resultMap.get(fieldName))) : null; } catch (NumberFormatException e) { throw new FqlException("Field '" + fieldName +"' is not a number.", e); } }
[ "public", "Float", "getFloat", "(", "String", "fieldName", ")", "{", "try", "{", "return", "hasValue", "(", "fieldName", ")", "?", "Float", ".", "valueOf", "(", "String", ".", "valueOf", "(", "resultMap", ".", "get", "(", "fieldName", ")", ")", ")", ":", "null", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "throw", "new", "FqlException", "(", "\"Field '\"", "+", "fieldName", "+", "\"' is not a number.\"", ",", "e", ")", ";", "}", "}" ]
Returns the value of the identified field as a Float. @param fieldName the name of the field @return the value of the field as a Float @throws FqlException if the field cannot be expressed as an Float
[ "Returns", "the", "value", "of", "the", "identified", "field", "as", "a", "Float", "." ]
ae2234d94367eaa3adbba251ec7790d5ba7ffa41
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java#L83-L89
159,949
spring-projects/spring-social-facebook
spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java
FqlResult.getBoolean
public Boolean getBoolean(String fieldName) { return hasValue(fieldName) ? Boolean.valueOf(String.valueOf(resultMap.get(fieldName))) : null; }
java
public Boolean getBoolean(String fieldName) { return hasValue(fieldName) ? Boolean.valueOf(String.valueOf(resultMap.get(fieldName))) : null; }
[ "public", "Boolean", "getBoolean", "(", "String", "fieldName", ")", "{", "return", "hasValue", "(", "fieldName", ")", "?", "Boolean", ".", "valueOf", "(", "String", ".", "valueOf", "(", "resultMap", ".", "get", "(", "fieldName", ")", ")", ")", ":", "null", ";", "}" ]
Returns the value of the identified field as a Boolean. @param fieldName the name of the field @return the value of the field as a Boolean
[ "Returns", "the", "value", "of", "the", "identified", "field", "as", "a", "Boolean", "." ]
ae2234d94367eaa3adbba251ec7790d5ba7ffa41
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java#L96-L98
159,950
spring-projects/spring-social-facebook
spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java
FqlResult.getTime
public Date getTime(String fieldName) { try { if (hasValue(fieldName)) { return new Date(Long.valueOf(String.valueOf(resultMap.get(fieldName))) * 1000); } else { return null; } } catch (NumberFormatException e) { throw new FqlException("Field '" + fieldName +"' is not a time.", e); } }
java
public Date getTime(String fieldName) { try { if (hasValue(fieldName)) { return new Date(Long.valueOf(String.valueOf(resultMap.get(fieldName))) * 1000); } else { return null; } } catch (NumberFormatException e) { throw new FqlException("Field '" + fieldName +"' is not a time.", e); } }
[ "public", "Date", "getTime", "(", "String", "fieldName", ")", "{", "try", "{", "if", "(", "hasValue", "(", "fieldName", ")", ")", "{", "return", "new", "Date", "(", "Long", ".", "valueOf", "(", "String", ".", "valueOf", "(", "resultMap", ".", "get", "(", "fieldName", ")", ")", ")", "*", "1000", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "throw", "new", "FqlException", "(", "\"Field '\"", "+", "fieldName", "+", "\"' is not a time.\"", ",", "e", ")", ";", "}", "}" ]
Returns the value of the identified field as a Date. Time fields returned from an FQL query are expressed in terms of seconds since midnight, January 1, 1970 UTC. @param fieldName the name of the field @return the value of the field as a Date @throws FqlException if the field's value cannot be expressed as a long value from which a Date object can be constructed.
[ "Returns", "the", "value", "of", "the", "identified", "field", "as", "a", "Date", ".", "Time", "fields", "returned", "from", "an", "FQL", "query", "are", "expressed", "in", "terms", "of", "seconds", "since", "midnight", "January", "1", "1970", "UTC", "." ]
ae2234d94367eaa3adbba251ec7790d5ba7ffa41
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java#L107-L117
159,951
spring-projects/spring-social-facebook
spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java
FqlResult.hasValue
public boolean hasValue(String fieldName) { return resultMap.containsKey(fieldName) && resultMap.get(fieldName) != null; }
java
public boolean hasValue(String fieldName) { return resultMap.containsKey(fieldName) && resultMap.get(fieldName) != null; }
[ "public", "boolean", "hasValue", "(", "String", "fieldName", ")", "{", "return", "resultMap", ".", "containsKey", "(", "fieldName", ")", "&&", "resultMap", ".", "get", "(", "fieldName", ")", "!=", "null", ";", "}" ]
Checks that a field exists and contains a non-null value. @param fieldName the name of the field to check existence/value of. @return true if the field exists in the result set and has a non-null value; false otherwise.
[ "Checks", "that", "a", "field", "exists", "and", "contains", "a", "non", "-", "null", "value", "." ]
ae2234d94367eaa3adbba251ec7790d5ba7ffa41
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java#L188-L190
159,952
spring-projects/spring-social-facebook
spring-social-facebook/src/main/java/org/springframework/social/facebook/api/impl/FacebookTemplate.java
FacebookTemplate.fetchObject
public <T> T fetchObject(String objectId, Class<T> type) { URI uri = URIBuilder.fromUri(getBaseGraphApiUrl() + objectId).build(); return getRestTemplate().getForObject(uri, type); }
java
public <T> T fetchObject(String objectId, Class<T> type) { URI uri = URIBuilder.fromUri(getBaseGraphApiUrl() + objectId).build(); return getRestTemplate().getForObject(uri, type); }
[ "public", "<", "T", ">", "T", "fetchObject", "(", "String", "objectId", ",", "Class", "<", "T", ">", "type", ")", "{", "URI", "uri", "=", "URIBuilder", ".", "fromUri", "(", "getBaseGraphApiUrl", "(", ")", "+", "objectId", ")", ".", "build", "(", ")", ";", "return", "getRestTemplate", "(", ")", ".", "getForObject", "(", "uri", ",", "type", ")", ";", "}" ]
low-level Graph API operations
[ "low", "-", "level", "Graph", "API", "operations" ]
ae2234d94367eaa3adbba251ec7790d5ba7ffa41
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/impl/FacebookTemplate.java#L204-L207
159,953
spring-projects/spring-social-facebook
spring-social-facebook-web/src/main/java/org/springframework/social/facebook/web/RealTimeUpdateController.java
RealTimeUpdateController.verifySubscription
@RequestMapping(value="/{subscription}", method=GET, params="hub.mode=subscribe") public @ResponseBody String verifySubscription( @PathVariable("subscription") String subscription, @RequestParam("hub.challenge") String challenge, @RequestParam("hub.verify_token") String verifyToken) { logger.debug("Received subscription verification request for '" + subscription + "'."); return tokens.containsKey(subscription) && tokens.get(subscription).equals(verifyToken) ? challenge : ""; }
java
@RequestMapping(value="/{subscription}", method=GET, params="hub.mode=subscribe") public @ResponseBody String verifySubscription( @PathVariable("subscription") String subscription, @RequestParam("hub.challenge") String challenge, @RequestParam("hub.verify_token") String verifyToken) { logger.debug("Received subscription verification request for '" + subscription + "'."); return tokens.containsKey(subscription) && tokens.get(subscription).equals(verifyToken) ? challenge : ""; }
[ "@", "RequestMapping", "(", "value", "=", "\"/{subscription}\"", ",", "method", "=", "GET", ",", "params", "=", "\"hub.mode=subscribe\"", ")", "public", "@", "ResponseBody", "String", "verifySubscription", "(", "@", "PathVariable", "(", "\"subscription\"", ")", "String", "subscription", ",", "@", "RequestParam", "(", "\"hub.challenge\"", ")", "String", "challenge", ",", "@", "RequestParam", "(", "\"hub.verify_token\"", ")", "String", "verifyToken", ")", "{", "logger", ".", "debug", "(", "\"Received subscription verification request for '\"", "+", "subscription", "+", "\"'.\"", ")", ";", "return", "tokens", ".", "containsKey", "(", "subscription", ")", "&&", "tokens", ".", "get", "(", "subscription", ")", ".", "equals", "(", "verifyToken", ")", "?", "challenge", ":", "\"\"", ";", "}" ]
Handles subscription verification callback from Facebook. @param subscription The subscription name. @param challenge A challenge that Facebook expects to be returned. @param verifyToken A verification token that must match with the subscription's token given when the controller was created. @return The challenge if the verification token matches; blank string otherwise.
[ "Handles", "subscription", "verification", "callback", "from", "Facebook", "." ]
ae2234d94367eaa3adbba251ec7790d5ba7ffa41
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook-web/src/main/java/org/springframework/social/facebook/web/RealTimeUpdateController.java#L82-L89
159,954
spring-projects/spring-social-facebook
spring-social-facebook/src/main/java/org/springframework/social/facebook/api/impl/FacebookErrorHandler.java
FacebookErrorHandler.handleFacebookError
void handleFacebookError(HttpStatus statusCode, FacebookError error) { if (error != null && error.getCode() != null) { int code = error.getCode(); if (code == UNKNOWN) { throw new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null); } else if (code == SERVICE) { throw new ServerException(FACEBOOK_PROVIDER_ID, error.getMessage()); } else if (code == TOO_MANY_CALLS || code == USER_TOO_MANY_CALLS || code == EDIT_FEED_TOO_MANY_USER_CALLS || code == EDIT_FEED_TOO_MANY_USER_ACTION_CALLS) { throw new RateLimitExceededException(FACEBOOK_PROVIDER_ID); } else if (code == PERMISSION_DENIED || isUserPermissionError(code)) { throw new InsufficientPermissionException(FACEBOOK_PROVIDER_ID); } else if (code == PARAM_SESSION_KEY || code == PARAM_SIGNATURE) { throw new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage()); } else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == null) { throw new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage()); } else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == 463) { throw new ExpiredAuthorizationException(FACEBOOK_PROVIDER_ID); } else if (code == PARAM_ACCESS_TOKEN) { throw new RevokedAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage()); } else if (code == MESG_DUPLICATE) { throw new DuplicateStatusException(FACEBOOK_PROVIDER_ID, error.getMessage()); } else if (code == DATA_OBJECT_NOT_FOUND || code == PATH_UNKNOWN) { throw new ResourceNotFoundException(FACEBOOK_PROVIDER_ID, error.getMessage()); } else { throw new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null); } } }
java
void handleFacebookError(HttpStatus statusCode, FacebookError error) { if (error != null && error.getCode() != null) { int code = error.getCode(); if (code == UNKNOWN) { throw new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null); } else if (code == SERVICE) { throw new ServerException(FACEBOOK_PROVIDER_ID, error.getMessage()); } else if (code == TOO_MANY_CALLS || code == USER_TOO_MANY_CALLS || code == EDIT_FEED_TOO_MANY_USER_CALLS || code == EDIT_FEED_TOO_MANY_USER_ACTION_CALLS) { throw new RateLimitExceededException(FACEBOOK_PROVIDER_ID); } else if (code == PERMISSION_DENIED || isUserPermissionError(code)) { throw new InsufficientPermissionException(FACEBOOK_PROVIDER_ID); } else if (code == PARAM_SESSION_KEY || code == PARAM_SIGNATURE) { throw new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage()); } else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == null) { throw new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage()); } else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == 463) { throw new ExpiredAuthorizationException(FACEBOOK_PROVIDER_ID); } else if (code == PARAM_ACCESS_TOKEN) { throw new RevokedAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage()); } else if (code == MESG_DUPLICATE) { throw new DuplicateStatusException(FACEBOOK_PROVIDER_ID, error.getMessage()); } else if (code == DATA_OBJECT_NOT_FOUND || code == PATH_UNKNOWN) { throw new ResourceNotFoundException(FACEBOOK_PROVIDER_ID, error.getMessage()); } else { throw new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null); } } }
[ "void", "handleFacebookError", "(", "HttpStatus", "statusCode", ",", "FacebookError", "error", ")", "{", "if", "(", "error", "!=", "null", "&&", "error", ".", "getCode", "(", ")", "!=", "null", ")", "{", "int", "code", "=", "error", ".", "getCode", "(", ")", ";", "if", "(", "code", "==", "UNKNOWN", ")", "{", "throw", "new", "UncategorizedApiException", "(", "FACEBOOK_PROVIDER_ID", ",", "error", ".", "getMessage", "(", ")", ",", "null", ")", ";", "}", "else", "if", "(", "code", "==", "SERVICE", ")", "{", "throw", "new", "ServerException", "(", "FACEBOOK_PROVIDER_ID", ",", "error", ".", "getMessage", "(", ")", ")", ";", "}", "else", "if", "(", "code", "==", "TOO_MANY_CALLS", "||", "code", "==", "USER_TOO_MANY_CALLS", "||", "code", "==", "EDIT_FEED_TOO_MANY_USER_CALLS", "||", "code", "==", "EDIT_FEED_TOO_MANY_USER_ACTION_CALLS", ")", "{", "throw", "new", "RateLimitExceededException", "(", "FACEBOOK_PROVIDER_ID", ")", ";", "}", "else", "if", "(", "code", "==", "PERMISSION_DENIED", "||", "isUserPermissionError", "(", "code", ")", ")", "{", "throw", "new", "InsufficientPermissionException", "(", "FACEBOOK_PROVIDER_ID", ")", ";", "}", "else", "if", "(", "code", "==", "PARAM_SESSION_KEY", "||", "code", "==", "PARAM_SIGNATURE", ")", "{", "throw", "new", "InvalidAuthorizationException", "(", "FACEBOOK_PROVIDER_ID", ",", "error", ".", "getMessage", "(", ")", ")", ";", "}", "else", "if", "(", "code", "==", "PARAM_ACCESS_TOKEN", "&&", "error", ".", "getSubcode", "(", ")", "==", "null", ")", "{", "throw", "new", "InvalidAuthorizationException", "(", "FACEBOOK_PROVIDER_ID", ",", "error", ".", "getMessage", "(", ")", ")", ";", "}", "else", "if", "(", "code", "==", "PARAM_ACCESS_TOKEN", "&&", "error", ".", "getSubcode", "(", ")", "==", "463", ")", "{", "throw", "new", "ExpiredAuthorizationException", "(", "FACEBOOK_PROVIDER_ID", ")", ";", "}", "else", "if", "(", "code", "==", "PARAM_ACCESS_TOKEN", ")", "{", "throw", "new", "RevokedAuthorizationException", "(", "FACEBOOK_PROVIDER_ID", ",", "error", ".", "getMessage", "(", ")", ")", ";", "}", "else", "if", "(", "code", "==", "MESG_DUPLICATE", ")", "{", "throw", "new", "DuplicateStatusException", "(", "FACEBOOK_PROVIDER_ID", ",", "error", ".", "getMessage", "(", ")", ")", ";", "}", "else", "if", "(", "code", "==", "DATA_OBJECT_NOT_FOUND", "||", "code", "==", "PATH_UNKNOWN", ")", "{", "throw", "new", "ResourceNotFoundException", "(", "FACEBOOK_PROVIDER_ID", ",", "error", ".", "getMessage", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "UncategorizedApiException", "(", "FACEBOOK_PROVIDER_ID", ",", "error", ".", "getMessage", "(", ")", ",", "null", ")", ";", "}", "}", "}" ]
Examines the error data returned from Facebook and throws the most applicable exception. @param errorDetails a Map containing a "type" and a "message" corresponding to the Graph API's error response structure.
[ "Examines", "the", "error", "data", "returned", "from", "Facebook", "and", "throws", "the", "most", "applicable", "exception", "." ]
ae2234d94367eaa3adbba251ec7790d5ba7ffa41
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/impl/FacebookErrorHandler.java#L66-L95
159,955
Manabu-GT/EtsyBlur
sample/src/main/java/com/ms/square/android/etsyblurdemo/ui/fragment/NavigationDrawerFragment.java
NavigationDrawerFragment.showGlobalContextActionBar
private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(R.string.app_name); }
java
private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(R.string.app_name); }
[ "private", "void", "showGlobalContextActionBar", "(", ")", "{", "ActionBar", "actionBar", "=", "getActionBar", "(", ")", ";", "actionBar", ".", "setDisplayShowTitleEnabled", "(", "true", ")", ";", "actionBar", ".", "setTitle", "(", "R", ".", "string", ".", "app_name", ")", ";", "}" ]
Per the navigation drawer design guidelines, updates the action bar to show the global app 'context', rather than just what's in the current screen.
[ "Per", "the", "navigation", "drawer", "design", "guidelines", "updates", "the", "action", "bar", "to", "show", "the", "global", "app", "context", "rather", "than", "just", "what", "s", "in", "the", "current", "screen", "." ]
b51c9e80e823fce3590cc061e79e267388b4d8e0
https://github.com/Manabu-GT/EtsyBlur/blob/b51c9e80e823fce3590cc061e79e267388b4d8e0/sample/src/main/java/com/ms/square/android/etsyblurdemo/ui/fragment/NavigationDrawerFragment.java#L266-L270
159,956
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/urls/UrlsInterface.java
UrlsInterface.getGroup
public String getGroup(String groupId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_GROUP); parameters.put("group_id", groupId); Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element payload = response.getPayload(); return payload.getAttribute("url"); }
java
public String getGroup(String groupId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_GROUP); parameters.put("group_id", groupId); Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element payload = response.getPayload(); return payload.getAttribute("url"); }
[ "public", "String", "getGroup", "(", "String", "groupId", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_GET_GROUP", ")", ";", "parameters", ".", "put", "(", "\"group_id\"", ",", "groupId", ")", ";", "Response", "response", "=", "transport", ".", "get", "(", "transport", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "Element", "payload", "=", "response", ".", "getPayload", "(", ")", ";", "return", "payload", ".", "getAttribute", "(", "\"url\"", ")", ";", "}" ]
Get the group URL for the specified group ID @param groupId The group ID @return The group URL @throws FlickrException
[ "Get", "the", "group", "URL", "for", "the", "specified", "group", "ID" ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/urls/UrlsInterface.java#L65-L78
159,957
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/urls/UrlsInterface.java
UrlsInterface.getUserProfile
public String getUserProfile(String userId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_USER_PROFILE); parameters.put("user_id", userId); Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element payload = response.getPayload(); return payload.getAttribute("url"); }
java
public String getUserProfile(String userId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_USER_PROFILE); parameters.put("user_id", userId); Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element payload = response.getPayload(); return payload.getAttribute("url"); }
[ "public", "String", "getUserProfile", "(", "String", "userId", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_GET_USER_PROFILE", ")", ";", "parameters", ".", "put", "(", "\"user_id\"", ",", "userId", ")", ";", "Response", "response", "=", "transport", ".", "get", "(", "transport", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "Element", "payload", "=", "response", ".", "getPayload", "(", ")", ";", "return", "payload", ".", "getAttribute", "(", "\"url\"", ")", ";", "}" ]
Get the URL for the user's profile. @param userId The user ID @return The URL @throws FlickrException
[ "Get", "the", "URL", "for", "the", "user", "s", "profile", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/urls/UrlsInterface.java#L111-L124
159,958
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/urls/UrlsInterface.java
UrlsInterface.lookupGroup
public Group lookupGroup(String url) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_LOOKUP_GROUP); parameters.put("url", url); Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Group group = new Group(); Element payload = response.getPayload(); Element groupnameElement = (Element) payload.getElementsByTagName("groupname").item(0); group.setId(payload.getAttribute("id")); group.setName(((Text) groupnameElement.getFirstChild()).getData()); return group; }
java
public Group lookupGroup(String url) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_LOOKUP_GROUP); parameters.put("url", url); Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Group group = new Group(); Element payload = response.getPayload(); Element groupnameElement = (Element) payload.getElementsByTagName("groupname").item(0); group.setId(payload.getAttribute("id")); group.setName(((Text) groupnameElement.getFirstChild()).getData()); return group; }
[ "public", "Group", "lookupGroup", "(", "String", "url", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_LOOKUP_GROUP", ")", ";", "parameters", ".", "put", "(", "\"url\"", ",", "url", ")", ";", "Response", "response", "=", "transport", ".", "get", "(", "transport", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "Group", "group", "=", "new", "Group", "(", ")", ";", "Element", "payload", "=", "response", ".", "getPayload", "(", ")", ";", "Element", "groupnameElement", "=", "(", "Element", ")", "payload", ".", "getElementsByTagName", "(", "\"groupname\"", ")", ".", "item", "(", "0", ")", ";", "group", ".", "setId", "(", "payload", ".", "getAttribute", "(", "\"id\"", ")", ")", ";", "group", ".", "setName", "(", "(", "(", "Text", ")", "groupnameElement", ".", "getFirstChild", "(", ")", ")", ".", "getData", "(", ")", ")", ";", "return", "group", ";", "}" ]
Lookup the group for the specified URL. @param url The url @return The group @throws FlickrException
[ "Lookup", "the", "group", "for", "the", "specified", "URL", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/urls/UrlsInterface.java#L134-L151
159,959
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/urls/UrlsInterface.java
UrlsInterface.lookupUser
public String lookupUser(String url) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_LOOKUP_USER); parameters.put("url", url); Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element payload = response.getPayload(); Element groupnameElement = (Element) payload.getElementsByTagName("username").item(0); return ((Text) groupnameElement.getFirstChild()).getData(); }
java
public String lookupUser(String url) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_LOOKUP_USER); parameters.put("url", url); Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element payload = response.getPayload(); Element groupnameElement = (Element) payload.getElementsByTagName("username").item(0); return ((Text) groupnameElement.getFirstChild()).getData(); }
[ "public", "String", "lookupUser", "(", "String", "url", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_LOOKUP_USER", ")", ";", "parameters", ".", "put", "(", "\"url\"", ",", "url", ")", ";", "Response", "response", "=", "transport", ".", "get", "(", "transport", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "Element", "payload", "=", "response", ".", "getPayload", "(", ")", ";", "Element", "groupnameElement", "=", "(", "Element", ")", "payload", ".", "getElementsByTagName", "(", "\"username\"", ")", ".", "item", "(", "0", ")", ";", "return", "(", "(", "Text", ")", "groupnameElement", ".", "getFirstChild", "(", ")", ")", ".", "getData", "(", ")", ";", "}" ]
Lookup the username for the specified User URL. @param url The user profile URL @return The username @throws FlickrException
[ "Lookup", "the", "username", "for", "the", "specified", "User", "URL", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/urls/UrlsInterface.java#L161-L175
159,960
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/urls/UrlsInterface.java
UrlsInterface.lookupGallery
public Gallery lookupGallery(String galleryId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_LOOKUP_GALLERY); parameters.put("url", galleryId); Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element galleryElement = response.getPayload(); Gallery gallery = new Gallery(); gallery.setId(galleryElement.getAttribute("id")); gallery.setUrl(galleryElement.getAttribute("url")); User owner = new User(); owner.setId(galleryElement.getAttribute("owner")); gallery.setOwner(owner); gallery.setCreateDate(galleryElement.getAttribute("date_create")); gallery.setUpdateDate(galleryElement.getAttribute("date_update")); gallery.setPrimaryPhotoId(galleryElement.getAttribute("primary_photo_id")); gallery.setPrimaryPhotoServer(galleryElement.getAttribute("primary_photo_server")); gallery.setVideoCount(galleryElement.getAttribute("count_videos")); gallery.setPhotoCount(galleryElement.getAttribute("count_photos")); gallery.setPrimaryPhotoFarm(galleryElement.getAttribute("farm")); gallery.setPrimaryPhotoSecret(galleryElement.getAttribute("secret")); gallery.setTitle(XMLUtilities.getChildValue(galleryElement, "title")); gallery.setDesc(XMLUtilities.getChildValue(galleryElement, "description")); return gallery; }
java
public Gallery lookupGallery(String galleryId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_LOOKUP_GALLERY); parameters.put("url", galleryId); Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element galleryElement = response.getPayload(); Gallery gallery = new Gallery(); gallery.setId(galleryElement.getAttribute("id")); gallery.setUrl(galleryElement.getAttribute("url")); User owner = new User(); owner.setId(galleryElement.getAttribute("owner")); gallery.setOwner(owner); gallery.setCreateDate(galleryElement.getAttribute("date_create")); gallery.setUpdateDate(galleryElement.getAttribute("date_update")); gallery.setPrimaryPhotoId(galleryElement.getAttribute("primary_photo_id")); gallery.setPrimaryPhotoServer(galleryElement.getAttribute("primary_photo_server")); gallery.setVideoCount(galleryElement.getAttribute("count_videos")); gallery.setPhotoCount(galleryElement.getAttribute("count_photos")); gallery.setPrimaryPhotoFarm(galleryElement.getAttribute("farm")); gallery.setPrimaryPhotoSecret(galleryElement.getAttribute("secret")); gallery.setTitle(XMLUtilities.getChildValue(galleryElement, "title")); gallery.setDesc(XMLUtilities.getChildValue(galleryElement, "description")); return gallery; }
[ "public", "Gallery", "lookupGallery", "(", "String", "galleryId", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_LOOKUP_GALLERY", ")", ";", "parameters", ".", "put", "(", "\"url\"", ",", "galleryId", ")", ";", "Response", "response", "=", "transport", ".", "get", "(", "transport", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "Element", "galleryElement", "=", "response", ".", "getPayload", "(", ")", ";", "Gallery", "gallery", "=", "new", "Gallery", "(", ")", ";", "gallery", ".", "setId", "(", "galleryElement", ".", "getAttribute", "(", "\"id\"", ")", ")", ";", "gallery", ".", "setUrl", "(", "galleryElement", ".", "getAttribute", "(", "\"url\"", ")", ")", ";", "User", "owner", "=", "new", "User", "(", ")", ";", "owner", ".", "setId", "(", "galleryElement", ".", "getAttribute", "(", "\"owner\"", ")", ")", ";", "gallery", ".", "setOwner", "(", "owner", ")", ";", "gallery", ".", "setCreateDate", "(", "galleryElement", ".", "getAttribute", "(", "\"date_create\"", ")", ")", ";", "gallery", ".", "setUpdateDate", "(", "galleryElement", ".", "getAttribute", "(", "\"date_update\"", ")", ")", ";", "gallery", ".", "setPrimaryPhotoId", "(", "galleryElement", ".", "getAttribute", "(", "\"primary_photo_id\"", ")", ")", ";", "gallery", ".", "setPrimaryPhotoServer", "(", "galleryElement", ".", "getAttribute", "(", "\"primary_photo_server\"", ")", ")", ";", "gallery", ".", "setVideoCount", "(", "galleryElement", ".", "getAttribute", "(", "\"count_videos\"", ")", ")", ";", "gallery", ".", "setPhotoCount", "(", "galleryElement", ".", "getAttribute", "(", "\"count_photos\"", ")", ")", ";", "gallery", ".", "setPrimaryPhotoFarm", "(", "galleryElement", ".", "getAttribute", "(", "\"farm\"", ")", ")", ";", "gallery", ".", "setPrimaryPhotoSecret", "(", "galleryElement", ".", "getAttribute", "(", "\"secret\"", ")", ")", ";", "gallery", ".", "setTitle", "(", "XMLUtilities", ".", "getChildValue", "(", "galleryElement", ",", "\"title\"", ")", ")", ";", "gallery", ".", "setDesc", "(", "XMLUtilities", ".", "getChildValue", "(", "galleryElement", ",", "\"description\"", ")", ")", ";", "return", "gallery", ";", "}" ]
Lookup the Gallery for the specified ID. @param galleryId The user profile URL @return The Gallery @throws FlickrException
[ "Lookup", "the", "Gallery", "for", "the", "specified", "ID", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/urls/UrlsInterface.java#L185-L216
159,961
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/favorites/FavoritesInterface.java
FavoritesInterface.add
public void add(String photoId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_ADD); parameters.put("photo_id", photoId); Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
java
public void add(String photoId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_ADD); parameters.put("photo_id", photoId); Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
[ "public", "void", "add", "(", "String", "photoId", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_ADD", ")", ";", "parameters", ".", "put", "(", "\"photo_id\"", ",", "photoId", ")", ";", "Response", "response", "=", "transportAPI", ".", "post", "(", "transportAPI", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "}" ]
Add a photo to the user's favorites. @param photoId The photo ID @throws FlickrException
[ "Add", "a", "photo", "to", "the", "user", "s", "favorites", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/favorites/FavoritesInterface.java#L61-L70
159,962
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/favorites/FavoritesInterface.java
FavoritesInterface.getContext
public PhotoContext getContext(String photoId, String userId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_CONTEXT); parameters.put("photo_id", photoId); parameters.put("user_id", userId); Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Collection<Element> payload = response.getPayloadCollection(); PhotoContext photoContext = new PhotoContext(); for (Element element : payload) { String elementName = element.getTagName(); if (elementName.equals("prevphoto")) { Photo photo = new Photo(); photo.setId(element.getAttribute("id")); photoContext.setPreviousPhoto(photo); } else if (elementName.equals("nextphoto")) { Photo photo = new Photo(); photo.setId(element.getAttribute("id")); photoContext.setNextPhoto(photo); } else { if (logger.isInfoEnabled()) { logger.info("unsupported element name: " + elementName); } } } return photoContext; }
java
public PhotoContext getContext(String photoId, String userId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_CONTEXT); parameters.put("photo_id", photoId); parameters.put("user_id", userId); Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Collection<Element> payload = response.getPayloadCollection(); PhotoContext photoContext = new PhotoContext(); for (Element element : payload) { String elementName = element.getTagName(); if (elementName.equals("prevphoto")) { Photo photo = new Photo(); photo.setId(element.getAttribute("id")); photoContext.setPreviousPhoto(photo); } else if (elementName.equals("nextphoto")) { Photo photo = new Photo(); photo.setId(element.getAttribute("id")); photoContext.setNextPhoto(photo); } else { if (logger.isInfoEnabled()) { logger.info("unsupported element name: " + elementName); } } } return photoContext; }
[ "public", "PhotoContext", "getContext", "(", "String", "photoId", ",", "String", "userId", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_GET_CONTEXT", ")", ";", "parameters", ".", "put", "(", "\"photo_id\"", ",", "photoId", ")", ";", "parameters", ".", "put", "(", "\"user_id\"", ",", "userId", ")", ";", "Response", "response", "=", "transportAPI", ".", "post", "(", "transportAPI", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "Collection", "<", "Element", ">", "payload", "=", "response", ".", "getPayloadCollection", "(", ")", ";", "PhotoContext", "photoContext", "=", "new", "PhotoContext", "(", ")", ";", "for", "(", "Element", "element", ":", "payload", ")", "{", "String", "elementName", "=", "element", ".", "getTagName", "(", ")", ";", "if", "(", "elementName", ".", "equals", "(", "\"prevphoto\"", ")", ")", "{", "Photo", "photo", "=", "new", "Photo", "(", ")", ";", "photo", ".", "setId", "(", "element", ".", "getAttribute", "(", "\"id\"", ")", ")", ";", "photoContext", ".", "setPreviousPhoto", "(", "photo", ")", ";", "}", "else", "if", "(", "elementName", ".", "equals", "(", "\"nextphoto\"", ")", ")", "{", "Photo", "photo", "=", "new", "Photo", "(", ")", ";", "photo", ".", "setId", "(", "element", ".", "getAttribute", "(", "\"id\"", ")", ")", ";", "photoContext", ".", "setNextPhoto", "(", "photo", ")", ";", "}", "else", "{", "if", "(", "logger", ".", "isInfoEnabled", "(", ")", ")", "{", "logger", ".", "info", "(", "\"unsupported element name: \"", "+", "elementName", ")", ";", "}", "}", "}", "return", "photoContext", ";", "}" ]
Returns next and previous favorites for a photo in a user's favorites @param photoId The photo id @param userId The user's ID @see <a href="http://www.flickr.com/services/api/flickr.favorites.getContext.html">flickr.favorites.getContext</a>
[ "Returns", "next", "and", "previous", "favorites", "for", "a", "photo", "in", "a", "user", "s", "favorites" ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/favorites/FavoritesInterface.java#L203-L234
159,963
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/people/PeopleInterface.java
PeopleInterface.editCoords
public void editCoords(String photoId, String userId, Rectangle bounds) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_EDIT_COORDS); parameters.put("photo_id", photoId); parameters.put("user_id", userId); parameters.put("person_x", bounds.x); parameters.put("person_y", bounds.y); parameters.put("person_w", bounds.width); parameters.put("person_h", bounds.height); Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
java
public void editCoords(String photoId, String userId, Rectangle bounds) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_EDIT_COORDS); parameters.put("photo_id", photoId); parameters.put("user_id", userId); parameters.put("person_x", bounds.x); parameters.put("person_y", bounds.y); parameters.put("person_w", bounds.width); parameters.put("person_h", bounds.height); Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
[ "public", "void", "editCoords", "(", "String", "photoId", ",", "String", "userId", ",", "Rectangle", "bounds", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_EDIT_COORDS", ")", ";", "parameters", ".", "put", "(", "\"photo_id\"", ",", "photoId", ")", ";", "parameters", ".", "put", "(", "\"user_id\"", ",", "userId", ")", ";", "parameters", ".", "put", "(", "\"person_x\"", ",", "bounds", ".", "x", ")", ";", "parameters", ".", "put", "(", "\"person_y\"", ",", "bounds", ".", "y", ")", ";", "parameters", ".", "put", "(", "\"person_w\"", ",", "bounds", ".", "width", ")", ";", "parameters", ".", "put", "(", "\"person_h\"", ",", "bounds", ".", "height", ")", ";", "Response", "response", "=", "transportAPI", ".", "get", "(", "transportAPI", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "}" ]
Edit the co-ordinates that the user shows in @param photoId @param userId @param bounds @throws FlickrException
[ "Edit", "the", "co", "-", "ordinates", "that", "the", "user", "shows", "in" ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/people/PeopleInterface.java#L122-L137
159,964
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/Flickr.java
Flickr.getAuthInterface
@Override public AuthInterface getAuthInterface() { if (authInterface == null) { authInterface = new AuthInterface(apiKey, sharedSecret, transport); } return authInterface; }
java
@Override public AuthInterface getAuthInterface() { if (authInterface == null) { authInterface = new AuthInterface(apiKey, sharedSecret, transport); } return authInterface; }
[ "@", "Override", "public", "AuthInterface", "getAuthInterface", "(", ")", "{", "if", "(", "authInterface", "==", "null", ")", "{", "authInterface", "=", "new", "AuthInterface", "(", "apiKey", ",", "sharedSecret", ",", "transport", ")", ";", "}", "return", "authInterface", ";", "}" ]
Get the AuthInterface. @return The AuthInterface
[ "Get", "the", "AuthInterface", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/Flickr.java#L378-L384
159,965
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/Flickr.java
Flickr.getActivityInterface
@Override public ActivityInterface getActivityInterface() { if (activityInterface == null) { activityInterface = new ActivityInterface(apiKey, sharedSecret, transport); } return activityInterface; }
java
@Override public ActivityInterface getActivityInterface() { if (activityInterface == null) { activityInterface = new ActivityInterface(apiKey, sharedSecret, transport); } return activityInterface; }
[ "@", "Override", "public", "ActivityInterface", "getActivityInterface", "(", ")", "{", "if", "(", "activityInterface", "==", "null", ")", "{", "activityInterface", "=", "new", "ActivityInterface", "(", "apiKey", ",", "sharedSecret", ",", "transport", ")", ";", "}", "return", "activityInterface", ";", "}" ]
Get the ActivityInterface. @return The ActivityInterface
[ "Get", "the", "ActivityInterface", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/Flickr.java#L391-L397
159,966
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/Flickr.java
Flickr.getTagsInterface
@Override public TagsInterface getTagsInterface() { if (tagsInterface == null) { tagsInterface = new TagsInterface(apiKey, sharedSecret, transport); } return tagsInterface; }
java
@Override public TagsInterface getTagsInterface() { if (tagsInterface == null) { tagsInterface = new TagsInterface(apiKey, sharedSecret, transport); } return tagsInterface; }
[ "@", "Override", "public", "TagsInterface", "getTagsInterface", "(", ")", "{", "if", "(", "tagsInterface", "==", "null", ")", "{", "tagsInterface", "=", "new", "TagsInterface", "(", "apiKey", ",", "sharedSecret", ",", "transport", ")", ";", "}", "return", "tagsInterface", ";", "}" ]
Get the TagsInterface for working with Flickr Tags. @return The TagsInterface
[ "Get", "the", "TagsInterface", "for", "working", "with", "Flickr", "Tags", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/Flickr.java#L583-L589
159,967
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/Flickr.java
Flickr.getSuggestionsInterface
@Override public SuggestionsInterface getSuggestionsInterface() { if (suggestionsInterface == null) { suggestionsInterface = new SuggestionsInterface(apiKey, sharedSecret, transport); } return suggestionsInterface; }
java
@Override public SuggestionsInterface getSuggestionsInterface() { if (suggestionsInterface == null) { suggestionsInterface = new SuggestionsInterface(apiKey, sharedSecret, transport); } return suggestionsInterface; }
[ "@", "Override", "public", "SuggestionsInterface", "getSuggestionsInterface", "(", ")", "{", "if", "(", "suggestionsInterface", "==", "null", ")", "{", "suggestionsInterface", "=", "new", "SuggestionsInterface", "(", "apiKey", ",", "sharedSecret", ",", "transport", ")", ";", "}", "return", "suggestionsInterface", ";", "}" ]
Get the SuggestionsInterface. @return The SuggestionsInterface
[ "Get", "the", "SuggestionsInterface", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/Flickr.java#L660-L666
159,968
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/Flickr.java
Flickr.getDiscussionInterface
@Override public GroupDiscussInterface getDiscussionInterface() { if (discussionInterface == null) { discussionInterface = new GroupDiscussInterface(apiKey, sharedSecret, transport); } return discussionInterface; }
java
@Override public GroupDiscussInterface getDiscussionInterface() { if (discussionInterface == null) { discussionInterface = new GroupDiscussInterface(apiKey, sharedSecret, transport); } return discussionInterface; }
[ "@", "Override", "public", "GroupDiscussInterface", "getDiscussionInterface", "(", ")", "{", "if", "(", "discussionInterface", "==", "null", ")", "{", "discussionInterface", "=", "new", "GroupDiscussInterface", "(", "apiKey", ",", "sharedSecret", ",", "transport", ")", ";", "}", "return", "discussionInterface", ";", "}" ]
Get the GroupDiscussInterface. @return The GroupDiscussInterface
[ "Get", "the", "GroupDiscussInterface", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/Flickr.java#L674-L680
159,969
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/blogs/BlogsInterface.java
BlogsInterface.getServices
public Collection<Service> getServices() throws FlickrException { List<Service> list = new ArrayList<Service>(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_SERVICES); Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element servicesElement = response.getPayload(); NodeList serviceNodes = servicesElement.getElementsByTagName("service"); for (int i = 0; i < serviceNodes.getLength(); i++) { Element serviceElement = (Element) serviceNodes.item(i); Service srv = new Service(); srv.setId(serviceElement.getAttribute("id")); srv.setName(XMLUtilities.getValue(serviceElement)); list.add(srv); } return list; }
java
public Collection<Service> getServices() throws FlickrException { List<Service> list = new ArrayList<Service>(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_SERVICES); Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element servicesElement = response.getPayload(); NodeList serviceNodes = servicesElement.getElementsByTagName("service"); for (int i = 0; i < serviceNodes.getLength(); i++) { Element serviceElement = (Element) serviceNodes.item(i); Service srv = new Service(); srv.setId(serviceElement.getAttribute("id")); srv.setName(XMLUtilities.getValue(serviceElement)); list.add(srv); } return list; }
[ "public", "Collection", "<", "Service", ">", "getServices", "(", ")", "throws", "FlickrException", "{", "List", "<", "Service", ">", "list", "=", "new", "ArrayList", "<", "Service", ">", "(", ")", ";", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_GET_SERVICES", ")", ";", "Response", "response", "=", "transportAPI", ".", "get", "(", "transportAPI", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "Element", "servicesElement", "=", "response", ".", "getPayload", "(", ")", ";", "NodeList", "serviceNodes", "=", "servicesElement", ".", "getElementsByTagName", "(", "\"service\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "serviceNodes", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Element", "serviceElement", "=", "(", "Element", ")", "serviceNodes", ".", "item", "(", "i", ")", ";", "Service", "srv", "=", "new", "Service", "(", ")", ";", "srv", ".", "setId", "(", "serviceElement", ".", "getAttribute", "(", "\"id\"", ")", ")", ";", "srv", ".", "setName", "(", "XMLUtilities", ".", "getValue", "(", "serviceElement", ")", ")", ";", "list", ".", "add", "(", "srv", ")", ";", "}", "return", "list", ";", "}" ]
Return a list of Flickr supported blogging services. This method does not require authentication. @return List of Services @throws FlickrException
[ "Return", "a", "list", "of", "Flickr", "supported", "blogging", "services", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/blogs/BlogsInterface.java#L53-L72
159,970
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/blogs/BlogsInterface.java
BlogsInterface.postPhoto
public void postPhoto(Photo photo, String blogId, String blogPassword) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_POST_PHOTO); parameters.put("blog_id", blogId); parameters.put("photo_id", photo.getId()); parameters.put("title", photo.getTitle()); parameters.put("description", photo.getDescription()); if (blogPassword != null) { parameters.put("blog_password", blogPassword); } Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
java
public void postPhoto(Photo photo, String blogId, String blogPassword) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_POST_PHOTO); parameters.put("blog_id", blogId); parameters.put("photo_id", photo.getId()); parameters.put("title", photo.getTitle()); parameters.put("description", photo.getDescription()); if (blogPassword != null) { parameters.put("blog_password", blogPassword); } Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
[ "public", "void", "postPhoto", "(", "Photo", "photo", ",", "String", "blogId", ",", "String", "blogPassword", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_POST_PHOTO", ")", ";", "parameters", ".", "put", "(", "\"blog_id\"", ",", "blogId", ")", ";", "parameters", ".", "put", "(", "\"photo_id\"", ",", "photo", ".", "getId", "(", ")", ")", ";", "parameters", ".", "put", "(", "\"title\"", ",", "photo", ".", "getTitle", "(", ")", ")", ";", "parameters", ".", "put", "(", "\"description\"", ",", "photo", ".", "getDescription", "(", ")", ")", ";", "if", "(", "blogPassword", "!=", "null", ")", "{", "parameters", ".", "put", "(", "\"blog_password\"", ",", "blogPassword", ")", ";", "}", "Response", "response", "=", "transportAPI", ".", "post", "(", "transportAPI", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "}" ]
Post the specified photo to a blog. Note that the Photo.title and Photo.description are used for the blog entry title and body respectively. @param photo The photo metadata @param blogId The blog ID @param blogPassword The blog password @throws FlickrException
[ "Post", "the", "specified", "photo", "to", "a", "blog", ".", "Note", "that", "the", "Photo", ".", "title", "and", "Photo", ".", "description", "are", "used", "for", "the", "blog", "entry", "title", "and", "body", "respectively", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/blogs/BlogsInterface.java#L85-L101
159,971
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/blogs/BlogsInterface.java
BlogsInterface.postPhoto
public void postPhoto(Photo photo, String blogId) throws FlickrException { postPhoto(photo, blogId, null); }
java
public void postPhoto(Photo photo, String blogId) throws FlickrException { postPhoto(photo, blogId, null); }
[ "public", "void", "postPhoto", "(", "Photo", "photo", ",", "String", "blogId", ")", "throws", "FlickrException", "{", "postPhoto", "(", "photo", ",", "blogId", ",", "null", ")", ";", "}" ]
Post the specified photo to a blog. @param photo The photo metadata @param blogId The blog ID @throws FlickrException
[ "Post", "the", "specified", "photo", "to", "a", "blog", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/blogs/BlogsInterface.java#L112-L114
159,972
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/blogs/BlogsInterface.java
BlogsInterface.getList
public Collection<Blog> getList() throws FlickrException { List<Blog> blogs = new ArrayList<Blog>(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_LIST); Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element blogsElement = response.getPayload(); NodeList blogNodes = blogsElement.getElementsByTagName("blog"); for (int i = 0; i < blogNodes.getLength(); i++) { Element blogElement = (Element) blogNodes.item(i); Blog blog = new Blog(); blog.setId(blogElement.getAttribute("id")); blog.setName(blogElement.getAttribute("name")); blog.setNeedPassword("1".equals(blogElement.getAttribute("needspassword"))); blog.setUrl(blogElement.getAttribute("url")); blogs.add(blog); } return blogs; }
java
public Collection<Blog> getList() throws FlickrException { List<Blog> blogs = new ArrayList<Blog>(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_LIST); Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element blogsElement = response.getPayload(); NodeList blogNodes = blogsElement.getElementsByTagName("blog"); for (int i = 0; i < blogNodes.getLength(); i++) { Element blogElement = (Element) blogNodes.item(i); Blog blog = new Blog(); blog.setId(blogElement.getAttribute("id")); blog.setName(blogElement.getAttribute("name")); blog.setNeedPassword("1".equals(blogElement.getAttribute("needspassword"))); blog.setUrl(blogElement.getAttribute("url")); blogs.add(blog); } return blogs; }
[ "public", "Collection", "<", "Blog", ">", "getList", "(", ")", "throws", "FlickrException", "{", "List", "<", "Blog", ">", "blogs", "=", "new", "ArrayList", "<", "Blog", ">", "(", ")", ";", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_GET_LIST", ")", ";", "Response", "response", "=", "transportAPI", ".", "post", "(", "transportAPI", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "Element", "blogsElement", "=", "response", ".", "getPayload", "(", ")", ";", "NodeList", "blogNodes", "=", "blogsElement", ".", "getElementsByTagName", "(", "\"blog\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "blogNodes", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Element", "blogElement", "=", "(", "Element", ")", "blogNodes", ".", "item", "(", "i", ")", ";", "Blog", "blog", "=", "new", "Blog", "(", ")", ";", "blog", ".", "setId", "(", "blogElement", ".", "getAttribute", "(", "\"id\"", ")", ")", ";", "blog", ".", "setName", "(", "blogElement", ".", "getAttribute", "(", "\"name\"", ")", ")", ";", "blog", ".", "setNeedPassword", "(", "\"1\"", ".", "equals", "(", "blogElement", ".", "getAttribute", "(", "\"needspassword\"", ")", ")", ")", ";", "blog", ".", "setUrl", "(", "blogElement", ".", "getAttribute", "(", "\"url\"", ")", ")", ";", "blogs", ".", "add", "(", "blog", ")", ";", "}", "return", "blogs", ";", "}" ]
Get the collection of configured blogs for the calling user. @return The Collection of configured blogs
[ "Get", "the", "collection", "of", "configured", "blogs", "for", "the", "calling", "user", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/blogs/BlogsInterface.java#L121-L144
159,973
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/PhotoUtils.java
PhotoUtils.getAttribute
private static String getAttribute(String name, Element firstElement, Element secondElement) { String val = firstElement.getAttribute(name); if (val.length() == 0 && secondElement != null) { val = secondElement.getAttribute(name); } return val; }
java
private static String getAttribute(String name, Element firstElement, Element secondElement) { String val = firstElement.getAttribute(name); if (val.length() == 0 && secondElement != null) { val = secondElement.getAttribute(name); } return val; }
[ "private", "static", "String", "getAttribute", "(", "String", "name", ",", "Element", "firstElement", ",", "Element", "secondElement", ")", "{", "String", "val", "=", "firstElement", ".", "getAttribute", "(", "name", ")", ";", "if", "(", "val", ".", "length", "(", ")", "==", "0", "&&", "secondElement", "!=", "null", ")", "{", "val", "=", "secondElement", ".", "getAttribute", "(", "name", ")", ";", "}", "return", "val", ";", "}" ]
Try to get an attribute value from two elements. @param firstElement @param secondElement @return attribute value
[ "Try", "to", "get", "an", "attribute", "value", "from", "two", "elements", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/PhotoUtils.java#L33-L39
159,974
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/PhotoUtils.java
PhotoUtils.createPhotoList
public static final PhotoList<Photo> createPhotoList(Element photosElement) { PhotoList<Photo> photos = new PhotoList<Photo>(); photos.setPage(photosElement.getAttribute("page")); photos.setPages(photosElement.getAttribute("pages")); photos.setPerPage(photosElement.getAttribute("perpage")); photos.setTotal(photosElement.getAttribute("total")); NodeList photoNodes = photosElement.getElementsByTagName("photo"); for (int i = 0; i < photoNodes.getLength(); i++) { Element photoElement = (Element) photoNodes.item(i); photos.add(PhotoUtils.createPhoto(photoElement)); } return photos; }
java
public static final PhotoList<Photo> createPhotoList(Element photosElement) { PhotoList<Photo> photos = new PhotoList<Photo>(); photos.setPage(photosElement.getAttribute("page")); photos.setPages(photosElement.getAttribute("pages")); photos.setPerPage(photosElement.getAttribute("perpage")); photos.setTotal(photosElement.getAttribute("total")); NodeList photoNodes = photosElement.getElementsByTagName("photo"); for (int i = 0; i < photoNodes.getLength(); i++) { Element photoElement = (Element) photoNodes.item(i); photos.add(PhotoUtils.createPhoto(photoElement)); } return photos; }
[ "public", "static", "final", "PhotoList", "<", "Photo", ">", "createPhotoList", "(", "Element", "photosElement", ")", "{", "PhotoList", "<", "Photo", ">", "photos", "=", "new", "PhotoList", "<", "Photo", ">", "(", ")", ";", "photos", ".", "setPage", "(", "photosElement", ".", "getAttribute", "(", "\"page\"", ")", ")", ";", "photos", ".", "setPages", "(", "photosElement", ".", "getAttribute", "(", "\"pages\"", ")", ")", ";", "photos", ".", "setPerPage", "(", "photosElement", ".", "getAttribute", "(", "\"perpage\"", ")", ")", ";", "photos", ".", "setTotal", "(", "photosElement", ".", "getAttribute", "(", "\"total\"", ")", ")", ";", "NodeList", "photoNodes", "=", "photosElement", ".", "getElementsByTagName", "(", "\"photo\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "photoNodes", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Element", "photoElement", "=", "(", "Element", ")", "photoNodes", ".", "item", "(", "i", ")", ";", "photos", ".", "add", "(", "PhotoUtils", ".", "createPhoto", "(", "photoElement", ")", ")", ";", "}", "return", "photos", ";", "}" ]
Parse a list of Photos from given Element. @param photosElement @return PhotoList
[ "Parse", "a", "list", "of", "Photos", "from", "given", "Element", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/PhotoUtils.java#L502-L515
159,975
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/auth/AuthInterface.java
AuthInterface.getRequestToken
public OAuth1RequestToken getRequestToken(String callbackUrl) { String callback = (callbackUrl != null) ? callbackUrl : OUT_OF_BOUND_AUTH_METHOD; OAuth10aService service = new ServiceBuilder(apiKey) .apiSecret(sharedSecret) .callback(callback) .build(FlickrApi.instance()); try { return service.getRequestToken(); } catch (IOException | InterruptedException | ExecutionException e) { throw new FlickrRuntimeException(e); } }
java
public OAuth1RequestToken getRequestToken(String callbackUrl) { String callback = (callbackUrl != null) ? callbackUrl : OUT_OF_BOUND_AUTH_METHOD; OAuth10aService service = new ServiceBuilder(apiKey) .apiSecret(sharedSecret) .callback(callback) .build(FlickrApi.instance()); try { return service.getRequestToken(); } catch (IOException | InterruptedException | ExecutionException e) { throw new FlickrRuntimeException(e); } }
[ "public", "OAuth1RequestToken", "getRequestToken", "(", "String", "callbackUrl", ")", "{", "String", "callback", "=", "(", "callbackUrl", "!=", "null", ")", "?", "callbackUrl", ":", "OUT_OF_BOUND_AUTH_METHOD", ";", "OAuth10aService", "service", "=", "new", "ServiceBuilder", "(", "apiKey", ")", ".", "apiSecret", "(", "sharedSecret", ")", ".", "callback", "(", "callback", ")", ".", "build", "(", "FlickrApi", ".", "instance", "(", ")", ")", ";", "try", "{", "return", "service", ".", "getRequestToken", "(", ")", ";", "}", "catch", "(", "IOException", "|", "InterruptedException", "|", "ExecutionException", "e", ")", "{", "throw", "new", "FlickrRuntimeException", "(", "e", ")", ";", "}", "}" ]
Get the OAuth request token - this is step one of authorization. @param callbackUrl optional callback URL - required for web auth flow, will be set to "oob" if not specified. @return the {@link OAuth1RequestToken}, store this for when the user returns from the Flickr website.
[ "Get", "the", "OAuth", "request", "token", "-", "this", "is", "step", "one", "of", "authorization", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/auth/AuthInterface.java#L88-L101
159,976
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/auth/AuthInterface.java
AuthInterface.getAuthorizationUrl
public String getAuthorizationUrl(OAuth1RequestToken oAuthRequestToken, Permission permission) { OAuth10aService service = new ServiceBuilder(apiKey) .apiSecret(sharedSecret) .build(FlickrApi.instance()); String authorizationUrl = service.getAuthorizationUrl(oAuthRequestToken); return String.format("%s&perms=%s", authorizationUrl, permission.toString()); }
java
public String getAuthorizationUrl(OAuth1RequestToken oAuthRequestToken, Permission permission) { OAuth10aService service = new ServiceBuilder(apiKey) .apiSecret(sharedSecret) .build(FlickrApi.instance()); String authorizationUrl = service.getAuthorizationUrl(oAuthRequestToken); return String.format("%s&perms=%s", authorizationUrl, permission.toString()); }
[ "public", "String", "getAuthorizationUrl", "(", "OAuth1RequestToken", "oAuthRequestToken", ",", "Permission", "permission", ")", "{", "OAuth10aService", "service", "=", "new", "ServiceBuilder", "(", "apiKey", ")", ".", "apiSecret", "(", "sharedSecret", ")", ".", "build", "(", "FlickrApi", ".", "instance", "(", ")", ")", ";", "String", "authorizationUrl", "=", "service", ".", "getAuthorizationUrl", "(", "oAuthRequestToken", ")", ";", "return", "String", ".", "format", "(", "\"%s&perms=%s\"", ",", "authorizationUrl", ",", "permission", ".", "toString", "(", ")", ")", ";", "}" ]
Get the auth URL, this is step two of authorization. @param oAuthRequestToken the token from a {@link AuthInterface#getRequestToken} call.
[ "Get", "the", "auth", "URL", "this", "is", "step", "two", "of", "authorization", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/auth/AuthInterface.java#L109-L116
159,977
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/auth/AuthInterface.java
AuthInterface.getAccessToken
@SuppressWarnings("boxing") public OAuth1Token getAccessToken(OAuth1RequestToken oAuthRequestToken, String verifier) { OAuth10aService service = new ServiceBuilder(apiKey) .apiSecret(sharedSecret) .build(FlickrApi.instance()); // Flickr seems to return invalid token sometimes so retry a few times. // See http://www.flickr.com/groups/api/discuss/72157628028927244/ OAuth1Token accessToken = null; boolean success = false; for (int i = 0; i < maxGetTokenRetries && !success; i++) { try { accessToken = service.getAccessToken(oAuthRequestToken, verifier); success = true; } catch (OAuthException | IOException | InterruptedException | ExecutionException e) { if (i == maxGetTokenRetries - 1) { logger.error(String.format("OAuthService.getAccessToken failing after %d tries, re-throwing exception", i), e); throw new FlickrRuntimeException(e); } else { logger.warn(String.format("OAuthService.getAccessToken failed, try number %d: %s", i, e.getMessage())); try { Thread.sleep(500); } catch (InterruptedException ie) { // Do nothing } } } } return accessToken; }
java
@SuppressWarnings("boxing") public OAuth1Token getAccessToken(OAuth1RequestToken oAuthRequestToken, String verifier) { OAuth10aService service = new ServiceBuilder(apiKey) .apiSecret(sharedSecret) .build(FlickrApi.instance()); // Flickr seems to return invalid token sometimes so retry a few times. // See http://www.flickr.com/groups/api/discuss/72157628028927244/ OAuth1Token accessToken = null; boolean success = false; for (int i = 0; i < maxGetTokenRetries && !success; i++) { try { accessToken = service.getAccessToken(oAuthRequestToken, verifier); success = true; } catch (OAuthException | IOException | InterruptedException | ExecutionException e) { if (i == maxGetTokenRetries - 1) { logger.error(String.format("OAuthService.getAccessToken failing after %d tries, re-throwing exception", i), e); throw new FlickrRuntimeException(e); } else { logger.warn(String.format("OAuthService.getAccessToken failed, try number %d: %s", i, e.getMessage())); try { Thread.sleep(500); } catch (InterruptedException ie) { // Do nothing } } } } return accessToken; }
[ "@", "SuppressWarnings", "(", "\"boxing\"", ")", "public", "OAuth1Token", "getAccessToken", "(", "OAuth1RequestToken", "oAuthRequestToken", ",", "String", "verifier", ")", "{", "OAuth10aService", "service", "=", "new", "ServiceBuilder", "(", "apiKey", ")", ".", "apiSecret", "(", "sharedSecret", ")", ".", "build", "(", "FlickrApi", ".", "instance", "(", ")", ")", ";", "// Flickr seems to return invalid token sometimes so retry a few times.\r", "// See http://www.flickr.com/groups/api/discuss/72157628028927244/\r", "OAuth1Token", "accessToken", "=", "null", ";", "boolean", "success", "=", "false", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "maxGetTokenRetries", "&&", "!", "success", ";", "i", "++", ")", "{", "try", "{", "accessToken", "=", "service", ".", "getAccessToken", "(", "oAuthRequestToken", ",", "verifier", ")", ";", "success", "=", "true", ";", "}", "catch", "(", "OAuthException", "|", "IOException", "|", "InterruptedException", "|", "ExecutionException", "e", ")", "{", "if", "(", "i", "==", "maxGetTokenRetries", "-", "1", ")", "{", "logger", ".", "error", "(", "String", ".", "format", "(", "\"OAuthService.getAccessToken failing after %d tries, re-throwing exception\"", ",", "i", ")", ",", "e", ")", ";", "throw", "new", "FlickrRuntimeException", "(", "e", ")", ";", "}", "else", "{", "logger", ".", "warn", "(", "String", ".", "format", "(", "\"OAuthService.getAccessToken failed, try number %d: %s\"", ",", "i", ",", "e", ".", "getMessage", "(", ")", ")", ")", ";", "try", "{", "Thread", ".", "sleep", "(", "500", ")", ";", "}", "catch", "(", "InterruptedException", "ie", ")", "{", "// Do nothing\r", "}", "}", "}", "}", "return", "accessToken", ";", "}" ]
Trade the request token for an access token, this is step three of authorization. @param oAuthRequestToken this is the token returned by the {@link AuthInterface#getRequestToken} call. @param verifier
[ "Trade", "the", "request", "token", "for", "an", "access", "token", "this", "is", "step", "three", "of", "authorization", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/auth/AuthInterface.java#L124-L154
159,978
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/auth/AuthInterface.java
AuthInterface.exchangeAuthToken
public OAuth1RequestToken exchangeAuthToken(String authToken) throws FlickrException { // Use TreeMap so keys are automatically sorted alphabetically Map<String, String> parameters = new TreeMap<String, String>(); parameters.put("method", METHOD_EXCHANGE_TOKEN); parameters.put(Flickr.API_KEY, apiKey); // This method call must be signed using Flickr (not OAuth) style signing parameters.put("api_sig", getSignature(sharedSecret, parameters)); Response response = transportAPI.getNonOAuth(transportAPI.getPath(), parameters); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } OAuth1RequestToken accessToken = constructToken(response); return accessToken; }
java
public OAuth1RequestToken exchangeAuthToken(String authToken) throws FlickrException { // Use TreeMap so keys are automatically sorted alphabetically Map<String, String> parameters = new TreeMap<String, String>(); parameters.put("method", METHOD_EXCHANGE_TOKEN); parameters.put(Flickr.API_KEY, apiKey); // This method call must be signed using Flickr (not OAuth) style signing parameters.put("api_sig", getSignature(sharedSecret, parameters)); Response response = transportAPI.getNonOAuth(transportAPI.getPath(), parameters); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } OAuth1RequestToken accessToken = constructToken(response); return accessToken; }
[ "public", "OAuth1RequestToken", "exchangeAuthToken", "(", "String", "authToken", ")", "throws", "FlickrException", "{", "// Use TreeMap so keys are automatically sorted alphabetically\r", "Map", "<", "String", ",", "String", ">", "parameters", "=", "new", "TreeMap", "<", "String", ",", "String", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_EXCHANGE_TOKEN", ")", ";", "parameters", ".", "put", "(", "Flickr", ".", "API_KEY", ",", "apiKey", ")", ";", "// This method call must be signed using Flickr (not OAuth) style signing\r", "parameters", ".", "put", "(", "\"api_sig\"", ",", "getSignature", "(", "sharedSecret", ",", "parameters", ")", ")", ";", "Response", "response", "=", "transportAPI", ".", "getNonOAuth", "(", "transportAPI", ".", "getPath", "(", ")", ",", "parameters", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "OAuth1RequestToken", "accessToken", "=", "constructToken", "(", "response", ")", ";", "return", "accessToken", ";", "}" ]
Exchange an auth token from the old Authentication API, to an OAuth access token. Calling this method will delete the auth token used to make the request. @param authToken @throws FlickrException @see "http://www.flickr.com/services/api/flickr.auth.oauth.getAccessToken.html"
[ "Exchange", "an", "auth", "token", "from", "the", "old", "Authentication", "API", "to", "an", "OAuth", "access", "token", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/auth/AuthInterface.java#L205-L222
159,979
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/auth/AuthInterface.java
AuthInterface.constructToken
private OAuth1RequestToken constructToken(Response response) { Element authElement = response.getPayload(); String oauthToken = XMLUtilities.getChildValue(authElement, "oauth_token"); String oauthTokenSecret = XMLUtilities.getChildValue(authElement, "oauth_token_secret"); OAuth1RequestToken token = new OAuth1RequestToken(oauthToken, oauthTokenSecret); return token; }
java
private OAuth1RequestToken constructToken(Response response) { Element authElement = response.getPayload(); String oauthToken = XMLUtilities.getChildValue(authElement, "oauth_token"); String oauthTokenSecret = XMLUtilities.getChildValue(authElement, "oauth_token_secret"); OAuth1RequestToken token = new OAuth1RequestToken(oauthToken, oauthTokenSecret); return token; }
[ "private", "OAuth1RequestToken", "constructToken", "(", "Response", "response", ")", "{", "Element", "authElement", "=", "response", ".", "getPayload", "(", ")", ";", "String", "oauthToken", "=", "XMLUtilities", ".", "getChildValue", "(", "authElement", ",", "\"oauth_token\"", ")", ";", "String", "oauthTokenSecret", "=", "XMLUtilities", ".", "getChildValue", "(", "authElement", ",", "\"oauth_token_secret\"", ")", ";", "OAuth1RequestToken", "token", "=", "new", "OAuth1RequestToken", "(", "oauthToken", ",", "oauthTokenSecret", ")", ";", "return", "token", ";", "}" ]
Construct a Access Token from a Flickr Response. @param response
[ "Construct", "a", "Access", "Token", "from", "a", "Flickr", "Response", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/auth/AuthInterface.java#L251-L258
159,980
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/auth/AuthInterface.java
AuthInterface.getSignature
private String getSignature(String sharedSecret, Map<String, String> params) { StringBuffer buffer = new StringBuffer(); buffer.append(sharedSecret); for (Map.Entry<String, String> entry : params.entrySet()) { buffer.append(entry.getKey()); buffer.append(entry.getValue()); } try { MessageDigest md = MessageDigest.getInstance("MD5"); return ByteUtilities.toHexString(md.digest(buffer.toString().getBytes("UTF-8"))); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException u) { throw new RuntimeException(u); } }
java
private String getSignature(String sharedSecret, Map<String, String> params) { StringBuffer buffer = new StringBuffer(); buffer.append(sharedSecret); for (Map.Entry<String, String> entry : params.entrySet()) { buffer.append(entry.getKey()); buffer.append(entry.getValue()); } try { MessageDigest md = MessageDigest.getInstance("MD5"); return ByteUtilities.toHexString(md.digest(buffer.toString().getBytes("UTF-8"))); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException u) { throw new RuntimeException(u); } }
[ "private", "String", "getSignature", "(", "String", "sharedSecret", ",", "Map", "<", "String", ",", "String", ">", "params", ")", "{", "StringBuffer", "buffer", "=", "new", "StringBuffer", "(", ")", ";", "buffer", ".", "append", "(", "sharedSecret", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "params", ".", "entrySet", "(", ")", ")", "{", "buffer", ".", "append", "(", "entry", ".", "getKey", "(", ")", ")", ";", "buffer", ".", "append", "(", "entry", ".", "getValue", "(", ")", ")", ";", "}", "try", "{", "MessageDigest", "md", "=", "MessageDigest", ".", "getInstance", "(", "\"MD5\"", ")", ";", "return", "ByteUtilities", ".", "toHexString", "(", "md", ".", "digest", "(", "buffer", ".", "toString", "(", ")", ".", "getBytes", "(", "\"UTF-8\"", ")", ")", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "u", ")", "{", "throw", "new", "RuntimeException", "(", "u", ")", ";", "}", "}" ]
Get a signature for a list of parameters using the given shared secret. @param sharedSecret The shared secret @param params The parameters @return The signature String
[ "Get", "a", "signature", "for", "a", "list", "of", "parameters", "using", "the", "given", "shared", "secret", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/auth/AuthInterface.java#L269-L285
159,981
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/util/UrlUtilities.java
UrlUtilities.buildUrl
@Deprecated public static URL buildUrl(String host, int port, String path, Map<String, String> parameters) throws MalformedURLException { return buildUrl("http", port, path, parameters); }
java
@Deprecated public static URL buildUrl(String host, int port, String path, Map<String, String> parameters) throws MalformedURLException { return buildUrl("http", port, path, parameters); }
[ "@", "Deprecated", "public", "static", "URL", "buildUrl", "(", "String", "host", ",", "int", "port", ",", "String", "path", ",", "Map", "<", "String", ",", "String", ">", "parameters", ")", "throws", "MalformedURLException", "{", "return", "buildUrl", "(", "\"http\"", ",", "port", ",", "path", ",", "parameters", ")", ";", "}" ]
Build a request URL. @param host The host @param port The port @param path The path @param parameters The parameters @return The URL @throws MalformedURLException @deprecated use {@link #buildSecureUrl(java.lang.String, int, java.lang.String, java.util.Map) }
[ "Build", "a", "request", "URL", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/util/UrlUtilities.java#L34-L37
159,982
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/util/UrlUtilities.java
UrlUtilities.buildUrl
public static URL buildUrl(String scheme, String host, int port, String path, Map<String, String> parameters) throws MalformedURLException { checkSchemeAndPort(scheme, port); StringBuilder buffer = new StringBuilder(); if (!host.startsWith(scheme + "://")) { buffer.append(scheme).append("://"); } buffer.append(host); if (port > 0) { buffer.append(':'); buffer.append(port); } if (path == null) { path = "/"; } buffer.append(path); if (!parameters.isEmpty()) { buffer.append('?'); } int size = parameters.size(); for (Map.Entry<String, String> entry : parameters.entrySet()) { buffer.append(entry.getKey()); buffer.append('='); Object value = entry.getValue(); if (value != null) { String string = value.toString(); try { string = URLEncoder.encode(string, UTF8); } catch (UnsupportedEncodingException e) { // Should never happen, but just in case } buffer.append(string); } if (--size != 0) { buffer.append('&'); } } /* * RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null && * !ignoreMethod(getMethod(parameters))) { buffer.append("&api_sig="); buffer.append(AuthUtilities.getSignature(sharedSecret, parameters)); } */ return new URL(buffer.toString()); }
java
public static URL buildUrl(String scheme, String host, int port, String path, Map<String, String> parameters) throws MalformedURLException { checkSchemeAndPort(scheme, port); StringBuilder buffer = new StringBuilder(); if (!host.startsWith(scheme + "://")) { buffer.append(scheme).append("://"); } buffer.append(host); if (port > 0) { buffer.append(':'); buffer.append(port); } if (path == null) { path = "/"; } buffer.append(path); if (!parameters.isEmpty()) { buffer.append('?'); } int size = parameters.size(); for (Map.Entry<String, String> entry : parameters.entrySet()) { buffer.append(entry.getKey()); buffer.append('='); Object value = entry.getValue(); if (value != null) { String string = value.toString(); try { string = URLEncoder.encode(string, UTF8); } catch (UnsupportedEncodingException e) { // Should never happen, but just in case } buffer.append(string); } if (--size != 0) { buffer.append('&'); } } /* * RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null && * !ignoreMethod(getMethod(parameters))) { buffer.append("&api_sig="); buffer.append(AuthUtilities.getSignature(sharedSecret, parameters)); } */ return new URL(buffer.toString()); }
[ "public", "static", "URL", "buildUrl", "(", "String", "scheme", ",", "String", "host", ",", "int", "port", ",", "String", "path", ",", "Map", "<", "String", ",", "String", ">", "parameters", ")", "throws", "MalformedURLException", "{", "checkSchemeAndPort", "(", "scheme", ",", "port", ")", ";", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "!", "host", ".", "startsWith", "(", "scheme", "+", "\"://\"", ")", ")", "{", "buffer", ".", "append", "(", "scheme", ")", ".", "append", "(", "\"://\"", ")", ";", "}", "buffer", ".", "append", "(", "host", ")", ";", "if", "(", "port", ">", "0", ")", "{", "buffer", ".", "append", "(", "'", "'", ")", ";", "buffer", ".", "append", "(", "port", ")", ";", "}", "if", "(", "path", "==", "null", ")", "{", "path", "=", "\"/\"", ";", "}", "buffer", ".", "append", "(", "path", ")", ";", "if", "(", "!", "parameters", ".", "isEmpty", "(", ")", ")", "{", "buffer", ".", "append", "(", "'", "'", ")", ";", "}", "int", "size", "=", "parameters", ".", "size", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "parameters", ".", "entrySet", "(", ")", ")", "{", "buffer", ".", "append", "(", "entry", ".", "getKey", "(", ")", ")", ";", "buffer", ".", "append", "(", "'", "'", ")", ";", "Object", "value", "=", "entry", ".", "getValue", "(", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "String", "string", "=", "value", ".", "toString", "(", ")", ";", "try", "{", "string", "=", "URLEncoder", ".", "encode", "(", "string", ",", "UTF8", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "// Should never happen, but just in case\r", "}", "buffer", ".", "append", "(", "string", ")", ";", "}", "if", "(", "--", "size", "!=", "0", ")", "{", "buffer", ".", "append", "(", "'", "'", ")", ";", "}", "}", "/*\r\n * RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null &&\r\n * !ignoreMethod(getMethod(parameters))) { buffer.append(\"&api_sig=\"); buffer.append(AuthUtilities.getSignature(sharedSecret, parameters)); }\r\n */", "return", "new", "URL", "(", "buffer", ".", "toString", "(", ")", ")", ";", "}" ]
Build a request URL using a given scheme. @param scheme the scheme, either {@code http} or {@code https} @param host The host @param port The port @param path The path @param parameters The parameters @return The URL @throws MalformedURLException
[ "Build", "a", "request", "URL", "using", "a", "given", "scheme", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/util/UrlUtilities.java#L54-L98
159,983
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/uploader/Uploader.java
Uploader.upload
@Override public String upload(byte[] data, UploadMetaData metaData) throws FlickrException { Payload payload = new Payload(data); return sendUploadRequest(metaData, payload); }
java
@Override public String upload(byte[] data, UploadMetaData metaData) throws FlickrException { Payload payload = new Payload(data); return sendUploadRequest(metaData, payload); }
[ "@", "Override", "public", "String", "upload", "(", "byte", "[", "]", "data", ",", "UploadMetaData", "metaData", ")", "throws", "FlickrException", "{", "Payload", "payload", "=", "new", "Payload", "(", "data", ")", ";", "return", "sendUploadRequest", "(", "metaData", ",", "payload", ")", ";", "}" ]
Upload a photo from a byte-array. @param data The photo data as a byte array @param metaData The meta data @return photoId or ticketId @throws FlickrException
[ "Upload", "a", "photo", "from", "a", "byte", "-", "array", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/uploader/Uploader.java#L74-L78
159,984
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/uploader/Uploader.java
Uploader.upload
@Override public String upload(File file, UploadMetaData metaData) throws FlickrException { Payload payload = new Payload(file); return sendUploadRequest(metaData, payload); }
java
@Override public String upload(File file, UploadMetaData metaData) throws FlickrException { Payload payload = new Payload(file); return sendUploadRequest(metaData, payload); }
[ "@", "Override", "public", "String", "upload", "(", "File", "file", ",", "UploadMetaData", "metaData", ")", "throws", "FlickrException", "{", "Payload", "payload", "=", "new", "Payload", "(", "file", ")", ";", "return", "sendUploadRequest", "(", "metaData", ",", "payload", ")", ";", "}" ]
Upload a photo from a File. @param file the photo file @param metaData The meta data @return photoId or ticketId @throws FlickrException
[ "Upload", "a", "photo", "from", "a", "File", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/uploader/Uploader.java#L90-L94
159,985
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/uploader/Uploader.java
Uploader.upload
@Override public String upload(InputStream in, UploadMetaData metaData) throws FlickrException { Payload payload = new Payload(in); return sendUploadRequest(metaData, payload); }
java
@Override public String upload(InputStream in, UploadMetaData metaData) throws FlickrException { Payload payload = new Payload(in); return sendUploadRequest(metaData, payload); }
[ "@", "Override", "public", "String", "upload", "(", "InputStream", "in", ",", "UploadMetaData", "metaData", ")", "throws", "FlickrException", "{", "Payload", "payload", "=", "new", "Payload", "(", "in", ")", ";", "return", "sendUploadRequest", "(", "metaData", ",", "payload", ")", ";", "}" ]
Upload a photo from an InputStream. @param in @param metaData @return photoId or ticketId @throws FlickrException
[ "Upload", "a", "photo", "from", "an", "InputStream", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/uploader/Uploader.java#L104-L108
159,986
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/uploader/Uploader.java
Uploader.replace
@Override public String replace(File file, String flickrId, boolean async) throws FlickrException { Payload payload = new Payload(file, flickrId); return sendReplaceRequest(async, payload); }
java
@Override public String replace(File file, String flickrId, boolean async) throws FlickrException { Payload payload = new Payload(file, flickrId); return sendReplaceRequest(async, payload); }
[ "@", "Override", "public", "String", "replace", "(", "File", "file", ",", "String", "flickrId", ",", "boolean", "async", ")", "throws", "FlickrException", "{", "Payload", "payload", "=", "new", "Payload", "(", "file", ",", "flickrId", ")", ";", "return", "sendReplaceRequest", "(", "async", ",", "payload", ")", ";", "}" ]
Replace a photo from a File. @param file @param flickrId @param async @return photoId or ticketId @throws FlickrException
[ "Replace", "a", "photo", "from", "a", "File", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/uploader/Uploader.java#L147-L151
159,987
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/uploader/Uploader.java
Uploader.getResponseString
private String getResponseString(boolean async, UploaderResponse response) { return async ? response.getTicketId() : response.getPhotoId(); }
java
private String getResponseString(boolean async, UploaderResponse response) { return async ? response.getTicketId() : response.getPhotoId(); }
[ "private", "String", "getResponseString", "(", "boolean", "async", ",", "UploaderResponse", "response", ")", "{", "return", "async", "?", "response", ".", "getTicketId", "(", ")", ":", "response", ".", "getPhotoId", "(", ")", ";", "}" ]
Get the photo or ticket id from the response. @param async @param response @return
[ "Get", "the", "photo", "or", "ticket", "id", "from", "the", "response", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/uploader/Uploader.java#L178-L180
159,988
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/Photo.java
Photo.setViews
@Deprecated public void setViews(String views) { if (views != null) { try { setViews(Integer.parseInt(views)); } catch (NumberFormatException e) { setViews(-1); } } }
java
@Deprecated public void setViews(String views) { if (views != null) { try { setViews(Integer.parseInt(views)); } catch (NumberFormatException e) { setViews(-1); } } }
[ "@", "Deprecated", "public", "void", "setViews", "(", "String", "views", ")", "{", "if", "(", "views", "!=", "null", ")", "{", "try", "{", "setViews", "(", "Integer", ".", "parseInt", "(", "views", ")", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "setViews", "(", "-", "1", ")", ";", "}", "}", "}" ]
Sets the number of views for this Photo. For un-authenticated calls this value is not available and will be set to -1. @param views @deprecated attribute no longer available
[ "Sets", "the", "number", "of", "views", "for", "this", "Photo", ".", "For", "un", "-", "authenticated", "calls", "this", "value", "is", "not", "available", "and", "will", "be", "set", "to", "-", "1", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/Photo.java#L461-L470
159,989
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/Photo.java
Photo.setRotation
public void setRotation(String rotation) { if (rotation != null) { try { setRotation(Integer.parseInt(rotation)); } catch (NumberFormatException e) { setRotation(-1); } } }
java
public void setRotation(String rotation) { if (rotation != null) { try { setRotation(Integer.parseInt(rotation)); } catch (NumberFormatException e) { setRotation(-1); } } }
[ "public", "void", "setRotation", "(", "String", "rotation", ")", "{", "if", "(", "rotation", "!=", "null", ")", "{", "try", "{", "setRotation", "(", "Integer", ".", "parseInt", "(", "rotation", ")", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "setRotation", "(", "-", "1", ")", ";", "}", "}", "}" ]
Set the degrees of rotation. Value will be set to -1, if not available. @param rotation
[ "Set", "the", "degrees", "of", "rotation", ".", "Value", "will", "be", "set", "to", "-", "1", "if", "not", "available", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/Photo.java#L498-L506
159,990
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/Photo.java
Photo.getOriginalAsStream
@Deprecated public InputStream getOriginalAsStream() throws IOException, FlickrException { if (originalFormat != null) { return getOriginalImageAsStream("_o." + originalFormat); } return getOriginalImageAsStream(DEFAULT_ORIGINAL_IMAGE_SUFFIX); }
java
@Deprecated public InputStream getOriginalAsStream() throws IOException, FlickrException { if (originalFormat != null) { return getOriginalImageAsStream("_o." + originalFormat); } return getOriginalImageAsStream(DEFAULT_ORIGINAL_IMAGE_SUFFIX); }
[ "@", "Deprecated", "public", "InputStream", "getOriginalAsStream", "(", ")", "throws", "IOException", ",", "FlickrException", "{", "if", "(", "originalFormat", "!=", "null", ")", "{", "return", "getOriginalImageAsStream", "(", "\"_o.\"", "+", "originalFormat", ")", ";", "}", "return", "getOriginalImageAsStream", "(", "DEFAULT_ORIGINAL_IMAGE_SUFFIX", ")", ";", "}" ]
Get an InputStream for the original image. Callers must close the stream upon completion. @deprecated @see PhotosInterface#getImageAsStream(Photo, int) @return The InputStream @throws IOException
[ "Get", "an", "InputStream", "for", "the", "original", "image", ".", "Callers", "must", "close", "the", "stream", "upon", "completion", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/Photo.java#L591-L597
159,991
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/Photo.java
Photo.getOriginalUrl
public String getOriginalUrl() throws FlickrException { if (originalSize == null) { if (originalFormat != null) { return getOriginalBaseImageUrl() + "_o." + originalFormat; } return getOriginalBaseImageUrl() + DEFAULT_ORIGINAL_IMAGE_SUFFIX; } else { return originalSize.getSource(); } }
java
public String getOriginalUrl() throws FlickrException { if (originalSize == null) { if (originalFormat != null) { return getOriginalBaseImageUrl() + "_o." + originalFormat; } return getOriginalBaseImageUrl() + DEFAULT_ORIGINAL_IMAGE_SUFFIX; } else { return originalSize.getSource(); } }
[ "public", "String", "getOriginalUrl", "(", ")", "throws", "FlickrException", "{", "if", "(", "originalSize", "==", "null", ")", "{", "if", "(", "originalFormat", "!=", "null", ")", "{", "return", "getOriginalBaseImageUrl", "(", ")", "+", "\"_o.\"", "+", "originalFormat", ";", "}", "return", "getOriginalBaseImageUrl", "(", ")", "+", "DEFAULT_ORIGINAL_IMAGE_SUFFIX", ";", "}", "else", "{", "return", "originalSize", ".", "getSource", "(", ")", ";", "}", "}" ]
Get the original image URL. @return The original image URL
[ "Get", "the", "original", "image", "URL", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/Photo.java#L604-L613
159,992
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/Photo.java
Photo.getImage
@Deprecated private BufferedImage getImage(String suffix) throws IOException { StringBuffer buffer = getBaseImageUrl(); buffer.append(suffix); return _getImage(buffer.toString()); }
java
@Deprecated private BufferedImage getImage(String suffix) throws IOException { StringBuffer buffer = getBaseImageUrl(); buffer.append(suffix); return _getImage(buffer.toString()); }
[ "@", "Deprecated", "private", "BufferedImage", "getImage", "(", "String", "suffix", ")", "throws", "IOException", "{", "StringBuffer", "buffer", "=", "getBaseImageUrl", "(", ")", ";", "buffer", ".", "append", "(", "suffix", ")", ";", "return", "_getImage", "(", "buffer", ".", "toString", "(", ")", ")", ";", "}" ]
Get an image using the specified URL suffix. @deprecated @param suffix The URL suffix, including the .extension @return The BufferedImage object @throws IOException
[ "Get", "an", "image", "using", "the", "specified", "URL", "suffix", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/Photo.java#L865-L870
159,993
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/Photo.java
Photo.getOriginalImage
@Deprecated private BufferedImage getOriginalImage(String suffix) throws IOException, FlickrException { StringBuffer buffer = getOriginalBaseImageUrl(); buffer.append(suffix); return _getImage(buffer.toString()); }
java
@Deprecated private BufferedImage getOriginalImage(String suffix) throws IOException, FlickrException { StringBuffer buffer = getOriginalBaseImageUrl(); buffer.append(suffix); return _getImage(buffer.toString()); }
[ "@", "Deprecated", "private", "BufferedImage", "getOriginalImage", "(", "String", "suffix", ")", "throws", "IOException", ",", "FlickrException", "{", "StringBuffer", "buffer", "=", "getOriginalBaseImageUrl", "(", ")", ";", "buffer", ".", "append", "(", "suffix", ")", ";", "return", "_getImage", "(", "buffer", ".", "toString", "(", ")", ")", ";", "}" ]
Get the original-image using the specified URL suffix. @deprecated @see PhotosInterface#getImage(Photo, int) @param suffix The URL suffix, including the .extension @return The BufferedImage object @throws IOException @throws FlickrException
[ "Get", "the", "original", "-", "image", "using", "the", "specified", "URL", "suffix", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/Photo.java#L883-L888
159,994
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/Photo.java
Photo.getImageAsStream
@Deprecated private InputStream getImageAsStream(String suffix) throws IOException { StringBuffer buffer = getBaseImageUrl(); buffer.append(suffix); return _getImageAsStream(buffer.toString()); }
java
@Deprecated private InputStream getImageAsStream(String suffix) throws IOException { StringBuffer buffer = getBaseImageUrl(); buffer.append(suffix); return _getImageAsStream(buffer.toString()); }
[ "@", "Deprecated", "private", "InputStream", "getImageAsStream", "(", "String", "suffix", ")", "throws", "IOException", "{", "StringBuffer", "buffer", "=", "getBaseImageUrl", "(", ")", ";", "buffer", ".", "append", "(", "suffix", ")", ";", "return", "_getImageAsStream", "(", "buffer", ".", "toString", "(", ")", ")", ";", "}" ]
Get an image as a stream. Callers must be sure to close the stream when they are done with it. @deprecated @see PhotosInterface#getImageAsStream(Photo, int) @param suffix The suffix @return The InputStream @throws IOException
[ "Get", "an", "image", "as", "a", "stream", ".", "Callers", "must", "be", "sure", "to", "close", "the", "stream", "when", "they", "are", "done", "with", "it", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/Photo.java#L920-L925
159,995
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/Photo.java
Photo.setSizes
public void setSizes(Collection<Size> sizes) { for (Size size : sizes) { if (size.getLabel() == Size.SMALL) { smallSize = size; } else if (size.getLabel() == Size.SQUARE) { squareSize = size; } else if (size.getLabel() == Size.THUMB) { thumbnailSize = size; } else if (size.getLabel() == Size.MEDIUM) { mediumSize = size; } else if (size.getLabel() == Size.LARGE) { largeSize = size; } else if (size.getLabel() == Size.LARGE_1600) { large1600Size = size; } else if (size.getLabel() == Size.LARGE_2048) { large2048Size = size; } else if (size.getLabel() == Size.ORIGINAL) { originalSize = size; } else if (size.getLabel() == Size.SQUARE_LARGE) { squareLargeSize = size; } else if (size.getLabel() == Size.SMALL_320) { small320Size = size; } else if (size.getLabel() == Size.MEDIUM_640) { medium640Size = size; } else if (size.getLabel() == Size.MEDIUM_800) { medium800Size = size; } else if (size.getLabel() == Size.VIDEO_PLAYER) { videoPlayer = size; } else if (size.getLabel() == Size.SITE_MP4) { siteMP4 = size; } else if (size.getLabel() == Size.VIDEO_ORIGINAL) { videoOriginal = size; } else if (size.getLabel() == Size.MOBILE_MP4) { mobileMP4 = size; } else if (size.getLabel() == Size.HD_MP4) { hdMP4 = size; } } }
java
public void setSizes(Collection<Size> sizes) { for (Size size : sizes) { if (size.getLabel() == Size.SMALL) { smallSize = size; } else if (size.getLabel() == Size.SQUARE) { squareSize = size; } else if (size.getLabel() == Size.THUMB) { thumbnailSize = size; } else if (size.getLabel() == Size.MEDIUM) { mediumSize = size; } else if (size.getLabel() == Size.LARGE) { largeSize = size; } else if (size.getLabel() == Size.LARGE_1600) { large1600Size = size; } else if (size.getLabel() == Size.LARGE_2048) { large2048Size = size; } else if (size.getLabel() == Size.ORIGINAL) { originalSize = size; } else if (size.getLabel() == Size.SQUARE_LARGE) { squareLargeSize = size; } else if (size.getLabel() == Size.SMALL_320) { small320Size = size; } else if (size.getLabel() == Size.MEDIUM_640) { medium640Size = size; } else if (size.getLabel() == Size.MEDIUM_800) { medium800Size = size; } else if (size.getLabel() == Size.VIDEO_PLAYER) { videoPlayer = size; } else if (size.getLabel() == Size.SITE_MP4) { siteMP4 = size; } else if (size.getLabel() == Size.VIDEO_ORIGINAL) { videoOriginal = size; } else if (size.getLabel() == Size.MOBILE_MP4) { mobileMP4 = size; } else if (size.getLabel() == Size.HD_MP4) { hdMP4 = size; } } }
[ "public", "void", "setSizes", "(", "Collection", "<", "Size", ">", "sizes", ")", "{", "for", "(", "Size", "size", ":", "sizes", ")", "{", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "SMALL", ")", "{", "smallSize", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "SQUARE", ")", "{", "squareSize", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "THUMB", ")", "{", "thumbnailSize", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "MEDIUM", ")", "{", "mediumSize", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "LARGE", ")", "{", "largeSize", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "LARGE_1600", ")", "{", "large1600Size", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "LARGE_2048", ")", "{", "large2048Size", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "ORIGINAL", ")", "{", "originalSize", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "SQUARE_LARGE", ")", "{", "squareLargeSize", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "SMALL_320", ")", "{", "small320Size", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "MEDIUM_640", ")", "{", "medium640Size", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "MEDIUM_800", ")", "{", "medium800Size", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "VIDEO_PLAYER", ")", "{", "videoPlayer", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "SITE_MP4", ")", "{", "siteMP4", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "VIDEO_ORIGINAL", ")", "{", "videoOriginal", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "MOBILE_MP4", ")", "{", "mobileMP4", "=", "size", ";", "}", "else", "if", "(", "size", ".", "getLabel", "(", ")", "==", "Size", ".", "HD_MP4", ")", "{", "hdMP4", "=", "size", ";", "}", "}", "}" ]
Set sizes to override the generated URLs of the different sizes. @param sizes @see com.flickr4java.flickr.photos.PhotosInterface#getSizes(String)
[ "Set", "sizes", "to", "override", "the", "generated", "URLs", "of", "the", "different", "sizes", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/Photo.java#L1044-L1084
159,996
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/transform/TransformInterface.java
TransformInterface.rotate
public void rotate(String photoId, int degrees) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_ROTATE); parameters.put("photo_id", photoId); parameters.put("degrees", String.valueOf(degrees)); Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
java
public void rotate(String photoId, int degrees) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_ROTATE); parameters.put("photo_id", photoId); parameters.put("degrees", String.valueOf(degrees)); Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
[ "public", "void", "rotate", "(", "String", "photoId", ",", "int", "degrees", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_ROTATE", ")", ";", "parameters", ".", "put", "(", "\"photo_id\"", ",", "photoId", ")", ";", "parameters", ".", "put", "(", "\"degrees\"", ",", "String", ".", "valueOf", "(", "degrees", ")", ")", ";", "Response", "response", "=", "transportAPI", ".", "post", "(", "transportAPI", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "}" ]
Rotate the specified photo. The only allowed values for degrees are 90, 180 and 270. @param photoId The photo ID @param degrees The degrees to rotate (90, 170 or 270)
[ "Rotate", "the", "specified", "photo", ".", "The", "only", "allowed", "values", "for", "degrees", "are", "90", "180", "and", "270", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/transform/TransformInterface.java#L40-L51
159,997
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/uploader/UploadMetaData.java
UploadMetaData.getUploadParameters
public Map<String, String> getUploadParameters() { Map<String, String> parameters = new TreeMap<>(); String title = getTitle(); if (title != null) { parameters.put("title", title); } String description = getDescription(); if (description != null) { parameters.put("description", description); } Collection<String> tags = getTags(); if (tags != null) { parameters.put("tags", StringUtilities.join(tags, " ")); } if (isHidden() != null) { parameters.put("hidden", isHidden().booleanValue() ? "1" : "0"); } if (getSafetyLevel() != null) { parameters.put("safety_level", getSafetyLevel()); } if (getContentType() != null) { parameters.put("content_type", getContentType()); } if (getPhotoId() != null) { parameters.put("photo_id", getPhotoId()); } parameters.put("is_public", isPublicFlag() ? "1" : "0"); parameters.put("is_family", isFamilyFlag() ? "1" : "0"); parameters.put("is_friend", isFriendFlag() ? "1" : "0"); parameters.put("async", isAsync() ? "1" : "0"); return parameters; }
java
public Map<String, String> getUploadParameters() { Map<String, String> parameters = new TreeMap<>(); String title = getTitle(); if (title != null) { parameters.put("title", title); } String description = getDescription(); if (description != null) { parameters.put("description", description); } Collection<String> tags = getTags(); if (tags != null) { parameters.put("tags", StringUtilities.join(tags, " ")); } if (isHidden() != null) { parameters.put("hidden", isHidden().booleanValue() ? "1" : "0"); } if (getSafetyLevel() != null) { parameters.put("safety_level", getSafetyLevel()); } if (getContentType() != null) { parameters.put("content_type", getContentType()); } if (getPhotoId() != null) { parameters.put("photo_id", getPhotoId()); } parameters.put("is_public", isPublicFlag() ? "1" : "0"); parameters.put("is_family", isFamilyFlag() ? "1" : "0"); parameters.put("is_friend", isFriendFlag() ? "1" : "0"); parameters.put("async", isAsync() ? "1" : "0"); return parameters; }
[ "public", "Map", "<", "String", ",", "String", ">", "getUploadParameters", "(", ")", "{", "Map", "<", "String", ",", "String", ">", "parameters", "=", "new", "TreeMap", "<>", "(", ")", ";", "String", "title", "=", "getTitle", "(", ")", ";", "if", "(", "title", "!=", "null", ")", "{", "parameters", ".", "put", "(", "\"title\"", ",", "title", ")", ";", "}", "String", "description", "=", "getDescription", "(", ")", ";", "if", "(", "description", "!=", "null", ")", "{", "parameters", ".", "put", "(", "\"description\"", ",", "description", ")", ";", "}", "Collection", "<", "String", ">", "tags", "=", "getTags", "(", ")", ";", "if", "(", "tags", "!=", "null", ")", "{", "parameters", ".", "put", "(", "\"tags\"", ",", "StringUtilities", ".", "join", "(", "tags", ",", "\" \"", ")", ")", ";", "}", "if", "(", "isHidden", "(", ")", "!=", "null", ")", "{", "parameters", ".", "put", "(", "\"hidden\"", ",", "isHidden", "(", ")", ".", "booleanValue", "(", ")", "?", "\"1\"", ":", "\"0\"", ")", ";", "}", "if", "(", "getSafetyLevel", "(", ")", "!=", "null", ")", "{", "parameters", ".", "put", "(", "\"safety_level\"", ",", "getSafetyLevel", "(", ")", ")", ";", "}", "if", "(", "getContentType", "(", ")", "!=", "null", ")", "{", "parameters", ".", "put", "(", "\"content_type\"", ",", "getContentType", "(", ")", ")", ";", "}", "if", "(", "getPhotoId", "(", ")", "!=", "null", ")", "{", "parameters", ".", "put", "(", "\"photo_id\"", ",", "getPhotoId", "(", ")", ")", ";", "}", "parameters", ".", "put", "(", "\"is_public\"", ",", "isPublicFlag", "(", ")", "?", "\"1\"", ":", "\"0\"", ")", ";", "parameters", ".", "put", "(", "\"is_family\"", ",", "isFamilyFlag", "(", ")", "?", "\"1\"", ":", "\"0\"", ")", ";", "parameters", ".", "put", "(", "\"is_friend\"", ",", "isFriendFlag", "(", ")", "?", "\"1\"", ":", "\"0\"", ")", ";", "parameters", ".", "put", "(", "\"async\"", ",", "isAsync", "(", ")", "?", "\"1\"", ":", "\"0\"", ")", ";", "return", "parameters", ";", "}" ]
Get the upload parameters. @return
[ "Get", "the", "upload", "parameters", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/uploader/UploadMetaData.java#L227-L268
159,998
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/comments/CommentsInterface.java
CommentsInterface.deleteComment
public void deleteComment(String commentId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_DELETE_COMMENT); parameters.put("comment_id", commentId); // Note: This method requires an HTTP POST request. Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } // This method has no specific response - It returns an empty // sucess response if it completes without error. }
java
public void deleteComment(String commentId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_DELETE_COMMENT); parameters.put("comment_id", commentId); // Note: This method requires an HTTP POST request. Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } // This method has no specific response - It returns an empty // sucess response if it completes without error. }
[ "public", "void", "deleteComment", "(", "String", "commentId", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_DELETE_COMMENT", ")", ";", "parameters", ".", "put", "(", "\"comment_id\"", ",", "commentId", ")", ";", "// Note: This method requires an HTTP POST request.\r", "Response", "response", "=", "transportAPI", ".", "post", "(", "transportAPI", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "// This method has no specific response - It returns an empty\r", "// sucess response if it completes without error.\r", "}" ]
Delete a comment as the currently authenticated user. This method requires authentication with 'write' permission. @param commentId The id of the comment to delete. @throws FlickrException
[ "Delete", "a", "comment", "as", "the", "currently", "authenticated", "user", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/comments/CommentsInterface.java#L89-L102
159,999
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/comments/CommentsInterface.java
CommentsInterface.editComment
public void editComment(String commentId, String commentText) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_EDIT_COMMENT); parameters.put("comment_id", commentId); parameters.put("comment_text", commentText); // Note: This method requires an HTTP POST request. Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } // This method has no specific response - It returns an empty // sucess response if it completes without error. }
java
public void editComment(String commentId, String commentText) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_EDIT_COMMENT); parameters.put("comment_id", commentId); parameters.put("comment_text", commentText); // Note: This method requires an HTTP POST request. Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } // This method has no specific response - It returns an empty // sucess response if it completes without error. }
[ "public", "void", "editComment", "(", "String", "commentId", ",", "String", "commentText", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_EDIT_COMMENT", ")", ";", "parameters", ".", "put", "(", "\"comment_id\"", ",", "commentId", ")", ";", "parameters", ".", "put", "(", "\"comment_text\"", ",", "commentText", ")", ";", "// Note: This method requires an HTTP POST request.\r", "Response", "response", "=", "transportAPI", ".", "post", "(", "transportAPI", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "// This method has no specific response - It returns an empty\r", "// sucess response if it completes without error.\r", "}" ]
Edit the text of a comment as the currently authenticated user. This method requires authentication with 'write' permission. @param commentId The id of the comment to edit. @param commentText Update the comment to this text. @throws FlickrException
[ "Edit", "the", "text", "of", "a", "comment", "as", "the", "currently", "authenticated", "user", "." ]
f66987ba0e360e5fb7730efbbb8c51f3d978fc25
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/comments/CommentsInterface.java#L115-L129