auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, true); START Button button = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); END button.setEnabled(false); } Both buttons are marked as defaultButton, make up your mind ;) Actually, setting a default button makes that button execute when you press ENTER. So this prevents the 'root path' text in the RemoteResourceBrowserWidget to execute its selection listener, and therefore a user cannot manually type in a path and have the tree update to the typed-in root path. So perhaps they should all be false?

Target:
protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); Button button = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, false); button.setEnabled(false); }
Source:
protected IDocument acquireDocument(IProgressMonitor pm) throws CoreException { SubMonitor subMonitor= SubMonitor.convert(pm, 2); START fCUnit.becomeWorkingCopy(subMonitor.newChild(1)); END Assert.isTrue(fCUnit.isWorkingCopy(), fCUnit.toString()); return super.acquireDocument(subMonitor.newChild(1)); } Change from subMonitor.newChild(...) to subMonitor.split(...)

Target:
protected IDocument acquireDocument(IProgressMonitor pm) throws CoreException { SubMonitor subMonitor= SubMonitor.convert(pm, 2); fCUnit.becomeWorkingCopy(subMonitor.split(1)); Assert.isTrue(fCUnit.isWorkingCopy(), fCUnit.toString()); return super.acquireDocument(subMonitor.split(1)); }
Source:
void moveAllEventsTo (Synchronizer toReceiveTheEvents) { RunnableLock[] oldMessages; int oldMessageCount; synchronized (messageLock) { oldMessages = messages; oldMessageCount = messageCount; messageCount = 0; } START toReceiveTheEvents.addFirst(oldMessages, oldMessageCount); END } what worries me is that the oldMessages is left unprotected between the calls and in theory could be modified.

Target:
void moveAllEventsTo (Synchronizer toReceiveTheEvents) { RunnableLock[] oldMessages; int oldMessageCount; synchronized (messageLock) { oldMessages = messages; messages = null; oldMessageCount = messageCount; messageCount = 0; } toReceiveTheEvents.addFirst(oldMessages, oldMessageCount); }
Source:
private String getColumnText(Object element, int columnIndex) { TaskReview reviewContainer = (TaskReview) element; switch (columnIndex) { case 0: return reviewContainer.getSummary(); case 1: START return reviewContainer.getCrString(); END case 2: return reviewContainer.getVString(); case 3: return reviewContainer.getIncomingChanges(); default: return ""; } } If this is the only reason we have a `getCrString` it'll be user to just store the value as an integer internally (it's true representation) and make a call out to Integer.toString to create the representation.

Target:
private String getColumnText(Object element, int columnIndex) { TaskReview reviewContainer = (TaskReview) element; switch (columnIndex) { case 0: return reviewContainer.getSummary(); case 3: return reviewContainer.getIncomingChanges(); default: return ""; } }
Source:
public TaskReview(String summary, String cr, String v, String incomingChanges) { START super(); END this.summary = summary; this.cr = cr; this.v = v; this.incomingChanges = incomingChanges; } Why call `super` if there is nothing above it? Maybe there's a best practice I missed the memo on.

Target:
public TaskReview(String summary, String cr, String v, String incomingChanges) { this.summary = summary; this.cr = cr; this.v = v; this.incomingChanges = incomingChanges; }
Source:
private void expandSection(final FormToolkit toolkit, Section section) { reviewsComposite = toolkit.createComposite(section); START section.setClient(reviewsComposite); END reviewsComposite.setLayout(EditorUtil.createSectionClientLayout()); getTaskEditorPage().registerDefaultDropListener(section); createReviewsTable(toolkit, reviewsComposite); toolkit.paintBordersFor(reviewsComposite); section.setClient(reviewsComposite); } I see a duplicate `setClient` call just below. Are both strictly necessary?

Target:
private void expandSection(final FormToolkit toolkit, Section section) { reviewsComposite = toolkit.createComposite(section); section.setClient(reviewsComposite); reviewsComposite.setLayout(EditorUtil.createSectionClientLayout()); getTaskEditorPage().registerDefaultDropListener(section); createReviewsTable(toolkit, reviewsComposite); toolkit.paintBordersFor(reviewsComposite); }
Source:
private static void assertBufferStringAndVariables(String expected, TemplateBuffer buffer) { assertEquals(expected, buffer.getString()); for (TemplateVariable v : buffer.getVariables()) { START assertEquals(true, v.isResolved()); END assertEquals(true, v.isUnambiguous()); } } Why not using directly assertTrue?

