barty/D4J-Repair huggingface dataset:
File: src/java/org/apache/commons/math/distribution/FDistributionImpl.java
Issue: denominatorDegreeOfFreedom in FDistribution leads to IllegalArgumentsException in UnivariateRealSolverUtils.bracket
We are using the FDistributionImpl from the commons.math project to do
some statistical calculations, namely receiving the upper and lower
boundaries of a confidence interval. Everything is working fine and the
results are matching our reference calculations.
However, the FDistribution behaves strange if a
denominatorDegreeOfFreedom of 2 is used, with an alpha-value of 0.95.
This results in an IllegalArgumentsException, stating:
Invalid endpoint parameters:  lowerBound=0.0 initial=Infinity
upperBound=1.7976931348623157E308
coming from
org.apache.commons.math.analysis.UnivariateRealSolverUtils.bracket
The problem is the 'initial' parameter to that function, wich is
POSITIVE_INFINITY and therefore not within the boundaries. I already
pinned down the problem to the FDistributions getInitialDomain()-method,
wich goes like:
        return getDenominatorDegreesOfFreedom() /
                    (getDenominatorDegreesOfFreedom() - 2.0);
Obviously, in case of denominatorDegreesOfFreedom == 2, this must lead
to a division-by-zero, resulting in POSTIVE_INFINITY. The result of this
operation is then directly passed into the
UnivariateRealSolverUtils.bracket() - method as second argument.

Buggy code:
protected double getInitialDomain(double p) {
    double ret;
    double d = getDenominatorDegreesOfFreedom();
        // use mean
        ret = d / (d - 2.0);
    return ret;
}

Fixed code:
protected double getInitialDomain(double p) {
    double ret = 1.0;
    double d = getDenominatorDegreesOfFreedom();
    if (d > 2.0) {
        // use mean
        ret = d / (d - 2.0);
    }
    return ret;
}
File: src/org/mockito/internal/util/reflection/GenericMaster.java
Issue: ArgumentCaptor no longer working for varargs
I ran into the issue described here: http://stackoverflow.com/questions/27303562/why-does-upgrading-mockito-from-1-9-5-to-1-10-8-break-this-captor

Buggy code:
public Class getGenericType(Field field) {        
    Type generic = field.getGenericType();
    if (generic != null && generic instanceof ParameterizedType) {
        Type actual = ((ParameterizedType) generic).getActualTypeArguments()[0];
            return (Class) actual;
            //in case of nested generics we don't go deep
    }
    
    return Object.class;
}

Fixed code:
public Class getGenericType(Field field) {        
    Type generic = field.getGenericType();
    if (generic != null && generic instanceof ParameterizedType) {
        Type actual = ((ParameterizedType) generic).getActualTypeArguments()[0];
        if (actual instanceof Class) {
            return (Class) actual;
        } else if (actual instanceof ParameterizedType) {
            //in case of nested generics we don't go deep
            return (Class) ((ParameterizedType) actual).getRawType();
        }
    }
    
    return Object.class;
}
File: src/org/mockito/internal/configuration/injection/FinalMockCandidateFilter.java
Issue: ArgumentCaptor no longer working for varargs
Fixes #188 . These commits should fix issue with capturing varargs.


Buggy code:
public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, final Object fieldInstance) {
        if(mocks.size() == 1) {
            final Object matchingMock = mocks.iterator().next();

            return new OngoingInjecter() {
                public boolean thenInject() {
                    try {
                            new FieldSetter(fieldInstance, field).set(matchingMock);
                    } catch (Exception e) {
                        throw new MockitoException("Problems injecting dependency in " + field.getName(), e);
                    }
                    return true;
                }
            };
        }

        return new OngoingInjecter() {
            public boolean thenInject() {
                return false;
            }
        };

    }

Fixed code:
public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, final Object fieldInstance) {
        if(mocks.size() == 1) {
            final Object matchingMock = mocks.iterator().next();

            return new OngoingInjecter() {
                public boolean thenInject() {
                    try {
                        if (!new BeanPropertySetter(fieldInstance, field).set(matchingMock)) {
                            new FieldSetter(fieldInstance, field).set(matchingMock);
                        }
                    } catch (Exception e) {
                        throw new MockitoException("Problems injecting dependency in " + field.getName(), e);
                    }
                    return true;
                }
            };
        }

        return new OngoingInjecter() {
            public boolean thenInject() {
                return false;
            }
        };

    }
