auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void registerModule(IAnalysisModule module) { if (module == null) { throw new IllegalArgumentException(); } ITmfTrace selectedTrace = TmfTraceManager.getInstance().getActiveTrace(); /* If no trace is active, just register the module */ if (selectedTrace == null) { fModule = module; return; } @SuppressWarnings("resource") IAnalysisModule selectedModule = selectedTrace.getAnalysisModule(module.getId()); /* register only if the module is for the currently selected trace */ if (selectedModule == module) { fModule = module; } }

Target:
Don't put this, it's a "real" warning atm, until we get rid of it ;)
Source:
public RankedAdapterFactoryDescriptor.Registry getAdapterFactoryRegistry() { RankedAdapterFactoryDescriptorRegistryImpl rankedAdapterFactoryRegistry = new RankedAdapterFactoryDescriptorRegistryImpl( ComposedAdapterFactory.Descriptor.Registry.INSTANCE, Multimaps .unmodifiableMultimap(adapterFactoryRegistry)); return rankedAdapterFactoryRegistry; }

Target:
this method should return the same instance each time (meaning of "get"), store this value in a field named 'adapterFactoryRegistry'
Source:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { try (IAnalysisModule module = createModule();) { if (module != null) { return module.getAnalysisRequirements(); } return Collections.EMPTY_SET; } }

Target:
Not sure if it's worth changing this, once we remove AutoCloseable from IAnalysisModule, this will become an _error_! *gasp*
Source:
protected int getReplaceOffset() { int start; if (fContext instanceof DocumentTemplateContext) { DocumentTemplateContext docContext = (DocumentTemplateContext)fContext; start= docContext.getStart(); } else { start= fRegion.getOffset(); } return start; }

Target:
Why do you need this? Can't you pass the offset via context or region?
Source:
public void setLockStatePrefetchEnabled(boolean enabled) { checkActive(); IEvent event = null; synchronized (CDOViewImpl.this) { if (enabled != lockStatePrefetchEnabled) { lockStatePrefetchEnabled = enabled; if (enabled) { cdoLockStatePrefetcher = new CDOLockStatePrefetcher(CDOViewImpl.this); } else if (cdoLockStatePrefetcher != null) { cdoLockStatePrefetcher.dispose(); cdoLockStatePrefetcher = null; } event = new LockStatePrefetchEventImpl(enabled); } } fireEvent(event); }

Target:
Why not just an "else"?
Source:
public Collection<LockState<OBJECT, CONTEXT>> getLockStates() { return new ArrayList<RWOLockManager.LockState<OBJECT, CONTEXT>>(objectToLockStateMap.values()); }

