auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean hasNext() { if (isNextMatchCalculated) { return true; } if (currentPlan == null) { return false; } try { boolean foundMatch = currentPlan.execute(frame); while ((!foundMatch) && planIterator.hasNext()) { foundMatch = selectNextPlan() && currentPlan.execute(frame); } <START> if (foundMatch) { <END> isNextMatchCalculated = true; } return foundMatch; } catch (LocalSearchException e) { throw new RuntimeException(e); } }</code><technical_language>This condition omitted this point isNextMatchCalculated is false (from condition 121). nitpicking, this code is executed times I propose simply put 'isNextMatchCalculated = foundMatch' here</technical_language>

Target:
public boolean hasNext() { if (isNextMatchCalculated) { return true; } if (currentPlan == null) { return false; } try { boolean foundMatch = currentPlan.execute(frame); while ((!foundMatch) && planIterator.hasNext()) { foundMatch = selectNextPlan() && currentPlan.execute(frame); } isNextMatchCalculated = foundMatch; return foundMatch; } catch (LocalSearchException e) { throw new RuntimeException(e); } }
Source:
<code>public void start(final Stage initialStage) { logger.info("TerasologyLauncher is starting"); logSystemInformation(); initProxy(); initLanguage(); final Task<LauncherConfiguration> launcherInitTask = new LauncherInitTask(initialStage); showSplashStage(initialStage, launcherInitTask); Thread initThread = new Thread(launcherInitTask); initThread.setName("Launcher init thread"); launcherInitTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(final WorkerStateEvent workerStateEvent) { try { LauncherConfiguration config = launcherInitTask.getValue(); if (config == null) { throw new LauncherStartFailedException("Launcher configuration was `null`."); } else if (config instanceof NullLauncherConfiguration) { logger.info("Closing the launcher ... (empty configuration, probably due to update)"); Platform.exit(); } else { showMainStage(config); } } catch (IOException | LauncherStartFailedException e) { openCrashReporterAndExit(e); } } }); <START> launcherInitTask.setOnFailed(event -> {openCrashReporterAndExit(new RuntimeException("FUUU"));}); <END> initThread.start(); }</code><technical_language>"FUUU" - point, I guess improve</technical_language>

Target:
public void start(final Stage initialStage) { logger.info("TerasologyLauncher is starting"); logSystemInformation(); initProxy(); initLanguage(); final Task<LauncherConfiguration> launcherInitTask = new LauncherInitTask(initialStage); showSplashStage(initialStage, launcherInitTask); Thread initThread = new Thread(launcherInitTask); initThread.setName("Launcher init thread"); launcherInitTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(final WorkerStateEvent workerStateEvent) { try { LauncherConfiguration config = launcherInitTask.getValue(); if (config == null) { throw new LauncherStartFailedException("Launcher configuration was `null`."); } else if (config instanceof NullLauncherConfiguration) { logger.info("Closing the launcher ... (empty configuration, probably due to update)"); Platform.exit(); } else { showMainStage(config); } } catch (IOException | LauncherStartFailedException e) { openCrashReporterAndExit(e); } } }); launcherInitTask.setOnFailed(event -> { Throwable throwable = event.getSource().getException(); Exception exception; if (throwable instanceof Exception) { exception = (Exception) throwable; } else { exception = new Exception("Wrapped throwable, see deeper", throwable); } openCrashReporterAndExit(exception); }); initThread.start(); }
Source:
<code>public JDBCStatusStoreLoader(GeoServerDataDirectory dd) throws IOException { dataDir = dd; try { Properties params = getParameters(); store = DataStoreFinder.getDataStore(params); } catch (IOException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>above, do meaningful :-)</technical_language>

Target:
public JDBCStatusStoreLoader(GeoServerDataDirectory dd) throws IOException { dataDir = dd; try { Properties params = getParameters(); store = DataStoreFinder.getDataStore(params); } catch (IOException e) { LOGGER.info("can't find or create JDBC Status store configuration file"); LOGGER.log(Level.FINE, "no config file?", e); } }
Source:
<code>public void testReferenceContainmentMultiMove2WayLtR() throws IOException { final Resource left = input.getReferenceContainmentMultiMoveLeft(); final Resource right = input.getReferenceContainmentMultiMoveRight(); final IComparisonScope scope = new DefaultComparisonScope(left, right, null); Comparison comparison = EMFCompare.builder().build().compare(scope); final List<Diff> differences = comparison.getDifferences(); assertSame(Integer.valueOf(1), Integer.valueOf(differences.size())); final String featureName = "containmentRef1"; final Diff diff = Iterators.find(differences.iterator(), and(fromSide(DifferenceSource.LEFT), moved( "root.value2", featureName))); mergerRegistry.getHighestRankingMerger(diff).copyLeftToRight(diff, new BasicMonitor()); final EObject targetNode = getNodeNamed(right, "value2"); assertNotNull(targetNode); final EObject sourceNode = getNodeNamed(left, "value2"); assertNotNull(sourceNode); final EStructuralFeature feature = targetNode.eClass().getEStructuralFeature(featureName); <START> assertNotNull(feature); <END> comparison = EMFCompare.builder().build().compare(scope); assertSame(Integer.valueOf(0), Integer.valueOf(comparison.getDifferences().size())); }</code><technical_language>lines testing anything, "Nodes" this feature. I this assertEquals(targetNode.eClass().eContainingFeature().getName() , featureName)</technical_language>

Target:
public void testReferenceContainmentMultiMove2WayLtR() throws IOException { final Resource left = input.getReferenceContainmentMultiMoveLeft(); final Resource right = input.getReferenceContainmentMultiMoveRight(); final IComparisonScope scope = new DefaultComparisonScope(left, right, null); Comparison comparison = EMFCompare.builder().build().compare(scope); final List<Diff> differences = comparison.getDifferences(); assertSame(Integer.valueOf(1), Integer.valueOf(differences.size())); final String featureName = "containmentRef1"; final Diff diff = Iterators.find(differences.iterator(), and(fromSide(DifferenceSource.LEFT), moved( "root.value2", featureName))); mergerRegistry.getHighestRankingMerger(diff).copyLeftToRight(diff, new BasicMonitor()); final EObject targetNode = getNodeNamed(right, "value2"); assertNotNull(targetNode); final EObject targetContainerNode = getNodeNamed(right, "root"); assertNotNull(targetContainerNode); assertEquals(targetContainerNode, targetNode.eContainer()); final EObject sourceNode = getNodeNamed(left, "value2"); assertNotNull(sourceNode); final EObject sourceContainerNode = getNodeNamed(left, "root"); assertNotNull(sourceContainerNode); assertEquals(sourceContainerNode, sourceNode.eContainer()); comparison = EMFCompare.builder().build().compare(scope); assertSame(Integer.valueOf(0), Integer.valueOf(comparison.getDifferences().size())); }
Source:
<code><START> public int compare(T a, T b) { if (a == b) { return 0; } else if (a == null) { return -1; } else if (b == null) { return 1; } throw DataUtils.newUnsupportedOperationException("Can not compare"); <END> }</code><technical_language>is a purpose of implementation? this method abstract throw exception unconditionally</technical_language>

Target:
public int compare(T a, T b) { throw DataUtils.newUnsupportedOperationException("Can not compare"); }
Source:
<code>public static Id parse(final String str) { final Id r = new Id(); String preparedStr = str; <START> if (preparedStr.endsWith("/")) { <END> preparedStr = preparedStr.substring(0, preparedStr.length() - 1); } r.fromString(preparedStr); return r; }</code><technical_language>This is wrong place perform this parsing. I belongs in Dispatcher.change (~line 459) UrlModule.directChangeById (~line 158)</technical_language>

Target:
public static Id parse(final String str) { final Id r = new Id(); r.fromString(str); return r; }
Source:
<code>public static MerlinsBeard from(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); AndroidVersion androidVersion = new AndroidVersion(); ResponseCodeValidator validator = new ResponseCodeValidator.DefaultEndpointResponseCodeValidator(); <START> EndpointPinger pinger = EndpointPinger.withCustomEndpointAndValidation(Endpoint.from(ENDPOINT), validator); <END> Ping ping = new Ping(Endpoint.defaultEndpoint(), new EndpointPinger.ResponseCodeFetcher(), validator); return new MerlinsBeard(connectivityManager, androidVersion, pinger, ping); }</code><technical_language>Maybe? suggestion EndpointPinger pinger = EndpointPinger.withCustomEndpointAndValidation(Endpoint.defaultEndpoint(), validator);</technical_language>

