auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Version toOSGIVersion() { START return new Version(toString()); END } Should this return null if version is not a valid OSGI version?

Target:
final public Version toOSGIVersion() { try { return new Version(toString()); } catch (IllegalArgumentException e) { return null; } }
Source:
private String getTeamStr(ArtifactReadable action) { String results = action.getSoleAttributeAsString(AtsAttributeTypes.TeamDefinition, ""); if (Strings.isValid(results)) { results = atsServer.getArtifactByGuid(results).getName(); } else { ArtifactReadable teamWf = getParentTeamWf(action); if (teamWf != null) { START return getTeamStr(teamWf); END } } return results; } For consistency, suggest replace return with results =

Target:
private String getTeamStr(ArtifactReadable action) { String results = action.getSoleAttributeAsString(AtsAttributeTypes.TeamDefinition, ""); if (Strings.isValid(results)) { results = atsServer.getArtifactByGuid(results).getName(); } else { ArtifactReadable teamWf = getParentTeamWf(action); if (teamWf != null) { results = getTeamStr(teamWf); } } return results; }
Source:
public void addData(String guid, String classification, PageOrientation orientation) { DataRightEntry toAdd = new DataRightEntry(); toAdd.setClassification(classification); toAdd.setGuid(guid); toAdd.setOrientation(orientation); getData(); START data.add(toAdd); END } one line this --- getData().add(toAdd);

Target:
public void addData(String guid, String classification, PageOrientation orientation) { DataRightEntry toAdd = new DataRightEntry(); toAdd.setClassification(classification); toAdd.setGuid(guid); toAdd.setOrientation(orientation); getData().add(toAdd); }
Source:
private Map<String, ContextSensitiveTokenType> createContextSensitiveTokenMap( ICPPParserExtensionConfiguration config) { Map<String, ContextSensitiveTokenType> result = new HashMap<String, ContextSensitiveTokenType>(); START result.put(new String(Keywords.cOVERRIDE), ContextSensitiveTokenType.OVERRIDE); END result.put(new String(Keywords.cFINAL), ContextSensitiveTokenType.FINAL); result.putAll(config.getAdditionalContextSensitiveKeywords()); return result; } Makes sense to add a string constant to Keywords. Same for FINAL.

Target:
private Map<String, ContextSensitiveTokenType> createContextSensitiveTokenMap( ICPPParserExtensionConfiguration config) { Map<String, ContextSensitiveTokenType> result = new HashMap<String, ContextSensitiveTokenType>(); result.put(Keywords.OVERRIDE, ContextSensitiveTokenType.OVERRIDE); result.put(Keywords.FINAL, ContextSensitiveTokenType.FINAL); result.putAll(config.getAdditionalContextSensitiveKeywords()); return result; }
Source:
protected TreeViewer doCreateTreeViewer(Composite parentComposite, int style) { fCheckboxTreeViewer = new CheckboxTreeViewer(parentComposite, style); fCheckboxTreeViewer.addCheckStateListener(new ICheckStateListener() { @Override public void checkStateChanged(CheckStateChangedEvent event) { fObjects.put(event.getElement(), event.getChecked()); } }); START treeViewer = END fCheckboxTreeViewer; return treeViewer; } treeViewer is already set in base class from the return value of this method.

