auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void removeGroup(GroupInfo group) { Object[] listenersArray = listeners.getListeners(); START for (Object element : listenersArray) { END ((IJobProgressManagerListener)element).removeGroup(group); } } inline listeners.getListeners()

Target:
public void removeGroup(GroupInfo group) { for (Object element : listeners.getListeners()) { ((IJobProgressManagerListener)element).removeGroup(group); } }
Source:
protected void checkNewDefaultBrowser(Object browser) { TableItem[] children = tableViewer.getTable().getItems(); for (TableItem element : children) { START TableItem item = element; END if (!(item.getData().equals(browser))) item.setChecked(false); } } unnecessary

Target:
protected void checkNewDefaultBrowser(Object browser) { for (TableItem item : tableViewer.getTable().getItems()) { if (!(item.getData().equals(browser))) item.setChecked(false); } }
Source:
protected void inputChanged(Object input, Object oldInput) { elements.clear(); Object[] children = getSortedChildren(getRoot()); list.removeAll(); for (Object START element : END children) { elements.add(element); mapElement(element, list); } list.setElements(children); } rename 'child'

Target:
protected void inputChanged(Object input, Object oldInput) { elements.clear(); Object[] children = getSortedChildren(getRoot()); list.removeAll(); for (Object child : children) { elements.add(child); mapElement(child, list); } list.setElements(children); }
Source:
public final void setChildren(IEditorPart[] children) { innerEditors = children; activeEditorIndex = 0; for (IEditorPart START element : END children) { element.addPropertyListener( (source, propId) -> handlePropertyChange(propId)); } innerEditorsCreated(); } rename 'child'

Target:
public final void setChildren(IEditorPart[] children) { innerEditors = children; activeEditorIndex = 0; for (IEditorPart child : children) { child.addPropertyListener( (source, propId) -> handlePropertyChange(propId)); } innerEditorsCreated(); }
Source:
public void setEnabled(boolean enabled, Composite parent) { super.setEnabled(enabled, parent); group.setEnabled(enabled); for (Control START element : END group.getChildren()) { element.setEnabled(enabled); } } rename 'child'