Target:
public static MerlinsBeard from(Context context) { return new MerlinsBeard.Builder() .build(context); }
Source:
<code>private void updateStoragePoolFormatType() { final storage_pool storagePool = getStoragePool(); final Guid spId = storagePool.getId(); final Version spVersion = storagePool.getcompatibility_version(); final Version oldSpVersion = _oldStoragePool.getcompatibility_version(); <START> if (Version.OpEquality(spVersion, oldSpVersion)) { <END> return; } StorageFormatType targetFormat = StorageFormatType.V1; if (spVersion.compareTo(Version.v3_0) == 0) { targetFormat = StorageFormatType.V2; } else if (spVersion.compareTo(Version.v3_1) == 0) { targetFormat = StorageFormatType.V3; } StorageType spType = storagePool.getstorage_pool_type(); if (targetFormat == StorageFormatType.V2 && spType != StorageType.ISCSI && spType != StorageType.FCP) { return; } storagePool.setStoragePoolFormatType(targetFormat); getStoragePoolDAO().updatePartial(storagePool); updateMemberDomainsFormat(targetFormat); if (storagePool.getstatus() != StoragePoolStatus.Up) { return; } if (getStoragePool().getstatus() == StoragePoolStatus.Up) { runVdsCommand(VDSCommandType.UpgradeStoragePool, new UpgradeStoragePoolVDSCommandParameters(spId, targetFormat)); } }</code><technical_language>This condition infers updateStoragePoolFormatType() in fact do nothing. separate this logic a method, called executeCommand(). E.g.: if (updateStoragePoolFormatTypeNeeded() { updateStoragePoolFormatType(); }</technical_language>

Target:
private void updateStoragePoolFormatType() { final storage_pool storagePool = getStoragePool(); final Guid spId = storagePool.getId(); final Version spVersion = storagePool.getcompatibility_version(); final Version oldSpVersion = _oldStoragePool.getcompatibility_version(); final StorageFormatType targetFormat; if (Version.OpEquality(spVersion, oldSpVersion)) { return; } if (spVersion.compareTo(Version.v3_0) == 0) { targetFormat = StorageFormatType.V2; } else if (spVersion.compareTo(Version.v3_1) == 0) { targetFormat = StorageFormatType.V3; } else { targetFormat = StorageFormatType.V1; } StorageType spType = storagePool.getstorage_pool_type(); if (targetFormat == StorageFormatType.V2 && spType != StorageType.ISCSI && spType != StorageType.FCP) { return; } storagePool.setStoragePoolFormatType(targetFormat); TransactionSupport.executeInScope(TransactionScopeOption.RequiresNew, new TransactionMethod<Object>() { @Override public Object runInTransaction() { getStoragePoolDAO().updatePartial(storagePool); updateMemberDomainsFormat(targetFormat); return null; } }); if (_oldStoragePool.getstatus() == StoragePoolStatus.Up) { runVdsCommand(VDSCommandType.UpgradeStoragePool, new UpgradeStoragePoolVDSCommandParameters(spId, targetFormat)); } }
Source:
<code>@Nullable public TcpDiscoveryNode nextNode(@Nullable Collection<TcpDiscoveryNode> excluded) { assert locNode.internalOrder() > 0 : locNode; assert excluded == null || excluded.isEmpty() || !excluded.contains(locNode) : excluded; rwLock.readLock().lock(); try { Iterator<TcpDiscoveryNode> filtered = serverNodes(excluded, locNode).iterator(); <START> if (filtered.hasNext()) { <END> return filtered.next(); } else { filtered = serverNodes(excluded).iterator(); if (filtered.hasNext()) { TcpDiscoveryNode firstNode = filtered.next(); if (firstNode.equals(locNode)) return null; else return firstNode; } else return null; } } finally { rwLock.readLock().unlock(); } }</code><technical_language>space line</technical_language>

Target:
@Nullable public TcpDiscoveryNode nextNode(@Nullable Collection<TcpDiscoveryNode> excluded) { assert locNode.internalOrder() > 0 : locNode; assert excluded == null || excluded.isEmpty() || !excluded.contains(locNode) : excluded; rwLock.readLock().lock(); try { return notSyncNextNode(excluded); } finally { rwLock.readLock().unlock(); } }
Source:
<code>public static IInputValidator getRemoteNameInputValidator( final StoredConfig config, final boolean errorOnEmptyName) { return new IInputValidator() { @Override public String isValid(String newText) { if (newText.length() == 0) { if (errorOnEmptyName) return UIText.ValidationUtils_PleaseEnterNameMessage; else return null; } <START> if (config.getNames(RepositoriesView.REMOTE, newText).size() > 0) { <END> return NLS.bind( UIText.ValidationUtils_RemoteAlreadyExistsMessage, newText); } return null; } }; }</code><technical_language>Repository.isValidRefName(Constants.R_REMOTES + remoteName)) JGit check validity of remote name (see CloneDestinationPage.checkPage())</technical_language>