File: src/org/mockito/internal/util/Timer.java
Issue: Mockito.after() method accepts negative timeperiods and subsequent verifications always pass
e.g.

```
Runnable runnable = Mockito.mock(Runnable.class);
Mockito.verify(runnable, Mockito.never()).run(); // passes as expected
Mockito.verify(runnable, Mockito.after(1000).never()).run(); // passes as expected
Mockito.verify(runnable, Mockito.after(-1000).atLeastOnce()).run(); // passes incorrectly
```


Buggy code:
public Timer(long durationMillis) {
        this.durationMillis = durationMillis;
    }

Fixed code:
public Timer(long durationMillis) {
        validateInput(durationMillis);
        this.durationMillis = durationMillis;
    }
File: src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
Issue: fix some rawtype warnings in tests
Current coverage is 87.76%

Merging #467 into master will not change coverage

@@             master       #467   diff @@
==========================================
  Files           263        263          
  Lines          4747       4747          
  Methods           0          0          
  Messages          0          0          
  Branches        767        767          
==========================================
  Hits           4166       4166          
  Misses          416        416          
  Partials        165        165          

Powered by Codecov. Last updated by 3fe0fd7...03d9a48

Buggy code:
public Object answer(InvocationOnMock invocation) {
    if (methodsGuru.isToString(invocation.getMethod())) {
        Object mock = invocation.getMock();
        MockName name = mockUtil.getMockName(mock);
        if (name.isDefault()) {
            return "Mock for " + mockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + ", hashCode: " + mock.hashCode();
        } else {
            return name.toString();
        }
    } else if (methodsGuru.isCompareToMethod(invocation.getMethod())) {
        //see issue 184.
        //mocks by default should return 0 if references are the same, otherwise some other value because they are not the same. Hence we return 1 (anything but 0 is good).
        //Only for compareTo() method by the Comparable interface
        return 1;
    }
    
    Class<?> returnType = invocation.getMethod().getReturnType();
    return returnValueFor(returnType);
}

Fixed code:
public Object answer(InvocationOnMock invocation) {
    if (methodsGuru.isToString(invocation.getMethod())) {
        Object mock = invocation.getMock();
        MockName name = mockUtil.getMockName(mock);
        if (name.isDefault()) {
            return "Mock for " + mockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + ", hashCode: " + mock.hashCode();
        } else {
            return name.toString();
        }
    } else if (methodsGuru.isCompareToMethod(invocation.getMethod())) {
        //see issue 184.
        //mocks by default should return 0 if references are the same, otherwise some other value because they are not the same. Hence we return 1 (anything but 0 is good).
        //Only for compareTo() method by the Comparable interface
        return invocation.getMock() == invocation.getArguments()[0] ? 0 : 1;
    }
    
    Class<?> returnType = invocation.getMethod().getReturnType();
    return returnValueFor(returnType);
}
File: src/org/mockito/internal/util/MockUtil.java
Issue: Exception when stubbing more than once with when...thenThrow
If I create a mock and stub a method so it throws an exception and do that twice the first exception will be thrown upon invoking the second stub instruction.
Example:
@Test
public void testThrowException() {
    Object o = Mockito.mock(Object.class);
    // test behavior with Runtimeexception
    Mockito.when(o.toString()).thenThrow(RuntimeException.class);
    // ...
    // test behavior with another exception
    // this throws a RuntimeException
    Mockito.when(o.toString()).thenThrow(IllegalArgumentException.class);
    // ...
}

I can work around this if I do it the other way around with doThrow...when. But I lose type safety then. Can you fix this?

Buggy code:
public <T> void resetMock(T mock) {
    MockHandlerInterface<T> oldMockHandler = getMockHandler(mock);
    MockHandler<T> newMockHandler = new MockHandler<T>(oldMockHandler);
    MethodInterceptorFilter newFilter = new MethodInterceptorFilter(newMockHandler, (MockSettingsImpl) org.mockito.Mockito.withSettings().defaultAnswer(org.mockito.Mockito.RETURNS_DEFAULTS));
    ((Factory) mock).setCallback(0, newFilter);
}

