auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean branchExists(String branchName) throws GerritException { START assertTrue("Branch requests are not supported in this version of Gerrit", reviewHarness.getClient() END .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; } We should probably check this in the client.

Target:
private boolean branchExists(String branchName) throws GerritException { 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; }
Source:
START public void resolveProxyCrossReferences(Resource resource) { if (!initialized) { initialize(); } adapter.resolveProxyCrossReferences(resource); } END Should probably do nothing, not even trigger the initialization, if we are not already initialized (in this case there is no cleanup to do).

Target:
public void resolveProxyCrossReferences(Resource resource) { if (initialized) { // The resolution of proxy is called only is the cross-referencer // has already been initialized. adapter.resolveProxyCrossReferences(resource); } }
Source:
PushCertificateParser(Repository into, ReceiveConfig cfg) { seed = cfg.certNonceSeed; nonceSlopLimit = cfg.certNonceSlopLimit; START nonceGenerator = new HMACSHA1NonceGenerator(); END db = into; } Push the seed into the generator: nonceGenerator = cfg.certNonceSeed != null ? new HMACSHA1NonceGenerator(cfg.certNonceSeed) : null;

Target:
PushCertificateParser(Repository into, ReceiveConfig cfg) { nonceSlopLimit = cfg.certNonceSlopLimit; nonceGenerator = cfg.certNonceSeed != null ? new HMACSHA1NonceGenerator(cfg.certNonceSeed) : null; db = into; }
Source:
public String getName() { String name= super.getName(); if (name != null) { name= MessageIds.IGNORED_TEST_PREFIX + name; if (reason != null && START reason.length() > 0) { END name= name + MessageIds.IGNORED_TEST_REASON_PREFIX + reason; } return name; } return null; } !reason.isEmpty() can be used

Target:
public String getName() { String name= super.getName(); if (name != null) { name= MessageIds.IGNORED_TEST_PREFIX + name; if (reason != null && !reason.isEmpty()) { name= name + MessageIds.IGNORED_TEST_REASON_PREFIX + reason; } return name; } return null; }
Source:
public EObject getEObject(String uriFragment) { Option<String> optionalRewrittenFragment = VSMMigrationService.getInstance().getNewFragment(uriFragment); if (optionalRewrittenFragment.some()) { return getEObject(optionalRewrittenFragment.get()); } else { START if (useURIFragmentAsId) { END return getEObjectUsingURIFragmentAsId(uriFragment); } else { return super.getEObject(uriFragment); } } } 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 { } }

Target:
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); } }
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()); START System.err.println(buf.toString()); END } Whe should a a @TODO that we want to do logging instead of writing to stderr.

Target:
private static void logCorruptPackError(IOException e, PackFile p) { StringBuilder buf = new StringBuilder(MessageFormat.format( JGitText.get().exceptionWhileReadingPack, p.getPackFile().getAbsolutePath())); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); buf.append('\n'); buf.append(sw.toString()); // TODO instead of syserr we should use a logging framework System.err.println(buf.toString()); }
Source:
protected ContentHandler createContentHandler(DocumentBuilder builder, boolean asDocument) { if (!asDocument && builder instanceof HtmlDocumentBuilder) { START ((HtmlDocumentBuilder) builder).setEmitAsDocument(false); END } return new DocumentBuilderAdapter(builder); } 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.

Target:
protected ContentHandler createContentHandler(DocumentBuilder builder, boolean asDocument) { if (builder instanceof HtmlDocumentBuilder) { ((HtmlDocumentBuilder) builder).setEmitAsDocument(asDocument); } return new DocumentBuilderAdapter(builder); }
Source:
private Set<Resource> getSessionResources(boolean includeMainResource) { List<Resource> result = Lists.newArrayList(); for (DAnalysis analysis : allAnalyses()) { Resource res = analysis.eResource(); if (res != null && START (analysis != sessionResource || includeMainResource)) END { result.add(res); } } return ImmutableSet.copyOf(result); } I would put includeMainResource || analysis != sessionResource

