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 = ... | 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 = ... | 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 ... | 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 d... | 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... | 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%93Whit... | 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%93W... | 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 mod... | 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);
... | 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(Doub... | 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... | 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+... | 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+... | 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) {
... | 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) {
... | 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 ta... | 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());
... | 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());
... | 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 varia... | 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
... | 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
... | 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.add... | 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);
... | 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).
Worka... | 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... | 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... | 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
... | 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 c... | 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 or... | 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(... | 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 fr... | 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 fr... | 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 t... | 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 ... | 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++) {
fin... | 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));
... | 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.max... | 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 construc... | 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++) {
... | 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++) {
... | 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.... | 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 Univa... | 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
... | 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
... | 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
... | 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
... | 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)
{
... | 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.asser... | 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)... | 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++) {
... | 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:
... | 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 do... | 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 do... | 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;
==============... | 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;
... | protected void iterateSimplex(final Comparator<RealPointValuePair> comparator)
throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {
final RealConvergenceChecker checker = getConvergenceChecker();
while (true) {
incrementIterationsCounter();
// save the ori... | 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;
}
... | 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)) {
... | 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 shou... | 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... | protected RealPointValuePair getSolution() {
double[] coefficients = new double[getOriginalNumDecisionVariables()];
Integer basicRow =
getBasicRow(getNumObjectiveFunctions() + getOriginalNumDecisionVariables());
double mostNegative = basicRow == null ? 0 : getEntry(basicRow, getRhsOffset());
Set... | 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 pla... | 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 compar... | 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 pla... | 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);
Syst... | 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
// ove... | 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
... | 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 == ... | 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
denominatorD... | 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... | 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... | 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.Bren... | 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... | 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;
... | 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
.getArgumentMatcherSto... | public Object handle(Invocation invocation) throws Throwable {
if (invocationContainerImpl.hasAnswersForStubbing()) {
// stubbing voids with stubVoid() or doAnswer() style
InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(mockingProgress
.getArgumentMatcherSto... | 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() {
... | 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() {
... | 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 colle... | 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 colle... | 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... | 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().ge... | 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().ge... | 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 ... | 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().default... | 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.toStri... | 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:
someOt... | 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);
... | 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);
... | 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.... | @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.... | 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 in... | 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();
/* Av... | 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... | 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 i... | 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);
}
... | public void validate(Answer<?> answer, Invocation invocation) {
if (answer instanceof ThrowsException) {
validateException((ThrowsException) answer, invocation);
}
if (answer instanceof Returns) {
validateReturnValue((Returns) 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.
A... | 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[] act... | protected void registerTypeVariablesOn(Type classType) {
if (!(classType instanceof ParameterizedType)) {
return;
}
ParameterizedType parameterizedType = (ParameterizedType) classType;
TypeVariable[] typeParameters = ((Class<?>) parameterizedType.getRawType()).getTypeParameters();
Type[] act... | 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(firstNamedMe... | 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 mo... | 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(Dat... | 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(iso... | 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 ov... | 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;
... | 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... | 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.getChron... | 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.getChron... | 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 2... | 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 instan... | 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 + ... | 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.ge... | 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 ba... | 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 ba... | 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 ran... | 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 = g... | 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 = g... | 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(201... | 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;
}
}
}
... | 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 = DateTimeFo... | 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 w... | 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("HS... | 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"... | 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 c... | 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);
... | 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);
... | 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 = g... | 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 = g... | 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. ... | 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... | 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... | 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()
.appendS... | 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];
... | 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];
... | 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 P... | 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) D... | 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) D... | 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 DurationF... | 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:... | 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:... | 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.