auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private int deltaSizeLimit(DeltaWindowEntry src) { if (bestBase == null) { // Any delta should be no more than 50% of the original size // (for text files deflate of whole form should shrink 50%). int n = res.size() >>> 1; // Evenly distribute delta size limits over allowed depth. // If src is non-delta (depth = 0), delta <= 50% of original. // If src is almost at limit (9/10), delta <= 10% of original. return n - (n * src.depth() / maxDepth); } // With a delta base chosen any new delta must be "better". // Retain the distribution described above. int d = bestBase.depth(); int n = (int) bestDelta.length(); // If src is whole (depth=0) and base is near limit (depth=9/10) // any delta using src can be 10x larger and still be better. // // If src is near limit (depth=9/10) and base is whole (depth=0) // a new delta dependent on src must be 1/10th the size. return n * (maxDepth - src.depth()) / (maxDepth - d); }

Target:
FYI, i have confirmed this equation is correct.
Source:
private IdJoinQuery populateBranchIdsJoinIdTable() throws OseeDataStoreException, OseeCoreException { IdJoinQuery branchJoin = JoinUtility.createIdJoinQuery(); // loop through all non-archieved non-deleted non-purged BranchFilter branchFilter = new BranchFilter(BranchArchivedState.UNARCHIVED); branchFilter.setNegatedBranchStates(BranchState.PURGED); branchFilter.setNegatedBranchStates(BranchState.DELETED); for (Branch branch : BranchManager.getBranches(branchFilter)) { branchJoin.add(branch.getId()); } branchJoin.store(); return branchJoin; }

Target:
Change to a single call with both arguments.
Source:
private int getVisibility(int memberIndex) throws CoreException { int visibilityBitOffset = memberIndex % VISIBILITY_VALUES_PER_BYTE; long visibilityOffset = record + MEMBER_VISIBILITIES + memberIndex / VISIBILITY_VALUES_PER_BYTE; int visibility = getDB().getByte(visibilityOffset); // Clearing visibility bits of other members visibility &= VISIBILITY_MASK << visibilityBitOffset * VISIBILITY_BITS; visibility >>>= visibilityBitOffset * VISIBILITY_BITS; return visibility; }

Target:
Simpler to apply the mask after the shift.
Source:
private long getMemberRecord(int memberIndex) throws CoreException { if (memberIndex >= MAX_MEMBER_COUNT) { return 0; } return getDB().getRecPtr(getMemberOffset(memberIndex)); }

Target:
It's preferable to sacrifice code reuse for readability and always check memberIndex < MAX_MEMBER_COUNT before calling getMemberRecord.
Source:
public PDOMCPPMemberBlock(PDOMLinkage linkage, long record) throws CoreException { this.linkage = linkage; this.record = record; updateNextPosition(); }

Target:
nextMemberPosition is needed only for addMember. Initialize it lazily only when needed.
Source:
public PDOMCPPMemberBlock(PDOMLinkage linkage) throws CoreException { Database db = linkage.getDB(); this.linkage = linkage; this.record = db.malloc(RECORD_SIZE); db.clearBytes(record, RECORD_SIZE); updateNextPosition(); }

Target:
Redundant call.
Source:
public ITmfTimestamp getCurrentTime() { return getCurrentTraceContext().getTimestamp(); }

Target:
Add synchronized to this method
Source:
public ITmfTrace getActiveTrace() { return fCurrentTrace; }

Target:
Add synchronized to this method
Source:
public ITmfTrace[] getActiveTraceSet() { final ITmfTrace trace = fCurrentTrace; if (trace instanceof TmfExperiment) { final TmfExperiment exp = (TmfExperiment) trace; return exp.getTraces(); } return new ITmfTrace[] { trace }; }

Target:
Add synchronized to this method
Source:
protected String[] getExecutionOrder(String group) { if (GROUP_TOP_LEVEL.equals(group)) { return new String[] { "stepInitializeBaseSequence", //$NON-NLS-1$ "stepSetEnvironmentVariables", //$NON-NLS-1$ "stepSetExecutable", //$NON-NLS-1$ "stepSetArguments", //$NON-NLS-1$ // For remote non-attach only "stepRemoteConnection", //$NON-NLS-1$ // For post-mortem launch only "stepSpecifyCoreFile", //$NON-NLS-1$ "stepStartTrackingBreakpoints", //$NON-NLS-1$ "stepInitializeMemory", //$NON-NLS-1$ "stepStartExecution", //$NON-NLS-1$ "stepCleanupBaseSequence", //$NON-NLS-1$ }; } return null; }

Target:
For all the attach cases you do the InitializeMemoryFirst and trackBreakpoints after. Here you do the reverse. Not a big deal, but I wondered if there is a reason?
Source:
public BigInteger getMinValue() { if (!signed) return BigInteger.ZERO; BigInteger capacity = BigInteger.ONE.shiftLeft(length); return capacity.divide(BigInteger.valueOf(2)).negate(); }

Target:
H-How did this happen?? The project setting's Save Actions are supposed to add brackets to all 'if' clauses automatically...
Source:
public User getUserByArtId(int userArtifactId) throws OseeCoreException { User toReturn = null; if (userArtifactId <= 0) { toReturn = getUser(SystemUser.OseeSystem); } else { for (User tempUser : getUsersAll()) { if (userArtifactId == tempUser.getArtId()) { toReturn = tempUser; } } } return toReturn; }

Target:
break out if you find the user?
Source:
public Object getObjectForTextSelection(TextSelection selection, IEditorPart editor) { if (editor instanceof CEditor) { TextSelection textSelection = selection; try { if (selection != null) { return SelectionConverter.getElementAtOffset(getInputCElement((CEditor) editor), textSelection); } else { ICElement element = getInputCElement((CEditor) editor); return element; } } catch (CModelException e) { // ignore } } return null; }

Target:
we should check if celement is null here
Source:
public ObjectReader newReader() { ObjectReader r = db.newReader(); r.setAvoidUnreachableObjects(avoidUnreachable); return r; }

Target:
IIRC this is not carried into the new clone reader by any other implementation.
Source:
private ObjectId endObject(ObjectId id, long offset) throws IOException { PackedObjectInfo obj = new PackedObjectInfo(id); obj.setOffset(offset); obj.setCRC((int) packOut.crc32.getValue()); objectList.add(obj); objectMap.addIfAbsent(obj); packOut.flushStream(); return id; }

Target:
Unlike flushBlock(), this doesn't put the newly written data in the DfsBlockCache. That seems good because otherwise we'd be asking a lot of the block cache by putting partial blocks there. Am I right in assuming that DfsOutputStream#read is meant to be fast already so this shouldn't hurt anything?
Source:
public RenameDetector(Repository repo) { objectReader = repo.newObjectReader(); renameLimit = repo.getConfig().get(DiffConfig.KEY).getRenameLimit(); reset(); }

Target:
Use this form instead: this(repo.newObjectReader(), repo.getConfig().get(DiffConfig.KEY));
Source:
public void partDeactivated(IWorkbenchPart part) { fTraceSelected = false; }

Target:
It should check that the part being deactivated is 'this'.
Source:
public Object getAdapter(Class adapter) { if (adapter == IResource.class || adapter == IContainer.class) { return getContainer(); } else if (adapter == IPath.class) { return path; } return null; }

Target:
style nit: we don't use braces around single line blocks, more of these below
Source:
private Object[] getCompressedRoots() { if (compressedRoots == null) { List<Object> compressedRootList = new ArrayList<Object>(); compressedFolders = getCompressedFolders(); for (StagingFolderEntry compressedFolder : compressedFolders) { compressedRootList.add(compressedFolder); } for (StagingEntry rootFile : rootFiles) { compressedRootList.add(rootFile); } compressedRoots = new Object[compressedRootList.size()]; compressedRootList.toArray(compressedRoots); } return compressedRoots; }

Target:
style nit: no braces here
Source:
public void TSDLSimpleTest() throws CTFReaderException { createDummyTrace(simpleTSDL); CTFTrace trace = new CTFTrace(tempTraceDir); assertNotNull(trace); trace.dispose(); }

Target:
Good thing to call that. However it should go in a separate @After method
Source:
public static void updateDefaultFormats() { fDefaultTimeFormat = new TmfTimestampFormat(TmfTimePreferences.getInstance().getTimePattern(), TmfTimePreferences.getInstance().getTimeZone()); fDefaultIntervalFormat = new TmfTimestampFormat(TmfTimePreferences.getInstance().getIntervalPattern()); TmfSignalManager.dispatchSignal(new TmfTimestampFormatUpdateSignal(null)); }

Target:
If this method is executed in non-UI thread the receiving components will have thread access problems. (org.eclipse.swt.SWTException: Invalid thread access). In an internal plug-in we see this problem when getting the timezone during a request handling.
Source:
public static TeamWorkFlowArtifact getCodeTeamWorkflowNamed(String name) throws OseeCoreException { for (Artifact art : ArtifactQuery.getArtifactListFromName(name, AtsUtil.getAtsBranchToken(), DeletionFlag.EXCLUDE_DELETED, QueryOptions.EXACT_MATCH_OPTIONS)) { if (art.isOfType(DemoArtifactTypes.DemoCodeTeamWorkflow)) { return (TeamWorkFlowArtifact) art; } } return null; }

Target:
Prefer one return statement.
Source:
private Map<String, String> getTraceProperties() { for (ITmfTrace fTrace : TmfTraceManager.getInstance().getOpenedTraces()) { if (fTrace.getResource().equals(this.getResource())) { if (fTrace instanceof ITmfTraceProperties) { ITmfTraceProperties traceProperties = (ITmfTraceProperties) fTrace; return traceProperties.getTraceProperties(); } } } return null; }

Target:
{ on the same line
Source:
public void setSDWidget(SDWidget sdWidget) { fSdWidget = sdWidget; }

Target:
fsdWidget was protected.
Source:
public boolean isNeedInit() { return fNeedInit; }

Target:
fNeedInit was protected
Source:
public boolean isComputeMinMax() { return fComputeMinMax; }

Target:
Those variables were protected
Source:
public void setStartOccurrence(int occurence) { fStartEventOccurrence = occurence; }

Target:
Those variables were protected
Source:
public Map<String, IFont> getFontPref() { return Collections.unmodifiableMap(fFontPref); }

Target:
fFontPref was protected
Source:
public IUser getAddedBy() { if (addedBy != null && addedBy.eIsProxy()) { InternalEObject oldAddedBy = (InternalEObject) addedBy; addedBy = (IUser) eResolveProxy(oldAddedBy); if (addedBy != oldAddedBy) { if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.RESOLVE, ReviewsPackage.REVIEW_ITEM__ADDED_BY, oldAddedBy, addedBy)); } } } return addedBy; }

Target:
Same issue here. With auto-generated code, we don't want to change what is already here. I personally hate the lack of braces in this case, but we need to stick with whatever is produced by the combination of a) generating the code, and b) running source format on it.
Source:
public boolean hasAllEvents(String[] names) { for (int i = 0; i < names.length; i++) { if (!hasEvent(names[i])) { return false; } } return true; }

Target:
You can use for-each for arrays too, for (String name : names) { !hasEvent(name)
Source:
public void testGetVersion() throws Exception { assertTrue(atsVersionCache.getVersion(teamWf).getName().equals("Test Version")); }

Target:
use assertEquals instead - it gives better output when things don't match. assertEquals("Test Version", atsVersionCache.getVersion(teamWf).getName());
Source:
public Object[] getElements(Object inputElement) { Object[] elements = contentProvider.getElements(inputElement); // add filler elements to ensure alignment with time analysis viewer Object[] oElements = Arrays.copyOf(elements, elements.length + fNumFillerRows); for (int i = 0; i < fNumFillerRows; i++) { oElements[elements.length + i] = FILLER; } return oElements; }

Target:
This change cause a java.lang.ArrayStoreException()
Source:
public void start(BundleContext context) throws Exception { ArchiveCommand.registerFormat("tar", new TarFormat()); ArchiveCommand.registerFormat("tgz", new TgzFormat()); ArchiveCommand.registerFormat("txz", new TxzFormat()); ArchiveCommand.registerFormat("zip", new ZipFormat()); }

Target:
Maybe pull this into a static method that pgm.Archive can invoke without having a BundleContext. Then we don't need to maintain this list in two places.
Source:
public void stop(BundleContext context) throws Exception { ArchiveCommand.unregisterFormat("zip"); ArchiveCommand.unregisterFormat("txz"); ArchiveCommand.unregisterFormat("tgz"); ArchiveCommand.unregisterFormat("tar"); }

Target:
Maybe use a small helper method to setup the registrations: private static final List<String> myFormats = Collections.synchronizedList(new ArrayList<String>()); private static final void register(String name, Format<?> fmt) { myFormats.add(name); ArchiveCommand.registerFormat(name, fmt); } public void stop(BundleContext context) throws Exception { for (String name : myFormats) { ArchiveCommand.unregisterFormat(name); } myFormats.clear(); }
Source:
public void hideAll() { Collection<Phantom> phantoms = fPhantomRegistry.values(); Iterable<Phantom> visiblePhantoms = Iterables.filter(phantoms, new Predicate<Phantom>() { public boolean apply(Phantom phantom) { return phantom.getFigure().getParent() != null; } }); for (Phantom phantom : visiblePhantoms) { handleDecorator(phantom, false, true); } }

Target:
this is the typical case where using Predicate is not wise. Your code would be more readable by filtering in the foreach loop: for (Phantom phantom : fPhantomRegistry.values()) { if (phantom.getFigures.getParent() != null) { handleDecorator(phantom, false, true); } }
Source:
private void joinAll() throws InterruptedException { if (!threads.isEmpty()) { for (Thread thread : threads) { thread.join(); } } }

Target:
Is threads.isEmpty() necessary ? I think the foreach loop can handle the same case.
Source:
public void run() { final Display display = Display.getDefault(); if ((display == null) || display.isDisposed()) { return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (!display.isDisposed()) { scrollView.scrollBy(deltaX, deltaY); } } }); }

Target:
When you close the view the ScrollView control could be disposed but not the display. Better to check if scrollView.isDisposed.
Source:
public SelectGraphWizard(IDataSet data, GraphData gdata) { model = new GraphModel(data); if (edit = (gdata != null) ) { model.setGraph(gdata.graphID); model.setKey(gdata.key); model.setTitle(gdata.title); model.setXSeries(gdata.xSeries); model.setYSeries(gdata.ySeries); } }

Target:
Please write this as two lines edit = (gdata != null); if (edit) It is more readable that way
Source:
private void setControlEnabled(Composite composite, boolean enabled){ composite.setEnabled(enabled); for (Control child : composite.getChildren()) { if (child == removeGraphButton || child == copyGraphButton) { child.setEnabled(false); } if(child instanceof Composite){ setControlEnabled((Composite)child, enabled); } } }

Target:
While this code makes sense. It does not agree with the idea of the function. In addition this gets called once for every child in the tree. Perhaps after setting the enablement for the whole composite you can add a call to removeGraphButton.setEnabled(false); and copyGraphButton.setEnabled(false);
Source:
private void saveDataToModelGraph(String selected) { model.setGraph(selected); setKeyEnablement( GraphFactory.isKeyRequired(model.getGraphID(), model.getDataSet()), GraphFactory.isKeyOptional(model.getGraphID(), model.getDataSet())); }

Target:
Yeah... The systemtap code is not in great shape but we try to improve the bits we touch little by little.
Source:
private void execute() throws ExecutionException { IOperationHistory operationHistory = PlatformUI.getWorkbench().getOperationSupport().getOperationHistory(); operationHistory.execute(this, new NullProgressMonitor(), null/*context*/); }

Target:
Should the context be passed in?
Source:
public static ReviewStatus getReviewStatus(com.google.gerrit.reviewdb.Change.Status gerritStatus) { switch (gerritStatus) { case NEW: return ReviewStatus.NEW; case MERGED: return ReviewStatus.MERGED; case SUBMITTED: return ReviewStatus.SUBMITTED; case ABANDONED: return ReviewStatus.ABANDONED; default: if (gerritStatus != null) { GerritCorePlugin.logError("Internal Error: unexpected change status: " + gerritStatus, new Exception()); } // DRAFT is not correctly parsed for ChangeInfo since Change.Status does not define the corresponding enum field return ReviewStatus.DRAFT; } }

Target:
I get this exception because it's doing a switch on a null: java.lang.NullPointerException at org.eclipse.mylyn.internal.gerrit.core.remote.GerritReviewRemoteFactory.getReviewStatus(GerritReviewRemoteFactory.java:338) at org.eclipse.mylyn.internal.gerrit.core.client.data.GerritQueryResult.<init>(GerritQueryResult.java:51) at org.eclipse.mylyn.internal.gerrit.core.GerritTaskDataHandler.updateTaskData(GerritTaskDataHandler.java:225) at org.eclipse.mylyn.internal.gerrit.core.GerritTaskDataHandler.getTaskData(GerritTaskDataHandler.java:114) at org.eclipse.mylyn.internal.gerrit.core.GerritConnector.getTaskData(GerritConnector.java:160) at org.eclipse.mylyn.internal.tasks.core.sync.SynchronizeTasksJob.synchronizeTask(SynchronizeTasksJob.java:245)
Source:
public Iterable<E> getSubgraphContaining(E element) { final Node<E> node = nodes.get(element); if (node != null) { return new SubgraphBuilder<E>(node).build(); } return Collections.emptyList(); }

Target:
this is not thread safe, nodes can be modified while building the subgraph. I suggest to use Lock for reading and writing accordingly instead of synchronized blocks
Source:
public void init(final IEditorSite site, final IEditorInput input) { AbstractReviewTaskEditorPage.super.init(site, input); IReviewRemoteFactoryProvider factoryProvider = getFactoryProvider(); if (factoryProvider != null) { checkIfModelIsCached(); reviewConsumer = factoryProvider.getReviewFactory().getConsumerForLocalKey(factoryProvider.getRoot(), getTask().getTaskId()); reviewConsumer.addObserver(reviewObserver); reviewConsumer.open(); } }

Target:
What happens if it's null? Should we log an error or something?
Source:
public void setClosed(boolean closed) { if (closed && !isClosed()) { // end list item builder.endBlock(); builder.characters("\n"); //$NON-NLS-1$ // end list block builder.endBlock(); } super.setClosed(closed); }

Target:
should not add newline here either
Source:
public String getHostId() { CTFClock clock = getCTFTrace().getClock(); if (clock != null) { return (String) clock.getProperty(CLOCK_HOST_PROPERTY); } return getName(); }

Target:
here it should use super.getHostId(). It's obviously the same thing now, but if we ever change how TmfTrace defines its host ID, then clock-less CTF traces should follow.
Source:
public boolean canMatchTrace(ITmfTrace trace) { if (!(trace instanceof LttngKernelTrace)) { return false; } LttngKernelTrace ktrace = (LttngKernelTrace) trace; String[] events = { TcpEventStrings.INET_SOCK_LOCAL_IN, TcpEventStrings.INET_SOCK_LOCAL_OUT }; return (ktrace.hasAtLeastOneOfEvents(events)); }

Target:
outer parentheses are not needed
Source:
protected void initMatching() { if (fMatches != null) { fMatches.init(fTraces); } List<ITmfMatchEventDefinition> deflist = fMatchDefinitions.get(getMatchingType()); if (deflist == null) { return; } for (ITmfTrace trace : fTraces) { for (ITmfMatchEventDefinition def : deflist) { if (def.canMatchTrace(trace)) { fMatchMap.put(trace, def); break; } } } }

Target:
Instead of having fMatches be potentially null, couldn't you just check at the constructor to make sure the parameter is not null? (and throw IllegalArgumentException if it is).
Source:
public boolean isSessionAllStop(String sessionId) { DsfServicesTracker servicesTracker = new DsfServicesTracker(MulticoreVisualizerUIPlugin.getBundleContext(), sessionId); IMIRunControl runCtrlService = servicesTracker.getService(IMIRunControl.class); servicesTracker.dispose(); if (runCtrlService != null && runCtrlService.getRunMode() == MIRunMode.ALL_STOP ) { return true; } return false; }

Target:
It is a good habit to avoid public methods unless you need them to be public. Here, since the class in internal, it does not matter, but normally it would be safer to put as private to avoid being stuck with an new API. Ok to leave it as is in this case though.
Source:
public EventList(List<ITimeEvent> list, long startTime, long endTime) { if (list != null) { fEventList = Collections.unmodifiableList(list); } fStartTime = startTime; fEndTime = endTime; }

Target:
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?
Source:
public boolean isSuccessful() { // TODO Auto-generated method stub return false; }

Target:
why is this unsuccessful ?
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); } fTimeGraphProvider.postDrawControl(bounds, gc); }

Target:
should be moved to paint method
Source:
public void handleData(ITmfEvent data) { if (data != null && !(data instanceof ITmfLostEvent)) { fNbRead++; } }

Target:
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.
Source:
private void generateInstallSection(StringBuilder buffer) { buffer.append("%install\n"); buffer.append("rm -rf %{buildroot}\n\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"); }

Target:
No need to clean the buildroot either, rpmbuild handles it internally.
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 if (file.getContents().available() <= 0) return; this.file = file; parse(); }

Target:
Common code style in Linux tools is to have around if statements. Please fix it everywhere.
Source:
public NullOperationLogger() { // singleton so prevent external construction }

Target:
This should not be public
Source:
protected final List<IMergeViewerItem> createMergeViewerItemFrom(Collection<?> values) { List<IMergeViewerItem> ret = newArrayListWithCapacity(values.size()); for (Object value : values) { if (value instanceof EObject) { IMergeViewerItem valueToAdd = createMergeViewerItemFrom((EObject)value); if (valueToAdd != null) { ret.add(valueToAdd); } } } return ret; }

Target:
I suspect the bug is before that point, please investigate more.
Source:
private List<Object> parseList(String str) { List<Object> rc = new ArrayList<Object>(); String temp = str.trim(); Pattern pattern = isPatternFoundList(str); if (pattern == null) return null; Matcher variableMatcher = pattern.matcher(temp); if (variableMatcher != null) { while (variableMatcher.find()) { rc.add(variableMatcher.group()); } } return rc; }

Target:
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.
Source:
public static boolean containsErrors(Comparison comparison) { boolean isError = false; Diagnostic diagnostic = comparison.getDiagnostic(); if (diagnostic != null) { return diagnostic.getSeverity() > Diagnostic.WARNING; } return isError; }

Target:
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.
Source:
public final IAnalysisModule getAnalysisModule(String analysisId) { if (!fAnalysisModules.containsKey(analysisId)) { return null; } return fAnalysisModules.get(analysisId); }

Target:
Unnecessary check, the get() below will return null
Source:
public void setParameter(String name, Object value) { synchronized (fParameters) { 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); } } }

Target:
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!)
Source:
public void registerOutput(IAnalysisOutput output) { fOutputs.add(output); }

Target:
One output could be added many times. Do we need to prevent that?
Source:
public static void registerParameterProvider(String analysisId, Class<? extends IAnalysisParameterProvider> paramProvider) { if (!fParameterProviders.containsKey(analysisId)) { fParameterProviders.put(analysisId, new ArrayList<Class<? extends IAnalysisParameterProvider>>()); } fParameterProviders.get(analysisId).add(paramProvider); }

Target:
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.
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); } remoteEmfObservers.add(observer); }

Target:
This could add null as an observer. Why would that be allowed?
Source:
public void testExecuteQueryRestWithEmptyOption() throws Exception { String query = "status:open"; String option = ""; List<GerritQueryResult> results = null; try { results = executeQueryRest(query, option); } catch (GerritException e) { exception.expect(GerritHttpException.class); exception.expectMessage(HTTP_ERROR_400); return; } assertNotNull(results); }

Target:
Done
Source:
public void testExecuteQueryWithOption() throws Exception { String query = "status:open"; String option = "LABELS"; List<GerritQueryResult> results = executeQuery(query, option); assertNotNull(results); }

Target:
These assertions don't help much to validate correctness of the returned result. Could we assert on the content?
Source:
public void setState(final String commandId, final boolean state) { if (commandId.equals(IOutlineViewState.SHOW_ELEMENT_CONTENT)) { showElementContent = state; } }

Target:
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.
Source:
public 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(); } }

Target:
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.
Source:
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; }

Target:
Please always use curly braces in 'for' statements.
Source:
private IASTName getLastInQualified(IASTName name) { if (name instanceof ICPPASTQualifiedName) { name= name.getLastName(); } return name; }

Target:
Redundant condition.
Source:
protected EPackage createModel(EPackage parent, TestRemoteEPackage remotePackage) { EPackage pckg = EcoreFactory.eINSTANCE.createEPackage(); pckg.setName(remotePackage.name.replaceAll("Remote", "Local")); System.err.println(pckg); return pckg; }

Target:
Remove as in https://git.eclipse.org/r/#/c/15004/9
Source:
public boolean hasTasks() { return !(fForegroundTasks.isEmpty() && fBackgroundTasks.isEmpty()); }

Target:
This could be private too.
Source:
public static KeyStroke getKeystrokeOfBestActiveBindingFor(String commandId) { 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; }

Target:
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".
Source:
public void add(Integer art_id, Integer branchId, Integer transactionId) { this.branchId = branchId; entries.add(new Entry(art_id, branchId, transactionId)); }

Target:
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?
Source:
public boolean isBranchesAllCommittedExcept(Artifact art, Branch branch) { boolean toReturn = false; try { toReturn = AtsBranchManagerCore.isBranchesAllCommittedExcept((TeamWorkFlowArtifact) art, branch); } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex.toString(), ex); toReturn = false; } return toReturn; }