Target:
private Set<Resource> getSessionResources(boolean includeMainResource) { List<Resource> result = Lists.newArrayList(); for (DAnalysis analysis : allAnalyses()) { Resource res = analysis.eResource(); if (res != null && (includeMainResource || analysis != sessionResource)) { result.add(res); } } return ImmutableSet.copyOf(result); }
Source:
private String stripGitCloneCommand(String input) { START if (input.startsWith(GIT_CLONE_COMMAND_PREFIX)) { END return input.substring(GIT_CLONE_COMMAND_PREFIX.length()).trim(); } return input.trim(); } you need to first trim input otherwise this doesn't match if input starts with whitespace

Target:
private String stripGitCloneCommand(String input) { input = input.trim(); if (input.startsWith(GIT_CLONE_COMMAND_PREFIX)) { return input.substring(GIT_CLONE_COMMAND_PREFIX.length()).trim(); } return input.trim(); }
Source:
public MojoParameter getContainer(String[] path) { START if(path == null || path.length == 0) END 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; } trivial, but we use around single statements.

Target:
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; }
Source:
public InstallableUnitDescription readOneIU(InputStream is) throws IOException { Parser parser = new START Parser(org.eclipse.tycho.p2.maven.repository.xmlio.MetadataIO.Parser.PARSER_MODE.IU); END parser.parse(is, new NullProgressMonitor()); return parser.getUnits().get(0); } omit?

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

Target:
public Set<IInstallableUnit> readXML(InputStream is) throws IOException { Parser parser = new Parser(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; }
Source:
protected void updateComboTooltip() { // fBuildConfigCombo might not be loaded when controls are created START if (fBuildConfigCombo != null && fBuildConfigCombo.getSelectionIndex() > 0) { END 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); } } Aren't selection index starts with 0? Main tooltip would be actually for 0th element... Just need regular NPE protection if (configId==null) return;

Target:
protected void updateComboTooltip() { if (fBuildConfigCombo != null) { // fBuildConfigCombo might not be loaded when controls are created String configId = (String) fBuildConfigCombo.getData(Integer.toString(fBuildConfigCombo.getSelectionIndex())); String tooltip = EMPTY_STRING; if (configId != null) { 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); } }
Source:
public void setFastViewBarVisible(boolean visible) { START boolean oldValue = fastViewBarVisible; END fastViewBarVisible = visible; if (oldValue != fastViewBarVisible) { } } Replace method with // not supported anymore

Target:
public void setFastViewBarVisible(boolean visible) { // not supported anymore }
Source:
public boolean getFastViewBarVisible() { return START fastViewBarVisible; END } I suggest to make this "false" and remove the field.

Target:
public boolean getFastViewBarVisible() { return false; }
Source:
public boolean getShowFastViewBars() { return START getWindowConfigurer().getShowFastViewBars(); END } return false and also update WorkbenchWindowConfigurer

Target:
public boolean getShowFastViewBars() { return false; }
Source:
START public static END 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; } 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

Target:
protected 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; }
Source:
START public static END 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; } 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

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

Target:
private String convertCharacterProxyData(CharacterDataProxy dp) { String toWrite = dp.getValueAsString(); return AXml.textToXml(toWrite); }
Source:
public String getProperty(String key) { START return (String) value.get(key); END } This method indicates that the "value" map is expected to be <String, String> rather than <?, ?>.

Target:
public String getProperty(String key) { return value.get(key); }
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++) { START Map values = attributeMap.get(new Long(deltas[i].getId())); END assertEquals("Changes different from expecations", deltas[i].getAttributes(), values); } } This map should be generified as well.

Target:
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<String, Object> values = attributeMap.get(new Long(deltas[i].getId())); assertEquals("Changes different from expecations", deltas[i].getAttributes(), values); } }
Source:
private static List<Variable> removeDuplicates(List<Variable> typeMatches) { HashSet<Variable> set = new START HashSet<Variable>(); END set.addAll(typeMatches); return Arrays.asList(set.toArray(new Variable[set.size()])); } Done

