task_id
stringlengths 5
19
| buggy_code
stringlengths 44
3.26k
| fixed_code
stringlengths 67
3.31k
| file_path
stringlengths 36
95
| issue_title
stringlengths 0
150
| issue_description
stringlengths 0
2.85k
| start_line
int64 9
4.43k
| end_line
int64 11
4.52k
|
---|---|---|---|---|---|---|---|
Math-25
|
private void guessAOmega() {
// initialize the sums for the linear model between the two integrals
double sx2 = 0;
double sy2 = 0;
double sxy = 0;
double sxz = 0;
double syz = 0;
double currentX = observations[0].getX();
double currentY = observations[0].getY();
double f2Integral = 0;
double fPrime2Integral = 0;
final double startX = currentX;
for (int i = 1; i < observations.length; ++i) {
// one step forward
final double previousX = currentX;
final double previousY = currentY;
currentX = observations[i].getX();
currentY = observations[i].getY();
// update the integrals of f<sup>2</sup> and f'<sup>2</sup>
// considering a linear model for f (and therefore constant f')
final double dx = currentX - previousX;
final double dy = currentY - previousY;
final double f2StepIntegral =
dx * (previousY * previousY + previousY * currentY + currentY * currentY) / 3;
final double fPrime2StepIntegral = dy * dy / dx;
final double x = currentX - startX;
f2Integral += f2StepIntegral;
fPrime2Integral += fPrime2StepIntegral;
sx2 += x * x;
sy2 += f2Integral * f2Integral;
sxy += x * f2Integral;
sxz += x * fPrime2Integral;
syz += f2Integral * fPrime2Integral;
}
// compute the amplitude and pulsation coefficients
double c1 = sy2 * sxz - sxy * syz;
double c2 = sxy * sxz - sx2 * syz;
double c3 = sx2 * sy2 - sxy * sxy;
if ((c1 / c2 < 0) || (c2 / c3 < 0)) {
final int last = observations.length - 1;
// Range of the observations, assuming that the
// observations are sorted.
final double xRange = observations[last].getX() - observations[0].getX();
if (xRange == 0) {
throw new ZeroException();
}
omega = 2 * Math.PI / xRange;
double yMin = Double.POSITIVE_INFINITY;
double yMax = Double.NEGATIVE_INFINITY;
for (int i = 1; i < observations.length; ++i) {
final double y = observations[i].getY();
if (y < yMin) {
yMin = y;
}
if (y > yMax) {
yMax = y;
}
}
a = 0.5 * (yMax - yMin);
} else {
// In some ill-conditioned cases (cf. MATH-844), the guesser
// procedure cannot produce sensible results.
a = FastMath.sqrt(c1 / c2);
omega = FastMath.sqrt(c2 / c3);
}
}
|
private void guessAOmega() {
// initialize the sums for the linear model between the two integrals
double sx2 = 0;
double sy2 = 0;
double sxy = 0;
double sxz = 0;
double syz = 0;
double currentX = observations[0].getX();
double currentY = observations[0].getY();
double f2Integral = 0;
double fPrime2Integral = 0;
final double startX = currentX;
for (int i = 1; i < observations.length; ++i) {
// one step forward
final double previousX = currentX;
final double previousY = currentY;
currentX = observations[i].getX();
currentY = observations[i].getY();
// update the integrals of f<sup>2</sup> and f'<sup>2</sup>
// considering a linear model for f (and therefore constant f')
final double dx = currentX - previousX;
final double dy = currentY - previousY;
final double f2StepIntegral =
dx * (previousY * previousY + previousY * currentY + currentY * currentY) / 3;
final double fPrime2StepIntegral = dy * dy / dx;
final double x = currentX - startX;
f2Integral += f2StepIntegral;
fPrime2Integral += fPrime2StepIntegral;
sx2 += x * x;
sy2 += f2Integral * f2Integral;
sxy += x * f2Integral;
sxz += x * fPrime2Integral;
syz += f2Integral * fPrime2Integral;
}
// compute the amplitude and pulsation coefficients
double c1 = sy2 * sxz - sxy * syz;
double c2 = sxy * sxz - sx2 * syz;
double c3 = sx2 * sy2 - sxy * sxy;
if ((c1 / c2 < 0) || (c2 / c3 < 0)) {
final int last = observations.length - 1;
// Range of the observations, assuming that the
// observations are sorted.
final double xRange = observations[last].getX() - observations[0].getX();
if (xRange == 0) {
throw new ZeroException();
}
omega = 2 * Math.PI / xRange;
double yMin = Double.POSITIVE_INFINITY;
double yMax = Double.NEGATIVE_INFINITY;
for (int i = 1; i < observations.length; ++i) {
final double y = observations[i].getY();
if (y < yMin) {
yMin = y;
}
if (y > yMax) {
yMax = y;
}
}
a = 0.5 * (yMax - yMin);
} else {
if (c2 == 0) {
// In some ill-conditioned cases (cf. MATH-844), the guesser
// procedure cannot produce sensible results.
throw new MathIllegalStateException(LocalizedFormats.ZERO_DENOMINATOR);
}
a = FastMath.sqrt(c1 / c2);
omega = FastMath.sqrt(c2 / c3);
}
}
|
src/main/java/org/apache/commons/math3/optimization/fitting/HarmonicFitter.java
|
"HarmonicFitter.ParameterGuesser" sometimes fails to return sensible values
|
The inner class "ParameterGuesser" in "HarmonicFitter" (package "o.a.c.m.optimization.fitting") fails to compute a usable guess for the "amplitude" parameter.
| 257 | 329 |
Math-27
|
public double percentageValue() {
return multiply(100).doubleValue();
}
|
public double percentageValue() {
return 100 * doubleValue();
}
|
src/main/java/org/apache/commons/math3/fraction/Fraction.java
|
Fraction percentageValue rare overflow
|
The percentageValue() method of the Fraction class works by first multiplying the Fraction by 100, then converting the Fraction to a double. This causes overflows when the numerator is greater than Integer.MAX_VALUE/100, even when the value of the fraction is far below this value.
The patch changes the method to first convert to a double value, and then multiply this value by 100 - the result should be the same, but with less overflows. An addition to the test for the method that covers this bug is also included.
| 596 | 598 |
Math-3
|
public static double linearCombination(final double[] a, final double[] b)
throws DimensionMismatchException {
final int len = a.length;
if (len != b.length) {
throw new DimensionMismatchException(len, b.length);
}
// Revert to scalar multiplication.
final double[] prodHigh = new double[len];
double prodLowSum = 0;
for (int i = 0; i < len; i++) {
final double ai = a[i];
final double ca = SPLIT_FACTOR * ai;
final double aHigh = ca - (ca - ai);
final double aLow = ai - aHigh;
final double bi = b[i];
final double cb = SPLIT_FACTOR * bi;
final double bHigh = cb - (cb - bi);
final double bLow = bi - bHigh;
prodHigh[i] = ai * bi;
final double prodLow = aLow * bLow - (((prodHigh[i] -
aHigh * bHigh) -
aLow * bHigh) -
aHigh * bLow);
prodLowSum += prodLow;
}
final double prodHighCur = prodHigh[0];
double prodHighNext = prodHigh[1];
double sHighPrev = prodHighCur + prodHighNext;
double sPrime = sHighPrev - prodHighNext;
double sLowSum = (prodHighNext - (sHighPrev - sPrime)) + (prodHighCur - sPrime);
final int lenMinusOne = len - 1;
for (int i = 1; i < lenMinusOne; i++) {
prodHighNext = prodHigh[i + 1];
final double sHighCur = sHighPrev + prodHighNext;
sPrime = sHighCur - prodHighNext;
sLowSum += (prodHighNext - (sHighCur - sPrime)) + (sHighPrev - sPrime);
sHighPrev = sHighCur;
}
double result = sHighPrev + (prodLowSum + sLowSum);
if (Double.isNaN(result)) {
// either we have split infinite numbers or some coefficients were NaNs,
// just rely on the naive implementation and let IEEE754 handle this
result = 0;
for (int i = 0; i < len; ++i) {
result += a[i] * b[i];
}
}
return result;
}
|
public static double linearCombination(final double[] a, final double[] b)
throws DimensionMismatchException {
final int len = a.length;
if (len != b.length) {
throw new DimensionMismatchException(len, b.length);
}
if (len == 1) {
// Revert to scalar multiplication.
return a[0] * b[0];
}
final double[] prodHigh = new double[len];
double prodLowSum = 0;
for (int i = 0; i < len; i++) {
final double ai = a[i];
final double ca = SPLIT_FACTOR * ai;
final double aHigh = ca - (ca - ai);
final double aLow = ai - aHigh;
final double bi = b[i];
final double cb = SPLIT_FACTOR * bi;
final double bHigh = cb - (cb - bi);
final double bLow = bi - bHigh;
prodHigh[i] = ai * bi;
final double prodLow = aLow * bLow - (((prodHigh[i] -
aHigh * bHigh) -
aLow * bHigh) -
aHigh * bLow);
prodLowSum += prodLow;
}
final double prodHighCur = prodHigh[0];
double prodHighNext = prodHigh[1];
double sHighPrev = prodHighCur + prodHighNext;
double sPrime = sHighPrev - prodHighNext;
double sLowSum = (prodHighNext - (sHighPrev - sPrime)) + (prodHighCur - sPrime);
final int lenMinusOne = len - 1;
for (int i = 1; i < lenMinusOne; i++) {
prodHighNext = prodHigh[i + 1];
final double sHighCur = sHighPrev + prodHighNext;
sPrime = sHighCur - prodHighNext;
sLowSum += (prodHighNext - (sHighCur - sPrime)) + (sHighPrev - sPrime);
sHighPrev = sHighCur;
}
double result = sHighPrev + (prodLowSum + sLowSum);
if (Double.isNaN(result)) {
// either we have split infinite numbers or some coefficients were NaNs,
// just rely on the naive implementation and let IEEE754 handle this
result = 0;
for (int i = 0; i < len; ++i) {
result += a[i] * b[i];
}
}
return result;
}
|
src/main/java/org/apache/commons/math3/util/MathArrays.java
|
ArrayIndexOutOfBoundsException in MathArrays.linearCombination
|
When MathArrays.linearCombination is passed arguments with length 1, it throws an ArrayOutOfBoundsException. This is caused by this line:
double prodHighNext = prodHigh[1];
linearCombination should check the length of the arguments and fall back to simple multiplication if length == 1.
| 814 | 872 |
Math-30
|
private double calculateAsymptoticPValue(final double Umin,
final int n1,
final int n2)
throws ConvergenceException, MaxCountExceededException {
final int n1n2prod = n1 * n2;
// http://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U#Normal_approximation
final double EU = n1n2prod / 2.0;
final double VarU = n1n2prod * (n1 + n2 + 1) / 12.0;
final double z = (Umin - EU) / FastMath.sqrt(VarU);
final NormalDistribution standardNormal = new NormalDistribution(0, 1);
return 2 * standardNormal.cumulativeProbability(z);
}
|
private double calculateAsymptoticPValue(final double Umin,
final int n1,
final int n2)
throws ConvergenceException, MaxCountExceededException {
final double n1n2prod = n1 * n2;
// http://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U#Normal_approximation
final double EU = n1n2prod / 2.0;
final double VarU = n1n2prod * (n1 + n2 + 1) / 12.0;
final double z = (Umin - EU) / FastMath.sqrt(VarU);
final NormalDistribution standardNormal = new NormalDistribution(0, 1);
return 2 * standardNormal.cumulativeProbability(z);
}
|
src/main/java/org/apache/commons/math3/stat/inference/MannWhitneyUTest.java
|
Mann-Whitney U Test Suffers From Integer Overflow With Large Data Sets
|
When performing a Mann-Whitney U Test on large data sets (the attached test uses two 1500 element sets), intermediate integer values used in calculateAsymptoticPValue can overflow, leading to invalid results, such as p-values of NaN, or incorrect calculations.
Attached is a patch, including a test, and a fix, which modifies the affected code to use doubles
| 168 | 184 |
Math-32
|
protected void computeGeometricalProperties() {
final Vector2D[][] v = getVertices();
if (v.length == 0) {
final BSPTree<Euclidean2D> tree = getTree(false);
if ((Boolean) tree.getAttribute()) {
// the instance covers the whole space
setSize(Double.POSITIVE_INFINITY);
setBarycenter(Vector2D.NaN);
} else {
setSize(0);
setBarycenter(new Vector2D(0, 0));
}
} else if (v[0][0] == null) {
// there is at least one open-loop: the polygon is infinite
setSize(Double.POSITIVE_INFINITY);
setBarycenter(Vector2D.NaN);
} else {
// all loops are closed, we compute some integrals around the shape
double sum = 0;
double sumX = 0;
double sumY = 0;
for (Vector2D[] loop : v) {
double x1 = loop[loop.length - 1].getX();
double y1 = loop[loop.length - 1].getY();
for (final Vector2D point : loop) {
final double x0 = x1;
final double y0 = y1;
x1 = point.getX();
y1 = point.getY();
final double factor = x0 * y1 - y0 * x1;
sum += factor;
sumX += factor * (x0 + x1);
sumY += factor * (y0 + y1);
}
}
if (sum < 0) {
// the polygon as a finite outside surrounded by an infinite inside
setSize(Double.POSITIVE_INFINITY);
setBarycenter(Vector2D.NaN);
} else {
setSize(sum / 2);
setBarycenter(new Vector2D(sumX / (3 * sum), sumY / (3 * sum)));
}
}
}
|
protected void computeGeometricalProperties() {
final Vector2D[][] v = getVertices();
if (v.length == 0) {
final BSPTree<Euclidean2D> tree = getTree(false);
if (tree.getCut() == null && (Boolean) tree.getAttribute()) {
// the instance covers the whole space
setSize(Double.POSITIVE_INFINITY);
setBarycenter(Vector2D.NaN);
} else {
setSize(0);
setBarycenter(new Vector2D(0, 0));
}
} else if (v[0][0] == null) {
// there is at least one open-loop: the polygon is infinite
setSize(Double.POSITIVE_INFINITY);
setBarycenter(Vector2D.NaN);
} else {
// all loops are closed, we compute some integrals around the shape
double sum = 0;
double sumX = 0;
double sumY = 0;
for (Vector2D[] loop : v) {
double x1 = loop[loop.length - 1].getX();
double y1 = loop[loop.length - 1].getY();
for (final Vector2D point : loop) {
final double x0 = x1;
final double y0 = y1;
x1 = point.getX();
y1 = point.getY();
final double factor = x0 * y1 - y0 * x1;
sum += factor;
sumX += factor * (x0 + x1);
sumY += factor * (y0 + y1);
}
}
if (sum < 0) {
// the polygon as a finite outside surrounded by an infinite inside
setSize(Double.POSITIVE_INFINITY);
setBarycenter(Vector2D.NaN);
} else {
setSize(sum / 2);
setBarycenter(new Vector2D(sumX / (3 * sum), sumY / (3 * sum)));
}
}
}
|
src/main/java/org/apache/commons/math3/geometry/euclidean/twod/PolygonsSet.java
|
BSPTree class and recovery of a Euclidean 3D BRep
|
New to the work here. Thanks for your efforts on this code.
I create a BSPTree from a BoundaryRep (Brep) my test Brep is a cube as represented by a float array containing 8 3D points in(x,y,z) order and an array of indices (12 triplets for the 12 faces of the cube). I construct a BSPMesh() as shown in the code below. I can construct the PolyhedronsSet() but have problems extracting the faces from the BSPTree to reconstruct the BRep. The attached code (BSPMesh2.java) shows that a small change to 1 of the vertex positions causes/corrects the problem.
Any ideas?
| 130 | 181 |
Math-33
|
protected void dropPhase1Objective() {
if (getNumObjectiveFunctions() == 1) {
return;
}
List<Integer> columnsToDrop = new ArrayList<Integer>();
columnsToDrop.add(0);
// positive cost non-artificial variables
for (int i = getNumObjectiveFunctions(); i < getArtificialVariableOffset(); i++) {
final double entry = tableau.getEntry(0, i);
if (Precision.compareTo(entry, 0d, maxUlps) > 0) {
columnsToDrop.add(i);
}
}
// non-basic artificial variables
for (int i = 0; i < getNumArtificialVariables(); i++) {
int col = i + getArtificialVariableOffset();
if (getBasicRow(col) == null) {
columnsToDrop.add(col);
}
}
double[][] matrix = new double[getHeight() - 1][getWidth() - columnsToDrop.size()];
for (int i = 1; i < getHeight(); i++) {
int col = 0;
for (int j = 0; j < getWidth(); j++) {
if (!columnsToDrop.contains(j)) {
matrix[i - 1][col++] = tableau.getEntry(i, j);
}
}
}
for (int i = columnsToDrop.size() - 1; i >= 0; i--) {
columnLabels.remove((int) columnsToDrop.get(i));
}
this.tableau = new Array2DRowRealMatrix(matrix);
this.numArtificialVariables = 0;
}
|
protected void dropPhase1Objective() {
if (getNumObjectiveFunctions() == 1) {
return;
}
List<Integer> columnsToDrop = new ArrayList<Integer>();
columnsToDrop.add(0);
// positive cost non-artificial variables
for (int i = getNumObjectiveFunctions(); i < getArtificialVariableOffset(); i++) {
final double entry = tableau.getEntry(0, i);
if (Precision.compareTo(entry, 0d, epsilon) > 0) {
columnsToDrop.add(i);
}
}
// non-basic artificial variables
for (int i = 0; i < getNumArtificialVariables(); i++) {
int col = i + getArtificialVariableOffset();
if (getBasicRow(col) == null) {
columnsToDrop.add(col);
}
}
double[][] matrix = new double[getHeight() - 1][getWidth() - columnsToDrop.size()];
for (int i = 1; i < getHeight(); i++) {
int col = 0;
for (int j = 0; j < getWidth(); j++) {
if (!columnsToDrop.contains(j)) {
matrix[i - 1][col++] = tableau.getEntry(i, j);
}
}
}
for (int i = columnsToDrop.size() - 1; i >= 0; i--) {
columnLabels.remove((int) columnsToDrop.get(i));
}
this.tableau = new Array2DRowRealMatrix(matrix);
this.numArtificialVariables = 0;
}
|
src/main/java/org/apache/commons/math3/optimization/linear/SimplexTableau.java
|
SimplexSolver gives bad results
|
Methode SimplexSolver.optimeze(...) gives bad results with commons-math3-3.0
in a simple test problem. It works well in commons-math-2.2.
| 327 | 367 |
Math-34
|
public Iterator<Chromosome> iterator() {
return chromosomes.iterator();
}
|
public Iterator<Chromosome> iterator() {
return getChromosomes().iterator();
}
|
src/main/java/org/apache/commons/math3/genetics/ListPopulation.java
|
ListPopulation Iterator allows you to remove chromosomes from the population.
|
Calling the iterator method of ListPopulation returns an iterator of the protected modifiable list. Before returning the iterator we should wrap it in an unmodifiable list.
| 208 | 210 |
Math-41
|
public double evaluate(final double[] values, final double[] weights,
final double mean, final int begin, final int length) {
double var = Double.NaN;
if (test(values, weights, begin, length)) {
if (length == 1) {
var = 0.0;
} else if (length > 1) {
double accum = 0.0;
double dev = 0.0;
double accum2 = 0.0;
for (int i = begin; i < begin + length; i++) {
dev = values[i] - mean;
accum += weights[i] * (dev * dev);
accum2 += weights[i] * dev;
}
double sumWts = 0;
for (int i = 0; i < weights.length; i++) {
sumWts += weights[i];
}
if (isBiasCorrected) {
var = (accum - (accum2 * accum2 / sumWts)) / (sumWts - 1.0);
} else {
var = (accum - (accum2 * accum2 / sumWts)) / sumWts;
}
}
}
return var;
}
|
public double evaluate(final double[] values, final double[] weights,
final double mean, final int begin, final int length) {
double var = Double.NaN;
if (test(values, weights, begin, length)) {
if (length == 1) {
var = 0.0;
} else if (length > 1) {
double accum = 0.0;
double dev = 0.0;
double accum2 = 0.0;
for (int i = begin; i < begin + length; i++) {
dev = values[i] - mean;
accum += weights[i] * (dev * dev);
accum2 += weights[i] * dev;
}
double sumWts = 0;
for (int i = begin; i < begin + length; i++) {
sumWts += weights[i];
}
if (isBiasCorrected) {
var = (accum - (accum2 * accum2 / sumWts)) / (sumWts - 1.0);
} else {
var = (accum - (accum2 * accum2 / sumWts)) / sumWts;
}
}
}
return var;
}
|
src/main/java/org/apache/commons/math/stat/descriptive/moment/Variance.java
|
One of Variance.evaluate() methods does not work correctly
|
The method org.apache.commons.math.stat.descriptive.moment.Variance.evaluate(double[] values, double[] weights, double mean, int begin, int length) does not work properly. Looks loke it ignores the length parameter and grabs the whole dataset.
Similar method in Mean class seems to work.
I did not check other methods taking the part of the array; they may have the same problem.
Workaround: I had to shrink my arrays and use the method without the length.
| 501 | 532 |
Math-42
|
protected RealPointValuePair getSolution() {
int negativeVarColumn = columnLabels.indexOf(NEGATIVE_VAR_COLUMN_LABEL);
Integer negativeVarBasicRow = negativeVarColumn > 0 ? getBasicRow(negativeVarColumn) : null;
double mostNegative = negativeVarBasicRow == null ? 0 : getEntry(negativeVarBasicRow, getRhsOffset());
Set<Integer> basicRows = new HashSet<Integer>();
double[] coefficients = new double[getOriginalNumDecisionVariables()];
for (int i = 0; i < coefficients.length; i++) {
int colIndex = columnLabels.indexOf("x" + i);
if (colIndex < 0) {
coefficients[i] = 0;
continue;
}
Integer basicRow = getBasicRow(colIndex);
// if the basic row is found to be the objective function row
// set the coefficient to 0 -> this case handles unconstrained
// variables that are still part of the objective function
if (basicRows.contains(basicRow)) {
// if multiple variables can take a given value
// then we choose the first and set the rest equal to 0
coefficients[i] = 0 - (restrictToNonNegative ? 0 : mostNegative);
} else {
basicRows.add(basicRow);
coefficients[i] =
(basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) -
(restrictToNonNegative ? 0 : mostNegative);
}
}
return new RealPointValuePair(coefficients, f.getValue(coefficients));
}
|
protected RealPointValuePair getSolution() {
int negativeVarColumn = columnLabels.indexOf(NEGATIVE_VAR_COLUMN_LABEL);
Integer negativeVarBasicRow = negativeVarColumn > 0 ? getBasicRow(negativeVarColumn) : null;
double mostNegative = negativeVarBasicRow == null ? 0 : getEntry(negativeVarBasicRow, getRhsOffset());
Set<Integer> basicRows = new HashSet<Integer>();
double[] coefficients = new double[getOriginalNumDecisionVariables()];
for (int i = 0; i < coefficients.length; i++) {
int colIndex = columnLabels.indexOf("x" + i);
if (colIndex < 0) {
coefficients[i] = 0;
continue;
}
Integer basicRow = getBasicRow(colIndex);
if (basicRow != null && basicRow == 0) {
// if the basic row is found to be the objective function row
// set the coefficient to 0 -> this case handles unconstrained
// variables that are still part of the objective function
coefficients[i] = 0;
} else if (basicRows.contains(basicRow)) {
// if multiple variables can take a given value
// then we choose the first and set the rest equal to 0
coefficients[i] = 0 - (restrictToNonNegative ? 0 : mostNegative);
} else {
basicRows.add(basicRow);
coefficients[i] =
(basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) -
(restrictToNonNegative ? 0 : mostNegative);
}
}
return new RealPointValuePair(coefficients, f.getValue(coefficients));
}
|
src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java
|
Negative value with restrictNonNegative
|
Problem: commons-math-2.2 SimplexSolver.
A variable with 0 coefficient may be assigned a negative value nevertheless restrictToNonnegative flag in call:
SimplexSolver.optimize(function, constraints, GoalType.MINIMIZE, true);
Function
1 * x + 1 * y + 0
Constraints:
1 * x + 0 * y = 1
Result:
x = 1; y = -1;
Probably variables with 0 coefficients are omitted at some point of computation and because of that the restrictions do not affect their values.
| 396 | 425 |
Math-43
|
public void addValue(double value) {
sumImpl.increment(value);
sumsqImpl.increment(value);
minImpl.increment(value);
maxImpl.increment(value);
sumLogImpl.increment(value);
secondMoment.increment(value);
// If mean, variance or geomean have been overridden,
// need to increment these
if (!(meanImpl instanceof Mean)) {
meanImpl.increment(value);
}
if (!(varianceImpl instanceof Variance)) {
varianceImpl.increment(value);
}
if (!(geoMeanImpl instanceof GeometricMean)) {
geoMeanImpl.increment(value);
}
n++;
}
|
public void addValue(double value) {
sumImpl.increment(value);
sumsqImpl.increment(value);
minImpl.increment(value);
maxImpl.increment(value);
sumLogImpl.increment(value);
secondMoment.increment(value);
// If mean, variance or geomean have been overridden,
// need to increment these
if (meanImpl != mean) {
meanImpl.increment(value);
}
if (varianceImpl != variance) {
varianceImpl.increment(value);
}
if (geoMeanImpl != geoMean) {
geoMeanImpl.increment(value);
}
n++;
}
|
src/main/java/org/apache/commons/math/stat/descriptive/SummaryStatistics.java
|
Statistics.setVarianceImpl makes getStandardDeviation produce NaN
|
Invoking SummaryStatistics.setVarianceImpl(new Variance(true/false) makes getStandardDeviation produce NaN. The code to reproduce it:
int[] scores = {1, 2, 3, 4};
SummaryStatistics stats = new SummaryStatistics();
stats.setVarianceImpl(new Variance(false)); //use "population variance"
for(int i : scores) {
stats.addValue(i);
}
double sd = stats.getStandardDeviation();
System.out.println(sd);
A workaround suggested by Mikkel is:
double sd = FastMath.sqrt(stats.getSecondMoment() / stats.getN());
| 149 | 168 |
Math-45
|
public OpenMapRealMatrix(int rowDimension, int columnDimension) {
super(rowDimension, columnDimension);
this.rows = rowDimension;
this.columns = columnDimension;
this.entries = new OpenIntToDoubleHashMap(0.0);
}
|
public OpenMapRealMatrix(int rowDimension, int columnDimension) {
super(rowDimension, columnDimension);
long lRow = (long) rowDimension;
long lCol = (long) columnDimension;
if (lRow * lCol >= (long) Integer.MAX_VALUE) {
throw new NumberIsTooLargeException(lRow * lCol, Integer.MAX_VALUE, false);
}
this.rows = rowDimension;
this.columns = columnDimension;
this.entries = new OpenIntToDoubleHashMap(0.0);
}
|
src/main/java/org/apache/commons/math/linear/OpenMapRealMatrix.java
|
Integer overflow in OpenMapRealMatrix
|
computeKey() has an integer overflow. Since it is a sparse matrix, this is quite easily encountered long before heap space is exhausted. The attached code demonstrates the problem, which could potentially be a security vulnerability (for example, if one was to use this matrix to store access control information).
Workaround: never create an OpenMapRealMatrix with more cells than are addressable with an int.
| 48 | 53 |
Math-5
|
public Complex reciprocal() {
if (isNaN) {
return NaN;
}
if (real == 0.0 && imaginary == 0.0) {
return NaN;
}
if (isInfinite) {
return ZERO;
}
if (FastMath.abs(real) < FastMath.abs(imaginary)) {
double q = real / imaginary;
double scale = 1. / (real * q + imaginary);
return createComplex(scale * q, -scale);
} else {
double q = imaginary / real;
double scale = 1. / (imaginary * q + real);
return createComplex(scale, -scale * q);
}
}
|
public Complex reciprocal() {
if (isNaN) {
return NaN;
}
if (real == 0.0 && imaginary == 0.0) {
return INF;
}
if (isInfinite) {
return ZERO;
}
if (FastMath.abs(real) < FastMath.abs(imaginary)) {
double q = real / imaginary;
double scale = 1. / (real * q + imaginary);
return createComplex(scale * q, -scale);
} else {
double q = imaginary / real;
double scale = 1. / (imaginary * q + real);
return createComplex(scale, -scale * q);
}
}
|
src/main/java/org/apache/commons/math3/complex/Complex.java
|
Complex.ZERO.reciprocal() returns NaN but should return INF.
|
Complex.ZERO.reciprocal() returns NaN but should return INF.
Class: org.apache.commons.math3.complex.Complex;
Method: reciprocal()
@version $Id: Complex.java 1416643 2012-12-03 19:37:14Z tn $
| 299 | 321 |
Math-53
|
public Complex add(Complex rhs)
throws NullArgumentException {
MathUtils.checkNotNull(rhs);
return createComplex(real + rhs.getReal(),
imaginary + rhs.getImaginary());
}
|
public Complex add(Complex rhs)
throws NullArgumentException {
MathUtils.checkNotNull(rhs);
if (isNaN || rhs.isNaN) {
return NaN;
}
return createComplex(real + rhs.getReal(),
imaginary + rhs.getImaginary());
}
|
src/main/java/org/apache/commons/math/complex/Complex.java
|
Complex Add and Subtract handle NaN arguments differently, but javadoc contracts are the same
|
For both Complex add and subtract, the javadoc states that
* If either this or <code>rhs</code> has a NaN value in either part,
* {@link #NaN} is returned; otherwise Inifinite and NaN values are
* returned in the parts of the result according to the rules for
* {@link java.lang.Double} arithmetic
Subtract includes an isNaN test and returns Complex.NaN if either complex argument isNaN; but add omits this test. The test should be added to the add implementation (actually restored, since this looks like a code merge problem going back to 1.1).
| 150 | 155 |
Math-55
|
public static Vector3D crossProduct(final Vector3D v1, final Vector3D v2) {
// rescale both vectors without losing precision,
// to ensure their norm are the same order of magnitude
// we reduce cancellation errors by preconditioning,
// we replace v1 by v3 = v1 - rho v2 with rho chosen in order to compute
// v3 without loss of precision. See Kahan lecture
// "Computing Cross-Products and Rotations in 2- and 3-Dimensional Euclidean Spaces"
// available at http://www.cs.berkeley.edu/~wkahan/MathH110/Cross.pdf
// compute rho as an 8 bits approximation of v1.v2 / v2.v2
// compute cross product from v3 and v2 instead of v1 and v2
return new Vector3D(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x);
}
|
public static Vector3D crossProduct(final Vector3D v1, final Vector3D v2) {
final double n1 = v1.getNormSq();
final double n2 = v2.getNormSq();
if ((n1 * n2) < MathUtils.SAFE_MIN) {
return ZERO;
}
// rescale both vectors without losing precision,
// to ensure their norm are the same order of magnitude
final int deltaExp = (FastMath.getExponent(n1) - FastMath.getExponent(n2)) / 4;
final double x1 = FastMath.scalb(v1.x, -deltaExp);
final double y1 = FastMath.scalb(v1.y, -deltaExp);
final double z1 = FastMath.scalb(v1.z, -deltaExp);
final double x2 = FastMath.scalb(v2.x, deltaExp);
final double y2 = FastMath.scalb(v2.y, deltaExp);
final double z2 = FastMath.scalb(v2.z, deltaExp);
// we reduce cancellation errors by preconditioning,
// we replace v1 by v3 = v1 - rho v2 with rho chosen in order to compute
// v3 without loss of precision. See Kahan lecture
// "Computing Cross-Products and Rotations in 2- and 3-Dimensional Euclidean Spaces"
// available at http://www.cs.berkeley.edu/~wkahan/MathH110/Cross.pdf
// compute rho as an 8 bits approximation of v1.v2 / v2.v2
final double ratio = (x1 * x2 + y1 * y2 + z1 * z2) / FastMath.scalb(n2, 2 * deltaExp);
final double rho = FastMath.rint(256 * ratio) / 256;
final double x3 = x1 - rho * x2;
final double y3 = y1 - rho * y2;
final double z3 = z1 - rho * z2;
// compute cross product from v3 and v2 instead of v1 and v2
return new Vector3D(y3 * z2 - z3 * y2, z3 * x2 - x3 * z2, x3 * y2 - y3 * x2);
}
|
src/main/java/org/apache/commons/math/geometry/Vector3D.java
|
Vector3D.crossProduct is sensitive to numerical cancellation
|
Cross product implementation uses the naive formulas (y1 z2 - y2 z1, ...). These formulas fail when vectors are almost colinear, like in the following example:
Vector3D v1 = new Vector3D(9070467121.0, 4535233560.0, 1);
Vector3D v2 = new Vector3D(9070467123.0, 4535233561.0, 1);
System.out.println(Vector3D.crossProduct(v1, v2));
The previous code displays
{ -1, 2, 0 }
instead of the correct answer
{ -1, 2, 1 }
| 457 | 475 |
Math-57
|
private static <T extends Clusterable<T>> List<Cluster<T>>
chooseInitialCenters(final Collection<T> points, final int k, final Random random) {
final List<T> pointSet = new ArrayList<T>(points);
final List<Cluster<T>> resultSet = new ArrayList<Cluster<T>>();
// Choose one center uniformly at random from among the data points.
final T firstPoint = pointSet.remove(random.nextInt(pointSet.size()));
resultSet.add(new Cluster<T>(firstPoint));
final double[] dx2 = new double[pointSet.size()];
while (resultSet.size() < k) {
// For each data point x, compute D(x), the distance between x and
// the nearest center that has already been chosen.
int sum = 0;
for (int i = 0; i < pointSet.size(); i++) {
final T p = pointSet.get(i);
final Cluster<T> nearest = getNearestCluster(resultSet, p);
final double d = p.distanceFrom(nearest.getCenter());
sum += d * d;
dx2[i] = sum;
}
// Add one new data point as a center. Each point x is chosen with
// probability proportional to D(x)2
final double r = random.nextDouble() * sum;
for (int i = 0 ; i < dx2.length; i++) {
if (dx2[i] >= r) {
final T p = pointSet.remove(i);
resultSet.add(new Cluster<T>(p));
break;
}
}
}
return resultSet;
}
|
private static <T extends Clusterable<T>> List<Cluster<T>>
chooseInitialCenters(final Collection<T> points, final int k, final Random random) {
final List<T> pointSet = new ArrayList<T>(points);
final List<Cluster<T>> resultSet = new ArrayList<Cluster<T>>();
// Choose one center uniformly at random from among the data points.
final T firstPoint = pointSet.remove(random.nextInt(pointSet.size()));
resultSet.add(new Cluster<T>(firstPoint));
final double[] dx2 = new double[pointSet.size()];
while (resultSet.size() < k) {
// For each data point x, compute D(x), the distance between x and
// the nearest center that has already been chosen.
double sum = 0;
for (int i = 0; i < pointSet.size(); i++) {
final T p = pointSet.get(i);
final Cluster<T> nearest = getNearestCluster(resultSet, p);
final double d = p.distanceFrom(nearest.getCenter());
sum += d * d;
dx2[i] = sum;
}
// Add one new data point as a center. Each point x is chosen with
// probability proportional to D(x)2
final double r = random.nextDouble() * sum;
for (int i = 0 ; i < dx2.length; i++) {
if (dx2[i] >= r) {
final T p = pointSet.remove(i);
resultSet.add(new Cluster<T>(p));
break;
}
}
}
return resultSet;
}
|
src/main/java/org/apache/commons/math/stat/clustering/KMeansPlusPlusClusterer.java
|
Truncation issue in KMeansPlusPlusClusterer
|
The for loop inside KMeansPlusPlusClusterer.chooseInitialClusters defines a variable
int sum = 0;
This variable should have type double, rather than int. Using an int causes the method to truncate the distances between points to (square roots of) integers. It's especially bad when the distances between points are typically less than 1.
As an aside, in version 2.2, this bug manifested itself by making the clusterer return empty clusters. I wonder if the EmptyClusterStrategy would still be necessary if this bug were fixed.
| 161 | 198 |
Math-59
|
public static float max(final float a, final float b) {
return (a <= b) ? b : (Float.isNaN(a + b) ? Float.NaN : b);
}
|
public static float max(final float a, final float b) {
return (a <= b) ? b : (Float.isNaN(a + b) ? Float.NaN : a);
}
|
src/main/java/org/apache/commons/math/util/FastMath.java
|
FastMath.max(50.0f, -50.0f) => -50.0f; should be +50.0f
|
FastMath.max(50.0f, -50.0f) => -50.0f; should be +50.0f.
This is because the wrong variable is returned.
The bug was not detected by the test case "testMinMaxFloat()" because that has a bug too - it tests doubles, not floats.
| 3,481 | 3,483 |
Math-60
|
public double cumulativeProbability(double x) throws MathException {
final double dev = x - mean;
try {
return 0.5 * (1.0 + Erf.erf((dev) /
(standardDeviation * FastMath.sqrt(2.0))));
} catch (MaxIterationsExceededException ex) {
if (x < (mean - 20 * standardDeviation)) { // JDK 1.5 blows at 38
return 0;
} else if (x > (mean + 20 * standardDeviation)) {
return 1;
} else {
throw ex;
}
}
}
|
public double cumulativeProbability(double x) throws MathException {
final double dev = x - mean;
if (FastMath.abs(dev) > 40 * standardDeviation) {
return dev < 0 ? 0.0d : 1.0d;
}
return 0.5 * (1.0 + Erf.erf((dev) /
(standardDeviation * FastMath.sqrt(2.0))));
}
|
src/main/java/org/apache/commons/math/distribution/NormalDistributionImpl.java
|
ConvergenceException in NormalDistributionImpl.cumulativeProbability()
|
I get a ConvergenceException in NormalDistributionImpl.cumulativeProbability() for very large/small parameters including Infinity, -Infinity.
For instance in the following code:
@Test
public void testCumulative() {
final NormalDistribution nd = new NormalDistributionImpl();
for (int i = 0; i < 500; i++) {
final double val = Math.exp;
try
{
System.out.println("val = " + val + " cumulative = " + nd.cumulativeProbability(val));
}
catch (MathException e)
{
e.printStackTrace();
fail();
}
}
}
In version 2.0, I get no exception.
My suggestion is to change in the implementation of cumulativeProbability(double) to catch all ConvergenceException (and return for very large and very small values), not just MaxIterationsExceededException.
| 124 | 138 |
Math-61
|
public PoissonDistributionImpl(double p, double epsilon, int maxIterations) {
if (p <= 0) {
throw MathRuntimeException.createIllegalArgumentException(LocalizedFormats.NOT_POSITIVE_POISSON_MEAN, p);
}
mean = p;
normal = new NormalDistributionImpl(p, FastMath.sqrt(p));
this.epsilon = epsilon;
this.maxIterations = maxIterations;
}
|
public PoissonDistributionImpl(double p, double epsilon, int maxIterations) {
if (p <= 0) {
throw new NotStrictlyPositiveException(LocalizedFormats.MEAN, p);
}
mean = p;
normal = new NormalDistributionImpl(p, FastMath.sqrt(p));
this.epsilon = epsilon;
this.maxIterations = maxIterations;
}
|
src/main/java/org/apache/commons/math/distribution/PoissonDistributionImpl.java
|
Dangerous code in "PoissonDistributionImpl"
|
In the following excerpt from class "PoissonDistributionImpl":
{code:title=PoissonDistributionImpl.java|borderStyle=solid}
public PoissonDistributionImpl(double p, NormalDistribution z) {
super();
setNormal(z);
setMean(p);
}
{code}
(1) Overridable methods are called within the constructor.
(2) The reference "z" is stored and modified within the class.
I've encountered problem (1) in several classes while working on issue 348. In those cases, in order to remove potential problems, I copied/pasted the body of the "setter" methods inside the constructor but I think that a more elegant solution would be to remove the "setters" altogether (i.e. make the classes immutable).
Problem (2) can also create unexpected behaviour. Is it really necessary to pass the "NormalDistribution" object; can't it be always created within the class?
| 92 | 100 |
Math-63
|
public static boolean equals(double x, double y) {
return (Double.isNaN(x) && Double.isNaN(y)) || x == y;
}
|
public static boolean equals(double x, double y) {
return equals(x, y, 1);
}
|
src/main/java/org/apache/commons/math/util/MathUtils.java
|
NaN in "equals" methods
|
In "MathUtils", some "equals" methods will return true if both argument are NaN.
Unless I'm mistaken, this contradicts the IEEE standard.
If nobody objects, I'm going to make the changes.
| 416 | 418 |
Math-69
|
public RealMatrix getCorrelationPValues() throws MathException {
TDistribution tDistribution = new TDistributionImpl(nObs - 2);
int nVars = correlationMatrix.getColumnDimension();
double[][] out = new double[nVars][nVars];
for (int i = 0; i < nVars; i++) {
for (int j = 0; j < nVars; j++) {
if (i == j) {
out[i][j] = 0d;
} else {
double r = correlationMatrix.getEntry(i, j);
double t = Math.abs(r * Math.sqrt((nObs - 2)/(1 - r * r)));
out[i][j] = 2 * (1 - tDistribution.cumulativeProbability(t));
}
}
}
return new BlockRealMatrix(out);
}
|
public RealMatrix getCorrelationPValues() throws MathException {
TDistribution tDistribution = new TDistributionImpl(nObs - 2);
int nVars = correlationMatrix.getColumnDimension();
double[][] out = new double[nVars][nVars];
for (int i = 0; i < nVars; i++) {
for (int j = 0; j < nVars; j++) {
if (i == j) {
out[i][j] = 0d;
} else {
double r = correlationMatrix.getEntry(i, j);
double t = Math.abs(r * Math.sqrt((nObs - 2)/(1 - r * r)));
out[i][j] = 2 * tDistribution.cumulativeProbability(-t);
}
}
}
return new BlockRealMatrix(out);
}
|
src/main/java/org/apache/commons/math/stat/correlation/PearsonsCorrelation.java
|
PearsonsCorrelation.getCorrelationPValues() precision limited by machine epsilon
|
Similar to the issue described in MATH-201, using PearsonsCorrelation.getCorrelationPValues() with many treatments results in p-values that are continuous down to 2.2e-16 but that drop to 0 after that.
In MATH-201, the problem was described as such:
> So in essence, the p-value returned by TTestImpl.tTest() is:
>
> 1.0 - (cumulativeProbability(t) - cumulativeProbabily(-t))
>
> For large-ish t-statistics, cumulativeProbabilty(-t) can get quite small, and cumulativeProbabilty(t) can get very close to 1.0. When
> cumulativeProbability(-t) is less than the machine epsilon, we get p-values equal to zero because:
>
> 1.0 - 1.0 + 0.0 = 0.0
The solution in MATH-201 was to modify the p-value calculation to this:
> p = 2.0 * cumulativeProbability(-t)
Here, the problem is similar. From PearsonsCorrelation.getCorrelationPValues():
p = 2 * (1 - tDistribution.cumulativeProbability(t));
Directly calculating the p-value using identical code as PearsonsCorrelation.getCorrelationPValues(), but with the following change seems to solve the problem:
p = 2 * (tDistribution.cumulativeProbability(-t));
| 160 | 176 |
Math-70
|
public double solve(final UnivariateRealFunction f, double min, double max, double initial)
throws MaxIterationsExceededException, FunctionEvaluationException {
return solve(min, max);
}
|
public double solve(final UnivariateRealFunction f, double min, double max, double initial)
throws MaxIterationsExceededException, FunctionEvaluationException {
return solve(f, min, max);
}
|
src/main/java/org/apache/commons/math/analysis/solvers/BisectionSolver.java
|
BisectionSolver.solve(final UnivariateRealFunction f, double min, double max, double initial) throws NullPointerException
|
Method
BisectionSolver.solve(final UnivariateRealFunction f, double min, double max, double initial)
invokes
BisectionSolver.solve(double min, double max)
which throws NullPointerException, as member variable
UnivariateRealSolverImpl.f
is null.
Instead the method:
BisectionSolver.solve(final UnivariateRealFunction f, double min, double max)
should be called.
Steps to reproduce:
invoke:
new BisectionSolver().solve(someUnivariateFunctionImpl, 0.0, 1.0, 0.5);
NullPointerException will be thrown.
| 70 | 73 |
Math-72
|
public double solve(final UnivariateRealFunction f,
final double min, final double max, final double initial)
throws MaxIterationsExceededException, FunctionEvaluationException {
clearResult();
verifySequence(min, initial, max);
// return the initial guess if it is good enough
double yInitial = f.value(initial);
if (Math.abs(yInitial) <= functionValueAccuracy) {
setResult(initial, 0);
return result;
}
// return the first endpoint if it is good enough
double yMin = f.value(min);
if (Math.abs(yMin) <= functionValueAccuracy) {
setResult(yMin, 0);
return result;
}
// reduce interval if min and initial bracket the root
if (yInitial * yMin < 0) {
return solve(f, min, yMin, initial, yInitial, min, yMin);
}
// return the second endpoint if it is good enough
double yMax = f.value(max);
if (Math.abs(yMax) <= functionValueAccuracy) {
setResult(yMax, 0);
return result;
}
// reduce interval if initial and max bracket the root
if (yInitial * yMax < 0) {
return solve(f, initial, yInitial, max, yMax, initial, yInitial);
}
if (yMin * yMax > 0) {
throw MathRuntimeException.createIllegalArgumentException(
NON_BRACKETING_MESSAGE, min, max, yMin, yMax);
}
// full Brent algorithm starting with provided initial guess
return solve(f, min, yMin, max, yMax, initial, yInitial);
}
|
public double solve(final UnivariateRealFunction f,
final double min, final double max, final double initial)
throws MaxIterationsExceededException, FunctionEvaluationException {
clearResult();
verifySequence(min, initial, max);
// return the initial guess if it is good enough
double yInitial = f.value(initial);
if (Math.abs(yInitial) <= functionValueAccuracy) {
setResult(initial, 0);
return result;
}
// return the first endpoint if it is good enough
double yMin = f.value(min);
if (Math.abs(yMin) <= functionValueAccuracy) {
setResult(min, 0);
return result;
}
// reduce interval if min and initial bracket the root
if (yInitial * yMin < 0) {
return solve(f, min, yMin, initial, yInitial, min, yMin);
}
// return the second endpoint if it is good enough
double yMax = f.value(max);
if (Math.abs(yMax) <= functionValueAccuracy) {
setResult(max, 0);
return result;
}
// reduce interval if initial and max bracket the root
if (yInitial * yMax < 0) {
return solve(f, initial, yInitial, max, yMax, initial, yInitial);
}
if (yMin * yMax > 0) {
throw MathRuntimeException.createIllegalArgumentException(
NON_BRACKETING_MESSAGE, min, max, yMin, yMax);
}
// full Brent algorithm starting with provided initial guess
return solve(f, min, yMin, max, yMax, initial, yInitial);
}
|
src/main/java/org/apache/commons/math/analysis/solvers/BrentSolver.java
|
Brent solver returns the wrong value if either bracket endpoint is root
|
The solve(final UnivariateRealFunction f, final double min, final double max, final double initial) function returns yMin or yMax if min or max are deemed to be roots, respectively, instead of min or max.
| 98 | 144 |
Math-73
|
public double solve(final UnivariateRealFunction f,
final double min, final double max, final double initial)
throws MaxIterationsExceededException, FunctionEvaluationException {
clearResult();
verifySequence(min, initial, max);
// return the initial guess if it is good enough
double yInitial = f.value(initial);
if (Math.abs(yInitial) <= functionValueAccuracy) {
setResult(initial, 0);
return result;
}
// return the first endpoint if it is good enough
double yMin = f.value(min);
if (Math.abs(yMin) <= functionValueAccuracy) {
setResult(yMin, 0);
return result;
}
// reduce interval if min and initial bracket the root
if (yInitial * yMin < 0) {
return solve(f, min, yMin, initial, yInitial, min, yMin);
}
// return the second endpoint if it is good enough
double yMax = f.value(max);
if (Math.abs(yMax) <= functionValueAccuracy) {
setResult(yMax, 0);
return result;
}
// reduce interval if initial and max bracket the root
if (yInitial * yMax < 0) {
return solve(f, initial, yInitial, max, yMax, initial, yInitial);
}
// full Brent algorithm starting with provided initial guess
return solve(f, min, yMin, max, yMax, initial, yInitial);
}
|
public double solve(final UnivariateRealFunction f,
final double min, final double max, final double initial)
throws MaxIterationsExceededException, FunctionEvaluationException {
clearResult();
verifySequence(min, initial, max);
// return the initial guess if it is good enough
double yInitial = f.value(initial);
if (Math.abs(yInitial) <= functionValueAccuracy) {
setResult(initial, 0);
return result;
}
// return the first endpoint if it is good enough
double yMin = f.value(min);
if (Math.abs(yMin) <= functionValueAccuracy) {
setResult(yMin, 0);
return result;
}
// reduce interval if min and initial bracket the root
if (yInitial * yMin < 0) {
return solve(f, min, yMin, initial, yInitial, min, yMin);
}
// return the second endpoint if it is good enough
double yMax = f.value(max);
if (Math.abs(yMax) <= functionValueAccuracy) {
setResult(yMax, 0);
return result;
}
// reduce interval if initial and max bracket the root
if (yInitial * yMax < 0) {
return solve(f, initial, yInitial, max, yMax, initial, yInitial);
}
if (yMin * yMax > 0) {
throw MathRuntimeException.createIllegalArgumentException(
NON_BRACKETING_MESSAGE, min, max, yMin, yMax);
}
// full Brent algorithm starting with provided initial guess
return solve(f, min, yMin, max, yMax, initial, yInitial);
}
|
src/main/java/org/apache/commons/math/analysis/solvers/BrentSolver.java
|
Brent solver doesn't throw IllegalArgumentException when initial guess has the wrong sign
|
Javadoc for "public double solve(final UnivariateRealFunction f, final double min, final double max, final double initial)" claims that "if the values of the function at the three points have the same sign" an IllegalArgumentException is thrown. This case isn't even checked.
| 98 | 140 |
Math-75
|
public double getPct(Object v) {
return getCumPct((Comparable<?>) v);
}
|
public double getPct(Object v) {
return getPct((Comparable<?>) v);
}
|
src/main/java/org/apache/commons/math/stat/Frequency.java
|
In stat.Frequency, getPct(Object) uses getCumPct(Comparable) instead of getPct(Comparable)
|
Drop in Replacement of 1.2 with 2.0 not possible because all getPct calls will be cummulative without code change
Frequency.java
/**
Returns the percentage of values that are equal to v
@deprecated replaced by
{@link #getPct(Comparable)}
as of 2.0
*/
@Deprecated
public double getPct(Object v)
{
return getCumPct((Comparable<?>) v);
}
| 302 | 304 |
Math-79
|
public static double distance(int[] p1, int[] p2) {
int sum = 0;
for (int i = 0; i < p1.length; i++) {
final int dp = p1[i] - p2[i];
sum += dp * dp;
}
return Math.sqrt(sum);
}
|
public static double distance(int[] p1, int[] p2) {
double sum = 0;
for (int i = 0; i < p1.length; i++) {
final double dp = p1[i] - p2[i];
sum += dp * dp;
}
return Math.sqrt(sum);
}
|
src/main/java/org/apache/commons/math/util/MathUtils.java
|
NPE in KMeansPlusPlusClusterer unittest
|
When running this unittest, I am facing this NPE:
java.lang.NullPointerException
at org.apache.commons.math.stat.clustering.KMeansPlusPlusClusterer.assignPointsToClusters(KMeansPlusPlusClusterer.java:91)
This is the unittest:
package org.fao.fisheries.chronicles.calcuation.cluster;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.apache.commons.math.stat.clustering.Cluster;
import org.apache.commons.math.stat.clustering.EuclideanIntegerPoint;
import org.apache.commons.math.stat.clustering.KMeansPlusPlusClusterer;
import org.fao.fisheries.chronicles.input.CsvImportProcess;
import org.fao.fisheries.chronicles.input.Top200Csv;
import org.junit.Test;
public class ClusterAnalysisTest {
@Test
public void testPerformClusterAnalysis2() {
KMeansPlusPlusClusterer<EuclideanIntegerPoint> transformer = new KMeansPlusPlusClusterer<EuclideanIntegerPoint>(
new Random(1746432956321l));
EuclideanIntegerPoint[] points = new EuclideanIntegerPoint[] {
new EuclideanIntegerPoint(new int[]
{ 1959, 325100 }
),
new EuclideanIntegerPoint(new int[]
{ 1960, 373200 }
), };
List<Cluster<EuclideanIntegerPoint>> clusters = transformer.cluster(Arrays.asList(points), 1, 1);
assertEquals(1, clusters.size());
}
}
| 1,623 | 1,630 |
Math-8
|
public T[] sample(int sampleSize) throws NotStrictlyPositiveException {
if (sampleSize <= 0) {
throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES,
sampleSize);
}
final T[]out = (T[]) java.lang.reflect.Array.newInstance(singletons.get(0).getClass(), sampleSize);
for (int i = 0; i < sampleSize; i++) {
out[i] = sample();
}
return out;
}
|
public Object[] sample(int sampleSize) throws NotStrictlyPositiveException {
if (sampleSize <= 0) {
throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES,
sampleSize);
}
final Object[] out = new Object[sampleSize];
for (int i = 0; i < sampleSize; i++) {
out[i] = sample();
}
return out;
}
|
src/main/java/org/apache/commons/math3/distribution/DiscreteDistribution.java
|
DiscreteDistribution.sample(int) may throw an exception if first element of singletons of sub-class type
|
Creating an array with Array.newInstance(singletons.get(0).getClass(), sampleSize) in DiscreteDistribution.sample(int) is risky. An exception will be thrown if:
singleons.get(0) is of type T1, an sub-class of T, and
DiscreteDistribution.sample() returns an object which is of type T, but not of type T1.
To reproduce:
List<Pair<Object,Double>> list = new ArrayList<Pair<Object, Double>>();
list.add(new Pair<Object, Double>(new Object() {}, new Double(0)));
list.add(new Pair<Object, Double>(new Object() {}, new Double(1)));
new DiscreteDistribution<Object>(list).sample(1);
Attaching a patch.
| 181 | 195 |
Math-82
|
private Integer getPivotRow(final int col, final SimplexTableau tableau) {
double minRatio = Double.MAX_VALUE;
Integer minRatioPos = null;
for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
final double entry = tableau.getEntry(i, col);
if (MathUtils.compareTo(entry, 0, epsilon) >= 0) {
final double ratio = rhs / entry;
if (ratio < minRatio) {
minRatio = ratio;
minRatioPos = i;
}
}
}
return minRatioPos;
}
|
private Integer getPivotRow(final int col, final SimplexTableau tableau) {
double minRatio = Double.MAX_VALUE;
Integer minRatioPos = null;
for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
final double entry = tableau.getEntry(i, col);
if (MathUtils.compareTo(entry, 0, epsilon) > 0) {
final double ratio = rhs / entry;
if (ratio < minRatio) {
minRatio = ratio;
minRatioPos = i;
}
}
}
return minRatioPos;
}
|
src/main/java/org/apache/commons/math/optimization/linear/SimplexSolver.java
|
SimplexSolver not working as expected 2
|
SimplexSolver didn't find the optimal solution.
Program for Lpsolve:
=====================
/* Objective function */
max: 7 a 3 b;
/* Constraints */
R1: +3 a -5 c <= 0;
R2: +2 a -5 d <= 0;
R3: +2 b -5 c <= 0;
R4: +3 b -5 d <= 0;
R5: +3 a +2 b <= 5;
R6: +2 a +3 b <= 5;
/* Variable bounds */
a <= 1;
b <= 1;
=====================
Results(correct): a = 1, b = 1, value = 10
Program for SimplexSolve:
=====================
LinearObjectiveFunction kritFcia = new LinearObjectiveFunction(new double[]
{7, 3, 0, 0}
, 0);
Collection<LinearConstraint> podmienky = new ArrayList<LinearConstraint>();
podmienky.add(new LinearConstraint(new double[]
{1, 0, 0, 0}
, Relationship.LEQ, 1));
podmienky.add(new LinearConstraint(new double[]
{0, 1, 0, 0}
, Relationship.LEQ, 1));
podmienky.add(new LinearConstraint(new double[]
{3, 0, -5, 0}
, Relationship.LEQ, 0));
podmienky.add(new LinearConstraint(new double[]
{2, 0, 0, -5}
, Relationship.LEQ, 0));
podmienky.add(new LinearConstraint(new double[]
{0, 2, -5, 0}
, Relationship.LEQ, 0));
podmienky.add(new LinearConstraint(new double[]
{0, 3, 0, -5}
, Relationship.LEQ, 0));
podmienky.add(new LinearConstraint(new double[]
{3, 2, 0, 0}
, Relationship.LEQ, 5));
podmienky.add(new LinearConstraint(new double[]
{2, 3, 0, 0}
, Relationship.LEQ, 5));
SimplexSolver solver = new SimplexSolver();
RealPointValuePair result = solver.optimize(kritFcia, podmienky, GoalType.MAXIMIZE, true);
=====================
Results(incorrect): a = 1, b = 0.5, value = 8.5
P.S. I used the latest software from the repository (including MATH-286 fix).
| 76 | 91 |
Math-84
|
protected void iterateSimplex(final Comparator<RealPointValuePair> comparator)
throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {
while (true) {
incrementIterationsCounter();
// save the original vertex
final RealPointValuePair[] original = simplex;
final RealPointValuePair best = original[0];
// perform a reflection step
final RealPointValuePair reflected = evaluateNewSimplex(original, 1.0, comparator);
if (comparator.compare(reflected, best) < 0) {
// compute the expanded simplex
final RealPointValuePair[] reflectedSimplex = simplex;
final RealPointValuePair expanded = evaluateNewSimplex(original, khi, comparator);
if (comparator.compare(reflected, expanded) <= 0) {
// accept the reflected simplex
simplex = reflectedSimplex;
}
return;
}
// compute the contracted simplex
final RealPointValuePair contracted = evaluateNewSimplex(original, gamma, comparator);
if (comparator.compare(contracted, best) < 0) {
// accept the contracted simplex
// check convergence
return;
}
}
}
|
protected void iterateSimplex(final Comparator<RealPointValuePair> comparator)
throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {
final RealConvergenceChecker checker = getConvergenceChecker();
while (true) {
incrementIterationsCounter();
// save the original vertex
final RealPointValuePair[] original = simplex;
final RealPointValuePair best = original[0];
// perform a reflection step
final RealPointValuePair reflected = evaluateNewSimplex(original, 1.0, comparator);
if (comparator.compare(reflected, best) < 0) {
// compute the expanded simplex
final RealPointValuePair[] reflectedSimplex = simplex;
final RealPointValuePair expanded = evaluateNewSimplex(original, khi, comparator);
if (comparator.compare(reflected, expanded) <= 0) {
// accept the reflected simplex
simplex = reflectedSimplex;
}
return;
}
// compute the contracted simplex
final RealPointValuePair contracted = evaluateNewSimplex(original, gamma, comparator);
if (comparator.compare(contracted, best) < 0) {
// accept the contracted simplex
return;
}
// check convergence
final int iter = getIterations();
boolean converged = true;
for (int i = 0; i < simplex.length; ++i) {
converged &= checker.converged(iter, original[i], simplex[i]);
}
if (converged) {
return;
}
}
}
|
src/main/java/org/apache/commons/math/optimization/direct/MultiDirectional.java
|
MultiDirectional optimzation loops forver if started at the correct solution
|
MultiDirectional.iterateSimplex loops forever if the starting point is the correct solution.
see the attached test case (testMultiDirectionalCorrectStart) as an example.
| 61 | 99 |
Math-87
|
private Integer getBasicRow(final int col) {
Integer row = null;
for (int i = getNumObjectiveFunctions(); i < getHeight(); i++) {
if (!MathUtils.equals(getEntry(i, col), 0.0, epsilon)) {
if (row == null) {
row = i;
} else {
return null;
}
}
}
return row;
}
|
private Integer getBasicRow(final int col) {
Integer row = null;
for (int i = getNumObjectiveFunctions(); i < getHeight(); i++) {
if (MathUtils.equals(getEntry(i, col), 1.0, epsilon) && (row == null)) {
row = i;
} else if (!MathUtils.equals(getEntry(i, col), 0.0, epsilon)) {
return null;
}
}
return row;
}
|
src/java/org/apache/commons/math/optimization/linear/SimplexTableau.java
|
Basic variable is not found correctly in simplex tableau
|
The last patch to SimplexTableau caused an automated test suite I'm running at work to go down a new code path and uncover what is hopefully the last bug remaining in the Simplex code.
SimplexTableau was assuming an entry in the tableau had to be nonzero to indicate a basic variable, which is incorrect - the entry should have a value equal to 1.
| 272 | 284 |
Math-88
|
protected RealPointValuePair getSolution() {
double[] coefficients = new double[getOriginalNumDecisionVariables()];
Integer basicRow =
getBasicRow(getNumObjectiveFunctions() + getOriginalNumDecisionVariables());
double mostNegative = basicRow == null ? 0 : getEntry(basicRow, getRhsOffset());
for (int i = 0; i < coefficients.length; i++) {
basicRow = getBasicRow(getNumObjectiveFunctions() + i);
// if multiple variables can take a given value
// then we choose the first and set the rest equal to 0
coefficients[i] =
(basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) -
(restrictToNonNegative ? 0 : mostNegative);
if (basicRow != null) {
for (int j = getNumObjectiveFunctions(); j < getNumObjectiveFunctions() + i; j++) {
if (tableau.getEntry(basicRow, j) == 1) {
coefficients[i] = 0;
}
}
}
}
return new RealPointValuePair(coefficients, f.getValue(coefficients));
}
|
protected RealPointValuePair getSolution() {
double[] coefficients = new double[getOriginalNumDecisionVariables()];
Integer basicRow =
getBasicRow(getNumObjectiveFunctions() + getOriginalNumDecisionVariables());
double mostNegative = basicRow == null ? 0 : getEntry(basicRow, getRhsOffset());
Set<Integer> basicRows = new HashSet<Integer>();
for (int i = 0; i < coefficients.length; i++) {
basicRow = getBasicRow(getNumObjectiveFunctions() + i);
if (basicRows.contains(basicRow)) {
// if multiple variables can take a given value
// then we choose the first and set the rest equal to 0
coefficients[i] = 0;
} else {
basicRows.add(basicRow);
coefficients[i] =
(basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) -
(restrictToNonNegative ? 0 : mostNegative);
}
}
return new RealPointValuePair(coefficients, f.getValue(coefficients));
}
|
src/java/org/apache/commons/math/optimization/linear/SimplexTableau.java
|
Simplex Solver arrives at incorrect solution
|
I have reduced the problem reported to me down to a minimal test case which I will attach.
| 324 | 345 |
Math-89
|
public void addValue(Object v) {
addValue((Comparable<?>) v);
}
|
public void addValue(Object v) {
if (v instanceof Comparable<?>){
addValue((Comparable<?>) v);
} else {
throw new IllegalArgumentException("Object must implement Comparable");
}
}
|
src/java/org/apache/commons/math/stat/Frequency.java
|
Bugs in Frequency API
|
I think the existing Frequency API has some bugs in it.
The addValue(Object v) method allows one to add a plain Object, but one cannot add anything further to the instance, as the second add fails with IllegalArgumentException.
In fact, the problem is with the first call to addValue(Object) which should not allow a plain Object to be added - it should only allow Comparable objects.
This could be fixed by checking that the object is Comparable.
Similar considerations apply to the getCumFreq(Object) and getCumPct(Object) methods - they will only work with objects that implement Comparable.
The getCount(Object) and getPct(Object) methods don't fail when given a non-Comparable object (because the class cast exception is caught), however they just return 0 as if the object was not present:
final Object OBJ = new Object();
f.addValue(OBJ); // This ought to fail, but doesn't, causing the unexpected behaviour below
System.out.println(f.getCount(OBJ)); // 0
System.out.println(f.getPct(OBJ)); // 0.0
Rather than adding extra checks for Comparable, it seems to me that the API would be much improved by using Comparable instead of Object.
Also, it should make it easier to implement generics.
However, this would cause compilation failures for some programs that pass Object rather than Comparable to the class.
These would need recoding, but I think they would continue to run OK against the new API.
It would also affect the run-time behaviour slightly, as the first attempt to add a non-Comparable object would fail, rather than the second add of a possibly valid object.
But is that a viable program? It can only add one object, and any attempt to get statistics will either return 0 or an Exception, and applying the instanceof fix would also cause it to fail.
| 109 | 111 |
Math-9
|
public Line revert() {
final Line reverted = new Line(zero, zero.subtract(direction));
return reverted;
}
|
public Line revert() {
final Line reverted = new Line(this);
reverted.direction = reverted.direction.negate();
return reverted;
}
|
src/main/java/org/apache/commons/math3/geometry/euclidean/threed/Line.java
|
Line.revert() is imprecise
|
Line.revert() only maintains ~10 digits for the direction. This becomes an issue when the line's position is evaluated far from the origin. A simple fix would be to use Vector3D.negate() for the direction.
Also, is there a reason why Line is not immutable? It is just comprised of two vectors.
| 86 | 89 |
Math-90
|
public void addValue(Object v) {
/**
* Adds 1 to the frequency count for v.
* <p>
* If other objects have already been added to this Frequency, v must
* be comparable to those that have already been added.
* </p>
*
* @param v the value to add.
* @throws IllegalArgumentException if <code>v</code> is not comparable with previous entries
*/
Object obj = v;
if (v instanceof Integer) {
obj = Long.valueOf(((Integer) v).longValue());
}
try {
Long count = (Long) freqTable.get(obj);
if (count == null) {
freqTable.put(obj, Long.valueOf(1));
} else {
freqTable.put(obj, Long.valueOf(count.longValue() + 1));
}
} catch (ClassCastException ex) {
//TreeMap will throw ClassCastException if v is not comparable
throw new IllegalArgumentException("Value not comparable to existing values.");
}
}
|
public void addValue(Object v) {
addValue((Comparable<?>) v);
}
|
src/java/org/apache/commons/math/stat/Frequency.java
|
Bugs in Frequency API
|
I think the existing Frequency API has some bugs in it.
The addValue(Object v) method allows one to add a plain Object, but one cannot add anything further to the instance, as the second add fails with IllegalArgumentException.
In fact, the problem is with the first call to addValue(Object) which should not allow a plain Object to be added - it should only allow Comparable objects.
This could be fixed by checking that the object is Comparable.
Similar considerations apply to the getCumFreq(Object) and getCumPct(Object) methods - they will only work with objects that implement Comparable.
The getCount(Object) and getPct(Object) methods don't fail when given a non-Comparable object (because the class cast exception is caught), however they just return 0 as if the object was not present:
final Object OBJ = new Object();
f.addValue(OBJ); // This ought to fail, but doesn't, causing the unexpected behaviour below
System.out.println(f.getCount(OBJ)); // 0
System.out.println(f.getPct(OBJ)); // 0.0
Rather than adding extra checks for Comparable, it seems to me that the API would be much improved by using Comparable instead of Object.
Also, it should make it easier to implement generics.
However, this would cause compilation failures for some programs that pass Object rather than Comparable to the class.
These would need recoding, but I think they would continue to run OK against the new API.
It would also affect the run-time behaviour slightly, as the first attempt to add a non-Comparable object would fail, rather than the second add of a possibly valid object.
But is that a viable program? It can only add one object, and any attempt to get statistics will either return 0 or an Exception, and applying the instanceof fix would also cause it to fail.
| 109 | 136 |
Math-91
|
public int compareTo(Fraction object) {
double nOd = doubleValue();
double dOn = object.doubleValue();
return (nOd < dOn) ? -1 : ((nOd > dOn) ? +1 : 0);
}
|
public int compareTo(Fraction object) {
long nOd = ((long) numerator) * object.denominator;
long dOn = ((long) denominator) * object.numerator;
return (nOd < dOn) ? -1 : ((nOd > dOn) ? +1 : 0);
}
|
src/java/org/apache/commons/math/fraction/Fraction.java
|
Fraction.comparTo returns 0 for some differente fractions
|
If two different fractions evaluate to the same double due to limited precision,
the compareTo methode returns 0 as if they were identical.
// value is roughly PI - 3.07e-18
Fraction pi1 = new Fraction(1068966896, 340262731);
// value is roughly PI + 1.936e-17
Fraction pi2 = new Fraction( 411557987, 131002976);
System.out.println(pi1.doubleValue() - pi2.doubleValue()); // exactly 0.0 due to limited IEEE754 precision
System.out.println(pi1.compareTo(pi2)); // display 0 instead of a negative value
| 258 | 262 |
Math-94
|
public static int gcd(int u, int v) {
if (u * v == 0) {
return (Math.abs(u) + Math.abs(v));
}
// keep u and v negative, as negative integers range down to
// -2^31, while positive numbers can only be as large as 2^31-1
// (i.e. we can't necessarily negate a negative number without
// overflow)
/* assert u!=0 && v!=0; */
if (u > 0) {
u = -u;
} // make u negative
if (v > 0) {
v = -v;
} // make v negative
// B1. [Find power of 2]
int k = 0;
while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { // while u and v are
// both even...
u /= 2;
v /= 2;
k++; // cast out twos.
}
if (k == 31) {
throw new ArithmeticException("overflow: gcd is 2^31");
}
// B2. Initialize: u and v have been divided by 2^k and at least
// one is odd.
int t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */;
// t negative: u was odd, v may be even (t replaces v)
// t positive: u was even, v is odd (t replaces u)
do {
/* assert u<0 && v<0; */
// B4/B3: cast out twos from t.
while ((t & 1) == 0) { // while t is even..
t /= 2; // cast out twos
}
// B5 [reset max(u,v)]
if (t > 0) {
u = -t;
} else {
v = t;
}
// B6/B3. at this point both u and v should be odd.
t = (v - u) / 2;
// |u| larger: t positive (replace u)
// |v| larger: t negative (replace v)
} while (t != 0);
return -u * (1 << k); // gcd is u*2^k
}
|
public static int gcd(int u, int v) {
if ((u == 0) || (v == 0)) {
return (Math.abs(u) + Math.abs(v));
}
// keep u and v negative, as negative integers range down to
// -2^31, while positive numbers can only be as large as 2^31-1
// (i.e. we can't necessarily negate a negative number without
// overflow)
/* assert u!=0 && v!=0; */
if (u > 0) {
u = -u;
} // make u negative
if (v > 0) {
v = -v;
} // make v negative
// B1. [Find power of 2]
int k = 0;
while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { // while u and v are
// both even...
u /= 2;
v /= 2;
k++; // cast out twos.
}
if (k == 31) {
throw new ArithmeticException("overflow: gcd is 2^31");
}
// B2. Initialize: u and v have been divided by 2^k and at least
// one is odd.
int t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */;
// t negative: u was odd, v may be even (t replaces v)
// t positive: u was even, v is odd (t replaces u)
do {
/* assert u<0 && v<0; */
// B4/B3: cast out twos from t.
while ((t & 1) == 0) { // while t is even..
t /= 2; // cast out twos
}
// B5 [reset max(u,v)]
if (t > 0) {
u = -t;
} else {
v = t;
}
// B6/B3. at this point both u and v should be odd.
t = (v - u) / 2;
// |u| larger: t positive (replace u)
// |v| larger: t negative (replace v)
} while (t != 0);
return -u * (1 << k); // gcd is u*2^k
}
|
src/java/org/apache/commons/math/util/MathUtils.java
|
MathUtils.gcd(u, v) fails when u and v both contain a high power of 2
|
The test at the beginning of MathUtils.gcd(u, v) for arguments equal to zero fails when u and v contain high enough powers of 2 so that their product overflows to zero.
assertEquals(3 * (1<<15), MathUtils.gcd(3 * (1<<20), 9 * (1<<15)));
Fix: Replace the test at the start of MathUtils.gcd()
if (u * v == 0) {
by
if (u == 0 || v == 0) {
| 411 | 460 |
Math-95
|
protected double getInitialDomain(double p) {
double ret;
double d = getDenominatorDegreesOfFreedom();
// use mean
ret = d / (d - 2.0);
return ret;
}
|
protected double getInitialDomain(double p) {
double ret = 1.0;
double d = getDenominatorDegreesOfFreedom();
if (d > 2.0) {
// use mean
ret = d / (d - 2.0);
}
return ret;
}
|
src/java/org/apache/commons/math/distribution/FDistributionImpl.java
|
denominatorDegreeOfFreedom in FDistribution leads to IllegalArgumentsException in UnivariateRealSolverUtils.bracket
|
We are using the FDistributionImpl from the commons.math project to do
some statistical calculations, namely receiving the upper and lower
boundaries of a confidence interval. Everything is working fine and the
results are matching our reference calculations.
However, the FDistribution behaves strange if a
denominatorDegreeOfFreedom of 2 is used, with an alpha-value of 0.95.
This results in an IllegalArgumentsException, stating:
Invalid endpoint parameters: lowerBound=0.0 initial=Infinity
upperBound=1.7976931348623157E308
coming from
org.apache.commons.math.analysis.UnivariateRealSolverUtils.bracket
The problem is the 'initial' parameter to that function, wich is
POSITIVE_INFINITY and therefore not within the boundaries. I already
pinned down the problem to the FDistributions getInitialDomain()-method,
wich goes like:
return getDenominatorDegreesOfFreedom() /
(getDenominatorDegreesOfFreedom() - 2.0);
Obviously, in case of denominatorDegreesOfFreedom == 2, this must lead
to a division-by-zero, resulting in POSTIVE_INFINITY. The result of this
operation is then directly passed into the
UnivariateRealSolverUtils.bracket() - method as second argument.
| 143 | 149 |
Math-97
|
public double solve(double min, double max) throws MaxIterationsExceededException,
FunctionEvaluationException {
clearResult();
verifyInterval(min, max);
double ret = Double.NaN;
double yMin = f.value(min);
double yMax = f.value(max);
// Verify bracketing
double sign = yMin * yMax;
if (sign >= 0) {
// check if either value is close to a zero
// neither value is close to zero and min and max do not bracket root.
throw new IllegalArgumentException
("Function values at endpoints do not have different signs." +
" Endpoints: [" + min + "," + max + "]" +
" Values: [" + yMin + "," + yMax + "]");
} else {
// solve using only the first endpoint as initial guess
ret = solve(min, yMin, max, yMax, min, yMin);
// either min or max is a root
}
return ret;
}
|
public double solve(double min, double max) throws MaxIterationsExceededException,
FunctionEvaluationException {
clearResult();
verifyInterval(min, max);
double ret = Double.NaN;
double yMin = f.value(min);
double yMax = f.value(max);
// Verify bracketing
double sign = yMin * yMax;
if (sign > 0) {
// check if either value is close to a zero
if (Math.abs(yMin) <= functionValueAccuracy) {
setResult(min, 0);
ret = min;
} else if (Math.abs(yMax) <= functionValueAccuracy) {
setResult(max, 0);
ret = max;
} else {
// neither value is close to zero and min and max do not bracket root.
throw new IllegalArgumentException
("Function values at endpoints do not have different signs." +
" Endpoints: [" + min + "," + max + "]" +
" Values: [" + yMin + "," + yMax + "]");
}
} else if (sign < 0){
// solve using only the first endpoint as initial guess
ret = solve(min, yMin, max, yMax, min, yMin);
} else {
// either min or max is a root
if (yMin == 0.0) {
ret = min;
} else {
ret = max;
}
}
return ret;
}
|
src/java/org/apache/commons/math/analysis/BrentSolver.java
|
BrentSolver throws IllegalArgumentException
|
I am getting this exception:
java.lang.IllegalArgumentException: Function values at endpoints do not have different signs. Endpoints: [-100000.0,1.7976931348623157E308] Values: [0.0,-101945.04630982173]
at org.apache.commons.math.analysis.BrentSolver.solve(BrentSolver.java:99)
at org.apache.commons.math.analysis.BrentSolver.solve(BrentSolver.java:62)
The exception should not be thrown with values [0.0,-101945.04630982173] because 0.0 is positive.
According to Brent Worden, the algorithm should stop and return 0 as the root instead of throwing an exception.
The problem comes from this method:
public double solve(double min, double max) throws MaxIterationsExceededException,
FunctionEvaluationException {
clearResult();
verifyInterval(min, max);
double yMin = f.value(min);
double yMax = f.value(max);
// Verify bracketing
if (yMin * yMax >= 0)
{
throw new IllegalArgumentException
("Function values at endpoints do not have different signs." +
" Endpoints: [" + min + "," + max + "]" +
" Values: [" + yMin + "," + yMax + "]");
}
// solve using only the first endpoint as initial guess
return solve(min, yMin, max, yMax, min, yMin);
}
One way to fix it would be to add this code after the assignment of yMin and yMax:
if (yMin ==0 || yMax == 0)
{
return 0;
}
| 125 | 152 |
Mockito-12
|
public Class getGenericType(Field field) {
Type generic = field.getGenericType();
if (generic != null && generic instanceof ParameterizedType) {
Type actual = ((ParameterizedType) generic).getActualTypeArguments()[0];
return (Class) actual;
//in case of nested generics we don't go deep
}
return Object.class;
}
|
public Class getGenericType(Field field) {
Type generic = field.getGenericType();
if (generic != null && generic instanceof ParameterizedType) {
Type actual = ((ParameterizedType) generic).getActualTypeArguments()[0];
if (actual instanceof Class) {
return (Class) actual;
} else if (actual instanceof ParameterizedType) {
//in case of nested generics we don't go deep
return (Class) ((ParameterizedType) actual).getRawType();
}
}
return Object.class;
}
|
src/org/mockito/internal/util/reflection/GenericMaster.java
|
ArgumentCaptor no longer working for varargs
|
I ran into the issue described here: http://stackoverflow.com/questions/27303562/why-does-upgrading-mockito-from-1-9-5-to-1-10-8-break-this-captor
| 16 | 25 |
Mockito-13
|
public Object handle(Invocation invocation) throws Throwable {
if (invocationContainerImpl.hasAnswersForStubbing()) {
// stubbing voids with stubVoid() or doAnswer() style
InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(mockingProgress
.getArgumentMatcherStorage(), invocation);
invocationContainerImpl.setMethodForStubbing(invocationMatcher);
return null;
}
VerificationMode verificationMode = mockingProgress.pullVerificationMode();
InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(mockingProgress.getArgumentMatcherStorage(),
invocation);
mockingProgress.validateState();
//if verificationMode is not null then someone is doing verify()
if (verificationMode != null) {
//We need to check if verification was started on the correct mock
// - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138)
if (verificationMode instanceof MockAwareVerificationMode && ((MockAwareVerificationMode) verificationMode).getMock() == invocation.getMock()) {
VerificationDataImpl data = new VerificationDataImpl(invocationContainerImpl, invocationMatcher);
verificationMode.verify(data);
return null;
// this means there is an invocation on a different mock. Re-adding verification mode
// - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138)
}
}
invocationContainerImpl.setInvocationForPotentialStubbing(invocationMatcher);
OngoingStubbingImpl<T> ongoingStubbing = new OngoingStubbingImpl<T>(invocationContainerImpl);
mockingProgress.reportOngoingStubbing(ongoingStubbing);
StubbedInvocationMatcher stubbedInvocation = invocationContainerImpl.findAnswerFor(invocation);
if (stubbedInvocation != null) {
stubbedInvocation.captureArgumentsFrom(invocation);
return stubbedInvocation.answer(invocation);
} else {
Object ret = mockSettings.getDefaultAnswer().answer(invocation);
// redo setting invocation for potential stubbing in case of partial
// mocks / spies.
// Without it, the real method inside 'when' might have delegated
// to other self method and overwrite the intended stubbed method
// with a different one. The reset is required to avoid runtime exception that validates return type with stubbed method signature.
invocationContainerImpl.resetInvocationForPotentialStubbing(invocationMatcher);
return ret;
}
}
|
public Object handle(Invocation invocation) throws Throwable {
if (invocationContainerImpl.hasAnswersForStubbing()) {
// stubbing voids with stubVoid() or doAnswer() style
InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(mockingProgress
.getArgumentMatcherStorage(), invocation);
invocationContainerImpl.setMethodForStubbing(invocationMatcher);
return null;
}
VerificationMode verificationMode = mockingProgress.pullVerificationMode();
InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(mockingProgress.getArgumentMatcherStorage(),
invocation);
mockingProgress.validateState();
//if verificationMode is not null then someone is doing verify()
if (verificationMode != null) {
//We need to check if verification was started on the correct mock
// - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138)
if (((MockAwareVerificationMode) verificationMode).getMock() == invocation.getMock()) {
VerificationDataImpl data = new VerificationDataImpl(invocationContainerImpl, invocationMatcher);
verificationMode.verify(data);
return null;
} else {
// this means there is an invocation on a different mock. Re-adding verification mode
// - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138)
mockingProgress.verificationStarted(verificationMode);
}
}
invocationContainerImpl.setInvocationForPotentialStubbing(invocationMatcher);
OngoingStubbingImpl<T> ongoingStubbing = new OngoingStubbingImpl<T>(invocationContainerImpl);
mockingProgress.reportOngoingStubbing(ongoingStubbing);
StubbedInvocationMatcher stubbedInvocation = invocationContainerImpl.findAnswerFor(invocation);
if (stubbedInvocation != null) {
stubbedInvocation.captureArgumentsFrom(invocation);
return stubbedInvocation.answer(invocation);
} else {
Object ret = mockSettings.getDefaultAnswer().answer(invocation);
// redo setting invocation for potential stubbing in case of partial
// mocks / spies.
// Without it, the real method inside 'when' might have delegated
// to other self method and overwrite the intended stubbed method
// with a different one. The reset is required to avoid runtime exception that validates return type with stubbed method signature.
invocationContainerImpl.resetInvocationForPotentialStubbing(invocationMatcher);
return ret;
}
}
|
src/org/mockito/internal/MockHandler.java
|
fix proposal for #114
|
@bric3, can you take a look at this one? If you don't have time I'll just merge it. All existing tests are passing.
Thanks for the fix!!!
| 58 | 106 |
Mockito-15
|
public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, final Object fieldInstance) {
if(mocks.size() == 1) {
final Object matchingMock = mocks.iterator().next();
return new OngoingInjecter() {
public boolean thenInject() {
try {
new FieldSetter(fieldInstance, field).set(matchingMock);
} catch (Exception e) {
throw new MockitoException("Problems injecting dependency in " + field.getName(), e);
}
return true;
}
};
}
return new OngoingInjecter() {
public boolean thenInject() {
return false;
}
};
}
|
public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, final Object fieldInstance) {
if(mocks.size() == 1) {
final Object matchingMock = mocks.iterator().next();
return new OngoingInjecter() {
public boolean thenInject() {
try {
if (!new BeanPropertySetter(fieldInstance, field).set(matchingMock)) {
new FieldSetter(fieldInstance, field).set(matchingMock);
}
} catch (Exception e) {
throw new MockitoException("Problems injecting dependency in " + field.getName(), e);
}
return true;
}
};
}
return new OngoingInjecter() {
public boolean thenInject() {
return false;
}
};
}
|
src/org/mockito/internal/configuration/injection/FinalMockCandidateFilter.java
|
ArgumentCaptor no longer working for varargs
|
Fixes #188 . These commits should fix issue with capturing varargs.
| 18 | 40 |
Mockito-18
|
Object returnValueFor(Class<?> type) {
if (Primitives.isPrimitiveOrWrapper(type)) {
return Primitives.defaultValueForPrimitiveOrWrapper(type);
//new instances are used instead of Collections.emptyList(), etc.
//to avoid UnsupportedOperationException if code under test modifies returned collection
} else if (type == Collection.class) {
return new LinkedList<Object>();
} else if (type == Set.class) {
return new HashSet<Object>();
} else if (type == HashSet.class) {
return new HashSet<Object>();
} else if (type == SortedSet.class) {
return new TreeSet<Object>();
} else if (type == TreeSet.class) {
return new TreeSet<Object>();
} else if (type == LinkedHashSet.class) {
return new LinkedHashSet<Object>();
} else if (type == List.class) {
return new LinkedList<Object>();
} else if (type == LinkedList.class) {
return new LinkedList<Object>();
} else if (type == ArrayList.class) {
return new ArrayList<Object>();
} else if (type == Map.class) {
return new HashMap<Object, Object>();
} else if (type == HashMap.class) {
return new HashMap<Object, Object>();
} else if (type == SortedMap.class) {
return new TreeMap<Object, Object>();
} else if (type == TreeMap.class) {
return new TreeMap<Object, Object>();
} else if (type == LinkedHashMap.class) {
return new LinkedHashMap<Object, Object>();
}
//Let's not care about the rest of collections.
return null;
}
|
Object returnValueFor(Class<?> type) {
if (Primitives.isPrimitiveOrWrapper(type)) {
return Primitives.defaultValueForPrimitiveOrWrapper(type);
//new instances are used instead of Collections.emptyList(), etc.
//to avoid UnsupportedOperationException if code under test modifies returned collection
} else if (type == Iterable.class) {
return new ArrayList<Object>(0);
} else if (type == Collection.class) {
return new LinkedList<Object>();
} else if (type == Set.class) {
return new HashSet<Object>();
} else if (type == HashSet.class) {
return new HashSet<Object>();
} else if (type == SortedSet.class) {
return new TreeSet<Object>();
} else if (type == TreeSet.class) {
return new TreeSet<Object>();
} else if (type == LinkedHashSet.class) {
return new LinkedHashSet<Object>();
} else if (type == List.class) {
return new LinkedList<Object>();
} else if (type == LinkedList.class) {
return new LinkedList<Object>();
} else if (type == ArrayList.class) {
return new ArrayList<Object>();
} else if (type == Map.class) {
return new HashMap<Object, Object>();
} else if (type == HashMap.class) {
return new HashMap<Object, Object>();
} else if (type == SortedMap.class) {
return new TreeMap<Object, Object>();
} else if (type == TreeMap.class) {
return new TreeMap<Object, Object>();
} else if (type == LinkedHashMap.class) {
return new LinkedHashMap<Object, Object>();
}
//Let's not care about the rest of collections.
return null;
}
|
src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
|
Return empty value for Iterables
|
http://code.google.com/p/mockito/issues/detail?id=175
I expect an Iterable to be mocked by default with an empty Iterable. I understand from the initial issue this behavior would be introduced in Mockito 2, but beta-8 still returns null.
Could we return null for Iterables ?
Should we have the same behavior for Iterator ?
Thanks
| 82 | 118 |
Mockito-2
|
public Timer(long durationMillis) {
this.durationMillis = durationMillis;
}
|
public Timer(long durationMillis) {
validateInput(durationMillis);
this.durationMillis = durationMillis;
}
|
src/org/mockito/internal/util/Timer.java
|
Mockito.after() method accepts negative timeperiods and subsequent verifications always pass
|
e.g.
```
Runnable runnable = Mockito.mock(Runnable.class);
Mockito.verify(runnable, Mockito.never()).run(); // passes as expected
Mockito.verify(runnable, Mockito.after(1000).never()).run(); // passes as expected
Mockito.verify(runnable, Mockito.after(-1000).atLeastOnce()).run(); // passes incorrectly
```
| 9 | 11 |
Mockito-24
|
public Object answer(InvocationOnMock invocation) {
if (methodsGuru.isToString(invocation.getMethod())) {
Object mock = invocation.getMock();
MockName name = mockUtil.getMockName(mock);
if (name.isDefault()) {
return "Mock for " + mockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + ", hashCode: " + mock.hashCode();
} else {
return name.toString();
}
} else if (methodsGuru.isCompareToMethod(invocation.getMethod())) {
//see issue 184.
//mocks by default should return 0 if references are the same, otherwise some other value because they are not the same. Hence we return 1 (anything but 0 is good).
//Only for compareTo() method by the Comparable interface
return 1;
}
Class<?> returnType = invocation.getMethod().getReturnType();
return returnValueFor(returnType);
}
|
public Object answer(InvocationOnMock invocation) {
if (methodsGuru.isToString(invocation.getMethod())) {
Object mock = invocation.getMock();
MockName name = mockUtil.getMockName(mock);
if (name.isDefault()) {
return "Mock for " + mockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + ", hashCode: " + mock.hashCode();
} else {
return name.toString();
}
} else if (methodsGuru.isCompareToMethod(invocation.getMethod())) {
//see issue 184.
//mocks by default should return 0 if references are the same, otherwise some other value because they are not the same. Hence we return 1 (anything but 0 is good).
//Only for compareTo() method by the Comparable interface
return invocation.getMock() == invocation.getArguments()[0] ? 0 : 1;
}
Class<?> returnType = invocation.getMethod().getReturnType();
return returnValueFor(returnType);
}
|
src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
|
fix some rawtype warnings in tests
|
Current coverage is 87.76%
Merging #467 into master will not change coverage
@@ master #467 diff @@
==========================================
Files 263 263
Lines 4747 4747
Methods 0 0
Messages 0 0
Branches 767 767
==========================================
Hits 4166 4166
Misses 416 416
Partials 165 165
Powered by Codecov. Last updated by 3fe0fd7...03d9a48
| 63 | 81 |
Mockito-27
|
public <T> void resetMock(T mock) {
MockHandlerInterface<T> oldMockHandler = getMockHandler(mock);
MockHandler<T> newMockHandler = new MockHandler<T>(oldMockHandler);
MethodInterceptorFilter newFilter = new MethodInterceptorFilter(newMockHandler, (MockSettingsImpl) org.mockito.Mockito.withSettings().defaultAnswer(org.mockito.Mockito.RETURNS_DEFAULTS));
((Factory) mock).setCallback(0, newFilter);
}
|
public <T> void resetMock(T mock) {
MockHandlerInterface<T> oldMockHandler = getMockHandler(mock);
MethodInterceptorFilter newFilter = newMethodInterceptorFilter(oldMockHandler.getMockSettings());
((Factory) mock).setCallback(0, newFilter);
}
|
src/org/mockito/internal/util/MockUtil.java
|
Exception when stubbing more than once with when...thenThrow
|
If I create a mock and stub a method so it throws an exception and do that twice the first exception will be thrown upon invoking the second stub instruction.
Example:
@Test
public void testThrowException() {
Object o = Mockito.mock(Object.class);
// test behavior with Runtimeexception
Mockito.when(o.toString()).thenThrow(RuntimeException.class);
// ...
// test behavior with another exception
// this throws a RuntimeException
Mockito.when(o.toString()).thenThrow(IllegalArgumentException.class);
// ...
}
I can work around this if I do it the other way around with doThrow...when. But I lose type safety then. Can you fix this?
| 62 | 67 |
Mockito-28
|
private void injectMockCandidate(Class<?> awaitingInjectionClazz, Set<Object> mocks, Object fieldInstance) {
for(Field field : orderedInstanceFieldsFrom(awaitingInjectionClazz)) {
mockCandidateFilter.filterCandidate(mocks, field, fieldInstance).thenInject();
}
}
|
private void injectMockCandidate(Class<?> awaitingInjectionClazz, Set<Object> mocks, Object fieldInstance) {
for(Field field : orderedInstanceFieldsFrom(awaitingInjectionClazz)) {
Object injected = mockCandidateFilter.filterCandidate(mocks, field, fieldInstance).thenInject();
mocks.remove(injected);
}
}
|
src/org/mockito/internal/configuration/DefaultInjectionEngine.java
|
nicer textual printing of typed parameters
|
When matchers fail but yield the same toString(), Mockito prints extra type information. However, the type information is awkwardly printed for Strings. I've encountered this issue while working on removing hard dependency to hamcrest.
//current:
someMethod(1, (Integer) 2);
someOther(1, "(String) 2");
//desired:
someOther(1, (String) "2");
| 91 | 95 |
Mockito-29
|
public void describeTo(Description description) {
description.appendText("same(");
appendQuoting(description);
description.appendText(wanted.toString());
appendQuoting(description);
description.appendText(")");
}
|
public void describeTo(Description description) {
description.appendText("same(");
appendQuoting(description);
description.appendText(wanted == null ? "null" : wanted.toString());
appendQuoting(description);
description.appendText(")");
}
|
src/org/mockito/internal/matchers/Same.java
|
Fixes #228: fixed a verify() call example in @Captor javadoc
|
Thanks for the fix :)
| 26 | 32 |
Mockito-3
|
public void captureArgumentsFrom(Invocation invocation) {
if (invocation.getMethod().isVarArgs()) {
int indexOfVararg = invocation.getRawArguments().length - 1;
for (int position = 0; position < indexOfVararg; position++) {
Matcher m = matchers.get(position);
if (m instanceof CapturesArguments) {
((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));
}
}
for (int position = indexOfVararg; position < matchers.size(); position++) {
Matcher m = matchers.get(position);
if (m instanceof CapturesArguments) {
((CapturesArguments) m).captureFrom(invocation.getRawArguments()[position - indexOfVararg]);
}
}
} else {
for (int position = 0; position < matchers.size(); position++) {
Matcher m = matchers.get(position);
if (m instanceof CapturesArguments) {
((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));
}
}
}
}
|
public void captureArgumentsFrom(Invocation invocation) {
if (invocation.getMethod().isVarArgs()) {
int indexOfVararg = invocation.getRawArguments().length - 1;
for (int position = 0; position < indexOfVararg; position++) {
Matcher m = matchers.get(position);
if (m instanceof CapturesArguments) {
((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));
}
}
for (Matcher m : uniqueMatcherSet(indexOfVararg)) {
if (m instanceof CapturesArguments) {
Object rawArgument = invocation.getRawArguments()[indexOfVararg];
for (int i = 0; i < Array.getLength(rawArgument); i++) {
((CapturesArguments) m).captureFrom(Array.get(rawArgument, i));
}
}
}
} else {
for (int position = 0; position < matchers.size(); position++) {
Matcher m = matchers.get(position);
if (m instanceof CapturesArguments) {
((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));
}
}
}
}
|
src/org/mockito/internal/invocation/InvocationMatcher.java
|
ArgumentCaptor no longer working for varargs
|
I ran into the issue described here: http://stackoverflow.com/questions/27303562/why-does-upgrading-mockito-from-1-9-5-to-1-10-8-break-this-captor
| 118 | 141 |
Mockito-32
|
@SuppressWarnings("deprecation")
public void process(Class<?> context, Object testClass) {
Field[] fields = context.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Spy.class)) {
assertNoAnnotations(Spy.class, field, Mock.class, org.mockito.MockitoAnnotations.Mock.class, Captor.class);
boolean wasAccessible = field.isAccessible();
field.setAccessible(true);
try {
Object instance = field.get(testClass);
if (instance == null) {
throw new MockitoException("Cannot create a @Spy for '" + field.getName() + "' field because the *instance* is missing\n" +
"The instance must be created *before* initMocks();\n" +
"Example of correct usage of @Spy:\n" +
" @Spy List mock = new LinkedList();\n" +
" //also, don't forget about MockitoAnnotations.initMocks();");
}
if (new MockUtil().isMock(instance)) {
// instance has been spied earlier
Mockito.reset(instance);
} else {
field.set(testClass, Mockito.spy(instance));
}
} catch (IllegalAccessException e) {
throw new MockitoException("Problems initiating spied field " + field.getName(), e);
} finally {
field.setAccessible(wasAccessible);
}
}
}
}
|
@SuppressWarnings("deprecation")
public void process(Class<?> context, Object testClass) {
Field[] fields = context.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Spy.class)) {
assertNoAnnotations(Spy.class, field, Mock.class, org.mockito.MockitoAnnotations.Mock.class, Captor.class);
boolean wasAccessible = field.isAccessible();
field.setAccessible(true);
try {
Object instance = field.get(testClass);
if (instance == null) {
throw new MockitoException("Cannot create a @Spy for '" + field.getName() + "' field because the *instance* is missing\n" +
"The instance must be created *before* initMocks();\n" +
"Example of correct usage of @Spy:\n" +
" @Spy List mock = new LinkedList();\n" +
" //also, don't forget about MockitoAnnotations.initMocks();");
}
if (new MockUtil().isMock(instance)) {
// instance has been spied earlier
Mockito.reset(instance);
} else {
field.set(testClass, Mockito.mock(instance.getClass(), withSettings()
.spiedInstance(instance)
.defaultAnswer(Mockito.CALLS_REAL_METHODS)
.name(field.getName())));
}
} catch (IllegalAccessException e) {
throw new MockitoException("Problems initiating spied field " + field.getName(), e);
} finally {
field.setAccessible(wasAccessible);
}
}
}
}
|
src/org/mockito/internal/configuration/SpyAnnotationEngine.java
|
Mockito can't create mock on public class that extends package-private class
|
I created simple project to demonstrate this:
https://github.com/astafev/mockito-package-private-class/
Please take a look. Even if it can't be implemented, I think that mockito should throw some normal exception at time of creation.
In my variant on first creation it returns wrong-working mock (invokes real method instead of stubbed). On second creation throws exception that doesn't really connected with problem.
Everything works fine if you mock package-private parent.
| 27 | 58 |
Mockito-33
|
public boolean hasSameMethod(Invocation candidate) {
//not using method.equals() for 1 good reason:
//sometimes java generates forwarding methods when generics are in play see JavaGenericsForwardingMethodsTest
Method m1 = invocation.getMethod();
Method m2 = candidate.getMethod();
/* Avoid unnecessary cloning */
return m1.equals(m2);
}
|
public boolean hasSameMethod(Invocation candidate) {
//not using method.equals() for 1 good reason:
//sometimes java generates forwarding methods when generics are in play see JavaGenericsForwardingMethodsTest
Method m1 = invocation.getMethod();
Method m2 = candidate.getMethod();
if (m1.getName() != null && m1.getName().equals(m2.getName())) {
/* Avoid unnecessary cloning */
Class[] params1 = m1.getParameterTypes();
Class[] params2 = m2.getParameterTypes();
if (params1.length == params2.length) {
for (int i = 0; i < params1.length; i++) {
if (params1[i] != params2[i])
return false;
}
return true;
}
}
return false;
}
|
src/org/mockito/internal/invocation/InvocationMatcher.java
|
ArgumentCaptor.fromClass's return type should match a parameterized type
|
ArgumentCaptor.fromClass's return type should match a parameterized type. I.e. the expression ArgumentCaptor.fromClass(Class<S>) should be of type ArgumentCaptor<U> where S is a subtype of U.
For example:
ArgumentCaptor<Consumer<String>> captor = ArgumentCaptor.fromClass(Consumer.class)
does not type check (i.e. it is a compile time error). It should type check.
The reasons that it is desirable for ArgumentCaptor.fromClass to allow expressions such as the example above to type check are:
ArgumentCaptor.fromClass is intended to be a convenience method to allow the user to construct an ArgumentCaptor without casting the returned value.
Currently, the user can devise a workaround such as:
ArgumentCaptor<? extends Consumer<String>> captor
= ArgumentCaptor.fromClass(Consumer.class)
This workaround is inconvenient, and so contrary to ArgumentCaptor.fromClass being a convenience method.
It is inconsistent with @Captor, which can be applied to a field with a paramterized type. I.e.
@Captor ArgumentCaptor<Consumer<String>> captor
type checks.
| 92 | 100 |
Mockito-34
|
public void captureArgumentsFrom(Invocation i) {
int k = 0;
for (Matcher m : matchers) {
if (m instanceof CapturesArguments) {
((CapturesArguments) m).captureFrom(i.getArguments()[k]);
}
k++;
}
}
|
public void captureArgumentsFrom(Invocation i) {
int k = 0;
for (Matcher m : matchers) {
if (m instanceof CapturesArguments && i.getArguments().length > k) {
((CapturesArguments) m).captureFrom(i.getArguments()[k]);
}
k++;
}
}
|
src/org/mockito/internal/invocation/InvocationMatcher.java
|
Source files should not be put in binary JAR
|
Source files (*.java) should not be put into binary mockito-core.jar. It stupefies Idea to show decompiled file even when source jar is available.
| 103 | 111 |
Mockito-36
|
public Object callRealMethod() throws Throwable {
return realMethod.invoke(mock, rawArguments);
}
|
public Object callRealMethod() throws Throwable {
if (this.getMethod().getDeclaringClass().isInterface()) {
new Reporter().cannotCallRealMethodOnInterface();
}
return realMethod.invoke(mock, rawArguments);
}
|
src/org/mockito/internal/invocation/Invocation.java
|
Make Mockito JUnit rule easier to use
|
- Mockito JUnit rule easier to use by avoiding the need to pass test instance
- Make it compatible with JUnit 4.7+ instead of 4.9+
| 201 | 203 |
Mockito-37
|
public void validate(Answer<?> answer, Invocation invocation) {
if (answer instanceof ThrowsException) {
validateException((ThrowsException) answer, invocation);
}
if (answer instanceof Returns) {
validateReturnValue((Returns) answer, invocation);
}
if (answer instanceof DoesNothing) {
validateDoNothing((DoesNothing) answer, invocation);
}
}
|
public void validate(Answer<?> answer, Invocation invocation) {
if (answer instanceof ThrowsException) {
validateException((ThrowsException) answer, invocation);
}
if (answer instanceof Returns) {
validateReturnValue((Returns) answer, invocation);
}
if (answer instanceof DoesNothing) {
validateDoNothing((DoesNothing) answer, invocation);
}
if (answer instanceof CallsRealMethods) {
validateMockingConcreteClass((CallsRealMethods) answer, invocation);
}
}
|
src/org/mockito/internal/stubbing/answers/AnswersValidator.java
|
Make Mockito JUnit rule easier to use
|
- Mockito JUnit rule easier to use by avoiding the need to pass test instance
- Make it compatible with JUnit 4.7+ instead of 4.9+
| 15 | 28 |
Mockito-38
|
private boolean toStringEquals(Matcher m, Object arg) {
return StringDescription.toString(m).equals(arg.toString());
}
|
private boolean toStringEquals(Matcher m, Object arg) {
return StringDescription.toString(m).equals(arg == null? "null" : arg.toString());
}
|
src/org/mockito/internal/verification/argumentmatching/ArgumentMatchingTool.java
|
Generate change list separated by types using labels
|
Changes Unknown when pulling 47a7016 on szpak:topic/releaseLabels into * on mockito:master*.
| 47 | 49 |
Mockito-7
|
private void readTypeVariables() {
for (Type type : typeVariable.getBounds()) {
registerTypeVariablesOn(type);
}
registerTypeVariablesOn(getActualTypeArgumentFor(typeVariable));
}
|
private void readTypeVariables() {
for (Type type : typeVariable.getBounds()) {
registerTypeVariablesOn(type);
}
registerTypeParametersOn(new TypeVariable[] { typeVariable });
registerTypeVariablesOn(getActualTypeArgumentFor(typeVariable));
}
|
src/org/mockito/internal/util/reflection/GenericMetadataSupport.java
|
Deep stubbing with generic responses in the call chain is not working
|
Deep stubbing will throw an Exception if multiple generics occur in the call chain. For instance, consider having a mock myMock1 that provides a function that returns a generic T. If T also has a function that returns a generic, an Exception with the message "Raw extraction not supported for : 'null'" will be thrown.
As an example the following test will throw an Exception:
public class MockitoGenericsDeepStubTest {
@Test
public void discoverDeepMockingOfGenerics() {
MyClass1 myMock1 = mock(MyClass1.class, RETURNS_DEEP_STUBS);
when(myMock1.getNested().getNested().returnSomething()).thenReturn("Hello World.");
}
public static interface MyClass1 <MC2 extends MyClass2> {
public MC2 getNested();
}
public static interface MyClass2<MC3 extends MyClass3> {
public MC3 getNested();
}
public static interface MyClass3 {
public String returnSomething();
}
}
You can make this test run if you step into the class ReturnsDeepStubs and change the method withSettingsUsing to return MockSettings with ReturnsDeepStubs instead of ReturnsDeepStubsSerializationFallback as default answer:
private MockSettings withSettingsUsing(GenericMetadataSupport returnTypeGenericMetadata, MockCreationSettings parentMockSettings) {
MockSettings mockSettings = returnTypeGenericMetadata.hasRawExtraInterfaces() ?
withSettings().extraInterfaces(returnTypeGenericMetadata.rawExtraInterfaces())
: withSettings();
return propagateSerializationSettings(mockSettings, parentMockSettings)
.defaultAnswer(this);
}
However, this breaks other tests and features.
I think, the issue is that further generics are not possible to be mocked by ReturnsDeepStubsSerializationFallback since the GenericMetadataSupport is "closed" at this point.
Thanks and kind regards
Tobias
| 375 | 380 |
Mockito-8
|
protected void registerTypeVariablesOn(Type classType) {
if (!(classType instanceof ParameterizedType)) {
return;
}
ParameterizedType parameterizedType = (ParameterizedType) classType;
TypeVariable[] typeParameters = ((Class<?>) parameterizedType.getRawType()).getTypeParameters();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
for (int i = 0; i < actualTypeArguments.length; i++) {
TypeVariable typeParameter = typeParameters[i];
Type actualTypeArgument = actualTypeArguments[i];
if (actualTypeArgument instanceof WildcardType) {
contextualActualTypeParameters.put(typeParameter, boundsOf((WildcardType) actualTypeArgument));
} else {
contextualActualTypeParameters.put(typeParameter, actualTypeArgument);
}
// logger.log("For '" + parameterizedType + "' found type variable : { '" + typeParameter + "(" + System.identityHashCode(typeParameter) + ")" + "' : '" + actualTypeArgument + "(" + System.identityHashCode(typeParameter) + ")" + "' }");
}
}
|
protected void registerTypeVariablesOn(Type classType) {
if (!(classType instanceof ParameterizedType)) {
return;
}
ParameterizedType parameterizedType = (ParameterizedType) classType;
TypeVariable[] typeParameters = ((Class<?>) parameterizedType.getRawType()).getTypeParameters();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
for (int i = 0; i < actualTypeArguments.length; i++) {
TypeVariable typeParameter = typeParameters[i];
Type actualTypeArgument = actualTypeArguments[i];
if (actualTypeArgument instanceof WildcardType) {
contextualActualTypeParameters.put(typeParameter, boundsOf((WildcardType) actualTypeArgument));
} else if (typeParameter != actualTypeArgument) {
contextualActualTypeParameters.put(typeParameter, actualTypeArgument);
}
// logger.log("For '" + parameterizedType + "' found type variable : { '" + typeParameter + "(" + System.identityHashCode(typeParameter) + ")" + "' : '" + actualTypeArgument + "(" + System.identityHashCode(typeParameter) + ")" + "' }");
}
}
|
src/org/mockito/internal/util/reflection/GenericMetadataSupport.java
|
1.10 regression (StackOverflowError) with interface where generic type has itself as upper bound
|
Add this to GenericMetadataSupportTest:
interface GenericsSelfReference<T extends GenericsSelfReference<T>> {
T self();
}
@Test
public void typeVariable_of_self_type() {
GenericMetadataSupport genericMetadata = inferFrom(GenericsSelfReference.class).resolveGenericReturnType(firstNamedMethod("self", GenericsSelfReference.class));
assertThat(genericMetadata.rawType()).isEqualTo(GenericsSelfReference.class);
}
It fails on master and 1.10.8 with this:
java.lang.StackOverflowError
at sun.reflect.generics.reflectiveObjects.TypeVariableImpl.hashCode(TypeVariableImpl.java:201)
at java.util.HashMap.hash(HashMap.java:338)
at java.util.HashMap.get(HashMap.java:556)
at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:193)
at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:196)
at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:196)
It worked on 1.9.5. May be caused by the changes in ab9e9f3 (cc @bric3).
(Also note that while the above interface looks strange, it is commonly used for builder hierarchies, where base class methods want to return this with a more specific type.)
| 66 | 84 |
Mockito-9
|
public Object answer(InvocationOnMock invocation) throws Throwable {
return invocation.callRealMethod();
}
|
public Object answer(InvocationOnMock invocation) throws Throwable {
if (Modifier.isAbstract(invocation.getMethod().getModifiers())) {
return new GloballyConfiguredAnswer().answer(invocation);
}
return invocation.callRealMethod();
}
|
src/org/mockito/internal/stubbing/answers/CallsRealMethods.java
|
Problem spying on abstract classes
|
There's a problem with spying on abstract classes when the real implementation calls out to the abstract method. More details: #121
| 35 | 37 |
Time-14
|
public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) {
// overridden as superclass algorithm can't handle
// 2004-02-29 + 48 months -> 2008-02-29 type dates
if (valueToAdd == 0) {
return values;
}
// month is largest field and being added to, such as month-day
if (DateTimeUtils.isContiguous(partial)) {
long instant = 0L;
for (int i = 0, isize = partial.size(); i < isize; i++) {
instant = partial.getFieldType(i).getField(iChronology).set(instant, values[i]);
}
instant = add(instant, valueToAdd);
return iChronology.get(partial, instant);
} else {
return super.add(partial, fieldIndex, values, valueToAdd);
}
}
|
public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) {
// overridden as superclass algorithm can't handle
// 2004-02-29 + 48 months -> 2008-02-29 type dates
if (valueToAdd == 0) {
return values;
}
if (partial.size() > 0 && partial.getFieldType(0).equals(DateTimeFieldType.monthOfYear()) && fieldIndex == 0) {
// month is largest field and being added to, such as month-day
int curMonth0 = partial.getValue(0) - 1;
int newMonth = ((curMonth0 + (valueToAdd % 12) + 12) % 12) + 1;
return set(partial, 0, values, newMonth);
}
if (DateTimeUtils.isContiguous(partial)) {
long instant = 0L;
for (int i = 0, isize = partial.size(); i < isize; i++) {
instant = partial.getFieldType(i).getField(iChronology).set(instant, values[i]);
}
instant = add(instant, valueToAdd);
return iChronology.get(partial, instant);
} else {
return super.add(partial, fieldIndex, values, valueToAdd);
}
}
|
src/main/java/org/joda/time/chrono/BasicMonthOfYearDateTimeField.java
|
#151 Unable to add days to a MonthDay set to the ISO leap date
|
It's not possible to add days to a MonthDay set to the ISO leap date (February 29th). This is even more bizarre given the exact error message thrown.
Sample snippet:
final MonthDay isoLeap = new MonthDay(DateTimeConstants.FEBRUARY, 29, ISOChronology.getInstanceUTC());
System.out.println(isoLeap);
System.out.println(isoLeap.plusDays(2));
Which generates the following combined console output and stack trace:
--02-29
Exception in thread "main" org.joda.time.IllegalFieldValueException: Value 29 for dayOfMonth must be in the range [1,28]
at org.joda.time.field.FieldUtils.verifyValueBounds(FieldUtils.java:215)
at org.joda.time.field.PreciseDurationDateTimeField.set(PreciseDurationDateTimeField.java:78)
at org.joda.time.chrono.BasicMonthOfYearDateTimeField.add(BasicMonthOfYearDateTimeField.java:212)
at org.joda.time.field.BaseDateTimeField.add(BaseDateTimeField.java:324)
at org.joda.time.MonthDay.withFieldAdded(MonthDay.java:519)
at org.joda.time.MonthDay.minusDays(MonthDay.java:672)
at ext.site.time.chrono.Main.m7(Main.java:191)
at ext.site.time.chrono.Main.main(Main.java:27)
The follwing method calls and parameters also generate the same or related error:
isoLeap.plusMonths(1);
isoLeap.plusMonths(-1);
isoLeap.minusMonths(1);
isoLeap.minusMonths(-1);
isoLeap.minusDays(-1);
However, the following methods work:
isoLeap.minusDays(1);
isoLeap.plusDays(-1);
Performing operations on dates around the ISO leap date react as if it exists, ie:
System.out.println(isoLeap.minusDays(1).plusDays(2));
Prints out '--03-01' as expected.
| 203 | 220 |
Time-15
|
public static long safeMultiply(long val1, int val2) {
switch (val2) {
case -1:
return -val1;
case 0:
return 0L;
case 1:
return val1;
}
long total = val1 * val2;
if (total / val2 != val1) {
throw new ArithmeticException("Multiplication overflows a long: " + val1 + " * " + val2);
}
return total;
}
|
public static long safeMultiply(long val1, int val2) {
switch (val2) {
case -1:
if (val1 == Long.MIN_VALUE) {
throw new ArithmeticException("Multiplication overflows a long: " + val1 + " * " + val2);
}
return -val1;
case 0:
return 0L;
case 1:
return val1;
}
long total = val1 * val2;
if (total / val2 != val1) {
throw new ArithmeticException("Multiplication overflows a long: " + val1 + " * " + val2);
}
return total;
}
|
src/main/java/org/joda/time/field/FieldUtils.java
|
#147 possibly a bug in org.joda.time.field.FieldUtils.safeMultipl
|
It seems to me that as currently written in joda-time-2.1.jar
org.joda.time.field.FieldUtils.safeMultiply(long val1, int scalar)
doesn't detect the overflow if the long val1 == Long.MIN_VALUE and the int scalar == -1.
The attached file demonstrates what I think is the bug and suggests a patch.
I looked at the Joda Time bugs list in SourceForge but couldn't see anything that looked relevant: my apologies if I've missed something, or if I'm making a mistake with this bug report.
Colin Bartlett
| 135 | 149 |
Time-16
|
public int parseInto(ReadWritableInstant instant, String text, int position) {
DateTimeParser parser = requireParser();
if (instant == null) {
throw new IllegalArgumentException("Instant must not be null");
}
long instantMillis = instant.getMillis();
Chronology chrono = instant.getChronology();
long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis);
chrono = selectChronology(chrono);
DateTimeParserBucket bucket = new DateTimeParserBucket(
instantLocal, chrono, iLocale, iPivotYear, iDefaultYear);
int newPos = parser.parseInto(bucket, text, position);
instant.setMillis(bucket.computeMillis(false, text));
if (iOffsetParsed && bucket.getOffsetInteger() != null) {
int parsedOffset = bucket.getOffsetInteger();
DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);
chrono = chrono.withZone(parsedZone);
} else if (bucket.getZone() != null) {
chrono = chrono.withZone(bucket.getZone());
}
instant.setChronology(chrono);
if (iZone != null) {
instant.setZone(iZone);
}
return newPos;
}
|
public int parseInto(ReadWritableInstant instant, String text, int position) {
DateTimeParser parser = requireParser();
if (instant == null) {
throw new IllegalArgumentException("Instant must not be null");
}
long instantMillis = instant.getMillis();
Chronology chrono = instant.getChronology();
long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis);
chrono = selectChronology(chrono);
DateTimeParserBucket bucket = new DateTimeParserBucket(
instantLocal, chrono, iLocale, iPivotYear, chrono.year().get(instantLocal));
int newPos = parser.parseInto(bucket, text, position);
instant.setMillis(bucket.computeMillis(false, text));
if (iOffsetParsed && bucket.getOffsetInteger() != null) {
int parsedOffset = bucket.getOffsetInteger();
DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);
chrono = chrono.withZone(parsedZone);
} else if (bucket.getZone() != null) {
chrono = chrono.withZone(bucket.getZone());
}
instant.setChronology(chrono);
if (iZone != null) {
instant.setZone(iZone);
}
return newPos;
}
|
src/main/java/org/joda/time/format/DateTimeFormatter.java
|
#148 DateTimeFormatter.parseInto broken when no year in format
|
In Joda Time 2.0, the default year was set to 2000 so that Feb 29 could be parsed correctly. However, parseInto now overwrites the given instant's year with 2000 (or whatever iDefaultYear is set to). The correct behavior would seem to be to use the given instant's year instead of iDefaultYear.
This does mean that Feb 29 might not be parseable if the instant's year is not a leap year, but in this case the caller asked for that in a sense.
| 697 | 724 |
Time-17
|
public long adjustOffset(long instant, boolean earlierOrLater) {
// a bit messy, but will work in all non-pathological cases
// evaluate 3 hours before and after to work out if anything is happening
long instantBefore = convertUTCToLocal(instant - 3 * DateTimeConstants.MILLIS_PER_HOUR);
long instantAfter = convertUTCToLocal(instant + 3 * DateTimeConstants.MILLIS_PER_HOUR);
if (instantBefore == instantAfter) {
return instant; // not an overlap (less than is a gap, equal is normal case)
}
// work out range of instants that have duplicate local times
long local = convertUTCToLocal(instant);
return convertLocalToUTC(local, false, earlierOrLater ? instantAfter : instantBefore);
// calculate result
// currently in later offset
// currently in earlier offset
}
|
public long adjustOffset(long instant, boolean earlierOrLater) {
// a bit messy, but will work in all non-pathological cases
// evaluate 3 hours before and after to work out if anything is happening
long instantBefore = instant - 3 * DateTimeConstants.MILLIS_PER_HOUR;
long instantAfter = instant + 3 * DateTimeConstants.MILLIS_PER_HOUR;
long offsetBefore = getOffset(instantBefore);
long offsetAfter = getOffset(instantAfter);
if (offsetBefore <= offsetAfter) {
return instant; // not an overlap (less than is a gap, equal is normal case)
}
// work out range of instants that have duplicate local times
long diff = offsetBefore - offsetAfter;
long transition = nextTransition(instantBefore);
long overlapStart = transition - diff;
long overlapEnd = transition + diff;
if (instant < overlapStart || instant >= overlapEnd) {
return instant; // not an overlap
}
// calculate result
long afterStart = instant - overlapStart;
if (afterStart >= diff) {
// currently in later offset
return earlierOrLater ? instant : instant - diff;
} else {
// currently in earlier offset
return earlierOrLater ? instant + diff : instant;
}
}
|
src/main/java/org/joda/time/DateTimeZone.java
|
#141 Bug on withLaterOffsetAtOverlap method
|
The method withLaterOffsetAtOverlap created to workaround the issue 3192457 seems to not be working at all.
I won´t write many info about the problem to solve because the issue 3192457 have this info indeed.
But If something is unclear I can answer on the comments.
Problem demonstration:
TimeZone.setDefault(TimeZone.getTimeZone("America/Sao_Paulo"));
DateTimeZone.setDefault( DateTimeZone.forID("America/Sao_Paulo") );
DateTime dtch;
{
dtch = new DateTime(2012,2,25,5,5,5,5).millisOfDay().withMaximumValue();
System.out.println( dtch ); // prints: 2012-02-25T23:59:59.999-02:00 //Were are at the first 23:** of the day.
//At this point dtch have the -03:00 offset
}
{
dtch = dtch.plus(60001);
System.out.println( dtch ); // prints: 2012-02-25T23:01:00.000-03:00 //Were are at the first minute of the second 23:** of the day. Ok its correct
//At this point dtch have the -03:00 offset
}
{
dtch = dtch.withEarlierOffsetAtOverlap();
System.out.println( dtch ); // prints: 2012-02-25T23:01:00.000-02:00 //Were are at the first minute of the first 23:** of the day. Ok its correct
//At this point dtch have the -02:00 offset ( because we called withEarlierOffsetAtOverlap() ) // This method is working perfectly
}
{
dtch = dtch.withLaterOffsetAtOverlap();
System.out.println( dtch ); // prints: 2012-02-25T23:01:00.000-02:00 //Were are at the first minute of the first 23:** of the day.
// Here is the problem we should have a -03:00 offset here since we called withLaterOffsetAtOverlap() expecting to change to the second 23:** of the day
}
On the last two brackets we can see that withLaterOffsetAtOverlap is not undoing withEarlierOffsetAtOverlap as it should ( and not even working at all )
| 1,163 | 1,180 |
Time-18
|
public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth,
int hourOfDay, int minuteOfHour,
int secondOfMinute, int millisOfSecond)
throws IllegalArgumentException
{
Chronology base;
if ((base = getBase()) != null) {
return base.getDateTimeMillis
(year, monthOfYear, dayOfMonth,
hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);
}
// Assume date is Gregorian.
long instant;
instant = iGregorianChronology.getDateTimeMillis
(year, monthOfYear, dayOfMonth,
hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);
if (instant < iCutoverMillis) {
// Maybe it's Julian.
instant = iJulianChronology.getDateTimeMillis
(year, monthOfYear, dayOfMonth,
hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);
if (instant >= iCutoverMillis) {
// Okay, it's in the illegal cutover gap.
throw new IllegalArgumentException("Specified date does not exist");
}
}
return instant;
}
|
public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth,
int hourOfDay, int minuteOfHour,
int secondOfMinute, int millisOfSecond)
throws IllegalArgumentException
{
Chronology base;
if ((base = getBase()) != null) {
return base.getDateTimeMillis
(year, monthOfYear, dayOfMonth,
hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);
}
// Assume date is Gregorian.
long instant;
try {
instant = iGregorianChronology.getDateTimeMillis
(year, monthOfYear, dayOfMonth,
hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);
} catch (IllegalFieldValueException ex) {
if (monthOfYear != 2 || dayOfMonth != 29) {
throw ex;
}
instant = iGregorianChronology.getDateTimeMillis
(year, monthOfYear, 28,
hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);
if (instant >= iCutoverMillis) {
throw ex;
}
}
if (instant < iCutoverMillis) {
// Maybe it's Julian.
instant = iJulianChronology.getDateTimeMillis
(year, monthOfYear, dayOfMonth,
hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);
if (instant >= iCutoverMillis) {
// Okay, it's in the illegal cutover gap.
throw new IllegalArgumentException("Specified date does not exist");
}
}
return instant;
}
|
src/main/java/org/joda/time/chrono/GJChronology.java
|
#130 GJChronology rejects valid Julian dates
|
Example:
DateTime jdt = new DateTime(1500, 2, 29, 0, 0, 0, 0, JulianChronology.getInstanceUTC()); // Valid.
DateTime gjdt = new DateTime(1500, 2, 29, 0, 0, 0, 0, GJChronology.getInstanceUTC()); // Invalid.
The 2nd statement fails with "org.joda.time.IllegalFieldValueException: Value 29 for dayOfMonth must be in the range [1,28]".
Given that I left the cutover date at the default (October 15, 1582), isn't 1500/02/29 a valid date in the GJChronology?
| 350 | 378 |
Time-19
|
public int getOffsetFromLocal(long instantLocal) {
// get the offset at instantLocal (first estimate)
final int offsetLocal = getOffset(instantLocal);
// adjust instantLocal using the estimate and recalc the offset
final long instantAdjusted = instantLocal - offsetLocal;
final int offsetAdjusted = getOffset(instantAdjusted);
// if the offsets differ, we must be near a DST boundary
if (offsetLocal != offsetAdjusted) {
// we need to ensure that time is always after the DST gap
// this happens naturally for positive offsets, but not for negative
if ((offsetLocal - offsetAdjusted) < 0) {
// if we just return offsetAdjusted then the time is pushed
// back before the transition, whereas it should be
// on or after the transition
long nextLocal = nextTransition(instantAdjusted);
long nextAdjusted = nextTransition(instantLocal - offsetAdjusted);
if (nextLocal != nextAdjusted) {
return offsetLocal;
}
}
} else if (offsetLocal > 0) {
long prev = previousTransition(instantAdjusted);
if (prev < instantAdjusted) {
int offsetPrev = getOffset(prev);
int diff = offsetPrev - offsetLocal;
if (instantAdjusted - prev <= diff) {
return offsetPrev;
}
}
}
return offsetAdjusted;
}
|
public int getOffsetFromLocal(long instantLocal) {
// get the offset at instantLocal (first estimate)
final int offsetLocal = getOffset(instantLocal);
// adjust instantLocal using the estimate and recalc the offset
final long instantAdjusted = instantLocal - offsetLocal;
final int offsetAdjusted = getOffset(instantAdjusted);
// if the offsets differ, we must be near a DST boundary
if (offsetLocal != offsetAdjusted) {
// we need to ensure that time is always after the DST gap
// this happens naturally for positive offsets, but not for negative
if ((offsetLocal - offsetAdjusted) < 0) {
// if we just return offsetAdjusted then the time is pushed
// back before the transition, whereas it should be
// on or after the transition
long nextLocal = nextTransition(instantAdjusted);
long nextAdjusted = nextTransition(instantLocal - offsetAdjusted);
if (nextLocal != nextAdjusted) {
return offsetLocal;
}
}
} else if (offsetLocal >= 0) {
long prev = previousTransition(instantAdjusted);
if (prev < instantAdjusted) {
int offsetPrev = getOffset(prev);
int diff = offsetPrev - offsetLocal;
if (instantAdjusted - prev <= diff) {
return offsetPrev;
}
}
}
return offsetAdjusted;
}
|
src/main/java/org/joda/time/DateTimeZone.java
|
#124 Inconsistent interpretation of ambiguous time during DST
|
The inconsistency appears for timezone Europe/London.
Consider the following code
…
DateTime britishDate = new DateTime(2011, 10, 30, 1, 59, 0, 0, DateTimeZone.forID("Europe/London"));
DateTime norwDate = new DateTime(2011, 10, 30, 2, 59, 0, 0, DateTimeZone.forID("Europe/Oslo"));
DateTime finnishDate = new DateTime(2011, 10, 30, 3, 59, 0, 0, DateTimeZone.forID("Europe/Helsinki"));
System.out.println(britishDate);
System.out.println(norwDate);
System.out.println(finnishDate);
…
These three DateTime objects should all represent the same moment in time even if they are ambiguous. And using jodatime 1.6.2 this is the case. The code produces the following output:
2011-10-30T01:59:00.000Z
2011-10-30T02:59:00.000+01:00
2011-10-30T03:59:00.000+02:00
Using jodatime 2.0 however, the output is:
2011-10-30T01:59:00.000Z
2011-10-30T02:59:00.000+02:00
2011-10-30T03:59:00.000+03:00
which IMO is wrong for Europe/London. Correct output should have been
2011-10-30T01:59:00.000+01:00
The release notes for 2.0 states that:
"Now, it always returns the earlier instant (summer time) during an overlap. …"
| 880 | 911 |
Time-20
|
public int parseInto(DateTimeParserBucket bucket, String text, int position) {
String str = text.substring(position);
for (String id : ALL_IDS) {
if (str.startsWith(id)) {
bucket.setZone(DateTimeZone.forID(id));
return position + id.length();
}
}
return ~position;
}
|
public int parseInto(DateTimeParserBucket bucket, String text, int position) {
String str = text.substring(position);
String best = null;
for (String id : ALL_IDS) {
if (str.startsWith(id)) {
if (best == null || id.length() > best.length()) {
best = id;
}
}
}
if (best != null) {
bucket.setZone(DateTimeZone.forID(best));
return position + best.length();
}
return ~position;
}
|
src/main/java/org/joda/time/format/DateTimeFormatterBuilder.java
|
#126 Errors creating/parsing dates with specific time zones.
|
Consider the following test code using Joda 2.0
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.Set;
public class JodaDateTimeZoneTester {
private static DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss.SSS ZZZ");
private static int numTimeZonesTested = 0;
private static int numTimeZonesPassed = 0;
private static int numTimeZonesFailed = 0;
private static int numTimeZonesException = 0;
private static String convertDateTimeToFormattedString(DateTime dateTime) {
return formatter.print(dateTime);
}
private static DateTime parseStringToDateTime(String formattedDateTime) {
return formatter.parseDateTime(formattedDateTime);
}
private static void testDateTimeFormatter(DateTime dateTime, String timeZone) {
numTimeZonesTested++;
final String dateTimeZoneId = dateTime.getZone().getID();
if (!timeZone.equals(dateTimeZoneId)) {
numTimeZonesFailed++;
System.out.println(timeZone + " failed to construct into the proper date time zone - constructed time zone = " + dateTimeZoneId);
return;
}
try {
DateTime convertedDateTime = parseStringToDateTime(convertDateTimeToFormattedString(dateTime));
if (dateTime.equals(convertedDateTime)) {
numTimeZonesPassed++;
//System.out.println(dateTime.getZone().getID() + " passed.");
} else {
numTimeZonesFailed++;
System.out.println("Formatter failed for time zone ID: " + dateTimeZoneId + " converted it to: " + convertedDateTime.getZone().getID());
}
} catch (IllegalArgumentException iae) {
numTimeZonesException++;
System.out.println("Formatter threw exception for time zone id: " + dateTimeZoneId);
}
}
public static void main(String[] args) {
Set<String> timeZones = DateTimeZone.getAvailableIDs();
for (String timeZone : timeZones) {
testDateTimeFormatter(DateTime.now().withZone(DateTimeZone.forID(timeZone)), timeZone);
}
System.out.println();
System.out.println("Number of Time Zones tested: " + numTimeZonesTested);
System.out.println("Number passed: " + numTimeZonesPassed);
System.out.println("Number failed: " + numTimeZonesFailed);
System.out.println("Number exceptions: " + numTimeZonesException);
System.out.println();
}
}
The results are out of 572 time zones 130 fail and 30 throw exceptions.
The failures are the most interesting. When I query DateTimeZone to get its time zone ids I will get a time zone like America/Atka. When I take that id and create a date time with it its time zone id is America/Adak. It is like there are multiple list of time zones in Joda time and they are out of sync.
Source code is attached.
| 2,540 | 2,549 |
Time-22
|
protected BasePeriod(long duration) {
this(duration, null, null);
// bug [3264409]
}
|
protected BasePeriod(long duration) {
super();
// bug [3264409]
iType = PeriodType.time();
int[] values = ISOChronology.getInstanceUTC().get(this, duration);
iType = PeriodType.standard();
iValues = new int[8];
System.arraycopy(values, 0, iValues, 4, 4);
}
|
src/main/java/org/joda/time/base/BasePeriod.java
|
#113 Duration.toPeriod with fixed time zones.
|
I have a question concerning the conversion of a Duration to Period. I'm not sure if this is a bug, or if there is a different way to do this.
The basis of the problem, is that using Duration.toPeriod() uses the chronology of the default time zone to do the conversion. This can cause different results from a timezone with DST and one without. This can be reproduced easily with this test.
//set default time zone with this argument -Duser.timezone="GMT"
public void testForJodaForum()
{
System.out.println("Timezone: " + DateTimeZone.getDefault());
//Duration of more than 24 hours
Duration aDuration = new Duration(DateTimeConstants.MILLIS_PER_HOUR * 30 + DateTimeConstants.MILLIS_PER_MINUTE * 50
+ DateTimeConstants.MILLIS_PER_SECOND * 14);
System.out.println("Duration before: " + aDuration);
Period period = aDuration.toPeriod();
System.out.println("Period after: " + period);
}
A fixed time zone produces this output
Timezone: Etc/GMT
Duration before: PT111014S
Period after: P1DT6H50M14S
A DST time zone produces this output
Timezone: America/Chicago
Duration before: PT111014S
Period after: PT30H50M14S
In the joda code, Duration.toPeriod() uses a period constructor that takes the chronology, but null is passed in, so the chronology of the default time zone is used, which leads to this behavior.
The javadoc of toPeriod() states that only precise fields of hours, minutes, seconds, and millis will be converted. But for a fixed timezone, days and weeks are also precise, which is stated in the javadoc for toPeriod(Chronology chrono). In our app, we need consistent behavior regardless of the default time zone, which is to have all the extra hours put into the hours bucket. Since Duration is supposed to be a 'time zone independent' length of time, I don't think we should have to do any chronology manipulation to get this to work.
Any help is appreciated.
Thanks,
Cameron
| 221 | 224 |
Time-23
|
private static synchronized String getConvertedId(String id) {
Map<String, String> map = cZoneIdConversion;
if (map == null) {
// Backwards compatibility with TimeZone.
map = new HashMap<String, String>();
map.put("GMT", "UTC");
map.put("MIT", "Pacific/Apia");
map.put("HST", "Pacific/Honolulu"); // JDK 1.1 compatible
map.put("AST", "America/Anchorage");
map.put("PST", "America/Los_Angeles");
map.put("MST", "America/Denver"); // JDK 1.1 compatible
map.put("PNT", "America/Phoenix");
map.put("CST", "America/Chicago");
map.put("EST", "America/New_York"); // JDK 1.1 compatible
map.put("IET", "America/Indianapolis");
map.put("PRT", "America/Puerto_Rico");
map.put("CNT", "America/St_Johns");
map.put("AGT", "America/Buenos_Aires");
map.put("BET", "America/Sao_Paulo");
map.put("WET", "Europe/London");
map.put("ECT", "Europe/Paris");
map.put("ART", "Africa/Cairo");
map.put("CAT", "Africa/Harare");
map.put("EET", "Europe/Bucharest");
map.put("EAT", "Africa/Addis_Ababa");
map.put("MET", "Asia/Tehran");
map.put("NET", "Asia/Yerevan");
map.put("PLT", "Asia/Karachi");
map.put("IST", "Asia/Calcutta");
map.put("BST", "Asia/Dhaka");
map.put("VST", "Asia/Saigon");
map.put("CTT", "Asia/Shanghai");
map.put("JST", "Asia/Tokyo");
map.put("ACT", "Australia/Darwin");
map.put("AET", "Australia/Sydney");
map.put("SST", "Pacific/Guadalcanal");
map.put("NST", "Pacific/Auckland");
cZoneIdConversion = map;
}
return map.get(id);
}
|
private static synchronized String getConvertedId(String id) {
Map<String, String> map = cZoneIdConversion;
if (map == null) {
// Backwards compatibility with TimeZone.
map = new HashMap<String, String>();
map.put("GMT", "UTC");
map.put("WET", "WET");
map.put("CET", "CET");
map.put("MET", "CET");
map.put("ECT", "CET");
map.put("EET", "EET");
map.put("MIT", "Pacific/Apia");
map.put("HST", "Pacific/Honolulu"); // JDK 1.1 compatible
map.put("AST", "America/Anchorage");
map.put("PST", "America/Los_Angeles");
map.put("MST", "America/Denver"); // JDK 1.1 compatible
map.put("PNT", "America/Phoenix");
map.put("CST", "America/Chicago");
map.put("EST", "America/New_York"); // JDK 1.1 compatible
map.put("IET", "America/Indiana/Indianapolis");
map.put("PRT", "America/Puerto_Rico");
map.put("CNT", "America/St_Johns");
map.put("AGT", "America/Argentina/Buenos_Aires");
map.put("BET", "America/Sao_Paulo");
map.put("ART", "Africa/Cairo");
map.put("CAT", "Africa/Harare");
map.put("EAT", "Africa/Addis_Ababa");
map.put("NET", "Asia/Yerevan");
map.put("PLT", "Asia/Karachi");
map.put("IST", "Asia/Kolkata");
map.put("BST", "Asia/Dhaka");
map.put("VST", "Asia/Ho_Chi_Minh");
map.put("CTT", "Asia/Shanghai");
map.put("JST", "Asia/Tokyo");
map.put("ACT", "Australia/Darwin");
map.put("AET", "Australia/Sydney");
map.put("SST", "Pacific/Guadalcanal");
map.put("NST", "Pacific/Auckland");
cZoneIdConversion = map;
}
return map.get(id);
}
|
src/main/java/org/joda/time/DateTimeZone.java
|
#112 Incorrect mapping of the MET time zone
|
This timezone is mapped to Asia/Tehran in DateTimeZone. It should be middle europena time.
I know that this bug has been raised before (Incorrect mapping of the MET time zone - ID: 2012274), and there is a comment stating that you won't break backward compatibility to fix this bug.
I disagree that this is a backward compatibility argument
No matter how you look at it, it is a bug.
You could very well state that ALL bugs won't be fixed, because of backward compatibility.
I request again that this bug be fixed.
| 558 | 598 |
Time-24
|
public long computeMillis(boolean resetFields, String text) {
SavedField[] savedFields = iSavedFields;
int count = iSavedFieldsCount;
if (iSavedFieldsShared) {
iSavedFields = savedFields = (SavedField[])iSavedFields.clone();
iSavedFieldsShared = false;
}
sort(savedFields, count);
if (count > 0) {
// alter base year for parsing if first field is month or day
DurationField months = DurationFieldType.months().getField(iChrono);
DurationField days = DurationFieldType.days().getField(iChrono);
DurationField first = savedFields[0].iField.getDurationField();
if (compareReverse(first, months) >= 0 && compareReverse(first, days) <= 0) {
saveField(DateTimeFieldType.year(), iDefaultYear);
return computeMillis(resetFields, text);
}
}
long millis = iMillis;
try {
for (int i = 0; i < count; i++) {
millis = savedFields[i].set(millis, resetFields);
}
} catch (IllegalFieldValueException e) {
if (text != null) {
e.prependMessage("Cannot parse \"" + text + '"');
}
throw e;
}
if (iZone == null) {
millis -= iOffset;
} else {
int offset = iZone.getOffsetFromLocal(millis);
millis -= offset;
if (offset != iZone.getOffset(millis)) {
String message =
"Illegal instant due to time zone offset transition (" + iZone + ')';
if (text != null) {
message = "Cannot parse \"" + text + "\": " + message;
}
throw new IllegalArgumentException(message);
}
}
return millis;
}
|
public long computeMillis(boolean resetFields, String text) {
SavedField[] savedFields = iSavedFields;
int count = iSavedFieldsCount;
if (iSavedFieldsShared) {
iSavedFields = savedFields = (SavedField[])iSavedFields.clone();
iSavedFieldsShared = false;
}
sort(savedFields, count);
if (count > 0) {
// alter base year for parsing if first field is month or day
DurationField months = DurationFieldType.months().getField(iChrono);
DurationField days = DurationFieldType.days().getField(iChrono);
DurationField first = savedFields[0].iField.getDurationField();
if (compareReverse(first, months) >= 0 && compareReverse(first, days) <= 0) {
saveField(DateTimeFieldType.year(), iDefaultYear);
return computeMillis(resetFields, text);
}
}
long millis = iMillis;
try {
for (int i = 0; i < count; i++) {
millis = savedFields[i].set(millis, resetFields);
}
if (resetFields) {
for (int i = 0; i < count; i++) {
millis = savedFields[i].set(millis, i == (count - 1));
}
}
} catch (IllegalFieldValueException e) {
if (text != null) {
e.prependMessage("Cannot parse \"" + text + '"');
}
throw e;
}
if (iZone == null) {
millis -= iOffset;
} else {
int offset = iZone.getOffsetFromLocal(millis);
millis -= offset;
if (offset != iZone.getOffset(millis)) {
String message =
"Illegal instant due to time zone offset transition (" + iZone + ')';
if (text != null) {
message = "Cannot parse \"" + text + "\": " + message;
}
throw new IllegalArgumentException(message);
}
}
return millis;
}
|
src/main/java/org/joda/time/format/DateTimeParserBucket.java
|
#107 Incorrect date parsed when week and month used together
|
I have following code snippet :
DateTimeFormatter dtf = DateTimeFormat.forPattern("xxxxMM'w'ww");
DateTime dt = dtf.parseDateTime("201101w01");
System.out.println(dt);
It should print 2011-01-03 but it is printing 2010-01-04.
Please let me know if I am doing something wrong here.
| 331 | 378 |
Time-25
|
public int getOffsetFromLocal(long instantLocal) {
// get the offset at instantLocal (first estimate)
final int offsetLocal = getOffset(instantLocal);
// adjust instantLocal using the estimate and recalc the offset
final long instantAdjusted = instantLocal - offsetLocal;
final int offsetAdjusted = getOffset(instantAdjusted);
// if the offsets differ, we must be near a DST boundary
if (offsetLocal != offsetAdjusted) {
// we need to ensure that time is always after the DST gap
// this happens naturally for positive offsets, but not for negative
if ((offsetLocal - offsetAdjusted) < 0) {
// if we just return offsetAdjusted then the time is pushed
// back before the transition, whereas it should be
// on or after the transition
long nextLocal = nextTransition(instantAdjusted);
long nextAdjusted = nextTransition(instantLocal - offsetAdjusted);
if (nextLocal != nextAdjusted) {
return offsetLocal;
}
}
}
return offsetAdjusted;
}
|
public int getOffsetFromLocal(long instantLocal) {
// get the offset at instantLocal (first estimate)
final int offsetLocal = getOffset(instantLocal);
// adjust instantLocal using the estimate and recalc the offset
final long instantAdjusted = instantLocal - offsetLocal;
final int offsetAdjusted = getOffset(instantAdjusted);
// if the offsets differ, we must be near a DST boundary
if (offsetLocal != offsetAdjusted) {
// we need to ensure that time is always after the DST gap
// this happens naturally for positive offsets, but not for negative
if ((offsetLocal - offsetAdjusted) < 0) {
// if we just return offsetAdjusted then the time is pushed
// back before the transition, whereas it should be
// on or after the transition
long nextLocal = nextTransition(instantAdjusted);
long nextAdjusted = nextTransition(instantLocal - offsetAdjusted);
if (nextLocal != nextAdjusted) {
return offsetLocal;
}
}
} else if (offsetLocal > 0) {
long prev = previousTransition(instantAdjusted);
if (prev < instantAdjusted) {
int offsetPrev = getOffset(prev);
int diff = offsetPrev - offsetLocal;
if (instantAdjusted - prev <= diff) {
return offsetPrev;
}
}
}
return offsetAdjusted;
}
|
src/main/java/org/joda/time/DateTimeZone.java
|
#90 DateTimeZone.getOffsetFromLocal error during DST transition
|
This may be a failure of my understanding, but the comments in DateTimeZone.getOffsetFromLocal lead me to believe that if an ambiguous local time is given, the offset corresponding to the later of the two possible UTC instants will be returned - i.e. the greater offset.
This doesn't appear to tally with my experience. In fall 2009, America/Los_Angeles changed from -7 to -8 at 2am wall time on November 11. Thus 2am became 1am - so 1:30am is ambiguous. I would therefore expect that constructing a DateTime for November 11th, 1:30am would give an instant corresponding with the later value (i.e. 9:30am UTC). This appears not to be the case:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class TzTest {
public static void main(String[] args) throws Exception {
DateTimeZone zone = DateTimeZone.forID("America/Los_Angeles");
DateTime when1 = new DateTime(2009, 11, 1, 0, 30, 0, 0, zone);
DateTime when2 = new DateTime(2009, 11, 1, 1, 30, 0, 0, zone);
DateTime when3 = new DateTime(2009, 11, 1, 2, 30, 0, 0, zone);
System.out.println(when1);
System.out.println(when2);
System.out.println(when3);
}
}
Results:
2009-11-01T00:30:00.000-07:00 // Correct
2009-11-01T01:30:00.000-07:00 // Should be -08:00
2009-11-01T02:30:00.000-08:00 // Correct
| 879 | 901 |
Time-27
|
private static PeriodFormatter toFormatter(List<Object> elementPairs, boolean notPrinter, boolean notParser) {
if (notPrinter && notParser) {
throw new IllegalStateException("Builder has created neither a printer nor a parser");
}
int size = elementPairs.size();
if (size >= 2 && elementPairs.get(0) instanceof Separator) {
Separator sep = (Separator) elementPairs.get(0);
PeriodFormatter f = toFormatter(elementPairs.subList(2, size), notPrinter, notParser);
sep = sep.finish(f.getPrinter(), f.getParser());
return new PeriodFormatter(sep, sep);
}
Object[] comp = createComposite(elementPairs);
if (notPrinter) {
return new PeriodFormatter(null, (PeriodParser) comp[1]);
} else if (notParser) {
return new PeriodFormatter((PeriodPrinter) comp[0], null);
} else {
return new PeriodFormatter((PeriodPrinter) comp[0], (PeriodParser) comp[1]);
}
}
|
private static PeriodFormatter toFormatter(List<Object> elementPairs, boolean notPrinter, boolean notParser) {
if (notPrinter && notParser) {
throw new IllegalStateException("Builder has created neither a printer nor a parser");
}
int size = elementPairs.size();
if (size >= 2 && elementPairs.get(0) instanceof Separator) {
Separator sep = (Separator) elementPairs.get(0);
if (sep.iAfterParser == null && sep.iAfterPrinter == null) {
PeriodFormatter f = toFormatter(elementPairs.subList(2, size), notPrinter, notParser);
sep = sep.finish(f.getPrinter(), f.getParser());
return new PeriodFormatter(sep, sep);
}
}
Object[] comp = createComposite(elementPairs);
if (notPrinter) {
return new PeriodFormatter(null, (PeriodParser) comp[1]);
} else if (notParser) {
return new PeriodFormatter((PeriodPrinter) comp[0], null);
} else {
return new PeriodFormatter((PeriodPrinter) comp[0], (PeriodParser) comp[1]);
}
}
|
src/main/java/org/joda/time/format/PeriodFormatterBuilder.java
|
#64 Different behaviour of PeriodFormatter
|
PeriodFormatter pfmt2 = pfmtbuilder2.append(ISOPeriodFormat.standard() ).toFormatter(); is not the same as
PeriodFormatterBuilder pfmtbuilder1 = new PeriodFormatterBuilder()
.appendLiteral("P")
.appendYears()
.appendSuffix("Y")
.appendMonths()
.appendSuffix("M")
.appendWeeks()
.appendSuffix("W")
.appendDays()
.appendSuffix("D")
.appendSeparatorIfFieldsAfter("T")
.appendHours()
.appendSuffix("H")
.appendMinutes()
.appendSuffix("M")
.appendSecondsWithOptionalMillis()
.appendSuffix("S");
which is copied from ISOPeriodFormat.standard() method
| 794 | 813 |
Time-4
|
public Partial with(DateTimeFieldType fieldType, int value) {
if (fieldType == null) {
throw new IllegalArgumentException("The field type must not be null");
}
int index = indexOf(fieldType);
if (index == -1) {
DateTimeFieldType[] newTypes = new DateTimeFieldType[iTypes.length + 1];
int[] newValues = new int[newTypes.length];
// find correct insertion point to keep largest-smallest order
int i = 0;
DurationField unitField = fieldType.getDurationType().getField(iChronology);
if (unitField.isSupported()) {
for (; i < iTypes.length; i++) {
DateTimeFieldType loopType = iTypes[i];
DurationField loopUnitField = loopType.getDurationType().getField(iChronology);
if (loopUnitField.isSupported()) {
int compare = unitField.compareTo(loopUnitField);
if (compare > 0) {
break;
} else if (compare == 0) {
DurationField rangeField = fieldType.getRangeDurationType().getField(iChronology);
DurationField loopRangeField = loopType.getRangeDurationType().getField(iChronology);
if (rangeField.compareTo(loopRangeField) > 0) {
break;
}
}
}
}
}
System.arraycopy(iTypes, 0, newTypes, 0, i);
System.arraycopy(iValues, 0, newValues, 0, i);
newTypes[i] = fieldType;
newValues[i] = value;
System.arraycopy(iTypes, i, newTypes, i + 1, newTypes.length - i - 1);
System.arraycopy(iValues, i, newValues, i + 1, newValues.length - i - 1);
// use public constructor to ensure full validation
// this isn't overly efficient, but is safe
Partial newPartial = new Partial(iChronology, newTypes, newValues);
iChronology.validate(newPartial, newValues);
return newPartial;
}
if (value == getValue(index)) {
return this;
}
int[] newValues = getValues();
newValues = getField(index).set(this, index, newValues, value);
return new Partial(this, newValues);
}
|
public Partial with(DateTimeFieldType fieldType, int value) {
if (fieldType == null) {
throw new IllegalArgumentException("The field type must not be null");
}
int index = indexOf(fieldType);
if (index == -1) {
DateTimeFieldType[] newTypes = new DateTimeFieldType[iTypes.length + 1];
int[] newValues = new int[newTypes.length];
// find correct insertion point to keep largest-smallest order
int i = 0;
DurationField unitField = fieldType.getDurationType().getField(iChronology);
if (unitField.isSupported()) {
for (; i < iTypes.length; i++) {
DateTimeFieldType loopType = iTypes[i];
DurationField loopUnitField = loopType.getDurationType().getField(iChronology);
if (loopUnitField.isSupported()) {
int compare = unitField.compareTo(loopUnitField);
if (compare > 0) {
break;
} else if (compare == 0) {
DurationField rangeField = fieldType.getRangeDurationType().getField(iChronology);
DurationField loopRangeField = loopType.getRangeDurationType().getField(iChronology);
if (rangeField.compareTo(loopRangeField) > 0) {
break;
}
}
}
}
}
System.arraycopy(iTypes, 0, newTypes, 0, i);
System.arraycopy(iValues, 0, newValues, 0, i);
newTypes[i] = fieldType;
newValues[i] = value;
System.arraycopy(iTypes, i, newTypes, i + 1, newTypes.length - i - 1);
System.arraycopy(iValues, i, newValues, i + 1, newValues.length - i - 1);
// use public constructor to ensure full validation
// this isn't overly efficient, but is safe
Partial newPartial = new Partial(newTypes, newValues, iChronology);
iChronology.validate(newPartial, newValues);
return newPartial;
}
if (value == getValue(index)) {
return this;
}
int[] newValues = getValues();
newValues = getField(index).set(this, index, newValues, value);
return new Partial(this, newValues);
}
|
src/main/java/org/joda/time/Partial.java
|
Constructing invalid Partials
|
Partials can be constructed by invoking a constructor Partial(DateTimeFieldType[], int[]) or by merging together a set of partials using with, each constructed by calling Partial(DateTimeFieldType, int), e.g.:
Partial a = new Partial(new DateTimeFieldType[] { year(), hourOfDay() }, new int[] { 1, 1});
Partial b = new Partial(year(), 1).with(hourOfDay(), 1);
assert(a == b);
However, the above doesn't work in all cases:
new Partial(new DateTimeFieldType[] { clockhourOfDay(), hourOfDay() }, new int[] { 1, 1}); // throws Types array must not contain duplicate
new Partial(clockhourOfDay(), 1).with(hourOfDay(), 1); // #<Partial [clockhourOfDay=1, hourOfDay=1]>
I suppose the Partials should not allow to be constructed in either case. Is that right?
There's also a related issue (probably stems from the fact that the Partial is invalid):
new Partial(clockhourOfDay(), 1).with(hourOfDay(), 1).isEqual(new Partial(hourOfDay() ,1).with(clockhourOfDay(), 1)) // throws objects must have matching field types
| 426 | 474 |
Time-5
|
public Period normalizedStandard(PeriodType type) {
type = DateTimeUtils.getPeriodType(type);
long millis = getMillis(); // no overflow can happen, even with Integer.MAX_VALUEs
millis += (((long) getSeconds()) * ((long) DateTimeConstants.MILLIS_PER_SECOND));
millis += (((long) getMinutes()) * ((long) DateTimeConstants.MILLIS_PER_MINUTE));
millis += (((long) getHours()) * ((long) DateTimeConstants.MILLIS_PER_HOUR));
millis += (((long) getDays()) * ((long) DateTimeConstants.MILLIS_PER_DAY));
millis += (((long) getWeeks()) * ((long) DateTimeConstants.MILLIS_PER_WEEK));
Period result = new Period(millis, type, ISOChronology.getInstanceUTC());
int years = getYears();
int months = getMonths();
if (years != 0 || months != 0) {
years = FieldUtils.safeAdd(years, months / 12);
months = months % 12;
if (years != 0) {
result = result.withYears(years);
}
if (months != 0) {
result = result.withMonths(months);
}
}
return result;
}
|
public Period normalizedStandard(PeriodType type) {
type = DateTimeUtils.getPeriodType(type);
long millis = getMillis(); // no overflow can happen, even with Integer.MAX_VALUEs
millis += (((long) getSeconds()) * ((long) DateTimeConstants.MILLIS_PER_SECOND));
millis += (((long) getMinutes()) * ((long) DateTimeConstants.MILLIS_PER_MINUTE));
millis += (((long) getHours()) * ((long) DateTimeConstants.MILLIS_PER_HOUR));
millis += (((long) getDays()) * ((long) DateTimeConstants.MILLIS_PER_DAY));
millis += (((long) getWeeks()) * ((long) DateTimeConstants.MILLIS_PER_WEEK));
Period result = new Period(millis, type, ISOChronology.getInstanceUTC());
int years = getYears();
int months = getMonths();
if (years != 0 || months != 0) {
long totalMonths = years * 12L + months;
if (type.isSupported(DurationFieldType.YEARS_TYPE)) {
int normalizedYears = FieldUtils.safeToInt(totalMonths / 12);
result = result.withYears(normalizedYears);
totalMonths = totalMonths - (normalizedYears * 12);
}
if (type.isSupported(DurationFieldType.MONTHS_TYPE)) {
int normalizedMonths = FieldUtils.safeToInt(totalMonths);
result = result.withMonths(normalizedMonths);
totalMonths = totalMonths - normalizedMonths;
}
if (totalMonths != 0) {
throw new UnsupportedOperationException("Unable to normalize as PeriodType is missing either years or months but period has a month/year amount: " + toString());
}
}
return result;
}
|
src/main/java/org/joda/time/Period.java
|
none standard PeriodType without year throws exception
|
Hi.
I tried to get a Period only for months and weeks with following code:
Period p = new Period(new DateTime(startDate.getTime()), new DateTime(endDate.getTime()), PeriodType.forFields(new DurationFieldType[]{DurationFieldType.months(), DurationFieldType.weeks()})).normalizedStandard(PeriodType.forFields(new DurationFieldType[]{DurationFieldType.months(), DurationFieldType.weeks()}));
return p.getMonths();
This throws following exception:
10-17 14:35:50.999: E/AndroidRuntime(1350): java.lang.UnsupportedOperationException: Field is not supported
10-17 14:35:50.999: E/AndroidRuntime(1350): at org.joda.time.PeriodType.setIndexedField(PeriodType.java:690)
10-17 14:35:50.999: E/AndroidRuntime(1350): at org.joda.time.Period.withYears(Period.java:896) 10-17
14:35:50.999: E/AndroidRuntime(1350): at org.joda.time.Period.normalizedStandard(Period.java:1630)
Even removing the year component with .withYearsRemoved() throws the same exception:
this works:
Period p = new Period(new DateTime(startDate.getTime()), new DateTime(endDate.getTime()), PeriodType.standard()).normalizedStandard(PeriodType.standard());
return p.getMonths();
this fails:
Period p = new Period(new DateTime(startDate.getTime()), new DateTime(endDate.getTime()), PeriodType.standard().withYearsRemoved()).normalizedStandard(PeriodType.standard().withYearsRemoved());
return p.getMonths();
| 1,616 | 1,638 |
Time-8
|
public static DateTimeZone forOffsetHoursMinutes(int hoursOffset, int minutesOffset) throws IllegalArgumentException {
if (hoursOffset == 0 && minutesOffset == 0) {
return DateTimeZone.UTC;
}
if (hoursOffset < -23 || hoursOffset > 23) {
throw new IllegalArgumentException("Hours out of range: " + hoursOffset);
}
if (minutesOffset < 0 || minutesOffset > 59) {
throw new IllegalArgumentException("Minutes out of range: " + minutesOffset);
}
int offset = 0;
try {
int hoursInMinutes = hoursOffset * 60;
if (hoursInMinutes < 0) {
minutesOffset = hoursInMinutes - minutesOffset;
} else {
minutesOffset = hoursInMinutes + minutesOffset;
}
offset = FieldUtils.safeMultiply(minutesOffset, DateTimeConstants.MILLIS_PER_MINUTE);
} catch (ArithmeticException ex) {
throw new IllegalArgumentException("Offset is too large");
}
return forOffsetMillis(offset);
}
|
public static DateTimeZone forOffsetHoursMinutes(int hoursOffset, int minutesOffset) throws IllegalArgumentException {
if (hoursOffset == 0 && minutesOffset == 0) {
return DateTimeZone.UTC;
}
if (hoursOffset < -23 || hoursOffset > 23) {
throw new IllegalArgumentException("Hours out of range: " + hoursOffset);
}
if (minutesOffset < -59 || minutesOffset > 59) {
throw new IllegalArgumentException("Minutes out of range: " + minutesOffset);
}
if (hoursOffset > 0 && minutesOffset < 0) {
throw new IllegalArgumentException("Positive hours must not have negative minutes: " + minutesOffset);
}
int offset = 0;
try {
int hoursInMinutes = hoursOffset * 60;
if (hoursInMinutes < 0) {
minutesOffset = hoursInMinutes - Math.abs(minutesOffset);
} else {
minutesOffset = hoursInMinutes + minutesOffset;
}
offset = FieldUtils.safeMultiply(minutesOffset, DateTimeConstants.MILLIS_PER_MINUTE);
} catch (ArithmeticException ex) {
throw new IllegalArgumentException("Offset is too large");
}
return forOffsetMillis(offset);
}
|
src/main/java/org/joda/time/DateTimeZone.java
|
DateTimeZone.forOffsetHoursMinutes cannot handle negative offset < 1 hour
|
DateTimeZone.forOffsetHoursMinutes(h,m) cannot handle negative offset < 1 hour like -0:30 due to argument range checking. I used forOffsetMillis() instead.
This should probably be mentioned in the documentation or negative minutes be accepted.
| 272 | 295 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.