Target:
protected TreeViewer doCreateTreeViewer(Composite parentComposite, int style) { fCheckboxTreeViewer = new CheckboxTreeViewer(parentComposite, style); fCheckboxTreeViewer.addCheckStateListener(new ICheckStateListener() { @Override public void checkStateChanged(CheckStateChangedEvent event) { if (event.getChecked()) { fObjects.add(event.getElement()); } else { fObjects.remove(event.getElement()); } } }); return fCheckboxTreeViewer; }
Source:
private void checkSubtree(Object element, boolean state) { TreeItem item = (TreeItem) START fCheckboxTreeViewer.testFindItem(element); END if (!state || (item != null)) { fObjects.put(element, state); for (Object o : ((ITreeContentProvider) fCheckboxTreeViewer.getContentProvider()).getChildren(element)) { checkSubtree(o, state); } } } Would it be better to use getPatternFilter().isElementVisible()? ...and... the answer is no, because there could be other external filters on the viewer, since TimeGraphFilterDialog has an addFilter() method ;(

Target:
private void checkSubtree(Object element, boolean state) { if (!state || (fCheckboxTreeViewer.testFindItem(element) != null)) { if (state) { fObjects.add(element); } else { fObjects.remove(element); } for (Object o : ((ITreeContentProvider) fCheckboxTreeViewer.getContentProvider()).getChildren(element)) { checkSubtree(o, state); } } }
Source:
private boolean isDTreeItemContainerOwnedTreeItems(Notification notification) { START return notification.getFeature() == TreePackage.Literals.DTREE_ITEM_CONTAINER__OWNED_TREE_ITEMS && notification.getNotifier() instanceof DTreeItemContainer; END } Nitpick: the instanceof check is redundant here.

Target:
private boolean isDTreeItemContainerOwnedTreeItems(Notification notification) { return notification.getFeature() == TreePackage.Literals.DTREE_ITEM_CONTAINER__OWNED_TREE_ITEMS; }
Source:
private boolean isRGBValuesChange(Notification notification) { START return ViewpointPackage.Literals.RGB_VALUES.getEStructuralFeatures().contains(notification.getFeature()) && notification.getNotifier() instanceof RGBValues; END } Nitpick: the instanceof check is redundant here.

Target:
private boolean isRGBValuesChange(Notification notification) { return ViewpointPackage.Literals.RGB_VALUES.getEStructuralFeatures().contains(notification.getFeature()); }
Source:
protected void sendDispositionHeader(OutputStream out) throws IOException { super.sendDispositionHeader(out); START out.write(EncodingUtil.getAsciiBytes(FILE_NAME)); END out.write(QUOTE_BYTES); out.write(EncodingUtil.getBytes(filename, getCharSet())); out.write(QUOTE_BYTES); } I think this still needs to check that the filename is not null.

Target:
protected void sendDispositionHeader(OutputStream out) throws IOException { super.sendDispositionHeader(out); if (filename != null) { out.write(EncodingUtil.getAsciiBytes(FILE_NAME)); out.write(QUOTE_BYTES); out.write(EncodingUtil.getBytes(filename, getCharSet())); out.write(QUOTE_BYTES); } }
Source:
START public CriteriaSet getLastCriteriaSet() { END return criterias.get(criterias.size() - 1); } check for empty criterias?

Target:
public CriteriaSet getLastCriteriaSet() { return !criterias.isEmpty() ? criterias.get(criterias.size() - 1) : null; }
Source:
protected Long getBranchUuidFromTxId(int tx) { START QueryFactory queryFactory = orcsApi.getQueryFactory(getContext()); END TransactionQuery txQuery = queryFactory.transactionQuery(); Long branchId = txQuery.andTxId(tx).getResults().getExactlyOne().getBranchId(); return branchId; } Any reason why this can't simply call getQueryFactory()?

Target:
protected Long getBranchUuidFromTxId(int tx) { TransactionQuery txQuery = getQueryFactory().transactionQuery(); Long branchId = txQuery.andTxId(tx).getResults().getExactlyOne().getBranchId(); return branchId; }
Source:
START String getViewId() { END return fViewId; } private? (the outer class will still be able to access it)

Target:
private String getViewId() { return fViewId; }
Source:
protected Collection<? extends ITmfTrace> getTraces() { Set<ITmfTrace> traces = new HashSet<>(); for (ITmfTrace trace : fTraces) { START traces.addAll(Arrays.asList(TmfTraceManager.getTraceSet(trace))); END } return traces; } wow, this is hard to understand :P I assume it makes sense... You don't want to include the experiments, you just want the "real" traces, so you unpack all experiments. But in that case, why not just do this unpacking when you write into fTraces instead? So this method can remain a simple getter. Although if it's exposed publicly, the collection should be either synchronized or Immutable

Target:
protected Collection<? extends ITmfTrace> getTraces() { return new HashSet<>(fTraces); }
Source:
START public void setUp() throws Exception { END IEclipseContext globalContext = Activator.getDefault() .getGlobalContext(); workbenchContext = globalContext.createChild("workbenchContext"); ContextInjectionFactory.make(CommandServiceAddon.class, workbenchContext); ContextInjectionFactory.make(ContextServiceAddon.class, workbenchContext); ContextInjectionFactory.make(BindingServiceAddon.class, workbenchContext); defineCommands(workbenchContext); defineContexts(workbenchContext); defineBindingTables(workbenchContext); } I think throws Exception can be removed

Target:
public void setUp() { IEclipseContext globalContext = Activator.getDefault() .getGlobalContext(); workbenchContext = globalContext.createChild("workbenchContext"); ContextInjectionFactory.make(CommandServiceAddon.class, workbenchContext); ContextInjectionFactory.make(ContextServiceAddon.class, workbenchContext); ContextInjectionFactory.make(BindingServiceAddon.class, workbenchContext); defineCommands(workbenchContext); defineContexts(workbenchContext); defineBindingTables(workbenchContext); }
Source:
START protected static Collection<IResourceSetHook> getMatchingHooks( END ResourceSetHookRegistry resourceSetHookRegistry, final Collection<URI> urisToLoad) { final Collection<IResourceSetHook> hooks; if (resourceSetHookRegistry == null) { hooks = Collections.emptyList(); } else { hooks = Collections2.filter(resourceSetHookRegistry.getResourceSetHooks(), new Predicate<IResourceSetHook>() { public boolean apply(IResourceSetHook input) { return input.isHookFor(urisToLoad); } }); } return hooks; } private

Target:
private static Collection<IResourceSetHook> getMatchingHooks( ResourceSetHookRegistry resourceSetHookRegistry, final Collection<URI> urisToLoad) { final Collection<IResourceSetHook> hooks; if (resourceSetHookRegistry == null) { hooks = Collections.emptyList(); } else { hooks = Collections2.filter(resourceSetHookRegistry.getResourceSetHooks(), new Predicate<IResourceSetHook>() { public boolean apply(IResourceSetHook input) { return input.isHookFor(urisToLoad); } }); } return hooks; }
Source:
private void importProjects(final Set<File> dotProjectFiles) { WorkspaceJob job = new WorkspaceJob( UIText.ImportChangedProjectsCommand_ImportingChangedProjects) { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { for (File f : dotProjectFiles) { START if (monitor.isCanceled()) { END return Status.CANCEL_STATUS; } String ap = f.getAbsolutePath(); importProject(ap); } return Status.OK_STATUS; } }; job.schedule(); } no braces

Target:
private void importProjects(final Set<File> dotProjectFiles) { WorkspaceJob job = new WorkspaceJob( UIText.ImportChangedProjectsCommand_ImportingChangedProjects) { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { for (File f : dotProjectFiles) { if (monitor.isCanceled()) return Status.CANCEL_STATUS; String ap = f.getAbsolutePath(); importProject(ap); } return Status.OK_STATUS; } }; job.schedule(); }
Source:
public void cleanup() { START module.close(); END } I get a NPE here when I don't the traces downloaded. Also in the other tests that were modified.

Target:
public void cleanup() { if (module != null) { module.close(); } }
Source:
public IAtsProgram getProgram(Object artifact) { IAtsProgram program = null; if (artifact instanceof ArtifactReadable) { ArtifactReadable artRead = (ArtifactReadable) artifact; if (artRead.isOfType(AtsArtifactTypes.Program)) { START program = new Program(logger, atsServer, (ArtifactReadable) artifact); END } } return program; } Any reason why you can't use artRead instead of casting artifact again?

Target:
public IAtsProgram getProgram(Object artifact) { IAtsProgram program = null; if (artifact instanceof ArtifactReadable) { ArtifactReadable artRead = (ArtifactReadable) artifact; if (artRead.isOfType(AtsArtifactTypes.Program)) { program = new Program(logger, atsServer, artRead); } } return program; }
Source:
public Properties getStatistics() throws GitAPIException { try { GC gc = new GC((FileRepository) repo); START gc.setPackConfig(pconfig); END return toProperties(gc.getStatistics()); } catch (IOException e) { throw new JGitInternalException( JGitText.get().couldNotGetRepoStatistics, e); } } I think this isn't necessary here since getStatistics() doesn't need the configuration

Target:
public Properties getStatistics() throws GitAPIException { try { GC gc = new GC((FileRepository) repo); return toProperties(gc.getStatistics()); } catch (IOException e) { throw new JGitInternalException( JGitText.get().couldNotGetRepoStatistics, e); } }
Source:
public int compareTo(@Nullable ITmfStateValue object) { if (object instanceof NullStateValue){ START return -1; END } return 1; } Careful with the return value: returning -1 means nullstate value is smaller than all other objects. It should also be that other objects are greater than nullstate value, so you should do explicitly in other methods if (object instanceof NullStateValue) return 1; Also, for your unit tests, you should always do both ways, for instance, assertTrue(val1.compareTo(val2) > 0); assertFalse(val2.compareTo(val1) > 0);

Target:
public int compareTo(@Nullable ITmfStateValue object) { if (object == null || object instanceof NullStateValue) { return 0; } /* * We assume that every non-null state value is greater than any null * state value. */ return -1; }
Source:
public IContainerDMContext[] getTargetFilters() throws CoreException { START synchronized (fFilteredThreadsByTarget) { END Set<IContainerDMContext> set = fFilteredThreadsByTarget.keySet(); return set.toArray(new IContainerDMContext[set.size()]); } } I think it is safe to only synchronize the iteration of the next line. It is ok if the set changes but not while we are iterating over it.

Target:
public IContainerDMContext[] getTargetFilters() throws CoreException { Set<IContainerDMContext> set = fFilteredThreadsByTarget.keySet(); synchronized (fFilteredThreadsByTarget) { return set.toArray(new IContainerDMContext[set.size()]); } }
Source:
START public MPartStack createStack(String id, boolean visible) { END MPartStack newStack = modelService.createModelElement(MPartStack.class); // temporary HACK for bug 303982 newStack.getTags().add("newtablook"); //$NON-NLS-1$ newStack.setElementId(id); newStack.setToBeRendered(visible); return newStack; } Did not check, but can this method be declared as private?

Target:
private MPartStack createStack(String id, boolean visible) { MPartStack newStack = modelService.createModelElement(MPartStack.class); // temporary HACK for bug 303982 newStack.getTags().add("newtablook"); //$NON-NLS-1$ newStack.setElementId(id); newStack.setToBeRendered(visible); return newStack; }
Source:
START public void insert(MUIElement toInsert, MUIElement relTo, END int swtSide, float ratio) { int pct = (int) (ratio * 10000); insert(toInsert, relTo, swtSide, pct); } Did not check, but can this method be declared as private?

Target:
private void insert(MUIElement toInsert, MUIElement relTo, int swtSide, float ratio) { int pct = (int) (ratio * 10000); insert(toInsert, relTo, swtSide, pct); }
Source:
public ChainingCredentialsProvider(CredentialsProvider... providers) { START this.credentialProviders = new LinkedList<CredentialsProvider>(); END for (CredentialsProvider p : providers) credentialProviders.add(p); } Why not use `credentialsProviders = new ArrayList<CredentialsProvider>(Arrays.asList(providers))` instead of a LinkedList? Not that it matters here, but see: http://stackoverflow.com/q/322715/305973

Target:
public ChainingCredentialsProvider(CredentialsProvider... providers) { this.credentialProviders = new ArrayList<CredentialsProvider>( Arrays.asList(providers)); for (CredentialsProvider p : providers) credentialProviders.add(p); }
Source:
public static boolean isReactOnSelection() { IPreferenceStore preferenceStore = getPreferencesStore(); if (!preferenceStore .contains(UIPreferences.REBASE_INTERACTIVE_SYNC_SELECTION)) preferenceStore.setDefault( START UIPreferences.REBASE_INTERACTIVE_SYNC_SELECTION, true); END return preferenceStore .getBoolean(UIPreferences.REBASE_INTERACTIVE_SYNC_SELECTION); } I think setting defaults is usually in the PluginPreferenceInitializer class.

Target:
public static boolean isReactOnSelection() { return getPreferencesStore().getBoolean( UIPreferences.REBASE_INTERACTIVE_SYNC_SELECTION); }
Source:
public void testCreateArtifactsEmpty() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); RoughArtifact roughParent = new RoughArtifact(RoughArtifactKind.CONTAINER); RoughArtifactCollector collector = new RoughArtifactCollector(roughParent); dtc.createArtifacts(collector); // exception because there is no data START Assert.fail(); END } fail is unecesary if an exception doesn't happen test will fail.

Target:
public void testCreateArtifactsEmpty() { RoughArtifact roughParent = new RoughArtifact(RoughArtifactKind.CONTAINER); RoughArtifactCollector collector = new RoughArtifactCollector(roughParent); dtc.createArtifacts(collector); // exception because there is no data }
Source:
public void testGetHTMLEmpty() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); DoorsTableRow dtr = new DoorsTableRow(); dtc.getHTML(dtr, DoorsColumnType.OBJECT_TEXT); START Assert.fail(); END } fail is unecesary if an exception doesn't happen test will fail.

Target:
public void testGetHTMLEmpty() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); DoorsTableRow dtr = new DoorsTableRow(); dtc.getHTML(dtr, DoorsColumnType.OBJECT_TEXT); }
Source:
public void testGetHTMLNullInput() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); dtc.getHTML(null, DoorsColumnType.OBJECT_TEXT); START Assert.fail(); END } fail is unecesary if an exception doesn't happen test will fail.