Target:
private static List<Variable> removeDuplicates(List<Variable> typeMatches) { HashSet<Variable> set = new HashSet<>(); set.addAll(typeMatches); return Arrays.asList(set.toArray(new Variable[set.size()])); }
Source:
public List<Object> prepend(List<Object> list, Object object) { // TODO use lazy collection START final List<Object> result = Lists.newArrayList(); END result.add(object); result.addAll(list); return result; } Size the result list properly : final List<Object> result = new ArrayList<Object>(list.size() + 1);

Target:
public List<Object> prepend(List<Object> list, Object object) { // TODO use lazy collection final List<Object> result = new ArrayList<Object>(list.size() + 1); result.add(object); result.addAll(list); return result; }
Source:
START private String initialConnectionName() throws CoreException { END String name = DEFAULT_CONNECTION_NAME; int count = 1; while (getSelectedConnectionType().getConnection(name) != null) { name = DEFAULT_CONNECTION_NAME + " " + count++; //$NON-NLS-1$ } return name; } I can't see any reason to throw CoreException here.

Target:
private String initialConnectionName() { String name = DEFAULT_CONNECTION_NAME; int count = 1; while (getSelectedConnectionType().getConnection(name) != null) { name = DEFAULT_CONNECTION_NAME + " " + count++; //$NON-NLS-1$ } return name; }
Source:
START public boolean useLoginShell() { END String str = fRemoteConnection.getAttribute(USE_LOGIN_SHELL_ATTR); return str != null ? Boolean.parseBoolean(str) : DEFAULT_USE_LOGIN_SHELL; } 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.

Target:
public boolean useLoginShell() { String str = fRemoteConnection.getAttribute(USE_LOGIN_SHELL_ATTR); return !str.isEmpty() ? Boolean.parseBoolean(str) : DEFAULT_USE_LOGIN_SHELL; }
Source:
public TmfVertex(final long ts) { START this.fTimestamp = ts; END this.fId = count++; } you can also remove the thises

Target:
public TmfVertex(final long ts) { fTimestamp = ts; synchronized (TmfVertex.class) { fId = count++; } }
Source:
public Long getSum(@Nullable Object worker) { Long sum = 0L; for (Long duration : fWorkerStats.get(worker)) { START sum += duration; END } return sum; } 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.

Target:
public Long getSum(@Nullable Object worker) { long sum = 0L; synchronized (fWorkerStats) { for (long duration : fWorkerStats.get(worker)) { sum += duration; } } return sum; }
Source:
private IModelUpdateStrategyProvider createModelUpdateStrategyProvider() { final IModelUpdateStrategyProvider ret; IAccessorFactory accessorFactory = getAccessorFactoryForTarget(); START if (accessorFactory != null && accessorFactory instanceof IModelUpdateStrategyProvider) { END 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; } It's useless to check for null here since null instanceof Something always returns false.

Target:
private IModelUpdateStrategyProvider createModelUpdateStrategyProvider() { final IModelUpdateStrategyProvider ret; IAccessorFactory accessorFactory = getAccessorFactoryForTarget(); if (accessorFactory instanceof IModelUpdateStrategyProvider) { ret = (IModelUpdateStrategyProvider)accessorFactory; } else { ret = new IModelUpdateStrategyProvider() { public IModelUpdateStrategy getModelUpdateStrategy() { return new SingleValuedAttributeModelUpdateStrategy(); } }; } return ret; }
Source:
private void closeSideParts(MPart part, boolean left) { MElementContainer<MUIElement> container = getParent(part); START if (container == null) END return; List<MPart> others = getCloseableSideParts(part, left); closeSiblingParts(part, others, true); } Use brackets for single statements (I know we are very inconsitent here but this should be the goal)

Target:
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); }
Source:
START protected void linkClicked(EObject value) { END getViewModelContext().getService(ReferenceService.class).openInNewContext(value); } make private

Target:
private void linkClicked(EObject value) { getViewModelContext().getService(ReferenceService.class).openInNewContext(value); }
Source:
START protected final Color getSystemColor(Composite parent, int color) { END if (parent == null) { return Display.getDefault().getSystemColor(color); } return parent.getShell().getDisplay().getSystemColor(color); } make private

Target:
private final Color getSystemColor(Composite parent, int color) { if (parent == null) { return Display.getDefault().getSystemColor(color); } return parent.getShell().getDisplay().getSystemColor(color); }
Source:
public void image(Attributes attributes, String url) { assertOpenBlock(); try { currentBlock.write('!'); writeAttributes(attributes); if (url != null) START { END currentBlock.write(url); } currentBlock.write('!'); } catch (IOException e) { throw new RuntimeException(e); } } consider moving this null check up into the write() method, since that would guard in other places as well.

Target:
public void image(Attributes attributes, String url) { assertOpenBlock(); try { currentBlock.write('!'); writeAttributes(attributes); currentBlock.write(url); currentBlock.write('!'); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
START public static void checkStringDataLength(Object dataValue) { END 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); } } 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.

Target:
private 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); } }
Source:
public void tearDown() { START fLogger.removeAllAppenders(); END fBot.closeAllEditors(); } this is an @After, it should be in a new @AfterClass (or else you would lose logging after the first test).

Target:
public void tearDown() { fBot.closeAllEditors(); }
Source:
public void setTimeBounds(long beginTime, long endTime) { fBeginTime = beginTime; fEndTime = endTime; fTime0Bound = fBeginTime != SWT.DEFAULT ? fBeginTime : fEndTime; START fTime1Bound = fEndTime != SWT.DEFAULT ? fEndTime : fBeginTime; END if (fTime0Bound > fTime1Bound) { // only possible if both are not default fBeginTime = endTime; fEndTime = beginTime; fTime0Bound = fBeginTime; fTime1Bound = fEndTime; } adjustHorizontalScrollBar(); } 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.

Target:
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(); }
Source:
private void addMatchingProposals(SortedSet<BranchContentProposal> branches, String searchText) { START if (proposals.size() > 0) { END for (String branchProposal : proposals) { if (branchProposal.toLowerCase().contains(searchText)) { branches.add(new BranchContentProposal(branchProposal)); } } } } Don't need this check.

Target:
private void addMatchingProposals(SortedSet<BranchContentProposal> branches, String searchText) { for (String branchProposal : proposals) { if (branchProposal.toLowerCase().contains(searchText)) { branches.add(new BranchContentProposal(branchProposal)); } } }
Source:
public SaveParticipantPlugin() { START super(); END deltaVerifier = new ResourceDeltaVerifier(); } This change is not about removing org.eclipse.core.runtime.compatibility* bundles.

Target:
public SaveParticipantPlugin() { deltaVerifier = new ResourceDeltaVerifier(); }
Source:
private void removeListeners() { if (restoreToSavePointListener != null) { restoreToSavePointListener.unregister(); START restoreToSavePointListener.dispose(); END restoreToSavePointListener = null; } if (this.saveSessionListener != null) { this.saveSessionListener.unregister(); this.saveSessionListener = null; } } Instead of having both unregister() and dispose() methods we could have only dispose().

Target:
private void removeListeners() { if (restoreToSavePointListener != null) { restoreToSavePointListener.dispose(); restoreToSavePointListener = null; } if (this.saveSessionListener != null) { this.saveSessionListener.unregister(); this.saveSessionListener = null; } }
Source:
public void statusesChanged(Collection<ResourceStatusChange> changes) { /* this may be call in a async thread */ if (session != null) { START if (SessionStatus.SYNC.equals(session.getStatus())) { END marker = null; } } } == is sufficient.

Target:
public void statusesChanged(Collection<ResourceStatusChange> changes) { /* this may be call in a async thread */ if (session != null) { if (SessionStatus.SYNC == session.getStatus()) { marker = null; } } }
Source:
public void historyNotification(OperationHistoryEvent event) { if (session != null && START SessionStatus.DIRTY.equals(session.getStatus())) END { if (marker == null) { marker = event.getOperation(); } } } equals() is not usefull for enum, == is sufficient.

Target:
public void historyNotification(OperationHistoryEvent event) { if (session != null && SessionStatus.DIRTY == session.getStatus()) { if (marker == null) { marker = event.getOperation(); } } }
Source:
protected String createHttpRequestURL() { String bugUrl = getUrlSuffix(); LoginToken token = ((BugzillaRestHttpClient) getClient()).getLoginToken(); START if ((!(this instanceof BugzillaRestValidateRequest) && !(this instanceof BugzillaRestUnauthenticatedGetRequest)) END && 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; } Why exclude BugzillaRestValidateRequest and BugzillaRestUnauthenticatedGetRequest here whereas BugzillaRestAuthenticatedPostRequest overrides this method? Might as well just have all 3 override it.

Target:
protected String createHttpRequestURL() { String bugUrl = getUrlSuffix(); LoginToken token = ((BugzillaRestHttpClient) getClient()).getLoginToken(); if (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; }
Source:
public static RemoteConfig findRemoteConfig(Config config, String remoteName) throws URISyntaxException { START List<RemoteConfig> allRemoteConfigs; END RemoteConfig remoteConfig = null; allRemoteConfigs = RemoteConfig.getAllRemoteConfigs(config); for (RemoteConfig rc : allRemoteConfigs) { if (rc.getName().equals(remoteName)) remoteConfig = rc; } return remoteConfig; } Can you join the variable definition please?

Target:
public static RemoteConfig findRemoteConfig(Config config, String remoteName) throws URISyntaxException { RemoteConfig remoteConfig = null; List<RemoteConfig> allRemoteConfigs = RemoteConfig .getAllRemoteConfigs(config); for (RemoteConfig rc : allRemoteConfigs) { if (rc.getName().equals(remoteName)) { remoteConfig = rc; break; } } return remoteConfig; }
Source:
public static void configurePushURI(RemoteConfig remoteConfig, URIish pushURI) START throws URISyntaxException { END List<URIish> pushURIs = new ArrayList<URIish>( remoteConfig.getPushURIs()); for (URIish urIish : pushURIs) { remoteConfig.removePushURI(urIish); } remoteConfig.addPushURI(pushURI); } exception is not thrown in the code, why is it needed here?

Target:
public static void configurePushURI(RemoteConfig remoteConfig, URIish pushURI) { List<URIish> pushURIs = new ArrayList<URIish>( remoteConfig.getPushURIs()); for (URIish urIish : pushURIs) { remoteConfig.removePushURI(urIish); } remoteConfig.addPushURI(pushURI); }
Source:
public static void configureFetchNotes(RemoteConfig remoteConfig) { String notesRef = Constants.R_NOTES + "*"; //$NON-NLS-1$ List<RefSpec> fetchRefSpecs = remoteConfig.getFetchRefSpecs(); for (RefSpec refSpec : fetchRefSpecs) { START if (refSpec.matchSource(notesRef)) END return; } remoteConfig.addFetchRefSpec(new RefSpec(notesRef + ":" + notesRef)); //$NON-NLS-1$ } can you put braces around if block please.

Target:
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$ }
Source:
public NotificationFilter getFilter() { return NotificationFilter.createEventTypeFilter(Notification.SET).or(NotificationFilter.createEventTypeFilter(Notification.UNSET)) START .and(NotificationFilter.createNotifierTypeFilter(EObject.class).and(NotificationFilter.NOT_TOUCH)); END } I wonder if we should not put this not_touch in first position or at least before the EObject type filter

Target:
public NotificationFilter getFilter() { return NotificationFilter.NOT_TOUCH.and(NotificationFilter.createEventTypeFilter(Notification.SET)).or(NotificationFilter.createEventTypeFilter(Notification.UNSET)) .and(NotificationFilter.createNotifierTypeFilter(EObject.class)); }
Source:
public ICommandShell createCommandShell() { START LTTngToolsFileShell shell END = fShell; if (shell == null) { shell = new LTTngToolsFileShell(); if ((fTestFile != null) && (fScenario != null)) { shell.loadScenarioFile(fTestFile); shell.setScenario(fScenario); } fShell = shell; } return shell; } good multi-thread catch

Target:
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; } fShell = shell; } return shell; }
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() { START if (!getEditorControl().isDisposed() && KeyPressCommitRunnable.this.toCommit != null && KeyPressCommitRunnable.this.toCommit.equals(getEditorValue())) { END commit(MoveDirectionEnum.NONE, false); } } }); } 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.

