barty/D4J-Repair huggingface dataset:
File: src/main/java/org/apache/commons/lang3/StringUtils.java
Issue: StringUtils methods do not handle Unicode 2.0+ supplementary characters correctly.
StringUtils.containsAny methods incorrectly matches Unicode 2.0+ supplementary characters.
For example, define a test fixture to be the Unicode character U+20000 where U+20000 is written in Java source as "\uD840\uDC00"
	private static final String CharU20000 = "\uD840\uDC00";
	private static final String CharU20001 = "\uD840\uDC01";
You can see Unicode supplementary characters correctly implemented in the JRE call:
	assertEquals(-1, CharU20000.indexOf(CharU20001));
But this is broken:
	assertEquals(false, StringUtils.containsAny(CharU20000, CharU20001));
	assertEquals(false, StringUtils.containsAny(CharU20001, CharU20000));
This is fine:
	assertEquals(true, StringUtils.contains(CharU20000 + CharU20001, CharU20000));
	assertEquals(true, StringUtils.contains(CharU20000 + CharU20001, CharU20001));
	assertEquals(true, StringUtils.contains(CharU20000, CharU20000));
	assertEquals(false, StringUtils.contains(CharU20000, CharU20001));
because the method calls the JRE to perform the match.
More than you want to know:

http://java.sun.com/developer/technicalArticles/Intl/Supplementary/

Buggy code:
public static boolean containsAny(CharSequence cs, char[] searchChars) {
	if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
		return false;
	}
	int csLength = cs.length();
	int searchLength = searchChars.length;
	for (int i = 0; i < csLength; i++) {
		char ch = cs.charAt(i);
		for (int j = 0; j < searchLength; j++) {
			if (searchChars[j] == ch) {
					// ch is a supplementary character
					// ch is in the Basic Multilingual Plane
					return true;
			}
		}
	}
	return false;
}

Fixed code:
public static boolean containsAny(CharSequence cs, char[] searchChars) {
	if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
		return false;
	}
	int csLength = cs.length();
	int searchLength = searchChars.length;
	int csLastIndex = csLength - 1;
	int searchLastIndex = searchLength - 1;
	for (int i = 0; i < csLength; i++) {
		char ch = cs.charAt(i);
		for (int j = 0; j < searchLength; j++) {
			if (searchChars[j] == ch) {
				if (i < csLastIndex && j < searchLastIndex && ch >= Character.MIN_HIGH_SURROGATE && ch <= Character.MAX_HIGH_SURROGATE) {
					// ch is a supplementary character
					if (searchChars[j + 1] == cs.charAt(i + 1)) {
						return true;
					}
				} else {
					// ch is in the Basic Multilingual Plane
					return true;
				}
			}
		}
	}
	return false;
}
File: src/main/java/org/apache/commons/lang3/ClassUtils.java
Issue: ClassUtils.toClass(Object[]) throws NPE on null array element
see summary

Buggy code:
public static Class<?>[] toClass(Object[] array) {
    if (array == null) {
        return null;
    } else if (array.length == 0) {
        return ArrayUtils.EMPTY_CLASS_ARRAY;
    }
    Class<?>[] classes = new Class[array.length];
    for (int i = 0; i < array.length; i++) {
        classes[i] = array[i].getClass();
    }
    return classes;
}

Fixed code:
public static Class<?>[] toClass(Object[] array) {
    if (array == null) {
        return null;
    } else if (array.length == 0) {
        return ArrayUtils.EMPTY_CLASS_ARRAY;
    }
    Class<?>[] classes = new Class[array.length];
    for (int i = 0; i < array.length; i++) {
        classes[i] = array[i] == null ? null : array[i].getClass();
    }
    return classes;
}
File: src/java/org/apache/commons/lang3/ArrayUtils.java
Issue: ArrayUtils.addAll(T[] array1, T... array2) does not handle mixed types very well
ArrayUtils.addAll(T[] array1, T... array2) does not handle mixed array types very well.
The stack trace for 
Number[] st = ArrayUtils.addAll(new Integer[]
{1}
, new Long[]
{2L}
);
starts:
java.lang.ArrayStoreException
	at java.lang.System.arraycopy(Native Method)
	at org.apache.commons.lang3.ArrayUtils.addAll(ArrayUtils.java:2962)
which is not all that obvious.
It would be a lot clearer if the method threw an IlegalArgumentException or similar.

