auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public BasicSymbolProviderPreferencePage(@NonNull BasicSymbolProvider provider) { super(provider); setDescription(MessageFormat.format(Messages.BasicSymbolProviderPrefPage_description, provider.getTrace().getName())); setValid(true); setTitle(MessageFormat.format(Messages.BasicSymbolProviderPrefPage_tabTitle, "GNU nm", provider.getTrace().getName())); //$NON-NLS-1$ }

Target:
externalize this.
Source:
protected boolean considerEvent(ITmfEvent event) { if (!(event instanceof CtfTmfEvent)) { return false; } Object tid = TmfTraceUtils.resolveEventAspectOfClassForEvent(event.getTrace(), LinuxTidAspect.class, event); if (!(tid instanceof Number)) { return false; } return true; }

Target:
return tid instanceof Number;?
Source:
public boolean appliesTo(Object selection) { EObject eo = EMFHelper.getEObject(selection); if (eo != null && eo instanceof Element) { return UMLRTProfileUtils.isUMLRTProfileApplied((Element) eo); } return false; }

Target:
Don't need this condition (null is not an instance of any class)
Source:
private void copyPathOfSelectionToClipboard(final TreeViewer viewer) { Clipboard cb = new Clipboard(viewer.getControl().getDisplay()); TextTransfer t = TextTransfer.getInstance(); String text = getTextFrom( (IStructuredSelection) viewer.getSelection()); if (text == null) { return; } else { cb.setContents(new Object[] { text }, new Transfer[] { t }); } cb.dispose(); }

Target:
No, that doesn't dispose cb.
Source:
public ViewpointSelectionCallbackWithConfimationAndDependenciesHandling() { super(); this.askUserForDependencyActivation = true; }

Target:
Should be "this(true)".
Source:
private String getRepositoryName(String location) { final String[] tokens = location.split(SEPARATOR); return (location.endsWith(GIT_EXTENSION)) ? tokens[4].substring(0, tokens[4].length() - 4) : tokens[4].substring(0); }

Target:
still you cannot be sure to have 5 tokens. you need to query that first
Source:
public WordTemplateContentRendererHandler(OrcsApi orcsApi, Log logger) { this.orcsApi = orcsApi; this.logger = logger; this.applicHandler = null; }

Target:
unnecessary
Source:
public void testDynamicImport() throws Exception { File testData = getTestData("dymamicImport", "testData/dynamicImport"); IInstallableUnit iu = BundlesAction.createBundleIU(BundlesAction.createBundleDescription(testData), null, new PublisherInfo()); Collection<IRequirement> requirements = iu.getRequirements(); for (IRequirement req : requirements) System.out.println("------> " + req); verifyRequirement(requirements, TESTDYN_REQ_EE_FILTER, 0, 1, true); assertEquals(1, requirements.size()); }

Target:
Please remove this debugging sysout.
Source:
public Collection<CallStackSeries> getCallStackSeries() { Collection<CallStackSeries> callstacks = fCallStacks; if (callstacks == null) { ITmfStateSystem ss = getStateSystem(); if (ss == null) { return Objects.requireNonNull(Collections.emptyList()); } callstacks = Collections.singleton(new CallStackSeries(ss, PATTERNS, 0, "", getHostId(), new CallStackSeries.AttributeValueThreadResolver(1))); //$NON-NLS-1$ fCallStacks = callstacks; } return callstacks; }

Target:
Not required, it's annotated
Source:
protected WorkbenchJob doCreateRefreshJob() { WorkbenchJob job = super.doCreateRefreshJob(); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { CheckboxTreeViewer checkboxTreeViewer = getCheckboxTreeViewer(); if (checkboxTreeViewer.getTree().isDisposed()) { return; } checkboxTreeViewer.expandAll(); checkboxTreeViewer.setCheckedElements(getCheckedElements()); maintainAllCheckIntegrity(); } }); return job; }

Target:
I'm not sure why the base class does these two actions, but in any case, it's not necessary here because the base class's JobChangeAdapter will do it anyways.
Source:
public void testMigrationIsNeededOnData() { Version migrationVersion = new SnapBackDistantLabelsMigrationParticipant().getMigrationVersion(); // Check that the migration of the session resource is needed. Version loadedVersion = checkRepresentationFileMigrationStatus(URI.createPlatformResourceURI(SiriusTestCase.TEMPORARY_PROJECT_NAME + "/" + SESSION_RESOURCE_NAME, true), true); assertTrue("The migration must be required on test data.", loadedVersion == null || migrationVersion.compareTo(loadedVersion) > 0); }

Target:
We should not have a null loaded version. If it is the case we should rather update this test
Source:
private static boolean validateTimeRange() { boolean isEmpty = fStartTimeRangeText.getText().isEmpty() || fEndTimeRangeText.getText().isEmpty(); return parseTimeRange() && fStartTimestamp.compareTo(fEndTimestamp) <= 0 && !isEmpty; }

Target:
should be first in the line, so that it returns if isEmpty, without trying to parse
Source:
public @Nullable T resolve(ITmfEvent event) { for (ITmfEventAspect<?> aspect : fAspects) { Object resolve = aspect.resolve(event); if (resolve != null && resolve.getClass().isAssignableFrom(fClazz.getClass())) { return (T) resolve; } } return null; }

Target:
shouldn't this filter go in the constructor?
Source:
public static Iterable<ITmfEventAspect<?>> getEventAspects(ITmfTrace trace, Class<? extends ITmfEventAspect<?>> aspectClass) { return StreamSupport.stream(Iterables.concat(trace.getEventAspects(), EXTRA_ASPECTS).spliterator(), false) .filter(aspect -> aspectClass.isAssignableFrom(aspect.getClass())) .collect(Collectors.toList()); }

Target:
Iterables.filter(Iterables.concat(bob), isAssignabe)). use iterables methods on iterables?
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((resource == null) ? 0 : resource.hashCode()); return result; }

Target:
I not see the link between the change of hashCode and equals, and the feature of this issue... Same remarks for all following items.
Source:
int computeWidthDifference (GtkRequisition requisition, int width) { int diffwidth; diffwidth = requisition.width - width; if (width - diffwidth < 0) { return requisition.width; } else { return width; } }