Target:
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() != null && !getEditorControl().isDisposed() && KeyPressCommitRunnable.this.toCommit != null && KeyPressCommitRunnable.this.toCommit.equals(getEditorValue())) { commit(MoveDirectionEnum.NONE, false); } } }); }
Source:
private static String getFailMessage(ProcessStatus result) { ProcessStatus firstFail = getFirstFail(result.getChildren()); if (firstFail != null) { START return result.getMessage() + ": " + getFailMessage(firstFail) + getLineMessage(firstFail); END } return result.getMessage(); } 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.

Target:
private static String getFailMessage(ProcessStatus result) { ProcessStatus firstFail = getFirstFail(result.getChildren()); if (firstFail != null) { return getLineMessage(firstFail) + result.getMessage() + ": " + getFailMessage(firstFail); } return result.getMessage(); }
Source:
START public void expand(IProgressMonitor monitor) { END item.setExpanded(true); refreshContent(); } Here the monitor parameter it not used, you should use it, especially in refreshContent() as it is the longer in time.

Target:
public void expand(IProgressMonitor monitor) { item.setExpanded(true); refreshContent(false, monitor); }
Source:
public void expand(IProgressMonitor monitor) { START this.progressMonitor = monitor; END item.setExpanded(true); refreshContent(); } 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