Target:
Should there be a second catch for ClassCastException? is art checked somewhere to verify that it is always a teamWorkFlowArtifact?
Source:
public void commitBranch(Artifact art, Branch branch, boolean isArchiveSource) { 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); } }

Target:
Should there be a second catch for ClassCastException? is art checked somewhere to verify that it is always a teamWorkFlowArtifact?
Source:
public Change perform(IProgressMonitor pm) throws CoreException { Resource roomRes = rs.getResources().get(0); // resolve all cross references for(Resource res : rs.getResources()) 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; }

Target:
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?
Source:
public DebugStringVariableSubstitutor(String projectName) { this(projectName == null ? null : projectName.isEmpty() ? null : ResourcesPlugin.getWorkspace().getRoot().getProject(projectName)); }

Target:
Probably slightly better: projectName == null || projectName.isEmpty() ? null ... Why is projectName empty instead of null for projectless debugging? Should this itself be changed?
Source:
AbstractDataManipulator (String title, IPath pathWorkDir, IProject project) { this.title = title; this.pathWorkDir=pathWorkDir; this.project=project; threads = new ArrayList<Thread>(); }

Target:
This should be simplified to : super(title, pathWorkingDir); this.project = project;
Source:
public String getColumnText(MyModel element, int columnIndex) { if (element instanceof MyModel) { switch (columnIndex) { case 0: return ((MyModel)element).col1; case 1: return ((MyModel)element).col2; } } return ""; }

Target:
Strange check
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. if (!Arrays.equals(packChecksum, idx.packChecksum)) invalidBitmap = true; else bitmapIdx = idx; } return bitmapIdx; }

