auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public EventList(List<ITimeEvent> list, long startTime, long endTime) { if (list != null) { fEventList = Collections.unmodifiableList(list); START } END fStartTime = startTime; fEndTime = endTime; } If the fields are set to final, here you'll probably have to do } else { fEventList = null; } or fEventList = new ArrayList<>() for an empty list?

Target:
public EventList(List<ITimeEvent> list, long startTime, long endTime) { if (list != null) { fEventList = Collections.unmodifiableList(list); } else { fEventList = null; } fStartTime = startTime; fEndTime = endTime; }
Source:
public boolean isSuccessful() { // TODO Auto-generated method stub START return false; END } why is this unsuccessful ?

Target:
public boolean isSuccessful() { return true; }
Source:
public void drawItems(Rectangle bounds, ITimeDataProvider timeProvider, Item[] items, int topIndex, int nameSpace, GC gc) { for (int i = topIndex; i < items.length; i++) { Item item = items[i]; drawItem(item, bounds, timeProvider, i, nameSpace, gc); START } END fTimeGraphProvider.postDrawControl(bounds, gc); } should be moved to paint method

Target:
public void drawItems(Rectangle bounds, ITimeDataProvider timeProvider, Item[] items, int topIndex, int nameSpace, GC gc) { for (int i = topIndex; i < items.length; i++) { Item item = items[i]; drawItem(item, bounds, timeProvider, i, nameSpace, gc); } }
Source:
public void handleData(ITmfEvent data) { START if (data != null && !(data instanceof ITmfLostEvent)) { END fNbRead++; } } I'm not sure we want to do this. When you have a request with a fixed number of events to read, the lost events should be counted. It's also used by the checkpoint indexer.

Target:
public void handleData(ITmfEvent data) { if (data != null) { fNbRead++; } }
Source:
private void generateInstallSection(StringBuilder buffer) { buffer.append("%install\n"); START buffer.append("rm -rf %{buildroot}\n\n"); END buffer.append("%if 0%{?with_python3}\n"); buffer.append("pushd %{py3dir}\n"); buffer.append("%{__python3} setup.py install --skip-build --root %{buildroot}\n"); buffer.append("popd\n"); buffer.append("%endif # with_python3\n\n"); buffer.append("%{__python} setup.py install --skip-build --root %{buildroot}\n\n\n"); } No need to clean the buildroot either, rpmbuild handles it internally.

Target:
private void generateInstallSection(StringBuilder buffer) { buffer.append("%install\n"); buffer.append("%if 0%{?with_python3}\n"); buffer.append("pushd %{py3dir}\n"); buffer.append("%{__python3} setup.py install --skip-build --root %{buildroot}\n"); buffer.append("popd\n"); buffer.append("%endif # with_python3\n\n"); buffer.append("%{__python} setup.py install --skip-build --root %{buildroot}\n\n\n"); }
Source:
public PythonEggParser(IFile file) throws IOException, CoreException { setupOptions = new HashMap<String, String>(); variables = new HashMap<String, String>(); // end if file is empty or cannot get its contents START if (file.getContents().available() <= 0) END return; this.file = file; parse(); } Common code style in Linux tools is to have around if statements. Please fix it everywhere.

Target:
public PythonEggParser(IFile file) throws IOException, CoreException { setupOptions = new HashMap<String, String>(); variables = new HashMap<String, String>(); // end if file is empty or cannot get its contents if (file.getContents().available() <= 0) { return; } this.file = file; parse(); }
Source:
public NullOperationLogger() { // singleton so prevent external construction START } END This should not be public

Target:
private NullOperationLogger() { // singleton so prevent external construction }
Source:
protected final List<IMergeViewerItem> createMergeViewerItemFrom(Collection<?> values) { List<IMergeViewerItem> ret = newArrayListWithCapacity(values.size()); for (Object value : values) { START if (value instanceof EObject) { END IMergeViewerItem valueToAdd = createMergeViewerItemFrom((EObject)value); if (valueToAdd != null) { ret.add(valueToAdd); } } } return ret; } I suspect the bug is before that point, please investigate more.

Target:
protected final List<IMergeViewerItem> createMergeViewerItemFrom(Collection<?> values) { List<IMergeViewerItem> ret = newArrayListWithCapacity(values.size()); for (Object value : values) { IMergeViewerItem valueToAdd = createMergeViewerItemFrom((EObject)value); if (valueToAdd != null) { ret.add(valueToAdd); } } return ret; }
Source:
private List<Object> parseList(String str) { List<Object> rc = new ArrayList<Object>(); String temp = str.trim(); Pattern pattern = isPatternFoundList(str); if (pattern == null) START return null; END Matcher variableMatcher = pattern.matcher(temp); if (variableMatcher != null) { while (variableMatcher.find()) { rc.add(variableMatcher.group()); } } return rc; } Please return the empty rc here to prevent NPEs. Users of the method can easily check whether the list is empty instead of null. Returning null when collection is expected is considered a really bad style.

Target:
private List<String> parseList(String str) { List<String> rc = new ArrayList<String>(); String temp = str.trim(); Pattern pattern = isPatternFoundList(str); if (pattern == null) { return rc; } Matcher variableMatcher = pattern.matcher(temp); if (variableMatcher != null) { while (variableMatcher.find()) { rc.add(variableMatcher.group()); } } return rc; }
Source:
public static boolean containsErrors(Comparison comparison) { boolean isError = false; Diagnostic diagnostic = comparison.getDiagnostic(); if (diagnostic != null) { START return diagnostic.getSeverity() > Diagnostic.WARNING; END } return isError; } why don't you use the variable isError ? It is assigned once to false and returned as is. You should either 'return false' at the end the method, or assign isError here. BTW, the variable should be renamed to containsError or hasError as 'isError' is not proper english.

Target:
public static boolean containsErrors(Comparison comparison) { Diagnostic diagnostic = comparison.getDiagnostic(); if (diagnostic != null) { return diagnostic.getSeverity() > Diagnostic.WARNING; } return false; }
Source:
public final IAnalysisModule getAnalysisModule(String analysisId) { START if (!fAnalysisModules.containsKey(analysisId)) { END return null; } return fAnalysisModules.get(analysisId); } Unnecessary check, the get() below will return null

Target:
public final IAnalysisModule getAnalysisModule(String analysisId) { return fAnalysisModules.get(analysisId); }
Source:
public void setParameter(String name, Object value) { START synchronized (fParameters) { END if (!fParameterNames.contains(name)) { throw new RuntimeException(NLS.bind(Messages.TmfAbstractAnalysisModule_InvalidParameter, name, getName())); } Object oldValue = fParameters.get(name); fParameters.put(name, value); if ((value != null) && !(value.equals(oldValue))) { parameterChanged(name); } } } if you are synchronizing whole methods on the same object, you might as well use the class's monitor, by using the synchronized keyword in the method signature (public synchronized void ...) This avoids extra sync objects (and saves one level of indentation!)

Target:
public synchronized void setParameter(String name, Object value) { if (!fParameterNames.contains(name)) { throw new RuntimeException(NLS.bind(Messages.TmfAbstractAnalysisModule_InvalidParameter, name, getName())); } Object oldValue = fParameters.get(name); fParameters.put(name, value); if ((value != null) && !(value.equals(oldValue))) { parameterChanged(name); } }
Source:
START public void registerOutput(IAnalysisOutput output) { END fOutputs.add(output); } One output could be added many times. Do we need to prevent that?

Target:
public void registerOutput(IAnalysisOutput output) { if (!fOutputs.contains(output)) { fOutputs.add(output); } }
Source:
START public static void registerParameterProvider(String analysisId, Class<? extends IAnalysisParameterProvider> paramProvider) { END if (!fParameterProviders.containsKey(analysisId)) { fParameterProviders.put(analysisId, new ArrayList<Class<? extends IAnalysisParameterProvider>>()); } fParameterProviders.get(analysisId).add(paramProvider); } can this be called from multiple threads? If yes then there is a concurrency issue. fParameterProviders needs to be handle thread safe in this class.

Target:
public static void registerParameterProvider(String analysisId, Class<? extends IAnalysisParameterProvider> paramProvider) { synchronized (fParameterProviders) { if (!fParameterProviders.containsKey(analysisId)) { fParameterProviders.put(analysisId, new ArrayList<Class<? extends IAnalysisParameterProvider>>()); } fParameterProviders.get(analysisId).add(paramProvider); } }
Source:
public void addObserver(RemoteEmfObserver<EParentObjectType, EObjectType, LocalKeyType, ObjectCurrentType> observer) { if (observer != null) { RemoteEmfObserver<EParentObjectType, EObjectType, LocalKeyType, ObjectCurrentType> remoteEmfObserver = observer; if (remoteEmfObserver.getConsumer() != null && remoteEmfObserver.getConsumer() != this) { remoteEmfObserver.getConsumer().removeObserver(remoteEmfObserver); } remoteEmfObserver.internalSetConsumer(this); } START remoteEmfObservers.add(observer); END } This could add null as an observer. Why would that be allowed?

Target:
public void addObserver(RemoteEmfObserver<EParentObjectType, EObjectType, LocalKeyType, ObjectCurrentType> observer) { if (observer != null) { RemoteEmfObserver<EParentObjectType, EObjectType, LocalKeyType, ObjectCurrentType> remoteEmfObserver = observer; if (remoteEmfObserver.getConsumer() != null && remoteEmfObserver.getConsumer() != this) { remoteEmfObserver.getConsumer().removeObserver(remoteEmfObserver); } remoteEmfObserver.internalSetConsumer(this); remoteEmfObservers.add(observer); } }
Source:
public void testExecuteQueryRestWithEmptyOption() throws Exception { String query = "status:open"; String option = ""; List<GerritQueryResult> results = null; try { results = executeQueryRest(query, option); } catch (GerritException e) { START exception.expect(GerritHttpException.class); END exception.expectMessage(HTTP_ERROR_400); return; } assertNotNull(results); } Done

Target:
public void testExecuteQueryRestWithEmptyOption() throws Exception { String query = "status:open"; String option = ""; List<GerritQueryResult> results = null; results = executeQueryRest(query, option); assertNotNull(results); }
Source:
public void testExecuteQueryWithOption() throws Exception { String query = "status:open"; String option = "LABELS"; List<GerritQueryResult> results = executeQuery(query, option); START assertNotNull(results); END } These assertions don't help much to validate correctness of the returned result. Could we assert on the content?

Target:
public void testExecuteQueryWithOption() throws Exception { String query = "status:open"; String option = "LABELS"; List<GerritQueryResult> results = executeQuery(query, option); assertNotNull(results); for (int index = 0; index < results.size(); index++) { assertNotNull(results.get(index)); } }
Source:
public void setState(final String commandId, final boolean state) { START if (commandId.equals(IOutlineViewState.SHOW_ELEMENT_CONTENT)) { END showElementContent = state; } } Why is SHOW_ELEMENT_CONTENT part of the interface IOutlineViewState? The constant represents an action provided by the DefaultOutlineProvider implementation, and it is only used in conjunction with that implementation. The interface itself defines a very generic mechanism to set and retrieve the state of a given command. I think SHOW_ELEMENT_CONTENT belongs rather to the DefaultOutlineProvider than to the interface.

Target:
public void setState(final String commandId, final boolean state) { if (commandId.equals(SHOW_ELEMENT_CONTENT)) { showElementContent = state; } }
Source:
START public static void initializeOprofileModule() { END // Check if kernel module is loaded, if not, try to load it if (!isKernelModuleLoaded()) initializeOprofile(); //it still may not have loaded, if not, critical error if (!isKernelModuleLoaded()) { OprofileCorePlugin.showErrorDialog("oprofileInit", null); //$NON-NLS-1$ // throw new ExceptionInInitializerError(OprofileProperties.getString("fatal.kernelModuleNotLoaded")); //$NON-NLS-1$ } else { initializeOprofileCore(); } } Is there any reason this needs to be public API ? If the Oprofile class is loaded then it's likely that the oprofile kernel module is also loaded.

Target:
private static void initializeOprofileModule() { // Check if kernel module is loaded, if not, try to load it if (!isKernelModuleLoaded()) initializeOprofile(); //it still may not have loaded, if not, critical error if (!isKernelModuleLoaded()) { OprofileCorePlugin.showErrorDialog("oprofileInit", null); //$NON-NLS-1$ // throw new ExceptionInInitializerError(OprofileProperties.getString("fatal.kernelModuleNotLoaded")); //$NON-NLS-1$ } else { initializeOprofileCore(); } }
Source:
public CPPASTQualifiedName copy(CopyStyle style) { CPPASTQualifiedName copy = new CPPASTQualifiedName(); if (fLastName != null) copy.addName(fLastName.copy(style)); START for (ICPPASTNameSpecifier nameSpecifier : getQualifier()) END copy.addNameSpecifier(nameSpecifier == null ? null : nameSpecifier.copy(style)); copy.setFullyQualified(fIsFullyQualified); copy.setOffsetAndLength(this); if (style == CopyStyle.withLocations) { copy.setCopyLocation(this); } return copy; } Please always use curly braces in 'for' statements.

Target:
public CPPASTQualifiedName copy(CopyStyle style) { CPPASTQualifiedName copy = new CPPASTQualifiedName(); if (fLastName != null) copy.addName(fLastName.copy(style)); for (ICPPASTNameSpecifier nameSpecifier : getQualifier()) { copy.addNameSpecifier(nameSpecifier == null ? null : nameSpecifier.copy(style)); } copy.setFullyQualified(fIsFullyQualified); copy.setOffsetAndLength(this); if (style == CopyStyle.withLocations) { copy.setCopyLocation(this); } return copy; }
Source:
private IASTName getLastInQualified(IASTName name) { START if (name instanceof ICPPASTQualifiedName) { END name= name.getLastName(); } return name; } Redundant condition.

Target:
private IASTName getLastInQualified(IASTName name) { return name.getLastName(); }
Source:
protected EPackage createModel(EPackage parent, TestRemoteEPackage remotePackage) { EPackage pckg = EcoreFactory.eINSTANCE.createEPackage(); pckg.setName(remotePackage.name.replaceAll("Remote", "Local")); START System.err.println(pckg); END return pckg; } Remove as in https://git.eclipse.org/r/#/c/15004/9

Target:
protected EPackage createModel(EPackage parent, TestRemoteEPackage remotePackage) { EPackage pckg = EcoreFactory.eINSTANCE.createEPackage(); pckg.setName(remotePackage.name.replaceAll("Remote", "Local")); return pckg; }
Source:
START public boolean hasTasks() { END return !(fForegroundTasks.isEmpty() && fBackgroundTasks.isEmpty()); } This could be private too.

Target:
private boolean hasTasks() { return !(fForegroundTasks.isEmpty() && fBackgroundTasks.isEmpty()); }
Source:
START public static KeyStroke getKeystrokeOfBestActiveBindingFor(String commandId) { END KeyStroke stroke = null; IBindingService bindingService = (IBindingService) PlatformUI .getWorkbench().getAdapter(IBindingService.class); TriggerSequence ts = bindingService .getBestActiveBindingFor("org.eclipse.ui.edit.text.contentAssist.proposals"); //$NON-NLS-1$ if (ts == null) return null; Trigger[] triggers = ts.getTriggers(); for (Trigger t : triggers) { if (t instanceof KeyStroke) stroke = (KeyStroke) t; } return stroke; } commandId is not used in the method. Either the string below should be replaced or we should remove the parameter and rename it to "getContentAssistKeystroke".

Target:
public static KeyStroke getKeystrokeOfBestActiveBindingFor(String commandId) { IBindingService bindingService = (IBindingService) PlatformUI .getWorkbench().getAdapter(IBindingService.class); TriggerSequence ts = bindingService.getBestActiveBindingFor(commandId); if (ts == null) return null; Trigger[] triggers = ts.getTriggers(); if (triggers.length == 1 && triggers[0] instanceof KeyStroke) return (KeyStroke) triggers[0]; else return null; }
Source:
public void add(Integer art_id, Integer branchId, Integer transactionId) { START this.branchId = branchId; END entries.add(new Entry(art_id, branchId, transactionId)); } Is it impossible for add to be called with different branch ids? That is, called once with id = 1 then with id = 2. If so, this is the last branch ID. Is that the intent?

Target:
public void add(Integer art_id, Integer branchId, Integer transactionId) { entries.add(new Entry(art_id, branchId, transactionId)); }
Source:
public boolean isBranchesAllCommittedExcept(Artifact art, Branch branch) { boolean toReturn = false; try { START toReturn = AtsBranchManagerCore.isBranchesAllCommittedExcept((TeamWorkFlowArtifact) art, branch); END } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex.toString(), ex); toReturn = false; } return toReturn; } Should there be a second catch for ClassCastException? is art checked somewhere to verify that it is always a teamWorkFlowArtifact?

Target:
public boolean isBranchesAllCommittedExcept(Artifact art, Branch branch) { boolean toReturn = false; if (art instanceof TeamWorkFlowArtifact) { try { toReturn = AtsBranchManagerCore.isBranchesAllCommittedExcept((TeamWorkFlowArtifact) art, branch); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex.toString(), ex); toReturn = false; } } return toReturn; }
Source:
public void commitBranch(Artifact art, Branch branch, boolean isArchiveSource) { IOperation operation; try { operation = START AtsBranchManager.commitWorkingBranch((TeamWorkFlowArtifact) art, false, false, branch, isArchiveSource); END Operations.executeAsJob(operation, true); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex.toString(), ex); } } Should there be a second catch for ClassCastException? is art checked somewhere to verify that it is always a teamWorkFlowArtifact?

Target:
public void commitBranch(Artifact art, Branch branch, boolean isArchiveSource) { if (art instanceof TeamWorkFlowArtifact) { IOperation operation; try { operation = AtsBranchManager.commitWorkingBranch((TeamWorkFlowArtifact) art, false, false, branch, isArchiveSource); Operations.executeAsJob(operation, true); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex.toString(), ex); } } }
Source:
public Change perform(IProgressMonitor pm) throws CoreException { Resource roomRes = rs.getResources().get(0); // resolve all cross references START for(Resource res : rs.getResources()) END if(res != roomRes) EcoreUtil.resolveAll(res); // change uri of room objects roomRes.setURI(newURI); // perform child changes (and create undo changes): // save only diagrams to change cross references Change undoChange = super.perform(pm); return undoChange; } the resource list will change during resolution if additional resources have been loaded. In this case a concurrent modification exception is thrown. I nevertheless accept the change and fix the bug by replacing the loop with EcoreUtil.resolveAll(rs); This handles the room file as well. Should that cause any problem?

Target:
public Change perform(IProgressMonitor pm) throws CoreException { Resource roomRes = rs.getResources().get(0); // resolve all cross references EcoreUtil.resolveAll(rs); // change uri of room objects roomRes.setURI(newURI); // perform child changes (and create undo changes): // save only diagrams to change cross references Change undoChange = super.perform(pm); return undoChange; }
Source:
public DebugStringVariableSubstitutor(String projectName) { START this(projectName == null ? null : projectName.isEmpty() ? null : ResourcesPlugin.getWorkspace().getRoot().getProject(projectName)); END } Probably slightly better: projectName == null || projectName.isEmpty() ? null ... Why is projectName empty instead of null for projectless debugging? Should this itself be changed?

Target:
public DebugStringVariableSubstitutor(String projectName) { this(projectName == null || projectName.isEmpty() ? null : ResourcesPlugin.getWorkspace().getRoot().getProject(projectName)); }
Source:
AbstractDataManipulator (String title, IPath pathWorkDir, IProject project) { START this.title = title; END this.pathWorkDir=pathWorkDir; this.project=project; threads = new ArrayList<Thread>(); } This should be simplified to : super(title, pathWorkingDir); this.project = project;

Target:
AbstractDataManipulator (String title, IPath pathWorkDir, IProject project) { this(title, pathWorkDir); this.project=project; }
Source:
public String getColumnText(MyModel element, int columnIndex) { START if (element instanceof MyModel) { END switch (columnIndex) { case 0: return ((MyModel)element).col1; case 1: return ((MyModel)element).col2; } } return ""; } Strange check

Target:
public String getColumnText(MyModel element, int columnIndex) { switch (columnIndex) { case 0: return element.col1; case 1: return element.col2; } return ""; }
Source:
synchronized PackBitmapIndex getBitmapIndex() throws IOException { if (invalid || invalidBitmap) return null; if (bitmapIdx == null && hasExt(BITMAP_INDEX)) { final PackBitmapIndex idx = PackBitmapIndex.open( extFile(BITMAP_INDEX), idx(), getReverseIdx()); // At this point, idx() will have set packChecksum. START if (!Arrays.equals(packChecksum, idx.packChecksum)) END invalidBitmap = true; else bitmapIdx = idx; } return bitmapIdx; } if not its good, do the bad, else do the good?

Target:
synchronized PackBitmapIndex getBitmapIndex() throws IOException { if (invalid || invalidBitmap) return null; if (bitmapIdx == null && hasExt(BITMAP_INDEX)) { final PackBitmapIndex idx = PackBitmapIndex.open( extFile(BITMAP_INDEX), idx(), getReverseIdx()); // At this point, idx() will have set packChecksum. if (Arrays.equals(packChecksum, idx.packChecksum)) bitmapIdx = idx; else invalidBitmap = true; } return bitmapIdx; }
Source:
protected AbstractRebaseCommandHandler(String jobname, String dialogMessage) { this.dialogMessage = dialogMessage; START this.jobname = jobname; END } you unnecessarily flipped the order of these two statements which makes the diff unnecessarily larger

Target:
protected AbstractRebaseCommandHandler(String jobname, String dialogMessage) { this.jobname = jobname; this.dialogMessage = dialogMessage; }
Source:
public RebaseOperation(Repository repository, Operation operation) { START Assert.isTrue(operation != Operation.BEGIN); END this.repository = repository; this.operation = operation; this.ref = null; } where did this come from ? you claim this is a refactoring

Target:
public RebaseOperation(Repository repository, Operation operation) { this.repository = repository; this.operation = operation; this.ref = null; }
Source:
protected boolean isDragEnabled() { if (getScoutObject() != null) { return getScoutObject().isDragEnabled(); } else { START return false; END } } You can omit the explicit else-case and "return false" directly instead.

Target:
protected boolean isDragEnabled() { if (getScoutObject() != null) { return getScoutObject().isDragEnabled(); } return false; }
Source:
public boolean validate(String path) { boolean valid = false; if (fTrace != null) { valid = standardValidate(path); } else if (TmfTraceType.isCustomTraceId(getCanonicalName())) { START valid = customValidate(path); END } return valid; } I don't think we need this anymore. (we may be able to kill customValidate(String bla) also. woooooooooooOOOOOOOOOOOOOoooooooooooooOOOOOOOOOOoooooooOOOOOOOOOoooooOOOOOOOOoooooOOOOOOoooooOOOOOoooooo

Target:
public boolean validate(String path) { boolean valid = false; if (fTrace != null) { valid = standardValidate(path); } return valid; }
Source:
public Object getAdapter(Object adaptableObject, Class adapterType) { if (adapterType == IPropertySheetPage.class) { if (propertySheetPage == null) { if (adaptableObject instanceof CompareEditor) { IEditorInput editorInput = ((CompareEditor)adaptableObject).getEditorInput(); if (editorInput instanceof CompareEditorInput) { propertySheetPage = new ExtendedPropertySheetPage(null); START CompareConfiguration configuration = ((CompareEditorInput)editorInput) END .getCompareConfiguration(); } } } return propertySheetPage; } return null; } Remove this line too because the variable "configuration" will become useless.

Target:
public Object getAdapter(Object adaptableObject, Class adapterType) { if (adapterType == IPropertySheetPage.class) { if (propertySheetPage == null) { if (adaptableObject instanceof CompareEditor) { IEditorInput editorInput = ((CompareEditor)adaptableObject).getEditorInput(); if (editorInput instanceof CompareEditorInput) { propertySheetPage = new ExtendedPropertySheetPage(null); } } } return propertySheetPage; } return null; }
Source:
START public static void generateTrace() { END List<String> processes = new ArrayList<String>(); for (String s : sfProcesses) { processes.add(s); } final int cpus = 25; GenerateKernelTrace gt = new GenerateKernelTrace(processes, 2l * Integer.MAX_VALUE - 100, 500000, cpus); gt.writeTrace(PATH); } delete the old file when a new one is generated? It's nice behavior to clean up our mess. Or use .deleteOnExit, if some tests might still be using the old file.

Target:
public static void generateTrace() { final int cpus = 25; GenerateKernelTrace gt = new GenerateKernelTrace(2l * Integer.MAX_VALUE - 100, 500000, cpus); gt.writeTrace(PATH); }
Source:
private String getImplementationVersion() { Package pkg = getClass().getPackage(); START if (pkg != null) { END return pkg.getImplementationVersion(); } return null; } Style nit: no braces here

Target:
private String getImplementationVersion() { Package pkg = getClass().getPackage(); return (pkg == null) ? null : pkg.getImplementationVersion(); }
Source:
public static URI createURIFor(IFile file) { // whether it exists or not (no longer), use platform:/resource final URI uri; String fullPath = file.getFullPath().toString(); START if (isAlreadyEncoded(fullPath)) { END uri = URI.createPlatformResourceURI(fullPath, false); } else { uri = URI.createPlatformResourceURI(fullPath, true); } return uri; } An IFile's full path is never encoded, except if we created it as such. Here, too, the bug is much higher in the call stack and should be handled there instead of trying to tackle the cause here. This will avoid it to slip through the cracks and be repeated elsewhere.

Target:
public static URI createURIFor(IFile file) { // whether it exists or not (no longer), use platform:/resource return URI.createPlatformResourceURI(file.getFullPath().toString(), true); }
Source:
protected Session getSession(URI sessionModelURI) { START Session sessionFromURI = null; END try { sessionFromURI = SessionManager.INSTANCE.getSession(sessionModelURI); if (sessionFromURI != null) { if (!sessionFromURI.isOpen()) { sessionFromURI.open(new NullProgressMonitor()); } IEditingSession uiSession = SessionUIManager.INSTANCE.getOrCreateUISession(sessionFromURI); uiSession.open(); } } catch (IllegalStateException e) { // Silent catch: can happen if failing to retrieve the session from // its URI } return sessionFromURI; } Maybe it's just me but the combination of a default null value and later a silent catch (which does nothing but relies on the earlier initialization to set the correct value) looks confusing. How about something like this: final Session sessionFromURI; try { sessionFromURI = ...; ... } catch (IllegalStateException e) { sessionFromURI = null; // maybe also log the error? } This makes it clearer that "when an error occurs we return null" (IMHO).

Target:
protected Session getSession(URI sessionModelURI) { Session sessionFromURI; try { sessionFromURI = SessionManager.INSTANCE.getSession(sessionModelURI); if (sessionFromURI != null) { if (!sessionFromURI.isOpen()) { sessionFromURI.open(new NullProgressMonitor()); } IEditingSession uiSession = SessionUIManager.INSTANCE.getOrCreateUISession(sessionFromURI); uiSession.open(); } } catch (IllegalStateException e) { sessionFromURI = null; // Silent catch: can happen if failing to retrieve the session from // its URI } return sessionFromURI; }
Source:
public String toString() { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.print("HashSettings:"); for(Map.Entry<String, String> e : settings.entrySet()) START pw.print(e.getKey()+"="+e.getValue()+";"); END pw.close(); return sw.toString(); } Add brackets around loop body (required by code conventions).

Target:
public String toString() { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.print("HashSettings:"); //$NON-NLS-1$ for(Map.Entry<String, String> e : settings.entrySet()) { pw.print(e.getKey()+"="+e.getValue()+";"); //$NON-NLS-1$ //$NON-NLS-2$ } pw.close(); return sw.toString(); }
Source:
public RemoteConnector(RemoteSettings settings) { fSettings = settings; START new Throwable().printStackTrace(); END } Please remove.

Target:
public RemoteConnector(RemoteSettings settings) { fSettings = settings; }
Source:
START public TerminalInfoView() { END addToList(this); } Should call super() here.

Target:
public TerminalInfoView() { super(); addToList(this); }
Source:
START String getDefault(String val, String defaultVal) { END if(val == null || val.trim().equals("")) { //$NON-NLS-1$ return defaultVal; } else { return val; } } Should be private.

Target:
private String getDefault(String val, String defaultVal) { if (val == null || val.trim().equals("")) { //$NON-NLS-1$ return defaultVal; } else { return val; } }
Source:
START synchronized public void doDisconnect() { END if (getInputStream() != null) { try { getInputStream().close(); } catch (Exception exception) { Activator.log(exception); } } if (getTerminalToRemoteStream() != null) { try { getTerminalToRemoteStream().close(); } catch (Exception exception) { Activator.log(exception); } } } public synchronized

Target:
public synchronized void doDisconnect() { if (getInputStream() != null) { try { getInputStream().close(); } catch (Exception exception) { Activator.log(exception); } } if (getTerminalToRemoteStream() != null) { try { getTerminalToRemoteStream().close(); } catch (Exception exception) { Activator.log(exception); } } }
Source:
START static synchronized void addToList(TerminalInfoView view) { END views.add(view); } Visibility missing. Synchronized comes before static

Target:
private static synchronized void addToList(TerminalInfoView view) { views.add(view); }
Source:
START static void alignRead(BitBuffer input, IDeclaration declaration){ END int align = (int) declaration.getAlignment(); int pos = input.position() + ((align - (input.position() % align)) % align); input.position(pos); } "protected" would be more appropriate, it's meant to be used by sub-classes of Definition, no matter which package they are in. Minor thing.

Target:
protected static void alignRead(BitBuffer input, IDeclaration declaration){ int align = (int) declaration.getAlignment(); int pos = input.position() + ((align - (input.position() % align)) % align); input.position(pos); }
Source:
public void init(String name, Class<? extends ITmfEvent> type) { super.init(name); fType = type; fDataQueue = (fQueueSize > 1) ? new LinkedBlockingQueue<ITmfEvent>(fQueueSize) : new SynchronousQueue<ITmfEvent>(); START if (fExecutor != null) { END fExecutor.stop(); } fExecutor = new TmfRequestExecutor(); fSignalDepth = 0; fLogData = TmfCoreTracer.isEventTraced(); // fLogError = TmfCoreTracer.isErrorTraced(); TmfProviderManager.register(fType, this); } Do we actually call init multiple times on a trace or is it a safe-guard? Just curious.

Target:
public void init(String name, Class<? extends ITmfEvent> type) { super.init(name); fType = type; fDataQueue = (fQueueSize > 1) ? new LinkedBlockingQueue<ITmfEvent>(fQueueSize) : new SynchronousQueue<ITmfEvent>(); fExecutor.init(); fSignalDepth = 0; fLogData = TmfCoreTracer.isEventTraced(); // fLogError = TmfCoreTracer.isErrorTraced(); TmfProviderManager.register(fType, this); }
Source:
private TmfTraceManager() { fTraces = new LinkedHashMap<ITmfTrace, TmfTraceContext>(); START fFilters = new LinkedHashMap<ITmfTrace, ITmfFilter>(); END TmfSignalManager.registerVIP(this); } I think the filter should be part of the TmfTraceContext. Please move it there.

Target:
private TmfTraceManager() { fTraces = new LinkedHashMap<ITmfTrace, TmfTraceContext>(); TmfSignalManager.registerVIP(this); }
Source:
public void setPriorities(List<RuleSpecification<?>> ruleSpecGroup) { START priorities.clear(); END int priority = ruleSpecGroup.size() + priorities.size(); for (RuleSpecification<?> rule : ruleSpecGroup) { this.setPriority(rule, priority); priority--; } } remove clear() call (probably left over from refactor)

Target:
public void setPriorities(List<RuleSpecification<?>> ruleSpecGroup) { int priority = ruleSpecGroup.size() + priorities.size(); for (RuleSpecification<?> rule : ruleSpecGroup) { this.setPriority(rule, priority); priority--; } }
Source:
public EventDrivenTransformationRule(String name, IQuerySpecification<Matcher> precondition, IMatchProcessor<Match> action, IncQueryActivationStateEnum transition, ActivationLifeCycle lifeCycle) { Job<Match> stJob = Jobs.newStatelessJob(transition, action); START Job<Match> job = Jobs.newRecordingJob(stJob); END ruleSpecification = Rules.newMatcherRuleSpecification(precondition, lifeCycle, CollectionLiterals.newHashSet(job)); } default usage of recording job seems problematic, please remove. The model editing API should handle editing domains and such

Target:
public EventDrivenTransformationRule(String name, IQuerySpecification<Matcher> precondition, IMatchProcessor<Match> action, IncQueryActivationStateEnum transition, ActivationLifeCycle lifeCycle) { Job<Match> job = Jobs.newStatelessJob(transition, action); ruleSpecification = Rules.newMatcherRuleSpecification(precondition, lifeCycle, CollectionLiterals.newHashSet(job)); }
Source:
public boolean isPaused() { synchronized (fSynchObject) { START return fIsPaused; END } } Accesses to volatile primitives are guaranteed to be atomic (as long as you don't depend on the current value itself). So the synchronized block is redundant here. Good reference on the volatile keyword: https://www.ibm.com/developerworks/java/library/j-jtp06197/

Target:
public boolean isPaused() { return fIsPaused; }
Source:
public synchronized void suspend() { START synchronized (fSynchObject) { END fIsPaused = true; } TmfCoreTracer.traceRequest(fRequest, "SUSPENDED"); //$NON-NLS-1$ } synchronized block is not needed

Target:
public void suspend() { fIsPaused = true; TmfCoreTracer.traceRequest(fRequest, "SUSPENDED"); //$NON-NLS-1$ }
Source:
public EvalBinding(IBinding binding, IType type, IBinding templateDefinition) { super(templateDefinition); fParameterPosition = -1; fBinding= binding; fType= type; fFixedType= type != null; if (fBinding == null) { START CCorePlugin.log(new NullPointerException()); END } } Please add a TODO to replace logging with throwing NPE.

Target:
public EvalBinding(IBinding binding, IType type, IBinding templateDefinition) { super(templateDefinition); fParameterPosition = -1; fBinding= binding; fType= type; fFixedType= type != null; }
Source:
public void cleanupTraces() { TmfTestTrace.A_TEST_10K.dispose(); START CtfTmfTestTrace.KERNEL.dispose(); END } For symmetry's sake, it'd be better to load those (the .getTrace()) in a @Before method.

Target:
public void cleanupTraces() { TmfTestTrace.A_TEST_10K.dispose(); }
Source:
START protected Double getDoubleValue(Object o) { END if (o == null) { return null; } if (o instanceof Integer) { return (double) ((Integer)o).intValue(); } if (o instanceof Double) { return ((Double)o).doubleValue(); } try { return new Double(o.toString()).doubleValue(); } catch (NumberFormatException e) { return null; } } You have changed the return type to Double but below you act like you are still returning double. For example, when the value is Double, you are getting its doubleValue() instead of just returning the object cast to Double.

Target:
protected Double getDoubleValue(Object o) { if (o == null) { return null; } if (o instanceof Integer) { return ((Integer)o).doubleValue(); } if (o instanceof Double) { return (Double) o; } try { return new Double(o.toString()); } catch (NumberFormatException e) { return null; } }
Source:
public String toString() { return String.format("title = [ %s ], author = [ %s ], company = [ %s ]", title.toString(), author.toString(), START company.toString()); END } I don't think we need to call .toString() on objects passed to String.format - the method does that internally.

Target:
public String toString() { return String.format("title = [ %s ], author = [ %s ], company = [ %s ]", title, author, company); }
Source:
private void addRepository(File repositoryDir) { util.addConfiguredRepository(repositoryDir); START if (doAutoShare()) { END autoShareProjects(repositoryDir); } } style nit: no braces around single line block

Target:
private void addRepository(File repositoryDir) { util.addConfiguredRepository(repositoryDir); if (doAutoShare()) autoShareProjects(repositoryDir); }
Source:
START public boolean equals(Object obj) { END return obj instanceof ResourceByDefinitionKey && key.hashCode() == obj.hashCode(); } This isn't enough to guarantee equality. key could implement hashCode()==1 and then this would be broken. You have to at least do key.equals(obj.key)

Target:
public boolean equals(Object obj) { return obj instanceof ResourceByDefinitionKey && key.equals(((ResourceByDefinitionKey) obj).key); }
Source:
public IInputOrder getInputOrder(String path) { // TODO Convert both paths to absolute? for (InputOrder io : getInputOrderList()) { String ioPath = (new START Path(io.getPath())).toOSString(); END if (path.compareToIgnoreCase(ioPath) == 0) { return io; } } return null; } Guy, perhaps you missed my question on the first patch? I'll copied it here: "Why the toOSString? Sorry I'm not very familiar with this code and I don't see it getting called in the CDT code. Does the path parameter always have the os separators? It sounds like this would make it host dependent. I'm thinking of a case where the host is Windows and the toolchain works remotely on Linux."

Target:
public IInputOrder getInputOrder(String path) { // TODO Convert both paths to absolute? for (InputOrder io : getInputOrderList()) { if (path.compareToIgnoreCase(io.getPath()) == 0) { return io; } } return null; }
Source:
private void createDiff(RevCommit parent) { Diff diff = revision.getDiffToParent(parent); if (diff != null) { try { createDiffLinkAndText(parent, diff); } catch (IOException e) { Activator.logError( START "Error creating diff in blame information control for commit " + parent.toObjectId(), e); //$NON-NLS-1$ END } } } Line is too long

Target:
private void createDiff(RevCommit parent) { Diff diff = revision.getDiffToParent(parent); if (diff != null) { try { createDiffLinkAndText(parent, diff); } catch (IOException e) { String msg = "Error creating diff in blame information control for commit " //$NON-NLS-1$ + parent.toObjectId(); Activator.logError(msg, e); } } }
Source:
public PushTagsPage(Repository repository, Collection<String> tagNamesToSelect) { super(UIText.PushTagsPage_PageName); setTitle(UIText.PushTagsPage_PageTitle); setMessage(UIText.PushTagsPage_PageMessage); this.repository = repository; for (String tagName : tagNamesToSelect) { START if (tagName.startsWith(Constants.R_TAGS)) { END tagRefNamesToSelect.add(tagName); } else { tagRefNamesToSelect.add(Constants.R_TAGS + tagName); } } } style nit: no braces here

Target:
public PushTagsPage(Repository repository, Collection<String> tagNamesToSelect) { super(UIText.PushTagsPage_PageName); setTitle(UIText.PushTagsPage_PageTitle); setMessage(UIText.PushTagsPage_PageMessage); this.repository = repository; for (String tagName : tagNamesToSelect) { if (tagName.startsWith(Constants.R_TAGS)) tagRefNamesToSelect.add(tagName); else tagRefNamesToSelect.add(Constants.R_TAGS + tagName); } }
Source:
private void setWindowTitle(boolean pushMode) { final String title; if (pushMode) { title = UIText.RefSpecWizard_pushTitle; } else { title = UIText.RefSpecWizard_fetchTitle; START } END setWindowTitle(title); } We don't use braces ({}) for such simple one-line statements, please remove them.

Target:
private void setWindowTitle(boolean pushMode) { final String title; if (pushMode) title = UIText.RefSpecWizard_pushTitle; else title = UIText.RefSpecWizard_fetchTitle; setWindowTitle(title); }
Source:
public IAtsUser getTransitionAsUser() throws OseeCoreException { IAtsUser user = helper.getTransitionUser(); if (user == null) { START System.err.println("Unexpected: AtsCore.getUserService().getCurrentUser();"); END user = AtsCore.getUserService().getCurrentUser(); } return user; } Should this be a thrown exception?

Target:
public IAtsUser getTransitionAsUser() throws OseeCoreException { IAtsUser user = helper.getTransitionUser(); if (user == null) { user = AtsCore.getUserService().getCurrentUser(); } return user; }
Source:
private List<String> getRepoTags() { if (projectPreferences != null) { String tagPref = projectPreferences.get(CreaterepoPreferenceConstants.PREF_REPO_TAG, ICreaterepoConstants.EMPTY_STRING); if (!tagPref.isEmpty()) { return Arrays.asList(tagPref.split(ICreaterepoConstants.DELIMITER)); } } START return ICreaterepoConstants.EMPTY_LIST; END } Do we need this constant at all? Isn't Collections.emptyList() sufficient?

Target:
private List<String> getRepoTags() { if (projectPreferences != null) { String tagPref = projectPreferences.get(CreaterepoPreferenceConstants.PREF_REPO_TAG, ICreaterepoConstants.EMPTY_STRING); if (!tagPref.isEmpty()) { return Arrays.asList(tagPref.split(ICreaterepoConstants.DELIMITER)); } } return Collections.EMPTY_LIST; }
Source:
public void setUp() throws CTFReaderException { START fixture = new BitBuffer(java.nio.ByteBuffer.allocateDirect(128)); END fixture.setByteOrder(ByteOrder.BIG_ENDIAN); createBuffer(fixture); } We import it already, no need for the java.nio part.

Target:
public void setUp() throws CTFReaderException { fixture = new BitBuffer(ByteBuffer.allocateDirect(128)); fixture.setByteOrder(ByteOrder.BIG_ENDIAN); createBuffer(fixture); }
Source:
public IntegerStateValue(int valueAsInt) { START this.value = new Integer(valueAsInt); END } I assume you don't want to re-box it? ;) (btw, I learned that recently, in almost all cases it's better to do Integer.valueOf(int) rather than new Integer(int), because valueOf will cache the most often-used values, and new Integer() will create a new object every time.)

Target:
public IntegerStateValue(int valueAsInt) { this.value = valueAsInt; }
Source:
public boolean equals(@Nullable Object object) { if (!(object instanceof IntegerStateValue)) { return false; } IntegerStateValue other = (IntegerStateValue) object; START return this.unboxInt() == other.unboxInt(); END } you could use this.value == other.value here, and in the other classes too. Would save one function call, I guess?

Target:
public boolean equals(@Nullable Object object) { if (!(object instanceof IntegerStateValue)) { return false; } IntegerStateValue other = (IntegerStateValue) object; return this.value == other.value; }
Source:
START public String getFormattedValue() { END if (formattedValue == null) { List<String> strings = new ArrayList<String>(); for (CtfTmfEventField element : getValue()) { strings.add(element.getFormattedValue()); } formattedValue = strings.toString(); } return formattedValue; } Method could be marked 'synchronized' (to ensure only one caller gets to build the array). Minor issue, because it will work either way, but it'd make it look like we actually look out for these things ;) I guess we'll have to fix IntegerArrayField too.

Target:
public synchronized String getFormattedValue() { if (formattedValue == null) { List<String> strings = new ArrayList<String>(); for (CtfTmfEventField element : getValue()) { strings.add(element.getFormattedValue()); } formattedValue = strings.toString(); } return formattedValue; }
Source:
private Set<String> getStringSet(String key) { String prefSetting = getIndexer().getProperty(key); START if (prefSetting != null && prefSetting.length() > 0) { END return new HashSet<String>(Arrays.asList(prefSetting.split(","))); //$NON-NLS-1$ } return Collections.emptySet(); } Better: prefSetting != null && !prefSetting.isEmpty()

Target:
private Set<String> getStringSet(String key) { String prefSetting = getIndexer().getProperty(key); if (prefSetting != null && !prefSetting.isEmpty()) { return new HashSet<String>(Arrays.asList(prefSetting.split(","))); //$NON-NLS-1$ } return Collections.emptySet(); }
Source:
START private String getHeadName(Ref head) { END String headName; if (head.isSymbolic()) headName = head.getTarget().getName(); else headName = head.getObjectId().getName(); return headName; } this method can be declared static

Target:
private static String getHeadName(Ref head) { String headName; if (head.isSymbolic()) headName = head.getTarget().getName(); else headName = head.getObjectId().getName(); return headName; }
Source:
public void testSetValue() { fixture.setValue("dummy"); String result = fixture.getValue(); assertNotNull(result); START assertEquals(result, "dummy"); END } the order of arguments in assert*() is counter-intuitive... it's (expected, actual). Technically the 'result' variables should always be second.

Target:
public void testSetValue() { fixture.setValue("dummy"); String result = fixture.getValue(); assertNotNull(result); assertEquals("dummy", result); }
Source:
public void decorateHeaderCell() { HeaderCell cell = m_headerCell; decorateHeaderCellInternal(cell); try { execDecorateHeaderCell(cell); START getTable().getColumnSet().updateColumn(this); END } catch (ProcessingException e) { LOG.warn(null, e); } catch (Throwable t) { LOG.warn(null, t); } } this can give a NullPointerException since getTable() can return null

Target:
public void decorateHeaderCell() { HeaderCell cell = m_headerCell; decorateHeaderCellInternal(cell); try { execDecorateHeaderCell(cell); if (getTable() != null && getTable().getColumnSet() != null) { getTable().getColumnSet().updateColumn(this); } } catch (ProcessingException e) { LOG.warn(null, e); } catch (Throwable t) { LOG.warn(null, t); } }
Source:
public boolean isModified(DirCacheEntry entry, boolean forceContentCheck) { START return isModified(null, false, null); END } Why does it pass null instead of entry here?

Target:
public boolean isModified(DirCacheEntry entry, boolean forceContentCheck) { return isModified(entry, false, null); }
Source:
protected @NonNull ITmfStateProvider createStateProvider() { ITmfTrace trace = getTrace(); START if (!(trace instanceof LttngKernelTrace)) { END throw new IllegalStateException("LttngKernelStateSystemModule: trace should be of type LttngKernelTrace"); //$NON-NLS-1$ } return new LttngKernelStateProvider((LttngKernelTrace) trace); } This check should be moved to setTrace() (overridden version which then calls super.setTrace()). Then getTrace() can be overridden in this class to always return a LttngKernelTrace.

Target:
protected @NonNull ITmfStateProvider createStateProvider() { return new LttngKernelStateProvider(getTrace()); }
Source:
public String getHelpText() { START return new String(); END } You should instead use return ""; It would avoid creating new objects everytime the method is called, since all "" refer to the same object (string literals get internalized). Or you can have a private static final String EMTPY_STRING = ""; in your class and use that instead, if you use a lot of them in the same file.

Target:
public String getHelpText() { return ""; }
Source:
public GdbMemoryBlockRetrievalManager(String modelId, ILaunchConfiguration config, DsfSession session) START throws DebugException { END fModelId = modelId; fSession = session; fLaunchConfig = config; } Why throw an exception?

Target:
public GdbMemoryBlockRetrievalManager(String modelId, ILaunchConfiguration config, DsfSession session) { fModelId = modelId; fSession = session; fLaunchConfig = config; }
Source:
private PositionInfo findMovePositionInfo(MUIElement element) { if (element != null) { for (String tag : element.getTags()) { if (tag.startsWith(MOVE_TAG)) { START return PositionInfo.parse(tag.substring(5)); END } } } return null; } The substring(#) should be calculated against the MOVE_TAG

Target:
private PositionInfo findMovePositionInfo(MUIElement element) { if (element != null) { for (String tag : element.getTags()) { if (tag.startsWith(MOVE_TAG)) { return PositionInfo.parse(tag.substring(MOVE_TAG.length())); } } } return null; }