Target:
private static void assertBufferStringAndVariables(String expected, TemplateBuffer buffer) { assertEquals(expected, buffer.getString()); for (TemplateVariable v : buffer.getVariables()) { assertTrue(v.isResolved()); assertTrue(v.isUnambiguous()); } }
Source:
protected String getFileName() { final String fileText = getFileText(); String[] extensions = getFileExtensions(); for (int i = 0; i < extensions.length; ++i) { String extension = extensions[i]; if (extension.isEmpty() || (!extension.isEmpty() && fileText.endsWith("." + extension))) { //$NON-NLS-1$ return fileText; } } START return fileText + "." + extensions[0]; //$NON-NLS-1$ END } Should the empty extension be rather handled here? Just to keep that condition simpler.

Target:
protected String getFileName() { final String fileText = getFileText(); String[] extensions = getFileExtensions(); for (int i = 0; i < extensions.length; ++i) { String extension = extensions[i]; if (!extension.isEmpty() && fileText.endsWith("." + extension)) { //$NON-NLS-1$ return fileText; } } if (extensions[0].isEmpty()) { return fileText; } return fileText + "." + extensions[0]; //$NON-NLS-1$ }
Source:
public void setServerContent(Map<String, String> serverContent) { START Preconditions.checkNotNull(serverContent); END this.serverContent = serverContent; } I'd prefer to use static imports for Preconditions, for improved readability and consistency. What do you think?

Target:
public void setServerContent(Map<String, String> serverContent) { checkNotNull(serverContent); this.serverContent = serverContent; }
Source:
public void testRgb() { START E4ThemeColor e4ThemeColor = new E4ThemeColor(); END RGB rgb = E4ThemeColor.getRGBFromCssString("rgb(238, 238, 238)"); assertEquals(new RGB(238, 238, 238), rgb); } Seems like there's no reason to instantiate E4ThemeColor. In fact, can you add a private constructor to E4ThemeColor?

Target:
public void testRgb() { RGB rgb = E4ThemeColor.getRGBFromCssString("rgb(238, 238, 238)"); //$NON-NLS-1$ assertEquals(new RGB(238, 238, 238), rgb); }
Source:
int nextSpan(int distanceFromTip) { if (distanceFromTip < 0) START throw new IllegalArgumentException(); END // Commits more toward the start will have more bitmaps. if (distanceFromTip <= recentCommitCount) return recentCommitSpan; int next = Math.min(distanceFromTip - recentCommitCount, distantCommitSpan); return Math.max(next, recentCommitSpan); } (nit) braces around one-line if body

Target:
int nextSpan(int distanceFromTip) { if (distanceFromTip < 0) { throw new IllegalArgumentException(); } // Commits more toward the start will have more bitmaps. if (distanceFromTip <= recentCommitCount) { return recentCommitSpan; } int next = Math.min(distanceFromTip - recentCommitCount, distantCommitSpan); return Math.max(next, recentCommitSpan); }
Source:
private int extractWorkFromLine(String line) { int pos1 = line.indexOf(DLTK_TOTAL_WORK_START); int pos2 = line.indexOf(DLTK_TOTAL_WORK_END); if (pos1 != -1 && pos2 != -1) { String totalWork = line.substring(pos1 + DLTK_TOTAL_WORK_START.length(), pos2); START int intValue = Integer.valueOf(totalWork).intValue(); END if (intValue == -1) { return IProgressMonitor.UNKNOWN; } return intValue; } return NOT_WORK_COUNT; } parseInt()

Target:
private int extractWorkFromLine(String line) { int pos1 = line.indexOf(DLTK_TOTAL_WORK_START); int pos2 = line.indexOf(DLTK_TOTAL_WORK_END); if (pos1 != -1 && pos2 != -1) { String totalWork = line.substring(pos1 + DLTK_TOTAL_WORK_START.length(), pos2); int intValue = Integer.parseInt(totalWork); if (intValue == -1) { return IProgressMonitor.UNKNOWN; } return intValue; } return NOT_WORK_COUNT; }
Source:
private void traceContainers(String action, long start) { Long delta = Long.valueOf(System.currentTimeMillis() - start); START Long length = Long.valueOf(getContainersFile().length()); END String pattern = "{0} {1} bytes in containers.dat in {2}ms"; //$NON-NLS-1$ String message = NLS.bind(pattern, new Object[] { action, length, delta }); System.out.println(message); } I would suggest "long" type here and let autoboxing work later

Target:
private void traceContainers(String action, long start) { Long delta = System.currentTimeMillis() - start; Long length = getContainersFile().length(); String pattern = "{0} {1} bytes in containers.dat in {2}ms"; //$NON-NLS-1$ String message = NLS.bind(pattern, new Object[] { action, length, delta }); System.out.println(message); }
Source:
public CellEditor createPropertyEditor(Composite parent) { CellEditor cellEditor = null; if (object instanceof EObject && getPermissionAuthority().canEditInstance((EObject) object)) { cellEditor = START super.createPropertyEditor(parent); END } return cellEditor; } why not call super.createPropertyEditor(parent); if the object is not a EObject? I think this is a bug.

Target:
public CellEditor createPropertyEditor(Composite parent) { CellEditor cellEditor = null; if (!(object instanceof EObject) || getPermissionAuthority() != null && getPermissionAuthority().canEditInstance((EObject) object)) { cellEditor = super.createPropertyEditor(parent); } return cellEditor; }
Source:
protected IPapyrusMarker getMarkerA() { START if (markerA == null) { END // create new marker for node A markerA = new NodeAMarker(getView()); } return markerA; } 'null' must be the first operande

Target:
protected IPapyrusMarker getMarkerA() { if (null == markerA) { // create new marker for node A markerA = new NodeAMarker(getView()); } return markerA; }
Source:
public boolean provides(final IOperation operation) { boolean provide = false; // it needs to be a CreateDecoratorsOperation if (operation instanceof CreateDecoratorsOperation) { final IDecoratorTarget decoratorTarget = ((CreateDecoratorsOperation) operation).getDecoratorTarget(); final View view = decoratorTarget.getAdapter(View.class); // Test if the decoratorTarget element is a CallBehavoirAction START if (view != null && ActivityDiagramEditPart.MODEL_ID.equals(UMLVisualIDRegistry.getModelID(view)) && view.getElement() instanceof CallBehaviorAction) { END provide = true; } else { provide = false; } } return provide; } 'null' must be first operande

Target:
public boolean provides(final IOperation operation) { boolean provide = false; // it needs to be a CreateDecoratorsOperation if (operation instanceof CreateDecoratorsOperation) { final IDecoratorTarget decoratorTarget = ((CreateDecoratorsOperation) operation).getDecoratorTarget(); final View view = decoratorTarget.getAdapter(View.class); // Test if the decoratorTarget element is a CallBehavoirAction if (null != view && ActivityDiagramEditPart.MODEL_ID.equals(UMLVisualIDRegistry.getModelID(view)) && view.getElement() instanceof CallBehaviorAction) { provide = true; } else { provide = false; } } return provide; }
Source:
public void launchTargetsChanged() { START targetSelector.refresh(); END } null check here now

Target:
public void launchTargetsChanged() { if (targetSelector!=null){ targetSelector.refresh(); } }
Source:
private static void loadRulesFromFile(IgnoreNode r, File exclude) throws FileNotFoundException, IOException { START try { END if (FS.DETECTED.exists(exclude)) { FileInputStream in = new FileInputStream(exclude); try { r.parse(in); } finally { in.close(); } } } catch (AccessControlException ignored) { } } how is this related to ignoring non-accessibility of ~/.gitconfig ?

Target:
private static void loadRulesFromFile(IgnoreNode r, File exclude) throws FileNotFoundException, IOException { if (FS.DETECTED.exists(exclude)) { FileInputStream in = new FileInputStream(exclude); try { r.parse(in); } finally { in.close(); } } }
Source:
public FileBasedConfig openUserConfig(Config parent, FS fs) { final File home = fs.userHome(); File userConfig = new File(home, ".gitconfig"); try { userConfig.canRead(); } catch (AccessControlException e) { START return new FileBasedConfig(null, fs) { END public void load() { // empty, do not load } public boolean isOutdated() { // regular class would bomb here return false; } }; } return new FileBasedConfig(parent, userConfig, fs); //$NON-NLS-1$ } Does this lose the parent Config?

Target:
public FileBasedConfig openUserConfig(Config parent, FS fs) { final File home = fs.userHome(); File userConfig = new File(home, ".gitconfig"); try { userConfig.canRead(); } catch (AccessControlException e) { return new FileBasedConfig(parent, null, fs) { public void load() { // empty, do not load } public boolean isOutdated() { // regular class would bomb here return false; } }; } return new FileBasedConfig(parent, userConfig, fs); //$NON-NLS-1$ }
Source:
final public List<IDecoration> setDecorationsNode(List<IPapyrusDecoration> pDecorations, int margin, boolean isVolatile) { START decorations = new BasicEList<IDecoration>(); END for (IPapyrusDecoration pDecoration : pDecorations) { Image image = addDecorationNode(pDecoration, margin, isVolatile); if (image != null) { margin += image.getBounds().width; } } // this.pDecorations = pDecorations; return decorations; } Now that the list is always created during instantiation, a simple clear() should be sufficient (Rather than creating a new list each time)

Target:
final public List<IDecoration> setDecorationsNode(List<IPapyrusDecoration> pDecorations, int margin, boolean isVolatile) { decorations.clear(); for (IPapyrusDecoration pDecoration : pDecorations) { Image image = addDecorationNode(pDecoration, margin, isVolatile); if (image != null) { margin += image.getBounds().width; } } // this.pDecorations = pDecorations; return decorations; }
Source:
public ITimeGraphEntry @Nullable getChildren(@Nullable Object parentElement) { if (parentElement instanceof CriticalPathEntry) { START List<@NonNull ? extends ITimeGraphEntry> children = ((CriticalPathEntry) parentElement).getChildren(); END return children.toArray(new TimeGraphEntry[children.size()]); } return null; } This does not change anything? However if we change the declaration in ITimeGraphEntry to List<@NonNull ? extends ITimeGraphEntry> getChildren(); Then the returned getChildren() here fits the required declaration, and no more warning. (ok I just noticed you also changed this, ok good!)

Target:
public ITimeGraphEntry @Nullable getChildren(@Nullable Object parentElement) { if (parentElement instanceof CriticalPathEntry) { List<? extends ITimeGraphEntry> children = ((CriticalPathEntry) parentElement).getChildren(); return children.toArray(new TimeGraphEntry[children.size()]); } return null; }
Source:
START public Iterable<@NonNull IEventDeclaration> getEventDeclarations() { END return checkNotNull(ImmutableList.copyOf(fStreamInput.getStream().getEventDeclarations())); } redundant, class is @NNBD

Target:
public Iterable<IEventDeclaration> getEventDeclarations() { return checkNotNull(ImmutableList.copyOf(fStreamInput.getStream().getEventDeclarations())); }
Source:
START public Iterable<@NonNull ITmfEventAspect> getEventAspects() { END return CTF_ASPECTS; } We could annotate the base method in TmfTrace directly.

Target:
public Iterable<ITmfEventAspect> getEventAspects() { return CTF_ASPECTS; }
Source:
START public @NonNull String getName() { END return fTypeId; } super-method only

Target:
public String getName() { return fTypeId; }
Source:
START public static <@NonNull T> Iterable<@NonNull T> getAnalysisModulesOfClass(ITmfTrace trace, Class<T> moduleClass) { END Iterable<@NonNull IAnalysisModule> analysisModules = trace.getAnalysisModules(); Set<T> modules = new HashSet<>(); for (IAnalysisModule module : analysisModules) { if (moduleClass.isAssignableFrom(module.getClass())) { modules.add(moduleClass.cast(module)); } } return modules; } don't annotate the first part

Target:
public static <T> Iterable<@NonNull T> getAnalysisModulesOfClass(ITmfTrace trace, Class<T> moduleClass) { Iterable<IAnalysisModule> analysisModules = trace.getAnalysisModules(); Set<@NonNull T> modules = new HashSet<>(); for (IAnalysisModule module : analysisModules) { if (moduleClass.isAssignableFrom(module.getClass())) { modules.add(moduleClass.cast(module)); } } return modules; }
Source:
public IKernelAnalysisEventLayout getEventLayout(ITmfTrace trace) { START IKernelAnalysisEventLayout layout = LttngEventLayout.getInstance(); END if (trace instanceof LttngKernelTrace) { layout = ((LttngKernelTrace) trace).getKernelEventLayout(); } return layout; } You don't need this variable: if (trace instanceof LttngKernelTrace) { return ((LttngKernelTrace) trace).getKernelEventLayout(); } return LttngEventLayout.getInstance();

Target:
public IKernelAnalysisEventLayout getEventLayout(ITmfTrace trace) { if (trace instanceof LttngKernelTrace) { return ((LttngKernelTrace) trace).getKernelEventLayout(); } return LttngEventLayout.getInstance(); }
Source:
public START long END getAtsSearchUuid() { if (iWorldEditorProvider instanceof WorldEditorParameterSearchItemProvider) { WorldSearchItem worldSearchItem = ((WorldEditorParameterSearchItemProvider) iWorldEditorProvider).getWorldSearchItem(); if (worldSearchItem instanceof AtsSearchWorkflowSearchItem) { return ((AtsSearchWorkflowSearchItem) worldSearchItem).getSearchUuid(); } } return 0L; } long or Long in this case? There's been discussion making this consistent in our code base. Is it appropriate to make that change here and now?

Target:
public Long getAtsSearchUuid() { if (iWorldEditorProvider instanceof WorldEditorParameterSearchItemProvider) { WorldSearchItem worldSearchItem = ((WorldEditorParameterSearchItemProvider) iWorldEditorProvider).getWorldSearchItem(); if (worldSearchItem instanceof AtsSearchWorkflowSearchItem) { return ((AtsSearchWorkflowSearchItem) worldSearchItem).getSearchUuid(); } } return 0L; }
Source:
private boolean isArtifact(ITask task) { // If it has associated task and has no context, scheduled date, or due date; artifact // TODO: This will require work on Blaine's part.. pending boolean hasAssosciatedTask = true; boolean hasContext = TasksUiPlugin.getContextStore().hasContext(task); // Two kludgy options here... // A) Cast to AbstractTask; do a direct comparison... but requires knowledge of the "concrete implementation" // B) Seems like we could delegate out to TaskActivityManager (better option?) // TODO: Figure out the best course of action for this; using the kludge for now (since I know it'l be replaced // and it'll give me a push to actually come back) boolean hasScheduledDate = false; AbstractTask abstractTask = (AbstractTask) task; if (abstractTask != null) { hasScheduledDate = abstractTask.getScheduledForDate() != null; } boolean hasDueDate = task.getDueDate() != null; START return hasAssosciatedTask && !(hasAssosciatedTask || hasScheduledDate || hasDueDate); END } The second hasAssosciatedTask should be hasContext?

Target:
private boolean isArtifact(ITask task) { // If it has associated task and has no context, scheduled date, or due date; artifact // TODO: This will require work on Blaine's part.. pending boolean hasAssosciatedTask = true; boolean hasContext = TasksUiPlugin.getContextStore().hasContext(task); boolean hasScheduledDate = false; if (task instanceof AbstractTask) { AbstractTask abstractTask = (AbstractTask) task; hasScheduledDate = abstractTask.getScheduledForDate() != null; } boolean hasDueDate = task.getDueDate() != null; return hasAssosciatedTask && !(hasContext || hasScheduledDate || hasDueDate); }
Source:
public void setToolTipText(ILaunchTarget target) { String text = Messages.TargetSelector_ToolTipPrefix + ": " + targetManager.getStatus(target).getMessage(); //$NON-NLS-1$ setToolTipText(text); START System.out.println(text); END } debug print

Target:
public void setToolTipText(ILaunchTarget target) { String text = Messages.TargetSelector_ToolTipPrefix + ": " + targetManager.getStatus(target).getMessage(); //$NON-NLS-1$ setToolTipText(text); }
Source:
public static boolean needFigureChange(final WorkspaceImage bundledImage, IWorkspaceImageFigure figure) { boolean result = false; String workspacePath = bundledImage.getWorkspacePath(); if (StringUtil.isEmpty(workspacePath)) { START if (!(figure instanceof WorkspaceImageFigure)) { result = true; } END } else if (WorkspaceImageFigure.isSvgImage(workspacePath)) { if (!(figure instanceof SVGWorkspaceImageFigure)) { result = true; } } else if (!(figure instanceof WorkspaceImageFigure)) { result = true; } return result; } We should simplify this by replacing the if(x){result = true;} by result = x;

Target:
public static boolean needFigureChange(final WorkspaceImage bundledImage, IWorkspaceImageFigure figure) { boolean result = false; String workspacePath = bundledImage.getWorkspacePath(); if (!StringUtil.isEmpty(workspacePath) && WorkspaceImageFigure.isSvgImage(workspacePath)) { result = !(figure instanceof SVGWorkspaceImageFigure); } else { result = !(figure instanceof WorkspaceImageFigure); } return result; }
Source:
protected IStatus run(IProgressMonitor monitor) { START ISourceModule module = null; END while ((module = modules.poll()) != null) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } processModule(module, buildType, state); } return Status.OK_STATUS; } initial null seems not needed. Probably can be a for () loop :) for (ISourceModule module; (module = modules.poll()) != null;) { ... }

Target:
protected IStatus run(IProgressMonitor monitor) { for (ISourceModule module; (module = modules.poll()) != null;) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } processModule(module, buildType, state); } return Status.OK_STATUS; }
Source:
public IBorderItemLocator getNewBorderItemLocator(IFigure mainFigure) { START ParameterPositionLocator locator = new ParameterPositionLocator(mainFigure, PositionConstants.NONE); return locator; END } return directly the value (Sonar rule)

Target:
public IBorderItemLocator getNewBorderItemLocator(IFigure mainFigure) { return new ParameterPositionLocator(mainFigure, PositionConstants.NONE); }
Source:
public void testReviewArtifactIsFiltered() { ITask task = mock(ITask.class); when(task.getAttribute("ARTIFACT")).thenReturn("true"); TaskReviewArtifactFilter filter = new TaskReviewArtifactFilter(); boolean wasFiltered = !filter.select(null, task); START Assert.assertTrue(wasFiltered); END } use static import for Assert.* methods.

Target:
public void testReviewArtifactIsFiltered() { ITask task = mock(ITask.class); when(task.getAttribute("ARTIFACT")).thenReturn("true"); TaskReviewArtifactFilter filter = new TaskReviewArtifactFilter(); boolean wasFiltered = !filter.select(null, task); assertTrue(wasFiltered); }
Source:
public long getModificationDate() { START if (getResource().isAccessible()) { END return super.getModificationDate(); } return timestamp; } why do we need this ? The type says it's a non-workspace typed element ... I'd assume that instances which are resources are rather of the super-class type

Target:
public long getModificationDate() { return timestamp; }
Source:
public boolean isSynchronized() { START if (getResource().isAccessible()) { END return super.isSynchronized(); } return path.toFile().lastModified() == timestamp; } why do we need this ? The type says it's a non-workspace typed element ... I'd assume that instances which are resources are rather of the super-class type

Target:
public boolean isSynchronized() { return path.toFile().lastModified() == timestamp; }
Source:
private Repository getRepository(IFileBuffer buffer) { IPath location = getPath(buffer); if (location != null) { return START org.eclipse.egit.core.Activator.getDefault() END .getRepositoryCache().getRepository(location); } return null; } Nit: package can be removed; Activator is already imported.

Target:
private Repository getRepository(IFileBuffer buffer) { IPath location = getPath(buffer); if (location != null) { return Activator.getDefault().getRepositoryCache() .getRepository(location); } return null; }
Source:
public String getBranch() throws IOException { String name = getFullBranch(); if (name != null) return shortenRefName(name); START return name; END } return null to make this more explicit ?

Target:
public String getBranch() throws IOException { String name = getFullBranch(); if (name != null) return shortenRefName(name); return null; }
Source:
private void initRevPool(boolean reverse) { if (queue != null) throw new IllegalStateException(); if (revPool != null) revPool.close(); if (reverse) revPool = new ReverseWalk(getRepository()); else revPool = new RevWalk(getRepository()); SEEN = revPool.newFlag("SEEN"); //$NON-NLS-1$ reader = revPool.getObjectReader(); START treeWalk = new TreeWalk(getRepository(), reader); END treeWalk.setRecursive(true); } is this change needed?

Target:
private void initRevPool(boolean reverse) { if (queue != null) throw new IllegalStateException(); if (revPool != null) revPool.close(); if (reverse) revPool = new ReverseWalk(getRepository()); else revPool = new RevWalk(getRepository()); SEEN = revPool.newFlag("SEEN"); //$NON-NLS-1$ reader = revPool.getObjectReader(); treeWalk = new TreeWalk(reader); treeWalk.setRecursive(true); }
Source:
InCoreMerger(final Repository local) { super(local); START tw = new NameConflictTreeWalk(local, reader); END cache = DirCache.newInCore(); } The incore merger works in memory without a working tree. Does he need attribute handling?

Target:
InCoreMerger(final Repository local) { super(local); tw = new NameConflictTreeWalk(reader); cache = DirCache.newInCore(); }
Source:
public int getKeyBinding(int key) { checkWidget(); Integer action = START keyActionMap.get(new Integer(key)); END return action == null ? SWT.NULL : action.intValue(); } Revert ?

Target:
public int getKeyBinding(int key) { checkWidget(); Integer action = keyActionMap.get(key); return action == null ? SWT.NULL : action.intValue(); }
Source:
public static int resolveTextDirection (String text) { START return 0; END } Suggest we replace with: return SWT.NONE;

Target:
public static int resolveTextDirection (String text) { return SWT.NONE; }
Source:
protected int getSpecificHeaderSize() { int maxChildren = getConfig().getMaxChildren(); int specificSize = SIZE_INT /* 1x int (extension node) */ + SIZE_INT /* 1x int (nbChildren) */ /* MAX_NB * int ('children' table) */ + SIZE_INT * maxChildren /* MAX_NB * Timevalue ('childStart' table) */ + SIZE_LONG * maxChildren /* MAX_NB * Timevalue ('childEnd' table) */ + SIZE_LONG * maxChildren /* MAX_NB * Timevalue ('childMin' table) */ START + SIZE_INT * maxChildren END /* MAX_NB * Timevalue ('childMax' table) */ + SIZE_INT * maxChildren; return specificSize; } What are those 2 ints? I don't see them written to the header

Target:
protected int getSpecificHeaderSize() { int maxChildren = getConfig().getMaxChildren(); int specificSize = SIZE_INT /* 1x int (extension node) */ + SIZE_INT /* 1x int (nbChildren) */ /* MAX_NB * int ('children' table) */ + SIZE_INT * maxChildren /* MAX_NB * Timevalue ('childStart' table) */ + SIZE_LONG * maxChildren /* MAX_NB * Timevalue ('childEnd' table) */ + SIZE_LONG * maxChildren; return specificSize; }
Source:
public int setCloseTime(int childSequenceNumber, long endTime) { int index = -1; for (int i = 0; i < nbChildren; i++) { if (childSequenceNumber == this.children[i]) { childEnd[i] = endTime; START index = i; END } } return index; } return i; Or break; No need to continue the loop

Target:
public int setCloseTime(int childSequenceNumber, long endTime) { for (int i = 0; i < nbChildren; i++) { if (childSequenceNumber == this.children[i]) { childEnd[i] = endTime; return i; } } return -1; }
Source:
public List<Integer> getIntersectingChildren(long time) { List<Integer> START intersectingChildren = END new LinkedList<>(); for (int i = 0; i < nbChildren; i++) { if (time >= childStart[i] && time <= childEnd[i]) { intersectingChildren.add(children[i]); } } return intersectingChildren; } This might be better as an array list. Faster iteration, and such.

Target:
public List<Integer> getIntersectingChildren(long time) { List<Integer> intersectingChildren = new ArrayList<>(); for (int i = 0; i < nbChildren; i++) { if (time >= childStart[i] && time <= childEnd[i]) { intersectingChildren.add(children[i]); } } return intersectingChildren; }
Source:
public int setCloseTime(int childSequenceNumber, long endTime) { for (int i = 0; i < nbChildren; i++) { START if (childSequenceNumber == this.children[i]) { END childEnd[i] = endTime; return i; } } return -1; } no need for the "this"

Target:
public int setCloseTime(int childSequenceNumber, long endTime) { for (int i = 0; i < nbChildren; i++) { if (childSequenceNumber == children[i]) { childEnd[i] = endTime; return i; } } return -1; }
Source:
public LooseRef peel(ObjectIdRef newLeaf) { ObjectId peeledObjectId = newLeaf.getPeeledObjectId(); ObjectId objectId = getObjectId(); START assert objectId != null; END if (peeledObjectId != null) { return new LoosePeeledTag(snapShot, getName(), objectId, peeledObjectId); } else { return new LooseNonTag(snapShot, getName(), objectId); } } An alternative way to phrase this would be to make ObjectIdRef.Unpeeled.getObjectId return non-null: @NonNull @Override public ObjectId getObjectId() { ObjectId id = super.getObjectId(); assert id != null; // checked in constructor return id; }

Target:
public LooseRef peel(ObjectIdRef newLeaf) { ObjectId peeledObjectId = newLeaf.getPeeledObjectId(); ObjectId objectId = getObjectId(); if (peeledObjectId != null) { return new LoosePeeledTag(snapShot, getName(), objectId, peeledObjectId); } else { return new LooseNonTag(snapShot, getName(), objectId); } }
Source:
private static <T> T getService(Class<T> serviceClass) { final Bundle bundle = FrameworkUtil.getBundle(ViewModelMigratorUtil.class); final BundleContext bundleContext = bundle.getBundleContext(); final ServiceReference<T> serviceReference = bundleContext.getServiceReference(serviceClass); if (serviceReference == null) { return null; } START final Object service = bundleContext.getService(serviceReference); END bundleContext.ungetService(serviceReference); return serviceClass.cast(service); } this should already be T so no cast necessary later

Target:
private static <T> T getService(Class<T> serviceClass) { final Bundle bundle = FrameworkUtil.getBundle(ViewModelMigratorUtil.class); final BundleContext bundleContext = bundle.getBundleContext(); final ServiceReference<T> serviceReference = bundleContext.getServiceReference(serviceClass); if (serviceReference == null) { return null; } final T service = bundleContext.getService(serviceReference); bundleContext.ungetService(serviceReference); return service; }
Source:
START private void populateReviews(List<TaskReview> reviewContainers) throws NumberFormatException { END for (ITask review : reviews) { reviewContainers.add(new TaskReview(review)); } } This doesn't throw NumberFormatException anymore.

Target:
private void populateReviews(List<TaskReview> reviewContainers) { for (ITask review : reviews) { reviewContainers.add(new TaskReview(review)); } }
Source:
public BPUserLibraryElement getNewLibrary() { BPListElement[] entries = null; Map<String, String> attributes = null; if (fElementToEdit != null) { entries = fElementToEdit.getChildren(); IBuildpathContainer buildpathContainer = fElementToEdit .getUpdatedContainer(); if (buildpathContainer instanceof IBuildpathContainerExtension3) { IBuildpathContainerExtension3 buildpathContainer3 = (IBuildpathContainerExtension3) buildpathContainer; START attributes = buildpathContainer3.getAttributes(); END } } return new BPUserLibraryElement(fNameField.getText(), fIsSystemField.isSelected(), entries, attributes); } I would suggest access attributes in a more direct way, involving IBuildpathContainerExtension3 here seems unnecessary.

Target:
public BPUserLibraryElement getNewLibrary() { BPListElement[] entries = null; Map<String, String> attributes = null; if (fElementToEdit != null) { entries = fElementToEdit.getChildren(); attributes = fElementToEdit.getAttributes(); } return new BPUserLibraryElement(fNameField.getText(), fIsSystemField.isSelected(), entries, attributes); }
Source:
public String getDescription(AbstractOperation op) { if (op instanceof CompositeOperation) { final CompositeOperation compositeOperation = (CompositeOperation) op; // artificial composite because of opposite ref, take description of // main operation if (compositeOperation.getMainOperation() != null) { return getDescription(compositeOperation.getMainOperation()); } } // check of a custom operation label provider can provide a label final OperationCustomLabelProvider customLabelProvider = getLabelProvider(); final String decorate = decorate(customLabelProvider, op); START customLabelProvider.dispose(); END return decorate; } Shouldn't we wrap the dispose call() in an finally block (e.g. in case of NPE)?

Target:
public String getDescription(AbstractOperation op) { if (op instanceof CompositeOperation) { final CompositeOperation compositeOperation = (CompositeOperation) op; // artificial composite because of opposite ref, take description of // main operation if (compositeOperation.getMainOperation() != null) { return getDescription(compositeOperation.getMainOperation()); } } // check of a custom operation label provider can provide a label final OperationCustomLabelProvider customLabelProvider = getLabelProvider(); String decorate; try { decorate = decorate(customLabelProvider, op); return decorate; } finally { customLabelProvider.dispose(); } }
Source:
private void configureExistingWindows() { List<MArea> elements = modelService.findElements(window, null, MArea.class, null); for (MArea area : elements) { Object widget = area.getWidget(); if (widget instanceof Control) { START installAreaDropSupport((Control) widget); END } } } First time I saw this code, without to check what the method is doing, I've understood it like : "for each area install D&D support". However, the installAreaDropSupport() has a guard to be installed only once *per page*. Please add break; after that method OR change the "for" loop to something like snippet below if(!elements.isEmpty()) { Object widget = elements.iterator.next(); ... }

Target:
private void configureExistingWindows() { List<MArea> elements = modelService.findElements(window, null, MArea.class, null); for (MArea area : elements) { Object widget = area.getWidget(); if (widget instanceof Control) { installAreaDropSupport((Control) widget); break; } } }
Source:
START private static END DropStrategy findStrategy(Map<DropStrategy, Command> matchingStrategies, Command command) { for (Map.Entry<DropStrategy, Command> entry : matchingStrategies.entrySet()) { if (entry.getValue() == command ) { return entry.getKey(); } } return null; } why not protected?

Target:
protected static DropStrategy findStrategy(Map<DropStrategy, Command> matchingStrategies, Command command) { for (Map.Entry<DropStrategy, Command> entry : matchingStrategies.entrySet()) { if (entry.getValue() == command ) { return entry.getKey(); } } return null; }
Source:
public void setTreeProviders(ITreeContentProvider contentProvider, ILabelProvider labelProvider) { List START items; END if (root == null) { items = Collections.emptyList(); } else { // remember checked elements items = getAllWhiteCheckedItems(); // reset all caches for (Object object : items) { setTreeChecked(object, false); } } treeViewer.setContentProvider(contentProvider); treeViewer.setLabelProvider(labelProvider); treeContentProvider = contentProvider; treeLabelProvider = labelProvider; // select (if any) previously checked elements again in the new model for (Object object : items) { setTreeChecked(object, true); } } Doesn't this line produce a "raw type" warning?

Target:
public void setTreeProviders(ITreeContentProvider contentProvider, ILabelProvider labelProvider) { List<?> items; if (root == null) { items = Collections.emptyList(); } else { // remember checked elements items = getAllWhiteCheckedItems(); // reset all caches for (Object object : items) { setTreeChecked(object, false); } } treeViewer.setContentProvider(contentProvider); treeViewer.setLabelProvider(labelProvider); treeContentProvider = contentProvider; treeLabelProvider = labelProvider; // select (if any) previously checked elements again in the new model for (Object object : items) { setTreeChecked(object, true); } }
Source:
public URL getURL() { START try { return new URL(url.toString()); } catch (MalformedURLException e) { // shouldn't happen since we checked this in the constructor already return null; } END } why not just return url?

Target:
public URL getURL() { return url; }
Source:
private void doPaint(GC gc) { START if (fCanvas.isVisible()) { END return; } ILineRange visibleModelLines= computeVisibleModelLines(); if (visibleModelLines == null) return; fSensitiveToTextChanges= isViewerCompletelyShown(); fScrollPos= fCachedTextWidget.getTopPixel(); fRevisionPainter.paint(gc, visibleModelLines); if (!fRevisionPainter.hasInformation()) // don't paint quick diff colors if revisions are painted fDiffPainter.paint(gc, visibleModelLines); } Did you mean NOT visible?

Target:
private void doPaint(GC gc) { if (!fCanvas.isVisible()) { return; } ILineRange visibleModelLines= computeVisibleModelLines(); if (visibleModelLines == null) return; fSensitiveToTextChanges= isViewerCompletelyShown(); fScrollPos= fCachedTextWidget.getTopPixel(); fRevisionPainter.paint(gc, visibleModelLines); if (!fRevisionPainter.hasInformation()) // don't paint quick diff colors if revisions are painted fDiffPainter.paint(gc, visibleModelLines); }
Source:
public JSchFileManager(IRemoteConnection connection) { if (connection instanceof JSchConnection) try { ((JSchConnection) connection).getSftpChannel(); } catch (RemoteConnectionException e) { throw new UnsupportedOperationException(Messages.JSchConnection_Remote_host_does_not_support_sftp); START } END fConnection = connection; } I don't like constructors throwing exceptions. I think this check should be made in getService() and the constructor access changed to private.

Target:
private JSchFileManager(IRemoteConnection connection) { fConnection = connection; }
Source:
protected Object doGetValue() { CapsulePartKindEnum kind = null; setUMLPropertiesValue(); // Define what is the kind of the capsulePart based on the multiplicity and the aggregation value if (capsulePartElement.getLower() == capsulePartElement.getUpper()) { kind = CapsulePartKindEnum.FIXED; START } else if (capsulePartElement.getLower() == 0) { END if (AggregationKind.COMPOSITE_LITERAL.equals(aggregation)) { kind = CapsulePartKindEnum.OPTIONAL; } else if (AggregationKind.SHARED_LITERAL.equals(aggregation)) { kind = CapsulePartKindEnum.PLUGIN; } } return kind; } invert == 0

Target:
protected Object doGetValue() { CapsulePartKindEnum kind = null; setUMLPropertiesValue(); // Define what is the kind of the capsulePart based on the multiplicity and the aggregation value if (capsulePartElement.getLower() == capsulePartElement.getUpper()) { kind = CapsulePartKindEnum.FIXED; } else if (0 == capsulePartElement.getLower()) { if (AggregationKind.COMPOSITE_LITERAL.equals(aggregation)) { kind = CapsulePartKindEnum.OPTIONAL; } else if (AggregationKind.SHARED_LITERAL.equals(aggregation)) { kind = CapsulePartKindEnum.PLUGIN; } } return kind; }
Source:
START protected static END IWorkbenchWindow getActiveWindow(MApplication app) { return PlatformUI.getWorkbench().getActiveWorkbenchWindow(); } why it is protected, not package protected or private?

Target:
private static IWorkbenchWindow getActiveWindow(MApplication app) { return PlatformUI.getWorkbench().getActiveWorkbenchWindow(); }
Source:
START public void END setBoldStylerProvider(BoldStylerProvider boldStylerProvider) { fBoldStylerProvider= boldStylerProvider; } Remove this, so that it becomes package visible only.

Target:
void setBoldStylerProvider(BoldStylerProvider boldStylerProvider) { fBoldStylerProvider= boldStylerProvider; }
Source:
public static String getPath() { CtfCoreTestPlugin plugin = CtfCoreTestPlugin.getDefault(); if (plugin == null) { return null; } Path tracePath = Paths.get("..", "..", "ctf", "org.eclipse.tracecompass.ctf.core.tests", TRACES_DIRECTORY, TRACE_NAME); tracePath = tracePath.toAbsolutePath(); File file = tracePath.toFile(); START if (file.exists()) { END deleteTrace(tracePath); } generateLttngKernelTrace(file); return file.getAbsolutePath(); } we shouldn't do this check

Target:
public static String getPath() { CtfCoreTestPlugin plugin = CtfCoreTestPlugin.getDefault(); if (plugin == null) { return null; } Path tracePath = Paths.get("..", "..", "ctf", "org.eclipse.tracecompass.ctf.core.tests", TRACES_DIRECTORY, TRACE_NAME); tracePath = tracePath.toAbsolutePath(); File file = tracePath.toFile(); generateLttngKernelTrace(file); return file.getAbsolutePath(); }
Source:
private void updateTaskWithIncomingReviewState(ITask task, boolean hasIncomingReviews) { START task.setAttribute(ReviewsCoreConstants.INCOMING_REVIEW_STATE, hasIncomingReviews ? "true" : "false"); //$NON-NLS-1$//$NON-NLS-2$ END } Use Boolean.toString.

Target:
private void updateTaskWithIncomingReviewState(ITask task, boolean hasIncomingReviews) { task.setAttribute(ReviewsCoreConstants.INCOMING_REVIEW_STATE, Boolean.toString(hasIncomingReviews)); }
Source:
public void childRendered(MElementContainer<MUIElement> parentElement, MUIElement element) { super.childRendered(parentElement, element); processContents(parentElement); ToolBar toolbar = (ToolBar) getUIContainer(element); if (toolbar != null && !toolbar.isDisposed()) { START toolbar.pack(true); END toolbar.requestLayout(); } } Remove call to pack

Target:
public void childRendered(MElementContainer<MUIElement> parentElement, MUIElement element) { super.childRendered(parentElement, element); processContents(parentElement); ToolBar toolbar = (ToolBar) getUIContainer(element); if (toolbar != null && !toolbar.isDisposed()) { toolbar.requestLayout(); } }
Source:
public Set<GAV> START getProjectGAVs() END { return Collections.unmodifiableSet(new LinkedHashSet<>(gavs)); } synchronized

Target:
public synchronized Set<GAV> getProjectGAVs() { return Collections.unmodifiableSet(new LinkedHashSet<>(gavs)); }
Source:
public void testCreateSymlink() throws IOException { FS fs = FS.DETECTED; // show test as ignored if the FS doesn't support symlinks Assume.assumeTrue(fs.supportsSymlinks()); fs.createSymLink(new File(trash, "x"), "y"); START assertTrue(fs.supportsSymlinks()); END String target = fs.readSymLink(new File(trash, "x")); assertEquals("y", target); } This assertion is not needed anymore

Target:
public void testCreateSymlink() throws IOException { FS fs = FS.DETECTED; // show test as ignored if the FS doesn't support symlinks Assume.assumeTrue(fs.supportsSymlinks()); fs.createSymLink(new File(trash, "x"), "y"); String target = fs.readSymLink(new File(trash, "x")); assertEquals("y", target); }
Source:
public void testCreateSymlinkOverrideExisting() throws IOException { FS fs = FS.DETECTED; // show test as ignored if the FS doesn't support symlinks Assume.assumeTrue(fs.supportsSymlinks()); File file = new File(trash, "x"); fs.createSymLink(file, "y"); START assertTrue(fs.supportsSymlinks()); END String target = fs.readSymLink(file); assertEquals("y", target); fs.createSymLink(file, "z"); target = fs.readSymLink(file); assertEquals("z", target); } This assertion is not needed anymore

Target:
public void testCreateSymlinkOverrideExisting() throws IOException { FS fs = FS.DETECTED; // show test as ignored if the FS doesn't support symlinks Assume.assumeTrue(fs.supportsSymlinks()); File file = new File(trash, "x"); fs.createSymLink(file, "y"); String target = fs.readSymLink(file); assertEquals("y", target); fs.createSymLink(file, "z"); target = fs.readSymLink(file); assertEquals("z", target); }
Source:
public ITmfStateValue getValue(ITmfEvent event) { if (fStateValue != null) { return fStateValue; } if (fType.equals(TmfXmlStrings.TYPE_NULL)) { START return TmfStateValue.nullValue(); END } try { return checkNotNull(fXmlStateValue).getValue(event); } catch (AttributeNotFoundException e) { Activator.logError("Failed to get the state value", e); //$NON-NLS-1$ } throw new IllegalStateException("Failed to get the value for the segment field " + fName); //$NON-NLS-1$ } I think you've set fStateValue to nullValue in the constructor in this case, so this is pretty much dead code

Target:
public ITmfStateValue getValue(ITmfEvent event) { if (fStateValue != null) { return fStateValue; } try { return checkNotNull(fXmlStateValue).getValue(event); } catch (AttributeNotFoundException e) { Activator.logError("Failed to get the state value", e); //$NON-NLS-1$ } throw new IllegalStateException("Failed to get the value for the segment field " + fName); //$NON-NLS-1$ }
Source:
public void setRefiningChanges(Diff extension, DifferenceKind extensionKind, Diff refiningDiff) { if (extensionKind == DifferenceKind.CHANGE) { extension.getRefinedBy().addAll( Collections2.filter(getAllDifferencesForChange(refiningDiff), START EMFComparePredicates .fromSide(extension.getSource()))); END } } There is a static import for EMFComparePredicates.fromSide in this class already that you can use.

Target:
public void setRefiningChanges(Diff extension, DifferenceKind extensionKind, Diff refiningDiff) { if (extensionKind == DifferenceKind.CHANGE) { extension.getRefinedBy().addAll( Collections2.filter(getAllDifferencesForChange(refiningDiff), fromSide(extension .getSource()))); } }
Source:
START void execute(RevWalk rw, List<Command> todo) throws IOException { END if (apply(todo) && nextId != null) { commit(rw); } } Why a 2nd statusless execute function? It doesn't have any of the safety in the overridden execute() above.

Target:
void execute(RevWalk rw, List<Command> todo) throws IOException { if (apply(todo) && nextId != null) { commit(rw, todo); } }
Source:
void removeNestedCopyfiles() { for (RepoProject proj : filteredProjects) { List<CopyFile> copyfiles = START new ArrayList<CopyFile>(); END copyfiles.addAll(proj.getCopyFiles()); proj.clearCopyFiles(); Iterator<CopyFile> iter = copyfiles.iterator(); while (iter.hasNext()) { if (isNestedCopyfile(iter.next())) iter.remove(); } proj.addCopyFiles(copyfiles); } } optional: can use new ArrayList<>()

Target:
void removeNestedCopyfiles() { for (RepoProject proj : filteredProjects) { List<CopyFile> copyfiles = new ArrayList<>(); copyfiles.addAll(proj.getCopyFiles()); proj.clearCopyFiles(); Iterator<CopyFile> iter = copyfiles.iterator(); while (iter.hasNext()) { if (isNestedCopyfile(iter.next())) { iter.remove(); } } proj.addCopyFiles(copyfiles); } }
Source:
public void addKeyListener(KeyListener listener) { if (this.text != null && !this.text.isDisposed()) this.text.addKeyListener(listener); if START (this.dropdownTableViewer != END null && !this.dropdownTable.isDisposed()) this.dropdownTable.addKeyListener(listener); } why a check for the viewer here? shouldn't this be the dropdownTable? Now that we keep the table.

Target:
public void addKeyListener(KeyListener listener) { if (this.text != null && !this.text.isDisposed()) this.text.addKeyListener(listener); if (this.dropdownTable != null && !this.dropdownTable.isDisposed()) this.dropdownTable.addKeyListener(listener); }
Source:
public void addMouseListener(MouseListener listener) { // only add the mouse listener to the dropdown, as clicking in the text // control should not trigger anything else than it is handled by the // text control itself. if START (this.dropdownTableViewer != END null && !this.dropdownTable.isDisposed()) this.dropdownTable.addMouseListener(listener); } why a check for the viewer here? shouldn't this be the dropdownTable? Now that we keep the table.

Target:
public void addMouseListener(MouseListener listener) { // only add the mouse listener to the dropdown, as clicking in the text // control should not trigger anything else than it is handled by the // text control itself. if (this.dropdownTable != null && !this.dropdownTable.isDisposed()) this.dropdownTable.addMouseListener(listener); }