auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static boolean isAnyPrefixOf(String pathToCheck, Collection<String> possiblePrefixes) { for (String possiblePrefix : possiblePrefixes) { if (pathToCheck.startsWith(possiblePrefix)) { return true; } if (possiblePrefix.length() == pathToCheck.length() + 1 && possiblePrefix.charAt(possiblePrefix.length() - 1) == '/' && possiblePrefix.startsWith(pathToCheck)) { return true; } } return false; }

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
Source:
private String convertCharacterProxyData(CharacterDataProxy dp) { String toWrite = dp.getValueAsString(); if (toWrite.length() > 1024) { toWrite = "truncated: " + toWrite.substring(0, 1023); } if (toWrite.length() == 0) { toWrite += " "; } return AXml.textToXml(toWrite); }

Target:
do you mean to trim the string more? (i.e. 1024 is max)? if so, you're adding "truncated: " to 1024 chars which will be greater.
Source:
public String getProperty(String key) { return (String) value.get(key); }

Target:
This method indicates that the "value" map is expected to be <String, String> rather than <?, ?>.
Source:
private void checkDelta(IMarkerDelta[] deltas) throws AssertionFailedError { assertEquals("wrong number of changes", attributeMap.size(), deltas.length); for (int i = 0; i < deltas.length; i++) { Map values = attributeMap.get(new Long(deltas[i].getId())); assertEquals("Changes different from expecations", deltas[i].getAttributes(), values); } }

Target:
This map should be generified as well.
Source:
private static List<Variable> removeDuplicates(List<Variable> typeMatches) { HashSet<Variable> set = new HashSet<Variable>(); set.addAll(typeMatches); return Arrays.asList(set.toArray(new Variable[set.size()])); }