Target:
public void expand(IProgressMonitor monitor) { item.setExpanded(true); refreshContent(); }
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; } START return NonNullUtils.equalsNullable(fFile, other.fFile); END } keep own check

Target:
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 (!equalsNullable(fTraceTypeId, other.fTraceTypeId)) { return false; } if (!equalsNullable(fFile, other.fFile)) { return false; } return true; }
Source:
private String getStorageKey(boolean perInstance) { START return (perInstance ? m_instance : "") + (m_category != "" ? "." + m_category : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ END } For strings, you have to use equals() to compare, not == or !=

Target:
private String getStorageKey(boolean perInstance) { return (perInstance ? m_instance : "") + (!m_category.equals("") ? "." + m_category : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ }
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$ } START initializePersistentParameters(); END } 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

Target:
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(m_visualizerInstanceId); }
Source:
private void persistParameter(T value) { // create memento String memento = MementoUtils.encodeStringIntoMemento(value.toString()); // save memento in store START IEclipsePreferences store = MulticoreVisualizerUIPlugin.getEclipsePreferenceStore(); END if (memento != null) { store.put(m_storeKey, memento); try { store.flush(); } catch (BackingStoreException e) { e.printStackTrace(); } } } Move above line to inside below if

Target:
private void persistParameter(T value) { // create memento String memento = MementoUtils.encodeStringIntoMemento(value.toString()); // save memento in store if (memento != null) { IEclipsePreferences store = MulticoreVisualizerUIPlugin.getEclipsePreferenceStore(); store.put(m_storeKey, memento); try { store.flush(); } catch (BackingStoreException e) { e.printStackTrace(); } } }
Source:
START protected END 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); } Remove protected to prevent access from outside the package and place the method near the other gtk_widget methods in this class.

