auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected AbstractXmlApplicationContext createApplicationContext() { String version = Version.getCurrentVersion(); ClassPathXmlApplicationContext applicationContext = null; START if (version.startsWith("2") && (version.contains("2.5") || version.contains("2.4"))) { END applicationContext = new ClassPathXmlApplicationContext(new String("org/apache/camel/component/cxf/jaxrs/CxfRsSpringEndpointBeans.xml")); } else { applicationContext = new ClassPathXmlApplicationContext(new String("org/apache/camel/component/cxf/jaxrs/CxfRsSpringEndpointBeans-2.6.xml")); } emulateBeanRegistrationProgrammatically(applicationContext); return applicationContext; } This version check could be removed as we already move to 2.6.x

Target:
protected AbstractXmlApplicationContext createApplicationContext() { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String("org/apache/camel/component/cxf/jaxrs/CxfRsSpringEndpointBeans.xml")); emulateBeanRegistrationProgrammatically(applicationContext); return applicationContext; }
Source:
private void handlePendingScenario(ITmfEvent event, boolean isInputValid) { if (fConsuming && isEventConsumed()) { return; } if ((fInitialStateId.equals(TmfXmlState.INITIAL_STATE_ID) || isInputValid) && fPendingScenario != null) { START @NonNull TmfXmlScenario scenario = fPendingScenario; END handleScenario(scenario, event); if (!scenario.isPending()) { addActiveScenario(scenario); fPendingScenario = null; } } } You should extract to local variable before the if and use this variable to null-check in the if

Target:
private void handlePendingScenario(ITmfEvent event, boolean isInputValid) { if (fConsuming && isEventConsumed()) { return; } TmfXmlScenario scenario = fPendingScenario; if ((fInitialStateId.equals(TmfXmlState.INITIAL_STATE_ID) || isInputValid) && scenario != null) { handleScenario(scenario, event); if (!scenario.isPending()) { addActiveScenario(scenario); fPendingScenario = null; } } }
Source:
public boolean isRestricted() { START throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. END } Oops.