Target:
if not its good, do the bad, else do the good?
Source:
protected AbstractRebaseCommandHandler(String jobname, String dialogMessage) { this.dialogMessage = dialogMessage; this.jobname = jobname; }

Target:
you unnecessarily flipped the order of these two statements which makes the diff unnecessarily larger
Source:
public RebaseOperation(Repository repository, Operation operation) { Assert.isTrue(operation != Operation.BEGIN); this.repository = repository; this.operation = operation; this.ref = null; }

Target:
where did this come from ? you claim this is a refactoring
Source:
protected boolean isDragEnabled() { if (getScoutObject() != null) { return getScoutObject().isDragEnabled(); } else { return false; } }

Target:
You can omit the explicit else-case and "return false" directly instead.
Source:
public boolean validate(String path) { boolean valid = false; if (fTrace != null) { valid = standardValidate(path); } else if (TmfTraceType.isCustomTraceId(getCanonicalName())) { valid = customValidate(path); } return valid; }

Target:
I don't think we need this anymore. (we may be able to kill customValidate(String bla) also. woooooooooooOOOOOOOOOOOOOoooooooooooooOOOOOOOOOOoooooooOOOOOOOOOoooooOOOOOOOOoooooOOOOOOoooooOOOOOoooooo
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); CompareConfiguration configuration = ((CompareEditorInput)editorInput) .getCompareConfiguration(); } } } return propertySheetPage; } return null; }