Target:
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); }
Source:
protected void setUp() throws Exception { super.setUp(); START removeLeftOverProjects(); END 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); } } Why project stuff in baseUiTestCase now? It should be its own base class at least

Target:
protected void setUp() throws Exception { super.setUp(); final IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IViewPart view= activePage.findView("org.eclipse.cdt.ui.tests.DOMAST.DOMAST"); if (view != null) { activePage.hideView(view); } }
Source:
public void dispose() { START treeViewerManager.dispose(); END treeViewerManager = null; super.dispose(); if (getAdapterFactory() instanceof IDisposable) { ((IDisposable) getAdapterFactory()).dispose(); } if (refreshAtOpeningActivator != null) { getSite().getPage().removePartListener(refreshAtOpeningActivator); refreshAtOpeningActivator = null; } } 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.

Target:
public void dispose() { super.dispose(); if (getAdapterFactory() instanceof IDisposable) { ((IDisposable) getAdapterFactory()).dispose(); } if (refreshAtOpeningActivator != null) { getSite().getPage().removePartListener(refreshAtOpeningActivator); refreshAtOpeningActivator = null; } }
Source:
public void dispose() { START treeViewerManager.dispose(); END treeViewerManager = null; if (refreshAtOpeningActivator != null) { getSite().getPage().removePartListener(refreshAtOpeningActivator); } refreshAtOpeningActivator = null; super.dispose(); if (getAdapterFactory() instanceof IDisposable) { ((IDisposable) getAdapterFactory()).dispose(); } } Where is treeViewerManager disposed ? in DTreeEditor or in the parent AbstractDTreeEditor ? Looks like you are doing both

