defects4j_project stringclasses 12
values | defects4j_bug_id stringlengths 1 3 | file_path stringlengths 38 95 | bug_start_line stringlengths 1 4 | bug_end_line stringlengths 2 4 | issue_title stringlengths 13 150 | issue_description stringlengths 4 8.74k | original_src stringlengths 44 9k | original_src_wo_comments stringlengths 38 5.83k | fixed_src stringlengths 40 9.55k | fixed_src_wo_comments stringlengths 34 5.76k |
|---|---|---|---|---|---|---|---|---|---|---|
Math | 19 | src/main/java/org/apache/commons/math3/optimization/direct/CMAESOptimizer.java | 504 | 561 | Wide bounds to CMAESOptimizer result in NaN parameters passed to fitness function | If you give large values as lower/upper bounds (for example -Double.MAX_VALUE as a lower bound), the optimizer can call the fitness function with parameters set to NaN. My guess is this is due to FitnessFunction.encode/decode generating NaN when normalizing/denormalizing parameters. For example, if the difference bet... | private void checkParameters() {
final double[] init = getStartPoint();
final double[] lB = getLowerBound();
final double[] uB = getUpperBound();
// Checks whether there is at least one finite bound value.
boolean hasFiniteBounds = false;
for (int i = 0; i < lB.length; i... | private void checkParameters ( ) { final double [ ] init = getStartPoint ( ) ; final double [ ] lB = getLowerBound ( ) ; final double [ ] uB = getUpperBound ( ) ; boolean hasFiniteBounds = false ; for ( int i = 0 ; i < lB . length ; i ++ ) { if ( ! Double . isInfinite ( lB [ i ] ) || ! Double . isInfinite ( uB [ i ] ) ... | private void checkParameters() {
final double[] init = getStartPoint();
final double[] lB = getLowerBound();
final double[] uB = getUpperBound();
// Checks whether there is at least one finite bound value.
boolean hasFiniteBounds = false;
for (int i = 0; i < lB.length; i... | private void checkParameters ( ) { final double [ ] init = getStartPoint ( ) ; final double [ ] lB = getLowerBound ( ) ; final double [ ] uB = getUpperBound ( ) ; boolean hasFiniteBounds = false ; for ( int i = 0 ; i < lB . length ; i ++ ) { if ( ! Double . isInfinite ( lB [ i ] ) || ! Double . isInfinite ( uB [ i ] ) ... |
Compress | 16 | src/main/java/org/apache/commons/compress/archivers/ArchiveStreamFactory.java | 197 | 258 | Too relaxed tar detection in ArchiveStreamFactory | The relaxed tar detection logic added in COMPRESS-117 unfortunately matches also some non-tar files like a [test AIFF file|https://svn.apache.org/repos/asf/tika/trunk/tika-parsers/src/test/resources/test-documents/testAIFF.aif] that Apache Tika uses. It would be good to improve the detection heuristics to still match f... | public ArchiveInputStream createArchiveInputStream(final InputStream in)
throws ArchiveException {
if (in == null) {
throw new IllegalArgumentException("Stream must not be null.");
}
if (!in.markSupported()) {
throw new IllegalArgumentException("Mark is not s... | public ArchiveInputStream createArchiveInputStream ( final InputStream in ) throws ArchiveException { if ( in == null ) { throw new IllegalArgumentException ( "Stream must not be null." ) ; } if ( ! in . markSupported ( ) ) { throw new IllegalArgumentException ( "Mark is not supported." ) ; } final byte [ ] signature =... | public ArchiveInputStream createArchiveInputStream(final InputStream in)
throws ArchiveException {
if (in == null) {
throw new IllegalArgumentException("Stream must not be null.");
}
if (!in.markSupported()) {
throw new IllegalArgumentException("Mark is not s... | public ArchiveInputStream createArchiveInputStream ( final InputStream in ) throws ArchiveException { if ( in == null ) { throw new IllegalArgumentException ( "Stream must not be null." ) ; } if ( ! in . markSupported ( ) ) { throw new IllegalArgumentException ( "Mark is not supported." ) ; } final byte [ ] signature =... |
Compress | 41 | src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java | 219 | 324 | ZipArchiveInputStream.getNextZipEntry() should differentiate between "invalid entry encountered" and "no more entries" | ZipArchiveInputStream.getNextZipEntry() currently returns null if an invalid entry is encountered. Thus, it's not possible to differentiate between "no more entries" and "invalid entry encountered" conditions.
Instead, it should throw an exception if an invalid entry is encountered.
I've created a test case and fix.... | public ZipArchiveEntry getNextZipEntry() throws IOException {
boolean firstEntry = true;
if (closed || hitCentralDirectory) {
return null;
}
if (current != null) {
closeEntry();
firstEntry = false;
}
try {
if (firstEntry) {... | public ZipArchiveEntry getNextZipEntry ( ) throws IOException { boolean firstEntry = true ; if ( closed || hitCentralDirectory ) { return null ; } if ( current != null ) { closeEntry ( ) ; firstEntry = false ; } try { if ( firstEntry ) { readFirstLocalFileHeader ( LFH_BUF ) ; } else { readFully ( LFH_BUF ) ; } } catch ... | public ZipArchiveEntry getNextZipEntry() throws IOException {
boolean firstEntry = true;
if (closed || hitCentralDirectory) {
return null;
}
if (current != null) {
closeEntry();
firstEntry = false;
}
try {
if (firstEntry) {... | public ZipArchiveEntry getNextZipEntry ( ) throws IOException { boolean firstEntry = true ; if ( closed || hitCentralDirectory ) { return null ; } if ( current != null ) { closeEntry ( ) ; firstEntry = false ; } try { if ( firstEntry ) { readFirstLocalFileHeader ( LFH_BUF ) ; } else { readFully ( LFH_BUF ) ; } } catch ... |
JacksonDatabind | 93 | src/main/java/com/fasterxml/jackson/databind/jsontype/impl/SubTypeValidator.java | 67 | 99 | `NullPointerException` in `SubTypeValidator.validateSubType` when validating Spring interface | In jackson-databind-2.8.11 jackson-databind-2.9.3 and jackson-databind-2.9.4-SNAPSHOT `SubTypeValidator.validateSubType` fails with a `NullPointerException` if the `JavaType.getRawClass()` is an interface that starts with `org.springframework.` For example, the following will fail:
```java
package org.springframew... | public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException
{
// There are certain nasty classes that could cause problems, mostly
// via default typing -- catch them here.
final Class<?> raw = type.getRawClass();
String full = raw.getName();
... | public void validateSubType ( DeserializationContext ctxt , JavaType type ) throws JsonMappingException { final Class < ? > raw = type . getRawClass ( ) ; String full = raw . getName ( ) ; main_check : do { if ( _cfgIllegalClassNames . contains ( full ) ) { break ; } if ( full . startsWith ( PREFIX_STRING ) ) { for ( C... | public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException
{
// There are certain nasty classes that could cause problems, mostly
// via default typing -- catch them here.
final Class<?> raw = type.getRawClass();
String full = raw.getName();
... | public void validateSubType ( DeserializationContext ctxt , JavaType type ) throws JsonMappingException { final Class < ? > raw = type . getRawClass ( ) ; String full = raw . getName ( ) ; main_check : do { if ( _cfgIllegalClassNames . contains ( full ) ) { break ; } if ( ! raw . isInterface ( ) && full . startsWith ( ... |
Math | 2 | src/main/java/org/apache/commons/math3/distribution/HypergeometricDistribution.java | 267 | 269 | HypergeometricDistribution.sample suffers from integer overflow | Hi, I have an application which broke when ported from commons math 2.2 to 3.2. It looks like the HypergeometricDistribution.sample() method doesn't work as well as it used to with large integer values -- the example code below should return a sample between 0 and 50, but usually returns -50.
{code}
import org.apache.... | public double getNumericalMean() {
return (double) (getSampleSize() * getNumberOfSuccesses()) / (double) getPopulationSize();
} | public double getNumericalMean ( ) { return ( double ) ( getSampleSize ( ) * getNumberOfSuccesses ( ) ) / ( double ) getPopulationSize ( ) ; } | public double getNumericalMean() {
return getSampleSize() * (getNumberOfSuccesses() / (double) getPopulationSize());
} | public double getNumericalMean ( ) { return getSampleSize ( ) * ( getNumberOfSuccesses ( ) / ( double ) getPopulationSize ( ) ) ; } |
Math | 58 | src/main/java/org/apache/commons/math/optimization/fitting/GaussianFitter.java | 119 | 122 | GaussianFitter Unexpectedly Throws NotStrictlyPositiveException | Running the following:
double[] observations =
{
1.1143831578403364E-29,
4.95281403484594E-28,
1.1171347211930288E-26,
1.7044813962636277E-25,
1.9784716574832164E-24,
1.8630236407866774E-23,
1.4820532905097742E-22,
1.0241963854632831E-21... | public double[] fit() {
final double[] guess = (new ParameterGuesser(getObservations())).guess();
return fit(new Gaussian.Parametric(), guess);
} | public double [ ] fit ( ) { final double [ ] guess = ( new ParameterGuesser ( getObservations ( ) ) ) . guess ( ) ; return fit ( new Gaussian . Parametric ( ) , guess ) ; } | public double[] fit() {
final double[] guess = (new ParameterGuesser(getObservations())).guess();
return fit(guess);
} | public double [ ] fit ( ) { final double [ ] guess = ( new ParameterGuesser ( getObservations ( ) ) ) . guess ( ) ; return fit ( guess ) ; } |
JacksonDatabind | 85 | src/main/java/com/fasterxml/jackson/databind/ser/std/DateTimeSerializerBase.java | 48 | 95 | `DateTimeSerializerBase` ignores configured date format when creating contextual | `DateTimeSerializerBase#createContextual` creates a new serializer with `StdDateFormat.DATE_FORMAT_STR_ISO8601` format instead of re-using the actual format that may have been specified on the configuration. See the following code:
```
final String pattern = format.hasPattern()
... | @Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property) throws JsonMappingException
{
if (property == null) {
return this;
}
JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
... | @ Override public JsonSerializer < ? > createContextual ( SerializerProvider serializers , BeanProperty property ) throws JsonMappingException { if ( property == null ) { return this ; } JsonFormat . Value format = findFormatOverrides ( serializers , property , handledType ( ) ) ; if ( format == null ) { return this ; ... | @Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property) throws JsonMappingException
{
if (property == null) {
return this;
}
JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
... | @ Override public JsonSerializer < ? > createContextual ( SerializerProvider serializers , BeanProperty property ) throws JsonMappingException { if ( property == null ) { return this ; } JsonFormat . Value format = findFormatOverrides ( serializers , property , handledType ( ) ) ; if ( format == null ) { return this ; ... |
JacksonDatabind | 1 | src/main/java/com/fasterxml/jackson/databind/ser/BeanPropertyWriter.java | 582 | 624 | NULL values are duplicated when serializing as array [via @JsonFormat(shape = JsonFormat.Shape.ARRAY)] | Example:
``` java
public class TestOuter {
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
public ArrayList<TestInner> array;
public TestOuter() {
this.array = new ArrayList<TestInner>();
this.array.add(new TestInner(1, "one"));
this.array.add(new TestInner(0, null));
}
priva... | public void serializeAsColumn(Object bean, JsonGenerator jgen, SerializerProvider prov)
throws Exception
{
Object value = get(bean);
if (value == null) { // nulls need specialized handling
if (_nullSerializer != null) {
_nullSerializer.serialize(null, jgen, prov);... | public void serializeAsColumn ( Object bean , JsonGenerator jgen , SerializerProvider prov ) throws Exception { Object value = get ( bean ) ; if ( value == null ) { if ( _nullSerializer != null ) { _nullSerializer . serialize ( null , jgen , prov ) ; } else { jgen . writeNull ( ) ; } } JsonSerializer < Object > ser = _... | public void serializeAsColumn(Object bean, JsonGenerator jgen, SerializerProvider prov)
throws Exception
{
Object value = get(bean);
if (value == null) { // nulls need specialized handling
if (_nullSerializer != null) {
_nullSerializer.serialize(null, jgen, prov);... | public void serializeAsColumn ( Object bean , JsonGenerator jgen , SerializerProvider prov ) throws Exception { Object value = get ( bean ) ; if ( value == null ) { if ( _nullSerializer != null ) { _nullSerializer . serialize ( null , jgen , prov ) ; } else { jgen . writeNull ( ) ; } return ; } JsonSerializer < Object ... |
Math | 74 | src/main/java/org/apache/commons/math/ode/nonstiff/EmbeddedRungeKuttaIntegrator.java | 191 | 359 | Wrong parameter for first step size guess for Embedded Runge Kutta methods | In a space application using DOP853 i detected what seems to be a bad parameter in the call to the method initializeStep of class AdaptiveStepsizeIntegrator.
Here, DormandPrince853Integrator is a subclass for EmbeddedRungeKuttaIntegrator which perform the call to initializeStep at the beginning of its method integrat... | @Override
public double integrate(final FirstOrderDifferentialEquations equations,
final double t0, final double[] y0,
final double t, final double[] y)
throws DerivativeException, IntegratorException {
sanityChecks(equations, t0, y0, t, y);
setEquations(... | @ Override public double integrate ( final FirstOrderDifferentialEquations equations , final double t0 , final double [ ] y0 , final double t , final double [ ] y ) throws DerivativeException , IntegratorException { sanityChecks ( equations , t0 , y0 , t , y ) ; setEquations ( equations ) ; resetEvaluations ( ) ; final... | @Override
public double integrate(final FirstOrderDifferentialEquations equations,
final double t0, final double[] y0,
final double t, final double[] y)
throws DerivativeException, IntegratorException {
sanityChecks(equations, t0, y0, t, y);
setEquations(... | @ Override public double integrate ( final FirstOrderDifferentialEquations equations , final double t0 , final double [ ] y0 , final double t , final double [ ] y ) throws DerivativeException , IntegratorException { sanityChecks ( equations , t0 , y0 , t , y ) ; setEquations ( equations ) ; resetEvaluations ( ) ; final... |
JacksonCore | 6 | src/main/java/com/fasterxml/jackson/core/JsonPointer.java | 185 | 206 | `JsonPointer` should not consider "00" to be valid index | Although `00` can be parsed as `0` in some cases, it is not a valid JSON number; and is also not legal numeric index for JSON Pointer. As such, `JsonPointer` class should ensure it can only match property name "00" and not array index.
| private final static int _parseIndex(String str) {
final int len = str.length();
// [core#133]: beware of super long indexes; assume we never
// have arrays over 2 billion entries so ints are fine.
if (len == 0 || len > 10) {
return -1;
}
// [core#176]: no lea... | private final static int _parseIndex ( String str ) { final int len = str . length ( ) ; if ( len == 0 || len > 10 ) { return - 1 ; } for ( int i = 0 ; i < len ; ++ i ) { char c = str . charAt ( i ) ; if ( c > '9' || c < '0' ) { return - 1 ; } } if ( len == 10 ) { long l = NumberInput . parseLong ( str ) ; if ( l > Int... | private final static int _parseIndex(String str) {
final int len = str.length();
// [core#133]: beware of super long indexes; assume we never
// have arrays over 2 billion entries so ints are fine.
if (len == 0 || len > 10) {
return -1;
}
// [core#176]: no lea... | private final static int _parseIndex ( String str ) { final int len = str . length ( ) ; if ( len == 0 || len > 10 ) { return - 1 ; } char c = str . charAt ( 0 ) ; if ( c <= '0' ) { return ( len == 1 && c == '0' ) ? 0 : - 1 ; } if ( c > '9' ) { return - 1 ; } for ( int i = 1 ; i < len ; ++ i ) { c = str . charAt ( i ) ... |
JacksonDatabind | 46 | src/main/java/com/fasterxml/jackson/databind/type/ReferenceType.java | 150 | 158 | Incorrect signature for generic type via `JavaType.getGenericSignature | (see https://github.com/FasterXML/jackson-modules-base/issues/8 for background)
It looks like generic signature generation is missing one closing `>` character to produce:
```
()Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;;
```
instead of expected
```
()Ljava/util/concurrent/atomic/AtomicReferenc... | @Override
public StringBuilder getGenericSignature(StringBuilder sb)
{
_classSignature(_class, sb, false);
sb.append('<');
sb = _referencedType.getGenericSignature(sb);
sb.append(';');
return sb;
} | @ Override public StringBuilder getGenericSignature ( StringBuilder sb ) { _classSignature ( _class , sb , false ) ; sb . append ( '<' ) ; sb = _referencedType . getGenericSignature ( sb ) ; sb . append ( ';' ) ; return sb ; } | @Override
public StringBuilder getGenericSignature(StringBuilder sb)
{
_classSignature(_class, sb, false);
sb.append('<');
sb = _referencedType.getGenericSignature(sb);
sb.append(">;");
return sb;
} | @ Override public StringBuilder getGenericSignature ( StringBuilder sb ) { _classSignature ( _class , sb , false ) ; sb . append ( '<' ) ; sb = _referencedType . getGenericSignature ( sb ) ; sb . append ( ">;" ) ; return sb ; } |
Math | 23 | src/main/java/org/apache/commons/math3/optimization/univariate/BrentOptimizer.java | 114 | 281 | "BrentOptimizer" not always reporting the best point | {{BrentOptimizer}} (package "o.a.c.m.optimization.univariate") does not check that the point it is going to return is indeed the best one it has encountered. Indeed, the last evaluated point might be slightly worse than the one before last. | @Override
protected UnivariatePointValuePair doOptimize() {
final boolean isMinim = getGoalType() == GoalType.MINIMIZE;
final double lo = getMin();
final double mid = getStartValue();
final double hi = getMax();
// Optional additional convergence criteria.
final Conv... | @ Override protected UnivariatePointValuePair doOptimize ( ) { final boolean isMinim = getGoalType ( ) == GoalType . MINIMIZE ; final double lo = getMin ( ) ; final double mid = getStartValue ( ) ; final double hi = getMax ( ) ; final ConvergenceChecker < UnivariatePointValuePair > checker = getConvergenceChecker ( ) ;... | @Override
protected UnivariatePointValuePair doOptimize() {
final boolean isMinim = getGoalType() == GoalType.MINIMIZE;
final double lo = getMin();
final double mid = getStartValue();
final double hi = getMax();
// Optional additional convergence criteria.
final Conv... | @ Override protected UnivariatePointValuePair doOptimize ( ) { final boolean isMinim = getGoalType ( ) == GoalType . MINIMIZE ; final double lo = getMin ( ) ; final double mid = getStartValue ( ) ; final double hi = getMax ( ) ; final ConvergenceChecker < UnivariatePointValuePair > checker = getConvergenceChecker ( ) ;... |
JacksonDatabind | 102 | src/main/java/com/fasterxml/jackson/databind/ser/std/DateTimeSerializerBase.java | 61 | 136 | Cannot set custom format for `SqlDateSerializer` globally | Version: 2.9.5
After https://github.com/FasterXML/jackson-databind/issues/219 was fixed, the default format for `java.sql.Date` serialization switched from string to numeric, following the default value of `WRITE_DATES_AS_TIMESTAMPS`.
In order to prevent breaks, I want `java.sql.Date` to serialize as a string, wi... | @Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property) throws JsonMappingException
{
// Note! Should not skip if `property` null since that'd skip check
// for config overrides, in case of root value
if (property == null) {
... | @ Override public JsonSerializer < ? > createContextual ( SerializerProvider serializers , BeanProperty property ) throws JsonMappingException { if ( property == null ) { return this ; } JsonFormat . Value format = findFormatOverrides ( serializers , property , handledType ( ) ) ; if ( format == null ) { return this ; ... | @Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property) throws JsonMappingException
{
// Note! Should not skip if `property` null since that'd skip check
// for config overrides, in case of root value
JsonFormat.Value format ... | @ Override public JsonSerializer < ? > createContextual ( SerializerProvider serializers , BeanProperty property ) throws JsonMappingException { JsonFormat . Value format = findFormatOverrides ( serializers , property , handledType ( ) ) ; if ( format == null ) { return this ; } JsonFormat . Shape shape = format . getS... |
JacksonDatabind | 11 | src/main/java/com/fasterxml/jackson/databind/type/TypeFactory.java | 889 | 930 | Problem resolving locally declared generic type | (reported by Hal H)
Case like:
``` java
class Something {
public <T extends Ruleform> T getEntity()
public <T extends Ruleform> void setEntity(T entity)
}
```
appears to fail on deserialization.
| protected JavaType _fromVariable(TypeVariable<?> type, TypeBindings context)
{
final String name = type.getName();
// 19-Mar-2015: Without context, all we can check are bounds.
if (context == null) {
// And to prevent infinite loops, now need this:
return _unknownType... | protected JavaType _fromVariable ( TypeVariable < ? > type , TypeBindings context ) { final String name = type . getName ( ) ; if ( context == null ) { return _unknownType ( ) ; } else { JavaType actualType = context . findType ( name ) ; if ( actualType != null ) { return actualType ; } } Type [ ] bounds = type . getB... | protected JavaType _fromVariable(TypeVariable<?> type, TypeBindings context)
{
final String name = type.getName();
// 19-Mar-2015: Without context, all we can check are bounds.
if (context == null) {
// And to prevent infinite loops, now need this:
context = new TypeB... | protected JavaType _fromVariable ( TypeVariable < ? > type , TypeBindings context ) { final String name = type . getName ( ) ; if ( context == null ) { context = new TypeBindings ( this , ( Class < ? > ) null ) ; } else { JavaType actualType = context . findType ( name , false ) ; if ( actualType != null ) { return act... |
Cli | 4 | src/java/org/apache/commons/cli/Parser.java | 290 | 309 | PosixParser interupts "-target opt" as "-t arget opt" | This was posted on the Commons-Developer list and confirmed as a bug.
> Is this a bug? Or am I using this incorrectly?
> I have an option with short and long values. Given code that is
> essentially what is below, with a PosixParser I see results as
> follows:
>
> A command line with just "-t" prints out the resu... | private void checkRequiredOptions()
throws MissingOptionException
{
// if there are required options that have not been
// processsed
if (requiredOptions.size() > 0)
{
Iterator iter = requiredOptions.iterator();
StringBuffer buff = new StringBuffer();
... | private void checkRequiredOptions ( ) throws MissingOptionException { if ( requiredOptions . size ( ) > 0 ) { Iterator iter = requiredOptions . iterator ( ) ; StringBuffer buff = new StringBuffer ( ) ; while ( iter . hasNext ( ) ) { buff . append ( iter . next ( ) ) ; } throw new MissingOptionException ( buff . toStrin... | private void checkRequiredOptions()
throws MissingOptionException
{
// if there are required options that have not been
// processsed
if (requiredOptions.size() > 0)
{
Iterator iter = requiredOptions.iterator();
StringBuffer buff = new StringBuffer("Mi... | private void checkRequiredOptions ( ) throws MissingOptionException { if ( requiredOptions . size ( ) > 0 ) { Iterator iter = requiredOptions . iterator ( ) ; StringBuffer buff = new StringBuffer ( "Missing required option" ) ; buff . append ( requiredOptions . size ( ) == 1 ? "" : "s" ) ; buff . append ( ": " ) ; whil... |
Codec | 9 | src/java/org/apache/commons/codec/binary/Base64.java | 822 | 837 | Base64.encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) throws IAE for valid maxResultSize if isChunked is false | If isChunked is false, Base64.encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) throws IAE for valid maxResultSize.
Test case and fix will be applied shortly. | public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) {
if (binaryData == null || binaryData.length == 0) {
return binaryData;
}
long len = getEncodeLength(binaryData, MIME_CHUNK_SIZE, CHUNK_SEPARATOR);
if (len > maxResul... | public static byte [ ] encodeBase64 ( byte [ ] binaryData , boolean isChunked , boolean urlSafe , int maxResultSize ) { if ( binaryData == null || binaryData . length == 0 ) { return binaryData ; } long len = getEncodeLength ( binaryData , MIME_CHUNK_SIZE , CHUNK_SEPARATOR ) ; if ( len > maxResultSize ) { throw new Ill... | public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) {
if (binaryData == null || binaryData.length == 0) {
return binaryData;
}
long len = getEncodeLength(binaryData, isChunked ? MIME_CHUNK_SIZE : 0, CHUNK_SEPARATOR);
if... | public static byte [ ] encodeBase64 ( byte [ ] binaryData , boolean isChunked , boolean urlSafe , int maxResultSize ) { if ( binaryData == null || binaryData . length == 0 ) { return binaryData ; } long len = getEncodeLength ( binaryData , isChunked ? MIME_CHUNK_SIZE : 0 , CHUNK_SEPARATOR ) ; if ( len > maxResultSize )... |
JacksonCore | 26 | src/main/java/com/fasterxml/jackson/core/json/async/NonBlockingJsonParser.java | 87 | 112 | Non-blocking parser reports incorrect locations when fed with non-zero offset | When feeding a non-blocking parser, the input array offset leaks into the offsets reported by `getCurrentLocation()` and `getTokenLocation()`.
For example, feeding with an offset of 7 yields tokens whose reported locations are 7 greater than they should be. Likewise the current location reported by the parser is 7 g... | @Override
public void feedInput(byte[] buf, int start, int end) throws IOException
{
// Must not have remaining input
if (_inputPtr < _inputEnd) {
_reportError("Still have %d undecoded bytes, should not call 'feedInput'", _inputEnd - _inputPtr);
}
if (end < start) {
... | @ Override public void feedInput ( byte [ ] buf , int start , int end ) throws IOException { if ( _inputPtr < _inputEnd ) { _reportError ( "Still have %d undecoded bytes, should not call 'feedInput'" , _inputEnd - _inputPtr ) ; } if ( end < start ) { _reportError ( "Input end (%d) may not be before start (%d)" , end , ... | @Override
public void feedInput(byte[] buf, int start, int end) throws IOException
{
// Must not have remaining input
if (_inputPtr < _inputEnd) {
_reportError("Still have %d undecoded bytes, should not call 'feedInput'", _inputEnd - _inputPtr);
}
if (end < start) {
... | @ Override public void feedInput ( byte [ ] buf , int start , int end ) throws IOException { if ( _inputPtr < _inputEnd ) { _reportError ( "Still have %d undecoded bytes, should not call 'feedInput'" , _inputEnd - _inputPtr ) ; } if ( end < start ) { _reportError ( "Input end (%d) may not be before start (%d)" , end , ... |
Mockito | 5 | src/org/mockito/internal/verification/VerificationOverTimeImpl.java | 75 | 99 | Mockito 1.10.x timeout verification needs JUnit classes (VerifyError, NoClassDefFoundError) | If JUnit is not on the classpath and mockito is version 1.10.x (as of now 1.10.1 up to 1.10.19) and the code is using the timeout verification which is not supposed to be related to JUnit, then the JVM may fail with a `VerifyError` or a `NoClassDefFoundError`.
This issue has been reported on the [mailing list](https:/... | public void verify(VerificationData data) {
AssertionError error = null;
timer.start();
while (timer.isCounting()) {
try {
delegate.verify(data);
if (returnOnSuccess) {
return;
} else {
error = ... | public void verify ( VerificationData data ) { AssertionError error = null ; timer . start ( ) ; while ( timer . isCounting ( ) ) { try { delegate . verify ( data ) ; if ( returnOnSuccess ) { return ; } else { error = null ; } } catch ( MockitoAssertionError e ) { error = handleVerifyException ( e ) ; } catch ( org . m... | public void verify(VerificationData data) {
AssertionError error = null;
timer.start();
while (timer.isCounting()) {
try {
delegate.verify(data);
if (returnOnSuccess) {
return;
} else {
error = ... | public void verify ( VerificationData data ) { AssertionError error = null ; timer . start ( ) ; while ( timer . isCounting ( ) ) { try { delegate . verify ( data ) ; if ( returnOnSuccess ) { return ; } else { error = null ; } } catch ( MockitoAssertionError e ) { error = handleVerifyException ( e ) ; } catch ( Asserti... |
JacksonDatabind | 50 | src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializer.java | 376 | 474 | `@JsonIdentityInfo` deserialization fails with combination of forward references, `@JsonCreator` | As a follow-up to bug #1255, the patch I provided exposes related deserialization problems.
I have attached a small project ('jackson-test.zip') to demonstrate these issues. When run with both patches from #1255, the output is provided in the attached 'both.txt'. When run with just the first patch from #1255, the outpu... | @Override
@SuppressWarnings("resource")
protected Object _deserializeUsingPropertyBased(final JsonParser p, final DeserializationContext ctxt)
throws IOException
{
final PropertyBasedCreator creator = _propertyBasedCreator;
PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, ... | @ Override @ SuppressWarnings ( "resource" ) protected Object _deserializeUsingPropertyBased ( final JsonParser p , final DeserializationContext ctxt ) throws IOException { final PropertyBasedCreator creator = _propertyBasedCreator ; PropertyValueBuffer buffer = creator . startBuilding ( p , ctxt , _objectIdReader ) ; ... | @Override
@SuppressWarnings("resource")
protected Object _deserializeUsingPropertyBased(final JsonParser p, final DeserializationContext ctxt)
throws IOException
{
final PropertyBasedCreator creator = _propertyBasedCreator;
PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, ... | @ Override @ SuppressWarnings ( "resource" ) protected Object _deserializeUsingPropertyBased ( final JsonParser p , final DeserializationContext ctxt ) throws IOException { final PropertyBasedCreator creator = _propertyBasedCreator ; PropertyValueBuffer buffer = creator . startBuilding ( p , ctxt , _objectIdReader ) ; ... |
JacksonDatabind | 27 | src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializer.java | 773 | 857 | Problem deserializing External Type Id if type id comes before POJO | (note: seems to be similar or related to https://github.com/FasterXML/jackson-module-afterburner/issues/58)
With 2.6, looks like handling of External Type Id is broken in some rare (?) cases; existing unit tests did not catch this. At this point I am speculating this is due to some refactoring, or change to use more e... | @SuppressWarnings("resource")
protected Object deserializeUsingPropertyBasedWithExternalTypeId(JsonParser p, DeserializationContext ctxt)
throws IOException
{
final ExternalTypeHandler ext = _externalTypeIdHandler.start();
final PropertyBasedCreator creator = _propertyBasedCreator;
... | @ SuppressWarnings ( "resource" ) protected Object deserializeUsingPropertyBasedWithExternalTypeId ( JsonParser p , DeserializationContext ctxt ) throws IOException { final ExternalTypeHandler ext = _externalTypeIdHandler . start ( ) ; final PropertyBasedCreator creator = _propertyBasedCreator ; PropertyValueBuffer buf... | @SuppressWarnings("resource")
protected Object deserializeUsingPropertyBasedWithExternalTypeId(JsonParser p, DeserializationContext ctxt)
throws IOException
{
final ExternalTypeHandler ext = _externalTypeIdHandler.start();
final PropertyBasedCreator creator = _propertyBasedCreator;
... | @ SuppressWarnings ( "resource" ) protected Object deserializeUsingPropertyBasedWithExternalTypeId ( JsonParser p , DeserializationContext ctxt ) throws IOException { final ExternalTypeHandler ext = _externalTypeIdHandler . start ( ) ; final PropertyBasedCreator creator = _propertyBasedCreator ; PropertyValueBuffer buf... |
Cli | 14 | src/java/org/apache/commons/cli2/option/GroupImpl.java | 237 | 282 | adding a FileValidator results in ClassCastException in parser.parseAndHelp(args) | When I add a FileValidator.getExistingFileInstance() to an Argument, I get a ClassCastException when I parse args.
Below is a testcase invoke with
java org.apache.commons.cli2.issues.CLI2Sample -classpath commons-cli-2.0-SNAPSHOT.jar --file-name path-to-an-existing-file
Run it and you get:
Exception in thread "m... | public void validate(final WriteableCommandLine commandLine)
throws OptionException {
// number of options found
int present = 0;
// reference to first unexpected option
Option unexpected = null;
for (final Iterator i = options.iterator(); i.hasNext();) {
fi... | public void validate ( final WriteableCommandLine commandLine ) throws OptionException { int present = 0 ; Option unexpected = null ; for ( final Iterator i = options . iterator ( ) ; i . hasNext ( ) ; ) { final Option option = ( Option ) i . next ( ) ; boolean validate = option . isRequired ( ) || option instanceof Gr... | public void validate(final WriteableCommandLine commandLine)
throws OptionException {
// number of options found
int present = 0;
// reference to first unexpected option
Option unexpected = null;
for (final Iterator i = options.iterator(); i.hasNext();) {
fi... | public void validate ( final WriteableCommandLine commandLine ) throws OptionException { int present = 0 ; Option unexpected = null ; for ( final Iterator i = options . iterator ( ) ; i . hasNext ( ) ; ) { final Option option = ( Option ) i . next ( ) ; boolean validate = option . isRequired ( ) || option instanceof Gr... |
Math | 15 | src/main/java/org/apache/commons/math3/util/FastMath.java | 1441 | 1599 | FastMath.pow deviates from Math.pow for negative, finite base values with an exponent 2^52 < y < 2^53 | As reported by Jeff Hain:
pow(double,double):
Math.pow(-1.0,5.000000000000001E15) = -1.0
FastMath.pow(-1.0,5.000000000000001E15) = 1.0
===> This is due to considering that power is an even
integer if it is >= 2^52, while you need to test
that it is >= 2^53 for it.
===> replace
"if (y >= TWO_POWER_52 || y <= -TWO_POWER... | public static double pow(double x, double y) {
final double lns[] = new double[2];
if (y == 0.0) {
return 1.0;
}
if (x != x) { // X is NaN
return x;
}
if (x == 0) {
long bits = Double.doubleToLongBits(x);
if ((bits & 0x8... | public static double pow ( double x , double y ) { final double lns [ ] = new double [ 2 ] ; if ( y == 0.0 ) { return 1.0 ; } if ( x != x ) { return x ; } if ( x == 0 ) { long bits = Double . doubleToLongBits ( x ) ; if ( ( bits & 0x8000000000000000L ) != 0 ) { long yi = ( long ) y ; if ( y < 0 && y == yi && ( yi & 1 )... | public static double pow(double x, double y) {
final double lns[] = new double[2];
if (y == 0.0) {
return 1.0;
}
if (x != x) { // X is NaN
return x;
}
if (x == 0) {
long bits = Double.doubleToLongBits(x);
if ((bits & 0x8... | public static double pow ( double x , double y ) { final double lns [ ] = new double [ 2 ] ; if ( y == 0.0 ) { return 1.0 ; } if ( x != x ) { return x ; } if ( x == 0 ) { long bits = Double . doubleToLongBits ( x ) ; if ( ( bits & 0x8000000000000000L ) != 0 ) { long yi = ( long ) y ; if ( y < 0 && y == yi && ( yi & 1 )... |
JacksonDatabind | 70 | src/main/java/com/fasterxml/jackson/databind/deser/impl/BeanPropertyMap.java | 426 | 453 | `ACCEPT_CASE_INSENSITIVE_PROPERTIES` fails with `@JsonUnwrapped` | (note: moved from https://github.com/FasterXML/jackson-dataformat-csv/issues/133)
When trying to deserialize type like:
```java
public class Person {
@JsonUnwrapped(prefix = "businessAddress.")
public Address businessAddress;
}
public class Address {
public String street;
public String addon;
... | public void remove(SettableBeanProperty propToRm)
{
ArrayList<SettableBeanProperty> props = new ArrayList<SettableBeanProperty>(_size);
String key = getPropertyName(propToRm);
boolean found = false;
for (int i = 1, end = _hashArea.length; i < end; i += 2) {
SettableBeanP... | public void remove ( SettableBeanProperty propToRm ) { ArrayList < SettableBeanProperty > props = new ArrayList < SettableBeanProperty > ( _size ) ; String key = getPropertyName ( propToRm ) ; boolean found = false ; for ( int i = 1 , end = _hashArea . length ; i < end ; i += 2 ) { SettableBeanProperty prop = ( Settabl... | public void remove(SettableBeanProperty propToRm)
{
ArrayList<SettableBeanProperty> props = new ArrayList<SettableBeanProperty>(_size);
String key = getPropertyName(propToRm);
boolean found = false;
for (int i = 1, end = _hashArea.length; i < end; i += 2) {
SettableBeanP... | public void remove ( SettableBeanProperty propToRm ) { ArrayList < SettableBeanProperty > props = new ArrayList < SettableBeanProperty > ( _size ) ; String key = getPropertyName ( propToRm ) ; boolean found = false ; for ( int i = 1 , end = _hashArea . length ; i < end ; i += 2 ) { SettableBeanProperty prop = ( Settabl... |
Math | 42 | src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java | 396 | 425 | 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 ... | 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, getRh... | 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 , getRhsOf... | 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, getRh... | 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 , getRhsOf... |
JacksonDatabind | 66 | src/main/java/com/fasterxml/jackson/databind/deser/std/StdKeyDeserializer.java | 306 | 324 | Failure with custom Enum key deserializer, polymorphic types | Normally the `JsonParser` and the `DeserializationContext` is passed to a `Module`'s `JsonDeserializer`.
However, in the `MapDeserializer`, when deserializing a `Map` with an `Enum` key, the `KeyDeserializer` doesn't accept the `JsonParser` as an argument:
https://github.com/FasterXML/jackson-databind/blob/maste... | @SuppressWarnings("resource")
@Override
public final Object deserializeKey(String key, DeserializationContext ctxt)
throws IOException
{
if (key == null) { // is this even legal call?
return null;
}
try {
// Ugh... s... | @ SuppressWarnings ( "resource" ) @ Override public final Object deserializeKey ( String key , DeserializationContext ctxt ) throws IOException { if ( key == null ) { return null ; } try { Object result = _delegate . deserialize ( ctxt . getParser ( ) , ctxt ) ; if ( result != null ) { return result ; } return ctxt . h... | @SuppressWarnings("resource")
@Override
public final Object deserializeKey(String key, DeserializationContext ctxt)
throws IOException
{
if (key == null) { // is this even legal call?
return null;
}
TokenBuffer tb = new TokenBuffer(... | @ SuppressWarnings ( "resource" ) @ Override public final Object deserializeKey ( String key , DeserializationContext ctxt ) throws IOException { if ( key == null ) { return null ; } TokenBuffer tb = new TokenBuffer ( ctxt . getParser ( ) , ctxt ) ; tb . writeString ( key ) ; try { JsonParser p = tb . asParser ( ) ; p ... |
Codec | 10 | src/java/org/apache/commons/codec/language/Caverphone.java | 50 | 142 | Caverphone encodes names starting and ending with "mb" incorrectly. | Caverphone encode names starting and ending with "mb" incorrectly.
According to the spec:
"If the name ends with mb make it m2".
This has been coded as:
"If the name _starts_ with mb make it m2". | public String caverphone(String txt) {
// NOTE: Version 1.0 of Caverphone is easily derivable from this code
// by commenting out the 2.0 lines and adding in the 1.0 lines
if( txt == null || txt.length() == 0 ) {
return "1111111111";
}
// 1. Convert to lowercase
... | public String caverphone ( String txt ) { if ( txt == null || txt . length ( ) == 0 ) { return "1111111111" ; } txt = txt . toLowerCase ( java . util . Locale . ENGLISH ) ; txt = txt . replaceAll ( "[^a-z]" , "" ) ; txt = txt . replaceAll ( "e$" , "" ) ; txt = txt . replaceAll ( "^cough" , "cou2f" ) ; txt = txt . repla... | public String caverphone(String txt) {
// NOTE: Version 1.0 of Caverphone is easily derivable from this code
// by commenting out the 2.0 lines and adding in the 1.0 lines
if( txt == null || txt.length() == 0 ) {
return "1111111111";
}
// 1. Convert to lowercase
... | public String caverphone ( String txt ) { if ( txt == null || txt . length ( ) == 0 ) { return "1111111111" ; } txt = txt . toLowerCase ( java . util . Locale . ENGLISH ) ; txt = txt . replaceAll ( "[^a-z]" , "" ) ; txt = txt . replaceAll ( "e$" , "" ) ; txt = txt . replaceAll ( "^cough" , "cou2f" ) ; txt = txt . repla... |
Math | 102 | src/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java | 64 | 81 | chiSquare(double[] expected, long[] observed) is returning incorrect test statistic | ChiSquareTestImpl is returning incorrect chi-squared value. An implicit assumption of public double chiSquare(double[] expected, long[] observed) is that the sum of expected and observed are equal. That is, in the code:
for (int i = 0; i < observed.length; i++) {
dev = ((double) observed[i] - expected[i]);
... | public double chiSquare(double[] expected, long[] observed)
throws IllegalArgumentException {
if ((expected.length < 2) || (expected.length != observed.length)) {
throw new IllegalArgumentException(
"observed, expected array lengths incorrect");
}
if (!isP... | public double chiSquare ( double [ ] expected , long [ ] observed ) throws IllegalArgumentException { if ( ( expected . length < 2 ) || ( expected . length != observed . length ) ) { throw new IllegalArgumentException ( "observed, expected array lengths incorrect" ) ; } if ( ! isPositive ( expected ) || ! isNonNegative... | public double chiSquare(double[] expected, long[] observed)
throws IllegalArgumentException {
if ((expected.length < 2) || (expected.length != observed.length)) {
throw new IllegalArgumentException(
"observed, expected array lengths incorrect");
}
if (!isP... | public double chiSquare ( double [ ] expected , long [ ] observed ) throws IllegalArgumentException { if ( ( expected . length < 2 ) || ( expected . length != observed . length ) ) { throw new IllegalArgumentException ( "observed, expected array lengths incorrect" ) ; } if ( ! isPositive ( expected ) || ! isNonNegative... |
Math | 78 | src/main/java/org/apache/commons/math/ode/events/EventState.java | 167 | 263 | during ODE integration, the last event in a pair of very close event may not be detected | When an events follows a previous one very closely, it may be ignored. The occurrence of the bug depends on the side of the bracketing interval that was selected. For example consider a switching function that is increasing around first event around t = 90, reaches its maximum and is decreasing around the second event ... | public boolean evaluateStep(final StepInterpolator interpolator)
throws DerivativeException, EventException, ConvergenceException {
try {
forward = interpolator.isForward();
final double t1 = interpolator.getCurrentTime();
final int n = Math.max(1, (int) Math.ce... | public boolean evaluateStep ( final StepInterpolator interpolator ) throws DerivativeException , EventException , ConvergenceException { try { forward = interpolator . isForward ( ) ; final double t1 = interpolator . getCurrentTime ( ) ; final int n = Math . max ( 1 , ( int ) Math . ceil ( Math . abs ( t1 - t0 ) / maxC... | public boolean evaluateStep(final StepInterpolator interpolator)
throws DerivativeException, EventException, ConvergenceException {
try {
forward = interpolator.isForward();
final double t1 = interpolator.getCurrentTime();
final int n = Math.max(1, (int) Math.ce... | public boolean evaluateStep ( final StepInterpolator interpolator ) throws DerivativeException , EventException , ConvergenceException { try { forward = interpolator . isForward ( ) ; final double t1 = interpolator . getCurrentTime ( ) ; final int n = Math . max ( 1 , ( int ) Math . ceil ( Math . abs ( t1 - t0 ) / maxC... |
Math | 97 | src/java/org/apache/commons/math/analysis/BrentSolver.java | 125 | 152 | 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.Bre... | 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);
... | 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 ) ; double sign = yMin * yMax ; if ( sign >= 0 ) { throw new ... | 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);
... | 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 ) ; double sign = yMin * yMax ; if ( sign > 0 ) { if ( Math .... |
Cli | 8 | src/java/org/apache/commons/cli/HelpFormatter.java | 792 | 823 | HelpFormatter wraps incorrectly on every line beyond the first | The method findWrapPos(...) in the HelpFormatter is a couple of bugs in the way that it deals with the "startPos" variable. This causes it to format every line beyond the first line by "startPos" to many characters, beyond the specified width.
To see this, create an option with a long description, and then use the ... | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.app... | protected StringBuffer renderWrappedText ( StringBuffer sb , int width , int nextLineTabStop , String text ) { int pos = findWrapPos ( text , width , 0 ) ; if ( pos == - 1 ) { sb . append ( rtrim ( text ) ) ; return sb ; } sb . append ( rtrim ( text . substring ( 0 , pos ) ) ) . append ( defaultNewLine ) ; final String... | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.app... | protected StringBuffer renderWrappedText ( StringBuffer sb , int width , int nextLineTabStop , String text ) { int pos = findWrapPos ( text , width , 0 ) ; if ( pos == - 1 ) { sb . append ( rtrim ( text ) ) ; return sb ; } sb . append ( rtrim ( text . substring ( 0 , pos ) ) ) . append ( defaultNewLine ) ; final String... |
Cli | 38 | src/main/java/org/apache/commons/cli/DefaultParser.java | 299 | 312 | Optional argument picking up next regular option as its argument | None | private boolean isShortOption(String token)
{
// short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
if (!token.startsWith("-") || token.length() == 1)
{
return false;
}
// remove leading "-" and "=value"
int pos = token.indexOf("=");
String optName = p... | private boolean isShortOption ( String token ) { if ( ! token . startsWith ( "-" ) || token . length ( ) == 1 ) { return false ; } int pos = token . indexOf ( "=" ) ; String optName = pos == - 1 ? token . substring ( 1 ) : token . substring ( 1 , pos ) ; return options . hasShortOption ( optName ) ; } | private boolean isShortOption(String token)
{
// short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
if (!token.startsWith("-") || token.length() == 1)
{
return false;
}
// remove leading "-" and "=value"
int pos = token.indexOf("=");
String optName = p... | private boolean isShortOption ( String token ) { if ( ! token . startsWith ( "-" ) || token . length ( ) == 1 ) { return false ; } int pos = token . indexOf ( "=" ) ; String optName = pos == - 1 ? token . substring ( 1 ) : token . substring ( 1 , pos ) ; if ( options . hasShortOption ( optName ) ) { return true ; } ret... |
Compress | 36 | src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java | 901 | 916 | Calling SevenZFile.read() on empty SevenZArchiveEntry throws IllegalStateException | I'm pretty sure COMPRESS-340 breaks reading empty archive entries. When calling getNextEntry() and that entry has no content, the code jumps into the first block at line 830 (SevenZFile.class), clearing the deferredBlockStreams. When calling entry.read(...) afterwards an IllegalStateException ("No current 7z entry (cal... | private InputStream getCurrentStream() throws IOException {
if (deferredBlockStreams.isEmpty()) {
throw new IllegalStateException("No current 7z entry (call getNextEntry() first).");
}
while (deferredBlockStreams.size() > 1) {
// In solid compression mode we need... | private InputStream getCurrentStream ( ) throws IOException { if ( deferredBlockStreams . isEmpty ( ) ) { throw new IllegalStateException ( "No current 7z entry (call getNextEntry() first)." ) ; } while ( deferredBlockStreams . size ( ) > 1 ) { final InputStream stream = deferredBlockStreams . remove ( 0 ) ; IOUtils . ... | private InputStream getCurrentStream() throws IOException {
if (archive.files[currentEntryIndex].getSize() == 0) {
return new ByteArrayInputStream(new byte[0]);
}
if (deferredBlockStreams.isEmpty()) {
throw new IllegalStateException("No current 7z entry (call getNextEntry... | private InputStream getCurrentStream ( ) throws IOException { if ( archive . files [ currentEntryIndex ] . getSize ( ) == 0 ) { return new ByteArrayInputStream ( new byte [ 0 ] ) ; } if ( deferredBlockStreams . isEmpty ( ) ) { throw new IllegalStateException ( "No current 7z entry (call getNextEntry() first)." ) ; } wh... |
Math | 39 | src/main/java/org/apache/commons/math/ode/nonstiff/EmbeddedRungeKuttaIntegrator.java | 190 | 328 | too large first step with embedded Runge-Kutta integrators (Dormand-Prince 8(5,3) ...) | Adaptive step size integrators compute the first step size by themselves if it is not provided.
For embedded Runge-Kutta type, this step size is not checked against the integration range, so if the integration range is extremely short, this step size may evaluate the function out of the range (and in fact it tries afte... | @Override
public void integrate(final ExpandableStatefulODE equations, final double t)
throws MathIllegalStateException, MathIllegalArgumentException {
sanityChecks(equations, t);
setEquations(equations);
final boolean forward = t > equations.getTime();
// create some internal working arrays
... | @ Override public void integrate ( final ExpandableStatefulODE equations , final double t ) throws MathIllegalStateException , MathIllegalArgumentException { sanityChecks ( equations , t ) ; setEquations ( equations ) ; final boolean forward = t > equations . getTime ( ) ; final double [ ] y0 = equations . getCompleteS... | @Override
public void integrate(final ExpandableStatefulODE equations, final double t)
throws MathIllegalStateException, MathIllegalArgumentException {
sanityChecks(equations, t);
setEquations(equations);
final boolean forward = t > equations.getTime();
// create some internal working arrays
... | @ Override public void integrate ( final ExpandableStatefulODE equations , final double t ) throws MathIllegalStateException , MathIllegalArgumentException { sanityChecks ( equations , t ) ; setEquations ( equations ) ; final boolean forward = t > equations . getTime ( ) ; final double [ ] y0 = equations . getCompleteS... |
Codec | 5 | src/java/org/apache/commons/codec/binary/Base64.java | 550 | 599 | Base64InputStream causes NullPointerException on some input | Certain (malformed?) input to {{Base64InputStream}} causes a {{NullPointerException}} in {{Base64.decode}}.
The exception occurs when {{Base64.decode}} is entered with the following conditions:
* {{buffer}} is {{null}}
* {{modulus}} is {{3}} from a previous entry.
* {{inAvail}} is {{-1}} because {{Base64InputStream.r... | void decode(byte[] in, int inPos, int inAvail) {
if (eof) {
return;
}
if (inAvail < 0) {
eof = true;
}
for (int i = 0; i < inAvail; i++) {
if (buffer == null || buffer.length - pos < decodeSize) {
resizeBuffer();
}
... | void decode ( byte [ ] in , int inPos , int inAvail ) { if ( eof ) { return ; } if ( inAvail < 0 ) { eof = true ; } for ( int i = 0 ; i < inAvail ; i ++ ) { if ( buffer == null || buffer . length - pos < decodeSize ) { resizeBuffer ( ) ; } byte b = in [ inPos ++ ] ; if ( b == PAD ) { eof = true ; break ; } else { if ( ... | void decode(byte[] in, int inPos, int inAvail) {
if (eof) {
return;
}
if (inAvail < 0) {
eof = true;
}
for (int i = 0; i < inAvail; i++) {
if (buffer == null || buffer.length - pos < decodeSize) {
resizeBuffer();
}
... | void decode ( byte [ ] in , int inPos , int inAvail ) { if ( eof ) { return ; } if ( inAvail < 0 ) { eof = true ; } for ( int i = 0 ; i < inAvail ; i ++ ) { if ( buffer == null || buffer . length - pos < decodeSize ) { resizeBuffer ( ) ; } byte b = in [ inPos ++ ] ; if ( b == PAD ) { eof = true ; break ; } else { if ( ... |
JxPath | 5 | src/java/org/apache/commons/jxpath/ri/model/NodePointer.java | 642 | 675 | Cannot compare pointers that do not belong to the same tree | For XPath "$var | /MAIN/A" exception is thrown:
org.apache.commons.jxpath.JXPathException: Cannot compare pointers that do not belong to the same tree: '$var' and ''
at org.apache.commons.jxpath.ri.model.NodePointer.compareNodePointers(NodePointer.java:665)
at org.apache.commons.jxpath.ri.model.NodePointer.compareNo... | private int compareNodePointers(
NodePointer p1,
int depth1,
NodePointer p2,
int depth2)
{
if (depth1 < depth2) {
int r = compareNodePointers(p1, depth1, p2.parent, depth2 - 1);
return r == 0 ? -1 : r;
}
if (depth1 > depth2) {
... | private int compareNodePointers ( NodePointer p1 , int depth1 , NodePointer p2 , int depth2 ) { if ( depth1 < depth2 ) { int r = compareNodePointers ( p1 , depth1 , p2 . parent , depth2 - 1 ) ; return r == 0 ? - 1 : r ; } if ( depth1 > depth2 ) { int r = compareNodePointers ( p1 . parent , depth1 - 1 , p2 , depth2 ) ; ... | private int compareNodePointers(
NodePointer p1,
int depth1,
NodePointer p2,
int depth2)
{
if (depth1 < depth2) {
int r = compareNodePointers(p1, depth1, p2.parent, depth2 - 1);
return r == 0 ? -1 : r;
}
if (depth1 > depth2) {
... | private int compareNodePointers ( NodePointer p1 , int depth1 , NodePointer p2 , int depth2 ) { if ( depth1 < depth2 ) { int r = compareNodePointers ( p1 , depth1 , p2 . parent , depth2 - 1 ) ; return r == 0 ? - 1 : r ; } if ( depth1 > depth2 ) { int r = compareNodePointers ( p1 . parent , depth1 - 1 , p2 , depth2 ) ; ... |
Chart | 17 | source/org/jfree/data/time/TimeSeries.java | 856 | 859 | cloning of TimeSeries | It's just a minor bug!
When I clone a TimeSeries which has no items, I get an IllegalArgumentException ("Requires start <= end").
But I don't think the user should be responsible for checking whether the TimeSeries has any items or not. | public Object clone() throws CloneNotSupportedException {
Object clone = createCopy(0, getItemCount() - 1);
return clone;
} | public Object clone ( ) throws CloneNotSupportedException { Object clone = createCopy ( 0 , getItemCount ( ) - 1 ) ; return clone ; } | public Object clone() throws CloneNotSupportedException {
TimeSeries clone = (TimeSeries) super.clone();
clone.data = (List) ObjectUtilities.deepClone(this.data);
return clone;
} | public Object clone ( ) throws CloneNotSupportedException { TimeSeries clone = ( TimeSeries ) super . clone ( ) ; clone . data = ( List ) ObjectUtilities . deepClone ( this . data ) ; return clone ; } |
Mockito | 9 | src/org/mockito/internal/stubbing/answers/CallsRealMethods.java | 35 | 37 | 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
| public Object answer(InvocationOnMock invocation) throws Throwable {
return invocation.callRealMethod();
} | 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();
} | public Object answer ( InvocationOnMock invocation ) throws Throwable { if ( Modifier . isAbstract ( invocation . getMethod ( ) . getModifiers ( ) ) ) { return new GloballyConfiguredAnswer ( ) . answer ( invocation ) ; } return invocation . callRealMethod ( ) ; } |
Mockito | 8 | src/org/mockito/internal/util/reflection/GenericMetadataSupport.java | 66 | 84 | 1.10 regression (StackOverflowError) with interface where generic type has itself as upper bound | Add this to `GenericMetadataSupportTest`:
``` java
interface GenericsSelfReference<T extends GenericsSelfReference<T>> {
T self();
}
@Test
public void typeVariable_of_self_type() {
GenericMetadataSupport genericMetadata = inferFrom(GenericsSelfReference.class).resolveGenericReturnType(... | protected void registerTypeVariablesOn(Type classType) {
if (!(classType instanceof ParameterizedType)) {
return;
}
ParameterizedType parameterizedType = (ParameterizedType) classType;
TypeVariable[] typeParameters = ((Class<?>) parameterizedType.getRawType()).getTypeParamete... | protected void registerTypeVariablesOn ( Type classType ) { if ( ! ( classType instanceof ParameterizedType ) ) { return ; } ParameterizedType parameterizedType = ( ParameterizedType ) classType ; TypeVariable [ ] typeParameters = ( ( Class < ? > ) parameterizedType . getRawType ( ) ) . getTypeParameters ( ) ; Type [ ]... | protected void registerTypeVariablesOn(Type classType) {
if (!(classType instanceof ParameterizedType)) {
return;
}
ParameterizedType parameterizedType = (ParameterizedType) classType;
TypeVariable[] typeParameters = ((Class<?>) parameterizedType.getRawType()).getTypeParamete... | protected void registerTypeVariablesOn ( Type classType ) { if ( ! ( classType instanceof ParameterizedType ) ) { return ; } ParameterizedType parameterizedType = ( ParameterizedType ) classType ; TypeVariable [ ] typeParameters = ( ( Class < ? > ) parameterizedType . getRawType ( ) ) . getTypeParameters ( ) ; Type [ ]... |
Csv | 1 | src/main/java/org/apache/commons/csv/ExtendedBufferedReader.java | 55 | 63 | ExtendedBufferReader does not handle EOL consistently | ExtendedBufferReader checks for '\n' (LF) in the read() methods, incrementing linecount when found.
However, the readLine() method calls BufferedReader.readLine() which treats CR, LF and CRLF equally (and drops them).
If the code is to be flexible in what it accepts, the class should also allow for CR alone as a line... | @Override
public int read() throws IOException {
int current = super.read();
if (current == '\n') {
lineCounter++;
}
lastChar = current;
return lastChar;
} | @ Override public int read ( ) throws IOException { int current = super . read ( ) ; if ( current == '\n' ) { lineCounter ++ ; } lastChar = current ; return lastChar ; } | @Override
public int read() throws IOException {
int current = super.read();
if (current == '\r' || (current == '\n' && lastChar != '\r')) {
lineCounter++;
}
lastChar = current;
return lastChar;
} | @ Override public int read ( ) throws IOException { int current = super . read ( ) ; if ( current == '\r' || ( current == '\n' && lastChar != '\r' ) ) { lineCounter ++ ; } lastChar = current ; return lastChar ; } |
Math | 80 | src/main/java/org/apache/commons/math/linear/EigenDecompositionImpl.java | 1132 | 1147 | wrong result in eigen decomposition | Some results computed by EigenDecompositionImpl are wrong. The following case computed by Fortran Lapack fails with version 2.0
{code}
public void testMathpbx02() {
double[] mainTridiagonal = {
7484.860960227216, 18405.28129035345, 13855.225609560746,
10016.708722343366, 559.8117399576... | private boolean flipIfWarranted(final int n, final int step) {
if (1.5 * work[pingPong] < work[4 * (n - 1) + pingPong]) {
// flip array
int j = 4 * n - 1;
for (int i = 0; i < j; i += 4) {
for (int k = 0; k < 4; k += step) {
final double tmp... | private boolean flipIfWarranted ( final int n , final int step ) { if ( 1.5 * work [ pingPong ] < work [ 4 * ( n - 1 ) + pingPong ] ) { int j = 4 * n - 1 ; for ( int i = 0 ; i < j ; i += 4 ) { for ( int k = 0 ; k < 4 ; k += step ) { final double tmp = work [ i + k ] ; work [ i + k ] = work [ j - k ] ; work [ j - k ] = ... | private boolean flipIfWarranted(final int n, final int step) {
if (1.5 * work[pingPong] < work[4 * (n - 1) + pingPong]) {
// flip array
int j = 4 * (n - 1);
for (int i = 0; i < j; i += 4) {
for (int k = 0; k < 4; k += step) {
final double t... | private boolean flipIfWarranted ( final int n , final int step ) { if ( 1.5 * work [ pingPong ] < work [ 4 * ( n - 1 ) + pingPong ] ) { int j = 4 * ( n - 1 ) ; for ( int i = 0 ; i < j ; i += 4 ) { for ( int k = 0 ; k < 4 ; k += step ) { final double tmp = work [ i + k ] ; work [ i + k ] = work [ j - k ] ; work [ j - k ... |
Mockito | 27 | src/org/mockito/internal/util/MockUtil.java | 62 | 67 | MockUtil.resetMock() doesn't create InvocationNotifierHandler when recreating a filter | What steps will reproduce the problem? 1. create a mock with verbose logging 2. reset a mock What is the expected output? What do you see instead? Verbose logging doesn't work after reseting a mock. What version of the product are you using? On what operating system? 1.9.0-rc1 Patch attached. | 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.withSettin... | 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 . w... | public <T> void resetMock(T mock) {
MockHandlerInterface<T> oldMockHandler = getMockHandler(mock);
MethodInterceptorFilter newFilter = newMethodInterceptorFilter(oldMockHandler.getMockSettings());
((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 ) ; } |
Math | 38 | src/main/java/org/apache/commons/math/optimization/direct/BOBYQAOptimizer.java | 1582 | 1755 | Errors in BOBYQAOptimizer when numberOfInterpolationPoints is greater than 2*dim+1 | I've been having trouble getting BOBYQA to minimize a function (actually a non-linear least squares fit) so as one change I increased the number of interpolation points. It seems that anything larger than 2*dim+1 causes an error (typically at
line 1662
interpolationPoints.setEntry(nfm, ipt, interpo... | private void prelim(double[] lowerBound,
double[] upperBound) {
printMethod(); // XXX
final int n = currentBest.getDimension();
final int npt = numberOfInterpolationPoints;
final int ndim = bMatrix.getRowDimension();
final double rhosq = initialTrustRegi... | private void prelim ( double [ ] lowerBound , double [ ] upperBound ) { printMethod ( ) ; final int n = currentBest . getDimension ( ) ; final int npt = numberOfInterpolationPoints ; final int ndim = bMatrix . getRowDimension ( ) ; final double rhosq = initialTrustRegionRadius * initialTrustRegionRadius ; final double ... | private void prelim(double[] lowerBound,
double[] upperBound) {
printMethod(); // XXX
final int n = currentBest.getDimension();
final int npt = numberOfInterpolationPoints;
final int ndim = bMatrix.getRowDimension();
final double rhosq = initialTrustRegi... | private void prelim ( double [ ] lowerBound , double [ ] upperBound ) { printMethod ( ) ; final int n = currentBest . getDimension ( ) ; final int npt = numberOfInterpolationPoints ; final int ndim = bMatrix . getRowDimension ( ) ; final double rhosq = initialTrustRegionRadius * initialTrustRegionRadius ; final double ... |
Codec | 4 | src/java/org/apache/commons/codec/binary/Base64.java | 224 | 226 | new Base64().encode() appends a CRLF, and chunks results into 76 character lines | The instance encode() method (e.g. new Base64().encode()) appends a CRLF. Actually it's fully chunking the output into 76 character lines. Commons-Codec-1.3 did not do this. The static Base64.encodeBase64() method behaves the same in both 1.3 and 1.4, so this problem only affects the instance encode() method.
{cod... | public Base64() {
this(false);
} | public Base64 ( ) { this ( false ) ; } | public Base64() {
this(0);
} | public Base64 ( ) { this ( 0 ) ; } |
Cli | 39 | src/main/java/org/apache/commons/cli/TypeHandler.java | 64 | 106 | Option parser type EXISTING_FILE_VALUE not check file existing | When the user pass option type FileInputStream.class, I think the expected behavior for the return value is the same type, which the user passed.
Options options = new Options();
options.addOption(Option.builder("f").hasArg().type(FileInputStream.class).build());
CommandLine cline = new DefaultParser().parse(options, ... | public static Object createValue(final String str, final Class<?> clazz) throws ParseException
{
if (PatternOptionBuilder.STRING_VALUE == clazz)
{
return str;
}
else if (PatternOptionBuilder.OBJECT_VALUE == clazz)
{
return createObject(str);
}
... | public static Object createValue ( final String str , final Class < ? > clazz ) throws ParseException { if ( PatternOptionBuilder . STRING_VALUE == clazz ) { return str ; } else if ( PatternOptionBuilder . OBJECT_VALUE == clazz ) { return createObject ( str ) ; } else if ( PatternOptionBuilder . NUMBER_VALUE == clazz )... | public static Object createValue(final String str, final Class<?> clazz) throws ParseException
{
if (PatternOptionBuilder.STRING_VALUE == clazz)
{
return str;
}
else if (PatternOptionBuilder.OBJECT_VALUE == clazz)
{
return createObject(str);
}
... | public static Object createValue ( final String str , final Class < ? > clazz ) throws ParseException { if ( PatternOptionBuilder . STRING_VALUE == clazz ) { return str ; } else if ( PatternOptionBuilder . OBJECT_VALUE == clazz ) { return createObject ( str ) ; } else if ( PatternOptionBuilder . NUMBER_VALUE == clazz )... |
Compress | 37 | src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java | 452 | 502 | Parsing PAX headers fails with NegativeArraySizeException | The {{TarArchiveInputStream.parsePaxHeaders}} method fails with a {{NegativeArraySizeException}} when there is an empty line at the end of the headers.
The inner loop starts reading the length, but it gets a newline (10) and ends up subtracting '0' (48) from it; the result is a negative length that blows up an attempt... | Map<String, String> parsePaxHeaders(final InputStream i)
throws IOException {
final Map<String, String> headers = new HashMap<String, String>(globalPaxHeaders);
// Format is "length keyword=value\n";
while(true){ // get length
int ch;
int len = 0;
int ... | Map < String , String > parsePaxHeaders ( final InputStream i ) throws IOException { final Map < String , String > headers = new HashMap < String , String > ( globalPaxHeaders ) ; while ( true ) { int ch ; int len = 0 ; int read = 0 ; while ( ( ch = i . read ( ) ) != - 1 ) { read ++ ; if ( ch == ' ' ) { final ByteArray... | Map<String, String> parsePaxHeaders(final InputStream i)
throws IOException {
final Map<String, String> headers = new HashMap<String, String>(globalPaxHeaders);
// Format is "length keyword=value\n";
while(true){ // get length
int ch;
int len = 0;
int ... | Map < String , String > parsePaxHeaders ( final InputStream i ) throws IOException { final Map < String , String > headers = new HashMap < String , String > ( globalPaxHeaders ) ; while ( true ) { int ch ; int len = 0 ; int read = 0 ; while ( ( ch = i . read ( ) ) != - 1 ) { read ++ ; if ( ch == '\n' ) { break ; } else... |
Cli | 9 | src/java/org/apache/commons/cli/Parser.java | 303 | 324 | MissingOptionException.getMessage() changed from CLI 1.0 > 1.1 | The MissingOptionException.getMessage() string changed from CLI 1.0 > 1.1.
CLI 1.0 was poorly formatted but readable:
Missing required options: -format-source-properties
CLI 1.1 is almost unreadable:
Missing required options: formatsourceproperties
In CLI 1.0 Options.addOption(Option) prefixed the stored options wi... | protected void checkRequiredOptions()
throws MissingOptionException
{
// if there are required options that have not been
// processsed
if (getRequiredOptions().size() > 0)
{
Iterator iter = getRequiredOptions().iterator();
StringBuffer buff = new Stri... | protected void checkRequiredOptions ( ) throws MissingOptionException { if ( getRequiredOptions ( ) . size ( ) > 0 ) { Iterator iter = getRequiredOptions ( ) . iterator ( ) ; StringBuffer buff = new StringBuffer ( "Missing required option" ) ; buff . append ( getRequiredOptions ( ) . size ( ) == 1 ? "" : "s" ) ; buff .... | protected void checkRequiredOptions()
throws MissingOptionException
{
// if there are required options that have not been
// processsed
if (getRequiredOptions().size() > 0)
{
Iterator iter = getRequiredOptions().iterator();
StringBuffer buff = new Stri... | protected void checkRequiredOptions ( ) throws MissingOptionException { if ( getRequiredOptions ( ) . size ( ) > 0 ) { Iterator iter = getRequiredOptions ( ) . iterator ( ) ; StringBuffer buff = new StringBuffer ( "Missing required option" ) ; buff . append ( getRequiredOptions ( ) . size ( ) == 1 ? "" : "s" ) ; buff .... |
Compress | 21 | src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFile.java | 634 | 649 | Writing 7z empty entries produces incorrect or corrupt archive | I couldn't find an exact rule that causes this incorrect behavior, but I tried to reduce it to some simple scenarios to reproduce it:
Input: A folder with certain files -> tried to archive it.
If the folder contains more than 7 files the incorrect behavior appears.
Scenario 1: 7 empty files
Result: The created archiv... | private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException {
int cache = 0;
int shift = 7;
for (int i = 0; i < length; i++) {
cache |= ((bits.get(i) ? 1 : 0) << shift);
--shift;
if (shift == 0) {
hea... | private void writeBits ( final DataOutput header , final BitSet bits , final int length ) throws IOException { int cache = 0 ; int shift = 7 ; for ( int i = 0 ; i < length ; i ++ ) { cache |= ( ( bits . get ( i ) ? 1 : 0 ) << shift ) ; -- shift ; if ( shift == 0 ) { header . write ( cache ) ; shift = 7 ; cache = 0 ; } ... | private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException {
int cache = 0;
int shift = 7;
for (int i = 0; i < length; i++) {
cache |= ((bits.get(i) ? 1 : 0) << shift);
if (--shift < 0) {
header.write(cache);
... | private void writeBits ( final DataOutput header , final BitSet bits , final int length ) throws IOException { int cache = 0 ; int shift = 7 ; for ( int i = 0 ; i < length ; i ++ ) { cache |= ( ( bits . get ( i ) ? 1 : 0 ) << shift ) ; if ( -- shift < 0 ) { header . write ( cache ) ; shift = 7 ; cache = 0 ; } } if ( sh... |
Math | 79 | src/main/java/org/apache/commons/math/util/MathUtils.java | 1623 | 1630 | 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.a... | 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 ) { 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);
} | 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 ) ; } |
Math | 96 | src/java/org/apache/commons/math/complex/Complex.java | 245 | 267 | Result of multiplying and equals for complex numbers is wrong | Hi.
The bug relates on complex numbers.
The methods "multiply" and "equals" of the class Complex are involved.
mathematic background: (0,i) * (-1,0i) = (0,-i).
little java program + output that shows the bug:
-----------------------------------------------------------------------
{code}
import org.apache.commons.ma... | public boolean equals(Object other) {
boolean ret;
if (this == other) {
ret = true;
} else if (other == null) {
ret = false;
} else {
try {
Complex rhs = (Complex)other;
if (rhs.isNaN()) {
... | public boolean equals ( Object other ) { boolean ret ; if ( this == other ) { ret = true ; } else if ( other == null ) { ret = false ; } else { try { Complex rhs = ( Complex ) other ; if ( rhs . isNaN ( ) ) { ret = this . isNaN ( ) ; } else { ret = ( Double . doubleToRawLongBits ( real ) == Double . doubleToRawLongBits... | public boolean equals(Object other) {
boolean ret;
if (this == other) {
ret = true;
} else if (other == null) {
ret = false;
} else {
try {
Complex rhs = (Complex)other;
if (rhs.isNaN()) {
... | public boolean equals ( Object other ) { boolean ret ; if ( this == other ) { ret = true ; } else if ( other == null ) { ret = false ; } else { try { Complex rhs = ( Complex ) other ; if ( rhs . isNaN ( ) ) { ret = this . isNaN ( ) ; } else { ret = ( real == rhs . real ) && ( imaginary == rhs . imaginary ) ; } } catch ... |
Mockito | 31 | src/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNulls.java | 59 | 61 | SmartNulls should identify the arguments that the stubbed method was invoked with | I've started mocking with RETURNS_SMART_NULLS. It is very useful and I like the fact that it can be configured with the @Mock annotation. I agree with the comment that it should be the default in Mockito 2.0. Returning null values from mocked methods encourages writing code that is designed to handle nulls, which IMO i... | private String formatMethodCall() {
return invocation.getMethod().getName() + "()";
} | private String formatMethodCall ( ) { return invocation . getMethod ( ) . getName ( ) + "()" ; } | private String formatMethodCall() {
String args = Arrays.toString(invocation.getArguments());
return invocation.getMethod().getName() + "(" + args.substring(1, args.length() - 1) + ")";
} | private String formatMethodCall ( ) { String args = Arrays . toString ( invocation . getArguments ( ) ) ; return invocation . getMethod ( ) . getName ( ) + "(" + args . substring ( 1 , args . length ( ) - 1 ) + ")" ; } |
Math | 103 | src/java/org/apache/commons/math/distribution/NormalDistributionImpl.java | 108 | 111 | ConvergenceException in normal CDF | NormalDistributionImpl::cumulativeProbability(double x) throws ConvergenceException
if x deviates too much from the mean. For example, when x=+/-100, mean=0, sd=1.
Of course the value of the CDF is hard to evaluate in these cases,
but effectively it should be either zero or one. | public double cumulativeProbability(double x) throws MathException {
return 0.5 * (1.0 + Erf.erf((x - mean) /
(standardDeviation * Math.sqrt(2.0))));
} | public double cumulativeProbability ( double x ) throws MathException { return 0.5 * ( 1.0 + Erf . erf ( ( x - mean ) / ( standardDeviation * Math . sqrt ( 2.0 ) ) ) ) ; } | public double cumulativeProbability(double x) throws MathException {
try {
return 0.5 * (1.0 + Erf.erf((x - mean) /
(standardDeviation * Math.sqrt(2.0))));
} catch (MaxIterationsExceededException ex) {
if (x < (mean - 20 * standardDeviation)) { // JDK 1.5 blow... | public double cumulativeProbability ( double x ) throws MathException { try { return 0.5 * ( 1.0 + Erf . erf ( ( x - mean ) / ( standardDeviation * Math . sqrt ( 2.0 ) ) ) ) ; } catch ( MaxIterationsExceededException ex ) { if ( x < ( mean - 20 * standardDeviation ) ) { return 0.0d ; } else if ( x > ( mean + 20 * stand... |
JacksonCore | 11 | src/main/java/com/fasterxml/jackson/core/sym/ByteQuadsCanonicalizer.java | 874 | 886 | ArrayIndexOutOfBoundsException: 128 when repeatedly serializing to a byte array | ```
java.lang.ArrayIndexOutOfBoundsException: 128
at com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer.addName(ByteQuadsCanonicalizer.java:853)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.addName(UTF8StreamJsonParser.java:2340)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.findName... | private void _verifySharing()
{
if (_hashShared) {
_hashArea = Arrays.copyOf(_hashArea, _hashArea.length);
_names = Arrays.copyOf(_names, _names.length);
_hashShared = false;
// 09-Sep-2015, tatu: As per [jackson-core#216], also need to ensure
// ... | private void _verifySharing ( ) { if ( _hashShared ) { _hashArea = Arrays . copyOf ( _hashArea , _hashArea . length ) ; _names = Arrays . copyOf ( _names , _names . length ) ; _hashShared = false ; } if ( _needRehash ) { rehash ( ) ; } } | private void _verifySharing()
{
if (_hashShared) {
_hashArea = Arrays.copyOf(_hashArea, _hashArea.length);
_names = Arrays.copyOf(_names, _names.length);
_hashShared = false;
// 09-Sep-2015, tatu: As per [jackson-core#216], also need to ensure
// ... | private void _verifySharing ( ) { if ( _hashShared ) { _hashArea = Arrays . copyOf ( _hashArea , _hashArea . length ) ; _names = Arrays . copyOf ( _names , _names . length ) ; _hashShared = false ; _verifyNeedForRehash ( ) ; } if ( _needRehash ) { rehash ( ) ; } } |
Math | 55 | src/main/java/org/apache/commons/math/geometry/Vector3D.java | 457 | 475 | 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:
{code}
Vector3D v1 = new Vector3D(9070467121.0, 4535233560.0, 1);
Vector3D v2 = new Vector3D(9070467123.0, 4535233561.0, 1);
System.out.println(Vector3D.crossPr... | 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 or... | public static Vector3D crossProduct ( final Vector3D v1 , final Vector3D 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 a... | 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 ; } final int deltaExp = ( FastMath . getExponent ( n1 ) - FastMath . getExponent ( n2 ) ) / 4 ; final dou... |
JacksonDatabind | 67 | src/main/java/com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.java | 1384 | 1416 | Map key deserializerModifiers ignored | We have a module that extends simple model to allow us to accept enum names in lower case in a fairly generic manner
Inside that we add the `modifyKeyDeserializer`
The incoming class (using immutables) is mapped to a guava immutable map.
Walking through the code:
> com.fasterxml.jackson.datatype.guava.deser.Imm... | @Override
public KeyDeserializer createKeyDeserializer(DeserializationContext ctxt,
JavaType type)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
KeyDeserializer deser = null;
if (_factoryConfig.hasKeyDeserializers()) {
... | @ Override public KeyDeserializer createKeyDeserializer ( DeserializationContext ctxt , JavaType type ) throws JsonMappingException { final DeserializationConfig config = ctxt . getConfig ( ) ; KeyDeserializer deser = null ; if ( _factoryConfig . hasKeyDeserializers ( ) ) { BeanDescription beanDesc = config . introspec... | @Override
public KeyDeserializer createKeyDeserializer(DeserializationContext ctxt,
JavaType type)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
KeyDeserializer deser = null;
if (_factoryConfig.hasKeyDeserializers()) {
... | @ Override public KeyDeserializer createKeyDeserializer ( DeserializationContext ctxt , JavaType type ) throws JsonMappingException { final DeserializationConfig config = ctxt . getConfig ( ) ; KeyDeserializer deser = null ; if ( _factoryConfig . hasKeyDeserializers ( ) ) { BeanDescription beanDesc = config . introspec... |
JacksonDatabind | 88 | src/main/java/com/fasterxml/jackson/databind/jsontype/impl/ClassNameIdResolver.java | 45 | 78 | Missing type checks when using polymorphic type ids | (report by Lukes Euler)
`JavaType` supports limited amount of generic typing for textual representation, originally just to support typing needed for `EnumMap` (I think). Based on some reports, it appears that some of type compatibility checks are not performed in those cases; if so, they should be made since there ... | protected JavaType _typeFromId(String id, DatabindContext ctxt) throws IOException
{
/* 30-Jan-2010, tatu: Most ids are basic class names; so let's first
* check if any generics info is added; and only then ask factory
* to do translation when necessary
*/
TypeFactor... | protected JavaType _typeFromId ( String id , DatabindContext ctxt ) throws IOException { TypeFactory tf = ctxt . getTypeFactory ( ) ; if ( id . indexOf ( '<' ) > 0 ) { JavaType t = tf . constructFromCanonical ( id ) ; return t ; } Class < ? > cls ; try { cls = tf . findClass ( id ) ; } catch ( ClassNotFoundException e ... | protected JavaType _typeFromId(String id, DatabindContext ctxt) throws IOException
{
/* 30-Jan-2010, tatu: Most ids are basic class names; so let's first
* check if any generics info is added; and only then ask factory
* to do translation when necessary
*/
TypeFactor... | protected JavaType _typeFromId ( String id , DatabindContext ctxt ) throws IOException { TypeFactory tf = ctxt . getTypeFactory ( ) ; if ( id . indexOf ( '<' ) > 0 ) { JavaType t = tf . constructFromCanonical ( id ) ; if ( ! t . isTypeOrSubTypeOf ( _baseType . getRawClass ( ) ) ) { throw new IllegalArgumentException ( ... |
Math | 43 | src/main/java/org/apache/commons/math/stat/descriptive/SummaryStatistics.java | 149 | 168 | Statistics.setVarianceImpl makes getStandardDeviation produce NaN | Invoking SummaryStatistics.setVarianceImpl(new Variance(true/false) makes getStandardDeviation produce NaN. The code to reproduce it:
{code:java}
int[] scores = {1, 2, 3, 4};
SummaryStatistics stats = new SummaryStatistics();
stats.setVarianceImpl(new Variance(false)); //use "population variance"
for(int i : scores) {... | 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,
... | public void addValue ( double value ) { sumImpl . increment ( value ) ; sumsqImpl . increment ( value ) ; minImpl . increment ( value ) ; maxImpl . increment ( value ) ; sumLogImpl . increment ( value ) ; secondMoment . increment ( value ) ; if ( ! ( meanImpl instanceof Mean ) ) { meanImpl . increment ( value ) ; } if ... | 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,
... | public void addValue ( double value ) { sumImpl . increment ( value ) ; sumsqImpl . increment ( value ) ; minImpl . increment ( value ) ; maxImpl . increment ( value ) ; sumLogImpl . increment ( value ) ; secondMoment . increment ( value ) ; if ( meanImpl != mean ) { meanImpl . increment ( value ) ; } if ( varianceImpl... |
JacksonDatabind | 71 | src/main/java/com/fasterxml/jackson/databind/deser/std/StdKeyDeserializer.java | 70 | 116 | Missing `KeyDeserializer` for `CharSequence` | Looks like use of nominal Map key type of `CharSequence` does not work yet (as of 2.7.8 / 2.8.6).
This is something that is needed to work with certain frameworks, such as Avro's generated POJOs.
| public static StdKeyDeserializer forType(Class<?> raw)
{
int kind;
// first common types:
if (raw == String.class || raw == Object.class) {
return StringKD.forType(raw);
} else if (raw == UUID.class) {
kind = TYPE_UUID;
} else if (raw == Integer.class... | public static StdKeyDeserializer forType ( Class < ? > raw ) { int kind ; if ( raw == String . class || raw == Object . class ) { return StringKD . forType ( raw ) ; } else if ( raw == UUID . class ) { kind = TYPE_UUID ; } else if ( raw == Integer . class ) { kind = TYPE_INT ; } else if ( raw == Long . class ) { kind =... | public static StdKeyDeserializer forType(Class<?> raw)
{
int kind;
// first common types:
if (raw == String.class || raw == Object.class || raw == CharSequence.class) {
return StringKD.forType(raw);
} else if (raw == UUID.class) {
kind = TYPE_UUID;
} ... | public static StdKeyDeserializer forType ( Class < ? > raw ) { int kind ; if ( raw == String . class || raw == Object . class || raw == CharSequence . class ) { return StringKD . forType ( raw ) ; } else if ( raw == UUID . class ) { kind = TYPE_UUID ; } else if ( raw == Integer . class ) { kind = TYPE_INT ; } else if (... |
Cli | 15 | src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java | 111 | 130 | deafult arguments only works if no arguments are submitted | When using multple arguments and defaults, the behaviour is counter-intuitive and will only pick up a default if no args are passed in.
For instance in the code below I have set up so 0, 1, or 2 args may bve accepted, with defaults 100 and 1000.
I expect it to behave as follows.
1. for 2 args, 1 and 2 the values shou... | public List getValues(final Option option,
List defaultValues) {
// initialize the return list
List valueList = (List) values.get(option);
// grab the correct default values
if ((valueList == null) || valueList.isEmpty()) {
valueList = defaultValues... | public List getValues ( final Option option , List defaultValues ) { List valueList = ( List ) values . get ( option ) ; if ( ( valueList == null ) || valueList . isEmpty ( ) ) { valueList = defaultValues ; } if ( ( valueList == null ) || valueList . isEmpty ( ) ) { valueList = ( List ) this . defaultValues . get ( opt... | public List getValues(final Option option,
List defaultValues) {
// initialize the return list
List valueList = (List) values.get(option);
// grab the correct default values
if (defaultValues == null || defaultValues.isEmpty()) {
defaultValues = (Li... | public List getValues ( final Option option , List defaultValues ) { List valueList = ( List ) values . get ( option ) ; if ( defaultValues == null || defaultValues . isEmpty ( ) ) { defaultValues = ( List ) this . defaultValues . get ( option ) ; } if ( defaultValues != null && ! defaultValues . isEmpty ( ) ) { if ( v... |
JxPath | 8 | src/java/org/apache/commons/jxpath/ri/compiler/CoreOperationRelationalExpression.java | 56 | 78 | Comparing with NaN is incorrect | 'NaN' > 'NaN' is true, but should be FALSE | private boolean compute(Object left, Object right) {
left = reduce(left);
right = reduce(right);
if (left instanceof InitialContext) {
((InitialContext) left).reset();
}
if (right instanceof InitialContext) {
((InitialContext) right).reset();
}
... | private boolean compute ( Object left , Object right ) { left = reduce ( left ) ; right = reduce ( right ) ; if ( left instanceof InitialContext ) { ( ( InitialContext ) left ) . reset ( ) ; } if ( right instanceof InitialContext ) { ( ( InitialContext ) right ) . reset ( ) ; } if ( left instanceof Iterator && right in... | private boolean compute(Object left, Object right) {
left = reduce(left);
right = reduce(right);
if (left instanceof InitialContext) {
((InitialContext) left).reset();
}
if (right instanceof InitialContext) {
((InitialContext) right).reset();
}
... | private boolean compute ( Object left , Object right ) { left = reduce ( left ) ; right = reduce ( right ) ; if ( left instanceof InitialContext ) { ( ( InitialContext ) left ) . reset ( ) ; } if ( right instanceof InitialContext ) { ( ( InitialContext ) right ) . reset ( ) ; } if ( left instanceof Iterator && right in... |
JacksonDatabind | 51 | src/main/java/com/fasterxml/jackson/databind/jsontype/impl/TypeDeserializerBase.java | 140 | 191 | Generic type returned from type id resolver seems to be ignored | https://github.com/benson-basis/jackson-custom-mess-tc
Here's the situation, with Jackson 2.7.4.
I have a TypeIdResolver that returns a JavaType for a generic type. However, something seems to be forgetting/erasing the generic, as it is failing to use the generic type param to understand the type of a field in the cl... | protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt,
String typeId) throws IOException
{
JsonDeserializer<Object> deser = _deserializers.get(typeId);
if (deser == null) {
/* As per [Databind#305], need to provide contextual info. But for
... | protected final JsonDeserializer < Object > _findDeserializer ( DeserializationContext ctxt , String typeId ) throws IOException { JsonDeserializer < Object > deser = _deserializers . get ( typeId ) ; if ( deser == null ) { JavaType type = _idResolver . typeFromId ( ctxt , typeId ) ; if ( type == null ) { deser = _find... | protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt,
String typeId) throws IOException
{
JsonDeserializer<Object> deser = _deserializers.get(typeId);
if (deser == null) {
/* As per [Databind#305], need to provide contextual info. But for
... | protected final JsonDeserializer < Object > _findDeserializer ( DeserializationContext ctxt , String typeId ) throws IOException { JsonDeserializer < Object > deser = _deserializers . get ( typeId ) ; if ( deser == null ) { JavaType type = _idResolver . typeFromId ( ctxt , typeId ) ; if ( type == null ) { deser = _find... |
JxPath | 12 | src/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java | 87 | 136 | Incomplete handling of undefined namespaces | Mcduffey, Joe <jdmcduf@nsa.gov>
Can someone tell me how to register namespaces so that attributes with namespaces does not cause the exception
org.apache.common.ri.model.dom.DOMNodePointer.createAttribute
unknown namespace prefix: xsi
For example the following
<ElementA A:myAttr="Mytype">
<B:ElementB>MY VALUE</B:... | public static boolean testNode(Node node, NodeTest test) {
if (test == null) {
return true;
}
if (test instanceof NodeNameTest) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
return false;
}
NodeNameTest nodeNameTest = (NodeNameT... | public static boolean testNode ( Node node , NodeTest test ) { if ( test == null ) { return true ; } if ( test instanceof NodeNameTest ) { if ( node . getNodeType ( ) != Node . ELEMENT_NODE ) { return false ; } NodeNameTest nodeNameTest = ( NodeNameTest ) test ; QName testName = nodeNameTest . getNodeName ( ) ; String ... | public static boolean testNode(Node node, NodeTest test) {
if (test == null) {
return true;
}
if (test instanceof NodeNameTest) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
return false;
}
NodeNameTest nodeNameTest = (NodeNameT... | public static boolean testNode ( Node node , NodeTest test ) { if ( test == null ) { return true ; } if ( test instanceof NodeNameTest ) { if ( node . getNodeType ( ) != Node . ELEMENT_NODE ) { return false ; } NodeNameTest nodeNameTest = ( NodeNameTest ) test ; QName testName = nodeNameTest . getNodeName ( ) ; String ... |
Math | 63 | src/main/java/org/apache/commons/math/util/MathUtils.java | 416 | 418 | 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.
| 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 ( Double . isNaN ( x ) && Double . isNaN ( y ) ) || x == y ; } | public static boolean equals(double x, double y) {
return equals(x, y, 1);
} | public static boolean equals ( double x , double y ) { return equals ( x , y , 1 ) ; } |
Cli | 35 | src/main/java/org/apache/commons/cli/Options.java | 233 | 250 | LongOpt falsely detected as ambiguous | Options options = new Options();
options.addOption(Option.builder().longOpt("importToOpen").hasArg().argName("FILE").build());
options.addOption(Option.builder("i").longOpt("import").hasArg().argName("FILE").build());
Parsing "--import=FILE" is not possible since 1.3 as it throws a AmbiguousOptionException stating tha... | public List<String> getMatchingOptions(String opt)
{
opt = Util.stripLeadingHyphens(opt);
List<String> matchingOpts = new ArrayList<String>();
// for a perfect match return the single option only
for (String longOpt : longOpts.keySet())
{
if (longOpt.st... | public List < String > getMatchingOptions ( String opt ) { opt = Util . stripLeadingHyphens ( opt ) ; List < String > matchingOpts = new ArrayList < String > ( ) ; for ( String longOpt : longOpts . keySet ( ) ) { if ( longOpt . startsWith ( opt ) ) { matchingOpts . add ( longOpt ) ; } } return matchingOpts ; } | public List<String> getMatchingOptions(String opt)
{
opt = Util.stripLeadingHyphens(opt);
List<String> matchingOpts = new ArrayList<String>();
// for a perfect match return the single option only
if(longOpts.keySet().contains(opt)) {
return Collections.singleton... | public List < String > getMatchingOptions ( String opt ) { opt = Util . stripLeadingHyphens ( opt ) ; List < String > matchingOpts = new ArrayList < String > ( ) ; if ( longOpts . keySet ( ) . contains ( opt ) ) { return Collections . singletonList ( opt ) ; } for ( String longOpt : longOpts . keySet ( ) ) { if ( longO... |
Math | 34 | src/main/java/org/apache/commons/math3/genetics/ListPopulation.java | 208 | 210 | 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. | public Iterator<Chromosome> iterator() {
return chromosomes.iterator();
} | public Iterator < Chromosome > iterator ( ) { return chromosomes . iterator ( ) ; } | public Iterator<Chromosome> iterator() {
return getChromosomes().iterator();
} | public Iterator < Chromosome > iterator ( ) { return getChromosomes ( ) . iterator ( ) ; } |
Cli | 23 | src/java/org/apache/commons/cli/HelpFormatter.java | 805 | 841 | infinite loop in the wrapping code of HelpFormatter | If there is not enough space to display a word on a single line, HelpFormatter goes into a infinite loops until the JVM crashes with an OutOfMemoryError.
Test case:
{code}
Options options = new Options();
options.addOption("h", "help", false, "This is a looooong description");
HelpFormatter formatter = new HelpForma... | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.app... | protected StringBuffer renderWrappedText ( StringBuffer sb , int width , int nextLineTabStop , String text ) { int pos = findWrapPos ( text , width , 0 ) ; if ( pos == - 1 ) { sb . append ( rtrim ( text ) ) ; return sb ; } sb . append ( rtrim ( text . substring ( 0 , pos ) ) ) . append ( defaultNewLine ) ; final String... | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.app... | protected StringBuffer renderWrappedText ( StringBuffer sb , int width , int nextLineTabStop , String text ) { int pos = findWrapPos ( text , width , 0 ) ; if ( pos == - 1 ) { sb . append ( rtrim ( text ) ) ; return sb ; } sb . append ( rtrim ( text . substring ( 0 , pos ) ) ) . append ( defaultNewLine ) ; final String... |
Cli | 5 | src/java/org/apache/commons/cli/Util.java | 34 | 46 | NullPointerException in Util.stripLeadingHyphens when passed a null argument | If you try to do a hasOption(null), you get a NPE:
java.lang.NullPointerException
at org.apache.commons.cli.Util.stripLeadingHyphens(Util.java:39)
at org.apache.commons.cli.CommandLine.resolveOption(CommandLine.java:166)
at org.apache.commons.cli.CommandLine.hasOption(CommandLine.java:68)
Either hasOption should r... | static String stripLeadingHyphens(String str)
{
if (str.startsWith("--"))
{
return str.substring(2, str.length());
}
else if (str.startsWith("-"))
{
return str.substring(1, str.length());
}
return str;
} | static String stripLeadingHyphens ( String str ) { if ( str . startsWith ( "--" ) ) { return str . substring ( 2 , str . length ( ) ) ; } else if ( str . startsWith ( "-" ) ) { return str . substring ( 1 , str . length ( ) ) ; } return str ; } | static String stripLeadingHyphens(String str)
{
if (str == null) {
return null;
}
if (str.startsWith("--"))
{
return str.substring(2, str.length());
}
else if (str.startsWith("-"))
{
return str.substring(1, str.length());
... | static String stripLeadingHyphens ( String str ) { if ( str == null ) { return null ; } if ( str . startsWith ( "--" ) ) { return str . substring ( 2 , str . length ( ) ) ; } else if ( str . startsWith ( "-" ) ) { return str . substring ( 1 , str . length ( ) ) ; } return str ; } |
JacksonDatabind | 47 | src/main/java/com/fasterxml/jackson/databind/AnnotationIntrospector.java | 795 | 896 | `@JsonSerialize(as=superType)` behavior disallowed in 2.7.4 | #1178 fixed the problem with collections, but I'm seeing a problem with individual objects.
I'm getting:
```
com.fasterxml.jackson.databind.JsonMappingException: Failed to widen type [simple type, class org.pharmgkb.model.AccessionIdentifier] with annotation (value org.pharmgkb.model.BaseAccessionIdentifier), from 'g... | public JavaType refineSerializationType(final MapperConfig<?> config,
final Annotated a, final JavaType baseType) throws JsonMappingException
{
JavaType type = baseType;
final TypeFactory tf = config.getTypeFactory();
// 10-Oct-2015, tatu: For 2.7, we'll need to delegate... | public JavaType refineSerializationType ( final MapperConfig < ? > config , final Annotated a , final JavaType baseType ) throws JsonMappingException { JavaType type = baseType ; final TypeFactory tf = config . getTypeFactory ( ) ; Class < ? > serClass = findSerializationType ( a ) ; if ( serClass != null ) { if ( type... | public JavaType refineSerializationType(final MapperConfig<?> config,
final Annotated a, final JavaType baseType) throws JsonMappingException
{
JavaType type = baseType;
final TypeFactory tf = config.getTypeFactory();
// 10-Oct-2015, tatu: For 2.7, we'll need to delegate... | public JavaType refineSerializationType ( final MapperConfig < ? > config , final Annotated a , final JavaType baseType ) throws JsonMappingException { JavaType type = baseType ; final TypeFactory tf = config . getTypeFactory ( ) ; Class < ? > serClass = findSerializationType ( a ) ; if ( serClass != null ) { if ( type... |
Math | 75 | src/main/java/org/apache/commons/math/stat/Frequency.java | 301 | 304 | 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(Obj... | @Deprecated
public double getPct(Object v) {
return getCumPct((Comparable<?>) v);
} | @ Deprecated public double getPct ( Object v ) { return getCumPct ( ( Comparable < ? > ) v ) ; } | @Deprecated
public double getPct(Object v) {
return getPct((Comparable<?>) v);
} | @ Deprecated public double getPct ( Object v ) { return getPct ( ( Comparable < ? > ) v ) ; } |
JacksonCore | 7 | src/main/java/com/fasterxml/jackson/core/json/JsonWriteContext.java | 166 | 185 | Add a check so `JsonGenerator.writeString()` won't work if `writeFieldName()` expected. | Looks like calling `writeString()` (and perhaps other scalar write methods) results in writing invalid output, instead of throwing an exception. It should instead fail; in future we may want to consider allowing this as an alias, but at any rate it should not produce invalid output.
| public int writeValue() {
// Most likely, object:
if (_type == TYPE_OBJECT) {
_gotName = false;
++_index;
return STATUS_OK_AFTER_COLON;
}
// Ok, array?
if (_type == TYPE_ARRAY) {
int ix = _index;
++_index;
r... | public int writeValue ( ) { if ( _type == TYPE_OBJECT ) { _gotName = false ; ++ _index ; return STATUS_OK_AFTER_COLON ; } if ( _type == TYPE_ARRAY ) { int ix = _index ; ++ _index ; return ( ix < 0 ) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_COMMA ; } ++ _index ; return ( _index == 0 ) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_SPAC... | public int writeValue() {
// Most likely, object:
if (_type == TYPE_OBJECT) {
if (!_gotName) {
return STATUS_EXPECT_NAME;
}
_gotName = false;
++_index;
return STATUS_OK_AFTER_COLON;
}
// Ok, array?
if (_... | public int writeValue ( ) { if ( _type == TYPE_OBJECT ) { if ( ! _gotName ) { return STATUS_EXPECT_NAME ; } _gotName = false ; ++ _index ; return STATUS_OK_AFTER_COLON ; } if ( _type == TYPE_ARRAY ) { int ix = _index ; ++ _index ; return ( ix < 0 ) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_COMMA ; } ++ _index ; return ( _ind... |
Math | 3 | src/main/java/org/apache/commons/math3/util/MathArrays.java | 814 | 872 | 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. | 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.
fin... | 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 ) ; } final double [ ] prodHigh = new double [ len ] ; double prodLowSum = 0 ; for ( int ... | 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 mult... | 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 ) { return a [ 0 ] * b [ 0 ] ; } final double [ ] prodHigh = new doub... |
Math | 59 | src/main/java/org/apache/commons/math/util/FastMath.java | 3481 | 3483 | 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. | 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 : b ) ; } | public static float max(final float a, final float b) {
return (a <= b) ? b : (Float.isNaN(a + b) ? Float.NaN : a);
} | public static float max ( final float a , final float b ) { return ( a <= b ) ? b : ( Float . isNaN ( a + b ) ? Float . NaN : a ) ; } |
Compress | 40 | src/main/java/org/apache/commons/compress/utils/BitInputStream.java | 81 | 109 | Overflow in BitInputStream | in Class BitInputStream.java(\src\main\java\org\apache\commons\compress\utils),
funcion:
public long readBits(final int count) throws IOException {
if (count < 0 || count > MAXIMUM_CACHE_SIZE) {
throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM_CACHE_SIZE);... | public long readBits(final int count) throws IOException {
if (count < 0 || count > MAXIMUM_CACHE_SIZE) {
throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM_CACHE_SIZE);
}
while (bitsCachedSize < count) {
final long nextByte = in.re... | public long readBits ( final int count ) throws IOException { if ( count < 0 || count > MAXIMUM_CACHE_SIZE ) { throw new IllegalArgumentException ( "count must not be negative or greater than " + MAXIMUM_CACHE_SIZE ) ; } while ( bitsCachedSize < count ) { final long nextByte = in . read ( ) ; if ( nextByte < 0 ) { retu... | public long readBits(final int count) throws IOException {
if (count < 0 || count > MAXIMUM_CACHE_SIZE) {
throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM_CACHE_SIZE);
}
while (bitsCachedSize < count && bitsCachedSize < 57) {
fina... | public long readBits ( final int count ) throws IOException { if ( count < 0 || count > MAXIMUM_CACHE_SIZE ) { throw new IllegalArgumentException ( "count must not be negative or greater than " + MAXIMUM_CACHE_SIZE ) ; } while ( bitsCachedSize < count && bitsCachedSize < 57 ) { final long nextByte = in . read ( ) ; if ... |
Compress | 17 | src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java | 102 | 151 | Tar file for Android backup cannot be read | Attached tar file was generated by some kind of backup tool on Android. Normal tar utilities seem to handle it fine, but Commons Compress doesn't.
{noformat}
java.lang.IllegalArgumentException: Invalid byte 0 at offset 5 in '01750{NUL}{NUL}{NUL}' len=8
at org.apache.commons.compress.archivers.tar.TarUtils.parseOct... | public static long parseOctal(final byte[] buffer, final int offset, final int length) {
long result = 0;
int end = offset + length;
int start = offset;
if (length < 2){
throw new IllegalArgumentException("Length "+length+" must be at least 2");
}
... | public static long parseOctal ( final byte [ ] buffer , final int offset , final int length ) { long result = 0 ; int end = offset + length ; int start = offset ; if ( length < 2 ) { throw new IllegalArgumentException ( "Length " + length + " must be at least 2" ) ; } if ( buffer [ start ] == 0 ) { return 0L ; } while ... | public static long parseOctal(final byte[] buffer, final int offset, final int length) {
long result = 0;
int end = offset + length;
int start = offset;
if (length < 2){
throw new IllegalArgumentException("Length "+length+" must be at least 2");
}
... | public static long parseOctal ( final byte [ ] buffer , final int offset , final int length ) { long result = 0 ; int end = offset + length ; int start = offset ; if ( length < 2 ) { throw new IllegalArgumentException ( "Length " + length + " must be at least 2" ) ; } if ( buffer [ start ] == 0 ) { return 0L ; } while ... |
Cli | 19 | src/java/org/apache/commons/cli/PosixParser.java | 227 | 239 | PosixParser ignores unrecognized tokens starting with '-' | PosixParser doesn't handle properly unrecognized tokens starting with '-' when stopAtNonOption is enabled, the token is simply ignored.
For example, if the option 'a' is defined, the following command line:
{code}-z -a foo{code}
is interpreted as:
{code}-a foo{code} | private void processOptionToken(String token, boolean stopAtNonOption)
{
if (options.hasOption(token))
{
currentOption = options.getOption(token);
tokens.add(token);
}
else if (stopAtNonOption)
{
eatTheRest = true;
tokens.add(to... | private void processOptionToken ( String token , boolean stopAtNonOption ) { if ( options . hasOption ( token ) ) { currentOption = options . getOption ( token ) ; tokens . add ( token ) ; } else if ( stopAtNonOption ) { eatTheRest = true ; tokens . add ( token ) ; } } | private void processOptionToken(String token, boolean stopAtNonOption)
{
if (options.hasOption(token))
{
currentOption = options.getOption(token);
}
else if (stopAtNonOption)
{
eatTheRest = true;
}
tokens.add(token);
} | private void processOptionToken ( String token , boolean stopAtNonOption ) { if ( options . hasOption ( token ) ) { currentOption = options . getOption ( token ) ; } else if ( stopAtNonOption ) { eatTheRest = true ; } tokens . add ( token ) ; } |
Cli | 12 | src/java/org/apache/commons/cli/GnuParser.java | 52 | 110 | PosixParser interupts "-target opt" as "-t arget opt" | This was posted on the Commons-Developer list and confirmed as a bug.
> Is this a bug? Or am I using this incorrectly?
> I have an option with short and long values. Given code that is
> essentially what is below, with a PosixParser I see results as
> follows:
>
> A command line with just "-t" prints out the resu... | protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption)
{
List tokens = new ArrayList();
boolean eatTheRest = false;
for (int i = 0; i < arguments.length; i++)
{
String arg = arguments[i];
if ("--".equals(arg))
{... | protected String [ ] flatten ( Options options , String [ ] arguments , boolean stopAtNonOption ) { List tokens = new ArrayList ( ) ; boolean eatTheRest = false ; for ( int i = 0 ; i < arguments . length ; i ++ ) { String arg = arguments [ i ] ; if ( "--" . equals ( arg ) ) { eatTheRest = true ; tokens . add ( "--" ) ;... | protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption)
{
List tokens = new ArrayList();
boolean eatTheRest = false;
for (int i = 0; i < arguments.length; i++)
{
String arg = arguments[i];
if ("--".equals(arg))
{... | protected String [ ] flatten ( Options options , String [ ] arguments , boolean stopAtNonOption ) { List tokens = new ArrayList ( ) ; boolean eatTheRest = false ; for ( int i = 0 ; i < arguments . length ; i ++ ) { String arg = arguments [ i ] ; if ( "--" . equals ( arg ) ) { eatTheRest = true ; tokens . add ( "--" ) ;... |
Math | 13 | src/main/java/org/apache/commons/math3/optimization/general/AbstractLeastSquaresOptimizer.java | 561 | 564 | new multivariate vector optimizers cannot be used with large number of weights | When using the Weigth class to pass a large number of weights to multivariate vector optimizers, an nxn full matrix is created (and copied) when a n elements vector is used. This exhausts memory when n is large.
This happens for example when using curve fitters (even simple curve fitters like polynomial ones for low d... | private RealMatrix squareRoot(RealMatrix m) {
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
} | private RealMatrix squareRoot ( RealMatrix m ) { final EigenDecomposition dec = new EigenDecomposition ( m ) ; return dec . getSquareRoot ( ) ; } | private RealMatrix squareRoot(RealMatrix m) {
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
... | private RealMatrix squareRoot ( RealMatrix m ) { if ( m instanceof DiagonalMatrix ) { final int dim = m . getRowDimension ( ) ; final RealMatrix sqrtM = new DiagonalMatrix ( dim ) ; for ( int i = 0 ; i < dim ; i ++ ) { sqrtM . setEntry ( i , i , FastMath . sqrt ( m . getEntry ( i , i ) ) ) ; } return sqrtM ; } else { f... |
JacksonDatabind | 76 | src/main/java/com/fasterxml/jackson/databind/deser/BuilderBasedDeserializer.java | 565 | 637 | Missing properties when deserializing using a builder class with a non-default constructor and a mutator annotated with `@JsonUnwrapped` | When deserializing using a builder class with a non-default constructor and any number of mutator methods annotated with @JsonUnwrapped, the `BuilderBasedDeserializer::deserializeUsingPropertyBasedWithUnwrapped` method cuts short the process of adding SettableBeanProperties.
The logic dictates that once all properti... | @SuppressWarnings("resource")
protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p,
DeserializationContext ctxt)
throws IOException, JsonProcessingException
{
final PropertyBasedCreator creator = _propertyBasedCreator;
PropertyValueBuffer buffer = creator.startB... | @ SuppressWarnings ( "resource" ) protected Object deserializeUsingPropertyBasedWithUnwrapped ( JsonParser p , DeserializationContext ctxt ) throws IOException , JsonProcessingException { final PropertyBasedCreator creator = _propertyBasedCreator ; PropertyValueBuffer buffer = creator . startBuilding ( p , ctxt , _obje... | @SuppressWarnings("resource")
protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p,
DeserializationContext ctxt)
throws IOException, JsonProcessingException
{
final PropertyBasedCreator creator = _propertyBasedCreator;
PropertyValueBuffer buffer = creator.startB... | @ SuppressWarnings ( "resource" ) protected Object deserializeUsingPropertyBasedWithUnwrapped ( JsonParser p , DeserializationContext ctxt ) throws IOException , JsonProcessingException { final PropertyBasedCreator creator = _propertyBasedCreator ; PropertyValueBuffer buffer = creator . startBuilding ( p , ctxt , _obje... |
JacksonDatabind | 99 | src/main/java/com/fasterxml/jackson/databind/type/ReferenceType.java | 162 | 170 | Canonical string for reference type is built incorrectly | Canonical string for reference type is built incorrectly.
E.g.:
`new ReferenceType(new TypeFactory(new LRUMap<Object, JavaType>(0, 10000)).constructType(Object.class), new PlaceholderForType(0)).toCanonical()`
yields:
`java.lang.Object<$1`
while the expected value is:
`java.lang.Object<$1>` | @Override
protected String buildCanonicalName()
{
StringBuilder sb = new StringBuilder();
sb.append(_class.getName());
sb.append('<');
sb.append(_referencedType.toCanonical());
return sb.toString();
} | @ Override protected String buildCanonicalName ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( _class . getName ( ) ) ; sb . append ( '<' ) ; sb . append ( _referencedType . toCanonical ( ) ) ; return sb . toString ( ) ; } | @Override
protected String buildCanonicalName()
{
StringBuilder sb = new StringBuilder();
sb.append(_class.getName());
sb.append('<');
sb.append(_referencedType.toCanonical());
sb.append('>');
return sb.toString();
} | @ Override protected String buildCanonicalName ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( _class . getName ( ) ) ; sb . append ( '<' ) ; sb . append ( _referencedType . toCanonical ( ) ) ; sb . append ( '>' ) ; return sb . toString ( ) ; } |
Math | 44 | src/main/java/org/apache/commons/math/ode/AbstractIntegrator.java | 274 | 374 | Incomplete reinitialization with some events handling | I get a bug with event handling: I track 2 events that occur in the same step, when the first one is accepted, it resets the state but the reinitialization is not complete and the second one becomes unable to find its way.
I can't give my context, which is rather large, but I tried a patch that works for me, unfortunat... | protected double acceptStep(final AbstractStepInterpolator interpolator,
final double[] y, final double[] yDot, final double tEnd)
throws MathIllegalStateException {
double previousT = interpolator.getGlobalPreviousTime();
final double currentT = interpol... | protected double acceptStep ( final AbstractStepInterpolator interpolator , final double [ ] y , final double [ ] yDot , final double tEnd ) throws MathIllegalStateException { double previousT = interpolator . getGlobalPreviousTime ( ) ; final double currentT = interpolator . getGlobalCurrentTime ( ) ; resetOccurred = ... | protected double acceptStep(final AbstractStepInterpolator interpolator,
final double[] y, final double[] yDot, final double tEnd)
throws MathIllegalStateException {
double previousT = interpolator.getGlobalPreviousTime();
final double currentT = interpol... | protected double acceptStep ( final AbstractStepInterpolator interpolator , final double [ ] y , final double [ ] yDot , final double tEnd ) throws MathIllegalStateException { double previousT = interpolator . getGlobalPreviousTime ( ) ; final double currentT = interpolator . getGlobalCurrentTime ( ) ; if ( ! statesIni... |
JacksonDatabind | 60 | src/main/java/com/fasterxml/jackson/databind/ser/std/JsonValueSerializer.java | 195 | 242 | Polymorphic type lost when using `@JsonValue` | When suppressing all getters but one with @JsonIgnore and choosing to use a byte array for serialization (marking its getter with @JsonValue), the typing of the object is changed to "[B", which is deserialized to a byte array. I would have expected verbose typing and usage of the constructor marked with @JsonCreator t... | @Override
public void serializeWithType(Object bean, JsonGenerator gen, SerializerProvider provider,
TypeSerializer typeSer0) throws IOException
{
// Regardless of other parts, first need to find value to serialize:
Object value = null;
try {
value = _accessorMeth... | @ Override public void serializeWithType ( Object bean , JsonGenerator gen , SerializerProvider provider , TypeSerializer typeSer0 ) throws IOException { Object value = null ; try { value = _accessorMethod . getValue ( bean ) ; if ( value == null ) { provider . defaultSerializeNull ( gen ) ; return ; } JsonSerializer <... | @Override
public void serializeWithType(Object bean, JsonGenerator gen, SerializerProvider provider,
TypeSerializer typeSer0) throws IOException
{
// Regardless of other parts, first need to find value to serialize:
Object value = null;
try {
value = _accessorMeth... | @ Override public void serializeWithType ( Object bean , JsonGenerator gen , SerializerProvider provider , TypeSerializer typeSer0 ) throws IOException { Object value = null ; try { value = _accessorMethod . getValue ( bean ) ; if ( value == null ) { provider . defaultSerializeNull ( gen ) ; return ; } JsonSerializer <... |
Math | 8 | src/main/java/org/apache/commons/math3/distribution/DiscreteDistribution.java | 181 | 195 | 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.
... | 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).get... | 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 ( ) , sampleS... | 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 <... | 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 ( ... |
Math | 52 | src/main/java/org/apache/commons/math/geometry/euclidean/threed/Rotation.java | 313 | 390 | numerical problems in rotation creation | building a rotation from the following vector pairs leads to NaN:
u1 = -4921140.837095533, -2.1512094250440013E7, -890093.279426377
u2 = -2.7238580938724895E9, -2.169664921341876E9, 6.749688708885301E10
v1 = 1, 0, 0
v2 = 0, 0, 1
The constructor first changes the (v1, v2) pair into (v1', v2') ensuring the following sca... | public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2) {
// norms computation
double u1u1 = u1.getNormSq();
double u2u2 = u2.getNormSq();
double v1v1 = v1.getNormSq();
double v2v2 = v2.getNormSq();
if ((u1u1 == 0) || (u2u2 == 0) || (v1v1 == 0) || (v2v2 == 0)) {
throw MathRuntimeException.c... | public Rotation ( Vector3D u1 , Vector3D u2 , Vector3D v1 , Vector3D v2 ) { double u1u1 = u1 . getNormSq ( ) ; double u2u2 = u2 . getNormSq ( ) ; double v1v1 = v1 . getNormSq ( ) ; double v2v2 = v2 . getNormSq ( ) ; if ( ( u1u1 == 0 ) || ( u2u2 == 0 ) || ( v1v1 == 0 ) || ( v2v2 == 0 ) ) { throw MathRuntimeException . c... | public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2) {
// norms computation
double u1u1 = u1.getNormSq();
double u2u2 = u2.getNormSq();
double v1v1 = v1.getNormSq();
double v2v2 = v2.getNormSq();
if ((u1u1 == 0) || (u2u2 == 0) || (v1v1 == 0) || (v2v2 == 0)) {
throw MathRuntimeException.c... | public Rotation ( Vector3D u1 , Vector3D u2 , Vector3D v1 , Vector3D v2 ) { double u1u1 = u1 . getNormSq ( ) ; double u2u2 = u2 . getNormSq ( ) ; double v1v1 = v1 . getNormSq ( ) ; double v2v2 = v2 . getNormSq ( ) ; if ( ( u1u1 == 0 ) || ( u2u2 == 0 ) || ( v1v1 == 0 ) || ( v2v2 == 0 ) ) { throw MathRuntimeException . c... |
JacksonDatabind | 37 | src/main/java/com/fasterxml/jackson/databind/type/SimpleType.java | 119 | 137 | Field in base class is not recognized, when using `@JsonType.defaultImpl` | When deserializing JSON to Java POJOS, a field inherited from a base class is not recognized. Here is the stack:
```
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "name" (class org.apache.calcite.model.JsonMapSchema), not marked as ignorable (2 known properties: "functions", "tab... | @Override
protected JavaType _narrow(Class<?> subclass)
{
if (_class == subclass) {
return this;
}
// Should we check that there is a sub-class relationship?
// 15-Jan-2016, tatu: Almost yes, but there are some complications with
// placeholder values, so n... | @ Override protected JavaType _narrow ( Class < ? > subclass ) { if ( _class == subclass ) { return this ; } return new SimpleType ( subclass , _bindings , _superClass , _superInterfaces , _valueHandler , _typeHandler , _asStatic ) ; } | @Override
protected JavaType _narrow(Class<?> subclass)
{
if (_class == subclass) {
return this;
}
// Should we check that there is a sub-class relationship?
// 15-Jan-2016, tatu: Almost yes, but there are some complications with
// placeholder values, so n... | @ Override protected JavaType _narrow ( Class < ? > subclass ) { if ( _class == subclass ) { return this ; } return new SimpleType ( subclass , _bindings , this , _superInterfaces , _valueHandler , _typeHandler , _asStatic ) ; } |
Mockito | 36 | src/org/mockito/internal/invocation/Invocation.java | 201 | 203 | Inform the user immediately when she tries to 'callRealMethod()' on a mock of a interface | Inform the user immediately when she tries to 'callRealMethod()' on a mock of a interface: //fail fast when: when(mockOfAnIterface.doStuff()).thenCallRealMethod(); | public Object callRealMethod() throws Throwable {
return realMethod.invoke(mock, rawArguments);
} | 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);
} | public Object callRealMethod ( ) throws Throwable { if ( this . getMethod ( ) . getDeclaringClass ( ) . isInterface ( ) ) { new Reporter ( ) . cannotCallRealMethodOnInterface ( ) ; } return realMethod . invoke ( mock , rawArguments ) ; } |
Math | 91 | src/java/org/apache/commons/math/fraction/Fraction.java | 258 | 262 | 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.
{code}
// 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)... | 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 ) { 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);
} | 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 ) ; } |
Cli | 28 | src/java/org/apache/commons/cli/Parser.java | 252 | 296 | Default options may be partially processed | The Properties instance passed to the Parser.parse() method to initialize the default options may be partially processed. This happens when the properties contains an option that doesn't accept arguments and has a default value that isn't evaluated to "true". When this case occurs the processing of the properties is st... | protected void processProperties(Properties properties)
{
if (properties == null)
{
return;
}
for (Enumeration e = properties.propertyNames(); e.hasMoreElements();)
{
String option = e.nextElement().toString();
if (!cmd.hasOption(option))... | protected void processProperties ( Properties properties ) { if ( properties == null ) { return ; } for ( Enumeration e = properties . propertyNames ( ) ; e . hasMoreElements ( ) ; ) { String option = e . nextElement ( ) . toString ( ) ; if ( ! cmd . hasOption ( option ) ) { Option opt = getOptions ( ) . getOption ( op... | protected void processProperties(Properties properties)
{
if (properties == null)
{
return;
}
for (Enumeration e = properties.propertyNames(); e.hasMoreElements();)
{
String option = e.nextElement().toString();
if (!cmd.hasOption(option))... | protected void processProperties ( Properties properties ) { if ( properties == null ) { return ; } for ( Enumeration e = properties . propertyNames ( ) ; e . hasMoreElements ( ) ; ) { String option = e . nextElement ( ) . toString ( ) ; if ( ! cmd . hasOption ( option ) ) { Option opt = getOptions ( ) . getOption ( op... |
Compress | 26 | src/main/java/org/apache/commons/compress/utils/IOUtils.java | 94 | 105 | IOUtils.skip does not work as advertised | I am trying to feed a TarInputStream from a CipherInputStream.
It does not work, because IOUtils.skip() does not adhere to the contract it claims in javadoc:
" * <p>This method will only skip less than the requested number of
* bytes if the end of the input stream has been reached.</p>"
However it does:
... | public static long skip(InputStream input, long numToSkip) throws IOException {
long available = numToSkip;
while (numToSkip > 0) {
long skipped = input.skip(numToSkip);
if (skipped == 0) {
break;
}
numToSkip -= skipped;
}
... | public static long skip ( InputStream input , long numToSkip ) throws IOException { long available = numToSkip ; while ( numToSkip > 0 ) { long skipped = input . skip ( numToSkip ) ; if ( skipped == 0 ) { break ; } numToSkip -= skipped ; } return available - numToSkip ; } | public static long skip(InputStream input, long numToSkip) throws IOException {
long available = numToSkip;
while (numToSkip > 0) {
long skipped = input.skip(numToSkip);
if (skipped == 0) {
break;
}
numToSkip -= skipped;
}
... | public static long skip ( InputStream input , long numToSkip ) throws IOException { long available = numToSkip ; while ( numToSkip > 0 ) { long skipped = input . skip ( numToSkip ) ; if ( skipped == 0 ) { break ; } numToSkip -= skipped ; } if ( numToSkip > 0 ) { byte [ ] skipBuf = new byte [ SKIP_BUF_SIZE ] ; while ( n... |
JacksonDatabind | 108 | src/main/java/com/fasterxml/jackson/databind/ObjectReader.java | 1166 | 1170 | Change of behavior (2.8 -> 2.9) with `ObjectMapper.readTree(input)` with no content | So, it looks like `readTree()` methods in `ObjectMapper`, `ObjectReader` that take input OTHER than `JsonParser`, and are given "empty input" (only white-space available before end), will
* Return `NullNode` (Jackson 2.x up to and including 2.8)
* Return `null` (Jackson 2.9)
Latter behavior is what `readTree(Jso... | @SuppressWarnings("unchecked")
@Override
public <T extends TreeNode> T readTree(JsonParser p) throws IOException {
return (T) _bindAsTree(p);
} | @ SuppressWarnings ( "unchecked" ) @ Override public < T extends TreeNode > T readTree ( JsonParser p ) throws IOException { return ( T ) _bindAsTree ( p ) ; } | @SuppressWarnings("unchecked")
@Override
public <T extends TreeNode> T readTree(JsonParser p) throws IOException {
return (T) _bindAsTreeOrNull(p);
} | @ SuppressWarnings ( "unchecked" ) @ Override public < T extends TreeNode > T readTree ( JsonParser p ) throws IOException { return ( T ) _bindAsTreeOrNull ( p ) ; } |
Compress | 9 | src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveOutputStream.java | 266 | 331 | TarArchiveOutputStream.getBytesWritten() returns invalid value | It appears the TarArchiveOutputStream.getBytesWritten()returns zero or invalid value when queried.
In the code sample below, it returns zero, even after an sizeable file was processed.
I've printed it twice, once before closing the output stream, and once after, just for the reference.
It is also demonstrable on multip... | @Override
public void write(byte[] wBuf, int wOffset, int numToWrite) throws IOException {
if ((currBytes + numToWrite) > currSize) {
throw new IOException("request to write '" + numToWrite
+ "' bytes exceeds size in header of '"
... | @ Override public void write ( byte [ ] wBuf , int wOffset , int numToWrite ) throws IOException { if ( ( currBytes + numToWrite ) > currSize ) { throw new IOException ( "request to write '" + numToWrite + "' bytes exceeds size in header of '" + currSize + "' bytes for entry '" + currName + "'" ) ; } if ( assemLen > 0 ... | @Override
public void write(byte[] wBuf, int wOffset, int numToWrite) throws IOException {
if ((currBytes + numToWrite) > currSize) {
throw new IOException("request to write '" + numToWrite
+ "' bytes exceeds size in header of '"
... | @ Override public void write ( byte [ ] wBuf , int wOffset , int numToWrite ) throws IOException { if ( ( currBytes + numToWrite ) > currSize ) { throw new IOException ( "request to write '" + numToWrite + "' bytes exceeds size in header of '" + currSize + "' bytes for entry '" + currName + "'" ) ; } if ( assemLen > 0 ... |
Compress | 30 | src/main/java/org/apache/commons/compress/compressors/bzip2/BZip2CompressorInputStream.java | 152 | 179 | BZip2CompressorInputStream return value wrong when told to read to a full buffer. | BZip2CompressorInputStream.read(buffer, offset, length) returns -1 when given an offset equal to the length of the buffer.
This indicates, not that the buffer was full, but that the stream was finished.
It seems like a pretty stupid thing to do - but I'm getting this when trying to use Kryo serialization (which is pr... | @Override
public int read(final byte[] dest, final int offs, final int len)
throws IOException {
if (offs < 0) {
throw new IndexOutOfBoundsException("offs(" + offs + ") < 0.");
}
if (len < 0) {
throw new IndexOutOfBoundsException("len(" + len + ") < 0.");
... | @ Override public int read ( final byte [ ] dest , final int offs , final int len ) throws IOException { if ( offs < 0 ) { throw new IndexOutOfBoundsException ( "offs(" + offs + ") < 0." ) ; } if ( len < 0 ) { throw new IndexOutOfBoundsException ( "len(" + len + ") < 0." ) ; } if ( offs + len > dest . length ) { throw ... | @Override
public int read(final byte[] dest, final int offs, final int len)
throws IOException {
if (offs < 0) {
throw new IndexOutOfBoundsException("offs(" + offs + ") < 0.");
}
if (len < 0) {
throw new IndexOutOfBoundsException("len(" + len + ") < 0.");
... | @ Override public int read ( final byte [ ] dest , final int offs , final int len ) throws IOException { if ( offs < 0 ) { throw new IndexOutOfBoundsException ( "offs(" + offs + ") < 0." ) ; } if ( len < 0 ) { throw new IndexOutOfBoundsException ( "len(" + len + ") < 0." ) ; } if ( offs + len > dest . length ) { throw ... |
Codec | 3 | src/java/org/apache/commons/codec/language/DoubleMetaphone.java | 418 | 469 | Double Metaphone bugs in alternative encoding | The new test case (CODEC-83) has highlighted a number of issues with the "alternative" encoding in the Double Metaphone implementation
1) Bug in the handleG method when "G" is followed by "IER"
* The alternative encoding of "Angier" results in "ANKR" rather than "ANJR"
* The alternative encoding of "rogier" resul... | private int handleG(String value,
DoubleMetaphoneResult result,
int index,
boolean slavoGermanic) {
if (charAt(value, index + 1) == 'H') {
index = handleGH(value, result, index);
} else if (charAt(value, index + 1) ==... | private int handleG ( String value , DoubleMetaphoneResult result , int index , boolean slavoGermanic ) { if ( charAt ( value , index + 1 ) == 'H' ) { index = handleGH ( value , result , index ) ; } else if ( charAt ( value , index + 1 ) == 'N' ) { if ( index == 1 && isVowel ( charAt ( value , 0 ) ) && ! slavoGermanic ... | private int handleG(String value,
DoubleMetaphoneResult result,
int index,
boolean slavoGermanic) {
if (charAt(value, index + 1) == 'H') {
index = handleGH(value, result, index);
} else if (charAt(value, index + 1) ==... | private int handleG ( String value , DoubleMetaphoneResult result , int index , boolean slavoGermanic ) { if ( charAt ( value , index + 1 ) == 'H' ) { index = handleGH ( value , result , index ) ; } else if ( charAt ( value , index + 1 ) == 'N' ) { if ( index == 1 && isVowel ( charAt ( value , 0 ) ) && ! slavoGermanic ... |
Mockito | 20 | src/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java | 24 | 53 | Allow convenient spying on abstract classes | I posted this in GoogleCode and was asked to submit in github.
Mockito is easy to use when the test needs to provide canned values for a certain method.
But it gets harder when a canned value isn't sufficient.
##### Example 1: Fake with trivial Logic
```
interface UserAccount {
List<String> getEmails();
void add... | public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
if (settings.getSerializableMode() == SerializableMode.ACROSS_CLASSLOADERS) {
throw new MockitoException("Serialization across classloaders not yet supported with ByteBuddyMockMaker");
}
Class<? extends ... | public < T > T createMock ( MockCreationSettings < T > settings , MockHandler handler ) { if ( settings . getSerializableMode ( ) == SerializableMode . ACROSS_CLASSLOADERS ) { throw new MockitoException ( "Serialization across classloaders not yet supported with ByteBuddyMockMaker" ) ; } Class < ? extends T > mockedPro... | public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
if (settings.getSerializableMode() == SerializableMode.ACROSS_CLASSLOADERS) {
throw new MockitoException("Serialization across classloaders not yet supported with ByteBuddyMockMaker");
}
Class<? extends ... | public < T > T createMock ( MockCreationSettings < T > settings , MockHandler handler ) { if ( settings . getSerializableMode ( ) == SerializableMode . ACROSS_CLASSLOADERS ) { throw new MockitoException ( "Serialization across classloaders not yet supported with ByteBuddyMockMaker" ) ; } Class < ? extends T > mockedPro... |
Chart | 11 | source/org/jfree/chart/util/ShapeUtilities.java | 264 | 296 | JCommon 1.0.12 ShapeUtilities.equal(path1,path2) | The comparison of two GeneralPath objects uses the same PathIterator for both objects. equal(GeneralPath path1, GeneralPath path2) will thus return true for any pair of non-null GeneralPath instances having the same windingRule. | public static boolean equal(GeneralPath p1, GeneralPath p2) {
if (p1 == null) {
return (p2 == null);
}
if (p2 == null) {
return false;
}
if (p1.getWindingRule() != p2.getWindingRule()) {
return false;
}
PathIterator iterator1 = ... | public static boolean equal ( GeneralPath p1 , GeneralPath p2 ) { if ( p1 == null ) { return ( p2 == null ) ; } if ( p2 == null ) { return false ; } if ( p1 . getWindingRule ( ) != p2 . getWindingRule ( ) ) { return false ; } PathIterator iterator1 = p1 . getPathIterator ( null ) ; PathIterator iterator2 = p1 . getPath... | public static boolean equal(GeneralPath p1, GeneralPath p2) {
if (p1 == null) {
return (p2 == null);
}
if (p2 == null) {
return false;
}
if (p1.getWindingRule() != p2.getWindingRule()) {
return false;
}
PathIterator iterator1 = ... | public static boolean equal ( GeneralPath p1 , GeneralPath p2 ) { if ( p1 == null ) { return ( p2 == null ) ; } if ( p2 == null ) { return false ; } if ( p1 . getWindingRule ( ) != p2 . getWindingRule ( ) ) { return false ; } PathIterator iterator1 = p1 . getPathIterator ( null ) ; PathIterator iterator2 = p2 . getPath... |
Math | 87 | src/java/org/apache/commons/math/optimization/linear/SimplexTableau.java | 272 | 284 | 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... | 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 {
retu... | 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, ... | 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 ) ) { r... |
Csv | 6 | src/main/java/org/apache/commons/csv/CSVRecord.java | 179 | 185 | CSVRecord.toMap() fails if row length shorter than header length | Similar to CSV-96, if .toMap() is called on a record that has fewer fields than we have header columns we'll get an ArrayOutOfBoundsException.
{code}
@Test
public void testToMapWhenHeaderTooLong() throws Exception {
final CSVParser parser = new CSVParser("a,b", CSVFormat.newBuilder().withHeader("A", "B", "C").build... | <M extends Map<String, String>> M putIn(final M map) {
for (final Entry<String, Integer> entry : mapping.entrySet()) {
final int col = entry.getValue().intValue();
map.put(entry.getKey(), values[col]);
}
return map;
} | < M extends Map < String , String > > M putIn ( final M map ) { for ( final Entry < String , Integer > entry : mapping . entrySet ( ) ) { final int col = entry . getValue ( ) . intValue ( ) ; map . put ( entry . getKey ( ) , values [ col ] ) ; } return map ; } | <M extends Map<String, String>> M putIn(final M map) {
for (final Entry<String, Integer> entry : mapping.entrySet()) {
final int col = entry.getValue().intValue();
if (col < values.length) {
map.put(entry.getKey(), values[col]);
}
}
return map;... | < M extends Map < String , String > > M putIn ( final M map ) { for ( final Entry < String , Integer > entry : mapping . entrySet ( ) ) { final int col = entry . getValue ( ) . intValue ( ) ; if ( col < values . length ) { map . put ( entry . getKey ( ) , values [ col ] ) ; } } return map ; } |
Csv | 15 | src/main/java/org/apache/commons/csv/CSVFormat.java | 1151 | 1256 | The behavior of quote char using is not similar as Excel does when the first string contains CJK char(s) | When using CSVFormat.EXCEL to print a CSV file, the behavior of quote char using is not similar as Microsoft Excel does when the first string contains Chinese, Japanese or Korean (CJK) char(s).
e.g.
There are 3 data members in a record, with Japanese chars: "あ", "い", "う":
Microsoft Excel outputs:
あ,い,う
Apa... | private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len,
final Appendable out, final boolean newRecord) throws IOException {
boolean quote = false;
int start = offset;
int pos = offset;
final int end = offset + len;
f... | private void printAndQuote ( final Object object , final CharSequence value , final int offset , final int len , final Appendable out , final boolean newRecord ) throws IOException { boolean quote = false ; int start = offset ; int pos = offset ; final int end = offset + len ; final char delimChar = getDelimiter ( ) ; ... | private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len,
final Appendable out, final boolean newRecord) throws IOException {
boolean quote = false;
int start = offset;
int pos = offset;
final int end = offset + len;
f... | private void printAndQuote ( final Object object , final CharSequence value , final int offset , final int len , final Appendable out , final boolean newRecord ) throws IOException { boolean quote = false ; int start = offset ; int pos = offset ; final int end = offset + len ; final char delimChar = getDelimiter ( ) ; ... |
Compress | 10 | src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java | 801 | 843 | Cannot Read Winzip Archives With Unicode Extra Fields | I have a zip file created with WinZip containing Unicode extra fields. Upon attempting to extract it with org.apache.commons.compress.archivers.zip.ZipFile, ZipFile.getInputStream() returns null for ZipArchiveEntries previously retrieved with ZipFile.getEntry() or even ZipFile.getEntries(). See UTF8ZipFilesTest.patch i... | private void resolveLocalFileHeaderData(Map<ZipArchiveEntry, NameAndComment>
entriesWithoutUTF8Flag)
throws IOException {
// changing the name of a ZipArchiveEntry is going to change
// the hashcode - see COMPRESS-164
// Map needs to be reconst... | private void resolveLocalFileHeaderData ( Map < ZipArchiveEntry , NameAndComment > entriesWithoutUTF8Flag ) throws IOException { for ( ZipArchiveEntry ze : entries . keySet ( ) ) { OffsetEntry offsetEntry = entries . get ( ze ) ; long offset = offsetEntry . headerOffset ; archive . seek ( offset + LFH_OFFSET_FOR_FILENA... | private void resolveLocalFileHeaderData(Map<ZipArchiveEntry, NameAndComment>
entriesWithoutUTF8Flag)
throws IOException {
// changing the name of a ZipArchiveEntry is going to change
// the hashcode - see COMPRESS-164
// Map needs to be reconst... | private void resolveLocalFileHeaderData ( Map < ZipArchiveEntry , NameAndComment > entriesWithoutUTF8Flag ) throws IOException { Map < ZipArchiveEntry , OffsetEntry > origMap = new LinkedHashMap < ZipArchiveEntry , OffsetEntry > ( entries ) ; entries . clear ( ) ; for ( ZipArchiveEntry ze : origMap . keySet ( ) ) { Off... |
Math | 48 | src/main/java/org/apache/commons/math/analysis/solvers/BaseSecantSolver.java | 129 | 251 | "RegulaFalsiSolver" failure | The following unit test:
{code}
@Test
public void testBug() {
final UnivariateRealFunction f = new UnivariateRealFunction() {
@Override
public double value(double x) {
return Math.exp(x) - Math.pow(Math.PI, 3.0);
}
};
UnivariateRealSolver solver = new... | protected final double doSolve() {
// Get initial solution
double x0 = getMin();
double x1 = getMax();
double f0 = computeObjectiveValue(x0);
double f1 = computeObjectiveValue(x1);
// If one of the bounds is the exact root, return it. Since these are
// not under... | protected final double doSolve ( ) { double x0 = getMin ( ) ; double x1 = getMax ( ) ; double f0 = computeObjectiveValue ( x0 ) ; double f1 = computeObjectiveValue ( x1 ) ; if ( f0 == 0.0 ) { return x0 ; } if ( f1 == 0.0 ) { return x1 ; } verifyBracketing ( x0 , x1 ) ; final double ftol = getFunctionValueAccuracy ( ) ;... | protected final double doSolve() {
// Get initial solution
double x0 = getMin();
double x1 = getMax();
double f0 = computeObjectiveValue(x0);
double f1 = computeObjectiveValue(x1);
// If one of the bounds is the exact root, return it. Since these are
// not under... | protected final double doSolve ( ) { double x0 = getMin ( ) ; double x1 = getMax ( ) ; double f0 = computeObjectiveValue ( x0 ) ; double f1 = computeObjectiveValue ( x1 ) ; if ( f0 == 0.0 ) { return x0 ; } if ( f1 == 0.0 ) { return x1 ; } verifyBracketing ( x0 , x1 ) ; final double ftol = getFunctionValueAccuracy ( ) ;... |
JacksonDatabind | 83 | src/main/java/com/fasterxml/jackson/databind/deser/std/FromStringDeserializer.java | 103 | 159 | `FromStringDeserializer` ignores registered `DeserializationProblemHandler` for `java.util.UUID` | Culprit appears to be [lines 155-161 of FromStringDeserializer](https://github.com/FasterXML/jackson-databind/blob/60ae6000d361f910ab0d7d269a5bac1fc66f4cd9/src/main/java/com/fasterxml/jackson/databind/deser/std/FromStringDeserializer.java#L155-L161):
```
// 05-May-2016, tatu: Unlike most usage, this see... | @SuppressWarnings("unchecked")
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
// 22-Sep-2012, tatu: For 2.1, use this new method, may force coercion:
String text = p.getValueAsString();
if (text != null) { // has String representation
... | @ SuppressWarnings ( "unchecked" ) @ Override public T deserialize ( JsonParser p , DeserializationContext ctxt ) throws IOException { String text = p . getValueAsString ( ) ; if ( text != null ) { if ( text . length ( ) == 0 || ( text = text . trim ( ) ) . length ( ) == 0 ) { return _deserializeFromEmptyString ( ) ; }... | @SuppressWarnings("unchecked")
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
// 22-Sep-2012, tatu: For 2.1, use this new method, may force coercion:
String text = p.getValueAsString();
if (text != null) { // has String representation
... | @ SuppressWarnings ( "unchecked" ) @ Override public T deserialize ( JsonParser p , DeserializationContext ctxt ) throws IOException { String text = p . getValueAsString ( ) ; if ( text != null ) { if ( text . length ( ) == 0 || ( text = text . trim ( ) ) . length ( ) == 0 ) { return _deserializeFromEmptyString ( ) ; }... |
JacksonDatabind | 7 | src/main/java/com/fasterxml/jackson/databind/util/TokenBuffer.java | 403 | 411 | Possibly wrong `TokenBuffer` delegate deserialization using `@JsonCreator` | ``` java
class Value {
@JsonCreator
public static Value from(TokenBuffer buffer) {
...
}
```
Given JSON string is `{ "a":1, "b":null }`, it is expected that while deserializing using delegate buffer,
current token will be start object `{`, and rest of the tokens will be available in buffer:
```
[START_OBJECT, FIELD_... | public TokenBuffer deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException
{
copyCurrentStructure(jp);
/* 28-Oct-2014, tatu: As per #592, need to support a special case of starting from
* FIELD_NAME, which is taken to mean that we are missing START_OBJECT, but need... | public TokenBuffer deserialize ( JsonParser jp , DeserializationContext ctxt ) throws IOException { copyCurrentStructure ( jp ) ; return this ; } | public TokenBuffer deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException
{
if (jp.getCurrentTokenId() != JsonToken.FIELD_NAME.id()) {
copyCurrentStructure(jp);
return this;
}
/* 28-Oct-2014, tatu: As per #592, need to support a special case of sta... | public TokenBuffer deserialize ( JsonParser jp , DeserializationContext ctxt ) throws IOException { if ( jp . getCurrentTokenId ( ) != JsonToken . FIELD_NAME . id ( ) ) { copyCurrentStructure ( jp ) ; return this ; } JsonToken t ; writeStartObject ( ) ; do { copyCurrentStructure ( jp ) ; } while ( ( t = jp . nextToken ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.