Target:
Remove this line too because the variable "configuration" will become useless.
Source:
public static void generateTrace() { 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); }

Target:
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.
Source:
private String getImplementationVersion() { Package pkg = getClass().getPackage(); if (pkg != null) { return pkg.getImplementationVersion(); } return null; }

Target:
Style nit: no braces here
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(); if (isAlreadyEncoded(fullPath)) { uri = URI.createPlatformResourceURI(fullPath, false); } else { uri = URI.createPlatformResourceURI(fullPath, true); } return uri; }

Target:
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.
Source:
protected Session getSession(URI sessionModelURI) { Session sessionFromURI = null; 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; }

Target:
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).
Source:
public String toString() { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.print("HashSettings:"); for(Map.Entry<String, String> e : settings.entrySet()) pw.print(e.getKey()+"="+e.getValue()+";"); pw.close(); return sw.toString(); }

Target:
Add brackets around loop body (required by code conventions).
Source:
public RemoteConnector(RemoteSettings settings) { fSettings = settings; new Throwable().printStackTrace(); }

Target:
Please remove.
Source:
public TerminalInfoView() { addToList(this); }

Target:
Should call super() here.
Source:
String getDefault(String val, String defaultVal) { if(val == null || val.trim().equals("")) { //$NON-NLS-1$ return defaultVal; } else { return val; } }

Target:
Should be private.
Source:
synchronized public 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); } } }