Target:
public static IInputValidator getRemoteNameInputValidator( final StoredConfig config, final boolean errorOnEmptyName) { return new IInputValidator() { @Override public String isValid(String newText) { if (newText.length() == 0) { if (errorOnEmptyName) return UIText.ValidationUtils_PleaseEnterNameMessage; else return null; } if (!Repository.isValidRefName(Constants.R_REMOTES + newText)) { return NLS.bind( UIText.ValidationUtils_InvalidRemoteNameMessage, newText); } if (config.getNames(RepositoriesView.REMOTE, newText).size() > 0) { return NLS.bind( UIText.ValidationUtils_RemoteAlreadyExistsMessage, newText); } return null; } }; }
Source:
<code>HTMLOptGroupElement makeOptionGroup(final String groupTitle, final List<DataType> dataTypes, final Function<DataType, String> dataTypeConsumer) { final HTMLOptGroupElement optionGroup = makeHTMLOptGroupElement(); optionGroup.label = groupTitle; dataTypes.stream() <START> .sorted(DATA_TYPE_COMPARATOR) <END> .forEach(dataType -> { final HTMLOptionElement option = makeOption(dataType, dataTypeConsumer); optionGroup.appendChild(option); }); return optionGroup; }</code><technical_language>ordering data types DataType::getName, however, a here: <LINK_0> ..we're DataType::getType function for default data types. So, I correctly ordered</technical_language>

Target:
HTMLOptGroupElement makeOptionGroup(final String groupTitle, final List<DataType> dataTypes, final Function<DataType, String> dataTypeConsumer) { final HTMLOptGroupElement optionGroup = makeHTMLOptGroupElement(); optionGroup.label = groupTitle; dataTypes.stream() .forEach(dataType -> { final HTMLOptionElement option = makeOption(dataType, dataTypeConsumer); optionGroup.appendChild(option); }); return optionGroup; }
Source:
<code>public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription description = null; if (rep instanceof RefRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addSelfLink(); return description; } <START> if (rep instanceof DefaultRepresentation || rep instanceof FullRepresentation) { <END> description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("name"); description.addProperty("description"); description.addProperty("identifierType"); description.addSelfLink(); if (rep instanceof DefaultRepresentation) { description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); } } return description; }</code><technical_language>else if</technical_language>

Target:
public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription description = null; if (rep instanceof RefRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addSelfLink(); return description; } else if (rep instanceof DefaultRepresentation || rep instanceof FullRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("name"); description.addProperty("description"); description.addProperty("identifierType"); description.addSelfLink(); if (rep instanceof DefaultRepresentation) { description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); } } return description; }
Source:
<code>protected List<? extends Module> getModules() { return ImmutableList.<Module>of( new Module() { @Override public void configure(Binder binder) { binder.bindConstant().annotatedWith(Names.named("serviceName")).to("druid/middlemanager"); binder.bindConstant().annotatedWith(Names.named("servicePort")).to(8091); IndexingServiceModuleHelper.configureTaskRunnerConfigs(binder); <START> binder.bind(NodeTypeConfig.class).toInstance(new NodeTypeConfig("middlemanager")); <END> JsonConfigProvider.bind(binder, "druid.indexer.task", TaskConfig.class); JsonConfigProvider.bind(binder, "druid.worker", WorkerConfig.class); binder.bind(TaskRunner.class).to(ForkingTaskRunner.class); binder.bind(ForkingTaskRunner.class).in(LazySingleton.class); binder.bind(ChatHandlerProvider.class).toProvider(Providers.<ChatHandlerProvider>of(null)); binder.bind(WorkerTaskMonitor.class).in(ManageLifecycle.class); binder.bind(WorkerCuratorCoordinator.class).in(ManageLifecycle.class); LifecycleModule.register(binder, WorkerTaskMonitor.class); binder.bind(JettyServerInitializer.class).toInstance(new MiddleManagerJettyServerInitializer()); Jerseys.addResource(binder, WorkerResource.class); LifecycleModule.register(binder, Server.class); } @Provides @LazySingleton public Worker getWorker(@Self DruidNode node, WorkerConfig config) { return new Worker( node.getHostAndPort(), config.getIp(), config.getCapacity(), config.getVersion() ); } }, new IndexingServiceFirehoseModule(), new IndexingServiceTaskLogsModule() ); }</code><technical_language>this "middleManager", consistent command name</technical_language>