Target:
public void dispose() { if (refreshAtOpeningActivator != null) { getSite().getPage().removePartListener(refreshAtOpeningActivator); } refreshAtOpeningActivator = null; super.dispose(); if (getAdapterFactory() instanceof IDisposable) { ((IDisposable) getAdapterFactory()).dispose(); } }
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) { START e.printStackTrace(); END throw new RuntimeException(e); } } Debugging leftover?

Target:
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) { throw new RuntimeException(e); } }
Source:
public static EObject getEObjectValue(View view, String property, EObject defaultValue) { EObject value = defaultValue; EClass eObjectValueStyle = NotationPackage.eINSTANCE.getEObjectValueStyle(); NamedStyle START style; END if (eObjectValueStyle != null) { style = view.getNamedStyle(eObjectValueStyle, property); if (style instanceof EObjectValueStyle) { value = ((EObjectValueStyle) style).getEObjectValue(); } } return value; } The variable is declared in the bad scope.

Target:
public static EObject getEObjectValue(View view, String property, EObject defaultValue) { EObject value = defaultValue; EClass eObjectValueStyle = NotationPackage.eINSTANCE.getEObjectValueStyle(); if (eObjectValueStyle != null) { NamedStyle style = view.getNamedStyle(eObjectValueStyle, property); if (style instanceof EObjectValueStyle) { value = ((EObjectValueStyle) style).getEObjectValue(); } } return value; }
Source:
public ImageData getImageData (int zoom) { copyImageDataFromDpiImageStorage(DPIUtil.mapZoomToImageSelectorIndex(zoom)); ImageData returnVal = getImageData (); START copyImageDataFromDpiImageStorage(device.getImageSelector()); END return returnVal; } why call copy 2nd time?

Target:
public ImageData getImageData (int zoom) { copyImageDataFromDpiImageStorage(DPIUtil.mapZoomToImageSelectorIndex(zoom)); ImageData returnVal = getImageData (); copyImageDataFromDpiImageStorage(getImageSelector()); return returnVal; }
Source:
private Image getEnhancedImage(final Image image, final Viewpoint viewpoint) { if START (ViewpointRegistry.getInstance().isFromPlugin(viewpoint) END && image != null) { return SiriusEditPlugin.getPlugin().getImage(getOverlayedDescriptor(image, "icons/full/decorator/folder_close.gif")); } return image; } We do not want to decorate Viewpoint from plugins but from workspace.