Target:
public void setEnabled(boolean enabled, Composite parent) { super.setEnabled(enabled, parent); group.setEnabled(enabled); for (Control child : group.getChildren()) { child.setEnabled(enabled); } }
Source:
public AboutInfo[] getFeatureInfos() { // cannot be cached since bundle groups come and go List infos = new ArrayList(); // add an entry for each bundle group IBundleGroupProvider[] providers = Platform.getBundleGroupProviders(); if (providers != null) { for (IBundleGroupProvider provider : providers) { START IBundleGroup[] bundleGroups = provider.getBundleGroups(); END for (IBundleGroup bundleGroup : bundleGroups) { infos.add(new AboutInfo(bundleGroup)); } } } return (AboutInfo[]) infos.toArray(new AboutInfo[infos.size()]); } inline

Target:
public AboutInfo[] getFeatureInfos() { // cannot be cached since bundle groups come and go List infos = new ArrayList(); // add an entry for each bundle group IBundleGroupProvider[] providers = Platform.getBundleGroupProviders(); if (providers != null) { for (IBundleGroupProvider provider : providers) { for (IBundleGroup bundleGroup : provider.getBundleGroups()) { infos.add(new AboutInfo(bundleGroup)); } } } return (AboutInfo[]) infos.toArray(new AboutInfo[infos.size()]); }
Source:
public void test_ConstructorLorg_eclipse_swt_widgets_CompositeI() { Browser browser = new Browser(shell, SWT.NONE); browser.dispose(); browser = new Browser(shell, SWT.BORDER); // System.out.println("Test_org_eclipse_swt_browser_Browser#test_Constructor*#getBrowserType(): " + browser.getBrowserType()); browser.dispose(); browser = new Browser(null, SWT.NONE); // Should throw. START fail("No exception thrown for parent == null"); END } No need for the fail. Junit will auto fail the test if the expected exception is not thrown.

Target:
public void test_ConstructorLorg_eclipse_swt_widgets_CompositeI() { Browser browser = new Browser(shell, SWT.NONE); browser.dispose(); browser = new Browser(shell, SWT.BORDER); // System.out.println("Test_org_eclipse_swt_browser_Browser#test_Constructor*#getBrowserType(): " + browser.getBrowserType()); browser.dispose(); browser = new Browser(null, SWT.NONE); // Should throw. }
Source:
protected Spec[] getSelectedSpecs() { START List list END = fileAssociationViewer.getStructuredSelection().toList(); return (Spec[]) list.toArray(new Spec[list.size()]); } add generic

Target:
protected Spec[] getSelectedSpecs() { List<Spec> list = fileAssociationViewer.getStructuredSelection().toList(); return list.toArray(new Spec[list.size()]); }
Source:
private static <T> List<T> getReversed(Collection<T> collection) { START ArrayList<T> result = new ArrayList<>(); result.addAll(collection); END Collections.reverse(result); return result; } Simpler: ArrayList<T> result = new ArrayList<>(collection);

Target:
private static <T> List<T> getReversed(Collection<T> collection) { ArrayList<T> result = new ArrayList<>(collection); Collections.reverse(result); return result; }
Source:
private Figure getGroupFigure(List<Figure> dDiagramElementDecorationFigures, Position position, Rectangle expectedGroupBounds) { Figure groupFigure = null; for (Figure currentGroupFigure : dDiagramElementDecorationFigures) { START System.out.println("figure bounds " + currentGroupFigure.getBounds()); END if (currentGroupFigure.getBounds().equals(expectedGroupBounds)) { groupFigure = currentGroupFigure; break; } } assertNotNull("Bad group decoration position at " + position.getName(), groupFigure); return groupFigure; } to remove

Target:
private Figure getGroupFigure(List<Figure> dDiagramElementDecorationFigures, Position position, Rectangle expectedGroupBounds) { Figure groupFigure = null; for (Figure currentGroupFigure : dDiagramElementDecorationFigures) { if (currentGroupFigure.getBounds().equals(expectedGroupBounds)) { groupFigure = currentGroupFigure; break; } } assertNotNull("Bad group decoration position at " + position.getName(), groupFigure); return groupFigure; }
Source:
START protected void updateEnablement(IAction action) { END boolean enabled = isEnabled(); action.setEnabled(enabled); } the superclass implementation seems to expect action may be null, also the super implementation also has some logic about whether the context is active. I don't know that we need this since our plugin XML is checking that property.

Target:
protected void updateEnablement(IAction action) { action.setEnabled(isEnabled()); }
Source:
START public ISearchResultPage getCurrentPage() { END IViewPart view = super.getPartForAction(); return ((SearchView) view).getActivePage(); } this should be private

Target:
private ISearchResultPage getCurrentPage() { IViewPart view = super.getPartForAction(); return ((SearchView) view).getActivePage(); }
Source:
public boolean isEnabled() { List<StructuredViewer> viewers = getViewers(); START ISearchResultPage page = getCurrentPage(); END return viewers.size() > 0 && page != null && WHITELISTED_IDS.contains(page.getID()); } viewers > 0 implies page is non-null

Target:
public boolean isEnabled() { List<StructuredViewer> viewers = getViewers(); ISearchResultPage page = getCurrentPage(); return viewers.size() > 0 && WHITELISTED_IDS.contains(page.getID()); }
Source:
public Object resolveArtifact(EObject artifact) { START ArtifactWrapper wrapper = (ArtifactWrapper) artifact; END String uri = wrapper.getUri(); CapraOfficeObject object = new CapraOfficeObject(); object.setUri(uri); return object; } I am pretty sure that gives you an unchecked cast warning. I think it would be pertinent to add a check here, just to make the code more robust.

Target:
public Object resolveArtifact(EObject artifact) { if (artifact instanceof ArtifactWrapper) { ArtifactWrapper wrapper = (ArtifactWrapper) artifact; String uri = wrapper.getUri(); CapraOfficeObject object = new CapraOfficeObject(); object.setUri(uri); return object; } else return null; }
Source:
protected static MarkupParser createParserWithConfiguration(MarkupLanguageConfiguration configuration) { MarkupLanguage markupLanguage = new AsciiDocLanguage(); if (configuration != null) { markupLanguage.configure(configuration); } START MarkupParser parser = new END MarkupParser(markupLanguage); return parser; } inline return statement here

Target:
protected static MarkupParser createParserWithConfiguration(MarkupLanguageConfiguration configuration) { MarkupLanguage markupLanguage = new AsciiDocLanguage(); if (configuration != null) { markupLanguage.configure(configuration); } return new MarkupParser(markupLanguage); }
Source:
protected boolean shouldBeDecorated(final EditPart editPart) { START boolean shouldBeDecorated = super.shouldBeDecorated(editPart); return shouldBeDecorated && editPart instanceof IDiagramElementEditPart; END } Doing the "instanceof" test first would avoid calling the more costly "super": return editPart instanceof IDiagramElementEditPart && super.shouldBeDecorated(editPart);

Target:
protected boolean shouldBeDecorated(final EditPart editPart) { return editPart instanceof IDiagramElementEditPart && super.shouldBeDecorated(editPart); }
Source:
START private List<ApplicabilityToken> getStoredApplicabilities() { END List<ApplicabilityToken> appls = new LinkedList<>(); appls.addAll(AtsClientService.getApplicabilityEndpoint( AtsClientService.get().getAtsBranch()).getApplicabilityReferenceTokens(workItem.getStoreObject())); return appls; } Looks like getApplicabilityReferenceTokens already returns a list? Don't need to add to another list?

Target:
private List<ApplicabilityToken> getStoredApplicabilities() { return AtsClientService.getApplicabilityEndpoint( AtsClientService.get().getAtsBranch()).getApplicabilityReferenceTokens(workItem.getStoreObject()); }
Source:
public boolean canHandleArtifact(T artifact) { try { START @SuppressWarnings("rawtypes") END Class<?> genericType = ((Class) ((ParameterizedType) this.getClass().getGenericSuperclass()) .getActualTypeArguments()[0]); return genericType.isAssignableFrom(artifact.getClass()); } catch (NoClassDefFoundError e) { return false; } } This is not necessary if the cast is to Class<?>.

Target:
public boolean canHandleArtifact(T artifact) { try { Class<?> genericType = ((Class<?>) ((ParameterizedType) this.getClass().getGenericSuperclass()) .getActualTypeArguments()[0]); return genericType.isAssignableFrom(artifact.getClass()); } catch (NoClassDefFoundError e) { return false; } }
Source:
public synchronized void dispose() { /* Clean up the index if applicable */ if (getIndexer() != null) { getIndexer().dispose(); } /* Clean up the analysis modules */ START @NonNull END Iterable<IAnalysisModule> analysisModules = getAnalysisModules(); for (IAnalysisModule module : analysisModules) { module.dispose(); } fAnalysisModules.clear(); super.dispose(); } Remove or put on same line?

Target:
public synchronized void dispose() { /* Clean up the index if applicable */ if (getIndexer() != null) { getIndexer().dispose(); } /* Clean up the analysis modules */ Iterable<IAnalysisModule> analysisModules = getAnalysisModules(); for (IAnalysisModule module : analysisModules) { module.dispose(); } fAnalysisModules.clear(); super.dispose(); }
Source:
START protected END T doGetValue() { // The value is not kept up to date when we are not listening. if (isListening) { return value; } return calculate(); } final

Target:
protected final T doGetValue() { // The value is not kept up to date when we are not listening. if (isListening) { return value; } return calculate(); }
Source:
START protected void doSetValue(T value) { END if (this.value != value) { fireValueChange(Diffs.createValueDiff(this.value, this.value = value)); } } final This should probably contain this.value = value at some point... and it should only do so if isListening = true.

Target:
protected final void doSetValue(T value) { if (this.value != value) { fireValueChange(Diffs.createValueDiff(this.value, this.value = value)); } }
Source:
START protected void firstListenerAdded() { END if (getRealm().isCurrent()) { startListeningInternal(); } else { getRealm().asyncExec(() -> { if (hasListeners && !isListening) { startListeningInternal(); } }); } hasListeners = true; super.firstListenerAdded(); } final

Target:
protected final void firstListenerAdded() { if (getRealm().isCurrent()) { startListeningInternal(); } else { getRealm().asyncExec(() -> { if (hasListeners && !isListening) { startListeningInternal(); } }); } hasListeners = true; super.firstListenerAdded(); }
Source:
private void startListeningInternal() { START startListening(); END isListening = true; value = calculate(); } startListening is overridable and calls into other code that this class has no control over. It should be the last thing in this method to prevent any possibility of other code calling back into this object while it's in an invalid intermediate state.

Target:
private void startListeningInternal() { isListening = true; value = calculate(); startListening(); }
Source:
public void testMenuNoMarkerSet() { SWTBotRootMenu viewMenu = fViewBot.viewMenu(); List<String> menuItems = viewMenu.menu("Marker Set").menuItems(); START assertEquals("number of items", 3, menuItems.size()); END assertArrayEquals("menu items, no marker set", MENU_ITEMS_NO_MARKERS_SET, menuItems.toArray()); } assertArrayEquals will check length

Target:
public void testMenuNoMarkerSet() { SWTBotRootMenu viewMenu = fViewBot.viewMenu(); List<String> menuItems = viewMenu.menu("Marker Set").menuItems(); assertArrayEquals("menu items, no marker set", MENU_ITEMS_NO_MARKERS_SET, menuItems.toArray()); }
Source:
private boolean hasIndirectDependent(Set<StructDef<?>> visited, StructDef<?> structDef) { for (StructDef<?> next : this.dependents) { if START (visited.contains(next)) { END continue; } visited.add(next); if (next.equals(structDef)) { return true; } if (next.hasIndirectDependent(visited, structDef)) { return true; } } return false; } Simpler: if (!visited.add(next))

Target:
private boolean hasIndirectDependent(Set<StructDef<?>> visited, StructDef<?> structDef) { for (StructDef<?> next : this.dependents) { if (!visited.add(next)) { continue; } if (next.equals(structDef)) { return true; } if (next.hasIndirectDependent(visited, structDef)) { return true; } } return false; }
Source:
public Map<String, String> createImageServerContent(String scheme) throws IOException { START HashMap<String, END String> map = new HashMap<>(); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml", createServerEntry("WikiToDocTaskIntegrationTest1.xml")); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml&gimcontinue=49671%7Cpict1.gif", createServerEntry("WikiToDocTaskIntegrationTest2.xml")); return map; } Map here, makes code more readable, e.g. Map<String,String> map = new HashMap<>()

Target:
public Map<String, String> createImageServerContent(String scheme) throws IOException { Map<String, String> map = new HashMap<>(); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml", createServerEntry("WikiToDocTaskIntegrationTest1.xml")); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml&gimcontinue=49671%7Cpict1.gif", createServerEntry("WikiToDocTaskIntegrationTest2.xml")); return map; }
Source:
protected Reader createInputReader(URL apiUrl) throws UnsupportedEncodingException, IOException { START if (serverContent == null) { throw new IllegalStateException( "Please specify some server content for images used during the tests. See: TestMediaWikiApiImageFetchingStrategy#serverContent"); } END String key = apiUrl.toString(); if (!serverContent.containsKey(key)) { throw new IllegalStateException("Please define a server content used during the tests for the key: " + key); } String pageContent = serverContent.get(key); return new StringReader(pageContent); } use checkNotNull in the constructor instead

Target:
protected Reader createInputReader(URL apiUrl) throws UnsupportedEncodingException, IOException { String key = apiUrl.toString(); if (!serverContent.containsKey(key)) { throw new IllegalStateException("Please define a server content used during the tests for the key: " + key); } String pageContent = serverContent.get(key); return new StringReader(pageContent); }
Source:
public START HashMap<String, END String> createImageServerContent(String scheme) throws IOException { HashMap<String, String> map = new HashMap<String, String>(); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml", createServerEntry("WikiToDocTaskIntegrationTest1.xml")); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml&gimcontinue=49671%7Cpict1.gif", createServerEntry("WikiToDocTaskIntegrationTest2.xml")); return map; } return Map instead of HashMap

Target:
public Map<String, String> createImageServerContent(String scheme) throws IOException { HashMap<String, String> map = new HashMap<>(); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml", createServerEntry("WikiToDocTaskIntegrationTest1.xml")); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml&gimcontinue=49671%7Cpict1.gif", createServerEntry("WikiToDocTaskIntegrationTest2.xml")); return map; }
Source:
private void findByName() throws IOException { RepositoryUtil repoUtil = getRepositoryUtil(); RepositoryCache repoCache = getRepositoryCache(); for (String dirs : repoUtil.getConfiguredRepositories()) { match = repoCache.lookupRepository(new File(dirs)); if (!ResourcePropertyTester.hasGerritConfiguration(match)) { START break; END } RemoteConfig remote = findRemoteByName(); if (remote != null) { return; } } match = null; } I have a question : Why testing if the configuration has a Gerrit config, If we don't, then break. It should be the opposite and we should keep the match value not re-init at the end of the method to null. In all cases, the match will be null,

Target:
private void findByName() throws IOException { RepositoryUtil repoUtil = getRepositoryUtil(); RepositoryCache repoCache = getRepositoryCache(); for (String dirs : repoUtil.getConfiguredRepositories()) { match = repoCache.lookupRepository(new File(dirs)); if (!ResourcePropertyTester.hasGerritConfiguration(match)) { continue; } RemoteConfig remote = findRemoteByName(); if (remote != null) { return; } } match = null; }
Source:
protected ICommand getBeforeMoveCommand(final MoveRequest request) { START ICommand gmfCommand = super.getBeforeMoveCommand(request); END if (request.getTargetContainer().eIsProxy()) { return UnexecutableCommand.INSTANCE; } return gmfCommand; } why call super here if the first return is call, gmfCommand will be never used. More the gmfCommand will be always null. It's not necessary to call super. Just return the unexecutable command in case of proxy or null: return request.getTargetContainer().eIsProxy()?UnexecutableCommand.INSTANCE:null should be enough.

Target:
protected ICommand getBeforeMoveCommand(final MoveRequest request) { return request.getTargetContainer().eIsProxy() ? UnexecutableCommand.INSTANCE : null; }
Source:
public boolean isExpandable(Object elementOrTreePath) { Object element; TreePath path; if (elementOrTreePath instanceof TreePath) { path = (TreePath) elementOrTreePath; element = path.getLastSegment(); } else { element = elementOrTreePath; START path = null; END } IContentProvider cp = getContentProvider(); if (cp instanceof ITreeContentProvider) { ITreeContentProvider tcp = (ITreeContentProvider) cp; return tcp.hasChildren(element); } return false; } what is the point of setting path to null here. It looks like it is only needed in the if statement above

Target:
public boolean isExpandable(Object elementOrTreePath) { Object element; TreePath path = null; if (elementOrTreePath instanceof TreePath) { path = (TreePath) elementOrTreePath; element = path.getLastSegment(); } else { element = elementOrTreePath; } IContentProvider cp = getContentProvider(); if (cp instanceof ITreeContentProvider) { ITreeContentProvider tcp = (ITreeContentProvider) cp; return tcp.hasChildren(element); } return false; }
Source:
public void createPartControl(@Nullable Composite parent) { super.createPartControl(parent); START String name = getViewSite().getSecondaryId(); END if (name != null) { fViewInfo.setName(name); } setViewTitle(); } Would the order need to be reversed here too? I don't have as many XY charts to test with...

Target:
public void createPartControl(@Nullable Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { /* must initialize view info before calling super */ fViewInfo.setName(name); } super.createPartControl(parent); setViewTitle(); }
Source:
public static START synchronized IndexedUserContainer END getInstance() { return container; } obsolete now, accessing a class attribute is thread-safe

Target:
public static IndexedUserContainer getInstance() { return container; }
Source:
protected void appendName(ActivityPartition activitypartition, Collection<String> displayValue, StringBuilder sb) { Element represents = activitypartition.getRepresents(); String activitypartitionName = UMLLabelInternationalization.getInstance().getLabel(activitypartition); START if (represents != null) { if (represents instanceof NamedElement) { END activitypartitionName = ((NamedElement) represents).getName() ; } } appendString(sb, activitypartitionName, UNNAMED); return; } instanceof already check the not null See https://gist.github.com/bmaggi/66a5803f79fefb6f57db887a9d9cec4f

Target:
protected void appendName(ActivityPartition activitypartition, Collection<String> displayValue, StringBuilder sb) { Element represents = activitypartition.getRepresents(); String activitypartitionName = UMLLabelInternationalization.getInstance().getLabel(activitypartition); if (represents instanceof NamedElement) { activitypartitionName = ((NamedElement) represents).getName() ; } appendString(sb, activitypartitionName, UNNAMED); return; }
Source:
protected void appendName(ActivityPartition activitypartition, Collection<String> displayValue, StringBuilder sb) { Element represents = activitypartition.getRepresents(); String activitypartitionName = UMLLabelInternationalization.getInstance().getLabel(activitypartition); if (represents != null) { START try { activitypartitionName = ((NamedElement) represents).getName() ; } catch (ClassCastException e) { } END } appendString(sb, activitypartitionName, UNAMED); return; } Seems like a strange way of handling the cast. Why not make an explicit check the represents instanceof NamedElement? Why cause an exception to be thrown and then catch it?

Target:
protected void appendName(ActivityPartition activitypartition, Collection<String> displayValue, StringBuilder sb) { Element represents = activitypartition.getRepresents(); String activitypartitionName = UMLLabelInternationalization.getInstance().getLabel(activitypartition); if (represents != null) { if (represents instanceof NamedElement) { activitypartitionName = ((NamedElement) represents).getName() ; } } appendString(sb, activitypartitionName, UNAMED); return; }
Source:
public long getPacketSizeBits() { return START 0; END } Should this be 1 if content size is 1?

Target:
public long getPacketSizeBits() { return 3; }
Source:
public void addChild(LaunchObjectModel model) { START for (LaunchObjectModel e : children) { model.compareTo(e); } END children.add(model); } This looks superfluous, since compareTo() must not have any side effects.

Target:
public void addChild(LaunchObjectModel model) { children.add(model); }
Source:
protected Map<String, TraceTypeHelper> getTraceTypeMap(String selected) { Map<String, TraceTypeHelper> traceTypeMap = new TreeMap<>(); for (TraceTypeHelper helper : TmfTraceType.getTraceTypeHelpers()) { if (!helper.isExperimentType() && (helper.isEnabled() || START (selected != null && END helper.getTraceTypeId().equals(selected)))) { traceTypeMap.put(helper.getLabel(), helper); } } return traceTypeMap; } Can remove, if it's null it won't be equal, and helper's id can't be null.

Target:
protected Map<String, TraceTypeHelper> getTraceTypeMap(String selected) { Map<String, TraceTypeHelper> traceTypeMap = new TreeMap<>(); for (TraceTypeHelper helper : TmfTraceType.getTraceTypeHelpers()) { if (!helper.isExperimentType() && (helper.isEnabled() || (helper.getTraceTypeId().equals(selected)))) { traceTypeMap.put(helper.getLabel(), helper); } } return traceTypeMap; }
Source:
START private RevCommit END parseCommit(AnyObjectId id) throws IncorrectObjectTypeException, IOException, MissingObjectException { if (id instanceof RevCommit) { return (RevCommit) id; } try (RevWalk walk = new RevWalk(this)) { return walk.parseCommit(id); } } Shouldn't it be public?

Target:
public RevCommit parseCommit(AnyObjectId id) throws IncorrectObjectTypeException, IOException, MissingObjectException { if (id instanceof RevCommit) { return (RevCommit) id; } try (RevWalk walk = new RevWalk(this)) { return walk.parseCommit(id); } }
Source:
private void writeCatchHandler(ICPPASTCatchHandler catchStatement) { START writeAttributes(catchStatement, EnumSet.of(SpaceLocation.AFTER)); END scribe.print(CATCH); if (catchStatement.isCatchAll()) { scribe.print(VAR_ARGS); } else { scribe.noSemicolon(); scribe.noNewLines(); catchStatement.getDeclaration().accept(visitor); scribe.newLines(); } scribe.print(')'); writeBodyStatement(catchStatement.getCatchBody(), true); } Are you sure that we can have attributes on an ICPPASTCatchHandler? Even though it is a CPPASTAttributeOwner, it seems to me that the standard does not allow for attributes here. [gram.stmt] allows for attribute-specifier-seq on try-block but [gram.except] does not further allow for attribute-specifier-seq on neither handler-seq nor handler. Maybe its a "bug" that ICPPASTCatchHandler is a CPPASTAttributeOwner in the first place?

Target:
private void writeCatchHandler(ICPPASTCatchHandler catchStatement) { scribe.print(CATCH); if (catchStatement.isCatchAll()) { scribe.print(VAR_ARGS); } else { scribe.noSemicolon(); scribe.noNewLines(); catchStatement.getDeclaration().accept(visitor); scribe.newLines(); } scribe.print(')'); writeBodyStatement(catchStatement.getCatchBody(), true); }
Source:
private static MergeAlgorithm getMergeAlgorithm(Config config) { SupportedAlgorithm diffAlg = config.getEnum( START ConfigConstants.CONFIG_DIFF_SECTION, null, END ConfigConstants.CONFIG_KEY_ALGORITHM, SupportedAlgorithm.HISTOGRAM); return new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg)); } optional: Can these be imported statically? I think that would make it easier to read.

