auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private ContentValues ensureAfter() { ContentValues values = mAfterContentValues; if (values == null) { values = new ContentValues(); mAfterContentValues = values; // also create mAfterKeys START mAfterKeys = new HashSet<>(); END } return values; } Please remove `mAfterKeys` while you're at it. It was only a workaround for the absence of `ContentValues.keySet()` on Android 2.x. Since we don't support Android 2 any more you can remove it in most places and replace by `mAfterContentValues.keySet()` where it's being read.

Target:
private ContentValues ensureAfter() { ContentValues values = mAfterContentValues; if (values == null) { values = new ContentValues(); mAfterContentValues = values; } return values; }
Source:
private Task<? extends Serializable> createDbTask(Database dbObj) { // note that we do not set location - for repl load, we want that auto-created. CreateDatabaseDesc createDbDesc = new CreateDatabaseDesc(dbObj.getName(), dbObj.getDescription(), null, false, START updateDbProps(dbObj, context.dumpDirectory, true)); END // If it exists, we want this to be an error condition. Repl Load is not intended to replace a // db. // TODO: we might revisit this in create-drop-recreate cases, needs some thinking on. DDLWork2 work = new DDLWork2(new HashSet<>(), new HashSet<>(), createDbDesc); return TaskFactory.get(work, context.hiveConf); } The parameter can bee removed

Target:
private Task<? extends Serializable> createDbTask(Database dbObj) { // note that we do not set location - for repl load, we want that auto-created. CreateDatabaseDesc createDbDesc = new CreateDatabaseDesc(dbObj.getName(), dbObj.getDescription(), null, false, updateDbProps(dbObj, context.dumpDirectory)); // If it exists, we want this to be an error condition. Repl Load is not intended to replace a // db. // TODO: we might revisit this in create-drop-recreate cases, needs some thinking on. DDLWork2 work = new DDLWork2(new HashSet<>(), new HashSet<>(), createDbDesc); return TaskFactory.get(work, context.hiveConf); }
Source:
public long writeTo(Write writeChannel) throws IOException { long sizeWritten = 0; ReadableByteChannel readableByteChannel = Channels.newChannel(streamToWrite); sizeWritten = writeChannel.appendFrom(readableByteChannel, sizeToWrite); if(sizeWritten != sizeToWrite) { throw new IOException("Not able to write fully. Expected : " + sizeToWrite + " Actual : " + sizeWritten ); } START return sizeWritten; END } what is the purpose of maxWriteTimeInMs now? how is it being used?

Target:
public long writeTo(Write writeChannel) throws IOException { ReadableByteChannel readableByteChannel = Channels.newChannel(streamToWrite); writeChannel.appendFrom(readableByteChannel, sizeToWrite); return sizeToWrite; }
Source:
static void addSnapshotJarToClassPath( File jarFile, Path intermediateClassPath, FileSystem fs, Job job ) throws IOException { // Snapshot jars are uploaded to non shared intermediate directory. final Path hdfsPath = new Path(intermediateClassPath, jarFile.getName()); // existing is used to prevent uploading file multiple times in same run. START if (!existing.contains(hdfsPath) || !fs.exists(hdfsPath)) { END uploadJar(jarFile, hdfsPath, fs); existing.add(hdfsPath); } job.addFileToClassPath(hdfsPath); } exists check is not done for SNAPSHOT jars intentionally so that they get updated everytime. SNAPSHOT jars are to be used for testing only and are designed to get updated on each run. Or else there would be no reason for method 'addSnapshotJarToClassPath' to exist. i guess your failure is a result of running concurrent jobs with SNAPSHOT jars.

Target:
static void addSnapshotJarToClassPath( File jarFile, Path intermediateClassPath, FileSystem fs, Job job ) throws IOException { // Snapshot jars are uploaded to non shared intermediate directory. final Path hdfsPath = new Path(intermediateClassPath, jarFile.getName()); // Prevent uploading same file multiple times in same run. if (!fs.exists(hdfsPath)) { uploadJar(jarFile, hdfsPath, fs); } job.addFileToClassPath(hdfsPath); }
Source:
public void start(ComponentContext context) { super.start(context); configs.forEach(this::createStreamIfNotExists); processorDescriptors.forEach(this::initProcessor); if (! componentListenerAdded) { // this must be done only once while start method can be called multiple time on hot reload Framework.getRuntime().getComponentManager().addListener(new ComponentsLifeCycleListener()); START componentListenerAdded = true; END } } It's better to make the listener unregister itself at stop time instead of storing a boolean. See for instance `WorkManagerImpl.init` and the implementation of `afterStop`.

Target:
public void start(ComponentContext context) { super.start(context); configs.forEach(this::createStreamIfNotExists); processorDescriptors.forEach(this::initProcessor); Framework.getRuntime().getComponentManager().addListener(new ComponentsLifeCycleListener()); }
Source:
public void reportTaskStatus(int id, Task.TaskStatus status, long miliseconds) throws JMSException { TextMessage message = session.createTextMessage("task:" + propertiesBean.getProperty("engine.unique.id") + ":" + id + ":" + status + ":" + miliseconds); producer.send(message, DeliveryMode.PERSISTENT, 6, 0); START log.debug("[{}] Task state sent to dispatcher.", id, status); END } Please keep it in info level.

Target:
public void reportTaskStatus(int id, Task.TaskStatus status, long miliseconds) throws JMSException { TextMessage message = session.createTextMessage("task:" + propertiesBean.getProperty("engine.unique.id") + ":" + id + ":" + status + ":" + miliseconds); producer.send(message, DeliveryMode.PERSISTENT, 6, 0); log.info("[{}] Task state sent to dispatcher.", id, status); }
Source:
public final BeanMetaData<T> getCurrentBeanMetaData() { START if ( currentBeanType != null && currentBeanMetaData == null ) { END currentBeanMetaData = beanMetaDataManager.getBeanMetaData( currentBeanType ); } return currentBeanMetaData; } Why is it done lazily? Seems we'll need it in any case?

Target:
public final BeanMetaData<T> getCurrentBeanMetaData() { return currentBeanMetaData; }
Source:
protected Object handleObjectGet() throws Exception { String workspace = getAttribute("workspace"); ServiceInfo service; if (workspace != null) { WorkspaceInfo ws = geoServer.getCatalog().getWorkspaceByName(workspace); service = geoServer.getService(ws, clazz); } else { service = geoServer.getService(clazz); } if (service == null) { throw new RestletException("Service for workspace " + workspace + " does not exist", Status.CLIENT_ERROR_NOT_FOUND); } START return service.clone(true); END } Given this is configuration, wouldn't it make more sense to show the parameters in the output, accept them in input, and then fix validation like it's done in the UI?

Target:
protected Object handleObjectGet() throws Exception { String workspace = getAttribute("workspace"); ServiceInfo service; if (workspace != null) { WorkspaceInfo ws = geoServer.getCatalog().getWorkspaceByName(workspace); service = geoServer.getService(ws, clazz); } else { service = geoServer.getService(clazz); } if (service == null) { throw new RestletException("Service for workspace " + workspace + " does not exist", Status.CLIENT_ERROR_NOT_FOUND); } return service; }
Source:
private String buildHashedPayload(HttpRequest request) { String hashedPayload = ""; try { byte[] unhashedBytes = request.getPayload() == null ? "".getBytes() : ByteStreams.toByteArray(request .getPayload().getInput()); START hashedPayload = sha256(unhashedBytes); END } catch (IOException e) { throw new HttpException("Error signing request", e); } return hashedPayload; } Return the result of `sha256` instead of using the local variable.

Target:
private static String buildHashedPayload(HttpRequest request) { try { byte[] unhashedBytes = request.getPayload() == null ? "".getBytes() : ByteStreams.toByteArray(request .getPayload().getInput()); return sha256(unhashedBytes); } catch (IOException e) { throw new HttpException("Error signing request", e); } }
Source:
public Map<Long, EventDefinition> getEventDefs(StreamInput id) { START return null; END } It's a little harsh to return null because the deprecated method should work as the original implementation, right? Can't this method read the StreamInputReader and get the information from there?

Target:
public Map<Long, EventDefinition> getEventDefs(StreamInput id) { return new HashMap<Long, EventDefinition>(); }
Source:
public void testSetTitleIconStartMargin() throws Throwable { int startMargin = 100; int navIconWidth = 100; mActivityRule.runOnUiThread(() -> { mToolbar.setNavigationIconContainerWidth(navIconWidth); mToolbar.setTitleIcon(android.R.drawable.sym_def_app_icon); mToolbar.setTitleIconStartMargin(startMargin); }); START InstrumentationRegistry.getInstrumentation().waitForIdleSync(); END onView(withId(R.id.title_icon)).check(matches(withLeft(navIconWidth + startMargin))); } You don't need this. onView() will wait

Target:
public void testSetTitleIconStartMargin() throws Throwable { int startMargin = 100; int navIconWidth = 100; mActivityRule.runOnUiThread(() -> { mToolbar.setNavigationIconContainerWidth(navIconWidth); mToolbar.setTitleIcon(android.R.drawable.sym_def_app_icon); mToolbar.setTitleIconStartMargin(startMargin); }); onView(withId(R.id.title_icon)).check(matches(withLeft(navIconWidth + startMargin))); }
Source:
Publisher<CoreEvent> getDownstreamPublisher() { return downstreamFlux START .compose(downstreamPublisher -> Mono.subscriberContext() END .flatMapMany(downstreamContext -> downstreamPublisher.doOnSubscribe(s -> { innerFlux.subscriberContext(downstreamContext).subscribe(); upstreamFlux.subscriberContext(downstreamContext).subscribe(); }))); } static import

Target:
Publisher<CoreEvent> getDownstreamPublisher() { return downstreamFlux .compose(downstreamPublisher -> subscriberContext() .flatMapMany(downstreamContext -> downstreamPublisher.doOnSubscribe(s -> { innerFlux.subscriberContext(downstreamContext).subscribe(); upstreamFlux.subscriberContext(downstreamContext).subscribe(); }))); }
Source:
public void onFailure(Throwable t) { log.error("Unable to RefreshCapabilities: {}", ExceptionUtils.getRootCauseMessage(t)); log.debug("Exception", t); START postProcessRefresh(false, releaseLock.getAndSet(false)); END } This change may cause the lock not to be released in some cases. With this change, in case of a failure VdsManager is responsible for releasing the lock. The VdsManager releases the lock only in case it catches an immediate exception. In case of a time-out or other SetupNetworks vdsm failure, the lock will never be unlocked.

Target:
public void onFailure(Throwable t) { log.error("Unable to RefreshCapabilities: {}", ExceptionUtils.getRootCauseMessage(t)); log.debug("Exception", t); postProcessRefresh(false); }
Source:
public CountsComputer( long lastCommittedTransactionId, NodeStore nodes, RelationshipStore relationships, int highLabelId, int highRelationshipTypeId ) { this( lastCommittedTransactionId, nodes, relationships, highLabelId, highRelationshipTypeId, START new SilentMigrationProgressMonitor().NO_OP_SECTION ); END } There is no reason to create new instance if SilentMigrationProgressMonitor here since NO_OP_SECTION is static

Target:
public CountsComputer( long lastCommittedTransactionId, NodeStore nodes, RelationshipStore relationships, int highLabelId, int highRelationshipTypeId ) { this( lastCommittedTransactionId, nodes, relationships, highLabelId, highRelationshipTypeId, SilentMigrationProgressMonitor.NO_OP_SECTION ); }
Source:
public ArrayLiteralTreeImpl newArrayLiteralWithElidedElements(List<InternalSyntaxToken> commaTokens) { List<Tree> commas = Lists.newArrayList(); for (InternalSyntaxToken comma : commaTokens) { commas.add(comma); } START return new ArrayLiteralTreeImpl(commas); END } @vilchik-elena can't we directly use commaTokens?

Target:
public ArrayLiteralTreeImpl newArrayLiteralWithElidedElements(List<InternalSyntaxToken> commaTokens) { return new ArrayLiteralTreeImpl(new ArrayList<Tree>(commaTokens)); }
Source:
public void onSuccess() { log.debug("Command succeeded, releasing macs {}.", START Arrays.toString(super.macs.toArray())); END releaseMacs(); } why not to rely on AbstractCollection..toString?

Target:
public void onSuccess() { log.debug("Command succeeded, releasing macs {}.", super.macs); releaseMacs(); }
Source:
START SubresourceParameter(String value) { END super("t", value); } Make the constructor public

Target:
public SubresourceParameter(String value) { super("t", value); }
Source:
private boolean isExpired(long expirationTimeInMs, long referenceTimeInMs) { START return expirationTimeInMs < referenceTimeInMs && expirationTimeInMs != Utils.Infinite_Time; END } flip the order of the checks - more intuitive IMO. Something like saying "time is valid and is less than" rather than "time is less than and valid"

Target:
private boolean isExpired(long expirationTimeInMs, long referenceTimeInMs) { return expirationTimeInMs != Utils.Infinite_Time && expirationTimeInMs < referenceTimeInMs; }
Source:
public void testEncodeSpatial() throws Exception { Document doc = encode(FilterMockData.intersects(), FES.Filter); assertEquals("fes:Filter", doc.getDocumentElement().getNodeName()); Element e = getElementByQName(doc, FES.Intersects); assertNotNull(e); START print(e); END assertNotNull(getElementByQName(e, FES.ValueReference)); assertNotNull(getElementByQName(e, GML.Point)); } Please do not print to stdout/stderr. Please log instead so output can be silenced by the build infrastructure.

Target:
public void testEncodeSpatial() throws Exception { Document doc = encode(FilterMockData.intersects(), FES.Filter); assertEquals("fes:Filter", doc.getDocumentElement().getNodeName()); Element e = getElementByQName(doc, FES.Intersects); assertNotNull(e); assertNotNull(getElementByQName(e, FES.ValueReference)); assertNotNull(getElementByQName(e, GML.Point)); }
Source:
public View getTopContainer(final View view) { View topView = null; START EObject container; END if (view != null) { container = view.eContainer(); if (isStereotypeCompartment(container) || isStereotypeBrace(container) || isStereotypeLabel(container)) { container = container.eContainer(); } if (container instanceof View) { topView = (View) container; } } return topView; } The local variable is declared in bad scope.

Target:
public View getTopContainer(final View view) { View topView = null; if (view != null) { EObject container = view.eContainer(); if (isStereotypeCompartment(container) || isStereotypeBrace(container) || isStereotypeLabel(container)) { container = container.eContainer(); } if (container instanceof View) { topView = (View) container; } } return topView; }
Source:
public StreamDeployer(ZooKeeperConnection zkConnection, StreamDefinitionRepository repository, StreamRepository streamRepository, XDParser parser) { super(zkConnection, repository, streamRepository, parser, stream); this.zkConnection = zkConnection; this.parser = parser; START updateModuleDefinitions(); END } I don't think this method should be called in a constructor.

Target:
public StreamDeployer(ZooKeeperConnection zkConnection, StreamDefinitionRepository repository, StreamRepository streamRepository, XDParser parser) { super(zkConnection, repository, streamRepository, parser, stream); this.zkConnection = zkConnection; this.parser = parser; }
Source:
public String toString() { Object oScope = scope; Object oKey = key; START if (oScope instanceof MarshalledValue) { END oScope = ((MarshalledValue) oScope).get(); } if (oKey instanceof MarshalledValue) { oKey = ((MarshalledValue) oKey).get(); } return "ScopedKey{scope = " + oScope + ", key = " + oKey + "}"; } Is this really necessary? AFAIK the scope and key should never be MarshalledValues.

Target:
public String toString() { return "ScopedKey{scope = " + scope + ", key = " + key + "}"; }
Source:
static String left(String str, int len) { START if (str == null || str.isEmpty() || len == 0) { END return ""; } if (len > 0) { return str.substring(0, Math.min(len, str.length())); } final int finalLen = str.length() + len; return finalLen > 0 ? str.substring(0, finalLen) : ""; } `str == null` cannot be true here as this was already checked upfront by https://github.com/crate/crate/pull/8879/files#diff-7a2324ee3f0c0f2c921e7ffeb1740058R70 (it also correctly results in `null` there). We could also move this empty string or 0 length up under that check as it would be same for both functions.

Target:
private static String left(String str, int len) { if (len > 0) { return str.substring(0, Math.min(len, str.length())); } final int finalLen = str.length() + len; return finalLen > 0 ? str.substring(0, finalLen) : ""; }
Source:
public ResponseEntity addRole(@RequestBody @Validated RoleForm roleForm, BindingResult bindingResult, @RequestHeader(HttpHeaders.ACCEPT) String acceptHeader) { START if (roleForm == null) END { throw new RequestBodyValidationException("Empty request body", bindingResult); } if (bindingResult.hasErrors()) { throw new RequestBodyValidationException(FAILED_ADD_ROLE, bindingResult); } // Convert RoleForm to Role Role role = conversionService.convert(roleForm, Role.class); return processConfig(config -> addRole(config, role), () -> SUCCESSFUL_ADD_ROLE, acceptHeader); } It should never happen, since `org.springframework.web.bind.annotation.RequestBody#required` is `default true`

Target:
public ResponseEntity addRole(@RequestBody @Validated RoleForm roleForm, BindingResult bindingResult, @RequestHeader(HttpHeaders.ACCEPT) String acceptHeader) { if (bindingResult.hasErrors()) { throw new RequestBodyValidationException(FAILED_ADD_ROLE, bindingResult); } Role role = conversionService.convert(roleForm, Role.class); return processConfig(config -> addRole(config, role), () -> SUCCESSFUL_ADD_ROLE, acceptHeader); }
Source:
START public AbstractJsonGetter(Getter parent) { END super(parent); } Minor: you can decrease the visibility modifier for some methods here and change some methods to be static.

Target:
AbstractJsonGetter(Getter parent) { super(parent); }
Source:
NumaValidator(VdsNumaNodeDao vdsNumaNodeDao) { Objects.requireNonNull(vdsNumaNodeDao); START this.vdsNumaNodeDao = vdsNumaNodeDao; END } how about this.vdsNumaNodeDao = Objects.requireNonNull(vdsNumaNodeDao) ?

Target:
NumaValidator(VdsNumaNodeDao vdsNumaNodeDao) { this.vdsNumaNodeDao = Objects.requireNonNull(vdsNumaNodeDao); }
Source:
public List<ClientModel> getClients() { START return session.realms().getClients(this, 0, session.realms().getClientsCount(this).intValue()); END } getClients(this, null, null)

Target:
public List<ClientModel> getClients() { return session.realms().getClients(this); }
Source:
public List<String> getTokens() { ArrayList<String> ret = new ArrayList<>(this.tokenCount); START END for (int i = 0; i < this.tokenCount; i++) { ret.add(getToken(i)); } return ret; } Coding best practices: Interface i = new Implementation();

Target:
public List<String> getTokens() { List<String> ret = new ArrayList<String>(tokenCount); for (int i = 0; i < tokenCount; i++) { ret.add(getToken(i)); } return ret; }
Source:
public EndpointAffinity(final DrillbitEndpoint endpoint, final double affinity, final boolean mandatory, final int maxWidth) { Preconditions.checkArgument(maxWidth >= 1, "MaxWidth for given endpoint should be at least one."); this.endpoint = endpoint; this.affinity = affinity; this.mandatory = mandatory; this.maxWidth = maxWidth; START this.numLocalWorkUnits = 0; END } Not needed. By default it will always be initialized to 0

Target:
public EndpointAffinity(final DrillbitEndpoint endpoint, final double affinity, final boolean mandatory, final int maxWidth) { Preconditions.checkArgument(maxWidth >= 1, "MaxWidth for given endpoint should be at least one."); this.endpoint = endpoint; this.affinity = affinity; this.mandatory = mandatory; this.maxWidth = maxWidth; }
Source:
public void run() { START LOG.trace("BacklogMetricEmitter running for entities"); END executor = new ScheduledThreadPoolExecutor(10); List<Future> futures = new ArrayList<>(); try { for (Entity entity : entityBacklogs.keySet()) { futures.add(executor.submit(new BacklogCalcService(entity, entityBacklogs.get(entity)))); } waitForFuturesToComplete(futures); } finally { executor.shutdown(); } } Intentional change. Keep the originial.

Target:
public void run() { LOG.debug("BacklogMetricEmitter running for entities"); executor = new ScheduledThreadPoolExecutor(10); List<Future> futures = new ArrayList<>(); try { for (Entity entity : entityBacklogs.keySet()) { futures.add(executor.submit(new BacklogCalcService(entity, entityBacklogs.get(entity)))); } waitForFuturesToComplete(futures); } finally { executor.shutdown(); } }
Source:
public void onBackPressed() { if (projectListFragment != null) { projectListFragment.cancelLoadProjectTask(); Log.d(TAG, "Back press detected!"); START } END super.onBackPressed(); } projectListFragment is always set, no null check needed Please remove log output

Target:
public void onBackPressed() { projectListFragment.cancelLoadProjectTask(); super.onBackPressed(); }
Source:
private void changeStatus(DestroyVmVDSCommandParameters parameters, VM curVm) { // do the state transition only if that VM is really running on SRC if (getParameters().getVdsId().equals(curVm.getRunOnVds())) { ResourceManager.getInstance().InternalSetVmStatus(curVm, START parameters.getGracefully() ? VMStatus.PoweringDown : VMStatus.Down, curVm.getStatusUpdatedTime()); END } } not needed (the value is null and won't be used anyway)

Target:
private void changeStatus(DestroyVmVDSCommandParameters parameters, VM curVm) { // do the state transition only if that VM is really running on SRC if (getParameters().getVdsId().equals(curVm.getRunOnVds())) { ResourceManager.getInstance().InternalSetVmStatus(curVm, parameters.getGracefully() ? VMStatus.PoweringDown : VMStatus.Down); } }
Source:
START public TransactionQuery(Selection selection, Publisher publisher, Optional<String> contentUri, END Optional<String> transactionId, Optional<TransactionStateType> transactionStatus) { this.selection = checkNotNull(selection); this.publisher = checkNotNull(publisher); this.contentUri = checkNotNull(contentUri); this.transactionId = checkNotNull(transactionId); this.transactionStatus = checkNotNull(transactionStatus); } Should this be private?

Target:
private TransactionQuery(Selection selection, Publisher publisher, Optional<String> contentUri, Optional<String> transactionId, Optional<TransactionStateType> transactionStatus) { this.selection = checkNotNull(selection); this.publisher = checkNotNull(publisher); this.contentUri = checkNotNull(contentUri); this.transactionId = checkNotNull(transactionId); this.transactionStatus = checkNotNull(transactionStatus); }
Source:
private static boolean appendPort(final String scheme, final int port) { START return port > -1 && ((HTTP.equals(scheme) && port != 80) || (HTTPS.equals(scheme) && port != 443)); END } maybe not necessary, but protocol is case-insensitive - maybe should be equalsIgnoreCase used?

Target:
private static boolean appendPort(final String scheme, final int port) { return port > -1 && ((HTTP.equalsIgnoreCase(scheme) && port != 80) || (HTTPS.equalsIgnoreCase(scheme) && port != 443)); }
Source:
public void addPage(BenchmarkData data) { int pageCount = data.getPageCount(); START Page page = data.getDataPage(); END PartitionedOutputOperator operator = data.createPartitionedOutputOperator(); for (int i = 0; i < pageCount; i++) { operator.addInput(page); } operator.finish(); } We can inline these two vars

Target:
public void addPage(BenchmarkData data) { PartitionedOutputOperator operator = data.createPartitionedOutputOperator(); for (int i = 0; i < data.getPageCount(); i++) { operator.addInput(data.getDataPage()); } operator.finish(); }
Source:
private Element timeZone() { START return textElement(BlogConstants.TIMEZONE, entity.getTimeZone()); END } Use import static

Target:
private Element timeZone() { return textElement(TIMEZONE, entity.getTimeZone()); }
Source:
private DbUser getDbUserForPrincipalName(String principalName, String authzName) { ExtMap principalRecord = AuthzUtils.fetchPrincipalRecord( EngineExtensionsManager.getInstance().getExtensionByName(authzName), START principalName, true, true); END if (principalRecord == null) { throw new RuntimeException(String.format("Unable to find principal %s in domain '%s'", principalName, authzName)); } return new DbUser(DirectoryUtils.mapPrincipalRecordToDirectoryUser(authzName, principalRecord)); } so do not resolve groups and no recursive as you going to search it anyway.

Target:
private DbUser getDbUserForPrincipalName(String principalName, String authzName) { ExtMap principalRecord = AuthzUtils.fetchPrincipalRecord( EngineExtensionsManager.getInstance().getExtensionByName(authzName), principalName, false, false); if (principalRecord == null) { throw new RuntimeException(String.format("Unable to find principal %s in domain '%s'", principalName, authzName)); } return new DbUser(DirectoryUtils.mapPrincipalRecordToDirectoryUser(authzName, principalRecord)); }
Source:
public PatternScatterGraphView() { super(ID); START this.addPartPropertyListener(new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(TmfXmlStrings.XML_LATENCY_OUTPUT_DATA)) { Object newValue = event.getNewValue(); if (newValue instanceof String) { String data = (String) newValue; fViewInfo.setViewData(data); setPartName(fViewInfo.getLabel()); loadLatencyView(); END } } } }); } lambda?

Target:
public PatternScatterGraphView() { super(ID); this.addPartPropertyListener(event -> { if (event.getProperty().equals(TmfXmlStrings.XML_LATENCY_OUTPUT_DATA)) { Object newValue = event.getNewValue(); if (newValue instanceof String) { String data = (String) newValue; fViewInfo.setViewData(data); setPartName(fViewInfo.getLabel()); loadLatencyView(); } } }); }
Source:
public void setMaxSpeed(double maxSpeed) { START if (this.maxSpeed == null || maxSpeed > this.maxSpeed) { END this.maxSpeed = maxSpeed; } } I believe `&&` should be here also

Target:
public void setMaxSpeed(double maxSpeed) { if (maxSpeed > this.maxSpeed) { this.maxSpeed = maxSpeed; } }
Source:
START Object getValue(Object obj) throws Exception { END throw new HazelcastException("Path agnostic value extraction is not supported"); } Minor: can remove `throws`

Target:
Object getValue(Object obj) { throw new HazelcastException("Path agnostic value extraction is not supported"); }
Source:
public boolean apply(Resource resource) { Predicate<EObject> hasOuterRef = new EObjectHasReferencesTo(modifiedResources); START boolean result = Iterators.any(EcoreUtil.<EObject> getAllProperContents(resource, false), hasOuterRef); END return result; } Except for debugging purpose, the "result" local does not seem necessary.

Target:
public boolean apply(Resource resource) { Predicate<EObject> hasOuterRef = new EObjectHasReferencesTo(modifiedResources); return Iterators.any(EcoreUtil.<EObject> getAllProperContents(resource, false), hasOuterRef); }
Source:
private URI endSessionEndpoint(OAuth2AuthenticationToken token) { String registrationId = token.getAuthorizedClientRegistrationId(); START ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); END Object endSessionEndpoint = clientRegistration.getProviderDetails().getConfigurationMetadata().get("end_session_endpoint"); URI result = null; if (endSessionEndpoint != null) { result = URI.create(endSessionEndpoint.toString()); } return result; } `clientRegistration` may be `null`. Please add a null check here.

Target:
private URI endSessionEndpoint(OAuth2AuthenticationToken token) { String registrationId = token.getAuthorizedClientRegistrationId(); ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); URI result = null; if (clientRegistration != null) { Object endSessionEndpoint = clientRegistration.getProviderDetails().getConfigurationMetadata().get("end_session_endpoint"); if (endSessionEndpoint != null) { result = URI.create(endSessionEndpoint.toString()); } } return result; }
Source:
public AddUnseenToBitmapFilter(BitmapBuilder seen, BitmapBuilder bitmap) { this.seen = seen; this.bitmap = START bitmapResult; END } bitmap.

Target:
public AddUnseenToBitmapFilter(BitmapBuilder seen, BitmapBuilder bitmap) { this.seen = seen; this.bitmap = bitmap; }
Source:
public void testQuantileAtValueBigint() { QuantileDigest qdigest = new QuantileDigest(1); addAll(qdigest, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); functionAssertions.assertFunction(format("quantile_at_value(CAST(X'%s' AS qdigest(bigint)), 20)", toHexString(qdigest)), START DOUBLE, END 1.0); functionAssertions.assertFunction(format("quantile_at_value(CAST(X'%s' AS qdigest(bigint)), 6)", toHexString(qdigest)), DOUBLE, 0.6); functionAssertions.assertFunction(format("quantile_at_value(CAST(X'%s' AS qdigest(bigint)), -1)", toHexString(qdigest)), DOUBLE, 0.0); } I see some surprising results here when adding additional test cases for doubles: * `Double.NaN` as the input value returns 1.0 (Edit: Double.MIN_VALUE is fine, I forgot this was just slightly greater than 0)

Target:
public void testQuantileAtValueBigint() { QuantileDigest qdigest = new QuantileDigest(1); addAll(qdigest, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); functionAssertions.assertFunction(format("quantile_at_value(CAST(X'%s' AS qdigest(bigint)), 20)", toHexString(qdigest)), DOUBLE, null); functionAssertions.assertFunction(format("quantile_at_value(CAST(X'%s' AS qdigest(bigint)), 6)", toHexString(qdigest)), DOUBLE, 0.6); functionAssertions.assertFunction(format("quantile_at_value(CAST(X'%s' AS qdigest(bigint)), -1)", toHexString(qdigest)), DOUBLE, null); }
Source:
public boolean isOverutilized() { START return memoryManager.isOverUtilized(); END } I'm ok with either capitalization. But it needs to be consistent. The `overutilized` 2 lines above is capitalized differently.

Target:
public boolean isOverutilized() { return memoryManager.isOverutilized(); }
Source:
public String explain() throws CouchbaseLiteException { START if (c4query == null) END check(); synchronized (getDatabase().getLock()) { return c4query.explain(); } } c4query should also be synchronized. Move c4query checks to the check method itself. The same thing for the execute() method. See https://github.com/couchbase/couchbase-lite-ios/blob/feature/2.0/Objective-C/CBLQuery.mm#L605-L606

Target:
public String explain() throws CouchbaseLiteException { synchronized (getDatabase().getLock()) { check(); return c4query.explain(); } }
Source:
public boolean isObjectFactory() { START return getTargetTypeParameter() != null || getParameters().isEmpty(); END } just return `false` here.

Target:
public boolean isObjectFactory() { return false; }
Source:
START StandardRotationPolicy(DelegatingSessionFactory<?> factory, List<KeyDirectory> keyDirectories, END boolean fair) { Assert.notNull(factory, "factory cannot be null"); Assert.notNull(keyDirectories, "keyDirectories cannot be null"); Assert.isTrue(keyDirectories.size() > 0, "At least one KeyDirectory is required"); this.factory = factory; this.keyDirectories.addAll(keyDirectories); this.fair = fair; this.iterator = this.keyDirectories.iterator(); } Shound't this ctor be `public` or at least `protected`? Otherwise I don't see reason in all those `protected` methods below.

Target:
public StandardRotationPolicy(DelegatingSessionFactory<?> factory, List<KeyDirectory> keyDirectories, boolean fair) { Assert.notNull(factory, "factory cannot be null"); Assert.notNull(keyDirectories, "keyDirectories cannot be null"); Assert.isTrue(keyDirectories.size() > 0, "At least one KeyDirectory is required"); this.factory = factory; this.keyDirectories.addAll(keyDirectories); this.fair = fair; this.iterator = this.keyDirectories.iterator(); }
Source:
public void add(EntityType entity) { validateAddAllowed(entity); START createAcl(entity); END super.add(entity); } Tricky! `validateAddAllowed` currently checks if you have the WRITE_META permission on the entity. Acl gets created after the check. This breaks OneClickImporter

Target:
public void add(EntityType entity) { createAcl(entity); super.add(entity); }
Source:
private ArtifactCoordinates getArtifactCoordinates(Path p) { START return ThrowingFunction.unchecked(RepositoryFiles::readCoordinates).apply((RepositoryPath) p); END } @adavid9 can you please add `throws IOException` here and use `TrowingFunction` at `GroupRepositoryProvider.search` ?

Target:
private ArtifactCoordinates getArtifactCoordinates(Path p) throws IOException { return RepositoryFiles.readCoordinates((RepositoryPath) p); }
Source:
START public IPinUpdater<? extends ActivityNode> instantiate(ActivityNode node){ END IPinUpdater<? extends ActivityNode> updater = null; if(node instanceof CallBehaviorAction){ updater = new CallBehaviorActionPinUpdater(); }else if(node instanceof CallOperationAction){ updater = new CallOperationActionPinUpdater(); }else if(node instanceof SendSignalAction){ updater = new SendSignalActionPinUpdater(); } return updater; } To avoid accidental class casts, you can use the following signature: public <T extends ActivityNode> IPinUpdater<T> instantiate(T node) Then unchecked casts can be regrouped into this method (Rather than in each Clients)

Target:
public <T extends ActivityNode> IPinUpdater<T> instantiate(ActivityNode node) { IPinUpdater<T> updater = null; if (node instanceof CallBehaviorAction) { updater = (IPinUpdater<T>) new CallBehaviorActionPinUpdater(); } else if (node instanceof CallOperationAction) { updater = (IPinUpdater<T>) new CallOperationActionPinUpdater(); } else if (node instanceof SendSignalAction) { updater = (IPinUpdater<T>) new SendSignalActionPinUpdater(); } return updater; }
Source:
public boolean supportsScroll() { StorageConfiguration conf = coreFeature.getStorageConfiguration(); // DBS mem and marklogic are not yet supported START return conf.isDBSMongoDB() || conf.isVCS(); END } Please don't do cleanups in the same commit as bugfixes/features/improvements

Target:
public boolean supportsScroll() { StorageConfiguration conf = coreFeature.getStorageConfiguration(); // DBS mem and marklogic are not yet supported return (conf.isDBSMongoDB() || conf.isVCS()); }
Source:
public void onResume() { super.onResume(); addCachedDevices(); START if (mLocalAdapter.getBluetoothState() != BluetoothAdapter.STATE_ON) END removeAllDevices(); if (mStartScanOnResume) { mLocalAdapter.startScanning(true); mStartScanOnResume = false; } } Style issue: please use braces in a multiline conditional.

Target:
public void onResume() { super.onResume(); addCachedDevices(); if (mLocalAdapter.getBluetoothState() != BluetoothAdapter.STATE_ON) { removeAllDevices(); } if (mStartScanOnResume) { mLocalAdapter.startScanning(true); mStartScanOnResume = false; } }
Source:
protected void upgradeNexusVersion() throws IOException { final String currentVersion = checkNotNull( applicationStatusSource.getSystemStatus().getVersion() ); final String previousVersion = getConfiguration().getNexusVersion(); if ( currentVersion.equals( previousVersion ) ) { setInstanceUpgraded( false ); } else { setInstanceUpgraded( true ); getConfiguration().setNexusVersion( currentVersion ); storeConfiguration(); START eventMulticaster.notifyEventListeners( new NexusVersionChangedEvent( this, previousVersion, END currentVersion ) ); } } Not sure i'd go with events (yet). Model upgrade was not emitting events either, and Status flags with this change would be properly set. Let's go with baby steps, and not introduce events for these yet (unless some other good reason mentioned for it's need)

Target:
protected void upgradeNexusVersion() throws IOException { final String currentVersion = checkNotNull( applicationStatusSource.getSystemStatus().getVersion() ); final String previousVersion = getConfiguration().getNexusVersion(); if ( currentVersion.equals( previousVersion ) ) { setInstanceUpgraded( false ); } else { setInstanceUpgraded( true ); getConfiguration().setNexusVersion( currentVersion ); storeConfiguration(); } }
Source:
START public DefDeclaration(String name, Type returnType, List<NameBinding> argNames, END TypedAST body, boolean isClassDef, FileLocation location) { if (argNames == null) { argNames = new LinkedList<NameBinding>(); } this.type = getMethodType(argNames, returnType); this.name = name; this.body = (ExpressionAST) body; this.argNames = argNames; this.isClass = isClassDef; this.location = location; } Can you make the old constructor call the new one (with a default value for the additional parameter)?

Target:
public DefDeclaration(String name, Type returnType, List<NameBinding> argNames, TypedAST body, boolean isClassDef, FileLocation location) { this(name, returnType, null, argNames, body, isClassDef, location); }
Source:
START public Waiter<HeadBucketRequest> bucketNotExists() { END return new WaiterBuilder<HeadBucketRequest, HeadBucketResult>() .withSdkFunction(new HeadBucketFunction(client)) .withAcceptors( new HttpFailureStatusAcceptor(404, WaiterState.SUCCESS)) .withDefaultPollingStrategy( new PollingStrategy(new MaxAttemptsRetryStrategy(20), new FixedDelayStrategy(5))) .withExecutorService(executorService).build(); } Can we all add the generic parameters for the acceptors? (Like `HttpFailureStatusAcceptor<HeadBucketResult>`?)

Target:
public Waiter<HeadBucketRequest> bucketNotExists() { return new WaiterBuilder<HeadBucketRequest, HeadBucketResult>() .withSdkFunction(new HeadBucketFunction(client)) .withAcceptors( new HttpFailureStatusAcceptor<HeadBucketResult>(404, WaiterState.SUCCESS)) .withDefaultPollingStrategy( new PollingStrategy(new MaxAttemptsRetryStrategy(20), new FixedDelayStrategy(5))) .withExecutorService(executorService).build(); }
Source:
public TextArea createWidget() { final TextArea textArea = GWT.create(TextArea.class); textArea.addKeyDownHandler(keyDownEvent -> { final int keyCode = keyDownEvent.getNativeKeyCode(); START if (keyCode == KeyCodes.KEY_TAB) { END destroyResources(); gridPanel.setFocus(true); keyDownEvent.preventDefault(); } keyDownEvent.stopPropagation(); }); textArea.addMouseDownHandler(DomEvent::stopPropagation); return textArea; } @jomarko A couple of question: 1) from the ticket description it seems that somehow both TAB and ESC should be managed (in different way) but I do not see that here: is the ESC managed elsewhere or in different way? 2) is this kind of interaction specific ot ScenarioSImulation? Is it not the same for other grid editor? If the behavior should be the same on different component, then it should be better to create a builder/getter somewhere else (some abstract/parent class) to avoid duplicate this snippet

Target:
public TextArea createWidget() { final TextArea textArea = GWT.create(TextArea.class); textArea.addMouseDownHandler(DomEvent::stopPropagation); return textArea; }
Source:
public void testHierarchyView() { DockerImagesTab imageTab = openDockerImagesTab(); buildImage(IMAGE_TEST_BUILD, DOCKERFILE_FOLDER, imageTab); if (mockitoIsUsed()) { START setupDataForMockito(); END } DockerImageHierarchyTab hierarchyTab = openDockerImageHierarchyTab(); List<TreeItem> treeItems = hierarchyTab.getTreeItems(); compareTextInFirstNode(treeItems, "alpine:3.3"); List<TreeItem> treeItems2 = treeItems.get(0).getItems(); compareTextInFirstNode(treeItems2, IMAGE_TEST_BUILD + NAME_TAG_SEPARATOR + IMAGE_TAG_LATEST); } Why is setupDataForMockito() called here when it is designated with the @Before keyword below? I have seen this in a few other tests as well.

Target:
public void testHierarchyView() { DockerImagesTab imageTab = openDockerImagesTab(); buildImage(IMAGE_TEST_BUILD, DOCKERFILE_FOLDER, imageTab); if (mockitoIsUsed()) { buildImage(); } DockerImageHierarchyTab hierarchyTab = openDockerImageHierarchyTab(); List<TreeItem> treeItems = hierarchyTab.getTreeItems(); compareTextInFirstNode(treeItems, "alpine:3.3"); List<TreeItem> treeItems2 = treeItems.get(0).getItems(); compareTextInFirstNode(treeItems2, IMAGE_TEST_BUILD + NAME_TAG_SEPARATOR + IMAGE_TAG_LATEST); }
Source:
START void doBadOffsetInputTest(String name, long offset) { END try { new Offset(name, offset); fail("Should have thrown because one of the inputs is invalid"); } catch (IllegalArgumentException e) { // expected. } } private

Target:
private void doBadOffsetInputTest(String name, long offset) { try { new Offset(name, offset); fail("Should have thrown because one of the inputs is invalid"); } catch (IllegalArgumentException e) { // expected. } }
Source:
private void enablePhiro() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); if (!sharedPreferences.getBoolean(Constants.PHIRO_INITIALIZED, false)) { START BaseSettingsActivity.setPhiroSharedPreferenceEnabled(this, true); END sharedPreferences.edit().putBoolean(Constants.PHIRO_INITIALIZED, true).apply(); } } why is the same code still present in the SettingsActivity?

Target:
private void enablePhiro() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); if (!sharedPreferences.getBoolean(PHIRO_INITIALIZED, false)) { BaseSettingsActivity.setPhiroSharedPreferenceEnabled(this, true); sharedPreferences.edit().putBoolean(PHIRO_INITIALIZED, true).apply(); } }
Source:
private void checkReturnedValue(ReturnStatementTree tree, String nonNullAnnotation) { SymbolicValue returnedValue = programState.peekValue(); Constraint constraint = programState.getConstraint(returnedValue); if (constraint == null) { START reportIssue(tree, "This method''s return value is marked \"{0}\" but null may be returned.", nonNullAnnotation); END } else if (constraint.isNull()) { reportIssue(tree, "This method''s return value is marked \"{0}\" but null is returned.", nonNullAnnotation); } } We should not raise issues in this case, as we are not certain. As we are not (yet) doing cross-procedural analysis, doing the assumption that we may end up with a null value with necessarily raise à lot of FPs.

Target:
private void checkReturnedValue(ReturnStatementTree tree, String nonNullAnnotation) { SymbolicValue returnedValue = programState.peekValue(); Constraint constraint = programState.getConstraint(returnedValue); if (constraint != null && constraint.isNull()) { reportIssue(tree, "This method''s return value is marked \"{0}\" but null is returned.", nonNullAnnotation); } }
Source:
private void verifyEditResultCode(EditingResult result) { START assertThat(result.getResult(), equalTo(SUCCESS)); END } Minor: consider replacing equalTo with is from Hamcrest here and below.

Target:
private void verifyEditResultCode(EditingResult result) { assertThat(result.getResult(), is(SUCCESS)); }
Source:
START public EnginesPreferencePage() { END } should call super(); explicitly

Target:
public EnginesPreferencePage() { super(); }
Source:
public List<AmbryReplica> getReplicaIds() { START return clusterManagerCallback.getReplicaIdsForPartition(this) END .stream() .map(r -> (AmbryReplica) r) .collect(Collectors.toList()); } Instead of copying the list and requiring a (potentially) unsafe cast. I think we could make more use of generics in `ClusterManagerCallback`.

Target:
public List<AmbryReplica> getReplicaIds() { return clusterManagerCallback.getReplicaIdsForPartition(this); }
Source:
private String blockingSSLConnect(int socketBufSize) throws IOException { String connectionId = selector.connect(new InetSocketAddress("localhost", server.port), socketBufSize, socketBufSize, PortType.SSL); while (!selector.connected().contains(connectionId)) { START System.out.println("here"); END selector.poll(10000L); } return connectionId; } remove?

Target:
private String blockingSSLConnect(int socketBufSize) throws IOException { String connectionId = selector.connect(new InetSocketAddress("localhost", server.port), socketBufSize, socketBufSize, PortType.SSL); while (!selector.connected().contains(connectionId)) { selector.poll(10000L); } return connectionId; }
Source:
START public EDDifferentialPrivacy(double epsilon, double delta, END DataGeneralizationScheme generalization) { super(delta); this.epsilon = epsilon; this.generalization = generalization; this.beta = calculateBeta(epsilon); this.k = calculateK(getDelta(), epsilon, this.beta); } Why does this constructor not simply call the other one?

Target:
public EDDifferentialPrivacy(double epsilon, double delta, DataGeneralizationScheme generalization) { this(epsilon, delta, generalization, false); }
Source:
private final String getSessionIndex(Assertion subjectAssertion) { List<AuthnStatement> authnStatements = subjectAssertion.getAuthnStatements(); if(authnStatements != null && authnStatements.size() > 0) { AuthnStatement statement = authnStatements.get(0); START return statement.getSessionIndex(); END } return null; } Can `statement` be null?

Target:
private final String getSessionIndex(Assertion subjectAssertion) { List<AuthnStatement> authnStatements = subjectAssertion.getAuthnStatements(); if(authnStatements != null && authnStatements.size() > 0) { AuthnStatement statement = authnStatements.get(0); if(statement != null) { return statement.getSessionIndex(); } } return null; }
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree method = (MethodTree) tree; START if (!INPUT_STREAM_READ.matches(method) || method.block() == null) { END return; } method.accept(new ReturnStatementVisitor()); } I would switch those two conditions.

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree method = (MethodTree) tree; if (method.block() != null && INPUT_STREAM_READ.matches(method)) { method.accept(new ReturnStatementVisitor()); } }
Source:
protected void onFinishInflate() { super.onFinishInflate(); View.inflate(getContext(), R.layout.merge_login_view, this); loginButton = Views.findById(this, R.id.sign_in_button); START loginButton.setSize(SignInButton.SIZE_WIDE); END } Can't be set in xml ?

Target:
protected void onFinishInflate() { super.onFinishInflate(); View.inflate(getContext(), R.layout.merge_login_view, this); loginButton = Views.findById(this, R.id.sign_in_button); }
Source:
START private int encode(int bucketIndex, int value) END { return (bucketIndex << VALUE_BITS) | value; } static

Target:
private static int encode(int bucketIndex, int value) { return (bucketIndex << VALUE_BITS) | value; }
Source:
public void onUberfireDocksInteractionEvent(@Observes final UberfireDocksInteractionEvent uberfireDocksInteractionEvent) { START if (isUberfireDocksInteractionEventToManage(uberfireDocksInteractionEvent) && !uberfireDocksInteractionEvent.getTargetDock().getIdentifier().equals(TestToolsPresenter.IDENTIFIER)) { END populateRightDocks(uberfireDocksInteractionEvent.getTargetDock().getIdentifier()); } } Are you sure that `getTargetDock().getIdentifier()` is always not `null`? I suggest to rewrite the condition as `!TestToolsPresenter.IDENTIFIER.equals(uberfireDocksInteractionEvent.getTargetDock().getIdentifier())`

Target:
public void onUberfireDocksInteractionEvent(@Observes final UberfireDocksInteractionEvent uberfireDocksInteractionEvent) { if (isUberfireDocksInteractionEventToManage(uberfireDocksInteractionEvent) && !TestToolsPresenter.IDENTIFIER.equals(uberfireDocksInteractionEvent.getTargetDock().getIdentifier())) { populateRightDocks(uberfireDocksInteractionEvent.getTargetDock().getIdentifier()); } }
Source:
public String getDocType() { if (Objects.isNull(docType)) { List<SelectItem> allDocTypes = getAllDoctypes(); for (SelectItem item : allDocTypes) { START if ("Monograph".equals(item.getValue())) { END setDocType((String) item.getValue()); return docType; } } setDocType((String) allDocTypes.get(0).getValue()); } return docType; } No, such a feature has not been requested so far. The current state is that each division can be the type of root element. It was discussed that we might later add a possibility that these types can be restricted. In the context, one could also implement the selection of a standard type.

Target:
public String getDocType() { if (Objects.isNull(docType) && !allDocTypes.isEmpty()) { setDocType((String) allDocTypes.get(0).getValue()); } return docType; }
Source:
START public boolean shouldUseCommitTemplate() { END return Activator.getDefault().getPreferenceStore() .getBoolean(UIPreferences.COMMIT_DIALOG_MESSAGE_TEMPLATE) && getCommitMessage() == null && getCommitTemplate().isPresent(); } why is this needed ?

Target:
public boolean shouldUseCommitTemplate() { return getCommitMessage() == null && getCommitTemplate().isPresent(); }