Fixed code:
public <T> void resetMock(T mock) {
    MockHandlerInterface<T> oldMockHandler = getMockHandler(mock);
    MethodInterceptorFilter newFilter = newMethodInterceptorFilter(oldMockHandler.getMockSettings());
    ((Factory) mock).setCallback(0, newFilter);
}
File: src/org/mockito/internal/configuration/DefaultInjectionEngine.java
Issue: nicer textual printing of typed parameters
When matchers fail but yield the same toString(), Mockito prints extra type information. However, the type information is awkwardly printed for Strings. I've encountered this issue while working on removing hard dependency to hamcrest.
//current:
someMethod(1, (Integer) 2);
someOther(1, "(String) 2");
//desired:
someOther(1, (String) "2");

Buggy code:
private void injectMockCandidate(Class<?> awaitingInjectionClazz, Set<Object> mocks, Object fieldInstance) {
    for(Field field : orderedInstanceFieldsFrom(awaitingInjectionClazz)) {
        mockCandidateFilter.filterCandidate(mocks, field, fieldInstance).thenInject();
    }
}

Fixed code:
private void injectMockCandidate(Class<?> awaitingInjectionClazz, Set<Object> mocks, Object fieldInstance) {
    for(Field field : orderedInstanceFieldsFrom(awaitingInjectionClazz)) {
        Object injected = mockCandidateFilter.filterCandidate(mocks, field, fieldInstance).thenInject();
        mocks.remove(injected);
    }
}
File: src/org/mockito/internal/matchers/Same.java
Issue: Fixes #228: fixed a verify() call example in @Captor javadoc
Thanks for the fix :)

Buggy code:
public void describeTo(Description description) {
    description.appendText("same(");
    appendQuoting(description);
    description.appendText(wanted.toString());
    appendQuoting(description);
    description.appendText(")");
}

Fixed code:
public void describeTo(Description description) {
    description.appendText("same(");
    appendQuoting(description);
    description.appendText(wanted == null ? "null" : wanted.toString());
    appendQuoting(description);
    description.appendText(")");
}
File: src/org/mockito/internal/invocation/InvocationMatcher.java
Issue: ArgumentCaptor no longer working for varargs
I ran into the issue described here: http://stackoverflow.com/questions/27303562/why-does-upgrading-mockito-from-1-9-5-to-1-10-8-break-this-captor


Buggy code:
public void captureArgumentsFrom(Invocation invocation) {
        if (invocation.getMethod().isVarArgs()) {
            int indexOfVararg = invocation.getRawArguments().length - 1;
            for (int position = 0; position < indexOfVararg; position++) {
                Matcher m = matchers.get(position);
                if (m instanceof CapturesArguments) {
                    ((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));
                }
            }
            for (int position = indexOfVararg; position < matchers.size(); position++) {
                Matcher m = matchers.get(position);
                if (m instanceof CapturesArguments) {
                    ((CapturesArguments) m).captureFrom(invocation.getRawArguments()[position - indexOfVararg]);
                }
            }
        } else {
            for (int position = 0; position < matchers.size(); position++) {
                Matcher m = matchers.get(position);
                if (m instanceof CapturesArguments) {
                    ((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));
                }
            }
        }
    }

Fixed code:
public void captureArgumentsFrom(Invocation invocation) {
        if (invocation.getMethod().isVarArgs()) {
            int indexOfVararg = invocation.getRawArguments().length - 1;
            for (int position = 0; position < indexOfVararg; position++) {
                Matcher m = matchers.get(position);
                if (m instanceof CapturesArguments) {
                    ((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));
                }
            }
            for (Matcher m : uniqueMatcherSet(indexOfVararg)) {
                if (m instanceof CapturesArguments) {
                    Object rawArgument = invocation.getRawArguments()[indexOfVararg];
                    for (int i = 0; i < Array.getLength(rawArgument); i++) {
                        ((CapturesArguments) m).captureFrom(Array.get(rawArgument, i));
                    }
                }
            }
        } else {
            for (int position = 0; position < matchers.size(); position++) {
                Matcher m = matchers.get(position);
                if (m instanceof CapturesArguments) {
                    ((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));
                }
            }
        }
    }