Target:
protected List<? extends Module> getModules() { return ImmutableList.<Module>of( new Module() { @Override public void configure(Binder binder) { binder.bindConstant().annotatedWith(Names.named("serviceName")).to("druid/middlemanager"); binder.bindConstant().annotatedWith(Names.named("servicePort")).to(8091); IndexingServiceModuleHelper.configureTaskRunnerConfigs(binder); binder.bind(NodeTypeConfig.class).toInstance(new NodeTypeConfig("middleManager")); JsonConfigProvider.bind(binder, "druid.indexer.task", TaskConfig.class); JsonConfigProvider.bind(binder, "druid.worker", WorkerConfig.class); binder.bind(TaskRunner.class).to(ForkingTaskRunner.class); binder.bind(ForkingTaskRunner.class).in(LazySingleton.class); binder.bind(ChatHandlerProvider.class).toProvider(Providers.<ChatHandlerProvider>of(null)); binder.bind(WorkerTaskMonitor.class).in(ManageLifecycle.class); binder.bind(WorkerCuratorCoordinator.class).in(ManageLifecycle.class); LifecycleModule.register(binder, WorkerTaskMonitor.class); binder.bind(JettyServerInitializer.class).toInstance(new MiddleManagerJettyServerInitializer()); Jerseys.addResource(binder, WorkerResource.class); LifecycleModule.register(binder, Server.class); } @Provides @LazySingleton public Worker getWorker(@Self DruidNode node, WorkerConfig config) { return new Worker( node.getHostAndPort(), config.getIp(), config.getCapacity(), config.getVersion() ); } }, new IndexingServiceFirehoseModule(), new IndexingServiceTaskLogsModule() ); }
Source:
<code>private static boolean isClassController(Symbol.MethodSymbol methodSymbol) { SymbolMetadata parentClassOwner = methodSymbol.owner().metadata(); <START> return parentClassOwner.isAnnotatedWith("org.springframework.stereotype.Controller"); <END> }</code><technical_language>inline parentClassOwner(Metadata) variable</technical_language>

Target:
private static boolean isClassController(Symbol.MethodSymbol methodSymbol) { return methodSymbol.owner().metadata().isAnnotatedWith("org.springframework.stereotype.Controller"); }
Source:
<code>private ProducerConnectionContext init() throws JMSException, NamingException { <START> InitialContext namingContext = new InitialContext(); <END> TopicConnectionFactory tcf = (TopicConnectionFactory) namingContext.lookup( configuration.getConnectionFactoryJndiName()); ConnectionContextFactory ccf = new ConnectionContextFactory(tcf); ProducerConnectionContext producerConnectionContext = ccf.createProducerConnectionContext( new Endpoint(Endpoint.Type.TOPIC, configuration.getInventoryChangesTopicName())); return producerConnectionContext; }</code><technical_language>InitialContext close()d afer usage, leak resources</technical_language>

Target:
private void init() throws JMSException { if (producerConnectionContext == null) { producerConnectionContext = connectionContextFactory.createProducerConnectionContext( new Endpoint(Endpoint.Type.TOPIC, topicName)); } }
Source:
<code>public void update(float delta) { float animDelta = delta; if (animDelta > 0.1f) { animDelta = 0.1f; } <START> if(animDelta == 0.0f) { <END> animDelta = 0.035f; } flyIn.update(animDelta); flyOut.update(animDelta); }</code><technical_language>Trivial code style issue: space if ( - a newline blocks. Quirky float risk: comparisons get weird them, do animDelta < 0.0001f instead</technical_language>

Target:
public void update(float delta) { float animDelta = delta; if (animDelta > 0.1f) { animDelta = 0.1f; } if (animDelta < 0.0001f) { animDelta = PAUSED_ANIMATION_FRAME_TICK_TIME; } flyIn.update(animDelta); flyOut.update(animDelta); }
Source:
<code>public String toString() { <START> StringBuilder builder = new StringBuilder(filePath.toString()); <END> getPosition().ifPresent(position -> { builder.append(" ["); builder.append(position.getLine()); builder.append(':'); builder.append(position.getColumn()); builder.append(']'); }); return builder.toString(); }</code><technical_language>toString() is superfluous</technical_language>

Target:
public String toString() { return new ToStringBuilder(this) .append("file", file) .append("filePosition", filePosition) .toString(); }
Source:
<code><START> public List<String> getGlobalStoresPrefixList() throws JSONException { <END> UserAccount userAccount = getUserAccountManager().getCurrentUser(); String communityId = userAccount!=null?userAccount.getCommunityId():null; List<String> globalDBNames = DBOpenHelper.getGlobalDatabasePrefixList(context,getUserAccountManager().getCurrentUser(),communityId); return globalDBNames; }</code><technical_language>call method getGlobalStoreNames() instead</technical_language>

Target:
public List<String> getGlobalStoresPrefixList(){ UserAccount userAccount = getUserAccountManager().getCurrentUser(); String communityId = userAccount!=null?userAccount.getCommunityId():null; List<String> globalDBNames = DBOpenHelper.getGlobalDatabasePrefixList(context,getUserAccountManager().getCurrentUser(),communityId); return globalDBNames; }
Source:
<code><START> private boolean isLatestFormRecord(AndroidCommCarePlatform platform) { <END> if (formDefId != -1) { Vector<Integer> formsForOurNamespace = FormDefRecord.getFormDefIdsByJrFormId(platform.getFormDefStorage(), namespace); if (formsForOurNamespace.size() == 1) { return true; } else if (formsForOurNamespace.size() > 1) { int maxFormResourceVersion = -1; for (int i = 0; i < formsForOurNamespace.size(); i++) { FormDefRecord formDefRecordItem = platform.getFormDefStorage().read(formsForOurNamespace.get(i)); if (formDefRecordItem.getResourceVersion() > maxFormResourceVersion) { maxFormResourceVersion = formDefRecordItem.getResourceVersion(); } } FormDefRecord currentFormDefRecord = platform.getFormDefStorage().read(formDefId); return maxFormResourceVersion == currentFormDefRecord.getResourceVersion(); } } return false; }</code><technical_language>a consistency / safety perspective, I dangerous this a per-resource question this, hard in a closed-form guarantee *is* form record XMLNS. I's breakdown I determined (or a fixed number) of forms XMLNS anyway, structure this method differently return *a* valid form ID (probably below) check this one. a small, stylistic point, I right for easy mistake results in forms latest (due nested rules)</technical_language>

Target:
private boolean isLatestFormRecord(AndroidCommCarePlatform platform) { if (formDefId != -1) { return getLatestFormDefId(platform) == formDefId; } return false; }
Source:
<code>public void should_fail_with_good_message_when_vararg_has_message_containing_assertion_is_failing() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThatThrownBy(raisingException("boom")).hasMessageContaining("bam", "boom")) .withMessageContaining("Expecting:") .withMessageContaining("<\"boom\">") .withMessageContaining("<[\"bam\", \"boom\"]>").withMessageContaining("but could not find:") <START> .withMessageContaining("<[\"bam\"]>"); <END> }</code><technical_language>avoid repeating call withMessageContaining ;-) for readability put expected string a new line (expect for first)</technical_language>