Target:
public synchronized
Source:
static synchronized void addToList(TerminalInfoView view) { views.add(view); }

Target:
Visibility missing. Synchronized comes before static
Source:
static void alignRead(BitBuffer input, IDeclaration declaration){ int align = (int) declaration.getAlignment(); int pos = input.position() + ((align - (input.position() % align)) % align); input.position(pos); }

Target:
"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.
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>(); if (fExecutor != null) { fExecutor.stop(); } fExecutor = new TmfRequestExecutor(); fSignalDepth = 0; fLogData = TmfCoreTracer.isEventTraced(); // fLogError = TmfCoreTracer.isErrorTraced(); TmfProviderManager.register(fType, this); }

Target:
Do we actually call init multiple times on a trace or is it a safe-guard? Just curious.
Source:
private TmfTraceManager() { fTraces = new LinkedHashMap<ITmfTrace, TmfTraceContext>(); fFilters = new LinkedHashMap<ITmfTrace, ITmfFilter>(); TmfSignalManager.registerVIP(this); }

Target:
I think the filter should be part of the TmfTraceContext. Please move it there.
Source:
public void setPriorities(List<RuleSpecification<?>> ruleSpecGroup) { priorities.clear(); int priority = ruleSpecGroup.size() + priorities.size(); for (RuleSpecification<?> rule : ruleSpecGroup) { this.setPriority(rule, priority); priority--; } }