File: src/org/mockito/internal/invocation/InvocationMatcher.java
Issue: ArgumentCaptor.fromClass's return type should match a parameterized type
ArgumentCaptor.fromClass's return type should match a parameterized type.  I.e. the expression ArgumentCaptor.fromClass(Class<S>) should be of type ArgumentCaptor<U> where S is a subtype of U.
For example:
ArgumentCaptor<Consumer<String>> captor = ArgumentCaptor.fromClass(Consumer.class)

does not type check (i.e. it is a compile time error). It should type check.
The reasons that it is desirable for ArgumentCaptor.fromClass to allow expressions such as the example above to type check are:

ArgumentCaptor.fromClass is intended to be a convenience method to allow the user to construct an ArgumentCaptor without casting the returned value.

Currently, the user can devise a workaround such as:
ArgumentCaptor<? extends Consumer<String>> captor 
= ArgumentCaptor.fromClass(Consumer.class)

This workaround is inconvenient, and so contrary to ArgumentCaptor.fromClass being a convenience method.

It is inconsistent with @Captor, which can be applied to a field with a paramterized type.  I.e.

@Captor ArgumentCaptor<Consumer<String>> captor 

type checks.

Buggy code:
public boolean hasSameMethod(Invocation candidate) {        
    //not using method.equals() for 1 good reason:
    //sometimes java generates forwarding methods when generics are in play see JavaGenericsForwardingMethodsTest
    Method m1 = invocation.getMethod();
    Method m2 = candidate.getMethod();
    
    	/* Avoid unnecessary cloning */
    return m1.equals(m2);
}

Fixed code:
public boolean hasSameMethod(Invocation candidate) {        
    //not using method.equals() for 1 good reason:
    //sometimes java generates forwarding methods when generics are in play see JavaGenericsForwardingMethodsTest
    Method m1 = invocation.getMethod();
    Method m2 = candidate.getMethod();
    
    if (m1.getName() != null && m1.getName().equals(m2.getName())) {
    	/* Avoid unnecessary cloning */
    	Class[] params1 = m1.getParameterTypes();
    	Class[] params2 = m2.getParameterTypes();
    	if (params1.length == params2.length) {
    	    for (int i = 0; i < params1.length; i++) {
    		if (params1[i] != params2[i])
    		    return false;
    	    }
    	    return true;
    	}
    }
    return false;
}
File: src/org/mockito/internal/invocation/InvocationMatcher.java
Issue: Source files should not be put in binary JAR
Source files (*.java) should not be put into binary mockito-core.jar. It stupefies Idea to show decompiled file even when source jar is available.

Buggy code:
public void captureArgumentsFrom(Invocation i) {
    int k = 0;
    for (Matcher m : matchers) {
        if (m instanceof CapturesArguments) {
            ((CapturesArguments) m).captureFrom(i.getArguments()[k]);
        }
        k++;
    }
}

Fixed code:
public void captureArgumentsFrom(Invocation i) {
    int k = 0;
    for (Matcher m : matchers) {
        if (m instanceof CapturesArguments && i.getArguments().length > k) {
            ((CapturesArguments) m).captureFrom(i.getArguments()[k]);
        }
        k++;
    }
}
File: src/org/mockito/internal/invocation/Invocation.java
Issue: Make Mockito JUnit rule easier to use
- Mockito JUnit rule easier to use by avoiding the need to pass test instance
- Make it compatible with JUnit 4.7+ instead of 4.9+


Buggy code:
public Object callRealMethod() throws Throwable {
        return realMethod.invoke(mock, rawArguments);
    }

Fixed code:
public Object callRealMethod() throws Throwable {
        if (this.getMethod().getDeclaringClass().isInterface()) {
            new Reporter().cannotCallRealMethodOnInterface();
        }
        return realMethod.invoke(mock, rawArguments);
    }
File: src/org/mockito/internal/stubbing/answers/AnswersValidator.java
Issue: Make Mockito JUnit rule easier to use
- Mockito JUnit rule easier to use by avoiding the need to pass test instance
- Make it compatible with JUnit 4.7+ instead of 4.9+


Buggy code:
public void validate(Answer<?> answer, Invocation invocation) {
        if (answer instanceof ThrowsException) {
            validateException((ThrowsException) answer, invocation);
        }
        
        if (answer instanceof Returns) {
            validateReturnValue((Returns) answer, invocation);
        }
        
        if (answer instanceof DoesNothing) {
            validateDoNothing((DoesNothing) answer, invocation);
        }
        
    }