Buggy code:
public static <T> T[] addAll(T[] array1, T... array2) {
    if (array1 == null) {
        return clone(array2);
    } else if (array2 == null) {
        return clone(array1);
    }
    final Class<?> type1 = array1.getClass().getComponentType();
    T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
    System.arraycopy(array1, 0, joinedArray, 0, array1.length);
        System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
        // Check if problem is incompatible types
    return joinedArray;
}

Fixed code:
public static <T> T[] addAll(T[] array1, T... array2) {
    if (array1 == null) {
        return clone(array2);
    } else if (array2 == null) {
        return clone(array1);
    }
    final Class<?> type1 = array1.getClass().getComponentType();
    T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
    System.arraycopy(array1, 0, joinedArray, 0, array1.length);
    try {
        System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
    } catch (ArrayStoreException ase) {
        // Check if problem is incompatible types
        final Class<?> type2 = array2.getClass().getComponentType();
        if (!type1.isAssignableFrom(type2)){
            throw new IllegalArgumentException("Cannot store "+type2.getName()+" in an array of "+type1.getName());
        }
        throw ase; // No, so rethrow original
    }
    return joinedArray;
}
File: src/java/org/apache/commons/lang3/time/FastDateFormat.java
Issue: DateFormatUtils.format does not correctly change Calendar TimeZone in certain situations
If a Calendar object is constructed in certain ways a call to Calendar.setTimeZone does not correctly change the Calendars fields.  Calling Calenar.getTime() seems to fix this problem.  While this is probably a bug in the JDK, it would be nice if DateFormatUtils was smart enough to detect/resolve this problem.
For example, the following unit test fails:

  public void testFormat_CalendarIsoMsZulu() {
    final String dateTime = "2009-10-16T16:42:16.000Z";

    // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16)
    // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone
    GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8"));
    cal.clear();
    cal.set(2009, 9, 16, 8, 42, 16);

    FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT"));
    assertEquals("dateTime", dateTime, format.format(cal));
  }

However, this unit test passes:

  public void testFormat_CalendarIsoMsZulu() {
    final String dateTime = "2009-10-16T16:42:16.000Z";
    GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8"));
    cal.clear();
    cal.set(2009, 9, 16, 8, 42, 16);
    cal.getTime();

    FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT"));
    assertEquals("dateTime", dateTime, format.format(cal));
  }

Buggy code:
public StringBuffer format(Calendar calendar, StringBuffer buf) {
    if (mTimeZoneForced) {
        calendar = (Calendar) calendar.clone();
        calendar.setTimeZone(mTimeZone);
    }
    return applyRules(calendar, buf);
}

Fixed code:
public StringBuffer format(Calendar calendar, StringBuffer buf) {
    if (mTimeZoneForced) {
        calendar.getTime(); /// LANG-538
        calendar = (Calendar) calendar.clone();
        calendar.setTimeZone(mTimeZone);
    }
    return applyRules(calendar, buf);
}
File: src/java/org/apache/commons/lang/StringUtils.java
Issue: Fix case-insensitive string handling
String.to*Case() is locale-sensitive, this is usually not intended for case-insensitive comparisions. Please see Common Bug #3 for details.

Buggy code:
public static boolean containsIgnoreCase(String str, String searchStr) {
    if (str == null || searchStr == null) {
        return false;
    }
    return contains(str.toUpperCase(), searchStr.toUpperCase());
}