Target:
remove clear() call (probably left over from refactor)
Source:
public EventDrivenTransformationRule(String name, IQuerySpecification<Matcher> precondition, IMatchProcessor<Match> action, IncQueryActivationStateEnum transition, ActivationLifeCycle lifeCycle) { Job<Match> stJob = Jobs.newStatelessJob(transition, action); Job<Match> job = Jobs.newRecordingJob(stJob); ruleSpecification = Rules.newMatcherRuleSpecification(precondition, lifeCycle, CollectionLiterals.newHashSet(job)); }

Target:
default usage of recording job seems problematic, please remove. The model editing API should handle editing domains and such
Source:
public boolean isPaused() { synchronized (fSynchObject) { return fIsPaused; } }

Target:
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/
Source:
public synchronized void suspend() { synchronized (fSynchObject) { fIsPaused = true; } TmfCoreTracer.traceRequest(fRequest, "SUSPENDED"); //$NON-NLS-1$ }

Target:
synchronized block is not needed
Source:
public EvalBinding(IBinding binding, IType type, IBinding templateDefinition) { super(templateDefinition); fParameterPosition = -1; fBinding= binding; fType= type; fFixedType= type != null; if (fBinding == null) { CCorePlugin.log(new NullPointerException()); } }

Target:
Please add a TODO to replace logging with throwing NPE.
Source:
public void cleanupTraces() { TmfTestTrace.A_TEST_10K.dispose(); CtfTmfTestTrace.KERNEL.dispose(); }

Target:
For symmetry's sake, it'd be better to load those (the .getTrace()) in a @Before method.
Source:
protected Double getDoubleValue(Object o) { 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; } }