Target:
public void should_fail_with_good_message_when_vararg_has_message_containing_assertion_is_failing() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThatThrownBy(raisingException("boom")).hasMessageContaining("bam") .hasMessageContainingAll("boom", "Expecting:", "<\"boom\">", "<[\"bam\", \"boom\"]>", "but could not find:", "<[\"bam\"]>")); }
Source:
<code>private static Set<String> getExternalResourceSet(Configuration config) { <START> return new HashSet<>(ConfigUtils.decodeListFromConfig(config, ExternalResourceOptions.EXTERNAL_RESOURCE_LIST, x -> x)); <END> }</code><technical_language>suggestion return new HashSet<>(config.get(ExternalResourceOptions.EXTERNAL_RESOURCE_LIST)); this work well</technical_language>

Target:
private static Set<String> getExternalResourceSet(Configuration config) { return new HashSet<>(config.get(ExternalResourceOptions.EXTERNAL_RESOURCE_LIST)); }
Source:
<code>public void shouldNotAllowToPersistNullItemsPrice() { Item saved = null; try { saved = itemRepository.save(new Item()); <START> } catch (Exception e) { <END> assertThat(saved).isNull(); assertThat(e).hasStackTraceContaining("must not be null"); } }</code><technical_language>This test green if exception is thrown, check this method: <LINK_0></technical_language>

Target:
public void shouldNotAllowToPersistNullItemsPrice() { assertThatThrownBy(() -> itemRepository.save(new Item())) .hasRootCauseInstanceOf(ConstraintViolationException.class) .hasStackTraceContaining("must not be null"); }
Source:
<code>public void shouldUnVoidAVisit() throws Exception { <START> Visit visit = service.getVisitByUuid(RestTestConstants1_9.VISIT_UUID); <END> visit = service.voidVisit(visit, "some random reason"); Assert.assertTrue(visit.isVoided()); String json = "{\"deleted\": \"false\"}"; SimpleObject response = deserialize(handle(newPostRequest(getURI() + "/" + getUuid(), json))); visit = service.getVisitByUuid(getUuid()); Assert.assertFalse(visit.isVoided()); Assert.assertEquals("false", PropertyUtils.getProperty(response, "voided").toString()); }</code><technical_language>try void existing visit in of datasets for VisitServiceTest in core platform</technical_language>

Target:
public void shouldUnVoidAVisit() throws Exception { Visit visit = service.getVisitByUuid(RestTestConstants1_9.VISIT_UUID); service.voidVisit(visit, "some random reason"); visit = service.getVisitByUuid(RestTestConstants1_9.VISIT_UUID); Assert.assertTrue(visit.isVoided()); String json = "{\"deleted\": \"false\"}"; SimpleObject response = deserialize(handle(newPostRequest(getURI() + "/" + getUuid(), json))); visit = service.getVisitByUuid(getUuid()); Assert.assertFalse(visit.isVoided()); Assert.assertEquals("false", PropertyUtils.getProperty(response, "voided").toString()); }
Source:
<code>public Tool getToolFromNamespaceAndRepo(final String organization, final String repository) { <START> throw new CustomWebApplicationException("Unsupported operation, only Quay.io is supported for now", HttpStatus.SC_BAD_REQUEST); <END> }</code><technical_language>nice if this string a constant. if add support for DockerHub manual, update string in location</technical_language>

Target:
public Tool getToolFromNamespaceAndRepo(final String organization, final String repository) { return unsupportedOperation(); }
Source:
<code>protected boolean modifierFunction(ImmutableBytesWritable ptr, int length, int offset, byte[] arrayBytes, PDataType baseType, int arrayLength, Integer maxLength, Expression arrayExp) { SortOrder sortOrder = arrayExp.getSortOrder(); if (ptr.getLength() == 0 || arrayBytes.length == 0) { ptr.set(arrayBytes, offset, length); return true; } PhoenixArray array = (PhoenixArray) getDataType().toObject(arrayBytes, offset, length, getDataType(), sortOrder, <START> maxLength, null); <END> Object toCompare = baseType.toObject(ptr, sortOrder); if(baseType.isFixedWidth()) { toCompare = baseType.pad(toCompare, array.getMaxLength()); } int dimensions = array.getDimensions(); List<Object> values = new ArrayList<>(); for (int i = 0; i < dimensions; i++) { Object element = array.getElement(i); if (element != null && element.equals(toCompare) || (element.getClass().isArray() && ArrayUtils.isEquals(element, toCompare))) { if (getDataType().isFixedWidth()) { values.add(null); } } else { values.add(element); } } PhoenixArray newArray = PArrayDataType.instantiatePhoenixArray(baseType, values.toArray(new Object[values.size()])); if (baseType.isFixedWidth() && maxLength != null && maxLength != newArray.getMaxLength()) { newArray = new PhoenixArray(newArray, maxLength); } ptr.set(getDataType().toBytes(newArray, sortOrder)); return true; }</code><technical_language>This potentially a lot of memory for large arrays. hit deserialization cost for element. alternative pass binary array data serialize values go, skipping element if equal removed</technical_language>