Fixed code:
public static boolean containsIgnoreCase(String str, String searchStr) {
    if (str == null || searchStr == null) {
        return false;
    }
    int len = searchStr.length();
    int max = str.length() - len;
    for (int i = 0; i <= max; i++) {
        if (str.regionMatches(true, i, searchStr, 0, len)) {
            return true;
        }
    }
    return false;
}
File: src/java/org/apache/commons/lang/Entities.java
Issue: StringEscapeUtils.escapeHtml incorrectly converts unicode characters above U+00FFFF into 2 characters
Characters that are represented as a 2 characters internaly by java are incorrectly converted by the function. The following test displays the problem quite nicely:
import org.apache.commons.lang.*;
public class J2 {
    public static void main(String[] args) throws Exception {
        // this is the utf8 representation of the character:
        // COUNTING ROD UNIT DIGIT THREE
        // in unicode
        // codepoint: U+1D362
        byte[] data = new byte[] 
{ (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 }
;
        //output is: &#55348;&#57186;
        // should be: &#119650;
        System.out.println("'" + StringEscapeUtils.escapeHtml(new String(data, "UTF8")) + "'");
    }
}
Should be very quick to fix, feel free to drop me an email if you want a patch.

Buggy code:
public void escape(Writer writer, String str) throws IOException {
    int len = str.length();
    for (int i = 0; i < len; i++) {
        char c = str.charAt(i);
        String entityName = this.entityName(c);
        if (entityName == null) {
            if (c > 0x7F) {
                writer.write("&#");
                writer.write(Integer.toString(c, 10));
                writer.write(';');
            } else {
                writer.write(c);
            }
        } else {
            writer.write('&');
            writer.write(entityName);
            writer.write(';');
        }
    }
}

Fixed code:
public void escape(Writer writer, String str) throws IOException {
    int len = str.length();
    for (int i = 0; i < len; i++) {
        int c = Character.codePointAt(str, i); 
        String entityName = this.entityName(c);
        if (entityName == null) {
            if (c >= 0x010000 && i < len - 1) {
                writer.write("&#");
                writer.write(Integer.toString(c, 10));
                writer.write(';');
                i++;
            } else if (c > 0x7F) { 
                writer.write("&#");
                writer.write(Integer.toString(c, 10));
                writer.write(';');
            } else {
                writer.write(c);
            }
        } else {
            writer.write('&');
            writer.write(entityName);
            writer.write(';');
        }
    }
}
File: src/java/org/apache/commons/lang/math/Fraction.java
Issue: infinite loop in Fraction.reduce when numerator == 0
Summary pretty much says it all.

Buggy code:
public Fraction reduce() {
    int gcd = greatestCommonDivisor(Math.abs(numerator), denominator);
    if (gcd == 1) {
        return this;
    }
    return Fraction.getFraction(numerator / gcd, denominator / gcd);
}

Fixed code:
public Fraction reduce() {
    if (numerator == 0) {
        return equals(ZERO) ? this : ZERO;
    }
    int gcd = greatestCommonDivisor(Math.abs(numerator), denominator);
    if (gcd == 1) {
        return this;
    }
    return Fraction.getFraction(numerator / gcd, denominator / gcd);
}
File: src/java/org/apache/commons/lang/time/StopWatch.java
Issue: StopWatch: suspend() acts as split(), if followed by stop()
In my opinion, it is a bug that suspend() acts as split(), if followed by stop(); see below:
        StopWatch sw = new StopWatch();
        sw.start();
        Thread.sleep(1000);
        sw.suspend();
        // Time 1 (ok)
        System.out.println(sw.getTime());
        Thread.sleep(2000);
        // Time 1 (again, ok)
        System.out.println(sw.getTime());
        sw.resume();
        Thread.sleep(3000);
        sw.suspend();
        // Time 2 (ok)
        System.out.println(sw.getTime());
        Thread.sleep(4000);
        // Time 2 (again, ok)
        System.out.println(sw.getTime());
        Thread.sleep(5000);
        sw.stop();
        // Time 2 (should be, but is Time 3 => NOT ok)
        System.out.println(sw.getTime());
suspend/resume is like a pause, where time counter doesn't continue. So a following stop()-call shouldn't increase the time counter, should it?

Buggy code:
public void stop() {
    if(this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) {
        throw new IllegalStateException("Stopwatch is not running. ");
    }
        stopTime = System.currentTimeMillis();
    this.runningState = STATE_STOPPED;
}

Fixed code:
public void stop() {
    if(this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) {
        throw new IllegalStateException("Stopwatch is not running. ");
    }
    if(this.runningState == STATE_RUNNING) {
        stopTime = System.currentTimeMillis();
    }
    this.runningState = STATE_STOPPED;
}
File: src/java/org/apache/commons/lang/LocaleUtils.java
Issue: NullPointerException in isAvailableLocale(Locale)
FindBugs pointed out:
   UwF: Field not initialized in constructor: org.apache.commons.lang.LocaleUtils.cAvailableLocaleSet
cAvailableSet is used directly once in the source - and if availableLocaleSet() hasn't been called it will cause a NullPointerException.

Buggy code:
public static boolean isAvailableLocale(Locale locale) {
    return cAvailableLocaleSet.contains(locale);
}

Fixed code:
public static boolean isAvailableLocale(Locale locale) {
    return availableLocaleList().contains(locale);
}
File: src/java/org/apache/commons/lang/text/StrBuilder.java
Issue: Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException
There's a bug in method appendFixedWidthPadRight of class StrBuilder:
public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {
        if (width > 0) {
            ensureCapacity(size + width);
            String str = (obj == null ? getNullText() : obj.toString());
            int strLen = str.length();
            if (strLen >= width) 
{
 ==>            str.getChars(0, strLen, buffer, size);   <==== BUG: it should be str.getChars(0, width, buffer, size);
            }
 else {
                int padLen = width - strLen;
                str.getChars(0, strLen, buffer, size);
                for (int i = 0; i < padLen; i++) 
{
                    buffer[size + strLen + i] = padChar;
                }
            }
            size += width;
        }
        return this;
    }
This is causing an ArrayIndexOutOfBoundsException, so this method is unusable when strLen > width.
It's counterpart method appendFixedWidthPadLeft seems to be ok.

Buggy code:
public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {
    if (width > 0) {
        ensureCapacity(size + width);
        String str = (obj == null ? getNullText() : obj.toString());
        int strLen = str.length();
        if (strLen >= width) {
            str.getChars(0, strLen, buffer, size);
        } else {
            int padLen = width - strLen;
            str.getChars(0, strLen, buffer, size);
            for (int i = 0; i < padLen; i++) {
                buffer[size + strLen + i] = padChar;
            }
        }
        size += width;
    }
    return this;
}

Fixed code:
public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {
    if (width > 0) {
        ensureCapacity(size + width);
        String str = (obj == null ? getNullText() : obj.toString());
        int strLen = str.length();
        if (strLen >= width) {
            str.getChars(0, width, buffer, size);
        } else {
            int padLen = width - strLen;
            str.getChars(0, strLen, buffer, size);
            for (int i = 0; i < padLen; i++) {
                buffer[size + strLen + i] = padChar;
            }
        }
        size += width;
    }
    return this;
}
File: src/main/java/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java
Issue: StringIndexOutOfBoundsException in CharSequenceTranslator
I found that there is bad surrogate pair handling in the CharSequenceTranslator
This is a simple test case for this problem.
\uD83D\uDE30 is a surrogate pair.

@Test
public void testEscapeSurrogatePairs() throws Exception {
    assertEquals("\uD83D\uDE30", StringEscapeUtils.escapeCsv("\uD83D\uDE30"));
}

You'll get the exception as shown below.

java.lang.StringIndexOutOfBoundsException: String index out of range: 2
	at java.lang.String.charAt(String.java:658)
	at java.lang.Character.codePointAt(Character.java:4668)
	at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:95)
	at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:59)
	at org.apache.commons.lang3.StringEscapeUtils.escapeCsv(StringEscapeUtils.java:556)