Target:
public boolean isRestricted() { return true; }
Source:
private Guid getTargetClusterId(Action action) { if (action.isSetCluster() && START (action.getCluster().isSetId() || action.getCluster().isSetName())) { END return getClusterId(action); } // means use the cluster of the provided host return null; } I think that this check makes more sense in the "getClusterId" method. Can we move it there?

Target:
private Guid getTargetClusterId(Action action) { if (action.isSetCluster()) { return getClusterId(action); } // means use the cluster of the provided host return null; }
Source:
public Object[] factory() { START List testsToRun = new ArrayList<>(); END testsToRun.add(new DistributedMultimapCacheTest().fromOwner(false).cacheMode(CacheMode.DIST_SYNC).transactional(false)); testsToRun.add(new DistributedMultimapCacheTest().fromOwner(true).cacheMode(CacheMode.DIST_SYNC).transactional(false)); return testsToRun.toArray(); } do you have any trouble with array initializers?

Target:
public Object[] factory() { return new Object[]{ new DistributedMultimapCacheTest().fromOwner(false).cacheMode(CacheMode.DIST_SYNC).transactional(false), new DistributedMultimapCacheTest().fromOwner(true).cacheMode(CacheMode.DIST_SYNC).transactional(false), }; }
Source:
private boolean isNimbus(Subject who) { START Set<Principal> principals = null; END boolean isNimbusInstance = false; if (who != null) { principals = who.getPrincipals(); for (Principal principal : principals) { if (principal instanceof NimbusPrincipal) { isNimbusInstance = true; } } } return isNimbusInstance; } unnecessary assignment, actually it can be moved into if

Target:
private boolean isNimbus(Subject who) { Set<Principal> principals; boolean isNimbusInstance = false; if (who != null) { principals = who.getPrincipals(); for (Principal principal : principals) { if (principal instanceof NimbusPrincipal) { isNimbusInstance = true; } } } return isNimbusInstance; }
Source:
ILogData read(long address) { if (!runtime.getParameters().isCacheDisabled()) { // The VersionLockedObject and the Transaction layer will generate // undoRecord(s) during a transaction commit, or object sync. These // undo records are stored in transient fields and are not persisted. // A missing undo record can cause a NoRollbackException, thus forcing // a complete object rebuild that generates a "scanning" behavior // which affects the LRU window. In essence, affecting other cache users // and making the VersionLockedObject very sensitive to caching behavior. // A concrete example of this would be unsynchronized readers/writes: // 1. Thread A starts replicating write1 // 2. Thread B discovers the write (via stream tail query) and // tries to read write1 // 3. Thread B's read results in a cache miss and the reader thread // starts loading the value into the cache // 4. Thread A completes its write and caches it with undo records // 5. Thread B finishes loading and caches the loaded value replacing // the cached value from step 4 (i.e. loss of undo records computed // by thread A) ILogData data = readCache.getIfPresent(address); if (data == null) { final ILogData loadedVal = fetch(address); START data = readCache.asMap().computeIfAbsent(address, (k) -> loadedVal); END } return data; } return fetch(address); } Return just here.

Target:
ILogData read(long address) { if (!runtime.getParameters().isCacheDisabled()) { // The VersionLockedObject and the Transaction layer will generate // undoRecord(s) during a transaction commit, or object sync. These // undo records are stored in transient fields and are not persisted. // A missing undo record can cause a NoRollbackException, thus forcing // a complete object rebuild that generates a "scanning" behavior // which affects the LRU window. In essence, affecting other cache users // and making the VersionLockedObject very sensitive to caching behavior. // A concrete example of this would be unsynchronized readers/writes: // 1. Thread A starts replicating write1 // 2. Thread B discovers the write (via stream tail query) and // tries to read write1 // 3. Thread B's read results in a cache miss and the reader thread // starts loading the value into the cache // 4. Thread A completes its write and caches it with undo records // 5. Thread B finishes loading and caches the loaded value replacing // the cached value from step 4 (i.e. loss of undo records computed // by thread A) ILogData data = readCache.getIfPresent(address); if (data == null) { // Loading a value without the cache loader can result in // redundant loading calls (i.e. multiple threads try to // load the same value), but currently a redundant RPC // is much cheaper than the cost of a NoRollBackException, therefore // this trade-off is reasonable final ILogData loadedVal = fetch(address); return readCache.asMap().computeIfAbsent(address, (k) -> loadedVal); } return data; } return fetch(address); }
Source:
public void tearDown() { START closeAllRuntimeException(queryRunner); END queryRunner = null; } Why not just `queryRunner.close();`?

Target:
public void tearDown() { queryRunner.close(); }
Source:
public AuditLogType getAuditLogTypeValue() { UserProfile existingProfile = getUserProfile(); START if (existingProfile != null && isSSHPublicKeyUpdate(existingProfile)) { END return getSucceeded() ? AuditLogType.USER_UPDATE_PROFILE : AuditLogType.USER_UPDATE_PROFILE_FAILED; } else { return getSucceeded() ? AuditLogType.USER_ADD_PROFILE : AuditLogType.USER_ADD_PROFILE_FAILED; } } since this method is called after the validate method, you can make the check shorter as you did in the executeCommand method

Target:
public AuditLogType getAuditLogTypeValue() { UserProfile existingProfile = getUserProfile(); if (existingProfile != null) { /* same as executeCommand below */ return getSucceeded() ? AuditLogType.USER_UPDATE_PROFILE : AuditLogType.USER_UPDATE_PROFILE_FAILED; } else { return getSucceeded() ? AuditLogType.USER_ADD_PROFILE : AuditLogType.USER_ADD_PROFILE_FAILED; } }
Source:
public ConfigurationBuilder getDefaultCacheBuilder() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.memory().storageType(StorageType.OFF_HEAP); // Off heap and compatibility don't work together START configurationBuilder.compatibility().disable(); END return configurationBuilder; } Aren't there any test methods that require compatibility?

Target:
public ConfigurationBuilder getDefaultCacheBuilder() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.memory().storageType(StorageType.OFF_HEAP); return configurationBuilder; }
Source:
public boolean counter(String key, int magnitude) { START String stat = String.format(Locale.ENGLISH, "%s:%d|c", key, magnitude); END return maybeAppend(stat); } UTF8?

Target:
public boolean counter(String key, int magnitude) { String stat = String.format("%s:%d|c", key, magnitude); return maybeAppend(stat); }
Source:
public FunctionMetadata getFunctionMetadata(FunctionHandle functionHandle) { START checkArgument(functionHandle.getCatalogSchemaName().equals(STATIC_FUNCTION_NAMESPACE_CATALOG_SCHEMA_NAME), "Expect static function namespace"); END return staticFunctionNamespace.getFunctionMetadata((StaticFunctionHandle) functionHandle); } Maybe a static helper function `isStaticFunctionNamespace(functionHandle)`; also, why not `functionHandle instanceof StaticFunctionHandle`?

Target:
public FunctionMetadata getFunctionMetadata(FunctionHandle functionHandle) { return staticFunctionNamespace.getFunctionMetadata(functionHandle); }
Source:
public void waitForValueToBePresentInElementsAttributeByCss(String selector, String attribute, String value) { changeImplicitWait(250, TimeUnit.MILLISECONDS); try { waitFor.until(CommonExpectedConditions.valueToBePresentInElementsAttribute( START By.cssSelector(selector), attribute, escapeHtml(value))); END } finally { restoreDeaultImplicitWait(); } } I don't think we should escape on this level, we should explicitly escape title of a video when passing to a method, not in here. Let's move it to `verifyVideoAdded(String videoTitle)` in `SpecialVideosPageObject`

Target:
public void waitForValueToBePresentInElementsAttributeByCss(String selector, String attribute, String value) { changeImplicitWait(250, TimeUnit.MILLISECONDS); try { waitFor.until(CommonExpectedConditions.valueToBePresentInElementsAttribute( By.cssSelector(selector), attribute, value)); } finally { restoreDeaultImplicitWait(); } }
Source:
public String parse() { StringBuilder myCommandBuilder = new StringBuilder(""); for (String argument:mArgs) { START myCommandBuilder.append(argument+" "); END } return myCommandBuilder.toString(); } А вообще надо два append() делать

Target:
public String parse() { StringBuilder myCommandBuilder = new StringBuilder(""); for (String argument : mArgs) { myCommandBuilder.append(argument); myCommandBuilder.append(" "); } return myCommandBuilder.toString(); }
Source:
public void testUseMetaAfterCreate() throws IOException { DataFileWriter<?> w = new DataFileWriter<>(new GenericDatumWriter<>()); w.create(Schema.create(Type.NULL), new ByteArrayOutputStream()); w.setMeta("foo", "bar"); START w.close(); END } Can we use a try-with-resource pattern here?

Target:
public void testUseMetaAfterCreate() throws IOException { try (DataFileWriter<?> w = new DataFileWriter<>(new GenericDatumWriter<>())) { w.create(Schema.create(Type.NULL), new ByteArrayOutputStream()); w.setMeta("foo", "bar"); } }
Source:
public LabelMetadataBuilder setOrigin(String origin) { this.origin = origin; START return this; END } Is the fluent required here? could we just a have a basic setter instead?

Target:
public void setOrigin(String origin) { this.origin = origin; }
Source:
START public long cyclesToNanos(long cycles) { END // CTFTrace adds the clock offset in cycles to the input CTFTrace trace = fTrace; if (trace != null) { CTFClock clock = trace.getClock(); return trace.timestampCyclesToNanos(cycles - trace.getOffset()) + clock.getClockOffsetNs(); } return 0; } This method is a simple converter that is only dependent on frequency and not dependent on clock offset. It should return cycles * clock.getScale(), or cycles if clock is null.

Target:
public long cyclesToNanos(long cycles) { // CTFTrace adds the clock offset in cycles to the input CTFTrace trace = fTrace; if (trace != null) { return trace.timestampCyclesToNanos(cycles - trace.getOffset()); } return 0; }
Source:
private Document createDocument() { Document document = null; try { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); document = documentBuilder.newDocument(); } catch (ParserConfigurationException pce) { START pce.printStackTrace(); END } return document; } dont do this but let the exception be propagated back up so we can have a better error reporting about not possible to generate jacoco report due to .... Also these methods can be static methods

Target:
private static Document createDocument() throws ParserConfigurationException { Document document = null; DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); document = documentBuilder.newDocument(); return document; }
Source:
public ConnectDocumentToLanguageServerSetupParticipant() { ITextFileBufferManager.DEFAULT.addFileBufferListener(new FileBufferListenerAdapter() { @Override public void bufferDisposed(IFileBuffer buffer) { START Job job = locationMap.get(buffer.getLocation()); END if (job != null) { job.cancel(); } locationMap.remove(buffer.getLocation()); } }); } You can directly invoke Job job = locationMap.remove(buffer.getLocation()); if (job != null) { job.cancel(); }

Target:
public ConnectDocumentToLanguageServerSetupParticipant() { ITextFileBufferManager.DEFAULT.addFileBufferListener(new FileBufferListenerAdapter() { @Override public void bufferDisposed(IFileBuffer buffer) { Job job = locationMap.remove(buffer.getLocation()); if (job != null) { job.cancel(); } } }); }
Source:
START public void createAndSetPhoneHome() { END this.phoneHome = new PhoneHome(node); } Can it be `protected`?

Target:
protected void createAndSetPhoneHome() { this.phoneHome = new PhoneHome(node); }
Source:
protected void verifySafeObject(final AnyObjectId id, final int type, final byte[] data) { try { super.verifySafeObject(id, type, data); } catch (CorruptObjectException e) { // catch the exception and continue parse the pack file START CorruptObject o = new CorruptObject(id.toObjectId(), type, END e.getErrorType()); corruptObjects.add(o); } } Can simplify by avoiding the temporary: corruptObjects.add(new CorruptObject(...));

Target:
protected void verifySafeObject(final AnyObjectId id, final int type, final byte[] data) { try { super.verifySafeObject(id, type, data); } catch (CorruptObjectException e) { corruptObjects.add( new CorruptObject(id.toObjectId(), type, e.getErrorType())); } }
Source:
public KeyValuePairValidation() { START this.allowAlsoKey = false; END } Nit-pick: to have more consistent constructor behavior, I'd prefer to do this(false)

Target:
public KeyValuePairValidation() { this(false); }
Source:
public String getNameTokenWithClass() { if (nameTokenPsiClass == null) { return ""; } START String s = nameTokenPsiClass.getName().replace(".java", "") + "." + nameToken; END return s; } nl and return directly

Target:
public String getNameTokenWithClass() { if (nameTokenPsiClass == null) { return ""; } return nameTokenPsiClass.getName().replace(".java", "") + "." + nameToken; }
Source:
public void setGrantType(String grantType) { START setProperty(GRANT_TYPE, grantType); END } the sole appropriate grantType must be an `stormpath_token` therefore please assert that the parameter is always `stormpath_token`. Additionally it should not be `public` (`protected` at the minimum), it should be just invoked internally when this class is created.

Target:
protected void setGrantType(String grantType) { setProperty(GRANT_TYPE, grantType); }
Source:
private static <T> void printIndented(Iterable<T> strings) { START for (T extension : strings) { END System.out.println(" " + extension); } } other name (for example item) instead of extension?

Target:
private static <T> void printIndented(Iterable<T> strings) { for (T item : strings) { System.out.println(" " + item); } }
Source:
public int getMaxDamage() { if (itemMaterial == null) { return 0; } else { return itemMaterial.getMaxDamage(); START } END } Can be simplified to ```java return itemMaterial == null ? 0 : itemMaterial.getMaxDamage(); ```

Target:
public int getMaxDamage() { return itemMaterial.getMaxDamage(); }
Source:
public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); JSONObject payload = getRequest().getPayload(); String type = payload.getString("type"); WebDriverLog log = (WebDriverLog) session.getLogManager().getLog(type); START List<LogEntry> entries = (log == null ? null : log.getAndClearEntries()); END return createResponse(entries); } Return empty list (ImmutableList.of()), not null, if log == null

Target:
public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); JSONObject payload = getRequest().getPayload(); String type = payload.getString("type"); List<LogEntry> entries = session.getLogManager().getLog(type); return createResponse(entries); }
Source:
public Cursor selectAll() { START return select("", new String[] {}, null); END } Could these params just be null, null, null?

Target:
public Cursor selectAll() { return select(null, null, null); }
Source:
public int getId() { try { return id; } catch (RuntimeException e) { throw logAndPrepareForRethrow(e); } catch (Error e) { throw logAndPrepareForRethrow(e); } catch (Throwable t) { throw logAndPrepareForRethrow(t); START } END } Well I think at least here we do not need all this try/catch stuff ))

Target:
public int getId() { return id; }
Source:
public ADBInfo(HashMap<String,String> env) { this.env = env; try { String dockerHost = env.get("DOCKER_HOST"); URI url = new URI(dockerHost); String h = url.getHost(); openshiftHost = "https://" + h; START } catch(URISyntaxException murle) { END murle.printStackTrace(); } } Why should this be catched? Shouldn't this make it to the caller that then can react accordingly?

Target:
public ADBInfo(HashMap<String,String> env) throws URISyntaxException { this.env = env; String dockerHost = env.get("DOCKER_HOST"); URI url = new URI(dockerHost); String h = url.getHost(); openshiftHost = "https://" + h; }
Source:
public void testStrlen() { assertExpr("strlen(x)", 3L); assertExpr("strlen(nonexistent)", NullHandling.defaultLongValue()); START assertExprFail("strlen(a)", AssertionError.class, null); END } This test should be adjusted since you removed the strlen change.

Target:
public void testStrlen() { assertExpr("strlen(x)", 3L); assertExpr("strlen(nonexistent)", NullHandling.defaultLongValue()); }
Source:
public boolean deleteFile(File file, boolean recursive) { if (recursive) { return this.deleteRecursive(file); } START return file.delete(); END } deleteFile(file)

Target:
public boolean deleteFile(File file, boolean recursive) { if (recursive) { return this.deleteRecursive(file); } return this.deleteFile(file); }
Source:
public ArrayList<Brick> getBricksRequiringResources(int resource) { START ArrayList<Brick> resourceBrickList = new ArrayList<Brick>(); END for (Brick brick : brickList) { if ((brick.getRequiredResources() & resource) > 0) { resourceBrickList.add(brick); } } return resourceBrickList; } > program to an interface, not to an implementation. Please use `List` instead of `ArrayList` everywhere. I'm just mentioning it here once.

Target:
public List<Brick> getBricksRequiringResources(int resource) { List<Brick> resourceBrickList = new ArrayList<Brick>(); for (Brick brick : brickList) { if ((brick.getRequiredResources() & resource) != 0) { resourceBrickList.add(brick); } } return resourceBrickList; }
Source:
public static ServerManager getInstance( final WorkspaceStatus wsStatus ) { if (instance == null) { instance = new ServerManager(); } START instance.setWorkspaceStatus(wsStatus); END return instance; } Should this line be moved up into the above block where the `ServerManager` instance is being created? And maybe just code it like `instance.wsStatus = wsStatus` and get rid of the `setWorkspaceStatus` method. I am assuming the status would only need to be set whenever the server variable is `null`. Is that true?

Target:
public static ServerManager getInstance( final WorkspaceStatus wsStatus ) { if (instance == null) { instance = new ServerManager(); instance.wsStatus = wsStatus; } return instance; }
Source:
public WebAccess addUserAgent(String userAgent) { START if (Objects.nonNull(userAgent)) END this.userAgent = userAgent; return this; } Meiner Meinung nach ist die Überprüfung überflüssig. ```userAgent``` darf null sein und es mag auch Fälle geben, wo ein Request *ohne* userAgent gemacht werden soll. Die Abfrage ```addUserAgent(null)``` ist m.E. ein gültiger Verwendung.

Target:
public WebAccess addUserAgent(String userAgent) { this.userAgent = userAgent; return this; }
Source:
START public void END setPromiscuousBinding(IBinding binding) { promiscuousBinding = binding; } Make final.

Target:
public final void setPromiscuousBinding(IBinding binding) { promiscuousBinding = binding; }
Source:
START public synchronized void clear() { END fZoom.setFullRange(0L, 0L); fZoom.setNewRange(0L, 0L); fZoom.stop(); super.clear(); } the null check is necessary because clear is called by the super class in the constructor.

Target:
public synchronized void clear() { if (fZoom != null) { fZoom.setFullRange(0L, 0L); fZoom.setNewRange(0L, 0L); fZoom.stop(); } super.clear(); }
Source:
public List<Object> getSortedObjects() { START Set<Object> sorted = newSetFromMap(new LinkedHashMap<>(objectCount)); END for (List<Object> bucket : buckets) { if (bucket != null) { sorted.addAll(bucket); } } return new ArrayList<>(sorted); } what's the point of doing this?

Target:
public List<Object> getSortedObjects() { List<Object> sorted = new ArrayList<>(objectCount); for (List<Object> bucket : buckets) { if (bucket != null) { sorted.addAll(bucket); } } return sorted; }
Source:
public void setOS(String os) { incrementSequenceNumber(); fOS = os; if (fRoot != null && os != null && START os.length() > 0) { END Element nlNode = TargetDefinitionDocumentTools.getChildElement(fRoot, TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.OS); nlNode.setTextContent(os); } else { removeElement(TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.OS); } } Please use !string.isEmpty().

Target:
public void setOS(String os) { incrementSequenceNumber(); fOS = os; if (fRoot != null && os != null && !os.isEmpty()) { Element nlNode = TargetDefinitionDocumentTools.getChildElement(fRoot, TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.OS); nlNode.setTextContent(os); } else { removeElement(TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.OS); } }
Source:
public ScriptEntryData getScriptEntryData() { return new BukkitScriptEntryData( hitBy.isPlayer() ? hitBy.getDenizenPlayer() : (entity.isPlayer() ? entity.getDenizenPlayer() : null), START END hitBy.isCitizensNPC() ? hitBy.getDenizenNPC() : (entity.isCitizensNPC() ? entity.getDenizenNPC() : null) ); } Stray doublenewline ^ Also the newlines on the individual parts I'm confused why this isn't formatted exactly the same as the EntityDamaged event, which I think is what you were referencing anyway? ```java return new BukkitScriptEntryData(damager != null && damager.isPlayer() ? damager.getDenizenPlayer() : entity.isPlayer() ? entity.getDenizenPlayer() : null, damager != null && damager.isCitizensNPC() ? damager.getDenizenNPC() : entity.isCitizensNPC() ? entity.getDenizenNPC() : null); ```

Target:
public ScriptEntryData getScriptEntryData() { return new BukkitScriptEntryData( hitBy.isPlayer() ? hitBy.getDenizenPlayer() : entity.isPlayer() ? entity.getDenizenPlayer() : null, hitBy.isCitizensNPC() ? hitBy.getDenizenNPC() : entity.isCitizensNPC() ? entity.getDenizenNPC() : null); }
Source:
public Void visit(Boolean inTailPosition, New newExpr) { for (Declaration decl : newExpr.getDecls()) { START decl.acceptVisitor(this, inTailPosition); END } return null; } This doesn't really matter because Val- and Var-Declaration pass "false" for inTailPosition, but it might be better conceptually to also pass "false" here.

Target:
public Void visit(Boolean inTailPosition, New newExpr) { for (Declaration decl : newExpr.getDecls()) { decl.acceptVisitor(this, false); } return null; }
Source:
public ReflectionMappers setColumnNameMatchers(List<ColumnNameMatcher> columnNameMatchers) { synchronized (lock) { this.columnNameMatchers.clear(); this.columnNameMatchers.addAll(columnNameMatchers); START } END return this; } What's the expected benefit for this change? This method is typically called at most once per VM--let's prioritize simplicity for low-traffic methods like this.

Target:
public ReflectionMappers setColumnNameMatchers(List<ColumnNameMatcher> columnNameMatchers) { this.columnNameMatchers = new ArrayList<>(columnNameMatchers); return this; }
Source:
private static MessageType getProjection(MessageType schema, Collection<SchemaPath> projectionColumns, List<SchemaPath> columnsNotFound) { projectionColumns = adaptColumnsToParquetSchema(projectionColumns, schema); List<SchemaPath> schemaColumns = getAllColumnsFrom(schema); Set<SchemaPath> selectedSchemaPaths = matchProjectionWithSchemaColumns(projectionColumns, schemaColumns, columnsNotFound); MessageType projection = convertSelectedColumnsToMessageType(schema, selectedSchemaPaths); START return projection; END } nit: `projection` variable may be avoided.

Target:
private static MessageType getProjection(MessageType schema, Collection<SchemaPath> projectionColumns, List<SchemaPath> columnsNotFound) { projectionColumns = adaptColumnsToParquetSchema(projectionColumns, schema); List<SchemaPath> schemaColumns = getAllColumnsFrom(schema); Set<SchemaPath> selectedSchemaPaths = matchProjectionWithSchemaColumns(projectionColumns, schemaColumns, columnsNotFound); return convertSelectedColumnsToMessageType(schema, selectedSchemaPaths); }
Source:
private FileObject ingestFileObject(ContentObject parent, Resource parentResc, Resource childResc) throws DepositException, IOException { if (skipResumed(childResc)) { START return null; END } // TODO add ACLs WorkObject work = (WorkObject) parent; FileObject obj = addFileToWork(work, childResc); // Add ingestion event for file object addIngestionEventForChild(obj); addPremisEvents(obj); // add MODS addDescription(work); // Increment the count of objects deposited addClicks(1); log.info("Created file object for deposit {}", obj.getPid(), getDepositPID()); return obj; } Can you remove the return types for ingest methods since they aren't being used now?

Target:
private void ingestFileObject(ContentObject parent, Resource parentResc, Resource childResc) throws DepositException, IOException { if (skipResumed(childResc)) { return; } // TODO add ACLs WorkObject work = (WorkObject) parent; FileObject obj = addFileToWork(work, childResc); // Add ingestion event for file object addIngestionEventForChild(obj); addPremisEvents(obj); // add MODS addDescription(obj); // Increment the count of objects deposited addClicks(1); log.info("Created file object for deposit {}", obj.getPid(), getDepositPID()); }
Source:
public int hashCode() { START return hash(getHost(), getPort(), getPassword(), getUsername(), getNonProxyHosts(), ntlmDomain); END } shouldn't this be `hash(super.hashCode, ntlmDomain)`... if you do it like this, any changes in the super class will break here.

Target:
public int hashCode() { return hash(super.hashCode(), ntlmDomain); }
Source:
public void subscribe(Subscriber<? super RecordsRetrieved> s) { subscriber = s; ++subscriptionTryCount; s.onSubscribe(new Subscription() { @Override public void request(long n) { START if (subscriptionTryCount == 1) { END } else { send(n); } } @Override public void cancel() { requested = 0; } }); } Would it be simpler to rewrite this block as just `if (subscriptionTryCount != 1)`?

Target:
public void subscribe(Subscriber<? super RecordsRetrieved> s) { subscriber = s; ++subscriptionTryCount; s.onSubscribe(new Subscription() { @Override public void request(long n) { if (subscriptionTryCount != 1) { send(n); } } @Override public void cancel() { requested = 0; } }); }
Source:
protected static boolean canAttachPrestartedVmToUser(Guid vmId) { // check that there isn't another user already attached to this VM: START boolean returnValue = !vmAssignedToUser(vmId, new java.util.ArrayList<String>()); END // Make sure the Vm is running stateless returnValue = returnValue && vmIsRunningStateless(vmId); return returnValue; } please remove the 'java.util.'

Target:
protected static boolean canAttachPrestartedVmToUser(Guid vmId) { // check that there isn't another user already attached to this VM // and make sure the Vm is running stateless return !vmAssignedToUser(vmId, new ArrayList<String>()) && vmIsRunningStateless(vmId); }
Source:
public void setInput(Object inputElement) { fInputElement = inputElement; ITimeGraphEntry[] input = fTimeGraphContentProvider.getElements(inputElement); synchronized (fListenerNotifierLock) { START fListenerNotifier = null; END } if (fTimeGraphCtrl != null) { setTimeRange(input); setTopIndex(0); fSelectionBegin = SWT.DEFAULT; fSelectionEnd = SWT.DEFAULT; fSelectedEntry = null; refreshAllData(input); } } The state of the reference is part of "this" object. The monitor of "fListenerNotifierLock" should be used to cover states in that object, not in "this". You could remove the synchronized block here, and extract to a local variable below.

Target:
public void setInput(Object inputElement) { fInputElement = inputElement; ITimeGraphEntry[] input = fTimeGraphContentProvider.getElements(inputElement); fListenerNotifier = null; if (fTimeGraphCtrl != null) { setTimeRange(input); setTopIndex(0); fSelectionBegin = SWT.DEFAULT; fSelectionEnd = SWT.DEFAULT; fSelectedEntry = null; refreshAllData(input); } }
Source:
public void onAttachOrDetach(AttachEvent event) { if (event.isAttached()) { index = 0; displayCurrent(); $(contents).on(TRANSITION_END, new Function() { @Override public void f() { START GQuery.console.log("TRANSITION_END"); END activeAnimation = false; $("[data-remove]", contents).remove(); } }); } else { $(contents).off(TRANSITION_END); } } You should remove console outputs for production

Target:
public void onAttachOrDetach(AttachEvent event) { if (event.isAttached()) { index = 0; displayCurrent(); $(contents).on(TRANSITION_END, new Function() { @Override public void f() { activeAnimation = false; $("[data-remove]", contents).remove(); } }); } else { $(contents).off(TRANSITION_END); } }
Source:
public int prepare(Xid xid) throws XAException { if (LOG.isTraceEnabled()) { START LOG.trace("DummyXAResource.prepare(xid=" + xid + ")"); END } return 0; } can be info

Target:
public int prepare(Xid xid) throws XAException { LOG.info("DummyXAResource.prepare(xid=" + xid + ")"); return 0; }
Source:
public void update(RuleBaseElementId name, String newCode) throws RuleBaseException { RuleBaseElement newBean = new RuleBaseElement(name, newCode); Map<String, String> metaData = newBean.toMetadata(); START RuleBaseConfiguration conf = new RuleBaseConfiguration(metaData, newBean); END try { rulePersistence.persist(conf); } catch (PersistenceException e) { throw new RuleBaseException(e); } builder.reloadPackage(name.getPackageName()); } Why not using here the Constructor where you only pass the RuleBaseElement?

Target:
public void update(RuleBaseElementId name, String newCode) throws RuleBaseException { RuleBaseElement newBean = new RuleBaseElement(name, newCode); RuleBaseConfiguration conf = new RuleBaseConfiguration(newBean); try { rulePersistence.persist(conf); } catch (PersistenceException e) { throw new RuleBaseException(e); } builder.reloadPackage(name.getPackageName()); }
Source:
@Override public Pair<SqlNode, RelDataType> validateAndGetType(SqlNode sqlNode) throws ValidationException { START final SqlNode validatedNode = this.validate(sqlNode); END final RelDataType type = m_validator.getValidatedNodeType(validatedNode); return Pair.of(validatedNode, type); } superfluous `this`

Target:
@Override public Pair<SqlNode, RelDataType> validateAndGetType(SqlNode sqlNode) throws ValidationException { final SqlNode validatedNode = validate(sqlNode); final RelDataType type = m_validator.getValidatedNodeType(validatedNode); return Pair.of(validatedNode, type); }
Source:
public Object inject(Object instance) throws InjectionProviderException { START return instance; END } I think this should just return null, similar to the default MyFaces implementation of InjectionProvider.

Target:
public Object inject(Object instance) throws InjectionProviderException { return null; }
Source:
private void validateVnicMappings(Action action) { START if (!(action.isSetVnicProfileMappings() && action.getVnicProfileMappings().isSetVnicProfileMappings())) { return; } action.getVnicProfileMappings().getVnicProfileMappings().forEach(this::validateVnicProfileMapping); END } please negate condition and move #121 into the 'then-clause'

Target:
private void validateVnicMappings(Action action) { if (action.isSetVnicProfileMappings() && action.getVnicProfileMappings().isSetVnicProfileMappings()) { action.getVnicProfileMappings().getVnicProfileMappings().forEach(this::validateVnicProfileMapping); } }
Source:
public Drawable getDrawable(Context context) { final PackageManager packageManager = context.getPackageManager(); Resources resources; try { START if (shortcutPojo.icon != null) { END return new BitmapDrawable(shortcutPojo.icon); } resources = packageManager.getResourcesForApplication(shortcutPojo.packageName); final int id = resources.getIdentifier(shortcutPojo.resourceName, null, null); return resources.getDrawable(id); } catch (NameNotFoundException e) { } return null; } you can try this from outside the try catch, before getting an instance to the packagemanager

Target:
public Drawable getDrawable(Context context) { final PackageManager packageManager = context.getPackageManager(); Resources resources; if (shortcutPojo.icon != null) { return new BitmapDrawable(shortcutPojo.icon); } try { resources = packageManager.getResourcesForApplication(shortcutPojo.packageName); final int id = resources.getIdentifier(shortcutPojo.resourceName, null, null); return resources.getDrawable(id); } catch (NameNotFoundException e) { } return null; }
Source:
protected boolean handlePreloadPackage(String packagePath, String libsPath) { START Log.d(TAG, "Preload package ********************************************************"); Log.d(TAG, "WebView package = " + packagePath); END return false; } Dianne will tell you to remove this. This is logspam.

Target:
protected boolean handlePreloadPackage(String packagePath, String libsPath) { // TODO: Use preload information to setup the ClassLoader. return false; }
Source:
public boolean equals(Object o) { Grant grant = (Grant) o; START if (!group.equals(grant.group)) return false; END if (!pattern.equals(grant.pattern)) return false; return true; } Style-nit: We don't cuddle onto the same line. But really isn't this shorter? Grant grant = (Grant)o; return group.equals(grant.group) && pattern.equals(grant.pattern);

Target:
public boolean equals(Object o) { Grant grant = (Grant) o; return group.equals(grant.group) && pattern.equals(grant.pattern); }
Source:
public void onValueChanged(final Consumer<Event> onValueChanged) { input.onkeyup = null; START input.onkeyup = event -> { END onValueChanged.accept(event); return this; }; } Is this two step handler change needed to avoid some memory leak? Isn't enough just to assign new value?

Target:
public void onValueChanged(final Consumer<Event> onValueChanged) { input.onkeyup = event -> { onValueChanged.accept(event); return this; }; }
Source:
public boolean isEntryRemovedInContext(Object key) { START throw new CacheException("This context is immutable"); END } So if the context is immutable why not just return false?

Target:
public boolean isEntryRemovedInContext(Object key) { return false; }
Source:
protected ITmfTreeColumnDataProvider getColumnDataProvider() { return () START -> { return ImmutableList.of( createColumn(Messages.AbstractSegmentStoreScatterView_Type, Comparator.comparing(TmfGenericTreeEntry::getName)), new TmfTreeColumnData(Messages.AbstractSegmentStoreScatterView_Legend)); }; END } remove curly braces

Target:
protected ITmfTreeColumnDataProvider getColumnDataProvider() { return () -> ImmutableList.of( createColumn(Messages.AbstractSegmentStoreScatterView_Type, Comparator.comparing(TmfGenericTreeEntry::getName)), new TmfTreeColumnData(Messages.AbstractSegmentStoreScatterView_Legend)); }
Source:
public void buttonStateChanged(VRControllerState_t stateBefore, VRControllerState_t stateAfter, int handIndex) { cachedStateBefore = stateBefore; cachedStateAfter = stateAfter; START queuedActions.add(new ControllerAction(InputType.CONTROLLER_BUTTON.getInput(ControllerId.X_AXIS), END "OpenVR", ButtonState.DOWN, 1.0f)); if (handIndex == 0) { handleController0(); } else { handleController1(); } } This seems odd here. What is this for?

Target:
public void buttonStateChanged(VRControllerState_t stateBefore, VRControllerState_t stateAfter, int handIndex) { cachedStateBefore = stateBefore; cachedStateAfter = stateAfter; if (handIndex == 0) { handleController0(); } else { handleController1(); } }
Source:
protected void cancelled() { logger.debug("Subscriber cancelled, ignoring the rest of the body"); try { future.done(); } catch (Exception t) { // Never propagate exception once we know we are done. logger.error(t.getMessage(), t); } // The subscriber cancelled early - this channel is dead and should be closed. channelManager.releaseChannelLock(future.getPartitionKey()); channelManager.closeChannel(channel); START channel.pipeline().remove(StreamedResponsePublisher.class); END } Now that we close the channel, I think it's useless to remove the publisher from the pipeline. The channel will be garbage collected.

Target:
protected void cancelled() { logger.debug("Subscriber cancelled, ignoring the rest of the body"); try { future.done(); } catch (Exception t) { // Never propagate exception once we know we are done. logger.debug(t.getMessage(), t); } // The subscriber cancelled early - this channel is dead and should be closed. channelManager.closeChannel(channel); }
Source:
public static List<String> getAuthenticatedUserRoles(IdentityProvider identityProvider) { START List<String> roles = identityProvider.getRoles(); END if (roles == null || roles.isEmpty()) { roles = new ArrayList<>(); roles.add(""); } return roles; } There should be a null check on the identityProvider, prior to calling its getRoles method. Maybe something like... `List<String> roles = (identityProvider != null) ? identityProvider.getRoles():null;`

Target:
public static List<String> getAuthenticatedUserRoles(IdentityProvider identityProvider) { List<String> roles = identityProvider != null ? identityProvider.getRoles() : new ArrayList<>(); if (roles == null || roles.isEmpty()) { roles = new ArrayList<>(); roles.add(""); } return roles; }
Source:
public void initializeDataSource(ITmfTrace trace) { TmfAbstractAnalysisModule module = createStatisticsAnalysiModule(); START if (!(module instanceof AbstractSegmentStatisticsAnalysis)) { END // null or not a segment analysis module return; } try { module.setTrace(trace); module.schedule(); if (fModule != null) { fModule.dispose(); } fModule = (AbstractSegmentStatisticsAnalysis) module; } catch (TmfAnalysisException e) { Activator.getDefault().logError("Error initializing statistics analysis module", e); //$NON-NLS-1$ } } legacy extensions might not use abstractSegmentStatisticsAnalysis

Target:
public void initializeDataSource(ITmfTrace trace) { TmfAbstractAnalysisModule module = createStatisticsAnalysiModule(); if (module == null) { return; } try { module.setTrace(trace); module.schedule(); if (fModule != null) { fModule.dispose(); } fModule = module; } catch (TmfAnalysisException e) { Activator.getDefault().logError("Error initializing statistics analysis module", e); //$NON-NLS-1$ } }
Source:
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Bundle extras = intent.getExtras(); if (ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { if (extras != null) { START dispatchAirplaneModeChange(extras.getBoolean(EXTRA_AIRPLANE_STATE, false)); END } } else if (CONNECTIVITY_ACTION.equals(action)) { dispatchNetworkStateChange(connectivityManager.getActiveNetworkInfo()); } } formatting here is off.

Target:
@Override public void onReceive(Context context, Intent intent) { // On some versions of Android this may be called with a null Intent if (null == intent) { return; } String action = intent.getAction(); Bundle extras = intent.getExtras(); if (ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { dispatchAirplaneModeChange(extras.getBoolean(EXTRA_AIRPLANE_STATE, false)); } else if (CONNECTIVITY_ACTION.equals(action)) { dispatchNetworkStateChange(connectivityManager.getActiveNetworkInfo()); } }
Source:
public void onDelete(@NonNull ReadingList readingList) { showDeleteListUndoSnackbar(readingList); ReadingList.DAO.removeList(readingList); funnel.logDeleteList(readingList, readingLists.size()); updateLists(); START if (callback() != null) { END callback().onReadingListModified(); } } Instead of adding a callback, consider using a ContentObserver wherever changes must be observed (I think SavePageSyncService does this?). This likely allow you to remove the tab change logic as well.

Target:
public void onDelete(@NonNull ReadingList readingList) { showDeleteListUndoSnackbar(readingList); ReadingList.DAO.removeList(readingList); funnel.logDeleteList(readingList, readingLists.size()); updateLists(); }
Source:
START public RelationTypeSchemaDescriptor( int relTypeId, int... propertyIds ) END { this.relTypeId = relTypeId; this.propertyIds = propertyIds; } I'm pretty certain there is a factory for making these, no public constructor required. (Took a lot of refactoring to achieve that, let's uphold the flag.)

Target:
RelationTypeSchemaDescriptor( int relTypeId, int... propertyIds ) { this.relTypeId = relTypeId; this.propertyIds = propertyIds; }
Source:
public Map<String, Object> introspect(String token) { START TokenIntrospectionSuccessResponse response = Optional.of(this.requestEntityConverter.convert(token)) END .map(this::makeRequest) .map(this::adaptToNimbusResponse) .map(this::parseNimbusResponse) .map(this::castToNimbusSuccess) // relying solely on the authorization server to validate this token (not checking 'exp', for example) .filter(TokenIntrospectionSuccessResponse::isActive) .orElseThrow(() -> new OAuth2IntrospectionException("Provided token [" + token + "] isn't active")); return convertClaimsSet(response); } What would you think of ```suggestion TokenIntrospectionSuccessResponse response = Optional.of(token) .map(this.requestEntityConverter::convert) ```

Target:
public Map<String, Object> introspect(String token) { TokenIntrospectionSuccessResponse response = Optional.of(token) .map(this.requestEntityConverter::convert) .map(this::makeRequest) .map(this::adaptToNimbusResponse) .map(this::parseNimbusResponse) .map(this::castToNimbusSuccess) // relying solely on the authorization server to validate this token (not checking 'exp', for example) .filter(TokenIntrospectionSuccessResponse::isActive) .orElseThrow(() -> new OAuth2IntrospectionException("Provided token [" + token + "] isn't active")); return convertClaimsSet(response); }
Source:
private boolean isColdReboot() { boolean coldReboot = (getVm().isRunOnce() && START !getVm().isVolatileRun()) END || getVm().isNextRunConfigurationExists(); log.info("VM '{}' is performing reboot; run once: '{}', running as volatile: '{}', has next run configuration: '{}'", getVm().getName(), coldReboot ? "cold" : "warm", getVm().isRunOnce(), getVm().isVolatileRun(), getVm().isNextRunConfigurationExists()); return coldReboot; } shouldn't we perform cold reboot for volatile runs?

Target:
private boolean isColdReboot() { boolean coldReboot = (getVm().isRunOnce() && getVm().isVolatileRun()) || getVm().isNextRunConfigurationExists(); log.info("VM '{}' is performing reboot; run once: '{}', running as volatile: '{}', has next run configuration: '{}'", getVm().getName(), coldReboot ? "cold" : "warm", getVm().isRunOnce(), getVm().isVolatileRun(), getVm().isNextRunConfigurationExists()); return coldReboot; }
Source:
public void updateVisibility() { super.updateVisibility(); messageLabel.setVisible(false); START subnetTab.setVisible(exportEditor.asCheckBox().getValue()); END } Again, I don't understand why this is needed? Isn't it the same thing that happens in AbstractNetworkPopupPresenterWidget?

Target:
public void updateVisibility() { super.updateVisibility(); messageLabel.setVisible(false); }
Source:
protected void executeVdsBrokerCommand() { START _result = getBroker().getStorageDomainStats(getParameters().getStorageDomainId().toString()); END proceedProxyReturnValue(); StorageDomain domain = buildStorageDynamicFromXmlRpcStruct(_result.storageStats); domain.setId(getParameters().getStorageDomainId()); setReturnValue(domain); } Could you please rename also _result?

Target:
protected void executeVdsBrokerCommand() { result = getBroker().getStorageDomainStats(getParameters().getStorageDomainId().toString()); proceedProxyReturnValue(); StorageDomain domain = buildStorageDynamicFromXmlRpcStruct(result.storageStats); domain.setId(getParameters().getStorageDomainId()); setReturnValue(domain); }
Source:
START Boolean canEditColumns() { END final String permission = WorkbenchFeatures.GUIDED_DECISION_TABLE_EDIT_COLUMNS; final User user = sessionInfo.getIdentity(); return authorizationManager.authorize(permission, user); } ```Boolean``` for a reason (vs ```boolean```)? Just asking.. Use of ```Boolean``` in my mind always makes me think this is a tri-value ```boolean``` (```true```, ```false```, ```null```)..

Target:
boolean canEditColumns() { final String permission = WorkbenchFeatures.GUIDED_DECISION_TABLE_EDIT_COLUMNS; final User user = sessionInfo.getIdentity(); return authorizationManager.authorize(permission, user); }
Source:
public CommandCallback getCallback() { START return isCinderDisksExist() ? null : new ConcurrentChildCommandsExecutionCallback(); END } This is a bug, if cinder disks exists return the call back (not null). Also use the parameter you have added in the previous patch

Target:
public CommandCallback getCallback() { return isCinderDisksExist() ? new ConcurrentChildCommandsExecutionCallback() : null; }
Source:
private Config loadHazelcastConfig(GeoServerResourceLoader rl) throws IOException{ Resource hzf = getConfigFile(HAZELCAST_FILENAME, HzCluster.class); InputStream hzIn = hzf.in(); try { return new XmlConfigBuilder(hzIn).build(); } finally { hzIn.close(); START } END } @NielsCharlier try-with-resources?

Target:
private Config loadHazelcastConfig(GeoServerResourceLoader rl) throws IOException{ Resource hzf = getConfigFile(HAZELCAST_FILENAME, HzCluster.class); try (InputStream hzIn = hzf.in()) { return new XmlConfigBuilder(hzIn).build(); } }
Source:
public void testDeserialize() throws Exception { String data = getFixture("/v1/accounts/acct_123"); Account resource = APIResource.GSON.fromJson(data, Account.class); assertNotNull(resource); START assertNotNull(resource.getId()); END } we likely want specific edge-case as fixtures to ensure deserialization works as needed.

Target:
public void testDeserialize() throws Exception { final String data = getFixture("/v1/accounts/acct_123"); final Account resource = APIResource.GSON.fromJson(data, Account.class); assertNotNull(resource); assertNotNull(resource.getId()); }
Source:
public VdcQueryParametersBase(String sessionId) { START this.sessionId = sessionId; END refresh = true; } Why not flip this around, have the constructor with the sessionId call the constructor without the parameter? That way you don't have to pass null into the constructor. Functionally it makes no difference, just reads a little nicer IMO.

Target:
public VdcQueryParametersBase(String sessionId) { this(); this.sessionId = sessionId; }