Target:
protected boolean modifierFunction(ImmutableBytesWritable ptr, int length, int offset, byte[] arrayBytes, PDataType baseType, int arrayLength, Integer maxLength, Expression arrayExp) { SortOrder sortOrder = arrayExp.getSortOrder(); if (ptr.getLength() == 0 || arrayBytes.length == 0) { ptr.set(arrayBytes, offset, length); return true; } PArrayDataTypeEncoder arrayDataTypeEncoder = new PArrayDataTypeEncoder(baseType, sortOrder); if (getRHSBaseType().equals(PChar.INSTANCE)) { int unpaddedCharLength = StringUtil.getUnpaddedCharLength(ptr.get(), ptr.getOffset(), ptr.getLength(), sortOrder); ptr.set(ptr.get(), offset, unpaddedCharLength); } for (int arrayIndex = 0; arrayIndex < arrayLength; arrayIndex++) { ImmutableBytesWritable ptr2 = new ImmutableBytesWritable(arrayBytes, offset, length); PArrayDataTypeDecoder.positionAtArrayElement(ptr2, arrayIndex, baseType, maxLength); if (baseType.compareTo(ptr2, sortOrder, ptr, sortOrder, baseType) != 0) { arrayDataTypeEncoder.appendValue(ptr2.get(), ptr2.getOffset(), ptr2.getLength()); } } ptr.set(arrayDataTypeEncoder.encode()); return true; }
Source:
<code>private void testStudentProfile(StudentProfile studentProfile) { assertNotNull(studentProfile); assertNotNull(studentProfile.getPictureUrl()); assertEquals(pictureUrl, studentProfile.getPictureUrl()); assertEquals(inputStudent.name, studentProfile.getName()); assertEquals(inputStudentProfile.shortName, studentProfile.getShortName()); <START> assertEquals(inputStudentProfile.gender.name(), studentProfile.getGender().toString()); <END> assertEquals(inputStudentProfile.email, studentProfile.getEmail()); assertEquals(inputStudentProfile.institute, studentProfile.getInstitute()); assertEquals(inputStudentProfile.nationality, studentProfile.getNationality()); assertEquals(inputStudentProfile.moreInfo, studentProfile.getMoreInfo()); }</code><technical_language>is this necessary</technical_language>

Target:
private void testStudentProfile(StudentProfile studentProfile) { assertNotNull(studentProfile); assertNotNull(studentProfile.getPictureUrl()); assertEquals(pictureUrl, studentProfile.getPictureUrl()); assertEquals(inputStudent.name, studentProfile.getName()); assertEquals(inputStudentProfile.shortName, studentProfile.getShortName()); assertEquals(inputStudentProfile.gender, studentProfile.getGender()); assertEquals(inputStudentProfile.email, studentProfile.getEmail()); assertEquals(inputStudentProfile.institute, studentProfile.getInstitute()); assertEquals(inputStudentProfile.nationality, studentProfile.getNationality()); assertEquals(inputStudentProfile.moreInfo, studentProfile.getMoreInfo()); }
Source:
<code>public void testPushImageToPrivateAuthedRegistryWithoutAuth() throws Exception { final String containerId = startAuthedRegistry(client); final DefaultDockerClient client = DefaultDockerClient.fromEnv().build(); final String dockerDirectory = Resources.getResource("dockerDirectory").getPath(); client.build(Paths.get(dockerDirectory), LOCAL_IMAGE); boolean correctExceptionThrown = false; try { client.push(LOCAL_IMAGE); } catch (ImagePushFailedException e) { if (e.getMessage().contains("no basic auth credentials")) { correctExceptionThrown = true; } } assertTrue(correctExceptionThrown); <START> stopAndRemoveContainer(client, containerId); <END> }</code><technical_language>if moved call stopAndRemoveContainer a @After method, this part correctExceptionThrown done</technical_language>

Target:
public void testPushImageToPrivateAuthedRegistryWithoutAuth() throws Exception { registryContainerId = startAuthedRegistry(client); final DefaultDockerClient client = DefaultDockerClient.fromEnv().build(); final String dockerDirectory = Resources.getResource("dockerDirectory").getPath(); client.build(Paths.get(dockerDirectory), LOCAL_IMAGE); exception.expect(ImagePushFailedException.class); exception.expectMessage("no basic auth credentials"); client.push(LOCAL_IMAGE); }
Source:
<code>public void invalidPropertiesFormat() { VmDevice device = new VmDevice(); device.setType(VmDeviceGeneralType.DISK); device.setCustomProperties("bootable"); DevicePropertiesUtils utils = mockDevicePropertiesUtils(); List<ValidationError> errors = utils.validateDeviceProperties(Version.v3_3, device); assertFalse(errors.isEmpty()); <START> assertTrue(errors.get(0).getReason() == ValidationFailureReason.SYNTAX_ERROR); <END> }</code><technical_language>prefer assertEquals</technical_language>

Target:
public void invalidPropertiesFormat() { VmDevice device = new VmDevice(); device.setType(VmDeviceGeneralType.DISK); device.setCustomProperties("bootable"); DevicePropertiesUtils utils = mockDevicePropertiesUtils(); List<ValidationError> errors = utils.validateDeviceProperties(Version.v3_3, device); assertFalse(errors.isEmpty()); assertEquals(ValidationFailureReason.SYNTAX_ERROR, errors.get(0).getReason()); }
Source:
<code>public void checkIndentation() { <START> final DetailAST firstChild = getMainAst().getFirstChild(); <END> final boolean isSwitchExpressionLambda = firstChild == null; if (!isSwitchExpressionLambda && getLineStart(firstChild) == expandedTabsColumnNo(firstChild)) { final int firstChildColumnNo = expandedTabsColumnNo(firstChild); final IndentLevel level = getIndent(); if (isNonAcceptableIndent(firstChildColumnNo, level)) { isLambdaCorrectlyIndented = false; logError(firstChild, "arguments", firstChildColumnNo, level); } } final int mainAstColumnNo = expandedTabsColumnNo(getMainAst()); final boolean isLineWrappedLambda = mainAstColumnNo == getLineStart(getMainAst()); if (isLineWrappedLambda) { checkLineWrappedLambda(isSwitchExpressionLambda, mainAstColumnNo); } }</code><technical_language>getMainAst() is called times function. extract out in a final variable</technical_language>