Fixed code:
public void validate(Answer<?> answer, Invocation invocation) {
        if (answer instanceof ThrowsException) {
            validateException((ThrowsException) answer, invocation);
        }
        
        if (answer instanceof Returns) {
            validateReturnValue((Returns) answer, invocation);
        }
        
        if (answer instanceof DoesNothing) {
            validateDoNothing((DoesNothing) answer, invocation);
        }
        
        if (answer instanceof CallsRealMethods) {
            validateMockingConcreteClass((CallsRealMethods) answer, invocation);
        }
    }
File: src/org/mockito/internal/verification/argumentmatching/ArgumentMatchingTool.java
Issue: Generate change list separated by types using labels
Changes Unknown when pulling 47a7016 on szpak:topic/releaseLabels into * on mockito:master*.

Buggy code:
private boolean toStringEquals(Matcher m, Object arg) {
    return StringDescription.toString(m).equals(arg.toString());
}

Fixed code:
private boolean toStringEquals(Matcher m, Object arg) {
    return StringDescription.toString(m).equals(arg == null? "null" : arg.toString());
}
File: src/org/mockito/internal/util/reflection/GenericMetadataSupport.java
Issue: Deep stubbing with generic responses in the call chain is not working
Deep stubbing will throw an Exception if multiple generics occur in the call chain. For instance, consider having a mock myMock1 that provides a function that returns a generic T. If T also has a function that returns a generic, an Exception with the message "Raw extraction not supported for : 'null'" will be thrown.
As an example the following test will throw an Exception:
public class MockitoGenericsDeepStubTest {

    @Test
    public void discoverDeepMockingOfGenerics() {
        MyClass1 myMock1 = mock(MyClass1.class, RETURNS_DEEP_STUBS);

        when(myMock1.getNested().getNested().returnSomething()).thenReturn("Hello World.");
    }

    public static interface MyClass1 <MC2 extends MyClass2> {
        public MC2 getNested();
    }

    public static interface MyClass2<MC3 extends MyClass3> {
        public MC3 getNested();
    }

    public static interface MyClass3 {
        public String returnSomething();
    }
}
You can make this test run if you step into the class ReturnsDeepStubs and change the method withSettingsUsing to return MockSettings with ReturnsDeepStubs instead of ReturnsDeepStubsSerializationFallback as default answer:
private MockSettings withSettingsUsing(GenericMetadataSupport returnTypeGenericMetadata, MockCreationSettings parentMockSettings) {
    MockSettings mockSettings = returnTypeGenericMetadata.hasRawExtraInterfaces() ?
            withSettings().extraInterfaces(returnTypeGenericMetadata.rawExtraInterfaces())
            : withSettings();

    return propagateSerializationSettings(mockSettings, parentMockSettings)
            .defaultAnswer(this);
}
However, this breaks other tests and features.
I think, the issue is that further generics are not possible to be mocked by ReturnsDeepStubsSerializationFallback since the GenericMetadataSupport is "closed" at this point.
Thanks and kind regards
Tobias

Buggy code:
private void readTypeVariables() {
    for (Type type : typeVariable.getBounds()) {
        registerTypeVariablesOn(type);
    }
    registerTypeVariablesOn(getActualTypeArgumentFor(typeVariable));
}

Fixed code:
private void readTypeVariables() {
    for (Type type : typeVariable.getBounds()) {
        registerTypeVariablesOn(type);
    }
    registerTypeParametersOn(new TypeVariable[] { typeVariable });
    registerTypeVariablesOn(getActualTypeArgumentFor(typeVariable));
}
File: src/org/mockito/internal/stubbing/answers/CallsRealMethods.java
Issue: 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 


Buggy code:
public Object answer(InvocationOnMock invocation) throws Throwable {
        return invocation.callRealMethod();
    }

Fixed code:
public Object answer(InvocationOnMock invocation) throws Throwable {
    	if (Modifier.isAbstract(invocation.getMethod().getModifiers())) {
    		return new GloballyConfiguredAnswer().answer(invocation);
    	}
        return invocation.callRealMethod();
    }