Patch attached, the method affected:

public final void translate(CharSequence input, Writer out) throws IOException

Buggy code:
public final void translate(CharSequence input, Writer out) throws IOException {
    if (out == null) {
        throw new IllegalArgumentException("The Writer must not be null");
    }
    if (input == null) {
        return;
    }
    int pos = 0;
    int len = input.length();
    while (pos < len) {
        int consumed = translate(input, pos, out);
        if (consumed == 0) {
            char[] c = Character.toChars(Character.codePointAt(input, pos));
            out.write(c);
            pos+= c.length;
            continue;
        }
        // contract with translators is that they have to understand codepoints 
        // and they just took care of a surrogate pair
        for (int pt = 0; pt < consumed; pt++) {
            pos += Character.charCount(Character.codePointAt(input, pos));
        }
    }
}

Fixed code:
public final void translate(CharSequence input, Writer out) throws IOException {
    if (out == null) {
        throw new IllegalArgumentException("The Writer must not be null");
    }
    if (input == null) {
        return;
    }
    int pos = 0;
    int len = input.length();
    while (pos < len) {
        int consumed = translate(input, pos, out);
        if (consumed == 0) {
            char[] c = Character.toChars(Character.codePointAt(input, pos));
            out.write(c);
            pos+= c.length;
            continue;
        }
        // contract with translators is that they have to understand codepoints 
        // and they just took care of a surrogate pair
        for (int pt = 0; pt < consumed; pt++) {
            pos += Character.charCount(Character.codePointAt(input, pt));
        }
    }
}
File: src/main/java/org/apache/commons/lang3/time/FastDateParser.java
Issue: FastDateParser does not handle unterminated quotes correctly
FDP does not handled unterminated quotes the same way as SimpleDateFormat
For example:
Format: 'd'd'
Date: d3
This should fail to parse the format and date but it actually works.
The format is parsed as:
Pattern: d(\p
{IsNd}
++)

