auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static ClassLoader createCombinedClassLoader(String testPlugin) throws BundleException { ClassLoader testClassLoader = getBundleClassLoader(testPlugin); ClassLoader contextFinder = Thread.currentThread().getContextClassLoader(); ClassLoader surefireClassLoader = ForkedBooter.class.getClassLoader(); START return new CombinedClassLoader(testClassLoader, new TychoContextFinder(contextFinder.getParent()), END surefireClassLoader); } I think context finder should be the last in the list because classloading happens in this order

Target:
private static ClassLoader createCombinedClassLoader(String testPlugin) throws BundleException { ClassLoader testClassLoader = getBundleClassLoader(testPlugin); ClassLoader contextFinder = Thread.currentThread().getContextClassLoader(); ClassLoader surefireClassLoader = ForkedBooter.class.getClassLoader(); return new CombinedClassLoader(testClassLoader, surefireClassLoader, new TychoContextFinder(contextFinder.getParent())); }
Source:
public synchronized void dispose() { START synchronized (this) { END if (fFileInput != null) { try { fFileInput.close(); } catch (IOException e) { Activator.getInstance().logError("Error disposing trace. File: " + getPath(), e); //$NON-NLS-1$ } } } super.dispose(); } I think it's unnecessary, method is synchronized?

Target:
public synchronized void dispose() { if (fFileInput != null) { try { fFileInput.close(); } catch (IOException e) { Activator.getInstance().logError("Error disposing trace. File: " + getPath(), e); //$NON-NLS-1$ } } super.dispose(); }
Source:
public Object run(Object object) throws Exception { String[] args = Platform.getCommandLineArgs(); // https://bugs.eclipse.org/bugs/show_bug.cgi?id=540222: log stack traces when we are nearing the test timeout String timeoutParameter = getParameterValue(args, "-timeout"); //$NON-NLS-1$ if (timeoutParameter != null) { DumpStackTracesTimer.startStackDumpTimeoutTimer(timeoutParameter); } START return Integer.valueOf(OsgiSurefireBooter.run(args)); END } Couldn't we have the timeout check implmented in the OsgiSurefireBooter (or a parent) instead? It would most likely allow easier reuse.

Target:
public Object run(Object object) throws Exception { String[] args = Platform.getCommandLineArgs(); return Integer.valueOf(OsgiSurefireBooter.run(args)); }
Source:
public void run() { CompoundCommand updateCmd = new CompoundCommand(); for(Object obj : getSelectedObjects()){ if (obj instanceof AbstractFBNElementEditPart) { START UpdateFBTypeCommand cmd; cmd = new UpdateFBTypeCommand(((AbstractFBNElementEditPart) obj).getModel(), entry); END if (cmd.canExecute()) { updateCmd.add(cmd); } } } execute(updateCmd); } that could be merged into one line

Target:
public void run() { CompoundCommand updateCmd = new CompoundCommand(); for(Object obj : getSelectedObjects()){ if (obj instanceof AbstractFBNElementEditPart) { UpdateFBTypeCommand cmd = new UpdateFBTypeCommand(((AbstractFBNElementEditPart) obj).getModel(), entry); if (cmd.canExecute()) { updateCmd.add(cmd); } } } execute(updateCmd); }
Source:
protected HttpURLConnection createConnection(String uri) throws IOException { URL url = new URL(createUri(uri)); START if (proxy != null) END return (HttpURLConnection) url.openConnection(proxy); return (HttpURLConnection) url.openConnection(); } Please add curly braces {}, also for single-line bodies. I know, old code doesn't have this, but for new code we require it since several years. We add it where we change things anyway, so don't change all the other ifs in this source.

Target:
protected HttpURLConnection createConnection(String uri) throws IOException { URL url = new URL(createUri(uri)); if (proxy != null) { return (HttpURLConnection) url.openConnection(proxy); } return (HttpURLConnection) url.openConnection(); }
Source:
private ACUser findUser(String name) throws ESException { ACUser result = null; for (final ACUser user : adminBroker.getUsers()) { if (user.getName().equals(name)) { START result = user; END } } return result; } We could break here (applies to findGroup as well)

Target:
private ACUser findUser(String name) throws ESException { for (final ACUser user : adminBroker.getUsers()) { if (user.getName().equals(name)) { return user; } } return null; }
Source:
public String getName() { return START fName.get(0); END } possible exception

Target:
public String getName() { return fName.isEmpty() ? "" : fName.get(0); //$NON-NLS-1$ }
Source:
public ICleanUpFix createFix(CleanUpContext context) throws CoreException { ICleanUpFixCore fixCore= coreCleanUp.createFixCore(context); return fixCore == null ? null : new START CleanUpFixWrapper(coreCleanUp.createFixCore(context)); END } Could this just be 'fixCore' instead of creating the object twice ?

Target:
public ICleanUpFix createFix(CleanUpContext context) throws CoreException { ICleanUpFixCore fixCore= coreCleanUp.createFixCore(context); return fixCore == null ? null : new CleanUpFixWrapper(fixCore); }
Source:
private void changeExperimentName(TracePackageExperimentElement experimentElement) { String currentName = experimentElement.getImportName(); int nameSuffixIndex = START 1; END while (experimentExists(experimentElement)) { String newName = currentName + " (" + nameSuffixIndex + ')'; //$NON-NLS-1$ experimentElement.setImportName(newName); nameSuffixIndex++; } } Should start at 2

Target:
private void changeExperimentName(TracePackageExperimentElement experimentElement) { String currentName = experimentElement.getImportName(); int nameSuffixIndex = 2; while (experimentExists(experimentElement)) { String newName = currentName + " (" + nameSuffixIndex + ')'; //$NON-NLS-1$ experimentElement.setImportName(newName); nameSuffixIndex++; } }
Source:
public void testResolveTipSha1() throws IOException { ObjectId masterId = db.resolve("refs/heads/master"); Set<Ref> resolved = db.getRefDatabase().resolveTipSha1(masterId); START assertEquals(resolved.size(), 2); END checkContainsRef(resolved, db.exactRef("refs/heads/master")); checkContainsRef(resolved, db.exactRef("HEAD")); assertEquals(db.getRefDatabase() .resolveTipSha1(ObjectId.zeroId()).size(), 0); } The arguments here are in the opposite order to previous uses, for example at L347. Which order is correct? If it's this one, we should do a cleanup of the others.

Target:
public void testResolveTipSha1() throws IOException { ObjectId masterId = db.resolve("refs/heads/master"); Set<Ref> resolved = db.getRefDatabase().resolveTipSha1(masterId); assertEquals(2, resolved.size()); checkContainsRef(resolved, db.exactRef("refs/heads/master")); checkContainsRef(resolved, db.exactRef("HEAD")); assertEquals(db.getRefDatabase() .resolveTipSha1(ObjectId.zeroId()).size(), 0); }
Source:
public void setGetterName(String name) { Assert.isNotNull(fGetterName); fGetterName= name; START fCreateGetter= !fGetterName.isEmpty(); END } This could probably be an assert since it is invalid and shouldn't get passed. The Encapsulate Field dialog doesn't allow an empty string and shows an error (though the message is not properly referenced and shows the id instead of the message).

Target:
public void setGetterName(String name) { Assert.isNotNull(name); fGetterName= name; fCreateGetter = !name.isEmpty(); }
Source:
public OutputStream write(String item, IProgressMonitor monitor) throws IOException { File file = getFile(item); START return new BufferedOutputStream(new FileOutputStream(file)); END } let's not modify this. looks like the classes that use this method implement buffered writing

Target:
public OutputStream write(String item, IProgressMonitor monitor) throws IOException { File file = getFile(item); return new FileOutputStream(file); }
Source:
public void display(IStructuredSelection selection) { if (selection != null && selection.getFirstElement() instanceof IJavaVariable) { IJavaVariable variable = (IJavaVariable) (selection.getFirstElement()); if (fVariable == null || !fVariable.equals(variable)) { fVariable = variable; START fExpressionHistory.setEnabled(true); END initializeExpressionHistoryDropDown(); } } super.display(selection); } I see NPE's here...

Target:
public void display(IStructuredSelection selection) { if (fExpressionHistory != null && selection != null && selection.getFirstElement() instanceof IJavaVariable) { IJavaVariable variable = (IJavaVariable) (selection.getFirstElement()); if (fVariable == null || !fVariable.equals(variable)) { fVariable = variable; fExpressionHistory.setEnabled(true); initializeExpressionHistoryDropDown(); } } super.display(selection); }
Source:
public DynamicSourcesWorkingSetUpdater() { fUpdateJob= new Job(WorkingSetMessages.JavaSourcesWorkingSets_updating) { @Override protected IStatus run(IProgressMonitor monitor) { return updateElements(monitor); } }; fUpdateUIJob = new UpdateUIJob(); START fUpdateJob.setSystem(true); END fResourceChangeListener= new ResourceChangeListener(); ResourcesPlugin.getWorkspace().addResourceChangeListener(fResourceChangeListener, IResourceChangeEvent.POST_CHANGE); fJavaElementChangeListener= new JavaElementChangeListener(); JavaCore.addElementChangedListener(fJavaElementChangeListener, ElementChangedEvent.POST_CHANGE); } shouldn't we also do: fUpdateUIJob.setSystem(true);

Target:
public DynamicSourcesWorkingSetUpdater() { fResourceChangeListener= new ResourceChangeListener(); ResourcesPlugin.getWorkspace().addResourceChangeListener(fResourceChangeListener, IResourceChangeEvent.POST_CHANGE); fJavaElementChangeListener= new JavaElementChangeListener(); JavaCore.addElementChangedListener(fJavaElementChangeListener, ElementChangedEvent.POST_CHANGE); }
Source:
public START int getMaxSeverityIncludingNestedProjects(IResource END resource) { return cache.getOrDefault(resource, 0).intValue(); } Would be nice to add @return about what kind of values are expected here

Target:
public Integer getMaxSeverityIncludingNestedProjects(IResource resource) { return cache.getOrDefault(resource, -1).intValue(); }
Source:
public String getText(final Object element) { if (element == null) { return ""; //$NON-NLS-1$ START } END return ((FileDiff) element).getLabel(element); } The super() returns "" on null. Why should we differ?

Target:
public String getText(final Object element) { if (element == null) { return null; } return ((FileDiff) element).getLabel(element); }
Source:
public PictogramElement[] getSelections(PictogramElement selection) { START if (selection instanceof Connection && !isConnectionSelectionEnabled()) { return null; } END PictogramElement[] selections = { selection }; return selections; } I agree. However, this is done inside the TBP to preserve backward compatibility. If backward compatibility is not desired, this should, indeed, move to caller.

Target:
public PictogramElement[] getSelections(PictogramElement selection) { PictogramElement[] selections = { selection }; return selections; }
Source:
long /*int*/ getsurePressReleaseProc (long /*int*/ gesture, int n_press, double x, double y, long /*int*/ user_data) { START long /*int*/ event = GTK.gtk_get_current_event(); END long /*int*/ result = 0; switch ((int)/*64*/user_data) { case GESTURE_PRESSED: result = gtk_gesture_press_event(gesture, n_press, x, y); break; case GESTURE_RELEASED: result = gtk_gesture_release_event(gesture, n_press, x, y); break; } gdk_event_free(event); return result; } If we aren't feeding the GdkEvent to the callback methods then just remove this line -- otherwise we are fetching the event and freeing it for no reason. :)

Target:
long /*int*/ getsurePressReleaseProc (long /*int*/ gesture, int n_press, double x, double y, long /*int*/ user_data) { long /*int*/ event = GTK.gtk_get_current_event(); long /*int*/ result = 0; switch ((int)/*64*/user_data) { case GESTURE_PRESSED: result = gtk_gesture_press_event(gesture, n_press, x, y, event); break; case GESTURE_RELEASED: result = gtk_gesture_release_event(gesture, n_press, x, y, event); break; } gdk_event_free(event); return result; }
Source:
public LanguageFilterServer() { START this.filterBoxService END = new FilterBoxService(this); this.filterWorkspaceService = new FilterWorkspaceService(); } Remove the this.

Target:
public LanguageFilterServer() { filterBoxService = new FilterBoxService(this); filterWorkspaceService = new FilterWorkspaceService(); }
Source:
public void createArtifacts() { ArtifactId parentArtifact = CoreArtifactTokens.OseeTypesFolder; START END List<String> names = new ArrayList<>(); names.add("TestArtifact1"); names.add("TestArtifact2"); names.add("TestArtifact3"); List<ArtifactToken> newArtifacts = artifactEndpoint.createArtifacts(COMMON, CoreArtifactTypes.PlainText, parentArtifact, names); Assert.assertFalse(newArtifacts.isEmpty()); } Consider Arrays.asList("xxx","yyy", "zzz");

Target:
public void createArtifacts() { ArtifactId parentArtifact = CoreArtifactTokens.OseeTypesFolder; List<String> names = Arrays.asList("TestArtifact1", "TestArtifact2", "TestArtifact3"); List<ArtifactToken> newArtifacts = artifactEndpoint.createArtifacts(COMMON, CoreArtifactTypes.PlainText, parentArtifact, names); Assert.assertFalse(newArtifacts.isEmpty()); }
Source:
private Topic getOrCreateTopic(MessageID messageId) throws JMSException { Topic topic = topicCache.get(messageId.getId()); if (topic == null) { topic = session.createTopic(messageId.getId()); Topic START catchReturn = END topicCache.putIfAbsent(messageId.getId(), topic); } return topic; } This variable is not being used. No reason to include it since calling a non-void method doesn't require catching its return object typically. To satisfy Findbugs, you could do something like this: if (topic == null) { topic = session.createTopic(messageId.getId()); return topicCache.putIfAbsent(messageId.getId(), topic); } return topic;

Target:
private Topic getOrCreateTopic(MessageID messageId) throws JMSException { Topic topic = topicCache.get(messageId.getId()); if (topic == null) { topic = session.createTopic(messageId.getId()); topicCache.put(messageId.getId(), topic); } return topic; }
Source:
private void createButton(Composite parent) { artifactSelectButton = new Button(parent, SWT.PUSH); START artifactSelectButton.setText(String.format("Select " + itemName)); END artifactSelectButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { handleSelectedArtifact(event); notifyListener(event); } }); artifactSelectButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); } Not sure what is going on here, as String.format always takes at least two arguments? "Select" is being picked up as an actual class and not treated as a string for some reason.

Target:
private void createButton(Composite parent) { artifactSelectButton = new Button(parent, SWT.PUSH); artifactSelectButton.setText("Select " + itemName); artifactSelectButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { handleSelectedArtifact(event); notifyListener(event); } }); artifactSelectButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); }
Source:
private void recreateEmptyArea() { if (emptyArea != null) { // throw away already existing empty area emptyArea.dispose(); emptyArea = null; } START if (images != null) { END disposeImages(); images = new ArrayList<>(); } // re-read the project wizards and re-create the empty area createEmptyArea(displayArea); switchTopControlRunnable.run(); } images is never null so just call disposeImages()

Target:
private void recreateEmptyArea() { if (emptyArea != null) { // throw away already existing empty area emptyArea.dispose(); emptyArea = null; } disposeImages(); // re-read the project wizards and re-create the empty area createEmptyArea(displayArea); switchTopControlRunnable.run(); }
Source:
public String getLine(int lineIndex) { try { final IRegion lineRegion = getLineInformation(lineIndex); return document.get(lineRegion.getOffset(), lineRegion.getLength()); } catch (BadLocationException e) { ConsolePlugin.log(e); START return null; END } } Before we always had non-null returns

Target:
public String getLine(int lineIndex) { try { final IRegion lineRegion = getLineInformation(lineIndex); return document.get(lineRegion.getOffset(), lineRegion.getLength()); } catch (BadLocationException e) { ConsolePlugin.log(e); return ""; //$NON-NLS-1$ } }
Source:
static long /*int*/ gdk_pixbuf_new_from_file(String filename) { int length = filename.length (); char chars = new char [length]; filename.getChars (0, length, chars, 0); byte buffer = Converter.wcsToMbcs(chars, true); START long /*int*/ pixbuf = GDK.gdk_pixbuf_new_from_file(buffer, null); return pixbuf; END } This can be combined into one line.

Target:
static long /*int*/ gdk_pixbuf_new_from_file(String filename) { int length = filename.length (); char chars = new char [length]; filename.getChars (0, length, chars, 0); byte buffer = Converter.wcsToMbcs(chars, true); return GDK.gdk_pixbuf_new_from_file(buffer, null); }
Source:
public void tesIsModifiedBySameLastModifiedAndDifferentSize() throws Exception { File f1 = createFile("foo", "lorem".getBytes()); File f2 = createFile("bar", "lorem ipsum".getBytes()); START long now = System.currentTimeMillis(); END f1.setLastModified(f2.lastModified()); // Make sure f1 and f2 have the same lastModified FileSnapshot save = FileSnapshot.save(f1); Thread.sleep(3000L); assertEquals(save.lastModified(), f2.lastModified()); assertTrue(save.isModified(f2)); } now is unused

Target:
public void tesIsModifiedBySameLastModifiedAndDifferentSize() throws Exception { File f1 = createFile("foo", "lorem".getBytes()); File f2 = createFile("bar", "lorem ipsum".getBytes()); f1.setLastModified(f2.lastModified()); // Make sure f1 and f2 have the same lastModified FileSnapshot save = FileSnapshot.save(f1); // Make sure that the modified and read timestamps are far enough, so that // check is done by size Thread.sleep(3000L); assertEquals(save.lastModified(), f2.lastModified()); assertTrue(save.isModified(f2)); }
Source:
public void createArtifact(@Nullable ArtifactToken parent, ArtifactToken artifact) { START ArtifactToken art = createArtifact(artifact); END addChild(parent, art); } If parent can be null, we need to check before setting parent. Or switch to NonNullable

Target:
public void createArtifact(@Nullable ArtifactToken parent, ArtifactToken artifact) { ArtifactToken art = createArtifact(artifact); if (parent != null) { addChild(parent, art); } }
Source:
public void setEmptyExceptionSpecification() { assertNotFrozen(); typeIds = IASTTypeId.EMPTY_TYPEID_ARRAY; START setNoexceptExpression(new CPPASTLiteralExpression(IASTLiteralExpression.lk_true, "true".toCharArray())); //$NON-NLS-1$ // TODO this is probably not the correct way to do it... END } I don't think we need to invent an AST node, we can just do it at the evaluation level. We can add ICPPASTFunctionDeclarator.getNoexceptEvaluation(), whose implementation does: if (getNoexceptionExpression() != null) { return getNoexceptionExpression().getEvaluation(); } if (getExceptionSpecification() == IASTTypeId.EMPTY_TYPEID_ARRAY) { return /* EvalFixed for "true" */; } return null; and then use getNoexceptionEvaluation() instead of getNoexceptExpression().getEvaluation() when creating function types.

Target:
public void setEmptyExceptionSpecification() { assertNotFrozen(); typeIds = IASTTypeId.EMPTY_TYPEID_ARRAY; }
Source:
public boolean isNoexcept(boolean inCalledContext) { ICPPFunction overload = getOverload(); if (overload != null) { START return EvalUtil.evaluateNoexceptSpecifier(overload.getType().getNoexceptSpecifier()); END } return fArg1.isNoexcept(inCalledContext) && fArg2.isNoexcept(inCalledContext); } If there's an overload the result should be (overload is noexcept) && (arg1 is noexcept) && (arg2 is noexcept).

Target:
public boolean isNoexcept(boolean inCalledContext) { ICPPFunction overload = getOverload(); if (overload != null) { if (!EvalUtil.evaluateNoexceptSpecifier(overload.getType().getNoexceptSpecifier())) return false; } return fArg1.isNoexcept(inCalledContext) && fArg2.isNoexcept(inCalledContext); }
Source:
public boolean isNoexcept(boolean inCalledContext) { if (fOperator == op_throw) return false; ICPPFunction overload = getOverload(); if (overload != null) { START return EvalUtil.evaluateNoexceptSpecifier(overload.getType().getNoexceptSpecifier()); END } return fArgument.isNoexcept(inCalledContext); } (overload is noexcept) && (argument is noexcept)

Target:
public boolean isNoexcept(boolean inCalledContext) { if (fOperator == op_throw) return false; ICPPFunction overload = getOverload(); if (overload != null) { if (!EvalUtil.evaluateNoexceptSpecifier(overload.getType().getNoexceptSpecifier())) return false; } return fArgument.isNoexcept(inCalledContext); }
Source:
public static boolean evaluateNoexceptSpecifier(ICPPEvaluation noexceptSpecifier) { if (noexceptSpecifier == null) return false; else { IntegralValue v = (IntegralValue) noexceptSpecifier.getValue(); START return v.numberValue().longValue() == 1; END } } numberValue() needs a null check

Target:
public static boolean evaluateNoexceptSpecifier(ICPPEvaluation noexceptSpecifier) { if (noexceptSpecifier != null) { IntegralValue v = (IntegralValue) noexceptSpecifier.getValue(); if (v.numberValue() != null) return v.numberValue().longValue() == 1; } return false; }
Source:
public static boolean evaluateNoexceptSpecifier(ICPPEvaluation noexceptSpecifier) { if (noexceptSpecifier != null) { START IntegralValue v = (IntegralValue) noexceptSpecifier.getValue(); END if (v.numberValue() != null) return v.numberValue().longValue() == 1; } return false; } Do we know it will be an IntegralValue? (Could we get here if it's dependent, in which case it could be a DependentValue?)

Target:
public static boolean evaluateNoexceptSpecifier(ICPPEvaluation noexceptSpecifier) { if (noexceptSpecifier != null && noexceptSpecifier.getValue() instanceof IntegralValue) { IntegralValue v = (IntegralValue) noexceptSpecifier.getValue(); if (v.numberValue() != null) return v.numberValue().longValue() == 1; } return false; }
Source:
private AccountInfo adaptAccountInfo(CommitInfo commitInfo, IProgressMonitor monitor) throws GerritException { String accountId = commitInfo.getAuthor().getEmail(); for (int retries = 0;; retries++) { try { return retrieveAccountInfo(accountId, monitor); } catch (GerritException e) { if (retries < 3) { accountId = commitInfo.getAuthor().getName(); continue; START } END } } } else throw e?

Target:
private AccountInfo adaptAccountInfo(CommitInfo commitInfo, IProgressMonitor monitor) throws GerritException { String accountId = commitInfo.getAuthor().getEmail(); for (int retries = 0;; retries++) { try { return retrieveAccountInfo(accountId, monitor); } catch (GerritException e) { if (retries < 3) { accountId = commitInfo.getAuthor().getName(); continue; } else { throw e; } } } }
Source:
private void addMethodToClass(ICPPClassType classType, Method method) { if (!isDuplicate(method)) { List<Method> methods = fData.get(classType); START if (methods == null) { END methods = new ArrayList<>(); methods.add(method); fData.put(classType, methods); } else { methods.add(method); } } } Can we do instead: if (methods == null) { methods = new ArrayList<>(); fData.put(classType, methods); } methods.add(method); ?

Target:
private void addMethodToClass(ICPPClassType classType, Method method) { if (!isDuplicate(method)) { List<Method> methods = fData.get(classType); if (methods == null) { methods = new ArrayList<>(); fData.put(classType, methods); } methods.add(method); } }
Source:
public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { if (adapterType == IToggleBreakpointsTarget.class && adaptableObject instanceof ExtensionBasedTextEditor START || adaptableObject instanceof TextEditor) { END return (T) new DSPBreakpointAdapter(); } return null; } I'm often unsure of the operator priority here, and I guess most people are. Can you please wrap the 2nd term of && with parenthesis to remove any form of doubt?

Target:
public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { if (adapterType == IToggleBreakpointsTarget.class && (adaptableObject instanceof ExtensionBasedTextEditor || adaptableObject instanceof TextEditor)) { return (T) new DSPBreakpointAdapter(); } return null; }
Source:
START public static void setUpBeforeClass() throws CoreException { END project = TestUtils.createProject("EditorToOutlineAdapterFactoryTest" + System.currentTimeMillis()); testFile = TestUtils.createUniqueTestFile(project, "Hello World !!"); // look for content outline in current workbench, could be null IViewPart viewPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .findView("org.eclipse.ui.views.ContentOutline"); //$NON-NLS-1$ // implicitly checks for null if (viewPart instanceof ContentOutline) { outline = (ContentOutline) viewPart; } Assert.assertNotNull(outline); } I think the AllCleanRule may delete the project and test file after this @BeforeClass. It may be better to put this directly in the test method.

Target:
public static void setUpBeforeClass() throws CoreException { // look for content outline in current workbench, could be null IViewPart viewPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .findView("org.eclipse.ui.views.ContentOutline"); //$NON-NLS-1$ // implicitly checks for null if (viewPart instanceof ContentOutline) { outline = (ContentOutline) viewPart; } Assert.assertNotNull(outline); }
Source:
public void testEquals_other() { START setUp(); END try (CtfIterator obj = (CtfIterator) trace.createIterator();) { assertNotNull(obj); CtfLocation ctfLocation1 = new CtfLocation(new CtfLocationInfo(1, 0)); obj.setLocation(ctfLocation1); obj.increaseRank(); boolean result = iterator.equals(obj); assertTrue(result); } } Why are you calling setUp()? Is there a way to avoid this?

Target:
public void testEquals_other() { CtfIterator obj = iterator; assertNotNull(obj); CtfLocation ctfLocation1 = new CtfLocation(new CtfLocationInfo(1, 0)); obj.setLocation(ctfLocation1); obj.increaseRank(); boolean result = iterator.equals(obj); assertTrue(result); }
Source:
public boolean visit(ConstructorInvocation constructorInvocation) { List<?> arguments= constructorInvocation.arguments(); if (!arguments.isEmpty()) { IMethodBinding constructorBinding= START constructorInvocation.resolveConstructorBinding(); END IMethod method = resolveMethodBinding(constructorBinding); collectParameterNamesCodeMinings(method, arguments, constructorBinding.isVarargs()); } return super.visit(constructorInvocation); } The same thing as mentioned below can also happen here.

Target:
public boolean visit(ConstructorInvocation constructorInvocation) { List<?> arguments= constructorInvocation.arguments(); if (!arguments.isEmpty()) { IMethodBinding constructorBinding= constructorInvocation.resolveConstructorBinding(); if (constructorBinding != null) { IMethod method = resolveMethodBinding(constructorBinding); collectParameterNamesCodeMinings(method, arguments, constructorBinding.isVarargs()); } } return super.visit(constructorInvocation); }
Source:
public boolean visit(MethodInvocation methodInvocation) { List<?> arguments= methodInvocation.arguments(); if (!arguments.isEmpty()) { IMethodBinding methodBinding= START methodInvocation.resolveMethodBinding(); END IMethod method = resolveMethodBinding(methodBinding); collectParameterNamesCodeMinings(method, arguments, methodBinding.isVarargs()); } return super.visit(methodInvocation); } methodBinding.isVarargs() will NPE if the line in question can't resolve its bindings. MethodInvocation.resolveMethodBinding() can return null, especially if there's plenty of errors. Your local resolveMethodBinding() checks that, so it's fine but methodBinding.isVarargs() would fail.

Target:
public boolean visit(MethodInvocation methodInvocation) { List<?> arguments= methodInvocation.arguments(); if (!arguments.isEmpty()) { IMethodBinding methodBinding= methodInvocation.resolveMethodBinding(); if (methodBinding != null) { IMethod method = resolveMethodBinding(methodBinding); collectParameterNamesCodeMinings(method, arguments, methodBinding.isVarargs()); } } return super.visit(methodInvocation); }
Source:
public static void beforeClass() { SWTBotUtils.initialize(); Thread.currentThread().setName("SWTBotTest"); /* set up for swtbot */ SWTBotPreferences.TIMEOUT = 60000; /* 60 second timeout */ SWTBotPreferences.KEYBOARD_LAYOUT = "EN_US"; SWTWorkbenchBot bot = new SWTWorkbenchBot(); SWTBotUtils.closeView("welcome", bot); /* Prepare the workspace */ START prepareWorkspace(); END /* Finish waiting for eclipse to load */ WaitUtils.waitForJobs(); /* Create project */ SWTBotUtils.createProject(PROJECT_NAME); } Implementing classes should be able to override this method to do their own stuff to prepare the workspace. With static, it is not possible to do so.

Target:
public void beforeClass() { SWTBotUtils.initialize(); Thread.currentThread().setName("SWTBotTest"); /* set up for swtbot */ SWTBotPreferences.TIMEOUT = 60000; /* 60 second timeout */ SWTBotPreferences.KEYBOARD_LAYOUT = "EN_US"; SWTWorkbenchBot bot = new SWTWorkbenchBot(); SWTBotUtils.closeView("welcome", bot); /* Prepare the workspace */ prepareWorkspace(); /* Finish waiting for eclipse to load */ WaitUtils.waitForJobs(); /* Create project */ SWTBotUtils.createProject(PROJECT_NAME); }
Source:
public void tearDown() { START fBot.closeAllEditors(); SWTBotUtils.deleteProject(PROJECT_NAME, fBot); END } This part should be move to cleanUp(). Right now the project is deleted after each test and never created again

Target:
public void tearDown() { fBot.closeAllEditors(); }
Source:
START public static void before() { END SWTBotUtils.openTrace(TRACE_PROJECT_NAME, fTestFile.getAbsolutePath(), TRACE_TYPE); fEditorBot = SWTBotUtils.activateEditor(fBot, fTestFile.getName()); } inline it instead of doing this.

Target:
public void before() { SWTBotUtils.openTrace(TRACE_PROJECT_NAME, fTestFile.getAbsolutePath(), TRACE_TYPE); fEditorBot = SWTBotUtils.activateEditor(fBot, fTestFile.getName()); }
Source:
START private static int inversePremultipliedColor(int color, int alpha) { END // Calculating inverse for premultiplied color gives a range of possible colors // due to rounding that occurs with integer calculations. However, alpha-blend // formula only has the multiplied component, so all of those inverses are equivalent. return (255*color + alpha-1) / alpha; } Let's make this non-static and non-private. It seems like it's a function that might be useful down the line.

Target:
static int inversePremultipliedColor(int color, int alpha) { return (255*color + alpha-1) / alpha; }
Source:
private boolean isVirtual(ContextInfo info) { START if (info.isVirtual != null) END return info.isVirtual; info.isVirtual = ClassTypeHelper.isVirtual(info.method); return info.isVirtual; } Slightly shorter: if (info.isVirtual == null) { info.isVirtual = ClassTypeHelper.isVirtual(info.method); } return info.isVirtual;

Target:
private boolean isVirtual(ContextInfo info) { if (info.isVirtual == null) { info.isVirtual = ClassTypeHelper.isVirtual(info.method); } return info.isVirtual; }
Source:
protected Notifier getNotifierFromEditorInput(Object editorInput) { Object input = editorInput; if (input instanceof RootObject) { final EObject root = ((RootObject) input).getRoot(); START if (root.eResource() != null) { END input = root.eResource(); } else { input = root; } } if (!Notifier.class.isInstance(input)) { throw new IllegalStateException("The editor input is not a Notifier!"); //$NON-NLS-1$ } return (Notifier) input; } In what case would there ever not be a resource? And we weren't previously setting the resource as input. Can this change break existing clients of the GenericEditor class, especially subclasses?

Target:
protected Notifier getNotifierFromEditorInput(Object editorInput) { Object input = editorInput; if (input instanceof RootObject) { input = ((RootObject) input).getRoot(); } if (!Notifier.class.isInstance(input)) { throw new IllegalStateException("The editor input is not a Notifier!"); //$NON-NLS-1$ } return (Notifier) input; }
Source:
START private org.eclipse.equinox.p2.repository.spi.RepositoryReference toSpiRepositoryReference(RepositoryReference rr) { END return new org.eclipse.equinox.p2.repository.spi.RepositoryReference(URI.create(rr.getLocation()), rr.getName(), IRepository.TYPE_METADATA, rr.isEnable() ? IRepository.ENABLED : IRepository.NONE); } could be static.

Target:
private static org.eclipse.equinox.p2.repository.spi.RepositoryReference toSpiRepositoryReference( RepositoryReference rr) { return new org.eclipse.equinox.p2.repository.spi.RepositoryReference(URI.create(rr.getLocation()), rr.getName(), IRepository.TYPE_METADATA, rr.isEnable() ? IRepository.ENABLED : IRepository.NONE); }
Source:
private Set<InferenceVariable> getInferenceVariables(ParameterizedTypeBinding parameterizedType) { final Set<InferenceVariable> inferenceVariables = new LinkedHashSet<>(); START for(int END i=0;i<parameterizedType.arguments.length;i++) { final TypeBinding argument = parameterizedType.arguments[i]; argument.collectInferenceVariables(inferenceVariables); } return inferenceVariables; } For each loop?

Target:
private Set<InferenceVariable> getInferenceVariables(ParameterizedTypeBinding parameterizedType) { final Set<InferenceVariable> inferenceVariables = new LinkedHashSet<>(); for(final TypeBinding argument: parameterizedType.arguments) { argument.collectInferenceVariables(inferenceVariables); } return inferenceVariables; }
Source:
START private boolean reportInternalServerErrorOverSideband() throws IOException { @SuppressWarnings("resource" /* java 7 */) SideBandOutputStream err = new SideBandOutputStream( SideBandOutputStream.CH_ERROR, SideBandOutputStream.SMALL_BUF, rawOut); err.write(Constants.encode(JGitText.get().internalServerError)); err.flush(); return true; } END Does this method still need to return a boolean type, now that it always returns true?

Target:
private void reportInternalServerErrorOverSideband() throws IOException { @SuppressWarnings("resource" /* java 7 */) SideBandOutputStream err = new SideBandOutputStream( SideBandOutputStream.CH_ERROR, SideBandOutputStream.SMALL_BUF, rawOut); err.write(Constants.encode(JGitText.get().internalServerError)); err.flush(); }
Source:
public TmfExperiment(final Class<? extends ITmfEvent> type, final String path, final ITmfTrace[] traces, final int indexPageSize, final @Nullable IResource resource) { initExperiment(type, path, traces, indexPageSize, resource, START null); END } shouldn't we pass TmfTraceType.DEFAULT_EXPERIMENT_TYPE instead?

Target:
public TmfExperiment(final Class<? extends ITmfEvent> type, final String path, final ITmfTrace[] traces, final int indexPageSize, final @Nullable IResource resource) { initExperiment(type, path, traces, indexPageSize, resource); }
Source:
START public boolean contains(Object o) { END return fInnerElements.containsValue(o); } Should we make special code for null (maybe by comparing size of this vs. size of hash map).

Target:
public boolean contains(Object o) { return (o == null && size() > fInnerElements.size()) || fInnerElements.containsValue(o); }
Source:
protected void setResult(Collection<T> newUserSelection) { START if (newUserSelection == null) { END result = null; } else { result = newUserSelection; } } The if and else blocks are unnecessary, you could just write "result = newUserSelection"

Target:
protected void setResult(Collection<T> newUserSelection) { result = newUserSelection; }
Source:
START public T getFirstResult() { END Collection<T> list = getResult(); if (list == null) { return null; } Iterator<T> iterator = list.iterator(); if (iterator.hasNext()) { return iterator.next(); } return null; } For new API I'd prefer to return an java.util.Optional<T> instead of null to avoid potential NPEs.

Target:
public Optional<T> getFirstResult() { Collection<T> list = getResult(); Iterator<T> iterator = list.iterator(); if (iterator.hasNext()) { return Optional.of(iterator.next()); } return Optional.empty(); }
Source:
protected void setResult(Collection<T> newUserSelection) { START if (newUserSelection == null) { END result = Collections.emptyList(); } else { result = newUserSelection; } } simply do "result = newUserSelection" here because the changed getResult() mehtod, which will manage the null

Target:
protected void setResult(Collection<T> newUserSelection) { if (newUserSelection == null) { result = null; } else { result = newUserSelection; } }
Source:
protected void setResult(T... newUserSelection) { if (newUserSelection == null) { START result = Collections.emptyList(); END } else { result = Arrays.asList(newUserSelection); } } Simply set the result to null here

Target:
protected void setResult(T... newUserSelection) { if (newUserSelection == null) { result = null; } else { result = Arrays.asList(newUserSelection); } }
Source:
public boolean supportsAtomicCreateNewFile() { if (supportsAtomicCreateNewFile == AtomicFileCreation.UNDEFINED) { determineAtomicFileCreationSupport(); START if (supportsAtomicCreateNewFile == AtomicFileCreation.UNDEFINED) { supportsAtomicCreateNewFile = AtomicFileCreation.SUPPORTED; } END } return supportsAtomicCreateNewFile == AtomicFileCreation.SUPPORTED; } I wonder if it's better to move this into the determineAtomicFileCreationSupport method? At the moment the only caller is here (L360) but if in future it gets called from somewhere else, this patch won't be effective.

Target:
public boolean supportsAtomicCreateNewFile() { if (supportsAtomicCreateNewFile == AtomicFileCreation.UNDEFINED) { determineAtomicFileCreationSupport(); } return supportsAtomicCreateNewFile == AtomicFileCreation.SUPPORTED; }
Source:
public void traceClosed(@Nullable TmfTraceClosedSignal signal) { if (signal == null || signal.getTrace() != fTrace) { return; } // Reset the internal data fTrace = null; START Runnable r = this::reset; END // Make sure that runnable is called from UI thread if (Display.getCurrent() == null) { Display d = Display.getDefault(); if (!d.isDisposed()) { d.asyncExec(r); } } else { r.run(); } } Not necessary, the signal should be sent from UI thread.

Target:
public void traceClosed(@Nullable TmfTraceClosedSignal signal) { if (signal == null || signal.getTrace() != fTrace) { return; } // Reset the internal data fTrace = null; reset(); }
Source:
private GitModelObject[] createChildren() { FileModelFactory fileModelFactory = new FileModelFactory() { @Override public GitModelBlob createFileModel(GitModelObjectContainer parent, Repository repository, Change change, IPath fullPath) { return new GitModelBlob(parent, repository, change, fullPath); } @Override public boolean isWorkingTree() { return false; } }; TreeModelFactory treeModelFactory = GitModelTree::new; return TreeBuilder.build(this, repo, commit.getChildren(), fileModelFactory, START treeModelFactory); END } Use GitModelTree::new here directly and remove the local variable treeModelFactory altogether.

Target:
private GitModelObject[] createChildren() { FileModelFactory fileModelFactory = new FileModelFactory() { @Override public GitModelBlob createFileModel(GitModelObjectContainer parent, Repository repository, Change change, IPath fullPath) { return new GitModelBlob(parent, repository, change, fullPath); } @Override public boolean isWorkingTree() { return false; } }; return TreeBuilder.build(this, repo, commit.getChildren(), fileModelFactory, GitModelTree::new); }
Source:
private Property toProperty(@NonNull String value) { switch (value) { case "hasStagedChanges": //$NON-NLS-1$ return Property.HAS_STAGED_CHANGES; case "hasUnstagedChanges": //$NON-NLS-1$ return Property.HAS_UNSTAGED_CHANGES; case "hasNotIgnoredResources": //$NON-NLS-1$ return Property.HAS_NOT_IGNORED_RESOURCES; case "hasTrackedResources": //$NON-NLS-1$ return Property.HAS_TRACKED_RESOURCES; default: START break; END } return null; } Simply default: return null; and removing line 129 would be a bit shorter and more regular.

Target:
private Property toProperty(@NonNull String value) { switch (value) { case "hasStagedChanges": //$NON-NLS-1$ return Property.HAS_STAGED_CHANGES; case "hasUnstagedChanges": //$NON-NLS-1$ return Property.HAS_UNSTAGED_CHANGES; case "hasNotIgnoredResources": //$NON-NLS-1$ return Property.HAS_NOT_IGNORED_RESOURCES; case "hasTrackedResources": //$NON-NLS-1$ return Property.HAS_TRACKED_RESOURCES; default: return null; } }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } START if (obj == null) { return false; } END if (!(obj instanceof ConnectionEndpoint)) { return false; } ConnectionEndpoint other = (ConnectionEndpoint) obj; return Arrays.equals(fAddress, other.fAddress) && fPort == other.fPort; } this is redundant with next instanceof check

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ConnectionEndpoint)) { return false; } ConnectionEndpoint other = (ConnectionEndpoint) obj; return Arrays.equals(fAddress, other.fAddress) && fPort == other.fPort; }
Source:
public boolean isSameValue(ICPPTemplateArgument arg) { START return arg.isTypeValue() && fType.isSameType(arg.getTypeValue()); END } To answer your question: I don't think so. I think there could be legitimate reasons to compare type and non-type template arguments. Thinking of an example is somewhat tricky, but perhaps something like this: template <typename T> void foo(); // Overload on template parameter kind. That's valid. template <int I> void foo(); template <typename T> auto bar() -> decltype(foo<T>()); // Declaration matching code will need to compare // template argument lists <T> and <T()> to determine // if this is a redeclaration or an overload. template <typename T> auto bar() -> decltype(foo<T()>());

Target:
public boolean isSameValue(ICPPTemplateArgument arg) { return fType.isSameType(arg.getTypeValue()); }
Source:
public ImageDescriptor getImageDescriptorForProgram(String extension) { ImageDescriptor imageDescriptor = getImageRegistry().getDescriptor(extension); if (imageDescriptor == null && extension != null) { Program program = START ProgramFinder.findProgram(extension.toLowerCase()); END if (program == null || program.getImageData() == null) { // provide no image (i.e. leave null) } else { imageDescriptor = ImageDescriptor.createFromImageData(program.getImageData()); getImageRegistry().put(extension, imageDescriptor); } } return imageDescriptor; } Perform this operation in the custom ProgramFinder.findProgram() method instead.

Target:
public ImageDescriptor getImageDescriptorForProgram(String extension) { ImageDescriptor imageDescriptor = getImageRegistry().getDescriptor(extension); if (imageDescriptor == null && extension != null) { Program program = ProgramFinder.findProgram(extension); if (program == null || program.getImageData() == null) { // provide no image (i.e. leave null) } else { imageDescriptor = ImageDescriptor.createFromImageData(program.getImageData()); getImageRegistry().put(extension, imageDescriptor); } } return imageDescriptor; }
Source:
public ImageDescriptor createImageDescriptor() { Program program = START ProgramFinder.findProgram(extension.toLowerCase()); END if (program == null || program.getImageData() == null) { return null; } return ImageDescriptor.createFromImageData(program.getImageData()); } Perform this operation in the custom ProgramFinder.findProgram() method instead.

Target:
public ImageDescriptor createImageDescriptor() { Program program = ProgramFinder.findProgram(extension); if (program == null || program.getImageData() == null) { return null; } return ImageDescriptor.createFromImageData(program.getImageData()); }
Source:
public boolean hasTimeEvents() { return fModel instanceof ITimeGraphEntryModel ? ((TimeGraphEntryModel) fModel).hasRowModel() : START true; END } I would have thought that if it's not a ITimeGraphEntryModel then it doesn't have a row model? If it does, then why is it not a ITimeGraphEntryModel? Cast should be to ITimeGraphEntryModel.

Target:
public boolean hasTimeEvents() { return fModel instanceof ITimeGraphEntryModel ? ((ITimeGraphEntryModel) fModel).hasRowModel() : true; }
Source:
START public long nanosToCycles(long nanos) { END // CTFTrace subtracts the clock offset in cycles from the output CTFTrace trace = fTrace; if (trace != null) { return trace.timestampNanoToCycles(nanos - trace.getClock().getClockOffsetNs()) + trace.getOffset(); } return 0; } This method is a simple converter that is only dependent on frequency and not dependent on clock offset. It should return nanos * clock.getAntiScale(), or nanos if clock is null.

Target:
public long nanosToCycles(long nanos) { // CTFTrace subtracts the clock offset in cycles from the output CTFTrace trace = fTrace; if (trace != null) { return trace.timestampNanoToCycles(nanos) + trace.getOffset(); } return 0; }
Source:
private void setOptionalDependencies(TargetPlatformConfiguration result, Xpp3Dom resolverDom) { String value = getStringValue(resolverDom.getChild("optionalDependencies")); START if (null == value) { END return; } else switch (value) { case OPTIONAL_RESOLUTION_REQUIRE: result.setOptionalResolutionAction(OptionalResolutionAction.REQUIRE); break; case OPTIONAL_RESOLUTION_IGNORE: result.setOptionalResolutionAction(OptionalResolutionAction.IGNORE); break; default: throw new BuildFailureException("Illegal value of <optionalDependencies> dependency resolution parameter: " + value); } } Same thing as in other class, it'd be better to invert the condition for readability.

Target:
private void setOptionalDependencies(TargetPlatformConfiguration result, Xpp3Dom resolverDom) { String value = getStringValue(resolverDom.getChild("optionalDependencies")); if (value == null) { return; } else switch (value) { case OPTIONAL_RESOLUTION_REQUIRE: result.setOptionalResolutionAction(OptionalResolutionAction.REQUIRE); break; case OPTIONAL_RESOLUTION_IGNORE: result.setOptionalResolutionAction(OptionalResolutionAction.IGNORE); break; default: throw new BuildFailureException("Illegal value of <optionalDependencies> dependency resolution parameter: " + value); } }
Source:
public void testReWriteArtifactViaStreamFails() throws Exception { ProvisionException expectedException = null; try { START try (OutputStream addSink = subject.getOutputStream(ARTIFACT_A_CANONICAL)) { END addSink.write(new byte[1]); } } catch (ProvisionException e) { expectedException = e; } assertThat(expectedException, is(instanceOf(ProvisionException.class))); assertThat(expectedException.getStatus().getCode(), is(ProvisionException.ARTIFACT_EXISTS)); } style nit: tabs vs spaces, inconsistent with surrounding code

Target:
public void testReWriteArtifactViaStreamFails() throws Exception { ProvisionException expectedException = null; try (OutputStream addSink = subject.getOutputStream(ARTIFACT_A_CANONICAL)) { addSink.write(new byte[1]); } catch (ProvisionException e) { expectedException = e; } assertThat(expectedException, is(instanceOf(ProvisionException.class))); assertThat(expectedException.getStatus().getCode(), is(ProvisionException.ARTIFACT_EXISTS)); }
Source:
public static synchronized void dispose() { ScriptingDataProviderManager manager = INSTANCE; if (manager != null) { TmfSignalManager.deregister(manager); manager.fInstances.clear(); } START INSTANCE = null; END } Move inside if statement

Target:
public static synchronized void dispose() { ScriptingDataProviderManager manager = INSTANCE; if (manager != null) { TmfSignalManager.deregister(manager); manager.fInstances.clear(); INSTANCE = null; } }
Source:
private void disposeToolBarElement(ToolBarManager parentManager, MToolBarElement toolBarElement) { IContributionItem ici = getContribution(toolBarElement); if (ici == null) { return; } parentManager.remove(ici); START ici.dispose(); END clearModelToContribution(toolBarElement, ici); } Shouldn't we dispose ici as last step?

Target:
private void disposeToolBarElement(ToolBarManager parentManager, MToolBarElement toolBarElement) { IContributionItem ici = getContribution(toolBarElement); if (ici == null) { return; } parentManager.remove(ici); clearModelToContribution(toolBarElement, ici); ici.dispose(); }
Source:
public void testDynamicItem_AddOne() { contextRule.createAndRunWorkbench(window); ToolBarManager tbm = getManager(toolBar); START assertTrue(tbm.getSize() == 0); END MToolItem toolItem1 = ems.createModelElement(MDirectToolItem.class); toolBar.getChildren().add(toolItem1); assertTrue(tbm.getSize() == 1); } It makes sense to use assertEquals here and below, to see the actual value in the failing case

Target:
public void testDynamicItem_AddOne() { contextRule.createAndRunWorkbench(window); ToolBarManager tbm = getManager(toolBar); assertEquals(tbm.getSize(), 0); MToolItem toolItem1 = ems.createModelElement(MDirectToolItem.class); toolBar.getChildren().add(toolItem1); assertEquals(tbm.getSize(), 1); }