Target:
private static MergeAlgorithm getMergeAlgorithm(Config config) { SupportedAlgorithm diffAlg = config.getEnum( CONFIG_DIFF_SECTION, null, CONFIG_KEY_ALGORITHM, HISTOGRAM); return new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg)); }
Source:
public synchronized IObjectDescriptor[] getDependentObjects() { if (objectDescriptors == null) { objectDescriptors = descriptorCache.computeIfAbsent(location, l -> { IObjectDescriptor[] descriptors = START calcDependentObjects(); END return descriptors.length > 0 ? descriptors : EMPTY_DESCRIPTORS; }); } return objectDescriptors; } This is an internal abstract class that I assume other parts of the code in this bundle implement for the calcDependentObjects() method. Wouldn't it be better for these implementations to all return the same EMPTY array constant instead of catching it here? I'm also concerned about impls that may return null resulting in an NPE here where one was not before.

Target:
public synchronized IObjectDescriptor[] getDependentObjects() { if (objectDescriptors == null) { objectDescriptors = descriptorCache.computeIfAbsent(location, l -> { IObjectDescriptor[] descriptors = calcDependentObjects(); return descriptors != null && descriptors.length > 0 ? descriptors : EMPTY_DESCRIPTORS; }); } return objectDescriptors; }
Source:
START protected Color END createColor(IPreferenceStore store, String key, Display display) { RGB rgb= null; if (store.contains(key)) { if (store.isDefault(key)) rgb= PreferenceConverter.getDefaultColor(store, key); else rgb= PreferenceConverter.getColor(store, key); if (rgb != null) return new Color(display, rgb); } return null; } this is a breaking change. NO GO.