Buggy code:
private void init() {
    thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR);

    nameValues= new ConcurrentHashMap<Integer, KeyValue[]>();

    StringBuilder regex= new StringBuilder();
    List<Strategy> collector = new ArrayList<Strategy>();

    Matcher patternMatcher= formatPattern.matcher(pattern);
    if(!patternMatcher.lookingAt()) {
        throw new IllegalArgumentException("Invalid pattern");
    }

    currentFormatField= patternMatcher.group();
    Strategy currentStrategy= getStrategy(currentFormatField);
    for(;;) {
        patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
        if(!patternMatcher.lookingAt()) {
            nextStrategy = null;
            break;
        }
        String nextFormatField= patternMatcher.group();
        nextStrategy = getStrategy(nextFormatField);
        if(currentStrategy.addRegex(this, regex)) {
            collector.add(currentStrategy);
        }
        currentFormatField= nextFormatField;
        currentStrategy= nextStrategy;
    }
    if(currentStrategy.addRegex(this, regex)) {
        collector.add(currentStrategy);
    }
    currentFormatField= null;
    strategies= collector.toArray(new Strategy[collector.size()]);
    parsePattern= Pattern.compile(regex.toString());
}

Fixed code:
private void init() {
    thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR);

    nameValues= new ConcurrentHashMap<Integer, KeyValue[]>();

    StringBuilder regex= new StringBuilder();
    List<Strategy> collector = new ArrayList<Strategy>();

    Matcher patternMatcher= formatPattern.matcher(pattern);
    if(!patternMatcher.lookingAt()) {
        throw new IllegalArgumentException("Invalid pattern");
    }

    currentFormatField= patternMatcher.group();
    Strategy currentStrategy= getStrategy(currentFormatField);
    for(;;) {
        patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
        if(!patternMatcher.lookingAt()) {
            nextStrategy = null;
            break;
        }
        String nextFormatField= patternMatcher.group();
        nextStrategy = getStrategy(nextFormatField);
        if(currentStrategy.addRegex(this, regex)) {
            collector.add(currentStrategy);
        }
        currentFormatField= nextFormatField;
        currentStrategy= nextStrategy;
    }
    if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {
        throw new IllegalArgumentException("Failed to parse \""+pattern+"\" ; gave up at index "+patternMatcher.regionStart());
    }
    if(currentStrategy.addRegex(this, regex)) {
        collector.add(currentStrategy);
    }
    currentFormatField= null;
    strategies= collector.toArray(new Strategy[collector.size()]);
    parsePattern= Pattern.compile(regex.toString());
}
File: src/java/org/apache/commons/math/distribution/NormalDistributionImpl.java
Issue: 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.

Buggy code:
public double cumulativeProbability(double x) throws MathException {
        return 0.5 * (1.0 + Erf.erf((x - mean) /
                (standardDeviation * Math.sqrt(2.0))));
}

Fixed code:
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 blows at 38
            return 0.0d;
        } else if (x > (mean + 20 * standardDeviation)) {
            return 1.0d;
        } else {
            throw ex;
        }
    }
}
File: src/main/java/org/apache/commons/math3/distribution/MultivariateNormalDistribution.java
Issue: MultivariateNormalDistribution.density(double[]) returns wrong value when the dimension is odd
To reproduce:

Assert.assertEquals(0.398942280401433, new MultivariateNormalDistribution(new double[]{0}, new double[][]{{1}}).density(new double[]{0}), 1e-15);

Buggy code:
public double density(final double[] vals) throws DimensionMismatchException {
    final int dim = getDimension();
    if (vals.length != dim) {
        throw new DimensionMismatchException(vals.length, dim);
    }

    return FastMath.pow(2 * FastMath.PI, -dim / 2) *
        FastMath.pow(covarianceMatrixDeterminant, -0.5) *
        getExponentTerm(vals);
}

Fixed code:
public double density(final double[] vals) throws DimensionMismatchException {
    final int dim = getDimension();
    if (vals.length != dim) {
        throw new DimensionMismatchException(vals.length, dim);
    }

    return FastMath.pow(2 * FastMath.PI, -0.5 * dim) *
        FastMath.pow(covarianceMatrixDeterminant, -0.5) *
        getExponentTerm(vals);
}