Target:
private Image getEnhancedImage(final Image image, final Viewpoint viewpoint) { // Add decorator if the viewpoint comes from workspace if (!ViewpointRegistry.getInstance().isFromPlugin(viewpoint) && image != null) { return SiriusEditPlugin.getPlugin().getImage(getOverlayedDescriptor(image, "icons/full/decorator/folder_close.gif")); } return image; }
Source:
public void add(Expression expression) { if (fExpressions == null) fExpressions= new START ArrayList<Expression>(2); END fExpressions.add(expression); } A diamond operator would suffice.

Target:
public void add(Expression expression) { if (fExpressions == null) fExpressions= new ArrayList<>(2); fExpressions.add(expression); }
Source:
private static String toHex(byte[] bytes) { START StringBuilder builder = new StringBuilder(); END for (byte b : bytes) { builder.append(HEX.charAt((b & 0xF0) >> 4)); builder.append(HEX.charAt(b & 0xF)); } return builder.toString(); } Optional: Presize to 2 * bytes.length

Target:
private static String toHex(byte[] bytes) { StringBuilder builder = new StringBuilder(2 * bytes.length); for (byte b : bytes) { builder.append(HEX.charAt((b & 0xF0) >> 4)); builder.append(HEX.charAt(b & 0xF)); } return builder.toString(); }
Source:
public static TreeWalk forPath(final Repository db, final String path, final AnyObjectId... trees) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { START ObjectReader reader = db.newObjectReader(); try { return forPath(reader, path, trees); } finally { reader.close(); } END } Rewrite as try-with-resources: try (ObjectReader reader = db.newObjectReader()) { return forPath(reader, path, trees); } ?

Target:
public static TreeWalk forPath(final Repository db, final String path, final AnyObjectId... trees) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { try (ObjectReader reader = db.newObjectReader()) { return forPath(reader, path, trees); } }
Source:
START public static boolean isFloatingLabel(EObject notationElement) { END 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; } This method must not be static.

Target:
public 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; }
Source:
public Element getElement(Object node) { if (node == null) { return null; } EObject notationElement = getNativeWidget(node); START CSSDOMSemanticElementHelper helper = new CSSDOMSemanticElementHelper(); END 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); } I think that CSSDOMSemanticElemntHelper should be an Singleton.

Target:
public Element getElement(Object node) { if (node == null) { return null; } EObject notationElement = getNativeWidget(node); View canonicalNotationElement = CSSDOMSemanticElementHelper.getInstance().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); }
Source:
public void notifyChanged(Notification notification) { START final int eventType = notification.getEventType(); END if (eventType == StereotypeExtensionNotification.STEREOTYPE_APPLIED_TO_ELEMENT) { initialisation(); refreshNotationStructure(); } else if (eventType == StereotypeExtensionNotification.STEREOTYPE_UNAPPLIED_FROM_ELEMENT) { initialisation(); refreshNotationStructure(); } } Why this field is final ? It is only used in method scope.

Target:
public void notifyChanged(Notification notification) { int eventType = notification.getEventType(); if (eventType == StereotypeExtensionNotification.STEREOTYPE_APPLIED_TO_ELEMENT) { initialisation(); refreshNotationStructure(); } else if (eventType == StereotypeExtensionNotification.STEREOTYPE_UNAPPLIED_FROM_ELEMENT) { initialisation(); refreshNotationStructure(); } }
Source:
public GMFUMLElementAdapter(View view, ExtendedCSSEngine engine) { super(view, engine); START super.helper = new CSSDOMUMLSemanticElementHelper(); END } There maybe an other way to initialise the helper field. It will be better with a setter.

Target:
public GMFUMLElementAdapter(View view, ExtendedCSSEngine engine) { super(view, engine); helper = CSSDOMUMLSemanticElementHelper.getInstance(); }
Source:
START public String getStoreKey() { END return m_storeKey; } Should this be protected, or do we really want to allow to call it outside this class?

Target:
protected String getStoreKey() { return m_storeKey; }
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(); } START return (m_value!=null)? m_value : m_defaultValue; END } Could you check for null instead of !null so it uses the same logic as the new class PersistentListParameter?

Target:
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_defaultValue : m_value; }
Source:
private List<T> convertToT(List<String> vals) { List<T> convertedList = new ArrayList<T>(); for(String val : vals) { START convertedList.add(super.convertToT(val)); END } return convertedList; } No need for super

Target:
private List<T> convertToT(List<String> vals) { List<T> convertedList = new ArrayList<T>(); for(String val : vals) { convertedList.add(convertToT(val)); } return convertedList; }
Source:
public void registerAnalysis(final DAnalysis analysis) { START if (!analysis.eAdapters().contains(this)) { END analysis.eAdapters().add(this); } for (final DView view : analysis.getOwnedViews()) { registerView(view); } } 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.

Target:
public void registerAnalysis(final DAnalysis analysis) { analysis.eAdapters().add(this); for (final DView view : analysis.getOwnedViews()) { registerView(view); } }
Source:
public Heap(final int estimatedSize, final int limit) { START super(limit, estimatedSize); END } wrong arg order

Target:
public Heap(final int estimatedSize, final int limit) { super(estimatedSize, limit); }