Target:
private Color createColor(IPreferenceStore store, String key, Display display) { RGB rgb= null; if (store.contains(key)) { if (store.isDefault(key)) rgb= PreferenceConverter.getDefaultColor(store, key); else rgb= PreferenceConverter.getColor(store, key); if (rgb != null) return new Color(display, rgb); } return null; }
Source:
public void notifyChanged(Notification notification) { // Handle when a port is defined as conjugated if START ((notification.getFeatureID(Property.class) END == UMLPackage.PORT__IS_CONJUGATED)) { refreshDisplay(); } else { super.notifyChanged(notification); Object object = notification.getNotifier(); Property property = getUMLElement(); if ((object != null) && (property != null)) { // Handle also the case of opaque expression bodies changing if (notification.getFeature() == UMLPackage.Literals.OPAQUE_EXPRESSION__BODY) { refreshDisplay(); } } } } This API is only reliable when the notifier is known a priori to be of the 'expectedClass' type. Usually we just check whether notification.getFeature() == UMLPackage.Literals.PORT__IS_CONJUGATED The getFeatureID API is usually only employed for notifiers that aren't Objects, such as Resources and ResourceSets.

Target:
public void notifyChanged(Notification notification) { // Handle when a port is defined as conjugated if (notification.getFeature() == UMLPackage.Literals.PORT__IS_CONJUGATED) { refreshDisplay(); } else { super.notifyChanged(notification); Object object = notification.getNotifier(); Property property = getUMLElement(); if ((object != null) && (property != null)) { // Handle also the case of opaque expression bodies changing if (notification.getFeature() == UMLPackage.Literals.OPAQUE_EXPRESSION__BODY) { refreshDisplay(); } } } }
Source:
private PackWriter newPackWriter() { PackConfig pc = packConfig; if (pc == null) { pc = db != null ? new PackConfig(db) : new PackConfig(); } if (reader != null) { return new PackWriter(pc, reader); } final ObjectReader or = db.newObjectReader(); return new PackWriter(pc, or) { @Override public void close() { super.close(); START or.close(); END } }; } super.close() already closes 'or' (as does writePack). Is the idea that PackWriter would gain a boolean to disable that behavior?

Target:
private PackWriter newPackWriter() { PackConfig pc = packConfig; if (pc == null) { pc = db != null ? new PackConfig(db) : new PackConfig(); } return new PackWriter(pc, reader != null ? reader : db.newObjectReader()); }
Source:
public synchronized void clear() { for (int i = 0; i < this.fPageTable.length; i++) { START final Chunk END chunk = this.fPageTable[i]; if (chunk == null) { continue; } chunk.fCacheIndex = -1; chunk.fDatabase.checkIfChunkReleased(chunk); this.fPageTable[i] = null; } this.fTableIsFull = false; this.fPointer = 0; } What's the reasoning for making this final?

Target:
public synchronized void clear() { for (int i = 0; i < this.fPageTable.length; i++) { Chunk chunk = this.fPageTable[i]; if (chunk == null) { continue; } chunk.fCacheIndex = -1; chunk.fDatabase.checkIfChunkReleased(chunk); this.fPageTable[i] = null; } this.fTableIsFull = false; this.fPointer = 0; }
Source:
private StatusAdapter getSingleSelection() { IStructuredSelection selection = statusListViewer.getStructuredSelection(); START if (selection.size() == 1) { END return (StatusAdapter) selection.getFirstElement(); } return null; } This is not same! *single* selection will return null if there are more then one element!

Target:
private StatusAdapter getSingleSelection() { return (StatusAdapter) statusListViewer.getStructuredSelection().getFirstElement(); }
Source:
START public static END Color getSystemForegroundColor() { ColorRegistry colorRegistry = JFaceResources.getColorRegistry(); Color foreground = colorRegistry.get(JFacePreferences.INFORMATION_FOREGROUND_COLOR); if (foreground == null) { return JFaceColors.getInformationViewerForegroundColor(Display.getDefault()); } return foreground; } No need to make this public.

Target:
private static Color getSystemForegroundColor() { ColorRegistry colorRegistry = JFaceResources.getColorRegistry(); Color foreground = colorRegistry.get(JFacePreferences.INFORMATION_FOREGROUND_COLOR); if (foreground == null) { return JFaceColors.getInformationViewerForegroundColor(Display.getDefault()); } return foreground; }
Source:
private void initialize() { project = (IProject) getElement().getAdapter(IResource.class); if (project == null) { throw new RuntimeException( START TasksUiPlugin.ID_PLUGIN + ": Can not get the project of " + getElement().toString()); //$NON-NLS-1$ END } noDefaultAndApplyButton(); setDescription( Messages.ProjectTaskRepositoryPage_Select_a_task_repository_to_associate_with_this_project_below); } explicit toString() is unnecessary. Simply "+ getElement()" will accomplish the same, and will work even if getElement() happens to return null

Target:
private void initialize() { project = (IProject) getElement().getAdapter(IResource.class); if (project == null) { throw new RuntimeException( TasksUiPlugin.ID_PLUGIN + ": Can not get the project of " + getElement()); //$NON-NLS-1$ } noDefaultAndApplyButton(); setDescription( Messages.ProjectTaskRepositoryPage_Select_a_task_repository_to_associate_with_this_project_below); }
Source:
public void dispose() { super.dispose(); START fCriticalPathModule.dispose(); END } should this be on top?

Target:
public void dispose() { fCriticalPathModule.dispose(); super.dispose(); }
Source:
public void shutdown() { fShutdown = true; START Job.getJobManager().cancel(AbstractDispatchJob.class); END } This is wrong, because this will try to cancel *all possible* dispatcher jobs, not the jobs of the current dispatcher.

Target:
public void shutdown() { fShutdown = true; Job.getJobManager().cancel(this); }
Source:
public void setDisableHyperLink() { if START (!selectHyperLinkLabel.isDisposed()) END { selectHyperLinkLabel.setEnabled(false); } if (!clearHyperLinkLabel.isDisposed()) { clearHyperLinkLabel.setEnabled(false); } } Can selectHyperLinkLabel be null?

Target:
public void setDisableHyperLink() { if (selectHyperLinkLabel != null && !selectHyperLinkLabel.isDisposed()) { selectHyperLinkLabel.setEnabled(false); } if (clearHyperLinkLabel != null && !clearHyperLinkLabel.isDisposed()) { clearHyperLinkLabel.setEnabled(false); } }
Source:
public void testReadPipePosixCommandStartFailure() throws CommandFailedException { FS fs = FS.DETECTED.newInstance(); START assumeTrue(fs instanceof FS_POSIX); END FS.readPipe(fs.userHome(), new String[] { "this-command-does-not-exist" }, Charset.defaultCharset().name()); } Why do you assume here that fs should be posix? This test should also fail on a windows machine, or?

Target:
public void testReadPipePosixCommandStartFailure() throws CommandFailedException { FS fs = FS.DETECTED.newInstance(); FS.readPipe(fs.userHome(), new String[] { "this-command-does-not-exist" }, Charset.defaultCharset().name()); }
Source:
START protected IEclipseContext createContext(final Event trigger) { END final IEclipseContext staticContext = EclipseContextFactory.create("keys-staticContext"); //$NON-NLS-1$ staticContext.set(Event.class, trigger); return staticContext; } This method should be private or default as otherwise it is API addition.

Target:
private IEclipseContext createContext(final Event trigger) { final IEclipseContext staticContext = EclipseContextFactory.create("keys-staticContext"); //$NON-NLS-1$ staticContext.set(Event.class, trigger); return staticContext; }
Source:
public void stop(BundleContext context_p) throws Exception { __plugin = null; if(_adapterFactory != null) START _adapterFactory.dispose(); END super.stop(context_p); } You should also set _adaterFactory to null after dispose.

Target:
public void stop(BundleContext context_p) throws Exception { __plugin = null; if(_adapterFactory != null){ _adapterFactory.dispose(); _adapterFactory = null; } super.stop(context_p); }
Source:
public BasicSymbolProviderPreferencePage(@NonNull BasicSymbolProvider provider) { super(provider); setDescription(MessageFormat.format(Messages.BasicSymbolProviderPrefPage_description, provider.getTrace().getName())); setValid(true); START setTitle(MessageFormat.format(Messages.BasicSymbolProviderPrefPage_tabTitle, "GNU nm", provider.getTrace().getName())); //$NON-NLS-1$ END } externalize this.

Target:
public BasicSymbolProviderPreferencePage(@NonNull BasicSymbolProvider provider) { super(provider); setDescription(MessageFormat.format(Messages.BasicSymbolProviderPrefPage_description, provider.getTrace().getName())); setValid(true); setTitle(MessageFormat.format(Messages.BasicSymbolProviderPrefPage_tabTitle, provider.getTrace().getName())); }
Source:
protected boolean considerEvent(ITmfEvent event) { if (!(event instanceof CtfTmfEvent)) { return false; } Object tid = TmfTraceUtils.resolveEventAspectOfClassForEvent(event.getTrace(), LinuxTidAspect.class, event); if (!(tid START instanceof END Number)) { return false; } return true; } return tid instanceof Number;?

Target:
protected boolean considerEvent(ITmfEvent event) { if (!(event instanceof CtfTmfEvent)) { return false; } Object tid = TmfTraceUtils.resolveEventAspectOfClassForEvent(event.getTrace(), LinuxTidAspect.class, event); if (!(tid instanceof Integer)) { return false; } return true; }
Source:
public boolean appliesTo(Object selection) { EObject eo = EMFHelper.getEObject(selection); if START (eo != null && END eo instanceof Element) { return UMLRTProfileUtils.isUMLRTProfileApplied((Element) eo); } return false; } Don't need this condition (null is not an instance of any class)

Target:
public boolean appliesTo(Object selection) { EObject eo = EMFHelper.getEObject(selection); if (eo instanceof Element) { return UMLRTProfileUtils.isUMLRTProfileApplied((Element) eo); } return false; }
Source:
private void copyPathOfSelectionToClipboard(final TreeViewer viewer) { Clipboard cb = new Clipboard(viewer.getControl().getDisplay()); TextTransfer t = TextTransfer.getInstance(); String text = getTextFrom( (IStructuredSelection) viewer.getSelection()); if (text == null) { START return; END } else { cb.setContents(new Object[] { text }, new Transfer[] { t }); } cb.dispose(); } No, that doesn't dispose cb.

Target:
private void copyPathOfSelectionToClipboard(final TreeViewer viewer) { Clipboard cb = new Clipboard(viewer.getControl().getDisplay()); TextTransfer t = TextTransfer.getInstance(); String text = getTextFrom( (IStructuredSelection) viewer.getSelection()); try { if (text != null) { cb.setContents(new Object[] { text }, new Transfer[] { t }); } } finally { cb.dispose(); } }
Source:
public ViewpointSelectionCallbackWithConfimationAndDependenciesHandling() { START super(); this.askUserForDependencyActivation = true; END } Should be "this(true)".

Target:
public ViewpointSelectionCallbackWithConfimationAndDependenciesHandling() { this(true); }
Source:
private String getRepositoryName(String location) { final String[] tokens = location.split(SEPARATOR); return (location.endsWith(GIT_EXTENSION)) START ? tokens[4].substring(0, END tokens[4].length() - 4) : tokens[4].substring(0); } still you cannot be sure to have 5 tokens. you need to query that first

Target:
private String getRepositoryName(String location) { final String[] tokens = location.split(SEPARATOR); if (tokens.length >= 5) return (location.endsWith(GIT_EXTENSION)) ? tokens[4].substring(0, tokens[4].length() - 4) : tokens[4].substring(0); return null; }
Source:
public WordTemplateContentRendererHandler(OrcsApi orcsApi, Log logger) { this.orcsApi = orcsApi; this.logger = logger; START this.applicHandler = null; END } unnecessary

Target:
public WordTemplateContentRendererHandler(OrcsApi orcsApi, Log logger) { this.orcsApi = orcsApi; this.logger = logger; }
Source:
public void testDynamicImport() throws Exception { File testData = getTestData("dymamicImport", "testData/dynamicImport"); IInstallableUnit iu = BundlesAction.createBundleIU(BundlesAction.createBundleDescription(testData), null, new PublisherInfo()); Collection<IRequirement> requirements = iu.getRequirements(); for (IRequirement req : requirements) START System.out.println("------> " + req); END verifyRequirement(requirements, TESTDYN_REQ_EE_FILTER, 0, 1, true); assertEquals(1, requirements.size()); } Please remove this debugging sysout.

Target:
public void testDynamicImport() throws Exception { File testData = getTestData("dymamicImport", "testData/dynamicImport"); IInstallableUnit iu = BundlesAction.createBundleIU(BundlesAction.createBundleDescription(testData), null, new PublisherInfo()); Collection<IRequirement> requirements = iu.getRequirements(); verifyRequirement(requirements, TESTDYN_REQ_EE_FILTER, 0, 1, true); assertEquals(1, requirements.size()); }
Source:
public Collection<CallStackSeries> getCallStackSeries() { Collection<CallStackSeries> callstacks = fCallStacks; if (callstacks == null) { ITmfStateSystem ss = getStateSystem(); if (ss == null) { return START Objects.requireNonNull(Collections.emptyList()); END } callstacks = Collections.singleton(new CallStackSeries(ss, PATTERNS, 0, "", getHostId(), new CallStackSeries.AttributeValueThreadResolver(1))); //$NON-NLS-1$ fCallStacks = callstacks; } return callstacks; } Not required, it's annotated

Target:
public Collection<CallStackSeries> getCallStackSeries() { Collection<CallStackSeries> callstacks = fCallStacks; if (callstacks == null) { ITmfStateSystem ss = getStateSystem(); if (ss == null) { return Collections.emptyList(); } callstacks = Collections.singleton(new CallStackSeries(ss, PATTERNS, 0, "", getHostId(), new CallStackSeries.AttributeValueThreadResolver(1))); //$NON-NLS-1$ fCallStacks = callstacks; } return callstacks; }
Source:
protected WorkbenchJob doCreateRefreshJob() { WorkbenchJob job = super.doCreateRefreshJob(); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { CheckboxTreeViewer checkboxTreeViewer = getCheckboxTreeViewer(); if (checkboxTreeViewer.getTree().isDisposed()) { return; } checkboxTreeViewer.expandAll(); START checkboxTreeViewer.setCheckedElements(getCheckedElements()); END maintainAllCheckIntegrity(); } }); return job; } I'm not sure why the base class does these two actions, but in any case, it's not necessary here because the base class's JobChangeAdapter will do it anyways.

Target:
protected WorkbenchJob doCreateRefreshJob() { WorkbenchJob job = super.doCreateRefreshJob(); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { maintainAllCheckIntegrity(); } }); return job; }
Source:
public void testMigrationIsNeededOnData() { Version migrationVersion = new SnapBackDistantLabelsMigrationParticipant().getMigrationVersion(); // Check that the migration of the session resource is needed. Version loadedVersion = checkRepresentationFileMigrationStatus(URI.createPlatformResourceURI(SiriusTestCase.TEMPORARY_PROJECT_NAME + "/" + SESSION_RESOURCE_NAME, true), true); assertTrue("The migration must be required on test data.", START loadedVersion == null || END migrationVersion.compareTo(loadedVersion) > 0); } We should not have a null loaded version. If it is the case we should rather update this test

Target:
public void testMigrationIsNeededOnData() { Version migrationVersion = new SnapBackDistantLabelsMigrationParticipant().getMigrationVersion(); // Check that the migration of the session resource is needed. Version loadedVersion = checkRepresentationFileMigrationStatus(URI.createPlatformResourceURI(SiriusTestCase.TEMPORARY_PROJECT_NAME + "/" + SESSION_RESOURCE_NAME, true), true); assertTrue("The migration must be required on test data.", migrationVersion.compareTo(loadedVersion) > 0); }
Source:
private static boolean validateTimeRange() { boolean isEmpty = fStartTimeRangeText.getText().isEmpty() || fEndTimeRangeText.getText().isEmpty(); return parseTimeRange() && fStartTimestamp.compareTo(fEndTimestamp) <= 0 && START !isEmpty; END } should be first in the line, so that it returns if isEmpty, without trying to parse

Target:
private boolean validateTimeRange() { boolean isEmpty = fStartTimeRangeText.getText().isEmpty() || fEndTimeRangeText.getText().isEmpty(); return !isEmpty && parseTimeRange() && fStartTimestamp.compareTo(fEndTimestamp) <= 0; }
Source:
public @Nullable T resolve(ITmfEvent event) { for (ITmfEventAspect<?> aspect : fAspects) { Object resolve = aspect.resolve(event); if (resolve != null && START resolve.getClass().isAssignableFrom(fClazz.getClass())) { END return (T) resolve; } } return null; } shouldn't this filter go in the constructor?

Target:
public @Nullable T resolve(ITmfEvent event) { for (ITmfEventAspect<?> aspect : fAspects) { Object resolve = aspect.resolve(event); if (resolve != null) { return (T) resolve; } } return null; }
Source:
public static Iterable<ITmfEventAspect<?>> getEventAspects(ITmfTrace trace, Class<? extends ITmfEventAspect<?>> aspectClass) { START return StreamSupport.stream(Iterables.concat(trace.getEventAspects(), EXTRA_ASPECTS).spliterator(), false) .filter(aspect -> aspectClass.isAssignableFrom(aspect.getClass())) .collect(Collectors.toList()); END } Iterables.filter(Iterables.concat(bob), isAssignabe)). use iterables methods on iterables?

Target:
public static Iterable<ITmfEventAspect<?>> getEventAspects(ITmfTrace trace, Class<? extends ITmfEventAspect<?>> aspectClass) { return Iterables.filter(Iterables.concat(trace.getEventAspects(), EXTRA_ASPECTS), aspect -> aspectClass.isAssignableFrom(aspect.getClass())); }
Source:
public int hashCode() { final int prime = 31; START int result = 1; END result = prime * result + ((resource == null) ? 0 : resource.hashCode()); return result; } I not see the link between the change of hashCode and equals, and the feature of this issue... Same remarks for all following items.

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((parent == null) ? 0 : parent.hashCode()); result = prime * result + ((resource == null) ? 0 : resource.hashCode()); return result; }
Source:
START int computeWidthDifference (GtkRequisition requisition, int width) { END int diffwidth; diffwidth = requisition.width - width; if (width - diffwidth < 0) { return requisition.width; } else { return width; } } Suggestion: Reduce this to a 1 liner: return (requisition.width - width) < 0 ? requisition.width : width;

Target:
int computeWidthDifference (GtkRequisition requisition, int width) { return (requisition.width - width) < 0 ? requisition.width : width; }
Source:
START private void resetData() { END for (CounterAnalysis analysis : fModules) { ITmfStateSystem ss = analysis.getStateSystem(); if (ss == null) { continue; } for (Integer quark : fQuarks) { deleteSeries(createSeriesName(ss, quark)); } } fQuarks.clear(); } In updateChart(), the collection fModules is updated first, then this method is called. So you don't have anymore the old modules to be able to recreate the old series that need to be deleted. How about getting the series set directly from the SWTChart and delete them one by one using their own id provided by ISeries?

Target:
private void resetData() { for (CounterAnalysis analysis : fModules) { ITmfStateSystem ss = analysis.getStateSystem(); if (ss == null) { continue; } for (Integer quark : fQuarks) { deleteSeries(createSeriesName(ss, quark)); } } fQuarks.clear(); fModules.clear(); }
Source:
public void updateChart(@NonNull Set<@NonNull Integer> quarks) { cancelUpdate(); resetData(); START fQuarks.addAll(quarks); END updateContent(); } fQuarks = quarks?

Target:
public void updateChart(@NonNull Set<@NonNull Integer> quarks) { cancelUpdate(); resetData(); fQuarks = quarks; updateContent(); }