Target:
public void checkIndentation() { final DetailAST mainAst = getMainAst(); final DetailAST firstChild = mainAst.getFirstChild(); final boolean isSwitchRuleLambda = firstChild == null; if (!isSwitchRuleLambda && getLineStart(firstChild) == expandedTabsColumnNo(firstChild)) { final int firstChildColumnNo = expandedTabsColumnNo(firstChild); final IndentLevel level = getIndent(); if (isNonAcceptableIndent(firstChildColumnNo, level)) { isLambdaCorrectlyIndented = false; logError(firstChild, "arguments", firstChildColumnNo, level); } } final int mainAstColumnNo = expandedTabsColumnNo(mainAst); final boolean isLineWrappedLambda = mainAstColumnNo == getLineStart(mainAst); if (isLineWrappedLambda) { checkLineWrappedLambda(isSwitchRuleLambda, mainAstColumnNo); } }
Source:
<code>private String getType(Contentlet contentlet) { <START> return contentlet != null && contentlet.isHost() ? SITE_EVENT_SUFFIX : contentlet.getStructure().getName().replace(" ", "_").toUpperCase(); <END> }</code><technical_language>safer I ask if contentlet.getStructure().getName() is null</technical_language>

Target:
private String getType(Contentlet contentlet) { if (contentlet.isHost()){ return SITE_EVENT_SUFFIX; }else if (contentlet.getStructure() != null && contentlet.getStructure().getName() != null){ return contentlet.getStructure().getName().replace(" ", "_").toUpperCase(); }else{ throw new IllegalStateException("The Content type is null"); } }
Source:
<code>private void replaceEnvironmentVariables(JsonNode node) { final Iterator<Entry<String, JsonNode>> fields = node.fields(); while (fields.hasNext()) { final Entry<String, JsonNode> field = fields.next(); final String fieldName = field.getKey(); final String textValue = field.getValue().textValue(); if (!Strings.isNullOrEmpty(textValue)) { <START> final Pattern pattern = Pattern.compile("\\$\\{(\\w+)\\}"); <END> final Matcher matcher = pattern.matcher(textValue); if (matcher.find()) { final String envVariableName = matcher.group(1) == null ? matcher.group(2) : matcher.group(1); final String envVariableValue = System.getenv(envVariableName); if (!Strings.isNullOrEmpty(envVariableValue)) { ((ObjectNode) node).put(fieldName, envVariableValue); } } } } for (JsonNode child : node) { replaceEnvironmentVariables(child); } }</code><technical_language>Move static const field</technical_language>

Target:
private void replaceEnvironmentVariables(JsonNode node) { final Iterator<Entry<String, JsonNode>> fields = node.fields(); while (fields.hasNext()) { final Entry<String, JsonNode> field = fields.next(); final String fieldName = field.getKey(); final String textValue = field.getValue().textValue(); if (!Strings.isNullOrEmpty(textValue)) { final Matcher matcher = ENV_VAR_PATTERN.matcher(textValue); if (matcher.matches()) { final String envVariableName = matcher.group(1); if (System.getenv().containsKey(envVariableName)) { final String envVariableValue = System.getenv(envVariableName); ((ObjectNode) node).put(fieldName, envVariableValue); } } } } for (JsonNode child : node) { replaceEnvironmentVariables(child); } }
Source:
<code>public static LocalPaxosComponents createWithBlockingMigration( TimelockPaxosMetrics metrics, PaxosUseCase paxosUseCase, Path legacyLogDirectory, DataSource sqliteDataSource, UUID leaderUuid, boolean canCreateNewClients) { LocalPaxosComponents components = new LocalPaxosComponents(metrics, paxosUseCase, legacyLogDirectory, sqliteDataSource, leaderUuid, canCreateNewClients); Path legacyClientDir = paxosUseCase.logDirectoryRelativeToDataDirectory(legacyLogDirectory); PersistentNamespaceLoader namespaceLoader = new DiskNamespaceLoader(legacyClientDir); namespaceLoader.getAllPersistedNamespaces().forEach(components::getOrCreateComponents); components.getOrCreateComponents(PaxosUseCase.PSEUDO_LEADERSHIP_CLIENT); <START> return components; <END> }</code><technical_language>this creates splitting log upfront, migration in creation of (but remember state, copying data more once)</technical_language>

Target:
public static LocalPaxosComponents createWithBlockingMigration( TimelockPaxosMetrics metrics, PaxosUseCase paxosUseCase, Path legacyLogDirectory, DataSource sqliteDataSource, UUID leaderUuid, boolean canCreateNewClients) { LocalPaxosComponents components = new LocalPaxosComponents(metrics, paxosUseCase, legacyLogDirectory, sqliteDataSource, leaderUuid, canCreateNewClients); Path legacyClientDir = paxosUseCase.logDirectoryRelativeToDataDirectory(legacyLogDirectory); PersistentNamespaceLoader namespaceLoader = new DiskNamespaceLoader(legacyClientDir); namespaceLoader.getAllPersistedNamespaces().forEach(components::getOrCreateComponents); return components; }
Source:
<code>public void addType(String typeId) { entityHelper.checkEntityTypeExists(typeId); EntityType entityType = dataService.getEntityType(entityHelper.getEntityTypeIdFromType(typeId)); if (!mutableAclClassService.getAclClassTypes().contains(typeId)) { mutableAclClassService.createAclClass(typeId, EntityIdentityUtils.toIdType(entityType)); dataService .findAll(entityType.getId()) .forEach( entity -> { try { mutableAclService.createAcl(new EntityIdentity(entity)); } catch (AlreadyExistsException e) { <START> LOG.warn( <END> "Acl for entity '{}' of type '{}' already exists", entity.getIdValue(), entityType.getIdValue()); } }); } else { throw new AclClassAlreadyExistsException(typeId); } }</code><technical_language>this result in exception for callee</technical_language>