Target:
It seems safer to synchronize this method! And all other methods return a List<...>.
Source:
public static void checkConfiguration() { // Schedule a job // This avoids that the check is executed too early // because in startup phase the JobManager is suspended // and scheduled Jobs are executed later Job job = new Job(UIText.ConfigurationChecker_checkConfiguration) { @Override protected IStatus run(IProgressMonitor monitor) { if (PlatformUI.isWorkbenchRunning()) PlatformUI.getWorkbench().getDisplay() .asyncExec(new Runnable() { public void run() { check(); } }); else schedule(1000L); return Status.OK_STATUS; } }; job.schedule(); }

Target:
Could you add braces for if and else? We only omit the braces in simple statements.
Source:
public String getLabel(long time){ try { int quark = fValuechange.handleEntry(fBaseQuark, time); ITmfStateInterval value = fSs.querySingleState(time, quark); if (value != null && !value.getStateValue().isNull()) { ITmfStateValue state = value.getStateValue(); return state.toString(); } } catch (StateValueTypeException | TimeRangeException | AttributeNotFoundException | StateSystemDisposedException e) { } return null; }

Target:
extra blank line
Source:
private static Collection<CustomEventTableColumn> generateColumns(CustomTraceDefinition definition) { List<CustomEventTableColumn> columns = new LinkedList<>(); List<OutputColumn> outputs = definition.outputs; for (int i = 0; i < outputs.size(); i++) { String name = outputs.get(i).name; if (name != null) { columns.add(new CustomEventTableColumn(name, i)); } } return columns; }

Target:
LinkedList :(
Source:
public TmfConstantTransform(ITmfTimestamp offset) { fOffset = new TmfNanoTimestamp(offset); }

Target:
If (?!) the offset is larger than Long.MAX_VALUE nanoseconds (using a different scale), this will overflow...
Source:
private String buildConflictingMessage(MergeResult mergeResult) { final StringBuilder messageBuildder = new StringBuilder(); final Integer returnCode; for (String conflictingFile : mergeResult.getConflicts().keySet()) { messageBuildder.append("Auto-merging failed in ").append(conflictingFile).append(EOL); messageBuildder.append("Automatic merge failed; fix conflicts and then commit the result.") .append(conflictingFile).append(EOL); } return messageBuildder.toString(); }

Target:
Unused variable
Source:
private boolean isAdd(ReferenceChange diff, boolean rightToLeft) { return rightToLeft ? isLeftDeleteOrRightAdd(diff) : isLeftAddOrRightDelete(diff); }

Target:
Please install checkstyle in your environment (https://wiki.eclipse.org/EMF_Compare/Contributor_Guide#Checkstyle), we forbid the use of the ternary operator in EMF Compare. This should be if (rightToLeft) { return isLeftDeleteOrRightAdd(diff); } else { return isLeftAddOrRightDelete(diff); }
Source:
private boolean isLeftAddOrRightDelete(ReferenceChange diff) { return (diff.getKind() == DifferenceKind.ADD && diff.getSource() == DifferenceSource.LEFT) || (diff.getKind() == DifferenceKind.DELETE && diff.getSource() == DifferenceSource.RIGHT); }

Target:
Checkstyle would allow this one, but I think the following would be easier to read : if (diff.getSource() == DifferenceSource.LEFT) { return diff.getKind() == DifferenceKind.ADD; } else { return diff.getKind() == DiferenceKind.DELETE; }
Source:
public void characters(String text) { assertOpenBlock(); try { for (int x = 0; x < text.length(); ++x) { char c = text.charAt(x); currentBlock.write(c); } } catch (IOException e) { throw new RuntimeException(e); } }

Target:
why not just use currentBlock.write(text) here?
Source:
public void entityReference(String entity) { throw new UnsupportedOperationException("Builder does not currently support entity references."); //$NON-NLS-1$ }

Target:
no need for messages on these exceptions (detail will be available from the stack trace, and these throw statements will have to be removed as part of this review chain anyways)
Source:
protected void finalize() throws Throwable { ((ClassDiagramPattern) comboSelection).setPatternConfiguration(false, false); super.finalize(); }

Target:
Do not configure the selected pattern from here. If the user clic on finish, the skeleton will be created with the default value. Another remark : you make again a dangerous cast: the combo selection is a IPatternPovider, You will not have enough time but ClassDiagramPattern is expected to have friends.
Source:
public Collection<IPatternProvider> getPatternsList() { Collection<IPatternProvider> newPatternList = new ArrayList<IPatternProvider>(); //creating a class Diagram pattern //and create his own command // the command can be changed by configuration page. ClassDiagramPattern pattern = new ClassDiagramPattern(); pattern.setPatternCommand(new InitializerCommand(resourceSet, selection)); newPatternList.add(pattern); return newPatternList; }

Target:
You must not init here the command. You configuration page should configure the pattern provider and it will instantiate the command on demand.
Source:
public void run() { InitializerWizard wizard = new InitializerWizard(this.editingDomain.getResourceSet(), selection); WizardDialog dialog = new WizardDialog(null, wizard); dialog.create(); if (dialog.open() == Window.OK) this.result = wizard.getCommand(); }

Target:
Please, add { and } to the if statement. if (dialog.open() == Window.OK) { ICommand cmd = wizard.getCommand(); //command execution ? } Modifiy the inheritance of the action and add the command execution
Source:
public int compareTo(Filter other) { if (!this.methodName.equals(other.methodName)) { return this.methodName.compareTo(other.methodName); } else if (!this.className.equals(other.className)) { return this.className.compareTo(other.className); } return 0; }

Target:
Rewrite as: int c = methodName.compareTo(other.methodName); if (c != 0) return c; return className.compareTo(other.className);
Source:
public void addFilter(ITmfFilterTreeNode filter) { ITmfFilterTreeNode root = fViewer.getInput(); for (int i = 0; i < root.getChildrenCount(); i++) { if (root.getChild(0).equals(filter)) { return; } } root.addChild(filter); fViewer.setInput(root); }

Target:
did you mean getChild(i)?
Source:
public TmfConstantTransform(long offset) { fOffset = Long.valueOf(offset); }

Target:
fOffset = offset?
Source:
public InputStream prefetchStream(URI uri, Map<?, ?> options) throws IOException { InputStream stream = createInputStream(uri, options); if (stream != null) { synchronized(prefetchedStreams) { prefetchedStreams.put(uri, stream); } } return stream; }

Target:
put(uri, stream) on a concurrentHashMap avoids the "synchronized"
Source:
public String getTargetTypeName(ILaunchTarget target) { return getContribution(target) == null ? null : getContribution(target).name; }

Target:
Instead of all these null check why don't you make getContribution always return non-null? I.e. return default provider if there is no mapping
Source:
public Set<ApprovalCategoryValue.Id> getApprovals() { return Collections.unmodifiableSet(approvals); }

Target:
Why are you using "Collections.unmodifiableSet(approvals);" and not just "approvals" since the variable is already defined as "Collections.unmodifiableSet"
Source:
public void testRetrieveCollecton() throws ItemNotFoundException, IllegalOperationException, IOException, AccessDeniedException, NoSuchResourceStoreException { final String collectionPath = "/dir"; final StorageItem item = unzipRepo.doRetrieveItem(new ResourceStoreRequest(collectionPath)); Assert.assertTrue(item instanceof ZipAwareStorageCollectionItem); final StorageCollectionItem collectionItem = (StorageCollectionItem) item; Assert.assertEquals(collectionPath, collectionItem.getPath()); TestUtil.assertMembers(new String[] { "/dir/subdir" }, new String[0], collectionItem.list()); }

Target:
(minor) simply declare "throws Exception" to remove clutter. This is perfectly OK for test methods. Same for other test methods in this class I guess.
Source:
public static TraceLogLevel valueOfString(String name) { if (name == null) { throw new InvalidParameterException(); } for (TraceLogLevel tllevel : TraceLogLevel.values()) { if (tllevel.getInName().equalsIgnoreCase(name)) { return tllevel; } } // No match return LEVEL_UNKNOWN; }

Target:
Use InvalidArgumentException instead
Source:
public ILocation getLocation() { LineRange selectedRange = getSelectedRange(); ILineLocation location = ReviewsFactory.eINSTANCE.createLineLocation(); ILineRange range = ReviewsFactory.eINSTANCE.createLineRange(); range.setStart(selectedRange.getStartLine()); range.setEnd(selectedRange.getStartLine() + selectedRange.getNumberOfLines()); location.getRanges().add(range); return location; }

Target:
Fine to move the command, but since you try to refactor the code, this method should be private
Source:
public long getId() { return fId; }

Target:
should remain int too
Source:
public void widgetSelected(SelectionEvent e) { IStructuredSelection selection = viewer.getStructuredSelection(); if (selection != null) { viewer.editElement(selection.getFirstElement(), 0); } }

Target:
Okay then I will apply a patch for your proposed bug report.
Source:
public int compareQualifier(RepositoryVersion other) { if (this.qualifier != null && other.qualifier == null) { return -1; } else { if (this.qualifier == null && other.qualifier != null) { return 1; } else { if (this.qualifier == null && other.qualifier == null) { return 0; } else { return this.qualifier.compareTo(other.qualifier); } } } }

Target:
protected?
Source:
public int compareMajor(RepositoryVersion other) { if (this.major != null && other.major == null) { return 1; } else { if (this.major == null && other.major != null) { return -1; } else { if (this.major == null && other.major == null) { return 0; } else { return this.major - other.major; } } } }

Target:
Should these be protected?
Source:
public Version toOSGIVersion() { return new Version(toString()); }

Target:
Should this return null if version is not a valid OSGI version?
Source:
private String getTeamStr(ArtifactReadable action) { String results = action.getSoleAttributeAsString(AtsAttributeTypes.TeamDefinition, ""); if (Strings.isValid(results)) { results = atsServer.getArtifactByGuid(results).getName(); } else { ArtifactReadable teamWf = getParentTeamWf(action); if (teamWf != null) { return getTeamStr(teamWf); } } return results; }

Target:
For consistency, suggest replace return with results =
Source:
public void addData(String guid, String classification, PageOrientation orientation) { DataRightEntry toAdd = new DataRightEntry(); toAdd.setClassification(classification); toAdd.setGuid(guid); toAdd.setOrientation(orientation); getData(); data.add(toAdd); }

Target:
one line this --- getData().add(toAdd);
Source:
private Map<String, ContextSensitiveTokenType> createContextSensitiveTokenMap( ICPPParserExtensionConfiguration config) { Map<String, ContextSensitiveTokenType> result = new HashMap<String, ContextSensitiveTokenType>(); result.put(new String(Keywords.cOVERRIDE), ContextSensitiveTokenType.OVERRIDE); result.put(new String(Keywords.cFINAL), ContextSensitiveTokenType.FINAL); result.putAll(config.getAdditionalContextSensitiveKeywords()); return result; }

Target:
Makes sense to add a string constant to Keywords. Same for FINAL.
Source:
protected TreeViewer doCreateTreeViewer(Composite parentComposite, int style) { fCheckboxTreeViewer = new CheckboxTreeViewer(parentComposite, style); fCheckboxTreeViewer.addCheckStateListener(new ICheckStateListener() { @Override public void checkStateChanged(CheckStateChangedEvent event) { fObjects.put(event.getElement(), event.getChecked()); } }); treeViewer = fCheckboxTreeViewer; return treeViewer; }

Target:
treeViewer is already set in base class from the return value of this method.
Source:
private void checkSubtree(Object element, boolean state) { TreeItem item = (TreeItem) fCheckboxTreeViewer.testFindItem(element); if (!state || (item != null)) { fObjects.put(element, state); for (Object o : ((ITreeContentProvider) fCheckboxTreeViewer.getContentProvider()).getChildren(element)) { checkSubtree(o, state); } } }

Target:
Would it be better to use getPatternFilter().isElementVisible()? ...and... the answer is no, because there could be other external filters on the viewer, since TimeGraphFilterDialog has an addFilter() method ;(
Source:
private boolean isDTreeItemContainerOwnedTreeItems(Notification notification) { return notification.getFeature() == TreePackage.Literals.DTREE_ITEM_CONTAINER__OWNED_TREE_ITEMS && notification.getNotifier() instanceof DTreeItemContainer; }

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

Target:
Nitpick: the instanceof check is redundant here.
Source:
protected void sendDispositionHeader(OutputStream out) throws IOException { super.sendDispositionHeader(out); out.write(EncodingUtil.getAsciiBytes(FILE_NAME)); out.write(QUOTE_BYTES); out.write(EncodingUtil.getBytes(filename, getCharSet())); out.write(QUOTE_BYTES); }

Target:
I think this still needs to check that the filename is not null.
Source:
public CriteriaSet getLastCriteriaSet() { return criterias.get(criterias.size() - 1); }

Target:
check for empty criterias?
Source:
protected Long getBranchUuidFromTxId(int tx) { QueryFactory queryFactory = orcsApi.getQueryFactory(getContext()); TransactionQuery txQuery = queryFactory.transactionQuery(); Long branchId = txQuery.andTxId(tx).getResults().getExactlyOne().getBranchId(); return branchId; }

Target:
Any reason why this can't simply call getQueryFactory()?
Source:
String getViewId() { return fViewId; }

Target:
private? (the outer class will still be able to access it)
Source:
protected Collection<? extends ITmfTrace> getTraces() { Set<ITmfTrace> traces = new HashSet<>(); for (ITmfTrace trace : fTraces) { traces.addAll(Arrays.asList(TmfTraceManager.getTraceSet(trace))); } return traces; }

Target:
wow, this is hard to understand :P I assume it makes sense... You don't want to include the experiments, you just want the "real" traces, so you unpack all experiments. But in that case, why not just do this unpacking when you write into fTraces instead? So this method can remain a simple getter. Although if it's exposed publicly, the collection should be either synchronized or Immutable
Source:
public void setUp() throws Exception { IEclipseContext globalContext = Activator.getDefault() .getGlobalContext(); workbenchContext = globalContext.createChild("workbenchContext"); ContextInjectionFactory.make(CommandServiceAddon.class, workbenchContext); ContextInjectionFactory.make(ContextServiceAddon.class, workbenchContext); ContextInjectionFactory.make(BindingServiceAddon.class, workbenchContext); defineCommands(workbenchContext); defineContexts(workbenchContext); defineBindingTables(workbenchContext); }

Target:
I think throws Exception can be removed
Source:
protected static Collection<IResourceSetHook> getMatchingHooks( ResourceSetHookRegistry resourceSetHookRegistry, final Collection<URI> urisToLoad) { final Collection<IResourceSetHook> hooks; if (resourceSetHookRegistry == null) { hooks = Collections.emptyList(); } else { hooks = Collections2.filter(resourceSetHookRegistry.getResourceSetHooks(), new Predicate<IResourceSetHook>() { public boolean apply(IResourceSetHook input) { return input.isHookFor(urisToLoad); } }); } return hooks; }

Target:
private
Source:
private void importProjects(final Set<File> dotProjectFiles) { WorkspaceJob job = new WorkspaceJob( UIText.ImportChangedProjectsCommand_ImportingChangedProjects) { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { for (File f : dotProjectFiles) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } String ap = f.getAbsolutePath(); importProject(ap); } return Status.OK_STATUS; } }; job.schedule(); }

Target:
no braces
Source:
public void cleanup() { module.close(); }

Target:
I get a NPE here when I don't the traces downloaded. Also in the other tests that were modified.
Source:
public IAtsProgram getProgram(Object artifact) { IAtsProgram program = null; if (artifact instanceof ArtifactReadable) { ArtifactReadable artRead = (ArtifactReadable) artifact; if (artRead.isOfType(AtsArtifactTypes.Program)) { program = new Program(logger, atsServer, (ArtifactReadable) artifact); } } return program; }

Target:
Any reason why you can't use artRead instead of casting artifact again?
Source:
public Properties getStatistics() throws GitAPIException { try { GC gc = new GC((FileRepository) repo); gc.setPackConfig(pconfig); return toProperties(gc.getStatistics()); } catch (IOException e) { throw new JGitInternalException( JGitText.get().couldNotGetRepoStatistics, e); } }

Target:
I think this isn't necessary here since getStatistics() doesn't need the configuration
Source:
public int compareTo(@Nullable ITmfStateValue object) { if (object instanceof NullStateValue){ return -1; } return 1; }

Target:
Careful with the return value: returning -1 means nullstate value is smaller than all other objects. It should also be that other objects are greater than nullstate value, so you should do explicitly in other methods if (object instanceof NullStateValue) return 1; Also, for your unit tests, you should always do both ways, for instance, assertTrue(val1.compareTo(val2) > 0); assertFalse(val2.compareTo(val1) > 0);
Source:
public IContainerDMContext[] getTargetFilters() throws CoreException { synchronized (fFilteredThreadsByTarget) { Set<IContainerDMContext> set = fFilteredThreadsByTarget.keySet(); return set.toArray(new IContainerDMContext[set.size()]); } }

Target:
I think it is safe to only synchronize the iteration of the next line. It is ok if the set changes but not while we are iterating over it.
Source:
public MPartStack createStack(String id, boolean visible) { MPartStack newStack = modelService.createModelElement(MPartStack.class); // temporary HACK for bug 303982 newStack.getTags().add("newtablook"); //$NON-NLS-1$ newStack.setElementId(id); newStack.setToBeRendered(visible); return newStack; }

Target:
Did not check, but can this method be declared as private?
Source:
public void insert(MUIElement toInsert, MUIElement relTo, int swtSide, float ratio) { int pct = (int) (ratio * 10000); insert(toInsert, relTo, swtSide, pct); }

Target:
Did not check, but can this method be declared as private?
Source:
public ChainingCredentialsProvider(CredentialsProvider... providers) { this.credentialProviders = new LinkedList<CredentialsProvider>(); for (CredentialsProvider p : providers) credentialProviders.add(p); }

Target:
Why not use `credentialsProviders = new ArrayList<CredentialsProvider>(Arrays.asList(providers))` instead of a LinkedList? Not that it matters here, but see: http://stackoverflow.com/q/322715/305973
Source:
public static boolean isReactOnSelection() { IPreferenceStore preferenceStore = getPreferencesStore(); if (!preferenceStore .contains(UIPreferences.REBASE_INTERACTIVE_SYNC_SELECTION)) preferenceStore.setDefault( UIPreferences.REBASE_INTERACTIVE_SYNC_SELECTION, true); return preferenceStore .getBoolean(UIPreferences.REBASE_INTERACTIVE_SYNC_SELECTION); }

Target:
I think setting defaults is usually in the PluginPreferenceInitializer class.
Source:
public void testCreateArtifactsEmpty() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); RoughArtifact roughParent = new RoughArtifact(RoughArtifactKind.CONTAINER); RoughArtifactCollector collector = new RoughArtifactCollector(roughParent); dtc.createArtifacts(collector); // exception because there is no data Assert.fail(); }

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

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

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

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

Target:
fail is unecesary if an exception doesn't happen test will fail.
Source:
public RoughArtifact populateArtifact(Queue<DoorsTableRow> queue) { Conditions.checkNotNullOrEmpty(queue, "Queue"); RoughArtifact combined = populateArtifact(queue.poll()); while (!queue.isEmpty()) { combineDoorsArtifacts(combined, populateArtifact(queue.poll())); } return combined; }

Target:
why the double poll here? should this use drain instead ?
Source:
public static synchronized DoorsColumnType fromString(String value) { // special case since Verification Criteria column heading varies by program if (value.contains("Verification Criteria")) { value = "Verification Criteria"; } if (rawStringToDataType.isEmpty()) { for (DoorsColumnType enumStatus : DoorsColumnType.values()) { DoorsColumnType.rawStringToDataType.put(enumStatus.columnType, enumStatus); } } DoorsColumnType returnVal = rawStringToDataType.get(value); return returnVal != null ? returnVal : OTHER; }

Target:
Remove synchronized and lazy loading of the map structure, add values to static map during enum element construction.
Source:
public void closeAllTestWindows() { Iterator<IWorkbenchWindow> iter = new ArrayList<IWorkbenchWindow>(testWindows).iterator(); while (iter.hasNext()) { IWorkbenchWindow win = iter.next(); win.close(); } testWindows.clear(); }

Target:
Making a new List, which contains the IWorkbenchWindows and getting its Iterator is not necessary here. I would propose to write: for(IWorkbenchWindow testWindow : testWindows){ testWindow.close(); }
Source:
protected void createDefaultEditPolicies() { super.createDefaultEditPolicies(); this.installEditPolicy(EditPolicyRoles.POPUPBAR_ROLE, new SiriusPopupBarEditPolicy()); // Replace the feedback policy to have a lighter color for guides removeEditPolicy(EditPolicyRoles.SNAP_FEEDBACK_ROLE); installEditPolicy(EditPolicyRoles.SNAP_FEEDBACK_ROLE, new SiriusSnapFeedbackPolicy()); }

Target:
I know we tend to always do remove/install in our code, but this is actually not needed: org.eclipse.gef.editparts.AbstractEditPart.installEditPolicy(Object, EditPolicy) will remove (and deactivate) any pre-existing policy in the role we want to install the new one.
Source:
public static boolean isEqualToDefault(EObject object, EStructuralFeature feature) { final Object value = ReferenceUtil.safeEGet(object, feature); final Object defaultValue = feature.getDefaultValue(); if (value == null) { return defaultValue == null; } return value.equals(feature.getDefaultValue()) || "".equals(value); //$NON-NLS-1$ }

Target:
We don't need this public. You can leave the renaming to "is*" in though, since that's a better name :).
Source:
protected ITmfTrace getTrace() { synchronized (syncObj) { return fTrace; } }

Target:
Unnecessary?
Source:
public boolean areRelated(Object object1, IRelationTypeSide relationType, Object object2) { boolean related = false; Artifact useArt1 = getArtifact(object1); Artifact useArt2 = getArtifact(object2); if (useArt1 != null & useArt2 != null) { related = useArt1.isRelated(relationType, useArt2); } return related; }

Target:
bitwise operation intended here?
Source:
public static void applyHyperlinkDetectorStyleRanges( ITextViewer textViewer, IHyperlinkDetector[] hyperlinkDetectors) { StyleRange[] styleRanges = getHyperlinkDetectorStyleRanges(textViewer, hyperlinkDetectors); StyledText styledText = textViewer.getTextWidget(); // Apply hyperlink style ranges one by one. setStyleRange takes care to // do the right thing in case they overlap with an existing style range. for (StyleRange styleRange : styleRanges) { styledText.setStyleRange(styleRange); } }

Target:
style nit: no braces
Source:
public IProject[] getTrackedProjects() { IProject[] projects = new IProject[trackedProjects.keySet().size()]; return trackedProjects.keySet().toArray(projects); }

Target:
I believe this can become 'return trackedProjects.keySet().toArray(new IProject[0])' . If the array passed in is not large enough, a new one will be created of the proper type to store the Set's content, so the size calculation isn't needed.
Source:
public void tearDown() { try { fResource.getProject().delete(true, null); } catch (CoreException e) { e.printStackTrace(); } }

Target:
here too, or just log the error
Source:
public void handleSuccess() { super.handleSuccess(); if (isCompleteTrace(trace)) { disposeProvider(false); } else { fNbRead += getNbRead(); synchronized (fRequestSyncObj) { final TmfTimeRange timeRange = fTimeRange; if (timeRange != null) { if (getRange().getEndTime().getValue() > timeRange.getEndTime().getValue()) { startRequest(); } } } } }

Target:
Shouldn't this be < instead? if the end of the time range of this request is before the time range that has been updated in the traceRangeUpdated signal handler?
Source:
public StreamGobbler(InputStream stream, OutputStream output) { this.reader = new BufferedReader(new InputStreamReader(stream)); if (output == null) this.writer = new BufferedWriter(new OutputStreamWriter( new ByteArrayOutputStream())); else this.writer = new BufferedWriter(new OutputStreamWriter(output)); }

Target:
why create a buffer to store some content which we want to throw away in the end? If output is <null> don't initialize a writer and during the call() method when writer is not initialized just read lines.
Source:
public ValidateScheduler(DiagramEditPart diagramEditPart, long delay) { this.diagramEditPart = diagramEditPart; this.scheduledJobs = new ArrayDeque<ValidateJob>(); }

Target:
this.delay = delay;
Source:
private void handleDisconnected() { removeAllChildren(); setTargetNodeState(TargetNodeState.DISCONNECTED); fService = null; }

Target:
fShell.disconnect() is never called (even in previous code). Which leads to that the hanging executor thread in the CommandShell.
Source:
public void run() { for (TimeGraphEntry entry : fZoomEntryList) { if (fMonitor.isCanceled()) { return; } if (entry == null) { break; } zoom(entry, fMonitor); } /* Refresh the arrows when zooming */ List<ILinkEvent> events = getLinkList(fZoomStartTime, fZoomEndTime, fResolution, fMonitor); fTimeGraphWrapper.getTimeGraphViewer().setLinks(events); redraw(); }

Target:
We have to put back the null check here. But perhaps you would prefer instead to make the getLinkList() return value @NonNull, and here we could check the monitor's canceled state to decide if we update the viewer or not.
Source:
public static boolean isBundleClassUri(String uri) { if (uri != null && uri.startsWith(BUNDLECLASS_SCHEMA)) { String[] split = uri.substring(14).split("/"); //$NON-NLS-1$ // valid bundleclass uri should have two segments: // first one for the bundle-symbolic-name // second one for the full qualified classname if (split.length == 2) { return true; } ; } return false; }

Target:
I would suppose to use the indexOf("/") method instead of split here as it has better performance and a constant for the prefix. int indexOf = uri.substring(BUNDLECLASS_PREFIX_LENGTH).indexOf("/"); if(indexOf > 0){ return true; } ....
Source:
public synchronized SynchronizationAlgorithm synchronizeTraces() { return synchronizeTraces(false); }

Target:
Good catch.
Source:
public EObject updateCreatedObject(EObject newObject, String loadedVersion) { EObject returnedValue = newObject; for (IMigrationParticipant contribution : delegatesParticipants) { returnedValue = contribution.updateCreatedObject(newObject, loadedVersion); } return returnedValue; }

Target:
There is a bug here --> returnedValue = contribution.updateCreatedObject(returnedValue, loadedVersion);
Source:
public EObject updateCreatedObject(EObject newObject, String loadedVersion) { EObject returnedValue = null; for (IMigrationParticipant contribution : delegatesParticipants) { returnedValue = contribution.updateCreatedObject(newObject, loadedVersion); if (returnedValue != null) { break; } } return returnedValue; }

Target:
This method prohibits that 2 participants update the EObject. I think that updateCreatedObject should always return the EObject even if there is no modification. With this you can have something like this EObject returnedValue = newObject; for (IMigrationParticipant contribution : delegatesParticipants) { returnedValue = contribution.updateCreatedObject(returnedValue, loadedVersion); }
Source:
private boolean isInteresting(ThreadInfo thread) { for (StackTraceElement element : thread.getStackTrace()) { String className = element.getClassName(); if (!className.startsWith("java.") && !className.startsWith("sun.") && //$NON-NLS-1$ //$NON-NLS-2$ !NON_INTERESTING_THREAD_FILTER.matchesFilter(element)) { return true; } } return false; }

Target:
Why don't we handle that via the Filter? I dislike having a special treatment of certain stacktraces. I think it is OK to add them to the filter (with wildcards) but hard-coding them, seems wrong.
Source:
public void testGetSWTColor() { Color result = getSWTColor(colorValue("red"), display); assertNotNull(result); assertEquals(255, result.getRed()); assertEquals(0, result.getBlue()); assertEquals(0, result.getGreen()); }

Target:
In this class all colors which are created, are not disposed at the end.
Source:
public static ImageFigureWithAlpha createImageFigure(final ContainerStyle containerStyle) { if (containerStyle instanceof FlatContainerStyle) { FlatContainerStyle style = (FlatContainerStyle) containerStyle; SVGWorkspaceImageFigure fig = new SVGWorkspaceImageFigure(); fig.refreshFigure(style); return fig; } // TODO handle other styles.. return null; }

Target:
I did not find any call for this method. Why did you change this ?
Source:
public void setAllowDeletes(final boolean canDelete) { allowAnyDeletes = canDelete; if (!canDelete) allowBranchDeletes = false; }

Target:
This loses information: after setAllowDeletes(true); setAllowBranchDeletes(true); setAllowDeletes(false); setAllowDeletes(true); what should isAllowBranchDeletes() say? I'd delete the above two lines and treat them as orthogonal (validateCommands would still prevent deleting branches when allowAnyDeletes is false).
Source:
public void resourceChanged(IResourceChangeEvent event) { IResourceDelta delta = event.getDelta(); if (delta != null) { ImageResourceDeltaVisitor visitor = getImageResourceDeltaVisitor(); try { delta.accept(visitor); } catch (CoreException e) { e.printStackTrace(); } for (String imageFileURI : visitor.changedImageFilesURI) { DiagramUIPlugin.getPlugin().removeImageFileStatusAndURIFromMaps(imageFileURI); } } }

Target:
Use Sirius logger here.
Source:
public void hashcodeTest() { VariantDeclaration a = new VariantDeclaration(); VariantDeclaration b = new VariantDeclaration(); b.addField("hi", StringDeclaration.getStringDeclaration(Encoding.UTF8)); VariantDeclaration c = new VariantDeclaration(); c.addField("hi", StringDeclaration.getStringDeclaration(Encoding.UTF8)); assertEquals(fixture.hashCode(), a.hashCode()); assertEquals(b.hashCode(), c.hashCode()); }

Target:
move this line below the "VariantDeclaration a = ..." line, and an empty line after. It'll make it clearer what are the two parts of the test.
Source:
public void trailingSlashes() { assertEquals("/foo/bar/", ServletUtils.getEncodedPathInfo("/s", "/c/s/foo/bar/", "/c")); assertEquals("/foo/bar/", ServletUtils.getEncodedPathInfo("/s", "/c/s/foo/bar///", "/c")); assertEquals("/foo%2Fbar/", ServletUtils.getEncodedPathInfo("/s", "/c/s/foo%2Fbar/", "/c")); assertEquals("/foo%2Fbar/", ServletUtils.getEncodedPathInfo("/s", "/c/s/foo%2Fbar///", "/c")); }

Target:
The argument order is... weird. Consider flipping it around to be: contextPath, servletPath, requestUri Then tests will be: "/c", "/s", "/c/s/foo/bar/" which is so much easier to read.
Source:
private String getText(final EObject element) { ComposedAdapterFactory adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE); AdapterFactoryItemDelegator adapterFactoryItemDelegator = new AdapterFactoryItemDelegator(adapterFactory); String text = adapterFactoryItemDelegator.getText(element); adapterFactory.dispose(); return text; }

Target:
The dispose() could be called from a finally block, to ensure it is always called even if an exception occurs during the getText() (which is possible given that it may call user-specified code outside of our control).
Source:
public TmfXmlReadOnlyStateValue(TmfXmlReadOnlyModelFactory modelFactory, Element node, IXmlStateSystemContainer container, String eventField) { super(modelFactory, node, container, NonNullUtils.checkNotNull(Collections.EMPTY_LIST), eventField); }

Target:
bloops
Source:
public String getName() { return NonNullUtils.checkNotNull(fModule.name()); }

Target:
bleep
Source:
private TextTraceEventContent(@NonNull String fieldName) { fName = fieldName; fValue = null; fFields = NonNullUtils.checkNotNull(Collections.EMPTY_LIST); }

Target:
Ni!
Source:
public String resolve(ITmfEvent event) { if (!(event instanceof PcapEvent)) { return EMPTY_STRING; } PcapEvent pcapEvent = (PcapEvent) event; TmfPcapProtocol protocol = pcapEvent.getMostEncapsulatedProtocol(); return NonNullUtils.checkNotNull(protocol.getShortName().toUpperCase()); }

Target:
poutine
Source:
protected @NonNull Iterable<ITmfTrace> getTracesToBuild(@NonNull ITmfTrace trace) { return NonNullUtils.checkNotNull(Arrays.asList(TmfTraceManager.getTraceSet(trace))); }

Target:
This almost looks like code I wrote!
Source:
protected boolean getCPULoadEnabled() { return m_model.getLoadMetersEnabled(); }

Target:
In the current flows, a check is made to insure the model is not null. But it might be prudent to check again here, in case it's eventually called from elsewhere.
Source:
protected void handleDispose(DisposeEvent event) { editingDomainChange(getCompareConfiguration().getEditingDomain(), null); getCompareConfiguration().getEventBus().unregister(this); differenceGroupProvider.dispose(); super.handleDispose(event); }

Target:
Are you sure that differenceGroupProvider is always not null at this place ? If not, please add guard.
Source:
public void testTypedefSyntheticMembers_415495() { final String[] expected= { "" }; assertCompletionResults(fCursorOffset, expected, REPLACEMENT); }

Target:
It's a good idea to run your tests before submitting them to Gerrit.
Source:
public ColorPickerEditor(Composite parent, int style, int defaultColor) { this(parent, style); doSetColor(defaultColor); }

Target:
this.defaultColor should be set as well. Otherwise, pressing "Default" will reset the color to Black
Source:
private View getFontStyleOwnerView() { if (this instanceof DNodeListElementEditPart) { return (View) getModel(); } else { return getPrimaryView(); } }

Target:
This should be done in DNodeListElementEditPart
Source:
public void initActionSets() { if (descriptor != null) { List<IActionSetDescriptor> temp = new ArrayList<IActionSetDescriptor>(); List<String> ids = ModeledPageLayout.getIds(layout, ModeledPageLayout.ACTION_SET_TAG); createInitialActionSets(temp, ids); for (IActionSetDescriptor descriptor : temp) { if (!alwaysOnActionSets.contains(descriptor)) { alwaysOnActionSets.add(descriptor); } } } }

Target:
maybe find a better name then "temp"?
Source:
protected void internalSetVariable(final String name, final Object content) { if (!JVMCompiledHelper.isSaveName(name)) throw new RuntimeException("\"" + name + "\" is not a valid Scala variable name"); }

Target:
setting a variable on a native engine might register that variable in a map. there is nothing more you could do to a variable. We do not need to check for save names either.
Source:
public boolean isSameType(IType type) { if (type == this) return true; if (type instanceof ITypedef || type instanceof IIndexBinding) return type.isSameType(this); if ( fDeferredInstance != null && type instanceof ICPPDeferredClassInstance) { return type.isSameType(fDeferredInstance); } return false; }

Target:
Extraneous space after (
Source:
public EObject createObject(EFactory eFactory, EClassifier type) { EFactory factory = eFactory; if (migrationNeeded) { // Handle EClass moved from one package to another, // prefix is not sufficient to retrieve the new package and factory // in // org.eclipse.emf.ecore.xmi.impl.XMLHandler.getFactoryForPrefix(String) // which does factory = // ePackage.getEFactoryInstance(); // The migration participants return the new type with EClassifier // getType(EPackage, String, String). // Then we get the factory instance from the EClassifier's EPackage. if (type != null && type.getEPackage() != null && type.getEPackage().getEFactoryInstance() != null) { factory = type.getEPackage().getEFactoryInstance(); } } EObject newObject = super.createObject(factory, type); if (migrationNeeded) { newObject = RepresentationsFileMigrationService.getInstance().updateCreatedObject(newObject, version); } return newObject; }

Target:
To me this modification should be done in its own commit which should reference Bug 449167
Source:
public static ITmfTimestampTransform createLinearFast(BigDecimal factor, BigDecimal offset) { return new TmfTimestampTransformLinearFast(new TmfTimestampTransformLinear(factor, offset)); }

Target:
If that is the case, why jerry-rig the factory, just create an object manually?
Source:
private String getLabel(final EObject eObject) { String label = "Element whithout name"; if (eObject instanceof IdentifiedElement) { label = new IdentifiedElementQuery((IdentifiedElement) eObject).getLabel(); } else if (eObject instanceof RepresentationExtensionDescription) { label = ((RepresentationExtensionDescription) eObject).getName(); } else { label = eObject.eClass().getName(); } return label; }

Target:
Could be protected to be reusable by child classes.
Source:
public TransientState(IStateHistoryBackend backend) { this.fBackend = backend; fIsActive = true; fOngoingStateInfo = new ArrayList<>(); fOngoingStateStartTimes = new ArrayList<>(); fStateValueTypes = new ArrayList<>(); fLatestTime = backend.getStartTime(); }

Target:
you can remove the "this." now that the names are different
Source:
public AbstractTmfStateProvider(ITmfTrace trace, Class<? extends ITmfEvent> eventType, String id) { this.fTrace = trace; this.fEventType = eventType; fEventsQueue = new ArrayBlockingQueue<>(DEFAULT_EVENTS_QUEUE_SIZE); fStateSystemAssigned = false; fEventHandlerThread = new Thread(new EventProcessor(), id + " Event Handler"); //$NON-NLS-1$ }

Target:
remove the "this."
Source:
private boolean isSequenceChange(Notification input) { return new NotificationQuery(input).isNotationChange() && isSequenceElement(input.getNotifier()) && needsLayout(input); }

Target:
isSequenceNotationChange would be a better name
Source:
private boolean branchExists(String branchName) throws GerritException { assertTrue("Branch requests are not supported in this version of Gerrit", reviewHarness.getClient() .isVersion29OrLater(new NullProgressMonitor())); BranchInfo[] branches = reviewHarness.getAdminClient().getRemoteProjectBranches("org.eclipse.mylyn.test", new NullProgressMonitor()); for (BranchInfo branch : branches) { String branchRef = StringUtils.trimToEmpty(StringUtils.substringAfterLast(branch.getRef(), "/")); if (branchRef.equals(branchName)) { return true; } } return false; }

Target:
We should probably check this in the client.
Source:
public void resolveProxyCrossReferences(Resource resource) { if (!initialized) { initialize(); } adapter.resolveProxyCrossReferences(resource); }

Target:
Should probably do nothing, not even trigger the initialization, if we are not already initialized (in this case there is no cleanup to do).
Source:
PushCertificateParser(Repository into, ReceiveConfig cfg) { seed = cfg.certNonceSeed; nonceSlopLimit = cfg.certNonceSlopLimit; nonceGenerator = new HMACSHA1NonceGenerator(); db = into; }

Target:
Push the seed into the generator: nonceGenerator = cfg.certNonceSeed != null ? new HMACSHA1NonceGenerator(cfg.certNonceSeed) : null;
Source:
public String getName() { String name= super.getName(); if (name != null) { name= MessageIds.IGNORED_TEST_PREFIX + name; if (reason != null && reason.length() > 0) { name= name + MessageIds.IGNORED_TEST_REASON_PREFIX + reason; } return name; } return null; }

Target:
!reason.isEmpty() can be used
Source:
public EObject getEObject(String uriFragment) { Option<String> optionalRewrittenFragment = VSMMigrationService.getInstance().getNewFragment(uriFragment); if (optionalRewrittenFragment.some()) { return getEObject(optionalRewrittenFragment.get()); } else { if (useURIFragmentAsId) { return getEObjectUsingURIFragmentAsId(uriFragment); } else { return super.getEObject(uriFragment); } } }

Target:
It looks like this introduces a nesting level of if/else blocks which is not needed. It could be: if (...) { } else if (...) { } else { } instead of if (...) { } else { if (...) { } else { } }
Source:
private static void logCorruptPackError(IOException e, PackFile p) { StringBuilder buf = new StringBuilder(MessageFormat.format( JGitText.get().exceptionWhileReadingPack, p.getPackFile().getAbsolutePath())); buf.append('\n'); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); buf.append(sw.toString()); System.err.println(buf.toString()); }

Target:
Whe should a a @TODO that we want to do logging instead of writing to stderr.
Source:
protected ContentHandler createContentHandler(DocumentBuilder builder, boolean asDocument) { if (!asDocument && builder instanceof HtmlDocumentBuilder) { ((HtmlDocumentBuilder) builder).setEmitAsDocument(false); } return new DocumentBuilderAdapter(builder); }

Target:
How do we know for sure that builder's emitAsDocument is true before this? Would be safer to say: if (builder instance of HtmlDocumentBuilder) { ((HtmlDocumentBuilder) builder).setEmitAsDocument(asDocument); } Also, this introduces a side effect for the builder parameter. Not sure how this method is used if that's a problem or not.
Source:
private Set<Resource> getSessionResources(boolean includeMainResource) { List<Resource> result = Lists.newArrayList(); for (DAnalysis analysis : allAnalyses()) { Resource res = analysis.eResource(); if (res != null && (analysis != sessionResource || includeMainResource)) { result.add(res); } } return ImmutableSet.copyOf(result); }

Target:
I would put includeMainResource || analysis != sessionResource
Source:
private String stripGitCloneCommand(String input) { if (input.startsWith(GIT_CLONE_COMMAND_PREFIX)) { return input.substring(GIT_CLONE_COMMAND_PREFIX.length()).trim(); } return input.trim(); }

Target:
you need to first trim input otherwise this doesn't match if input starts with whitespace
Source:
public MojoParameter getContainer(String[] path) { if(path == null || path.length == 0) return this; MojoParameter param = this; int i = 0; while(param != null && i < path.length) { param = param.getNestedParameter(path[i]); i++ ; } if(param == null) return null; return param; }

Target:
trivial, but we use around single statements.
Source:
public InstallableUnitDescription readOneIU(InputStream is) throws IOException { Parser parser = new Parser(org.eclipse.tycho.p2.maven.repository.xmlio.MetadataIO.Parser.PARSER_MODE.IU); parser.parse(is, new NullProgressMonitor()); return parser.getUnits().get(0); }

Target:
omit?
Source:
public Set<IInstallableUnit> readXML(InputStream is) throws IOException { Parser parser = new Parser(org.eclipse.tycho.p2.maven.repository.xmlio.MetadataIO.Parser.PARSER_MODE.REPO); parser.parse(is, new NullProgressMonitor()); Set<IInstallableUnit> units = new LinkedHashSet<IInstallableUnit>(); for (InstallableUnitDescription desc : parser.getUnits()) { units.add(MetadataFactory.createInstallableUnit(desc)); } return units; }

Target:
omit?
Source:
protected void updateComboTooltip() { // fBuildConfigCombo might not be loaded when controls are created if (fBuildConfigCombo != null && fBuildConfigCombo.getSelectionIndex() > 0) { String configId = (String) fBuildConfigCombo.getData(Integer.toString(fBuildConfigCombo.getSelectionIndex())); String tooltip = EMPTY_STRING; if (configId.equals(AUTO_CONFIG)) { tooltip = LaunchMessages.CMainTab_Build_Config_Auto_tooltip; } else if (configId.equals(EMPTY_STRING)) { tooltip = LaunchMessages.CMainTab_Build_Config_Active_tooltip; } fBuildConfigCombo.setToolTipText(tooltip); } }

Target:
Aren't selection index starts with 0? Main tooltip would be actually for 0th element... Just need regular NPE protection if (configId==null) return;
Source:
public void setFastViewBarVisible(boolean visible) { boolean oldValue = fastViewBarVisible; fastViewBarVisible = visible; if (oldValue != fastViewBarVisible) { } }

Target:
Replace method with // not supported anymore
Source:
public boolean getFastViewBarVisible() { return fastViewBarVisible; }

Target:
I suggest to make this "false" and remove the field.
Source:
public boolean getShowFastViewBars() { return getWindowConfigurer().getShowFastViewBars(); }

Target:
return false and also update WorkbenchWindowConfigurer
Source:
public static Set<String> mergeIgnored(Set<String> oldIgnoredPaths, Collection<String> changedPaths, Set<String> newIgnoredPaths) { Set<String> merged = new HashSet<String>(); for (String oldIgnoredPath : oldIgnoredPaths) { boolean changed = isAnyPrefixOf(oldIgnoredPath, changedPaths); if (!changed) { merged.add(oldIgnoredPath); } } merged.addAll(newIgnoredPaths); return merged; }

Target:
it's unnecessary to declare this method public, if it's package visible the test can still use it since it's in the same package