Target:
Suggestion: Reduce this to a 1 liner: return (requisition.width - width) < 0 ? requisition.width : width;
Source:
private void resetData() { for (CounterAnalysis analysis : fModules) { ITmfStateSystem ss = analysis.getStateSystem(); if (ss == null) { continue; } for (Integer quark : fQuarks) { deleteSeries(createSeriesName(ss, quark)); } } fQuarks.clear(); }

Target:
In updateChart(), the collection fModules is updated first, then this method is called. So you don't have anymore the old modules to be able to recreate the old series that need to be deleted. How about getting the series set directly from the SWTChart and delete them one by one using their own id provided by ISeries?
Source:
public void updateChart(@NonNull Set<@NonNull Integer> quarks) { cancelUpdate(); resetData(); fQuarks.addAll(quarks); updateContent(); }

Target:
fQuarks = quarks?
Source:
protected @NonNull TmfViewer createLeftChildViewer(Composite parent) { CounterTreeViewer treeViewer = new CounterTreeViewer(parent); treeViewer.addSelectionChangeListener(new SelectionChangeListener()); // Initialize the viewers with the currently selected trace ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace != null) { TmfTraceSelectedSignal signal = new TmfTraceSelectedSignal(this, trace); treeViewer.traceSelected(signal); setTrace(trace); } return treeViewer; }

Target:
The base class TmfChartView already sets the trace in its createPartControl(). - If TmfTimeViewer handles TmfTraceSelectedSignal signal, shouldn't it initialize its trace itself? - If TmfChartView initializes its trace, shouldn't it handle TmfTraceSelectedSignal by itself? - After TmfChartView has set its initial trace, it never gets changed even when a new trace is selected. But it doesn't seem to matter because the viewers handle the trace change themselves.
Source:
private void resetData() { for (CounterAnalysis analysis : fModules) { ITmfStateSystem ss = analysis.getStateSystem(); if (ss == null) { continue; } for (Integer quark : fQuarks) { deleteSeries(createSeriesName(ss, quark)); } } fQuarks = new TreeSet<>(); }

Target:
Because of the AIOOB exception above, this doesn't work. I wonder if we should not clear more broadly, can we tell the viewer to clear all its data without having to tell it what it was?
Source:
public static @Nullable SegmentStoreDataProvider create(ITmfTrace trace, @Nullable ISegmentStoreProvider provider) { if (provider == null) { return null; } if (provider instanceof IAnalysisModule) { ((IAnalysisModule) provider).schedule(); } return new SegmentStoreDataProvider(trace, provider); }

Target:
return only if the provider is an AnalysisModule?
Source:
public static boolean isExcludedColumn(VerifyTreeData tree, int ind) { List<Integer> excludedColumns = tree.getExcludedColumns(); for (Integer excludedColumn : excludedColumns) { if (excludedColumn.equals(ind)) { return true; } } return false; }

Target:
excludedColumns.contains(Integer.valueOf(ind))
Source:
protected void openDiagram(String name) { editor = (SWTBotSiriusDiagramEditor) openRepresentation(localSession.getOpenedSession(), VIEWPOINT_NAME + " " + name, name, DDiagram.class); editor.setSnapToGrid(false); editor.zoom(ZoomLevel.ZOOM_100); }

Target:
you could replace with openDiagram(name, ZoomLevel.ZOOM_100);
Source:
public CommonXAxisModelBuilder addYSeries(IYSeries ySeries) { if (fXValues.length == 0) { throw new IllegalStateException("X values must be set before setting Y values"); //$NON-NLS-1$ } if (fXValues.length != ySeries.getDatapoints().length) { throw new IllegalStateException("All series in list must be of length : " + fXValues.length); //$NON-NLS-1$ } fYSeries.put(ySeries.getLabel(), ySeries); fModel = null; return this; }

Target:
what if you query on a single timestamp.
Source:
public long getEnd() { return fXvalues[fXvalues.length]; }

Target:
length - 1 ?
Source:
public static @Nullable KernelMemoryUsageDataProvider create(ITmfTrace trace) { TmfStateSystemAnalysisModule module = TmfTraceUtils.getAnalysisModuleOfClass(trace, TmfStateSystemAnalysisModule.class, KernelMemoryAnalysisModule.ID); if (module != null) { module.schedule(); return new KernelMemoryUsageDataProvider(trace, module); } return null; }

Target:
KernelMemoryAnalysisModule
Source:
public ITmfCommonXAxisResponse fetchXY(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { if (!(filter instanceof SelectedCpuQueryFilter)) { return TmfCommonXAxisResponseFactory.createFailedResponse(CommonStatusMessage.UNEXPECTED_QUERY_FILTER); } return fetchXY((SelectedCpuQueryFilter) filter, monitor); }

Target:
invert your condition to do if(A instanceof B) { use (B) A }
Source:
public boolean isMatch(String relativeTarget, boolean isDirectory) { if (relativeTarget == null) { return false; } relativeTarget = stripTrailing(relativeTarget, FastIgnoreRule.PATH_SEPARATOR); if (relativeTarget.length() == 0) { return false; } boolean match = matcher.matches(relativeTarget, isDirectory); return match; }

Target:
I decided to strip the trailing slashes here. The caller here don't care if it is "dir" or "dir/", so we will get the "native git" behavior. I decided not to do this in PathMatcher, because it is more generic one and this would also have implications on ignore rules, which I can't overlook right now.
Source:
public void setClosestMatch(String text) { System.out.println("matching text " + text); //$NON-NLS-1$ final boolean matchFound = ComboUtil.setClosestMatch(getCCombo(), text); // if no literal matches, reset to initial state if (!matchFound) { reset(); } }

Target:
Remove sysout
Source:
private void applyExpandedStateContext(ViewContext viewContext) { if (viewContext != null) { fTimeGraphViewer.expandAll(); fTimeGraphViewer.setExpandedState(viewContext.getCollapsedEntries(), false); fTimeGraphViewer.refresh(); } }

Target:
This refresh shouldn't be necessary?
Source:
public void goToLastEvent() throws CTFException { long endTime = Long.MIN_VALUE; for (CTFStreamInputReader sir : fPrio) { sir.goToLastEvent(); IEventDefinition currentEvent = sir.getCurrentEvent(); if (currentEvent != null) { endTime = Math.max(currentEvent.getTimestamp(), endTime); } } setEndTime(fTrace.timestampCyclesToNanos(endTime)); // Go right before the end time, may be several events before the end but they // would all be the "last" event occurring at the same time seek(fTrace.timestampNanoToCycles(getEndTime())); }

Target:
To avoid unnecessary conversion (and possibly rounding error?), you could use 'endTime' directly?
Source:
public Collection<ViewPrototype> getAllPrototypes() { Collection<ViewPrototype> result = new ArrayList<ViewPrototype>(); for (MergedArchitectureViewpoint viewpoint : getViewpoints()) { for (RepresentationKind kind : viewpoint.getRepresentationKinds()) { PapyrusRepresentationKind view = (PapyrusRepresentationKind) kind; ViewPrototype proto = ViewPrototype.get(view); if (!result.contains(proto) && null != proto) { result.add(proto); } } } return result; }

Target:
invert contains and null condition please. It's not necessary to call contains if proto == null
Source:
public IPluginBase createPluginBase(boolean isFragment) { if (fPluginBase != null) return fPluginBase; if (isFragment) { fPluginBase = new FragmentNode(); fPluginBase.setXMLTagName("fragment"); //$NON-NLS-1$ } else { fPluginBase = new PluginNode(); fPluginBase.setXMLTagName("plugin"); //$NON-NLS-1$ } fPluginBase.setInTheModel(true); fPluginBase.setModel(this); return fPluginBase; }

Target:
Use brackets also for single statements
Source:
public List<PageUpdateCommand> notifyAndGetUpdateCommands(ResourceSetChangeEvent resourceSetChangeEvent) { return null; }

Target:
Should return an empty list instead of null in such a case.
Source:
public static List<RGBColor> getDefaultPalette() { return Arrays.asList( BLUE, RED, GREEN, MAGENTA, CYAN, DARK_BLUE, DARK_RED, DARK_GREEN, DARK_BLUE, DARK_RED, DARK_GREEN, DARK_MAGENTA, DARK_CYAN, DARK_YELLOW, BLACK, GRAY, YELLOW); }

Target:
repeated colors
Source:
public void registerHandler(ITraceEventHandler handler) { int pos = Collections.binarySearch(fHandlers, handler, HANDLER_COMPARATOR); if (pos < 0) { fHandlers.add(-pos - 1, handler); } else { fHandlers.add(handler); } }

Target:
Do you really need to add this since it is already in the list?
Source:
private void establishHistoryLimit() { int historyLimit= SearchPreferencePage.getHistoryLimit(); QueryManager searchManager= getSearchManager(); if (historyLimit >= searchManager.getSize()) { return; } int numberQueriesNotShown= 0; SearchViewManager searchViewManager= getSearchViewManager(); ISearchQuery[] queries= searchManager.getQueries(); for (ISearchQuery querie : queries) { ISearchQuery query= querie; if (!searchViewManager.isShown(query)) { if (++numberQueriesNotShown >= historyLimit) { removeQuery(query); } } } }

Target:
No need for the intermediate querie - you should use the query from following line which is not needed.
Source:
public boolean provides(String pageId) { if (DebugPage.PAGE_ID.equals(pageId)) { return true; } return false; }

Target:
"return DebugPage.PAGE_ID.equals(pageId)" ?
Source:
public static void incrementAttributeLong(ITmfStateSystemBuilder ssb, long t, int attributeQuark, long increment) { @Nullable Object stateValue = ssb.queryOngoing(attributeQuark); /* if the attribute was previously null, start counting at 0 */ long prevValue = 0; if (stateValue != null && stateValue instanceof Long) { prevValue = (long) stateValue; } ssb.modifyAttribute(t, prevValue + increment, attributeQuark); }

Target:
write nullable on the same line or don't write it
Source:
public static void incrementAttributeInt(ITmfStateSystemBuilder ssb, long t, int attributeQuark, int increment) throws StateValueTypeException, AttributeNotFoundException { Object stateValue = ssb.queryOngoing(attributeQuark); /* if the attribute was previously null, start counting at 0 */ int prevValue = 0; if (stateValue != null && stateValue instanceof Integer) { prevValue = (int) stateValue; } ssb.modifyAttribute(t, prevValue + increment, attributeQuark); }

Target:
cannot remove this?
Source:
public void setExecuteOnKeyRelease(boolean executeOnKeyRelease) { this.executeOnKeyRelease = executeOnKeyRelease; }

Target:
protected?
Source:
public boolean handles(final Table table, final Object axisElement) { final String id = AxisUtils.getPropertyId(axisElement); // Handle only the Requirement::text column in Requirement table return (null != id && id.equals(SYSML_REQUIREMENTS_REQUIREMENT_TEXT_ID)); }

Target:
return SYSML_REQUIREMENTS_REQUIREMENT_TEXT_ID.equals(AxisUtils.getPropertyId(axisElement)) should work no ?
Source:
protected boolean isForceRefLog(ReceiveCommand cmd) { return cmd.isForceRefLog() != null ? cmd.isForceRefLog().booleanValue() : isForceRefLog(); }

Target:
When ReceiveCommand.isForceRefLog() is annotated as @Nullable this causes a "potential null pointer" error in Eclipse. This is clearly a false positive since we check for null on the previous line. Factoring it out to a variable fixes it.
Source:
public Sampling setSampling(Sampling sampling) { Sampling prev = fSampling; fSampling = sampling; return prev; }

Target:
It this worth it to return previous? Doesn't seem to be used?
Source:
public TmfResolvedSymbol getSymbolEntry(long address) { Entry<Long, TmfResolvedSymbol> floorEntry = fSymbolMapping.floorEntry(address); if (floorEntry == null) { return null; } // See if the symbol returned is the end of a block, in this case, don't // use the floor unless it hits the exact address TmfResolvedSymbol symbol = floorEntry.getValue(); long floorValue = symbol.getBaseAddress(); if (symbol.getSymbolName().endsWith(getEndSuffix()) && floorValue != address) { return null; } return symbol; }

Target:
Ternary operator if you're feeling fancy.
Source:
public AccessContext(IASTName name) { this.name = name; this.isPrefixLookup = false; }

Target:
Please delegate to the other constructor using this(name, false); in the constructor body.
Source:
public StatusAdapter getStatusAdapter(JobInfo info) { if (map == null) { return null; } StatusAdapter statusAdapter = (StatusAdapter) map.remove(info); if (statusAdapter != null) statusAdapter.setProperty( IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.FALSE); return statusAdapter; }

Target:
Could you follow the code style elsewhere and use braces please?
Source:
private boolean userRequestedSpecificFile(MIBreakpoint miBpt) { assert isFunctionBreakpoint(miBpt); String originalLocation = miBpt.getOriginalLocation(); boolean userRequestedSpecificFile = originalLocation != null && originalLocation.contains(":"); //$NON-NLS-1$ return userRequestedSpecificFile; }

Target:
No need for 'userRequestedSpecificFile', use 'return originalLocation...'
Source:
private synchronized void newUpdateThread(@NonNull FlowScopeLog fScope) { cancelUpdate(); if (getSwtChart().isDisposed()) { return; } int numRequests = fOverrideNbPoints != 0 ? fOverrideNbPoints : (int) Math.min(getWindowEndTime() - getWindowStartTime() + 1, (long) (getSwtChart().getPlotArea().getBounds().width * fResolution)); fUpdateThread = new UpdateThread(numRequests, fScope); fUpdateThread.start(); }

Target:
practically, we can theoretically be handling over 2b pixels wide, but then we will have more issues.
Source:
protected void selectCellToFillToDown(final TreeNattableModelManager treeManager) { System.out.println(treeManager.getBodyLayerStack().getSelectionLayer().getCellByPosition(0, 0).getDataValue().toString()); treeManager.getBodyLayerStack().getSelectionLayer().setSelectedCell(0, 0); }

Target:
syso here
Source:
public IReconcilingStrategy getReconcilingStrategy(String contentType) { if(fReconcilers.size() == 1) { return fReconcilers.get(0).getReconcilingStrategy(contentType); } List<IReconcilingStrategy> strategies = new ArrayList<>(); for (IReconciler iReconciler : fReconcilers) { IReconcilingStrategy strategy = iReconciler.getReconcilingStrategy(contentType); if(strategy != null) { strategies.add(strategy); } } return new CompositeReconcilerStrategy(strategies); }

Target:
I believe the size of the strategies list matters more here. So I'd get rid of the check on lines 66-68 and would check whether strategies is empty then return null, if size if one then return the single one, otherwise compose them.
Source:
protected TmfXYChartViewer createChartViewer(Composite parent) { return new CounterChartViewer(parent, new TmfXYChartSettings(null, null, null, 1), fXYPresentationProvider); }

Target:
I think the chart viewer should be responsible for its own presentation provider. The tree viewer could ask the chart viewer for a series appearance directly, perhaps through the ITreeViewerInterface? (could be renamed ICounterChartViewer).
Source:
public void loadTrace(ITmfTrace trace) { cancelUpdate(); clearStyles(); super.loadTrace(trace); initializeDataProvider(); }

Target:
The order of colors is changed when switching back and forth to a trace.
Source:
private void handleRepeatedInvocation() { if (fContentAssistant.isRepeatedInvocationMode()) { fComputedProposals= computeProposals(fFilterOffset); setProposals(fComputedProposals, false); } }

Target:
Please do not reduce visibility of existing fields as part of this change, there might be reasons to investigate separately before reducing visibility.
Source:
public List<UpdateSummaryData> broadcastUpdateItems(Collection<String> ids, Collection<DispoItem> items, DispoSet set) { List<UpdateSummaryData> summaryData = null; for (DispoListenerApi listener : listeners) { summaryData = listener.onUpdateItemStats(ids, items, set); } return summaryData; }

Target:
As a suggestion, you might want to initialize this to new ArrayList<>(); This would help avoid a NPE on the upstream.
Source:
boolean isSelected(MPart part) { MElementContainer<?> parent = part.getParent(); if (parent == null) { MPlaceholder placeholder = part.getCurSharedRef(); if (placeholder == null) { return false; } parent = placeholder.getParent(); return parent instanceof MGenericStack ? parent.getSelectedElement() == placeholder : parent != null; } return parent instanceof MGenericStack ? parent.getSelectedElement() == part : true; }

Target:
!(parent instanceof MGenericStack) || parent.getSelectedElement() == part
Source:
protected void tearDown() throws Exception { Job.getJobManager().cancel(BuildTestProject.class); IProject testProject = getTestProject(); if (testProject.exists()) { testProject.delete(true, null); } setWorkspaceAutoBuild(wasAutoBuildOn); logListener.clear(); Platform.removeLogListener(logListener); super.tearDown(); }

Target:
Please enclose with try/finally and put the autobuild restore code to the finally block.
Source:
public synchronized IncrementalProjectBuilder getBuilder(IBuildConfiguration config) { synchronized (builderLock) { if (builders != null && supportsConfigs()) return builders.get(config); return builder; } }

Target:
Please remove this
Source:
public boolean isInstanceOfScoped(EObject object, EClass clazz) { Object typeKey = toKey(object.eClass()); if (!doCalculateInstanceOf(typeKey, clazz)) { return false; } final Set<EObject> instances = instanceStore.getInstanceSet(typeKey); return instances != null && instances.contains(object); }

Target:
the second parameter should be toKey(clazz) instead of clazz, to support dynamic EMF mode. (sorry for not catching it earlier)
Source:
public void fireFilterChanged() { for (ITimeGraphViewerFilterListener listener : fViewerFilterListeners) { listener.filterChanged(); } }

Target:
Does this need to be public?
Source:
public void addFilter(@NonNull ViewerFilter filter) { fTimeGraphCtrl.addFilter(filter); refresh(); fTimeGraphCtrl.fireFilterApplied(); }

Target:
If a filter is applied directly to the TimeGraphControl, the listeners won't be notified. In that case, perhaps the TimeGraphViewer should be the sole owner of the listener list, and the one to fire the events. Otherwise, the TimeGraphControl should fire the events when addFilter() or removeFilter() is called.
Source:
private static boolean isEntry(ITmfEvent event) { String phase = event.getContent().getFieldValue(String.class, ITraceEventConstants.PHASE); return "B" == phase || phase == "s"; //$NON-NLS-1$ //$NON-NLS-2$ }

Target:
string equals
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof ITuple)) return false; final ITuple other = (ITuple) obj; if (cachedHash != other.hashCode()) return false; return internalEquals(other); }

Target:
other.hashCode() is only fast for immutable Tuples with cachedHash, not for VolatileTuples. If `obj` is volatile, we can jump straight to internalEquals() I believe. Though this should not matter a lot, I guess most comparisons will happen against other immutable Tuples anyway.
Source:
public boolean hasNext() { if (isNextMatchCalculated) { return true; } if (currentPlan == null) { return false; } try { boolean foundMatch = currentPlan.execute(frame); while ((!foundMatch) && planIterator.hasNext()) { foundMatch = selectNextPlan() && currentPlan.execute(frame); } if (foundMatch) { isNextMatchCalculated = true; } return foundMatch; } catch (LocalSearchException e) { throw new RuntimeException(e); } }

Target:
This condition can be omitted as at this point isNextMatchCalculated is known to be false (from the condition at 121). It may be nitpicking, but this particular code is executed many times so I propose to simply put 'isNextMatchCalculated = foundMatch' here.
Source:
protected void fireContentEditorFieldEvent(ContentEditorFieldEvent e) { EventListener[] listeners = m_listenerList.getListeners(ContentEditorFieldListener.class); if (listeners != null && listeners.length > 0) { for (int i = 0; i < listeners.length; i++) { ((ContentEditorFieldListener) listeners[i]).contentEditorFieldChanged(e); } } }

Target:
I'd rather use an early return (if null) and a simple loop, the counter variable is not required here: for (EventListener l : listeners) {
Source:
protected void attachModel() { super.attachModel(); if (m_modelListener != null) { throw new IllegalStateException("Already attached"); } m_modelListener = new P_ModelListener(); getModel().addContentEditorFieldListener(m_modelListener); }

Target:
IllegalStateException is not required here (check is already performed in super call)
Source:
protected boolean isExitState(EObject model) { if (currentModel == null) { return false; } if (model == null) { return true; } if (model != currentModel) { // return true; } return false; }

Target:
return currentmodel!=null && model == null
Source:
public SelectedCounterQueryFilter(long start, long end, int n, Collection<Long> ids, boolean isCumulative) { super(start, end, n, ImmutableList.copyOf(ids)); fIsCumulative = isCumulative; }

Target:
put it up
Source:
private byte[] generate(int size, int nullAt) { byte[] data = new byte[size]; for (int i = 0; i < data.length; i++) { data[i] = (byte) ((i % 72 == 0) ? '\n' : (i%10) + '0'); } if (nullAt >= 0) { data[nullAt] = '\0'; } return data; }

Target:
static
Source:
public boolean createEObjectDescriptions(EObject eObject, IAcceptor<IEObjectDescription> acceptor) { if (eObject instanceof PatternModel) { } else if (eObject instanceof Pattern) { QualifiedName qualifiedName = getQualifiedNameProvider().getFullyQualifiedName(eObject); if (qualifiedName != null) { acceptor.accept(EObjectDescription.create(qualifiedName, eObject, getUserData((Pattern) eObject))); } return false; } return super.createEObjectDescriptions(eObject, acceptor); }

Target:
This empty if block seems redundant.
Source:
public Collection<Tuple> get(Tuple signature) { Object bucket = matchings.get(signature); if (bucket instanceof MarkedSet<?>) { return (Collection<Tuple>) bucket; } else { // singleton or empty if (bucket == null) return null; return Collections.singleton((Tuple)bucket); } }

Target:
This instanceof/cast pair seems strange. I'd synchronize them if possible (even if on the bytecode level this is the same as the synchronized version).
Source:
WorkbenchSiteProgressService getSiteProgressService() { return (WorkbenchSiteProgressService) e4Context.get(IWorkbenchSiteProgressService.class); }

Target:
I think this cast can be removed.
Source:
public Rectangle getBounds() { return syncExec(() -> this.widget.getBounds()); }

Target:
Is the super class implementation not working?
Source:
static URI getStereotypeURI(EObject stereotypeApplication) { return EcoreUtil.getURI(stereotypeApplication.eClass()); }

Target:
private
Source:
static <K, L, V> V put(Map<K, Map<L, V>> mapOfMaps, K key1, L key2, V value) { Map<L, V> map = mapOfMaps.get(key1); if (map == null) { map = Maps.newHashMap(); mapOfMaps.put(key1, map); } return map.put(key2, value); }

Target:
Done
Source:
public void enterModule(ModuleInfo moduleInfo) { this.indexer.addModuleDeclaration(moduleInfo.moduleName); if (moduleInfo.requires != null) { for (ISourceElementRequestor.RequiresInfo req : moduleInfo.requires) { if (req == null || req.moduleName == null || req.moduleName == CharOperation.NO_CHAR) { continue; } this.indexer.addModuleReference(req.moduleName); } } enterPackageVisibilityInfo(moduleInfo.exports); enterPackageVisibilityInfo(moduleInfo.opens); /* note: provides and uses directives processed automatically on IParser (SEParser) */ }

Target:
why introduce a block here (and in the other ifs)?
Source:
public static VView loadView(IFile file, Collection<String> registeredEcores) throws IOException { final String path = file.getLocation().toString(); VView view = loadView(path); if (!viewIsResolved(view)) { view = tryResolve(view, path, registeredEcores); if (viewIsResolved(view)) { return null; } } return view; }

Target:
null should only be returned when the view is NOT resolved. However with the new use cases I think it makes more sense to return the view anyway, resolved or unresolved, and let the callers handle it themselves.
Source:
public BitmapObjectFilter(BitmapBuilder bitmap) { this.bitmap = bitmap; }

Target:
use default, no need public.
Source:
public static <T extends org.eclipse.swt.widgets.Widget> org.hamcrest.Matcher<T> withId(java.lang.String key, java.lang.String value) { return org.eclipse.swtbot.swt.finder.matchers.WithId.withId(key, value); }

Target:
Cast value to (Object) to prevent a deprecation warning
Source:
public SWTBotButton buttonWithId(String key, Object value) { Matcher matcher = allOf(widgetOfType(Button.class), withId(key, value), withStyle(SWT.PUSH, "SWT.PUSH")); return new SWTBotButton((Button) widget(matcher), matcher); }

Target:
To be consistent, we should probably have buttonWithId(key, value, index)
Source:
private void updateExportDialogAutoScaleSettings(boolean value) { IDialogSettings settings = getExportDialogSettings(); settings.put(AbstractExportRepresentationsAsImagesDialog.AUTO_SCALE_SETTING_PROPERTY, value); if (value) { // full autoScale used settings.put(AbstractExportRepresentationsAsImagesDialog.SCALE_LEVEL_SETTING_PROPERTY, 100); } else { // no autoScale used settings.put(AbstractExportRepresentationsAsImagesDialog.SCALE_LEVEL_SETTING_PROPERTY, 0); } }

Target:
10
Source:
public int compareTo(LfsPointer o) { int x = getOid().compareTo(o.getOid()); if (x != 0) { return 0; } return (int) (getSize() - o.getSize()); }

Target:
why do we return 0 if the oids aren't equal ? Shouldn't we return x in this case ?
Source:
public static LocalFile cleanLfsBlob(Repository db, InputStream originalContent) throws IOException { LocalFile buffer = new TemporaryBuffer.LocalFile(null); CleanFilter f = new CleanFilter(db, originalContent, buffer); while (f.run() != -1) { // loop as long as command.run() tells there is work to do } return buffer; }

Target:
Any reason why the interface is specific to LocalFile? Why not TemporaryBuffer?
Source:
public PrePushHook getPrePushHook(Repository repo, PrintStream outputStream) { if (isAvailable() && isEnabled(repo)) { return new LfsPrePushHook(repo, outputStream); } return null; }

Target:
this is always true hence can be skipped
Source:
protected void onSetUpBeforeClosingWelcomePage() throws Exception { copyFileToTestProject(Activator.PLUGIN_ID, DATA_UNIT_DIR, MODEL_FILE, SESSION_FILE, VSM_FILE, IMAGE_FILE); sessionAirdResource = new UIResource(designerProject, SESSION_FILE); localSession = designerPerspective.openSessionFromFile(sessionAirdResource, true); }

Target:
is it really useful?
Source:
public MarkerItem getMarkerItem(IMarker marker) { Map<IMarker, MarkerEntry> entryMap = markerToEntryMap; if (entryMap == null) { entryMap = new HashMap<>(); for (MarkerEntry markerEntry : markerEntryArray) { IMarker nextMarker = markerEntry.getMarker(); if (nextMarker != null) { entryMap.put(nextMarker, markerEntry); } } markerToEntryMap = entryMap; } if (entryMap.containsKey(marker)) { return entryMap.get(marker); } return null; }

Target:
The loop iterates over the mutable array, which is guarded by "this" lock, but the loop itself is not guarded by "this". If we are going to fix MT issue here, we will also need to guard against the inconsistent data we might see in the array, which is changed in two synchronized sort* methods. At the end we might see less entries in the entryMap because we might see same elements multiple times while sorting of the array. So probably the easiest way to fix the original issue is to make the getMarkerItem() synchronized.
Source:
public LanguageServerWrapper(@Nullable IProject project, @NonNull LanguageServerDefinition serverDefinition) { this.initialProject = project; this.allWatchedProjects = new HashSet<>(); this.serverDefinition = serverDefinition; this.lspStreamProvider = serverDefinition.createConnectionProvider(); if (this.lspStreamProvider == null) { throw new IllegalStateException(Messages.LanguageServerWrapper_initializationException); } this.connectedDocuments = new HashMap<>(); }

Target:
This would better be made not final and set during the start method. So the LanguageServiceAccessor would store the Wrapper and keep it cached for further usage, and most further usages of the LS would attempt to retry it until it works.
Source:
public CloseUnrelatedProjectsAction(IShellProvider provider){ super(provider, IDEWorkbenchMessages.CloseUnrelatedProjectsAction_text); TEXT_STRING = IDEWorkbenchMessages.CloseUnrelatedProjectsAction_text; TOOLTIP_STRING = IDEWorkbenchMessages.CloseUnrelatedProjectsAction_toolTip; TEXT_PLURAL_STRING = IDEWorkbenchMessages.CloseUnrelatedProjectsAction_text_plural; TOOLTIP_PLURAL_STRING = IDEWorkbenchMessages.CloseUnrelatedProjectsAction_toolTip_plural; initAction(); }

Target:
Ideall in super constructor
Source:
private String getUniqueNameFor(String seriesName) { Integer quark = fQuarkToString.inverse().get(seriesName); int index = 0; String newName = seriesName; while (quark != null) { newName = seriesName + '(' + index + ')'; quark = fQuarkToString.inverse().get(newName); } return newName; }

Target:
don't you need to increment the index to avoid infinite looping? how do you avoid having seriesName, and seriesName(0)?
Source:
public CPPASTLiteralExpression(int kind, char[] value, char[] numericCompilerSuffixes) { fKind = kind; setValue(kind, value); fNumericCompilerSuffixes = (numericCompilerSuffixes == null) ? CharArrayUtils.EMPTY : numericCompilerSuffixes; }

Target:
Isn't this equivalent to: fValue = value; fSuffix = CharArrayUtils.EMPTY?
Source:
public CPPASTLiteralExpression copy(CopyStyle style) { CPPASTLiteralExpression copy = new CPPASTLiteralExpression(fKind, this.getValue()); copy.fNumericCompilerSuffixes = fNumericCompilerSuffixes.clone(); copy.fStringLiteralSize = fStringLiteralSize; copy.fEvaluation = fEvaluation; copy.fUserDefinedLiteralOperator = fUserDefinedLiteralOperator; copy.fImplicitNames = fImplicitNames == null ? null : fImplicitNames.clone(); return copy(copy, style); }

Target:
It is unfortunate that compiler suffixes, which are not really supposed to change, are cloned here. Cloning can be avoided by passing compiler suffixes to the constructor as a parameter.
Source:
public boolean isResolved() { return resolveFuture == null || resolveFuture.isDone() || label != null; }

Target:
That's not very clear: if doResolve does return null, it most likely means that the CodeMining doesn't require resolution, so isResolved should be true. The implementation seems erroneous here. This may be caused by `resolveFuture == null` which can mean 2 different things: either the future wasn't requested yet, or the future was requested and null was returned (ie no resolution required). I believe you need some more details or another state variable in the class to distinguish both cases.
Source:
public void testNoDefaulColortMenuInAppearancePropertyViewFromContainerMappingFontColor() { selectAndCheckEditPart(NODE_CONTAINER, DNodeContainerEditPart.class); bot.viewByTitle("Properties").setFocus(); SWTBotSiriusHelper.selectPropertyTabItem("Appearance"); try { bot.viewByTitle("Properties").bot().buttonInGroup("Fonts and Colors:", 0).click().contextMenu(DEFAULT_COLOR); fail(); } catch (WidgetNotFoundException e) { assertTrue(true); } }

Target:
All of these are completely useless.
Source:
public void setProgressMonitor(ProgressMonitor monitor) { if (monitor == null) { monitor = NullProgressMonitor.INSTANCE; } this.monitor = monitor; }

Target:
`this.monitor` to avoid confusion with the parameter of the same name optional: this whole block could be a ternary: this.monitor = monitor != null ? monitor : NullProgressMonitor.INSTANCE;
Source:
public void cleanup() { fModule.dispose(); fTrace.dispose(); CtfTmfTestTraceUtils.dispose(getTestTrace()); }

Target:
they both disposing the same trace. Keep the second call
Source:
private static ImportDeclaration getProblematicImport(IProblem problem, CompilationUnit cu) { ASTNode coveringNode= new NodeFinder(cu, problem.getSourceStart(), problem.getSourceEnd() - problem.getSourceStart()).getCoveringNode(); if (coveringNode != null) { ASTNode importNode= ASTNodes.getParent(coveringNode, ASTNode.IMPORT_DECLARATION); if (importNode instanceof ImportDeclaration) { return (ImportDeclaration) importNode; } } return null; }

Target:
Check the old code where: fLength= problem.getSourceEnd() - fOffset + 1; Here, +1 is missing.
Source:
public void setStatusLineManager(IStatusLineManager statusLineManager) { if (fStatusLineManager != null && statusLineManager == null) { fStatusLineManager.setMessage(""); //$NON-NLS-1$ } fStatusLineManager = statusLineManager; }

Target:
according to the docs, you are supposed to pass null to clear the message
Source:
public Object addInheritableProperty(String key, Object value) { if (getNonInheritableProperties().containsKey(key)) { final Object oldValue = getNonInheritableProperties().get(key); getNonInheritableProperties().removeKey(key); getInheritableProperties().put(key, value); return oldValue; } return getInheritableProperties().put(key, value); }

Target:
removeKey returns the value already no need to fetch it first
Source:
public @Nullable String getRemoteBranchName() { return remoteBranchName; }

Target:
Move to a separate commit
Source:
public int getWidth() { return width; }

Target:
Shouldn't we make it final in a 1st iteration or do you have use-cases that need to override it?
Source:
public void setWidth(int width) { this.width= width; }

Target:
Does this need to be public? It seems to me this would only be useful to call from subclasses, so it could be protected. Shouldn't we make it final in a 1st iteration or do you have use-cases that need to override it?
Source:
public static synchronized @Nullable SegmentStoreScatterDataProvider create(ITmfTrace trace, @Nullable ISegmentStoreProvider provider) { if (provider == null) { return null; } SegmentStoreScatterDataProvider dataProvider = PROVIDER_MAP.get(provider); if (dataProvider != null) { return dataProvider; } if (provider instanceof IAnalysisModule) { ((IAnalysisModule) provider).schedule(); dataProvider = new SegmentStoreScatterDataProvider(trace, provider); PROVIDER_MAP.put(provider, dataProvider); } return null; }

Target:
rename smth like getOrCreate?
Source:
public void dispose() { menuManager.dispose(); if (toolbarManager != null) { ((ToolBarManager) toolbarManager).dispose(); } super.dispose(); }

Target:
could be removed if the field will have right type
Source:
public int compare(String o1, String o2) { String name1 = tocNames.get(o1); String name2 = tocNames.get(o2); if (name1 == null) { return -1; } if (name2 == null) { return 1; } return Collator.getInstance().compare(name1, name2); }

Target:
case not handled when both are null name2 != null ? -1 : 0
Source:
private static void loadXmlFile() { XmlUtils.addXmlFile(TmfXmlTestFiles.CONDITION_FILE.getFile()); XmlUtils.addXmlFile(TmfXmlTestFiles.VALID_TIMEGRAPH_VIEW_ELEMENT_FILE.getFile()); File xmlFile = XmlUtils.getXmlFilesPath().addTrailingSeparator().append(TmfXmlTestFiles.VALID_TIMEGRAPH_VIEW_ELEMENT_FILE.getFile().getName()).toFile(); XmlUtils.preloadXmlAnalysesOutput(xmlFile); XmlAnalysisModuleSource.notifyModuleChange(); }

Target:
What bugs me is that you have to worry about the file path before calling this, this shouldn't be... You should be able to just call the preload with the same File as the one in addXmlFile.
Source:
public static int determineModularClasspathProperty(IClasspathEntry entry) { return Arrays.stream(entry.getExtraAttributes()) .anyMatch(p -> p.getName().equals(IClasspathAttribute.MODULE) && p.getValue().equals("true")) ? IRuntimeClasspathEntry.MODULE_PATH : IRuntimeClasspathEntry.CLASS_PATH; }

Target:
"true".equals(p.getValue()) if getValue() can yield null
Source:
public boolean isMergerFor(Diff target) { final Conflict conflict = target.getConflict(); return conflict != null && conflict.getKind() == ConflictKind.PSEUDO; }

Target:
I'll take this occasion to mention this. This kind of variable extraction does nothing for performance and often hinders readability. please avoid them (they're cluttering most of these "performance" patches). Simple getters like this are only highlighted by profilers because of the instrumentation.
Source:
public boolean equals(Object obj) { if (!(obj instanceof DependencyEvent)) { return false; } DependencyEvent other = (DependencyEvent) obj; return Objects.equals(fTrace, other.fTrace) && Objects.equals(fTimestamp, other.fTimestamp); }

Target:
Objects.equals is safe though.
Source:
protected void okPressed() { boolean copyAsLink = false; if(fCopyLinkButton != null) { copyAsLink = fCopyLinkButton.getSelection(); } IResource trace = copyTrace(fNewTraceName.getText(), copyAsLink); if (trace == null) { return; } setSelectionResult(new IResource[] { trace }); super.okPressed(); }

Target:
Missing space. Or could be shortened as: copyAsLink = not null && is selected;
Source:
public FtraceEvent(ITmfTrace trace, long rank, FtraceField field) { super(trace, rank, TmfTimestamp.fromNanos(field.getTs()), FtraceEventTypeFactory.get(field.getName()), field.getContent()); fField = field; fName = field.getName(); fLogLevel = Level.INFO; fCallsite = null; }

Target:
Do we need this?
Source:
public Stream<Tuple> getAllMatches(Object[] parameters) { return matchAll(parameters, notNull(parameters)).stream(); }

Target:
matchAll will internally still copy the entire match set, so in case of hybrid matching, this will not perform as expected
Source:
private void checkCanceled(IProgressMonitor pm) { if (pm.isCanceled()) throw new OperationCanceledException(); }

Target:
static
Source:
private ITypeHierarchy createHierarchyOfTypes(IProgressMonitor pm, WorkingCopyOwner owner, Stream<IType> types) throws JavaModelException { IRegion region= JavaCore.newRegion(); for (Iterator<IType> iter= types.iterator(); iter.hasNext(); ) { IType type= iter.next(); region.add(type); } return JavaCore.newTypeHierarchy(region, owner, pm); }

Target:
static
Source:
private static void checkCanceled(IProgressMonitor pm) { if (pm.isCanceled()) throw new OperationCanceledException(); }

Target:
can you please use for if block. I know the old code doesn't use this always, but in the new code we can do better.
Source:
public OperationReport getOperationSummary() { String operationSummaryJson = artifact.getSoleAttributeAsString(DispoConstants.OperationSummary, "{}"); try { return DispoUtil.jsonObjToOperationSummary(operationSummaryJson); } catch (Exception ex) { throw new OseeCoreException("Could not parse Operation Summary Json", ex); } }

Target:
move try-catch to DispoUtil.jsonObjToOperationSummary
Source:
private void ensureAllSet(EventTester tester) { String[] unfiredIds = tester.getAttIds(false); if (unfiredIds.length > 0) { StringBuilder msg = new StringBuilder("No event fired:" + unfiredIds); for (int i = 0; i < unfiredIds.length; i++) { msg.append(' ' + unfiredIds[i]); } fail(msg.toString()); } }

Target:
use append instead of +
Source:
public String getName() { // String name = ""; //$NON-NLS-1$ StringBuilder name = new StringBuilder(); for (int i = 0; i < (input.length - 1); i++) { name.append(input[i].getName() + "/"); //$NON-NLS-1$ } name.append(input[input.length - 1].getName()); return name.toString(); }

Target:
use append instead of +
Source:
public boolean setSubtreeChecked(Object element, boolean state) { IPreCheckStateListener preCheckStateListener = fPreCheckStateListener; if (preCheckStateListener != null && preCheckStateListener.setSubtreeChecked(element, state)) { // uncheck the root element setChecked(element, false); return false; } checkSubtree(element, state); return fCheckboxTreeViewer.setSubtreeChecked(element, state); }

Target:
This doesn't get executed in our case because TriStateFilteredCheckboxTree overrides setSubtreeChecked().
Source:
private AbstractSelectTreeViewer(Composite parent, TriStateFilteredCheckboxTree checkboxTree, int legendIndex, String id) { super(parent, checkboxTree.getViewer()); TreeViewer treeViewer = checkboxTree.getViewer(); treeViewer.setComparator(COMPARATOR); if (treeViewer instanceof CheckboxTreeViewer) { ((CheckboxTreeViewer) treeViewer).addCheckStateListener(new CheckStateChangedListener()); } fCheckboxTree = checkboxTree; fLegendIndex = legendIndex; fId = id; checkboxTree.setPreCheckStateListener(new ManyEntriesSelectedDialogPreCheckedListener(checkboxTree)); }

Target:
I would prefer if the listener was added in TmfChartView.coupleSelectViewer(). The Many... listener should also go in that package. AbstractSelectTreeViewer would need either a addPreCheckListener() or getFilteredCheckboxTree() method.
Source:
public boolean isInVisibleLines() { return support.isInVisibleLines(this); }

Target:
Does this one have to be public? As an extender of such annotation, I don't think this is something I would need to invoke directly and I'd expect the underlying framework to do the necssary optimizations.
Source:
public boolean isInVisibleLines(AbstractInlinedAnnotation annotation) { return visibleLines.isInVisibleLines(annotation); }

Target:
Does it have to be public? Couldn't it be package visible only?
Source:
protected final Collection<DRepresentation> getRepresentationsByName(final String representationName) { final Collection<DRepresentation> representations = DialectManager.INSTANCE.getAllLoadedRepresentations(session).stream().filter(rep -> rep.getName().equals(representationName)) .collect(Collectors.toList()); return representations; }

Target:
representationName.equals(rep -> rep.getName())
Source:
public boolean canExecute(ITmfTrace trace) { if (!(trace instanceof TmfExperiment)) { throw new IllegalStateException(); } return super.canExecute(trace); }

Target:
you can just return false here, even better : return trace instanceof TmfExperiment && super.canExecute(trace);
Source:
public void after() { fTrace.dispose(); }

Target:
technically, you should null check here
Source:
public static PackIndex open(final File idxFile) throws IOException { try (SilentFileInputStream fd = new SilentFileInputStream( idxFile)) { try { return read(fd); } catch (IOException ioe) { throw new IOException( MessageFormat.format(JGitText.get().unreadablePackIndex, idxFile.getAbsolutePath()), ioe); } } }

Target:
unnecessary nested try block
Source:
public @NonNull String getPresetFilterName(String presetFilterId) { String presetFilterName = null; if (fPresetFilterName != null) { presetFilterName = fPresetFilterName.get(presetFilterId); } if (presetFilterName == null && fPresetFilter != null) { presetFilterName = fPresetFilter.get(fPresetFilter.indexOf(presetFilterId)); } return presetFilterName == null ? "" : presetFilterName; //$NON-NLS-1$ }

Target:
"" to remove the last ternary