auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static String[] getErrorParserExtensionIds() { START return fExtensionErrorParsers.keySet().toArray(new String[0]); END } Better: new String[fExtensionErrorParsers.size()]

Target:
public static String[] getErrorParserExtensionIds() { return fExtensionErrorParsers.keySet().toArray(new String[fExtensionErrorParsers.size()]); }
Source:
public static String[] getDefaultErrorParserIds() { START if (fDefaultErrorParserIds==null) { END return fAvailableErrorParsers.keySet().toArray(new String[0]); } return fDefaultErrorParserIds.toArray(new String[0]); } Restore the spaces.

Target:
public static String[] getDefaultErrorParserIds() { if (fDefaultErrorParserIds == null) { return fAvailableErrorParsers.keySet().toArray(new String[fAvailableErrorParsers.size()]); } return fDefaultErrorParserIds.toArray(new String[fDefaultErrorParserIds.size()]); }
Source:
public boolean isEnabled() { final Repository repository = getRepository(); START return repository != null && containsHead(repository); END } I'd prefer to remove the field itself. Feels a bit unclean to have a field which is only valid during the execute method. It should be a local variable in execute and passed as an argument to getTagTarget. What do you think?

Target:
public boolean isEnabled() { final Repository repo = getRepository(); return repo != null && containsHead(repo); }
Source:
public static void trace(String option, String message, Throwable throwable) { //copy the message to a new string, then print the new string to the //console in blocks of 100 characters. String systemPrintableMessage = message; while (systemPrintableMessage.length() > 100) { String partial = systemPrintableMessage.substring(0, 100); systemPrintableMessage = systemPrintableMessage.substring(100); System.out.println(partial + "\\"); //$NON-NLS-1$ START } END //then pass the original message to be traced into a file if(fgDebugTrace != null) { fgDebugTrace.trace(option, message, throwable); } } Missing System.out.print(systemPrintableMessage); after the while loop, to deal with the part of the string that is <= 100.

Target:
public static void trace(String option, String message, Throwable throwable) { //divide the string into substrings of 100 chars or less for printing //to console String systemPrintableMessage = message; while (systemPrintableMessage.length() > 100) { String partial = systemPrintableMessage.substring(0, 100); systemPrintableMessage = systemPrintableMessage.substring(100); System.out.println(partial + "\\"); //$NON-NLS-1$ } System.out.println(systemPrintableMessage); //then pass the original message to be traced into a file if(fgDebugTrace != null) { fgDebugTrace.trace(option, message, throwable); } }
Source:
public GdbCommandTimeoutManager( ICommandControl commandControl ) { fCommandControl = commandControl; fListeners = new ListenerList(); START new GdbDebugOptions(GdbPlugin.getBundleContext()); END } Remove. This is done only once in the plugin.start() method.

Target:
public GdbCommandTimeoutManager( ICommandControl commandControl ) { fCommandControl = commandControl; fListeners = new ListenerList(); }
Source:
public static void trace(String option, String message, Throwable throwable) { //divide the string into substrings of 100 chars or less for printing //to console String systemPrintableMessage = message; while (systemPrintableMessage.length() > 100) { String partial = systemPrintableMessage.substring(0, 100); systemPrintableMessage = systemPrintableMessage.substring(100); System.out.print(partial + "\\"); //$NON-NLS-1$ } START System.out.println(systemPrintableMessage); END //then pass the original message to be traced into a file if(fgDebugTrace != null) { fgDebugTrace.trace(option, message, throwable); } } You changed the wrong one :) It is the one outside the while loop that must be print()

Target:
public static void trace(String option, String message, Throwable throwable) { //divide the string into substrings of 100 chars or less for printing //to console String systemPrintableMessage = message; while (systemPrintableMessage.length() > 100) { String partial = systemPrintableMessage.substring(0, 100); systemPrintableMessage = systemPrintableMessage.substring(100); System.out.println(partial + "\\"); //$NON-NLS-1$ } System.out.print(systemPrintableMessage); //then pass the original message to be traced into a file if(fgDebugTrace != null) { fgDebugTrace.trace(option, message, throwable); } }
Source:
public PullCommand setRebase(boolean useRebase) { checkCallable(); START if (useRebase) { END pullRebaseMode = PullRebaseMode.REBASE; } else { pullRebaseMode = PullRebaseMode.NO_REBASE; } return this; } style nit: we don't use curly braces around single line statements

Target:
public PullCommand setRebase(boolean useRebase) { checkCallable(); pullRebaseMode = useRebase ? PullRebaseMode.REBASE : PullRebaseMode.NO_REBASE; return this; }
Source:
START private String getAttribute(PlexusConfiguration dom, String attrName) throws PlexusConfigurationException { END String attr = dom.getAttribute(attrName); if (attr == null) { return null; } attr = attr.trim(); if (attr.length() == 0) { return null; } return attr; } This Exception is never thrown. It may be that while developing, you had a change here that required the throws clause, but it isn't need in the proposed patch. I would have expected that would have reviewed your own change before proposing it here, and that you have removed this change.

Target:
private String getAttribute(PlexusConfiguration dom, String attrName) { String attr = dom.getAttribute(attrName); if (attr == null) { return null; } attr = attr.trim(); if (attr.length() == 0) { return null; } return attr; }
Source:
public String getLabel(Object object) { START return "" + object; //$NON-NLS-1$ END } Should invoke object.toString()

Target:
public String getLabel(Object object) { return object.toString(); }
Source:
START public String getKey() { END return key; } private?

Target:
String getKey() { return key; }
Source:
private void lazyLoadModulesConfig() throws IOException, ConfigInvalidException { START if (modulesConfig == null) { END loadModulesConfig(); } } curly braces aren't required

Target:
private void lazyLoadModulesConfig() throws IOException, ConfigInvalidException { if (modulesConfig == null) loadModulesConfig(); }
Source:
public static SubmoduleWalk forIndex(Repository repository) throws IOException { SubmoduleWalk generator = new SubmoduleWalk(repository); try { DirCache index = repository.readDirCache(); generator.setTree(new DirCacheIterator(index)); START if (repository.isBare()) END generator.setRootTree(new DirCacheIterator(index)); else generator.useWorkingTree = true; } catch (IOException e) { generator.release(); throw e; } return generator; } Does this make sense? I didn't think bare repositories have an index so repository.readDirCache() would already throw an exception at this point since repository.getIndexFile() throws an exception for bare repositories as is called by DirCache.read

Target:
public static SubmoduleWalk forIndex(Repository repository) throws IOException { SubmoduleWalk generator = new SubmoduleWalk(repository); try { DirCache index = repository.readDirCache(); generator.setTree(new DirCacheIterator(index)); generator.useWorkingTree = true; } catch (IOException e) { generator.release(); throw e; } return generator; }
Source:
public String toString() { START return "SubscribeCommand[" + command.toString() + " " + spec + "]"; END } .toString() isn't necessary. + will call it for you.

Target:
public String toString() { return "SubscribeCommand[" + command + " " + spec + "]"; }
Source:
public int hashCode() { int hash = 1; hash = hash * 31 + command.hashCode(); hash = hash * 31 + spec.hashCode(); START return hash; END } Alternatively you can do: Arrays.hashCode(new Object[]{command, spec});

Target:
public int hashCode() { return Arrays.hashCode(new Object[] { command, spec }); }
Source:
private void writeSubscribeCommands( String repoName, List<SubscribeCommand> commands) throws IOException { write("repository " + repoName); for (SubscribeCommand cmd : commands) { switch (cmd.getCommand()) { case SUBSCRIBE: write("want " + cmd.getSpec()); break; case UNSUBSCRIBE: write("stop " + cmd.getSpec()); break; default: START throw new IllegalArgumentException(); END } } } include the cmd as the message.

Target:
private void writeSubscribeCommands( String repoName, List<SubscribeCommand> commands) throws IOException { write("repository " + repoName); for (SubscribeCommand cmd : commands) { switch (cmd.getCommand()) { case SUBSCRIBE: write("want " + cmd.getSpec()); break; case UNSUBSCRIBE: write("stop " + cmd.getSpec()); break; default: throw new IllegalArgumentException(cmd.toString()); } } }
Source:
BasePackSubscribeConnection(PackTransport packTransport) { super(packTransport); START closed = false; END } Unnecessary, booleans default to false.

Target:
BasePackSubscribeConnection(PackTransport packTransport) { super(packTransport); }
Source:
START public void dispose() { END fTCPBlock.dispose(); fSerialBlock.dispose(); fConnectionStack.dispose(); fConnectionField.dispose(); } This method overrides StandardGDBDebuggerPage.dispose(). Why don't you just use super.dispose() in it and dispose only of the widgets and classes added to GDBServerDebuggerPage?

Target:
public void dispose() { fTCPBlock.dispose(); fSerialBlock.dispose(); fConnectionStack.dispose(); fConnectionField.dispose(); super.dispose(); }
Source:
START public void setSessionLifetime(int lifetime) { END sessionLifetime = lifetime; } synchronized

Target:
public synchronized void setSessionLifetime(int lifetime) { sessionLifetime = lifetime; }
Source:
private Window(Node n, int capacity) { current = start = first = n; markCapacity = capacity; START marked = new ArrayList<Node>(capacity); END } capacity + 1

Target:
private Window(Node n, int capacity) { current = start = first = n; markCapacity = capacity; marked = new ArrayList<Node>(capacity + 1); }
Source:
public static boolean isPublishSubscribe(String pathOrUri) { START return pathOrUri != null && pathOrUri.endsWith(PUBLISH_SUBSCRIBE_PATH); END } Because the pubsub handler matches ^/ rather than */, this logic needs to be different.

Target:
public static boolean isPublishSubscribe(String pathOrUri) { return pathOrUri != null && pathOrUri.equals(PUBLISH_SUBSCRIBE_PATH); }
Source:
long milliTime() { START return System.nanoTime() / 1000000; END } I usually prefer TimeUnit.NANOS.toMillis(System.nanoTime())

Target:
private long milliTime() { return System.nanoTime() / 1000000; }
Source:
START void doSubscribe( END Map<String, List<SubscribeCommand>> commands, PrintWriter output) throws NotSupportedException, TransportException, InterruptedException, IOException { connection = transport.openSubscribe(subscriber); transport.setTimeout(timeout); try { connection.subscribe(subscriber, commands, output); } finally { closeConnection(); } } this should be private.

Target:
void doSubscribe( Map<String, List<SubscribeCommand>> commands, PrintWriter output) throws NotSupportedException, TransportException, InterruptedException, IOException { transport.setTimeout(timeout); connection = transport.openSubscribe(subscriber); try { connection.subscribe(subscriber, commands, output); } finally { connection.close(); connection = null; } }
Source:
public void start(BundleContext context) throws Exception { super.start(context); contextStore = new LocalContextStore(commonContextScaling); File storeFile = getDefaultContextLocation().toFile(); if (!storeFile.exists()) { storeFile.mkdirs(); } contextStore.setContextDirectory(storeFile); contextManager = new InteractionContextManager(contextStore); // Because ContextContributor are ContextListener, we need them right away START initContextContributor(); END } Loading a chain of classes and potentially activating other bundles during bundle startup can be very problematic. We'll need to find a way to initialize contributors lazily, e.g. on first context activation.

Target:
public void start(BundleContext context) throws Exception { super.start(context); contextStore = new LocalContextStore(commonContextScaling); File storeFile = getDefaultContextLocation().toFile(); if (!storeFile.exists()) { storeFile.mkdirs(); } contextStore.setContextDirectory(storeFile); contextManager = new InteractionContextManager(contextStore); }
Source:
protected void setDefaultProfileAttributes( START ILaunchConfigurationWorkingCopy wc) throws CoreException { END wc.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, false); wc.setAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true); } CoreException is not actaully thrown from this method body.

Target:
protected void setDefaultProfileAttributes( ILaunchConfigurationWorkingCopy wc) { wc.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, false); wc.setAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true); }
Source:
public String getResult() { try { float res = Float.parseFloat(result); if (res > 0) { return "+" + result; } else { return result; } START } catch (Exception e) { END return result; } } Again, please don't catch Exception. Code compiles fine without the try catch but you might want to replace it with catch for NumberFormatException.

Target:
public String getResult(){ return result; }
Source:
public DefaultDsfExecutor(String name) { super(1, new DsfThreadFactory(name + " - " + fgInstanceCounter++)); //$NON-NLS-1$ fName = name; START if(DsfDebugOptions.DEBUG_EXECUTOR || ASSERTIONS_ENABLED) { END // If tracing, pre-start the dispatch thread, and add it to the map. prestartAllCoreThreads(); fThreadToExecutorMap.put(((DsfThreadFactory)getThreadFactory()).fThread, DefaultDsfExecutor.this); } } This is done in the constructor and therefore does not allow to be changed during a debug session. However, other areas below do allow such a dynamic change. I'm worried that we'll have a conflict where we try tracing while not everything is initialized. Either the stuff in the constructor should be moved out in a smart way, or the flags should be per instance of the class and not allowed to change once the class is created.

Target:
public DefaultDsfExecutor(String name) { super(1, new DsfThreadFactory(name + " - " + fgInstanceCounter++)); //$NON-NLS-1$ fName = name; if(DEBUG_EXECUTOR || ASSERTIONS_ENABLED) { // If tracing, pre-start the dispatch thread, and add it to the map. prestartAllCoreThreads(); fThreadToExecutorMap.put(((DsfThreadFactory)getThreadFactory()).fThread, DefaultDsfExecutor.this); } }
Source:
public void execute(Runnable command) { // Check if executable wasn't executed already. START if (DsfDebugOptions.DEBUG && DsfDebugOptions.DEBUG_EXECUTOR && command instanceof DsfExecutable) { END assert !((DsfExecutable)command).getSubmitted() : "Executable was previously executed."; //$NON-NLS-1$ ((DsfExecutable)command).setSubmitted(); } command.run(); } Remove chedk for DEBUG which should be part of DsfDebugOptions directly

Target:
public void execute(Runnable command) { // Check if executable wasn't executed already. if (DsfDebugOptions.DEBUG_EXECUTOR && command instanceof DsfExecutable) { assert !((DsfExecutable)command).getSubmitted() : "Executable was previously executed."; //$NON-NLS-1$ ((DsfExecutable)command).setSubmitted(); } command.run(); }
Source:
public void registerModelAdapter(Class<?> adapterType, Object adapter) { START if (DsfDebugOptions.DEBUG && DsfDebugOptions.DEBUG_SESSION && DsfDebugOptions.DEBUG_SESSION_MODEL_ADAPTERS) { END String msg = new Formatter().format( "%s Registering model adapter %s of type %s to session %s (%s)", //$NON-NLS-1$ DsfPlugin.getDebugTime(), LoggingUtils.toString(adapter), adapterType.getName(), LoggingUtils.toString(this), getId() ).toString(); DsfDebugOptions.trace(msg); } fAdapters.put(adapterType, adapter); } Let's only use DsfDebugOptions... as mentioned above

Target:
public void registerModelAdapter(Class<?> adapterType, Object adapter) { if (DsfDebugOptions.DEBUG_SESSION_MODEL_ADAPTERS) { String msg = new Formatter().format( "%s Registering model adapter %s of type %s to session %s (%s)", //$NON-NLS-1$ DsfPlugin.getDebugTime(), LoggingUtils.toString(adapter), adapterType.getName(), LoggingUtils.toString(this), getId() ).toString(); DsfDebugOptions.trace(msg); } fAdapters.put(adapterType, adapter); }
Source:
public void unregisterModelAdapter(Class<?> adapterType) { START if (DsfDebugOptions.DEBUG && DsfDebugOptions.DEBUG_SESSION && DsfDebugOptions.DEBUG_SESSION_MODEL_ADAPTERS) { END String msg = new Formatter().format( "%s Unregistering model adapter of type %s from session %s (%s)", //$NON-NLS-1$ DsfPlugin.getDebugTime(), adapterType.getName(), LoggingUtils.toString(this), getId() ).toString(); DsfDebugOptions.trace(msg); } fAdapters.remove(adapterType); } Let's only use DsfDebugOptions... as mentioned above

Target:
public void unregisterModelAdapter(Class<?> adapterType) { if (DsfDebugOptions.DEBUG_SESSION_MODEL_ADAPTERS) { String msg = new Formatter().format( "%s Unregistering model adapter of type %s from session %s (%s)", //$NON-NLS-1$ DsfPlugin.getDebugTime(), adapterType.getName(), LoggingUtils.toString(this), getId() ).toString(); DsfDebugOptions.trace(msg); } fAdapters.remove(adapterType); }
Source:
public double getLocationRatio(ITmfLocation<?> location) { final CtfLocation curLocation = (CtfLocation) location; START CtfIterator iterator = CtfIteratorManager.getIterator(this, ctx); END ctx.setLocation(curLocation); ctx.seek(curLocation.getLocation()); long currentTime = ((Long)ctx.getLocation().getLocation()); return ((double) currentTime - iterator.getStartTime()) / (iterator.getEndTime() - iterator.getStartTime()); } Could you use a local context instead?

Target:
public double getLocationRatio(ITmfLocation<?> location) { final CtfLocation curLocation = (CtfLocation) location; CtfIterator iterator = getIterator(); ctx.setLocation(curLocation); ctx.seek(curLocation.getLocation()); long currentTime = ((Long)ctx.getLocation().getLocation()); return ((double) currentTime - iterator.getStartTime()) / (iterator.getEndTime() - iterator.getStartTime()); }
Source:
public void addResolutionListener(IQualifiedTypeResolutionListener resolutionListener) { for (int i = 0; i < this.resolutionListeners.length; i++){ if (this.resolutionListeners[i].equals(resolutionListener)) return; } int length = this.resolutionListeners.length; System.arraycopy(this.resolutionListeners, 0, this.resolutionListeners = new IQualifiedTypeResolutionListener[length + 1], 0, length); START this.resolutionListeners[this.resolutionListeners.length - 1] = resolutionListener; END } this.resolutionListeners[length] = resolutionListener would have sufficed.

Target:
public void addResolutionListener(IQualifiedTypeResolutionListener resolutionListener) { for (int i = 0; i < this.resolutionListeners.length; i++){ if (this.resolutionListeners[i].equals(resolutionListener)) return; } int length = this.resolutionListeners.length; System.arraycopy(this.resolutionListeners, 0, this.resolutionListeners = new IQualifiedTypeResolutionListener[length + 1], 0, length); this.resolutionListeners[length] = resolutionListener; }
Source:
public void registerEventInTimeRange(ITmfEvent event, ITmfExtraEventInfo extraInfo) { TmfFixedArray<String>[] paths = getNormalPaths(event, extraInfo); for (TmfFixedArray<String> path : paths) START ++(getOrCreate(path).getValue().nbEventsInTimeRange); END paths = getTypePaths(event, extraInfo); for (TmfFixedArray<String> path : paths) ++(getOrCreate(path).getValue().nbEventsInTimeRange); } Hmm, this I don't really like, a getter shouldn't be used for writing to a value. You could add .incrementValue() method or something.

Target:
public void registerEventInTimeRange(ITmfEvent event, ITmfExtraEventInfo extraInfo) { TmfFixedArray<String>[] paths = getNormalPaths(event, extraInfo); for (TmfFixedArray<String> path : paths) { ++(getOrCreate(path).getValue().nbEventsInTimeRange); } paths = getTypePaths(event, extraInfo); for (TmfFixedArray<String> path : paths) { ++(getOrCreate(path).getValue().nbEventsInTimeRange); } }
Source:
START public int compareTo(ActivityEvent object) { END if (date == null || object.getDate() == null) { return 0; } return date.compareTo(object.getDate()); } This implementation is not transitive. null elements should either be ordered first or last.

Target:
public int compareTo(ActivityEvent object) { if (date == null && object.getDate() == null) { return 0; } if (date == null || object.getDate() == null) { return -1; } return date.compareTo(object.getDate()); }
Source:
private void initialize() { START Assert.isNotNull(scope, "Task scope should not be null."); //$NON-NLS-1$ END events.addAll(manager.getEvents(scope)); try { ReviewTaskProvider reviewTaskProvider = new ReviewTaskProvider(); reviewTaskProvider.open(manager); reviewTaskProvider.query(scope, null); } catch (CoreException e) { System.out.println(e); } events.addAll(manager.getEvents(scope)); } the constructor already asserts that

Target:
private void initialize() { events.addAll(manager.getEvents(scope)); }
Source:
public Collection<ActivityEvent> getEvents(ActivityScope scope) { Assert.isNotNull(scope, "Task scope should not be null."); //$NON-NLS-1$ START events.addAll(new ReviewTaskProvider().getReviews(((TaskActivityScope) scope).getTask().getTaskId())); END return events; } Querying of provider should be implemented in ActivityStream by invoking the query() method on the different providers.

Target:
public Collection<ActivityEvent> getEvents(ActivityScope scope) { return events; }
Source:
public void dispose() { super.dispose(); START if (fStatsViewers != null) { END fStatsViewers.dispose(); } // clean the model TmfStatisticsTreeRootFactory.removeAll(); } I see this check in many places. Can fStatsViewers actually be null? Would it be possible to make it final, and initialize it in the constructor?

Target:
public void dispose() { super.dispose(); fStatsViewers.dispose(); // clean the model TmfStatisticsTreeRootFactory.removeAll(); }
Source:
public IQueryResult<IInstallableUnit> query(IQuery<IInstallableUnit> query, IProgressMonitor monitor) { START if (consider == Consider.FALSE) { END return new CollectionResult<IInstallableUnit>(Collections.<IInstallableUnit> emptyList()); } else { return super.query(query, monitor); } } I am wondering if this check shouldn't be on the caller side of this method.

Target:
public IQueryResult<IInstallableUnit> query(IQuery<IInstallableUnit> query, IProgressMonitor monitor) { if (consider == Boolean.FALSE) { return new CollectionResult<IInstallableUnit>(Collections.<IInstallableUnit> emptyList()); } else { return super.query(query, monitor); } }
Source:
void setDeltaAttempted(boolean deltaAttempted) { if (deltaAttempted) flags |= DELTA_ATTEMPTED; else START flags &= DELTA_ATTEMPTED; END } Missing ~

Target:
void setDeltaAttempted(boolean deltaAttempted) { if (deltaAttempted) flags |= DELTA_ATTEMPTED; else flags &= ~DELTA_ATTEMPTED; }
Source:
public TmfSimpleTimestamp(final ITmfTimestamp timestamp) { super(timestamp.getValue(), 0, 0); START if (timestamp.getScale() != 0 || timestamp.getPrecision() != 0) { END throw new IllegalArgumentException(); } } I'm having second thought on this one: maybe we should not throw an exception but use this as a conversion function i.e. normalize to scale=0 and drop the precision.

Target:
public TmfSimpleTimestamp(final ITmfTimestamp timestamp) { super(timestamp.getValue(), 0, 0); }
Source:
public ITmfContext seekEvent(double ratio) { CtfTmfLightweightContext context = new CtfTmfLightweightContext(this); final long end = this.getEndTime().getValue(); final long start = this.getStartTime().getValue(); final long diff = end - start; final CtfTmfTimestamp ratioTs = new CtfTmfTimestamp((long) (diff * ratio) + start); START context.seek( ratioTs.getValue() ); END context.setRank(ITmfContext.UNKNOWN_RANK); return context; } Spacing is wrong, Ctrl+Shift+F this part

Target:
public ITmfContext seekEvent(double ratio) { CtfTmfLightweightContext context = new CtfTmfLightweightContext(this); final long end = this.getEndTime().getValue(); final long start = this.getStartTime().getValue(); final long diff = end - start; final long ratioTs = (long) (diff * ratio) + start; context.seek(ratioTs); context.setRank(ITmfContext.UNKNOWN_RANK); return context; }
Source:
private void setExecutionEnvironment(TargetPlatformConfiguration result, Xpp3Dom configuration) { String value = getStringValue(configuration.getChild("executionEnvironment")); if (value == null) { return; } START if (value.startsWith("?")) { END throw new RuntimeException( "The target-platform-configuration parameter <executionEnvironment> must not start with a '?'. Use <defaultExecutionEnvironment> without a leading '?' instead."); } try { ExecutionEnvironmentUtils.getExecutionEnvironment(value); } catch (UnknownEnvironmentException e) { throw new RuntimeException("Invalid execution environment profile name " + value); } result.setExecutionEnvironment(value); } We don't need this check. Even if "?" is used somewhere, which I doubt, UnknownEnvironmentException be self-exlanatory enough for somebody to investigate and fix it.

Target:
private void setExecutionEnvironment(TargetPlatformConfiguration result, Xpp3Dom configuration) { String value = getStringValue(configuration.getChild("executionEnvironment")); if (value == null) { return; } try { ExecutionEnvironmentUtils.getExecutionEnvironment(value); } catch (UnknownEnvironmentException e) { throw new RuntimeException("Invalid execution environment profile name " + value); } result.setExecutionEnvironment(value); }
Source:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { START Hashtable<String, String> parameters = (Hashtable<String, String>) data; END String profilingType = parameters .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY); String profilingTypeName = parameters .get(ProviderProfileConstants.INIT_DATA_NAME_KEY); if (profilingType == null) { profilingType = ""; } if (profilingTypeName == null) { profilingTypeName = ""; } setProfilingType(profilingType); setProfilingTypeName(profilingTypeName); } even though data is a HashTable, it's best to cast it as a Map since that's all that we require.

Target:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { Map<String, String> parameters = (Map<String, String>) data; String profilingType = parameters .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY); String profilingTypeName = parameters .get(ProviderProfileConstants.INIT_DATA_NAME_KEY); if (profilingType == null) { profilingType = ""; } if (profilingTypeName == null) { profilingTypeName = ""; } setProfilingType(profilingType); setProfilingTypeName(profilingTypeName); }
Source:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { START Hashtable<String, String> parameters = (Hashtable<String, String>) data; END String profilingType = parameters .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY); String configId = parameters .get(ProviderProfileConstants.INIT_DATA_CONFIG_ID_KEY); if (profilingType == null) { profilingType = ""; } if (configId == null) { configId = ""; } setLaunchConfigID(configId); setProfilingType(profilingType); } This should cast to Map<String,String>.

Target:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { Map<String, String> parameters = (Map<String, String>) data; String profilingType = parameters .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY); String configId = parameters .get(ProviderProfileConstants.INIT_DATA_CONFIG_ID_KEY); if (profilingType == null) { profilingType = ""; } if (configId == null) { configId = ""; } setLaunchConfigID(configId); setProfilingType(profilingType); }
Source:
public String getCommitMessage() { String text = getText(); text = Utils.normalizeLineEndings(text); START if (shouldHardWrap()) { END text = hardWrap(text); } return text; } style nit: we don't use braces around single line blocks

Target:
public String getCommitMessage() { String text = getText(); text = Utils.normalizeLineEndings(text); if (shouldHardWrap()) text = hardWrap(text); return text; }
Source:
public void doSubmit() { START if (!checkCanSubmit(IMessageProvider.ERROR)) { END return; } super.doSubmit(); } style nit: we don't use braces around single line blocks

Target:
public void doSubmit() { if (!checkCanSubmit(IMessageProvider.ERROR)) return; super.doSubmit(); }
Source:
public void execute() throws MojoExecutionException, MojoFailureException { if (!TARGET_DEFINITION_PACKAGING.equals(project.getPackaging())) { throw new MojoExecutionException("This goal can only be executed on projects with packaging type '" START + TARGET_DEFINITION_PACKAGING + "'"); END } File targetFile = new File(project.getBasedir(), project.getArtifactId() + FILE_EXTENSION); if (!targetFile.isFile()) { throw new MojoExecutionException("Expected target definition file '" + targetFile.getAbsolutePath() + "' could not be found."); } project.getArtifact().setFile(targetFile); } What is this check needed for? We might as well omit it to allow others to create a packaging type "my-eclipse-target-definition" that for example includes additional steps in the default lifecycle.

Target:
public void execute() throws MojoExecutionException, MojoFailureException { File targetFile = new File(project.getBasedir(), project.getArtifactId() + FILE_EXTENSION); if (!targetFile.isFile()) { throw new MojoExecutionException("Expected target definition file '" + targetFile.getAbsolutePath() + "' could not be found."); } project.getArtifact().setFile(targetFile); }
Source:
START protected DirCacheEntry keep(DirCacheEntry e) { END DirCacheEntry newEntry = new DirCacheEntry(e.getPathString(), e.getStage()); newEntry.setFileMode(e.getFileMode()); newEntry.setObjectId(e.getObjectId()); newEntry.setLastModified(e.getLastModified()); newEntry.setLength(e.getLength()); builder.add(newEntry); return newEntry; } You don't need to change this method signature. I would leave this method private

Target:
private DirCacheEntry keep(DirCacheEntry e) { DirCacheEntry newEntry = new DirCacheEntry(e.getPathString(), e.getStage()); newEntry.setFileMode(e.getFileMode()); newEntry.setObjectId(e.getObjectId()); newEntry.setLastModified(e.getLastModified()); newEntry.setLength(e.getLength()); builder.add(newEntry); return newEntry; }
Source:
START protected int mergeFileModes(int modeB, int modeO, int modeT) { END if (modeO == modeT) return modeO; if (modeB == modeO) // Base equal to Ours -> chooses Theirs if that is not missing return (modeT == FileMode.MISSING.getBits()) ? modeO : modeT; if (modeB == modeT) // Base equal to Theirs -> chooses Ours if that is not missing return (modeO == FileMode.MISSING.getBits()) ? modeT : modeO; return FileMode.MISSING.getBits(); } You don't need to change this method signature. I would leave this method private.

Target:
private int mergeFileModes(int modeB, int modeO, int modeT) { if (modeO == modeT) return modeO; if (modeB == modeO) // Base equal to Ours -> chooses Theirs if that is not missing return (modeT == FileMode.MISSING.getBits()) ? modeO : modeT; if (modeB == modeT) // Base equal to Theirs -> chooses Ours if that is not missing return (modeO == FileMode.MISSING.getBits()) ? modeT : modeO; return FileMode.MISSING.getBits(); }
Source:
protected boolean mergeImpl() throws IOException { boolean implicitDirCache = false; boolean clean = false; if (dircache == null) { dircache = getRepository().lockDirCache(); implicitDirCache = true; } clean = mergeTrees(mergeBase().getEntryObjectId(), sourceTrees[0], sourceTrees[1]); START if (implicitDirCache) { END dircache.unlock(); } return clean; } style nit: no braces around single line blocks

Target:
protected boolean mergeImpl() throws IOException { boolean implicitDirCache = false; boolean clean = false; if (dircache == null) { dircache = getRepository().lockDirCache(); implicitDirCache = true; } try { clean = mergeTrees(mergeBase(), sourceTrees[0], sourceTrees[1]); } finally { if (implicitDirCache) { dircache.unlock(); } } return clean; }
Source:
public TaskJobEvent(ITask originalTask, ITask task) { START this.originalTask = originalTask; END this.task = task; } This should invoke the other constructor so that taskData can be marked as final.

Target:
public TaskJobEvent(ITask originalTask, ITask task) { this(originalTask, task, null); }
Source:
public boolean filter(List<?> filters) { if (filters == null) { START return true; END } fLock.lock(); try { cancelOngoingRequests(); List<FilterCriteria> list = (List<FilterCriteria>)filters; fFilterCriteria = new ArrayList<FilterCriteria>(list); fillCurrentPage(fEvents); } finally { fLock.unlock(); } return true; } Will the page update if filters were previously active?

Target:
public boolean filter(List<?> filters) { fLock.lock(); try { cancelOngoingRequests(); if (filters == null) { fFilterCriteria = new ArrayList<FilterCriteria>(); } else { List<FilterCriteria> list = (List<FilterCriteria>)filters; fFilterCriteria = new ArrayList<FilterCriteria>(list); } fillCurrentPage(fEvents); } finally { fLock.unlock(); } return true; }
Source:
public BugzillaPeoplePart() { START setPartName(Messages.BugzillaPeoplePart_People); END } This is the same string so we don't need to do this.

Target:
public BugzillaPeoplePart() { }
Source:
START private void createAttributeEditors(FormToolkit toolkit, Composite peopleComposite) { END Collection<TaskAttribute> attributes = getAttributes(); for (TaskAttribute attribute : attributes) { addAttribute(peopleComposite, toolkit, attribute); } } We should probably leave this protected to avoid breaking people.

Target:
protected void createAttributeEditors(FormToolkit toolkit, Composite peopleComposite) { Collection<TaskAttribute> attributes = getAttributes(); for (TaskAttribute attribute : attributes) { addAttribute(peopleComposite, toolkit, attribute); } }
Source:
private AlternateHandle openAlternate(File objdir) throws IOException { final File parent = objdir.getParentFile(); if (FileKey.isGitRepository(parent, fs)) { FileKey key = FileKey.exact(parent, fs); FileRepository db = (FileRepository) RepositoryCache.open(key); return new AlternateRepository(db); } START ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, shallowFile); END return new AlternateHandle(db); } The alternate shouldn't have this repository's shallow file. Define the alternate to have a shallow file of null and handle this case in getShallowCommits() where shallowFile == null means use the empty set.

Target:
private AlternateHandle openAlternate(File objdir) throws IOException { final File parent = objdir.getParentFile(); if (FileKey.isGitRepository(parent, fs)) { FileKey key = FileKey.exact(parent, fs); FileRepository db = (FileRepository) RepositoryCache.open(key); return new AlternateRepository(db); } ObjectDirectory db = new ObjectDirectory(config, objdir, null, fs, null); return new AlternateHandle(db); }
Source:
public boolean isMergedInto(final RevCommit base, final RevCommit tip) throws MissingObjectException, IncorrectObjectTypeException, IOException { START initializeShallowCommits(); END final RevFilter oldRF = filter; final TreeFilter oldTF = treeFilter; try { finishDelayedFreeFlags(); reset(~freeFlags & APP_FLAGS); filter = RevFilter.MERGE_BASE; treeFilter = TreeFilter.ALL; markStart(tip); markStart(base); return next() == base; } finally { filter = oldRF; treeFilter = oldTF; } } Not necessary here.

Target:
public boolean isMergedInto(final RevCommit base, final RevCommit tip) throws MissingObjectException, IncorrectObjectTypeException, IOException { final RevFilter oldRF = filter; final TreeFilter oldTF = treeFilter; try { finishDelayedFreeFlags(); reset(~freeFlags & APP_FLAGS); filter = RevFilter.MERGE_BASE; treeFilter = TreeFilter.ALL; markStart(tip); markStart(base); return next() == base; } finally { filter = oldRF; treeFilter = oldTF; } }
Source:
public RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { START initializeShallowCommits(); END return pending.next(); } Not necessary here.

Target:
public RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { return pending.next(); }
Source:
public RevCommit parseCommit(final AnyObjectId id) throws MissingObjectException, IncorrectObjectTypeException, IOException { START initializeShallowCommits(); END RevObject c = peel(parseAny(id)); if (!(c instanceof RevCommit)) throw new IncorrectObjectTypeException(id.toObjectId(), Constants.TYPE_COMMIT); return (RevCommit) c; } Not necessary here. Its handled within parseAny.

Target:
public RevCommit parseCommit(final AnyObjectId id) throws MissingObjectException, IncorrectObjectTypeException, IOException { RevObject c = peel(parseAny(id)); if (!(c instanceof RevCommit)) throw new IncorrectObjectTypeException(id.toObjectId(), Constants.TYPE_COMMIT); return (RevCommit) c; }
Source:
private RevCommit getCommit(Repository repository, String objectId) { RevWalk revWalk = null; try { revWalk = new RevWalk(repository); return revWalk.parseCommit(ObjectId.fromString(objectId)); START } catch (MissingObjectException e) { END return null; } catch (IncorrectObjectTypeException e) { return null; } catch (IOException e) { return null; } finally { if (revWalk != null) { revWalk.release(); } } } Catch Exception instead to simplify the code?

Target:
private RevCommit getCommit(Repository repository, String objectId) { RevWalk revWalk = null; try { revWalk = new RevWalk(repository); return revWalk.parseCommit(ObjectId.fromString(objectId)); } catch (Exception e) { return null; } finally { if (revWalk != null) { revWalk.release(); } } }
Source:
FileRevisionTypedElement getAncestorRevision() { START if (ancestor instanceof FileRevisionTypedElement) { END return (FileRevisionTypedElement) ancestor; } return null; } style nit: no braces here

Target:
FileRevisionTypedElement getAncestorRevision() { if (ancestor instanceof FileRevisionTypedElement) return (FileRevisionTypedElement) ancestor; return null; }
Source:
public String getProperty(String key) { if (properties != null) { START if (properties.containsKey(key)) { END return properties.get(key); } } return null; } Should just return properties.get(), the containsKey() call is redundant.

Target:
public String getProperty(String key) { if (properties != null) { return properties.get(key); } return null; }
Source:
public void add(final String[] log) { table.getControl().getDisplay().syncExec(new Runnable() { public void run() { table.addRow(log); try { PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().showView(ID); } catch(PartInitException pie) { START } catch(NullPointerException npe) END } }); } NPE should not be catched btu the case where it might appear should be checked with if (smth != null). We definetely don't want to ignore every NPE.

Target:
public void add(final String[] log) { table.getControl().getDisplay().syncExec(new Runnable() { public void run() { table.addRow(log); try { PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().showView(ID); } catch(PartInitException pie) { } } }); }
Source:
public void doAfterTest() throws Exception { START getGDBLaunch().terminate(); END fBreakpointService = null; fTraceService = null; fBreakpointsDmc = null; fTraceTargetDmc = null; if (fServicesTracker != null) { fServicesTracker.dispose(); fServicesTracker = null; } super.doAfterTest(); } This is already done by super.doAfterTest();

Target:
public void doAfterTest() throws Exception { super.doAfterTest(); fBreakpointService = null; fTraceService = null; fBreakpointsDmc = null; fTraceTargetDmc = null; if (fServicesTracker != null) { fServicesTracker.dispose(); fServicesTracker = null; } }
Source:
public void testSFINAEInDefaultArgument() throws Exception { START parseAndCheckBindings(getAboveComment(), CPP, true); END } parseAndCheckBindings() is sufficient since GNU extensions are not needed.

Target:
public void testSFINAEInDefaultArgument() throws Exception { parseAndCheckBindings(); }
Source:
public String[] getProbeVariableCompletions(String probe, String prefix){ TreeNode node = TapsetLibrary.getProbes(); // Get the matching leaf node. node = node.getChildByName(getTapset(probe)); if (node == null ) return NO_MATCHES; node = node.getChildByName(probe); if (node == null ) return NO_MATCHES; // Get the completions. String[] matchingChildren = getMatchingChildren(node, prefix); if(matchingChildren.length == 0) START return NO_MATCHES; END return matchingChildren; } Here if we change NO_MATCHES to be of length 0 then we would not need this change because any array of length 0 would do

Target:
public String[] getProbeVariableCompletions(String probe, String prefix){ TreeNode node = TapsetLibrary.getProbes(); // Get the matching leaf node. node = node.getChildByName(getTapset(probe)); if (node == null ) return NO_MATCHES; node = node.getChildByName(probe); if (node == null ) return NO_MATCHES; // Get the completions. return getMatchingChildren(node, prefix); }
Source:
public void testCustomAttributes() { START Collection<String> attributes = fixture.listCustomAttributes(); END assertEquals(0, attributes.size()); String attrib = fixture.getCustomAttribute("bozo"); //$NON-NLS-1$ assertNull(attrib); } You can use Set<String> here now, but it doesn't really matter...

Target:
public void testCustomAttributes() { Set<String> attributes = fixture.listCustomAttributes(); assertEquals(0, attributes.size()); String attrib = fixture.getCustomAttribute("bozo"); //$NON-NLS-1$ assertNull(attrib); }
Source:
public void dispose() { for (StreamInputReader reader : streamInputReaders) { if (reader != null) { reader.dispose(); } START } END } We should call clear after disposing all the readers

Target:
public void dispose() { for (StreamInputReader reader : streamInputReaders) { if (reader != null) { reader.dispose(); } } streamInputReaders.clear(); }
Source:
static String readSymlink(File path) throws IOException { Path nioPath = path.toPath(); Path target = Files.readSymbolicLink(nioPath); String targetString = target.toString(); if (SystemReader.getInstance().isWindows()) targetString = targetString.replace('\\', '/'); START else if (SystemReader.getInstance().isMacOS()) { END targetString = Normalizer.normalize(targetString, Form.NFC); } return targetString; } style nit: no braces here

Target:
static String readSymlink(File path) throws IOException { Path nioPath = path.toPath(); Path target = Files.readSymbolicLink(nioPath); String targetString = target.toString(); if (SystemReader.getInstance().isWindows()) targetString = targetString.replace('\\', '/'); else if (SystemReader.getInstance().isMacOS()) targetString = Normalizer.normalize(targetString, Form.NFC); return targetString; }
Source:
public void setHidden(File path, boolean hidden) throws IOException { START super.setHidden(path, hidden); END } instead of delegating to the super class I would instead not override this method in this subclass

Target:
public void setHidden(File path, boolean hidden) throws IOException { // no action on POSIX }
Source:
public RDTCommandLauncher(IProject project) { fProcess = null; fShowCommand = false; try { if (project.hasNature(SYNC_NATURE)) { IRemoteResource remoteRes = (IRemoteResource)project.getAdapter(IRemoteResource.class); uri = remoteRes.getActiveLocationURI(); } else{ uri = project.getLocationURI(); } lineSeparator = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (CoreException e) { // TODO Auto-generated catch block START e.printStackTrace(); END } } Please don't print the stack trace.

Target:
public RDTCommandLauncher(IProject project) { fProcess = null; fShowCommand = false; try { if (project.hasNature(Messages.SYNC_NATURE)) { IRemoteResource remoteRes = (IRemoteResource)project.getAdapter(IRemoteResource.class); uri = remoteRes.getActiveLocationURI(); } else{ uri = project.getLocationURI(); } lineSeparator = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (CoreException e) { uri = project.getLocationURI(); } }
Source:
private String toStringDescription() { if (Strings.isValid(getDescription())) { return " - " + getDescription(); } return ""; START } END Can we adhere to the coding style of this file and not have multiple return statements?

Target:
private String toStringDescription() { String description = ""; if (Strings.isValid(getDescription())) { description = " - " + getDescription(); } return description; }
Source:
public static int indexOfChangeId(String message, String delimiter) { String[] lines = message.split(delimiter); int footerFirstLine = indexOfFirstFooterLine(lines); if (footerFirstLine == lines.length) return -1; int indexOfFooter = 0; START for (int i = 0; i < footerFirstLine; ++i) { END indexOfFooter += lines[i].length() + delimiter.length(); } return message.indexOf(CHANGE_ID, indexOfFooter); } style nit: no braces around single line blocks

Target:
public static int indexOfChangeId(String message, String delimiter) { String[] lines = message.split(delimiter); int footerFirstLine = indexOfFirstFooterLine(lines); if (footerFirstLine == lines.length) return -1; int indexOfFooter = 0; for (int i = 0; i < footerFirstLine; ++i) indexOfFooter += lines[i].length() + delimiter.length(); return message.indexOf(CHANGE_ID, indexOfFooter); }
Source:
public void getReport(XResultData rd) { START rd.logWithFormat("AtsConfigCache\n", AtsConfigCache.instance); END rd.logWithFormat("TagToConfigObject size %d\n", tagToConfigObject.keySet().size()); rd.logWithFormat("ConfigObjects size %d\n", configObjects.size()); } Looks like you don't need to pass in the instance here since there's no formatting characters in the string.

Target:
public void getReport(XResultData rd) { rd.logWithFormat("TagToConfigObject size %d\n", tagToConfigObject.keySet().size()); rd.logWithFormat("ConfigObjects size %d\n", configObjects.size()); }
Source:
public DfsPackDescription(DfsRepositoryDescription repoDesc, String name) { this.repoDesc = repoDesc; int dot = name.lastIndexOf('.'); this.packName = (dot < 0) ? name : name.substring(0, dot); START this.sizeMap = new HashMap<String, Long>(); END } Set the table size to 5. We expect ~4 entries. 5 is a good default size.

Target:
public DfsPackDescription(DfsRepositoryDescription repoDesc, String name) { this.repoDesc = repoDesc; int dot = name.lastIndexOf('.'); this.packName = (dot < 0) ? name : name.substring(0, dot); this.sizeMap = new HashMap<String, Long>(5); }
Source:
public long getFileSize(String ext) { Long size = sizeMap.get(ext); START return (size == null) ? 0 : size.longValue(); END } No parens on condition.

Target:
public long getFileSize(String ext) { Long size = sizeMap.get(ext); return size == null ? 0 : size.longValue(); }
Source:
public String printMatchingStats() { String stats = ""; for (int i = 0; i<fTraces.length; i++) { START stats += "Trace " + i + ": " + fUnmatched[i].size() + " unmatched events"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ END } return stats; } Instead of using String += otherString, it's more efficient to use a StringBuilder and .append() (especially when in a loop), then return sb.toString() at the end.

Target:
public String printMatchingStats() { StringBuilder b = new StringBuilder(); for (int i = 0; i < fTraces.length; i++) { b.append("Trace " + i + ": " + fUnmatched[i].size() + " unmatched events"); } return b.toString(); }
Source:
protected int countEvents(Map<Object, LinkedList<ITmfEvent>> tbl) { Iterator<Entry<Object, LinkedList<ITmfEvent>>> iterator = tbl.entrySet().iterator(); int count = 0; while (iterator.hasNext()) { count += iterator.next().getValue().size(); START } END return count; } Would be a tad simpler to do: for (List<ITmfEvent> list : tbl.values()) { count += list.size(); }

Target:
protected int countEvents(Map<Object, LinkedList<ITmfEvent>> tbl) { int count = 0; for (LinkedList<ITmfEvent> entry : tbl.values()) { count += entry.size(); } return count; }
Source:
public void run() { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { START ScriptConsole console = ScriptConsole.getActive(); END if(null != console && console.isRunning()){ console.stop(); } } }); } We should use console class member not ask for the active.

Target:
public void run() { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { if(null != console && console.isRunning()){ console.stop(); } } }); }