Target:
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.
Source:
public String toString() { return String.format("title = [ %s ], author = [ %s ], company = [ %s ]", title.toString(), author.toString(), company.toString()); }

Target:
I don't think we need to call .toString() on objects passed to String.format - the method does that internally.
Source:
private void addRepository(File repositoryDir) { util.addConfiguredRepository(repositoryDir); if (doAutoShare()) { autoShareProjects(repositoryDir); } }

Target:
style nit: no braces around single line block
Source:
public boolean equals(Object obj) { return obj instanceof ResourceByDefinitionKey && key.hashCode() == obj.hashCode(); }

Target:
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)
Source:
public IInputOrder getInputOrder(String path) { // TODO Convert both paths to absolute? for (InputOrder io : getInputOrderList()) { String ioPath = (new Path(io.getPath())).toOSString(); if (path.compareToIgnoreCase(ioPath) == 0) { return io; } } return null; }

Target:
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."
Source:
private void createDiff(RevCommit parent) { Diff diff = revision.getDiffToParent(parent); if (diff != null) { try { createDiffLinkAndText(parent, diff); } catch (IOException e) { Activator.logError( "Error creating diff in blame information control for commit " + parent.toObjectId(), e); //$NON-NLS-1$ } } }

Target:
Line is too long
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) { if (tagName.startsWith(Constants.R_TAGS)) { tagRefNamesToSelect.add(tagName); } else { tagRefNamesToSelect.add(Constants.R_TAGS + tagName); } } }

Target:
style nit: no braces here
Source:
private void setWindowTitle(boolean pushMode) { final String title; if (pushMode) { title = UIText.RefSpecWizard_pushTitle; } else { title = UIText.RefSpecWizard_fetchTitle; } setWindowTitle(title); }

Target:
We don't use braces ({}) for such simple one-line statements, please remove them.
Source:
public IAtsUser getTransitionAsUser() throws OseeCoreException { IAtsUser user = helper.getTransitionUser(); if (user == null) { System.err.println("Unexpected: AtsCore.getUserService().getCurrentUser();"); user = AtsCore.getUserService().getCurrentUser(); } return user; }

Target:
Should this be a thrown exception?
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)); } } return ICreaterepoConstants.EMPTY_LIST; }