Target:
public void addType(String typeId) { entityHelper.checkEntityTypeExists(typeId); entityHelper.checkIsNotSystem(typeId); EntityType entityType = dataService.getEntityType(entityHelper.getEntityTypeIdFromType(typeId)); if (mutableAclClassService.getAclClassTypes().contains(typeId)) { throw new AclClassAlreadyExistsException(typeId); } mutableAclClassService.createAclClass(typeId, EntityIdentityUtils.toIdType(entityType)); dataService .findAll(entityType.getId()) .forEach( entity -> { try { mutableAclService.createAcl(new EntityIdentity(entity)); } catch (AlreadyExistsException e) { throw new AclAlreadyExistsException(typeId, entityType.getId()); } }); }
Source:
<code>private void loadFromCompilation() { List<Section> sections = new ArrayList<>(); <START> sections.add(new Section()); <END> String normalizedTitle = OfflineManager.instance().getNormalizedTitle(model.getTitle().getDisplayText()); PageTitle newTitle = TextUtils.isEmpty(normalizedTitle) ? model.getTitle() : new PageTitle(normalizedTitle, model.getTitle().getWikiSite()); Page page = new Page(newTitle, sections, new PageProperties(newTitle)); model.setPage(page); editHandler.setPage(model.getPage()); leadImagesHandler.beginLayout(new LeadImagesHandler.OnLeadImageLayoutListener() { @Override public void onLayoutComplete(int sequence) { if (!fragment.isAdded() || !sequenceNumber.inSync(sequence)) { return; } toolbarHideHandler.setFadeEnabled(leadImagesHandler.isLeadImageEnabled()); loadContentsFromCompilation(); } }, sequenceNumber.get()); if (webView.getVisibility() != View.VISIBLE) { webView.setVisibility(View.VISIBLE); } refreshView.setRefreshing(false); if (fragment.callback() != null) { fragment.callback().onPageUpdateProgressBar(true, true, 0); } }</code><technical_language>here? Dummy lead section</technical_language>

Target:
private void loadFromCompilation() { String normalizedTitle = OfflineManager.instance().getNormalizedTitle(model.getTitle().getDisplayText()); PageTitle newTitle = TextUtils.isEmpty(normalizedTitle) ? model.getTitle() : new PageTitle(normalizedTitle, model.getTitle().getWikiSite()); Page page = new Page(newTitle, new ArrayList<Section>(), new PageProperties(newTitle)); model.setPage(page); editHandler.setPage(model.getPage()); leadImagesHandler.beginLayout(new LeadImagesHandler.OnLeadImageLayoutListener() { @Override public void onLayoutComplete(int sequence) { if (!fragment.isAdded() || !sequenceNumber.inSync(sequence)) { return; } toolbarHideHandler.setFadeEnabled(leadImagesHandler.isLeadImageEnabled()); loadContentsFromCompilation(); } }, sequenceNumber.get()); if (webView.getVisibility() != View.VISIBLE) { webView.setVisibility(View.VISIBLE); } refreshView.setRefreshing(false); if (fragment.callback() != null) { fragment.callback().onPageUpdateProgressBar(true, true, 0); } }
Source:
<code>public int run() throws Exception { <START> dbInjector = createDbInjector(MULTI_USER); <END> manager.add(dbInjector); manager.start(); dbInjector.injectMembers(this); Project.NameKey project = new Project.NameKey(projectName); Repository git = gitManager.openRepository(project); try { PrologJar jarMaker = new PrologJar(config, site, git); return jarMaker.run() ? 0 : 1; } finally { git.close(); } }</code><technical_language>s/MULTI_USER/SINGLE_USER/</technical_language>

Target:
public int run() throws Exception { dbInjector = createDbInjector(SINGLE_USER); manager.add(dbInjector); manager.start(); dbInjector.injectMembers(this); Project.NameKey project = new Project.NameKey(projectName); Repository git = gitManager.openRepository(project); try { PrologJar jarMaker = new PrologJar(config, site, git); jarMaker.run(); return 0; } finally { git.close(); } }
Source:
<code>public MatchAttributeWithValue(String attributeName, String attributeRegex) { super("match attribute"); this.attributeName = attributeName; <START> this.attributeRegex = Pattern.compile(attributeRegex, DOTALL); <END> }</code><technical_language>DOTALL? I know, needed support multiline Strings, happen attribute values</technical_language>

Target:
public MatchAttributeWithValue(String attributeName, String attributeRegex) { super("match attribute"); this.attributeName = attributeName; this.attributeRegex = Pattern.compile(attributeRegex); }
Source:
<code>protected Void call() throws Volume.VolumeException, InterruptedException { try { vault.lock(false); } catch (Volume.VolumeException e) { LOG.debug("Regular lock of failed.", vault.getDisplayName(), e); var decision = askUserForAction(); switch (decision) { case FORCE -> vault.lock(true); case CANCEL -> cancel(false); default -> throw new IllegalArgumentException("Unknown decision " + decision); } } <START> <END> return null; }</code><technical_language>suggestion</technical_language>

Target:
protected Void call() throws Volume.VolumeException, InterruptedException { try { vault.lock(false); } catch (Volume.VolumeException e) { LOG.debug("Regular lock of failed.", vault.getDisplayName(), e); var decision = askUserForAction(); switch (decision) { case FORCE -> vault.lock(true); case CANCEL -> cancel(false); } } return null; }
Source:
<code>public GroupRest getAdminGroup(@Nullable HttpServletRequest request, UUID communityId, @Nullable Pageable optionalPageable, Projection projection) { try { Context context = obtainContext(); Community community = communityService.find(context, communityId); if (community == null) { throw new ResourceNotFoundException("No such community: " + communityId); } Group administrators = community.getAdministrators(); <START> if (!authorizeService.isAdmin(context) && !authorizeService.authorizeActionBoolean(context, community, <END> Constants.ADMIN, true)) { throw new AccessDeniedException("The current user was not allowed to retrieve the AdminGroup for" + " community: " + communityId); } if (administrators == null) { return null; } return converter.toRest(administrators, projection); } catch (SQLException e) { throw new RuntimeException(e); } }</code><technical_language>here, move authorization check</technical_language>

Target:
public GroupRest getAdminGroup(@Nullable HttpServletRequest request, UUID communityId, @Nullable Pageable optionalPageable, Projection projection) { try { Context context = obtainContext(); Community community = communityService.find(context, communityId); if (community == null) { throw new ResourceNotFoundException("No such community: " + communityId); } try { AuthorizeUtil.authorizeManageAdminGroup(context, community); } catch (AuthorizeException e) { throw new AccessDeniedException("The current user was not allowed to retrieve the AdminGroup for" + " community: " + communityId); } Group administrators = community.getAdministrators(); if (administrators == null) { return null; } return converter.toRest(administrators, projection); } catch (SQLException e) { throw new RuntimeException(e); } }