Target:
public void testGetHTMLNullInput() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); dtc.getHTML(null, DoorsColumnType.OBJECT_TEXT); }
Source:
public void testGetPreferredNameEmpty() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); DoorsTableRow dtr = new DoorsTableRow(); dtc.getPreferredName(dtr); START Assert.fail(); END } fail is unecesary if an exception doesn't happen test will fail.

Target:
public void testGetPreferredNameEmpty() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); DoorsTableRow dtr = new DoorsTableRow(); dtc.getPreferredName(dtr); }
Source:
public void testGetPreferredNameNullInput() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); dtc.getPreferredName(null); START Assert.fail(); END } fail is unecesary if an exception doesn't happen test will fail.

Target:
public void testGetPreferredNameNullInput() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); dtc.getPreferredName(null); }
Source:
public RoughArtifact populateArtifact(Queue<DoorsTableRow> queue) { Conditions.checkNotNullOrEmpty(queue, "Queue"); START END RoughArtifact combined = populateArtifact(queue.poll()); while (!queue.isEmpty()) { combineDoorsArtifacts(combined, populateArtifact(queue.poll())); } return combined; } why the double poll here? should this use drain instead ?

Target:
public RoughArtifact populateArtifact(Queue<DoorsTableRow> queue) { Conditions.checkNotNullOrEmpty(queue, "Queue"); RoughArtifact combined = populateArtifact(queue.remove()); while (!queue.isEmpty()) { combineDoorsArtifacts(combined, populateArtifact(queue.remove())); } return combined; }
Source:
START public static synchronized DoorsColumnType fromString(String value) { END // special case since Verification Criteria column heading varies by program if (value.contains("Verification Criteria")) { value = "Verification Criteria"; } if (rawStringToDataType.isEmpty()) { for (DoorsColumnType enumStatus : DoorsColumnType.values()) { DoorsColumnType.rawStringToDataType.put(enumStatus.columnType, enumStatus); } } DoorsColumnType returnVal = rawStringToDataType.get(value); return returnVal != null ? returnVal : OTHER; } Remove synchronized and lazy loading of the map structure, add values to static map during enum element construction.

Target:
public static DoorsColumnType fromString(String value) { // special case since Verification Criteria column heading varies by program if (value.contains("Verification Criteria")) { value = "Verification Criteria"; } DoorsColumnType returnVal = rawStringToDataType.get(value); return returnVal != null ? returnVal : OTHER; }
Source:
public void closeAllTestWindows() { START Iterator<IWorkbenchWindow> iter = new ArrayList<IWorkbenchWindow>(testWindows).iterator(); END while (iter.hasNext()) { IWorkbenchWindow win = iter.next(); win.close(); } testWindows.clear(); } Making a new List, which contains the IWorkbenchWindows and getting its Iterator is not necessary here. I would propose to write: for(IWorkbenchWindow testWindow : testWindows){ testWindow.close(); }

Target:
public void closeAllTestWindows() { for (IWorkbenchWindow testWindows : testWindows) { testWindows.close(); } testWindows.clear(); }
Source:
protected void createDefaultEditPolicies() { super.createDefaultEditPolicies(); this.installEditPolicy(EditPolicyRoles.POPUPBAR_ROLE, new SiriusPopupBarEditPolicy()); // Replace the feedback policy to have a lighter color for guides START removeEditPolicy(EditPolicyRoles.SNAP_FEEDBACK_ROLE); END installEditPolicy(EditPolicyRoles.SNAP_FEEDBACK_ROLE, new SiriusSnapFeedbackPolicy()); } I know we tend to always do remove/install in our code, but this is actually not needed: org.eclipse.gef.editparts.AbstractEditPart.installEditPolicy(Object, EditPolicy) will remove (and deactivate) any pre-existing policy in the role we want to install the new one.

Target:
protected void createDefaultEditPolicies() { super.createDefaultEditPolicies(); this.installEditPolicy(EditPolicyRoles.POPUPBAR_ROLE, new SiriusPopupBarEditPolicy()); // Replace the feedback policy to have a lighter color for guides installEditPolicy(EditPolicyRoles.SNAP_FEEDBACK_ROLE, new SiriusSnapFeedbackPolicy()); }
Source:
START public static boolean isEqualToDefault(EObject object, EStructuralFeature feature) { END final Object value = ReferenceUtil.safeEGet(object, feature); final Object defaultValue = feature.getDefaultValue(); if (value == null) { return defaultValue == null; } return value.equals(feature.getDefaultValue()) || "".equals(value); //$NON-NLS-1$ } We don't need this public. You can leave the renaming to "is*" in though, since that's a better name :).

Target:
private static boolean isEqualToDefault(EObject object, EStructuralFeature feature) { final Object value = ReferenceUtil.safeEGet(object, feature); final Object defaultValue = feature.getDefaultValue(); if (value == null) { return defaultValue == null; } return value.equals(feature.getDefaultValue()) || "".equals(value); //$NON-NLS-1$ }
Source:
protected ITmfTrace getTrace() { START synchronized (syncObj) { END return fTrace; } } Unnecessary?

Target:
protected ITmfTrace getTrace() { return fTrace; }
Source:
public boolean areRelated(Object object1, IRelationTypeSide relationType, Object object2) { boolean related = false; Artifact useArt1 = getArtifact(object1); Artifact useArt2 = getArtifact(object2); START if (useArt1 != null & useArt2 != null) { END related = useArt1.isRelated(relationType, useArt2); } return related; } bitwise operation intended here?

Target:
public boolean areRelated(Object object1, IRelationTypeSide relationType, Object object2) { boolean related = false; Artifact useArt1 = getArtifact(object1); Artifact useArt2 = getArtifact(object2); if (useArt1 != null && useArt2 != null) { related = useArt1.isRelated(relationType, useArt2); } return related; }
Source:
public static void applyHyperlinkDetectorStyleRanges( ITextViewer textViewer, IHyperlinkDetector[] hyperlinkDetectors) { StyleRange[] styleRanges = getHyperlinkDetectorStyleRanges(textViewer, hyperlinkDetectors); StyledText styledText = textViewer.getTextWidget(); // Apply hyperlink style ranges one by one. setStyleRange takes care to // do the right thing in case they overlap with an existing style range. START for (StyleRange styleRange : styleRanges) { END styledText.setStyleRange(styleRange); } } style nit: no braces

Target:
public static void applyHyperlinkDetectorStyleRanges( ITextViewer textViewer, IHyperlinkDetector[] hyperlinkDetectors) { StyleRange[] styleRanges = getHyperlinkDetectorStyleRanges(textViewer, hyperlinkDetectors); StyledText styledText = textViewer.getTextWidget(); // Apply hyperlink style ranges one by one. setStyleRange takes care to // do the right thing in case they overlap with an existing style range. for (StyleRange styleRange : styleRanges) styledText.setStyleRange(styleRange); }
Source:
public IProject[] getTrackedProjects() { IProject[] projects = new IProject[trackedProjects.keySet().size()]; START return trackedProjects.keySet().toArray(projects); END } I believe this can become 'return trackedProjects.keySet().toArray(new IProject[0])' . If the array passed in is not large enough, a new one will be created of the proper type to store the Set's content, so the size calculation isn't needed.

Target:
public IProject[] getTrackedProjects() { return trackedProjects.keySet().toArray(new IProject[0]); }
Source:
public void tearDown() { try { fResource.getProject().delete(true, null); } catch (CoreException e) { START e.printStackTrace(); END } } here too, or just log the error

Target:
public void tearDown() throws CoreException { if (fResource != null && fResource.exists()) { fResource.getProject().delete(true, null); } }
Source:
public void handleSuccess() { super.handleSuccess(); if (isCompleteTrace(trace)) { disposeProvider(false); } else { fNbRead += getNbRead(); synchronized (fRequestSyncObj) { final TmfTimeRange timeRange = fTimeRange; if (timeRange != null) { START if (getRange().getEndTime().getValue() > timeRange.getEndTime().getValue()) { END startRequest(); } } } } } Shouldn't this be < instead? if the end of the time range of this request is before the time range that has been updated in the traceRangeUpdated signal handler?

Target:
public void handleSuccess() { super.handleSuccess(); if (isCompleteTrace(trace)) { disposeProvider(false); } else { fNbRead += getNbRead(); synchronized (fRequestSyncObj) { final TmfTimeRange timeRange = fTimeRange; if (timeRange != null) { if (getRange().getEndTime().getValue() < timeRange.getEndTime().getValue()) { startRequest(); } } } } }
Source:
public StreamGobbler(InputStream stream, OutputStream output) { this.reader = new BufferedReader(new InputStreamReader(stream)); if (output == null) this.writer = new BufferedWriter(new OutputStreamWriter( new START ByteArrayOutputStream())); END else this.writer = new BufferedWriter(new OutputStreamWriter(output)); } why create a buffer to store some content which we want to throw away in the end? If output is <null> don't initialize a writer and during the call() method when writer is not initialized just read lines.

Target:
public StreamGobbler(InputStream stream, OutputStream output) { this.reader = new BufferedReader(new InputStreamReader(stream)); if (output == null) this.writer = null; else this.writer = new BufferedWriter(new OutputStreamWriter(output)); }
Source:
public ValidateScheduler(DiagramEditPart diagramEditPart, long delay) { this.diagramEditPart = diagramEditPart; START this.scheduledJobs = new ArrayDeque<ValidateJob>(); END } this.delay = delay;

Target:
public ValidateScheduler(DiagramEditPart diagramEditPart, long delay) { this.diagramEditPart = diagramEditPart; this.scheduledJobs = new ArrayDeque<ValidateJob>(); this.delay = delay; }
Source:
private void handleDisconnected() { removeAllChildren(); setTargetNodeState(TargetNodeState.DISCONNECTED); START fService = null; END } fShell.disconnect() is never called (even in previous code). Which leads to that the hanging executor thread in the CommandShell.

Target:
private void handleDisconnected() { fService = null; setTargetNodeState(TargetNodeState.DISCONNECTED); removeAllChildren(); }
Source:
public void run() { for (TimeGraphEntry entry : fZoomEntryList) { if (fMonitor.isCanceled()) { return; } if (entry == null) { break; } zoom(entry, fMonitor); } /* Refresh the arrows when zooming */ List<ILinkEvent> events = getLinkList(fZoomStartTime, fZoomEndTime, fResolution, fMonitor); START fTimeGraphWrapper.getTimeGraphViewer().setLinks(events); END redraw(); } We have to put back the null check here. But perhaps you would prefer instead to make the getLinkList() return value @NonNull, and here we could check the monitor's canceled state to decide if we update the viewer or not.

Target:
public void run() { for (TimeGraphEntry entry : fZoomEntryList) { if (fMonitor.isCanceled()) { return; } if (entry == null) { break; } zoom(entry, fMonitor); } /* Refresh the arrows when zooming */ List<ILinkEvent> events = getLinkList(fZoomStartTime, fZoomEndTime, fResolution, fMonitor); if (events != null) { fTimeGraphWrapper.getTimeGraphViewer().setLinks(events); redraw(); } }
Source:
public static boolean isBundleClassUri(String uri) { if (uri != null && uri.startsWith(BUNDLECLASS_SCHEMA)) { START String[] split = uri.substring(14).split("/"); //$NON-NLS-1$ END // valid bundleclass uri should have two segments: // first one for the bundle-symbolic-name // second one for the full qualified classname if (split.length == 2) { return true; } ; } return false; } I would suppose to use the indexOf("/") method instead of split here as it has better performance and a constant for the prefix. int indexOf = uri.substring(BUNDLECLASS_PREFIX_LENGTH).indexOf("/"); if(indexOf > 0){ return true; } ....

Target:
public static boolean isBundleClassUri(String uri) { if (uri != null && uri.startsWith(BUNDLECLASS_SCHEMA)) { String[] split = uri.substring(BUNDLECLASS_SCHEMA.length()).split("/"); //$NON-NLS-1$ // valid bundleclass uri should have two segments: // first one for the bundle-symbolic-name // second one for the full qualified classname if (split.length == 2) { return true; } } return false; }
Source:
START public synchronized SynchronizationAlgorithm synchronizeTraces() { END return synchronizeTraces(false); } Good catch.

Target:
public SynchronizationAlgorithm synchronizeTraces() { return synchronizeTraces(false); }
Source:
public EObject updateCreatedObject(EObject newObject, String loadedVersion) { EObject returnedValue = newObject; for (IMigrationParticipant contribution : delegatesParticipants) { START returnedValue = contribution.updateCreatedObject(newObject, loadedVersion); END } return returnedValue; } There is a bug here --> returnedValue = contribution.updateCreatedObject(returnedValue, loadedVersion);

Target:
public EObject updateCreatedObject(EObject newObject, String loadedVersion) { EObject returnedValue = null; for (IMigrationParticipant contribution : delegatesParticipants) { returnedValue = contribution.updateCreatedObject(newObject, loadedVersion); if (returnedValue != null) { break; } } return returnedValue; }
Source:
START public EObject updateCreatedObject(EObject newObject, String loadedVersion) { END EObject returnedValue = null; for (IMigrationParticipant contribution : delegatesParticipants) { returnedValue = contribution.updateCreatedObject(newObject, loadedVersion); if (returnedValue != null) { break; } } return returnedValue; } This method prohibits that 2 participants update the EObject. I think that updateCreatedObject should always return the EObject even if there is no modification. With this you can have something like this EObject returnedValue = newObject; for (IMigrationParticipant contribution : delegatesParticipants) { returnedValue = contribution.updateCreatedObject(returnedValue, loadedVersion); }

Target:
public EObject updateCreatedObject(EObject newObject, String loadedVersion) { EObject returnedValue = newObject; for (IMigrationParticipant contribution : delegatesParticipants) { returnedValue = contribution.updateCreatedObject(newObject, loadedVersion); } return returnedValue; }
Source:
private boolean isInteresting(ThreadInfo thread) { for (StackTraceElement element : thread.getStackTrace()) { String className = element.getClassName(); START if (!className.startsWith("java.") && !className.startsWith("sun.") && //$NON-NLS-1$ //$NON-NLS-2$ END !NON_INTERESTING_THREAD_FILTER.matchesFilter(element)) { return true; } } return false; } Why don't we handle that via the Filter? I dislike having a special treatment of certain stacktraces. I think it is OK to add them to the filter (with wildcards) but hard-coding them, seems wrong.

Target:
private boolean isInteresting(ThreadInfo thread) { for (StackTraceElement element : thread.getStackTrace()) { if (!NON_INTERESTING_THREAD_FILTER.matchesFilter(element)) { return true; } } return false; }
Source:
public void testGetSWTColor() { START Color result = getSWTColor(colorValue("red"), display); END assertNotNull(result); assertEquals(255, result.getRed()); assertEquals(0, result.getBlue()); assertEquals(0, result.getGreen()); } In this class all colors which are created, are not disposed at the end.

Target:
public void testGetSWTColor() { result = getSWTColor(colorValue("red"), display); assertNotNull(result); assertEquals(255, result.getRed()); assertEquals(0, result.getBlue()); assertEquals(0, result.getGreen()); }
Source:
START public static ImageFigureWithAlpha createImageFigure(final ContainerStyle containerStyle) { END if (containerStyle instanceof FlatContainerStyle) { FlatContainerStyle style = (FlatContainerStyle) containerStyle; SVGWorkspaceImageFigure fig = new SVGWorkspaceImageFigure(); fig.refreshFigure(style); return fig; } // TODO handle other styles.. return null; } I did not find any call for this method. Why did you change this ?

Target:
public static SVGWorkspaceImageFigure createImageFigure(final ContainerStyle containerStyle) { if (containerStyle instanceof FlatContainerStyle) { FlatContainerStyle style = (FlatContainerStyle) containerStyle; SVGWorkspaceImageFigure fig = new SVGWorkspaceImageFigure(); fig.refreshFigure(style); return fig; } // TODO handle other styles.. return null; }
Source:
public void setAllowDeletes(final boolean canDelete) { allowAnyDeletes = canDelete; START if (!canDelete) allowBranchDeletes = false; END } This loses information: after setAllowDeletes(true); setAllowBranchDeletes(true); setAllowDeletes(false); setAllowDeletes(true); what should isAllowBranchDeletes() say? I'd delete the above two lines and treat them as orthogonal (validateCommands would still prevent deleting branches when allowAnyDeletes is false).

Target:
public void setAllowDeletes(final boolean canDelete) { allowAnyDeletes = canDelete; }
Source:
public void resourceChanged(IResourceChangeEvent event) { IResourceDelta delta = event.getDelta(); if (delta != null) { ImageResourceDeltaVisitor visitor = getImageResourceDeltaVisitor(); try { delta.accept(visitor); START } catch (CoreException e) { END e.printStackTrace(); } for (String imageFileURI : visitor.changedImageFilesURI) { DiagramUIPlugin.getPlugin().removeImageFileStatusAndURIFromMaps(imageFileURI); } } } Use Sirius logger here.

Target:
public void resourceChanged(IResourceChangeEvent event) { // Do nothing. }
Source:
public void hashcodeTest() { VariantDeclaration a = new VariantDeclaration(); VariantDeclaration b = new VariantDeclaration(); b.addField("hi", StringDeclaration.getStringDeclaration(Encoding.UTF8)); VariantDeclaration c = new VariantDeclaration(); c.addField("hi", StringDeclaration.getStringDeclaration(Encoding.UTF8)); START assertEquals(fixture.hashCode(), a.hashCode()); END assertEquals(b.hashCode(), c.hashCode()); } move this line below the "VariantDeclaration a = ..." line, and an empty line after. It'll make it clearer what are the two parts of the test.

Target:
public void hashcodeTest() { VariantDeclaration a = new VariantDeclaration(); assertEquals(fixture.hashCode(), a.hashCode()); VariantDeclaration b = new VariantDeclaration(); b.addField("hi", StringDeclaration.getStringDeclaration(Encoding.UTF8)); VariantDeclaration c = new VariantDeclaration(); c.addField("hi", StringDeclaration.getStringDeclaration(Encoding.UTF8)); assertEquals(b.hashCode(), c.hashCode()); }
Source:
public void trailingSlashes() { assertEquals("/foo/bar/", START ServletUtils.getEncodedPathInfo("/s", "/c/s/foo/bar/", "/c")); END assertEquals("/foo/bar/", ServletUtils.getEncodedPathInfo("/s", "/c/s/foo/bar///", "/c")); assertEquals("/foo%2Fbar/", ServletUtils.getEncodedPathInfo("/s", "/c/s/foo%2Fbar/", "/c")); assertEquals("/foo%2Fbar/", ServletUtils.getEncodedPathInfo("/s", "/c/s/foo%2Fbar///", "/c")); } The argument order is... weird. Consider flipping it around to be: contextPath, servletPath, requestUri Then tests will be: "/c", "/s", "/c/s/foo/bar/" which is so much easier to read.

Target:
public void trailingSlashes() { assertEquals("/foo/bar/", ServletUtils.getEncodedPathInfo("/c", "/s", "/c/s/foo/bar/")); assertEquals("/foo/bar/", ServletUtils.getEncodedPathInfo("/c", "/s", "/c/s/foo/bar///")); assertEquals("/foo%2Fbar/", ServletUtils.getEncodedPathInfo("/c", "/s", "/c/s/foo%2Fbar/")); assertEquals("/foo%2Fbar/", ServletUtils.getEncodedPathInfo("/c", "/s", "/c/s/foo%2Fbar///")); }
Source:
private String getText(final EObject element) { ComposedAdapterFactory adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE); START AdapterFactoryItemDelegator adapterFactoryItemDelegator = new AdapterFactoryItemDelegator(adapterFactory); String text = adapterFactoryItemDelegator.getText(element); adapterFactory.dispose(); END return text; } The dispose() could be called from a finally block, to ensure it is always called even if an exception occurs during the getText() (which is possible given that it may call user-specified code outside of our control).

Target:
private String getText(final EObject element) { String text = null; ComposedAdapterFactory adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE); AdapterFactoryItemDelegator adapterFactoryItemDelegator = new AdapterFactoryItemDelegator(adapterFactory); try { text = adapterFactoryItemDelegator.getText(element); } finally { adapterFactory.dispose(); } return text; }
Source:
public TmfXmlReadOnlyStateValue(TmfXmlReadOnlyModelFactory modelFactory, Element node, IXmlStateSystemContainer container, String eventField) { START super(modelFactory, node, container, NonNullUtils.checkNotNull(Collections.EMPTY_LIST), eventField); END } bloops

Target:
public TmfXmlReadOnlyStateValue(TmfXmlReadOnlyModelFactory modelFactory, Element node, IXmlStateSystemContainer container, String eventField) { super(modelFactory, node, container, checkNotNull(Collections.EMPTY_LIST), eventField); }
Source:
public String getName() { START return NonNullUtils.checkNotNull(fModule.name()); END } bleep

Target:
public String getName() { return checkNotNull(fModule.name()); }
Source:
private TextTraceEventContent(@NonNull String fieldName) { fName = fieldName; fValue = null; START fFields = NonNullUtils.checkNotNull(Collections.EMPTY_LIST); END } Ni!

Target:
private TextTraceEventContent(@NonNull String fieldName) { fName = fieldName; fValue = null; fFields = checkNotNull(Collections.EMPTY_LIST); }
Source:
public String resolve(ITmfEvent event) { if (!(event instanceof PcapEvent)) { return EMPTY_STRING; } PcapEvent pcapEvent = (PcapEvent) event; TmfPcapProtocol protocol = pcapEvent.getMostEncapsulatedProtocol(); START return NonNullUtils.checkNotNull(protocol.getShortName().toUpperCase()); END } poutine

Target:
public String resolve(ITmfEvent event) { if (!(event instanceof PcapEvent)) { return EMPTY_STRING; } PcapEvent pcapEvent = (PcapEvent) event; TmfPcapProtocol protocol = pcapEvent.getMostEncapsulatedProtocol(); return checkNotNull(protocol.getShortName().toUpperCase()); }
Source:
protected @NonNull Iterable<ITmfTrace> getTracesToBuild(@NonNull ITmfTrace trace) { START return NonNullUtils.checkNotNull(Arrays.asList(TmfTraceManager.getTraceSet(trace))); END } This almost looks like code I wrote!

Target:
protected @NonNull Iterable<ITmfTrace> getTracesToBuild(@NonNull ITmfTrace trace) { return checkNotNull(Arrays.asList(TmfTraceManager.getTraceSet(trace))); }
Source:
protected boolean getCPULoadEnabled() { START return m_model.getLoadMetersEnabled(); END } In the current flows, a check is made to insure the model is not null. But it might be prudent to check again here, in case it's eventually called from elsewhere.

Target:
protected boolean getCPULoadEnabled() { return m_model == null ? false : m_model.getLoadMetersEnabled(); }
Source:
protected void handleDispose(DisposeEvent event) { editingDomainChange(getCompareConfiguration().getEditingDomain(), null); START getCompareConfiguration().getEventBus().unregister(this); END differenceGroupProvider.dispose(); super.handleDispose(event); } Are you sure that differenceGroupProvider is always not null at this place ? If not, please add guard.

Target:
protected void handleDispose(DisposeEvent event) { editingDomainChange(getCompareConfiguration().getEditingDomain(), null); getCompareConfiguration().getEventBus().unregister(this); if (differenceGroupProvider != null) { differenceGroupProvider.dispose(); } super.handleDispose(event); }
Source:
START public void testTypedefSyntheticMembers_415495() { END final String[] expected= { "" }; assertCompletionResults(fCursorOffset, expected, REPLACEMENT); } It's a good idea to run your tests before submitting them to Gerrit.

Target:
public void testTypedefSyntheticMembers_415495() throws Exception { final String[] expected= {}; assertCompletionResults(fCursorOffset, expected, REPLACEMENT); }
Source:
public ColorPickerEditor(Composite parent, int style, int defaultColor) { this(parent, style); START doSetColor(defaultColor); END } this.defaultColor should be set as well. Otherwise, pressing "Default" will reset the color to Black

Target:
public ColorPickerEditor(Composite parent, int style, int defaultColor) { this(parent, style); this.defaultColor = defaultColor; doSetColor(defaultColor); }
Source:
private View getFontStyleOwnerView() { START if (this instanceof DNodeListElementEditPart) { return (View) getModel(); } else { END return getPrimaryView(); } } This should be done in DNodeListElementEditPart

Target:
protected View getFontStyleOwnerView() { return getPrimaryView(); }
Source:
public void initActionSets() { if (descriptor != null) { START List<IActionSetDescriptor> temp = new ArrayList<IActionSetDescriptor>(); END List<String> ids = ModeledPageLayout.getIds(layout, ModeledPageLayout.ACTION_SET_TAG); createInitialActionSets(temp, ids); for (IActionSetDescriptor descriptor : temp) { if (!alwaysOnActionSets.contains(descriptor)) { alwaysOnActionSets.add(descriptor); } } } } maybe find a better name then "temp"?

Target:
public void initActionSets() { if (descriptor != null) { List<String> ids = ModeledPageLayout.getIds(layout, ModeledPageLayout.ACTION_SET_TAG); for (IActionSetDescriptor descriptor : createInitialActionSets(ids)) { if (!alwaysOnActionSets.contains(descriptor)) { alwaysOnActionSets.add(descriptor); } } } }
Source:
START protected void internalSetVariable(final String name, final Object content) { END if (!JVMCompiledHelper.isSaveName(name)) throw new RuntimeException("\"" + name + "\" is not a valid Scala variable name"); } setting a variable on a native engine might register that variable in a map. there is nothing more you could do to a variable. We do not need to check for save names either.

Target:
protected void internalSetVariable(final String name, final Object content) { }
Source:
public boolean isSameType(IType type) { if (type == this) return true; if (type instanceof ITypedef || type instanceof IIndexBinding) return type.isSameType(this); START if ( fDeferredInstance != null && type instanceof ICPPDeferredClassInstance) { END return type.isSameType(fDeferredInstance); } return false; } Extraneous space after (

Target:
public boolean isSameType(IType type) { if (type == this) return true; if (type instanceof ITypedef || type instanceof IIndexBinding) return type.isSameType(this); return false; }
Source:
public EObject createObject(EFactory eFactory, EClassifier type) { EFactory factory = eFactory; if (migrationNeeded) { // Handle EClass moved from one package to another, // prefix is not sufficient to retrieve the new package and factory // in // org.eclipse.emf.ecore.xmi.impl.XMLHandler.getFactoryForPrefix(String) // which does factory = // ePackage.getEFactoryInstance(); // The migration participants return the new type with EClassifier // getType(EPackage, String, String). // Then we get the factory instance from the EClassifier's EPackage. if (type != null && type.getEPackage() != null && type.getEPackage().getEFactoryInstance() != null) { factory = type.getEPackage().getEFactoryInstance(); } } START EObject newObject = super.createObject(factory, type); if (migrationNeeded) { newObject = RepresentationsFileMigrationService.getInstance().updateCreatedObject(newObject, version); } return newObject; END } To me this modification should be done in its own commit which should reference Bug 449167

Target:
public EObject createObject(EFactory eFactory, EClassifier type) { EFactory factory = eFactory; if (migrationNeeded) { // Handle EClass moved from one package to another, // prefix is not sufficient to retrieve the new package and factory // in // org.eclipse.emf.ecore.xmi.impl.XMLHandler.getFactoryForPrefix(String) // which does factory = // ePackage.getEFactoryInstance(); // The migration participants return the new type with EClassifier // getType(EPackage, String, String). // Then we get the factory instance from the EClassifier's EPackage. if (type != null && type.getEPackage() != null && type.getEPackage().getEFactoryInstance() != null) { factory = type.getEPackage().getEFactoryInstance(); } } return super.createObject(factory, type); }
Source:
START public static ITmfTimestampTransform createLinearFast(BigDecimal factor, BigDecimal offset) { END return new TmfTimestampTransformLinearFast(new TmfTimestampTransformLinear(factor, offset)); } If that is the case, why jerry-rig the factory, just create an object manually?

Target:
public static ITmfTimestampTransform createLinearFast(BigDecimal factor, BigDecimal offset) { return new TmfTimestampTransformLinearFast(factor, offset); }
Source:
START private String getLabel(final EObject eObject) { END String label = "Element whithout name"; if (eObject instanceof IdentifiedElement) { label = new IdentifiedElementQuery((IdentifiedElement) eObject).getLabel(); } else if (eObject instanceof RepresentationExtensionDescription) { label = ((RepresentationExtensionDescription) eObject).getName(); } else { label = eObject.eClass().getName(); } return label; } Could be protected to be reusable by child classes.

Target:
protected String getLabel(final EObject eObject) { String label = "Element whithout name"; if (eObject instanceof IdentifiedElement) { label = new IdentifiedElementQuery((IdentifiedElement) eObject).getLabel(); } else if (eObject instanceof RepresentationExtensionDescription) { label = ((RepresentationExtensionDescription) eObject).getName(); } else { label = eObject.eClass().getName(); } return label; }
Source:
public TransientState(IStateHistoryBackend backend) { START this.fBackend = backend; END fIsActive = true; fOngoingStateInfo = new ArrayList<>(); fOngoingStateStartTimes = new ArrayList<>(); fStateValueTypes = new ArrayList<>(); fLatestTime = backend.getStartTime(); } you can remove the "this." now that the names are different

Target:
public TransientState(IStateHistoryBackend backend) { fBackend = backend; fIsActive = true; fOngoingStateInfo = new ArrayList<>(); fOngoingStateStartTimes = new ArrayList<>(); fStateValueTypes = new ArrayList<>(); fLatestTime = backend.getStartTime(); }
Source:
public AbstractTmfStateProvider(ITmfTrace trace, Class<? extends ITmfEvent> eventType, String id) { this.fTrace = trace; START this.fEventType = eventType; END fEventsQueue = new ArrayBlockingQueue<>(DEFAULT_EVENTS_QUEUE_SIZE); fStateSystemAssigned = false; fEventHandlerThread = new Thread(new EventProcessor(), id + " Event Handler"); //$NON-NLS-1$ } remove the "this."

Target:
public AbstractTmfStateProvider(ITmfTrace trace, Class<? extends ITmfEvent> eventType, String id) { fTrace = trace; fEventType = eventType; fEventsQueue = new ArrayBlockingQueue<>(DEFAULT_EVENTS_QUEUE_SIZE); fStateSystemAssigned = false; fEventHandlerThread = new Thread(new EventProcessor(), id + " Event Handler"); //$NON-NLS-1$ }
Source:
private boolean START isSequenceChange(Notification END input) { return new NotificationQuery(input).isNotationChange() && isSequenceElement(input.getNotifier()) && needsLayout(input); } isSequenceNotationChange would be a better name

Target:
private boolean isSequenceChange(Notification input) { return new NotificationQuery(input).isNotationChange() && isSequenceElement(input) && needsLayout(input); }