Target:
Do we need this constant at all? Isn't Collections.emptyList() sufficient?
Source:
public void setUp() throws CTFReaderException { fixture = new BitBuffer(java.nio.ByteBuffer.allocateDirect(128)); fixture.setByteOrder(ByteOrder.BIG_ENDIAN); createBuffer(fixture); }

Target:
We import it already, no need for the java.nio part.
Source:
public IntegerStateValue(int valueAsInt) { this.value = new Integer(valueAsInt); }

Target:
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.)
Source:
public boolean equals(@Nullable Object object) { if (!(object instanceof IntegerStateValue)) { return false; } IntegerStateValue other = (IntegerStateValue) object; return this.unboxInt() == other.unboxInt(); }

Target:
you could use this.value == other.value here, and in the other classes too. Would save one function call, I guess?
Source:
public String getFormattedValue() { if (formattedValue == null) { List<String> strings = new ArrayList<String>(); for (CtfTmfEventField element : getValue()) { strings.add(element.getFormattedValue()); } formattedValue = strings.toString(); } return formattedValue; }

Target:
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.
Source:
private Set<String> getStringSet(String key) { String prefSetting = getIndexer().getProperty(key); if (prefSetting != null && prefSetting.length() > 0) { return new HashSet<String>(Arrays.asList(prefSetting.split(","))); //$NON-NLS-1$ } return Collections.emptySet(); }

Target:
Better: prefSetting != null && !prefSetting.isEmpty()
Source:
private String getHeadName(Ref head) { String headName; if (head.isSymbolic()) headName = head.getTarget().getName(); else headName = head.getObjectId().getName(); return headName; }

Target:
this method can be declared static
Source:
public void testSetValue() { fixture.setValue("dummy"); String result = fixture.getValue(); assertNotNull(result); assertEquals(result, "dummy"); }

Target:
the order of arguments in assert*() is counter-intuitive... it's (expected, actual). Technically the 'result' variables should always be second.
Source:
public void decorateHeaderCell() { HeaderCell cell = m_headerCell; decorateHeaderCellInternal(cell); try { execDecorateHeaderCell(cell); getTable().getColumnSet().updateColumn(this); } catch (ProcessingException e) { LOG.warn(null, e); } catch (Throwable t) { LOG.warn(null, t); } }

Target:
this can give a NullPointerException since getTable() can return null
Source:
public boolean isModified(DirCacheEntry entry, boolean forceContentCheck) { return isModified(null, false, null); }

Target:
Why does it pass null instead of entry here?