Target:
Done
Source:
public List<Object> prepend(List<Object> list, Object object) { // TODO use lazy collection final List<Object> result = Lists.newArrayList(); result.add(object); result.addAll(list); return result; }

Target:
Size the result list properly : final List<Object> result = new ArrayList<Object>(list.size() + 1);
Source:
private String initialConnectionName() throws CoreException { String name = DEFAULT_CONNECTION_NAME; int count = 1; while (getSelectedConnectionType().getConnection(name) != null) { name = DEFAULT_CONNECTION_NAME + " " + count++; //$NON-NLS-1$ } return name; }

Target:
I can't see any reason to throw CoreException here.
Source:
public boolean useLoginShell() { String str = fRemoteConnection.getAttribute(USE_LOGIN_SHELL_ATTR); return str != null ? Boolean.parseBoolean(str) : DEFAULT_USE_LOGIN_SHELL; }

Target:
It has taken some time to track down, but it looks like this is returning false where it used to return true. This is causing remote commands to break because they are not escaped properly. That is a separate problem (a bug in the original implementation, I think), but this attribute needs to be fixed also.
Source:
public TmfVertex(final long ts) { this.fTimestamp = ts; this.fId = count++; }

Target:
you can also remove the thises
Source:
public Long getSum(@Nullable Object worker) { Long sum = 0L; for (Long duration : fWorkerStats.get(worker)) { sum += duration; } return sum; }

Target:
doing += on a Long object causes boxing every time. It'd be better to have sum be a "long", and return Long.valueOf(sum) at the end. Or simply return a long in this method.
Source:
private IModelUpdateStrategyProvider createModelUpdateStrategyProvider() { final IModelUpdateStrategyProvider ret; IAccessorFactory accessorFactory = getAccessorFactoryForTarget(); if (accessorFactory != null && accessorFactory instanceof IModelUpdateStrategyProvider) { ret = (IModelUpdateStrategyProvider)accessorFactory; } else { // if we have no model update strategy provider, we use the following one by default, which will // always provide the tolerant SingleValuedAttributeModelUpdateStrategy ret = new IModelUpdateStrategyProvider() { public IModelUpdateStrategy getModelUpdateStrategy() { return new SingleValuedAttributeModelUpdateStrategy(); } }; } return ret; }

Target:
It's useless to check for null here since null instanceof Something always returns false.
Source:
private void closeSideParts(MPart part, boolean left) { MElementContainer<MUIElement> container = getParent(part); if (container == null) return; List<MPart> others = getCloseableSideParts(part, left); closeSiblingParts(part, others, true); }

Target:
Use brackets for single statements (I know we are very inconsitent here but this should be the goal)
Source:
protected void linkClicked(EObject value) { getViewModelContext().getService(ReferenceService.class).openInNewContext(value); }

Target:
make private
Source:
protected final Color getSystemColor(Composite parent, int color) { if (parent == null) { return Display.getDefault().getSystemColor(color); } return parent.getShell().getDisplay().getSystemColor(color); }

Target:
make private
Source:
public void image(Attributes attributes, String url) { assertOpenBlock(); try { currentBlock.write('!'); writeAttributes(attributes); if (url != null) { currentBlock.write(url); } currentBlock.write('!'); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
consider moving this null check up into the write() method, since that would guard in other places as well.
Source:
public static void checkStringDataLength(Object dataValue) { int length = ((String) dataValue).length(); if (length > JDBC__MAX_VARCHAR_LENGTH) { throw newJdbcException("SQL data value length must be <= %d not %d\nValue: %s", JDBC__MAX_VARCHAR_LENGTH, length, dataValue); } }

Target:
I think we should keep the instance of check in this method. Meaning this method should never exception of even if the object is not of the right type.
Source:
public void tearDown() { fLogger.removeAllAppenders(); fBot.closeAllEditors(); }

Target:
this is an @After, it should be in a new @AfterClass (or else you would lose logging after the first test).
Source:
public void setTimeBounds(long beginTime, long endTime) { fBeginTime = beginTime; fEndTime = endTime; fTime0Bound = fBeginTime != SWT.DEFAULT ? fBeginTime : fEndTime; fTime1Bound = fEndTime != SWT.DEFAULT ? fEndTime : fBeginTime; if (fTime0Bound > fTime1Bound) { // only possible if both are not default fBeginTime = endTime; fEndTime = beginTime; fTime0Bound = fBeginTime; fTime1Bound = fEndTime; } adjustHorizontalScrollBar(); }

Target:
I'd recommend using parentheses with elvis notations: fTime1Bound = (fEndTime != SWT.DEFAULT ? fEndTime : fBeginTime); so that we don't read the code as fTime1Bound = fEndtime But here you're actually assigning fEndtime, so maybe it's not that bad. Up to you.
Source:
private void addMatchingProposals(SortedSet<BranchContentProposal> branches, String searchText) { if (proposals.size() > 0) { for (String branchProposal : proposals) { if (branchProposal.toLowerCase().contains(searchText)) { branches.add(new BranchContentProposal(branchProposal)); } } } }

Target:
Don't need this check.
Source:
public SaveParticipantPlugin() { super(); deltaVerifier = new ResourceDeltaVerifier(); }

Target:
This change is not about removing org.eclipse.core.runtime.compatibility* bundles.
Source:
private void removeListeners() { if (restoreToSavePointListener != null) { restoreToSavePointListener.unregister(); restoreToSavePointListener.dispose(); restoreToSavePointListener = null; } if (this.saveSessionListener != null) { this.saveSessionListener.unregister(); this.saveSessionListener = null; } }

Target:
Instead of having both unregister() and dispose() methods we could have only dispose().
Source:
public void statusesChanged(Collection<ResourceStatusChange> changes) { /* this may be call in a async thread */ if (session != null) { if (SessionStatus.SYNC.equals(session.getStatus())) { marker = null; } } }

Target:
== is sufficient.
Source:
public void historyNotification(OperationHistoryEvent event) { if (session != null && SessionStatus.DIRTY.equals(session.getStatus())) { if (marker == null) { marker = event.getOperation(); } } }

Target:
equals() is not usefull for enum, == is sufficient.
Source:
protected String createHttpRequestURL() { String bugUrl = getUrlSuffix(); LoginToken token = ((BugzillaRestHttpClient) getClient()).getLoginToken(); if ((!(this instanceof BugzillaRestValidateRequest) && !(this instanceof BugzillaRestUnauthenticatedGetRequest)) && token != null && bugUrl.length() > 0) { if (!bugUrl.endsWith("?")) { //$NON-NLS-1$ bugUrl += "&"; //$NON-NLS-1$ } bugUrl += "token=" + token.getToken(); //$NON-NLS-1$ } return baseUrl() + bugUrl; }

Target:
Why exclude BugzillaRestValidateRequest and BugzillaRestUnauthenticatedGetRequest here whereas BugzillaRestAuthenticatedPostRequest overrides this method? Might as well just have all 3 override it.
Source:
public static RemoteConfig findRemoteConfig(Config config, String remoteName) throws URISyntaxException { List<RemoteConfig> allRemoteConfigs; RemoteConfig remoteConfig = null; allRemoteConfigs = RemoteConfig.getAllRemoteConfigs(config); for (RemoteConfig rc : allRemoteConfigs) { if (rc.getName().equals(remoteName)) remoteConfig = rc; } return remoteConfig; }

Target:
Can you join the variable definition please?
Source:
public static void configurePushURI(RemoteConfig remoteConfig, URIish pushURI) throws URISyntaxException { List<URIish> pushURIs = new ArrayList<URIish>( remoteConfig.getPushURIs()); for (URIish urIish : pushURIs) { remoteConfig.removePushURI(urIish); } remoteConfig.addPushURI(pushURI); }

Target:
exception is not thrown in the code, why is it needed here?
Source:
public static void configureFetchNotes(RemoteConfig remoteConfig) { String notesRef = Constants.R_NOTES + "*"; //$NON-NLS-1$ List<RefSpec> fetchRefSpecs = remoteConfig.getFetchRefSpecs(); for (RefSpec refSpec : fetchRefSpecs) { if (refSpec.matchSource(notesRef)) return; } remoteConfig.addFetchRefSpec(new RefSpec(notesRef + ":" + notesRef)); //$NON-NLS-1$ }

Target:
can you put braces around if block please.
Source:
public NotificationFilter getFilter() { return NotificationFilter.createEventTypeFilter(Notification.SET).or(NotificationFilter.createEventTypeFilter(Notification.UNSET)) .and(NotificationFilter.createNotifierTypeFilter(EObject.class).and(NotificationFilter.NOT_TOUCH)); }

Target:
I wonder if we should not put this not_touch in first position or at least before the EObject type filter
Source:
public ICommandShell createCommandShell() { LTTngToolsFileShell shell = fShell; if (shell == null) { shell = new LTTngToolsFileShell(); if ((fTestFile != null) && (fScenario != null)) { shell.loadScenarioFile(fTestFile); shell.setScenario(fScenario); } fShell = shell; } return shell; }

Target:
good multi-thread catch
Source:
public void run() { // the access to the editor needs to be executed in the display // thread Display.getDefault().syncExec(new Runnable() { @Override public void run() { if (!getEditorControl().isDisposed() && KeyPressCommitRunnable.this.toCommit != null && KeyPressCommitRunnable.this.toCommit.equals(getEditorValue())) { commit(MoveDirectionEnum.NONE, false); } } }); }

Target:
If it is possible that the editor control is disposed here, it might also be possible that it is null. So I would add getEditorControl() != null && ... And please make every && condition on a new line for better readability. Not your fault, just for better readability.
Source:
private static String getFailMessage(ProcessStatus result) { ProcessStatus firstFail = getFirstFail(result.getChildren()); if (firstFail != null) { return result.getMessage() + ": " + getFailMessage(firstFail) + getLineMessage(firstFail); } return result.getMessage(); }

Target:
Line number could be near the command, not separated from it by failure message. Example: 50: click: Control is disabled. Discuss with Ulyana ond Olya.
Source:
public void expand(IProgressMonitor monitor) { item.setExpanded(true); refreshContent(); }

Target:
Here the monitor parameter it not used, you should use it, especially in refreshContent() as it is the longer in time.
Source:
public void expand(IProgressMonitor monitor) { this.progressMonitor = monitor; item.setExpanded(true); refreshContent(); }

Target:
Not useful to have the monitor in field, you can pass it directly to refreshContent() in parameter as it will be useful mainly for the refresh
Source:
public boolean equals(Object obj) { // do not take "name" into account since it can change on the fly. if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof FileAndName)) { return false; } FileAndName other = (FileAndName) obj; if (!NonNullUtils.equalsNullable(fTraceTypeId, other.fTraceTypeId)) { return false; } return NonNullUtils.equalsNullable(fFile, other.fFile); }

Target:
keep own check
Source:
private String getStorageKey(boolean perInstance) { return (perInstance ? m_instance : "") + (m_category != "" ? "." + m_category : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ }

Target:
For strings, you have to use equals() to compare, not == or !=
Source:
public void initializeVisualizer() { fEventListener = new MulticoreVisualizerEventListener(this); m_cpuCoreContextsCache = new ArrayList<IDMContext>(); m_visualizerInstanceId = getViewer().getView().getViewSite().getSecondaryId(); // The first visualizer view will have a null secondary id - override that if (m_visualizerInstanceId == null) { m_visualizerInstanceId = "0"; //$NON-NLS-1$ } initializePersistentParameters(); }

Target:
Pass the visualizerId to the above method. Doing this will help avoid that method being moved to a place where the visualizerInstanceId is not set yet
Source:
private void persistParameter(T value) { // create memento String memento = MementoUtils.encodeStringIntoMemento(value.toString()); // save memento in store IEclipsePreferences store = MulticoreVisualizerUIPlugin.getEclipsePreferenceStore(); if (memento != null) { store.put(m_storeKey, memento); try { store.flush(); } catch (BackingStoreException e) { e.printStackTrace(); } } }

Target:
Move above line to inside below if
Source:
protected void gtk_widget_set_align(long /*int*/ widget, int hAlign, int vAlign) { OS.gtk_widget_set_halign (widget, hAlign); OS.gtk_widget_set_valign (widget, vAlign); }

Target:
Remove protected to prevent access from outside the package and place the method near the other gtk_widget methods in this class.
Source:
protected void setUp() throws Exception { super.setUp(); removeLeftOverProjects(); cproject = createProject(isCpp()); tmpDir = cproject.getProject().getLocation().makeAbsolute().toFile(); final IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IViewPart view= activePage.findView("org.eclipse.cdt.ui.tests.DOMAST.DOMAST"); if (view != null) { activePage.hideView(view); } }

Target:
Why project stuff in baseUiTestCase now? It should be its own base class at least
Source:
public void dispose() { treeViewerManager.dispose(); treeViewerManager = null; super.dispose(); if (getAdapterFactory() instanceof IDisposable) { ((IDisposable) getAdapterFactory()).dispose(); } if (refreshAtOpeningActivator != null) { getSite().getPage().removePartListener(refreshAtOpeningActivator); refreshAtOpeningActivator = null; } }

Target:
If you set the fields to null it is generally a good idea to make sure dispose() will not fail if called twice. In this case you'll get an NPE here.
Source:
public void dispose() { treeViewerManager.dispose(); treeViewerManager = null; if (refreshAtOpeningActivator != null) { getSite().getPage().removePartListener(refreshAtOpeningActivator); } refreshAtOpeningActivator = null; super.dispose(); if (getAdapterFactory() instanceof IDisposable) { ((IDisposable) getAdapterFactory()).dispose(); } }

Target:
Where is treeViewerManager disposed ? in DTreeEditor or in the parent AbstractDTreeEditor ? Looks like you are doing both
Source:
public void setInternalJobState(int state) { try { final Field field = InternalJob.class.getDeclaredField("flags"); field.setAccessible(true); // hack for testing field.set(this, new Integer(state)); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }

Target:
Debugging leftover?
Source:
public static EObject getEObjectValue(View view, String property, EObject defaultValue) { EObject value = defaultValue; EClass eObjectValueStyle = NotationPackage.eINSTANCE.getEObjectValueStyle(); NamedStyle style; if (eObjectValueStyle != null) { style = view.getNamedStyle(eObjectValueStyle, property); if (style instanceof EObjectValueStyle) { value = ((EObjectValueStyle) style).getEObjectValue(); } } return value; }

Target:
The variable is declared in the bad scope.
Source:
public ImageData getImageData (int zoom) { copyImageDataFromDpiImageStorage(DPIUtil.mapZoomToImageSelectorIndex(zoom)); ImageData returnVal = getImageData (); copyImageDataFromDpiImageStorage(device.getImageSelector()); return returnVal; }

Target:
why call copy 2nd time?
Source:
private Image getEnhancedImage(final Image image, final Viewpoint viewpoint) { if (ViewpointRegistry.getInstance().isFromPlugin(viewpoint) && image != null) { return SiriusEditPlugin.getPlugin().getImage(getOverlayedDescriptor(image, "icons/full/decorator/folder_close.gif")); } return image; }

Target:
We do not want to decorate Viewpoint from plugins but from workspace.
Source:
public void add(Expression expression) { if (fExpressions == null) fExpressions= new ArrayList<Expression>(2); fExpressions.add(expression); }

Target:
A diamond operator would suffice.
Source:
private static String toHex(byte[] bytes) { StringBuilder builder = new StringBuilder(); for (byte b : bytes) { builder.append(HEX.charAt((b & 0xF0) >> 4)); builder.append(HEX.charAt(b & 0xF)); } return builder.toString(); }

Target:
Optional: Presize to 2 * bytes.length
Source:
public static TreeWalk forPath(final Repository db, final String path, final AnyObjectId... trees) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { ObjectReader reader = db.newObjectReader(); try { return forPath(reader, path, trees); } finally { reader.close(); } }

Target:
Rewrite as try-with-resources: try (ObjectReader reader = db.newObjectReader()) { return forPath(reader, path, trees); } ?
Source:
public static boolean isFloatingLabel(EObject notationElement) { if (!(notationElement instanceof DecorationNode)) { return false; } DecorationNode node = (DecorationNode) notationElement; if (node instanceof BasicCompartment) { return false; } if (node.eContainer() instanceof Connector) { return true; } if (node.eContainer() instanceof Shape) { if (node.getLayoutConstraint() != null) { return true; } } return false; }

Target:
This method must not be static.
Source:
public Element getElement(Object node) { if (node == null) { return null; } EObject notationElement = getNativeWidget(node); CSSDOMSemanticElementHelper helper = new CSSDOMSemanticElementHelper(); View canonicalNotationElement = helper.findPrimaryView(notationElement); // Orphaned view if (canonicalNotationElement.getDiagram() == null) { return null; } // A View and a Compartment associated to the same Semantic Element // must have the same XML Element. They share the same children. // This is required to map the Semantic model (Used by the CSS selectors) // to the Notation model (Used by the CSS properties) return super.getElement(canonicalNotationElement); }

Target:
I think that CSSDOMSemanticElemntHelper should be an Singleton.
Source:
public void notifyChanged(Notification notification) { final int eventType = notification.getEventType(); if (eventType == StereotypeExtensionNotification.STEREOTYPE_APPLIED_TO_ELEMENT) { initialisation(); refreshNotationStructure(); } else if (eventType == StereotypeExtensionNotification.STEREOTYPE_UNAPPLIED_FROM_ELEMENT) { initialisation(); refreshNotationStructure(); } }

Target:
Why this field is final ? It is only used in method scope.
Source:
public GMFUMLElementAdapter(View view, ExtendedCSSEngine engine) { super(view, engine); super.helper = new CSSDOMUMLSemanticElementHelper(); }

Target:
There maybe an other way to initialise the helper field. It will be better with a setter.
Source:
public String getStoreKey() { return m_storeKey; }

Target:
Should this be protected, or do we really want to allow to call it outside this class?
Source:
public T value() { if (m_value == null) { // attempt to get the value from the preference store m_value = restoreParameter(); } // parameter has one value for any/all instances else if(!isPerInstance()) { // do not rely on cached value, since another instance might have // changed it - reread from data store m_value = restoreParameter(); } return (m_value!=null)? m_value : m_defaultValue; }

Target:
Could you check for null instead of !null so it uses the same logic as the new class PersistentListParameter?
Source:
private List<T> convertToT(List<String> vals) { List<T> convertedList = new ArrayList<T>(); for(String val : vals) { convertedList.add(super.convertToT(val)); } return convertedList; }

Target:
No need for super
Source:
public void registerAnalysis(final DAnalysis analysis) { if (!analysis.eAdapters().contains(this)) { analysis.eAdapters().add(this); } for (final DView view : analysis.getOwnedViews()) { registerView(view); } }

Target:
This reveals probably a more impacting problem. Why registerAnalysis is called twice? With this change you probably hide the consequence of the problem but not the cause.
Source:
public Heap(final int estimatedSize, final int limit) { super(limit, estimatedSize); }

Target:
wrong arg order
Source:
public PathVariablesGroup(boolean multiSelect, int variableType) { this.multiSelect = multiSelect; this.variableType = variableType; pathVariableManager = ResourcesPlugin.getWorkspace() .getPathVariableManager(); removedVariableNames = new HashSet(); Collator ignoreCaseComparator = Collator.getInstance(); ignoreCaseComparator.setStrength(Collator.TERTIARY); tempPathVariables = new TreeMap(ignoreCaseComparator); // initialize internal model initTemporaryState(); }

Target:
Is there a reason to set the strength? None of the Platform/UI nor JDT code does so.
Source:
protected void paintFigure(final Graphics g) { g.setBackgroundColor(getBackgroundColor()); g.setForegroundColor(getForegroundColor()); g.setLineWidth(getLineWidth()); g.setLineStyle(getLineStyle()); final PointList points = calculatePoints(new Rectangle(getBounds())); g.fillPolygon(points); g.drawPolygon(points); }

Target:
Line dash / line attributes ?
Source:
public ChooseWorkspaceDialog(Shell parentShell, ChooseWorkspaceData launchData, boolean suppressAskAgain, boolean centerOnMonitor) { super(parentShell); this.launchData = launchData; this.suppressAskAgain = suppressAskAgain; this.centerOnMonitor = centerOnMonitor; // Bug 462707 - [WorkbenchLauncher] dialog not closed on ESC this.parentShell = parentShell; this.keyListener = new Listener() { @Override public void handleEvent(Event event) { if (event.character == SWT.ESC) cancelPressed(); } }; parentShell.getDisplay().addFilter(SWT.KeyDown, keyListener); }

Target:
style nit: can you add braces around if block?
Source:
public void emptyLine() { String html = parseToHtml(" "); assertEquals(html, ""); }

Target:
should reverse order as follows: assertEquals("",html)
Source:
public void strong() { String html = parseToHtml("*foo bar*"); assertEquals(html,"<p><strong>foo bar</strong></p>\n"); }

Target:
Should also have tests for strong with preceding character content, and following character content. (those are areas where we've had troubles before)
Source:
public void disconnect() { if (fExplicitConnect) { fHost.close(); } }

Target:
We should also set the variable to false, so we only close the connection once.
Source:
private static String extractScriptStackTrace(RhinoException e) { String st = e.getScriptStackTrace(); if (st.equals("")) return null; return st; }

Target:
return (e.getScriptStackTrace().isEmpty() ? null : e.getScriptStackTrace();
Source:
private static void checkIfSessionIsAssociatedWithProject(SessionId sessionId, ProjectId projectId) throws AccessControlException { final EList<Adapter> eAdapters = sessionId.eAdapters(); for (final Adapter adapter : eAdapters) { if (ShareProjectAdapter.class.isInstance(adapter)) { final ShareProjectAdapter shareAdapter = (ShareProjectAdapter) adapter; final boolean didRemove = shareAdapter.removeProject(projectId); if (!didRemove) { throw new AccessControlException(Messages.AdminEmfStoreImpl_IllegalRequestToAddInitialRole); } return; } } throw new AccessControlException(Messages.AdminEmfStoreImpl_IllegalRequestToAddInitialRole); }

Target:
Logic is weird here, I would change it to: if (didRemove) { return }
Source:
public boolean isQualifiedNameDisplay(View labelView) { boolean QNDisplayed; String depth = NotationUtils.getStringValue(labelView, StereotypeDisplayUtils.STEREOTYPE_LABEL_DEPTH, StereotypeDisplayUtils.DEFAULT_DEPTH_VALUE); QNDisplayed = StereotypeDisplayUtils.DEPTH_MAX.equals(depth); return QNDisplayed; }

Target:
Return directly the evaluation value.
Source:
void initialize() { fgKeys= new HashMap<String, Integer>(); Integer k= new Integer(KEY); for (String word : fgKeywords) fgKeys.put(word, k); }

Target:
No need for type here.
Source:
String getQualifier(Date timestamp) throws MojoFailureException { String qualifier = format.format(timestamp); // parse an empty version with the given qualifier to check if the qualifier is valid try { Version.parseVersion(Version.emptyVersion + "." + qualifier); } catch (IllegalArgumentException e) { throw new MojoFailureException("Invalid build qualifier format '" + format.toPattern() + "', it does not match the OSGi qualifier constraint ([0..9]|[a..zA..Z]|'_'|'-')"); } return qualifier; }

Target:
in calculateQualifiedVersion(), there are other ways to set the qualifier which are not being validated. rather pull this out into a dedicated validateQualifer method and call it after qualifier was determined.
Source:
public String getOSRecommendedFolder() { try { return _get_os_recommended_folder(); } catch (UnsatisfiedLinkError e) { if (!libraryLoaded) { loadLibrary(); return _get_os_recommended_folder(); } return null; } }

Target:
I know the effect is the same but just to be consistent with the rest of the code in this class, may be this statement can be changed to 'return getOSRecommendedFolder()' - wdyt? I'm fine if you don't want to change but decided to ask anyway...
Source:
private static void checkTerminateFailures() { synchronized (fTestFailedToTerminate) { while (fTerminateThreadsRunning > 0) { try { fTestFailedToTerminate.wait(500); } catch (InterruptedException e) { } } if (fTestFailedToTerminate.isEmpty() == false) { StringBuffer buffer = new StringBuffer(); for (String failedName : fTestFailedToTerminate) { buffer.append("\nTermination failed for test " + failedName); } fTestFailedToTerminate.clear(); Assert.assertTrue(buffer.toString(), false); } } }

Target:
Can this cause an infinite loop?
Source:
public Repository open(HttpServletRequest req, String name) throws RepositoryNotFoundException, ServiceNotEnabledException { if (!name.equals(repoName)) throw new RepositoryNotFoundException(name); Repository db = repo.getRepository(); db.incrementOpen(); return db; }

Target:
Done. (Copy-paste)
Source:
public IRemoteProcess getCommandShell(int flags) throws IOException { return new JSchProcessBuilder(getRemoteConnection(), "shell").start(flags); }

Target:
This should either use the one argument constructor, or the one argument constructor should be removed as it is not being used. If this is kept, then it is missing //$NON-NLS-$
Source:
public <T extends IRemoteConnection.Service> T getService(IRemoteConnection connection, Class<T> service) { if (IRemoteCommandShellService.class.equals(service)) { return (T) new JSchCommandShellService(connection); } else { return null; } }

Target:
else is redundant.
Source:
protected void doWakeUp() { IJobManager jobManager = Job.getJobManager(); jobManager.wakeUp(TestJob.FAMILY_TEST_JOB); }

Target:
Why not just replace Platform with Job? Same below.
Source:
public long getBucketStartTime(int index) { // .5 for rounding return fFirstBucketTime + (long) (index * fBucketDuration + .5); }

Target:
Remove rounding... 3rd strike ;)
Source:
protected boolean batchValidate(EObject eObject, DiagnosticChain diagnostics, Map<Object, Object> context) { IStatus status = Status.OK_STATUS; // no point in validating if we can't report results if (diagnostics != null) { // if EMF Mode Validation Service already covered the sub-tree, // which it does for efficient computation and error reporting, // then don't repeat (the Diagnostician does the recursion // externally). If there is no context map, then we can't // help it if (!hasProcessed(eObject, context)) { if (canCompareUpperGeLower(eObject)) { status = batchValidator.validate( eObject, new NullProgressMonitor()); processed(eObject, context, status); appendDiagnostics(status, diagnostics); } } } return status.isOK(); }

Target:
Only the Lower/Upper constraint should be disabled. In this case, unrelated constraints on the same element will be ignored too
Source:
public int draw(GC gc, long nanosec, Rectangle rect) { String stime; synchronized (formats) { stime = YEAR_FORMAT.format(new Date(nanosec / MILLISEC_IN_NS)); } return Utils.drawText(gc, stime, rect, true); }

Target:
You only need synchronized (YEAR_FORMAT) { here. And it will block with the .setTimeZone() calls above.
Source:
public int getAvailableWidth(int requestedOffset) { int totalWidth = fTimeAlignedComposite.getSize().x; int availableWidth = totalWidth - requestedOffset; return availableWidth; }

Target:
inline this maybe?
Source:
public ISchedulingRule getSchedulingRule() { return RuleUtil.getRuleForContainers(Collections.<IPath> emptySet()); }

Target:
can't you just return null ?
Source:
public static void handleIssue(int severity, String message, Throwable throwable, boolean show) { IStatus status = new Status(severity, getPluginId(), message, throwable); int style = StatusManager.LOG; if (show) style |= StatusManager.SHOW; StatusManager.getManager().handle(status, style); }

Target:
missing braces
Source:
public boolean isSupported() { return version.compareTo(MINIMUM_SUPPORTED_VERSION) >= 0 && version.compareTo(MAXIMUM_SUPPORTED_VERSION) < 0; }

Target:
Shouldnt this be <= ? Is it possible you haven't pulled latest changes? I think this was changed to < 2_12_0 but <= 2_11_0 would be equivalent (and maintain the appropriate value of MAXIMUM_SUPPORTED_VERSION)
Source:
boolean shouldReactToChildVisibilityChanges(MUIElement theElement) { return (theElement instanceof MPartSashContainer || theElement instanceof MPartStack); }

Target:
The method should probably be made static.
Source:
public void activate() { if (!isActive()) { final IPermissionAuthority auth = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(getEditingDomain().getResourceSet()); auth.addAuthorityListener(this.getEditPartAuthorityListener()); super.activate(); DiagramElementEditPartOperation.activate(this); } EditPartAuthorityListener editModeUpdater = getEditPartAuthorityListener(); if (editModeUpdater.shouldRefresh()) { editModeUpdater.refreshEditMode(); } }

Target:
why do you not do this in DiagramElementEditPartOperation.activate(this); ?
Source:
public CompositeMenuBuilder(final String label, final Collection<AbstractMenuBuilder> menus) { this.label = label; this.menus = menus; AbstractMenuBuilder firstMenu = (AbstractMenuBuilder) menus.toArray()[0]; priority = firstMenu.getPriority(); }

Target:
A little dangerous to access an array index without checking its validity.
Source:
public static void updateDefaultFormats() { fDefaultTimeFormat = new TmfTimestampFormat( TmfTimePreferences.getTimePattern(), TmfTimePreferences.getTimeZone(), TmfTimePreferences.getLocale()); fDefaultIntervalFormat = new TmfTimestampFormat(TmfTimePreferences.getIntervalPattern()); }

Target:
synchronized here
Source:
public void setHeight(int height) { int oldHeight = this.fHeight; this.fHeight = height; if (oldHeight != height) { getParent().layout(new Control[] { this }); } }

Target:
Could avoid this local variable if you store fHeight inside the if clause, if you feel like it (also, this. unnecessary).
Source:
public int compareTo(FileAndName o) { int retVal = getFile().compareTo(o.getFile()); if (retVal == 0) { if (getTraceTypeId() != null) { if (o.getTraceTypeId() != null) { retVal = getTraceTypeId().compareTo(o.getTraceTypeId()); } } } return retVal; }

Target:
While at it, you could merge the if's together: if (retVal == 0 && getTraceTypeId() != null && o.getTraceTypeId() != null) { retVal = .... } Technically, if getTraceTypeId() returns a mutable value, it'd be safer to extract it to a local variable first, because the value could change between the if check and using it in the compareTo() below since there is more than one condition in the if. But I don't think the trace type ID is supposed to change once we're here so that's probably fine.
Source:
private void lruRemove(final Slot e) { Slot p = e.lruPrev; Slot n = e.lruNext; if (p != null) p.lruNext = n; else lruHead = n; if (n != null) n.lruPrev = p; else lruTail = p; }

Target:
So braces here, I guess.
Source:
public static void parallel(String task, Iterable<Job> jobs) { IProgressMonitor group = getProgressGroup(); try { group.beginTask(task, size(jobs)); for (Job job : jobs) { job.setProgressGroup(group, 1); job.schedule(); } for (Job job : jobs) { job.join(); } } catch (InterruptedException e) { // ignore } finally { group.done(); } }

Target:
wouldn't join block the caller?
Source:
public void dispose() { super.dispose(); if (this.tabFolder != null) { this.tabFolder.dispose(); this.tabFolder = null; } tabItems.clear(); for (ModelExplorerTabDescriptor tabDescriptor : ModelExplorerTabRegistry.getRegisteredExtensions()) { IModelExplorerTabExtension tab = tabDescriptor.getTabExtension(); if (tab != null) { tab.dispose(); } } lockDecorationUpdater.unregister(); }

Target:
Should be set to null, especially as LockDecorationUpdater has not all its fields set to null on unregister() call.
Source:
public void testDeactivateDoesNotRestoreForNoOpenTasks() { taskActivityManager.activateTask(task1); taskActivityManager.deactivateTask(task1); assertNoTaskOrTextEditorsOpen(); taskActivityManager.activateTask(task1); assertEquals(Collections.emptyList(), getOpenEditorsByType(TaskEditor.class)); }

Target:
Should we just call assertNoTaskOrTextEditorsOpen again?
Source:
public static IConsole[] findConsole(IRemoteConnection connection) { return new TerminalConsoleFactory().findConsole(connection); }

Target:
Done
Source:
private TreeItem thisOrFirstItem(TreeItem item) { return item != null ? item : getFirstItemInTree(); }

Target:
I know that checkstyle is disabled for this project (not sure why actually), but the EMF Compare checkstyle config discourages ternary expressions, so I'd replace this with a common if statement here.
Source:
public WordUpdateChange updateWordArtifacts(WordUpdateData data) { WordUpdateArtifact updateArt = new WordUpdateArtifact(logger, orcsApi); WordUpdateChange change = null; try { validate(data); change = updateArt.updateArtifacts(data, atsServer); } catch (Exception ex) { throw new OseeWebApplicationException(Status.INTERNAL_SERVER_ERROR, "Exception in updateWordArtifacts", ex); } return change; }

Target:
don't catch, but instead allow the ExceptionMapper to handle it
Source:
private AbstractTreeIterator getTreeIterator(String name) throws IOException { final ObjectId id = db.resolve(name); if (id == null) throw new IllegalArgumentException(name); final CanonicalTreeParser p = new CanonicalTreeParser(); try (final ObjectReader or = db.newObjectReader()) { p.reset(or, new RevWalk(db).parseTree(id)); return p; } }

Target:
(optional) likewise
Source:
public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (selection == null || part instanceof GenericHistoryView) { return; } IStructuredSelection structuredSelection = SelectionUtils .getStructuredSelection(selection); System.out.println("selectionChanged[" + part + "]: " //$NON-NLS-1$ //$NON-NLS-2$ + structuredSelection.size()); if (structuredSelection.isEmpty()) { return; } setSelection(structuredSelection); }

Target:
Argh, thanks for noticing! ;-)
Source:
protected FS() { gitSystemConfig = new Holder<File>(discoverGitSystemConfig()); }

Target:
It would be better to evaluate gitSystemConfig lazily in getGitSystemConfig(), so a call to discoverGitSystemConfig() can be avoided completely if gitSystemConfig has been set 'manually' before. discoverGitSystemConfig() is possibly slow and may even hang if the bash configuration is screwed up.
Source:
protected View getView() { if (getHost().getModel() instanceof View) { if (((View) getHost().getModel()) instanceof View) { return (View) ((View) getHost().getModel()); } return null; } return null; }

Target:
Multi return is forbidden.
Source:
public ITopic[] getSubtopics() { return subTopics.toArray(new ITopic[subTopics.size()]); }

Target:
You could just do 'return subTopics.toArray(new ITopic[0]);'
Source:
public long getCountOfLoadedCommits() { return countOfLoadedCommits; }

Target:
s/public// This type is not visible, so the methods aren't visible even if you declared them public. In such cases we avoid public to make it less confusing.
Source:
public InputStream getInputStream(GzipEntry entry) { if (entry.equals(fEntry)) { return fInternalEntryStream; } throw new IllegalArgumentException(); }

Target:
I think the == is right here. You don't want two "equivalent" entries from a different Gzipfile to return the inputstream from this file.
Source:
public Builder hostname(final String hostname) { if (hostname != null && !hostname.isEmpty()) { this.hostname = hostname; } return this; }

Target:
This means both .hostname("").hostname("wonka") .hostname("wonka").hostname("") result in hostname being "wonka" ? That seems inconsistent. Why is this needed ?
Source:
public Builder cmd(final List<String> cmd) { if (cmd != null && !cmd.isEmpty()) { this.cmd = new ArrayList<String>(cmd); } return this; }

Target:
same, why not set what is coming in here ?
Source:
public Builder entryPoint(final String entrypoint) { if (entrypoint != null && !entrypoint.isEmpty()) { return entryPoint(entrypoint.split(" ")); } return this; }

Target:
so how do make the entryPoint be empty ?
Source:
public void setSelectedTime(long time, boolean ensureVisible) { /* if there is a pending time selection, ignore this one */ synchronized (fListenerNotifierLock) { if (fListenerNotifier != null && fListenerNotifier.hasTimeSelected()) { return; } } setSelectedTimeInt(time, ensureVisible, false); }

Target:
idem
Source:
public void setSelectionRange(long beginTime, long endTime) { /* if there is a pending time selection, ignore this one */ synchronized (fListenerNotifierLock) { if (fListenerNotifier != null && fListenerNotifier.hasTimeSelected()) { return; } } fSelectionBegin = Math.max(fTime0Bound, Math.min(fTime1Bound, beginTime)); fSelectionEnd = Math.max(fTime0Bound, Math.min(fTime1Bound, endTime)); fTimeGraphCtrl.redraw(); fTimeScaleCtrl.redraw(); }

Target:
idem
Source:
protected boolean hasShortcuts() { return true; }

Target:
sollte false nicht default sein?
Source:
public Option<String> getNewFragment(String uriFragment) { boolean contains = false; String newUriFragment = uriFragment; // do not directly do a replaceAll on "@firstModelOperations" to avoid // an infinite loop if (uriFragment.endsWith("@firstModelOperations")) { contains = true; newUriFragment = newUriFragment + ".0"; } if (uriFragment.contains("@firstModelOperations/")) { contains = true; newUriFragment = newUriFragment.replaceAll("@firstModelOperations/", "@firstModelOperations.0/"); } if (contains) { return Options.newSome(newUriFragment); } else { return super.getNewFragment(uriFragment); } }

Target:
Could be an "else if" to make it more obvious these are exclusive cases.
Source:
public boolean launchConfigurationChanged(ILaunchConfiguration configuration) throws CoreException { if (ownsLaunchConfiguration(configuration)) { // we have to ignore notifications from working copies, otherwise // we will be adding them here and not removing destroying the proper cache // change event will be sent to original configuration later if (configuration.isWorkingCopy()) return true; // clear cache, target could have changed launchConfigurationRemoved(configuration); return addLaunchConfiguration(configuration); } else if (ownedConfigs.contains(configuration)) { // something changed that will cause us to loose ownership of this // configuration. Remove and add it back in. ILaunchBarManager manager = getManager(); manager.launchConfigurationRemoved(configuration); manager.launchConfigurationAdded(configuration); return true; } else { return false; } }

Target:
Shouldn't this check be at the top of this method. Should we ignore working copies all the time?
Source:
public boolean accept(final Object element) { if (element instanceof ILabelProviderContextElementWrapper) { final Object object = ((ILabelProviderContextElementWrapper) element).getObject(); if (object instanceof ITreeItemAxis) { ITreeItemAxis curr = (ITreeItemAxis) object; Object el = curr.getElement(); if (el instanceof TreeFillingConfiguration) { final IAxis axis = ((TreeFillingConfiguration) el).getAxisUsedAsAxisProvider(); return axis instanceof EOperation || axis instanceof EOperationAxis; } } } return false; }

Target:
Multi returns are to avoid.
Source:
private String getLabelProviderContextForTreeFillingConfiguration(final Table table, final Object listenObject) { if (listenObject instanceof EStructuralFeature) { return Constants.HEADER_LABEL_PROVIDER_TREE_FILLING_FEATURE_CONFIGURATION_CONTEXT; } else if (listenObject instanceof EOperation) { return Constants.HEADER_LABEL_PROVIDER_TREE_FILLING_OPERATION_CONFIGURATION_CONTEXT; } else { // TODO return ""; //$NON-NLS-1$ } }

Target:
Multi return is to avoid?
Source:
private RGB getRGBFromTheme(String value) { if (Platform.getBundle("org.eclipse.e4.ui.css.swt.theme") != null) { String backgroundColor = E4ThemeColor.getCssValueFromTheme(display, value); if (backgroundColor != null) { RGB themeColor = E4ThemeColor.getRGBFromCssString(backgroundColor); if (themeColor != null) { return themeColor; } } } return getImpliedBackground().getRGB(); }

Target:
It's odd for getRGBFromTheme to call getImpliedBackground. Instead we should have a method getBackground that calls getRGBFromTheme and getImpliedBackground.
Source:
public synchronized void setLocation(ITmfLocation location) { if (location != null) { CtfIterator iterator = getIterator(); iterator.seek(((CtfLocation) location).getLocationInfo()); fCurLocation = iterator.getLocation(); } else { fCurLocation = null; } }

Target:
could we instanceof here?? just a thought?
Source:
protected View getView() { EditPart host = getHost(); if (host == null) { return null; } Object hostView = host.getModel(); if (hostView instanceof View) { // The mask have to be applied on the label and not on the parent if (((View) getHost().getModel()) instanceof View) { return (View) ((View) getHost().getModel()); } return null; } return null; }

Target:
Casting to View before checking instanceof is highly suspicious
Source:
public void testAtsProgramInsertionBadProgramIdRestCall() throws Exception { String result = doRequestString("/ats/program/" + getSawTeam().getArtId() + "/insertion", HttpMethod.GET, null, javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Assert.assertTrue(result.contains("SERVER_ERROR")); }

Target:
use .getUuid instead of getArtId, which will go away
Source:
public boolean hasVisibleCompartment(View comment) { boolean empty = true; if (isStereotypeComment(comment)) { Iterator<?> childrenIterator = comment.getChildren().iterator(); while (childrenIterator.hasNext() && empty) { Object child = childrenIterator.next(); if (isStereotypeCompartment(child)) { empty = !((View) child).isVisible(); } } } return !empty; }

Target:
'final' is missing
Source:
public void removeListener() { if (!stereotypeList.isEmpty()) { if (comment != null) { for (Stereotype stereotype : stereotypeList) { getDiagramEventBroker().removeNotificationListener(helper.getStereotypeCompartment(comment, stereotype), this); getDiagramEventBroker().removeNotificationListener(helper.getStereotypeBraceCompartment(comment, stereotype), this); } } } }

Target:
'null !=' is preferably used
Source:
protected void executeAppliedStereotypeCommentDeletion(final TransactionalEditingDomain domain, final View commentNode) { if (commentNode != null) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { // because it is asynchronous the comment node's domain maybe become null if (TransactionUtil.getEditingDomain(commentNode) == domain) { DeleteCommand command = new DeleteCommand(commentNode); try { GMFUnsafe.write(domain, command); } catch (Exception e) { Activator.log.error(e); } } } }); } }

Target:
null or constant must be first for operations.
Source:
protected boolean isStereotypedElement(final View view) { boolean result = false; if (view.getElement() instanceof Element && !((Element) view.getElement()).getAppliedStereotypes().isEmpty()) { result = true; } return result; }

Target:
Why do you not return directly the value of condition ?
Source:
public void setAccelerator (int accelerator) { checkWidget(); if (this.accelerator == accelerator) return; long /*int*/ accelGroup = getAccelGroup (); if (accelGroup != 0) removeAccelerator (accelGroup); this.accelerator = accelerator; if (accelGroup != 0) { addAccelerator (accelGroup); } }

Target:
I like this re-factoring. But you haven't made any changes in this function other than this refactoring. I would recommend to submit as a separate re-factoring patch. This patch is already very long. Also, if you're doing it here, you should ideally do this if-separation across the whole widget in a 2nd refactoring patch (or across all of menu-item ideally). Also, you touch this line, but don't change the near identical line if statement above it (L 900) which makes this function look a bit inconsistent.
Source:
public static <E> ListDiff<E> createListDiff( final List<ListDiffEntry<E>> differences) { final ListDiffEntry<?>[] differencesArray = differences .toArray(new ListDiffEntry[differences.size()]); return new ListDiff<E>() { @Override public ListDiffEntry<?>[] getDifferences() { return differencesArray; } }; }

Target:
Better to break after the equal sign.
Source:
private T getLiveValue() { for (Option option : options) { if (Boolean.TRUE.equals(option.observable.getValue())) return option.value; } return null; }

Target:
This code can be simplified to rely on autounboxing.
Source:
protected void doSetValue(Object value) { int index = indexOfValue(value); try { updating = true; for (int i = 0; i < options.size(); i++) { options.get(i).observable.setValue(i == index ? Boolean.TRUE : Boolean.FALSE); } } finally { updating = false; } notifyIfChanged(index); }

Target:
This code can be simplified to rely on autoboxing.
Source:
public boolean addAll(Collection<? extends E> c) { boolean changed = false; for (Iterator<? extends E> iterator = c.iterator(); iterator.hasNext();) { E element = iterator.next(); changed |= wrappedSet.add(IdentityWrapper.wrap(element)); } return changed; }

Target:
Better: E element : c
Source:
protected Boolean doGetValue() { return tracked.isStale() ? Boolean.TRUE : Boolean.FALSE; }

Target:
The code can be simplified to rely on autoboxing.
Source:
boolean containsValue(Object value) { for (Iterator<DelegateCache> it = delegateCaches.values().iterator(); it .hasNext();) { DelegateCache cache = it.next(); if (cache.containsValue(value)) return true; } return false; }

Target:
Better: DelegateCache cache : delegateCache.values()
Source:
public void removeTable(Table tableInstance) { getResource().getContents().remove(tableInstance); }

Target:
Same here; will probably not work with controlled models
Source:
public void addCommand(ReceiveCommand cmd, String rawLine) { received = true; commands.add(cmd); rawCommands.append(rawLine); }

Target:
not for addCommand, see below
Source:
public void addCommand(String rawLine) { received = true; commands.add(parseCommand(chomp(rawLine))); rawCommands.append(rawLine); }

Target:
No, not for addCommand. The caller runs this if push cert is enabled, but the client didn't send a push cert.
Source:
public int hashCode() { int hashCode = 0; if (this.isSystemLibrary()) { hashCode++; } for (int i = 0; i < this.entries.length; i++) { hashCode = hashCode * 17 + this.entries.hashCode(); } return hashCode; }

Target:
there is a bug here, reported to JDT (470535)