auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void cloneTemplate() { Snapshot snapshot = getSelectedItem(); if (snapshot == null) { return; } if (getWindow() != null) { return; } VM selectedVm = getEntity(); final UnitVmModel model = new UnitVmModel(new NewTemplateVmModelBehavior(), this); setWindow(model); model.startProgress(null); model.getVmType().setSelectedItem(selectedVm.getVmType()); model.getIsHighlyAvailable().setEntity(selectedVm.getStaticData().isAutoStartup()); AsyncDataProvider.getInstance().getVmConfigurationBySnapshot(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { NewTemplateVmModelBehavior behavior = (NewTemplateVmModelBehavior) model.getBehavior(); VM vm = (VM) returnValue; behavior.setVm(vm); model.setTitle(ConstantsManager.getInstance().getConstants().newTemplateTitle()); <START> model.setHelpTag(HelpTag.new_template); <END> model.setHashName("new_template"); model.setIsNew(true); model.setCustomPropertiesKeysList(AsyncDataProvider.getInstance().getCustomPropertiesList()); model.initialize(VmSnapshotListModel.this.getSystemTreeSelectedItem()); model.getCommands().add( new UICommand("OnNewTemplate", VmSnapshotListModel.this) .setTitle(ConstantsManager.getInstance().getConstants().ok()) .setIsDefault(true)); model.getCommands().add(UICommand.createCancelUiCommand("Cancel", VmSnapshotListModel.this)); model.stopProgress(); } }), snapshot.getId()); }</code><technical_language>this definithion contains this: "VMs Tab > Template" is correct for this. Please add a new entry HelpTag correct path</technical_language>

Target:
private void cloneTemplate() { Snapshot snapshot = getSelectedItem(); if (snapshot == null) { return; } if (getWindow() != null) { return; } VM selectedVm = getEntity(); final UnitVmModel model = new UnitVmModel(new NewTemplateVmModelBehavior(), this); setWindow(model); model.startProgress(null); model.getVmType().setSelectedItem(selectedVm.getVmType()); model.getIsHighlyAvailable().setEntity(selectedVm.getStaticData().isAutoStartup()); AsyncDataProvider.getInstance().getVmConfigurationBySnapshot(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { NewTemplateVmModelBehavior behavior = (NewTemplateVmModelBehavior) model.getBehavior(); VM vm = (VM) returnValue; behavior.setVm(vm); model.setTitle(ConstantsManager.getInstance().getConstants().newTemplateTitle()); model.setHelpTag(HelpTag.clone_template_from_snapshot); model.setHashName("clone_template_from_snapshot"); model.setIsNew(true); model.setCustomPropertiesKeysList(AsyncDataProvider.getInstance().getCustomPropertiesList()); model.initialize(VmSnapshotListModel.this.getSystemTreeSelectedItem()); model.getCommands().add( new UICommand("OnNewTemplate", VmSnapshotListModel.this) .setTitle(ConstantsManager.getInstance().getConstants().ok()) .setIsDefault(true)); model.getCommands().add(UICommand.createCancelUiCommand("Cancel", VmSnapshotListModel.this)); model.stopProgress(); } }), snapshot.getId()); }
Source:
<code>private boolean mediateMessage(SequenceMediator sequenceMediator, MessageContext synCtx) { try { return sequenceMediator.mediate(synCtx); } catch (SynapseException syne) { if (!synCtx.getFaultStack().isEmpty()) { <START> log.warn("Executing fault handler due to exception encountered" + syne); <END> ((FaultHandler) synCtx.getFaultStack().pop()).handleFault(synCtx, syne); } else { log.warn("Exception encountered but no fault handler found - message dropped"); } } catch (Exception e) { String msg = "Unexpected error occurred executing the Target"; log.error(msg, e); if (synCtx.getServiceLog() != null) { synCtx.getServiceLog().error(msg, e); } if (!synCtx.getFaultStack().isEmpty()) { log.warn("Executing fault handler due to exception encountered"); ((FaultHandler) synCtx.getFaultStack().pop()).handleFault(synCtx, e); } else { log.warn("Exception encountered but no fault handler found - message dropped"); } } return true; }</code><technical_language>modify log.warn("Executing fault handler due exception encountered" , syne);</technical_language>

Target:
private boolean mediateMessage(SequenceMediator sequenceMediator, MessageContext synCtx) { try { return sequenceMediator.mediate(synCtx); } catch (SynapseException syne) { if (!synCtx.getFaultStack().isEmpty()) { log.warn("Executing fault handler due to exception encountered", syne); ((FaultHandler) synCtx.getFaultStack().pop()).handleFault(synCtx, syne); } else { log.warn("Exception encountered but no fault handler found - message dropped"); } } catch (Exception e) { String msg = "Unexpected error occurred executing the Target"; log.error(msg, e); if (synCtx.getServiceLog() != null) { synCtx.getServiceLog().error(msg, e); } if (!synCtx.getFaultStack().isEmpty()) { log.warn("Executing fault handler due to exception encountered"); ((FaultHandler) synCtx.getFaultStack().pop()).handleFault(synCtx, e); } else { log.warn("Exception encountered but no fault handler found - message dropped"); } } return true; }
Source:
<code>private String getTemplateDirectory(String template) { <START> String templateDirectoryName; <END> switch (infrastructure) { case openshift: case k8s: templateDirectoryName = Infrastructure.k8s.toString().toLowerCase(); break; case docker: default: templateDirectoryName = infrastructure.toString().toLowerCase(); } return String.format("/templates/factory/%s/%s", templateDirectoryName, template); }</code><technical_language>simplified: private String getTemplateDirectory(String template) { String templateDirectoryName = infrastructure.toString().toLowerCase(); if (infrastructure == k8s){ templateDirectoryName = k8s.toString().toLowerCase(); } return format("/templates/factory/%s/%s", templateDirectoryName, template);</technical_language>

Target:
private String getTemplateDirectory(String template) { String templateDirectoryName; switch (infrastructure) { case OSIO: templateDirectoryName = Infrastructure.OPENSHIFT.toString().toLowerCase(); break; default: templateDirectoryName = infrastructure.toString().toLowerCase(); } return String.format("/templates/factory/%s/%s", templateDirectoryName, template); }
Source:
<code>protected DiskImage getDiskImage() { if (_diskImage == null) { DiskImage tmpImage = getImage(); <START> _diskImage = (tmpImage == null || tmpImage.getVmEntityType() == VmEntityType.TEMPLATE)?(null):(tmpImage); <END> } return _diskImage; }</code><technical_language>this logic is correct, DiskImage is linked template is in fact a DiskImage instance. way, IImage anymore this call removed duplicate field (_diskImage) it.</technical_language>

Target:
protected DiskImage getDiskImage() { if (_diskImage == null) { _diskImage = getImage(); } return _diskImage; }
Source:
<code>public ConfigAccessor(String zkAddress) { _usesExternalZkClient = false; <START> if (Boolean.parseBoolean(System.getProperty(SystemPropertyKeys.MULTI_ZK_ENABLED))) { <END> try { _zkClient = new FederatedZkClient( new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder().build(), new RealmAwareZkClient.RealmAwareZkClientConfig()); return; } catch (IOException | InvalidRoutingDataException | IllegalStateException e) { throw new HelixException("Failed to create ConfigAccessor!", e); } } _zkClient = SharedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddress), new HelixZkClient.ZkClientConfig().setZkSerializer(new ZNRecordSerializer())); }</code><technical_language>Nit: allow users set upper case "TRUE" honor true. I getBoolean() restrict true if if string is lowercase "true"</technical_language>

Target:
public ConfigAccessor(String zkAddress) { _usesExternalZkClient = false; if (Boolean.parseBoolean(System.getProperty(SystemPropertyKeys.MULTI_ZK_ENABLED))) { try { _zkClient = new FederatedZkClient( new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder().build(), new RealmAwareZkClient.RealmAwareZkClientConfig() .setZkSerializer(new ZNRecordSerializer())); return; } catch (IOException | InvalidRoutingDataException | IllegalStateException e) { throw new HelixException("Failed to create ConfigAccessor!", e); } } _zkClient = SharedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddress), new HelixZkClient.ZkClientConfig().setZkSerializer(new ZNRecordSerializer())); }
Source:
<code>public Boolean call() throws InterruptedException { CallContext callContext = bulkOutputCallerImpl.getCallContextQueue().poll(); continueCalling = (callContext == null)? false:bulkOutputCallerImpl.processOutput(callContext); if(continueCalling) { bulkOutputCallerImpl.getCallContextQueue().put(callContext); submitTask(this); } <START> else if(getPhase() == WorkPhase.COMPLETED && bulkOutputCallerImpl.getCallContextQueue().isEmpty()) { <END> getCallerThreadPoolExecutor().shutdown(); } return true; }</code><technical_language>bulk exec caller, remove test phase altogether line 247 test queue is empty</technical_language>

Target:
public Boolean call() throws InterruptedException { CallContext callContext = bulkOutputCallerImpl.getCallContextQueue().poll(); continueCalling = (callContext == null)? false:bulkOutputCallerImpl.processOutput(callContext); if(continueCalling) { bulkOutputCallerImpl.getCallContextQueue().put(callContext); submitTask(this); } else if(bulkOutputCallerImpl.getCallContextQueue().isEmpty() && getCallerThreadPoolExecutor().getActiveCount() == 0) { getCallerThreadPoolExecutor().shutdown(); } return true; }
Source:
<code>public void init() throws DBException { synchronized(RocksDBClient.class) { if(rocksDb == null) { <START> rocksdbDir = Paths.get(getProperties().getProperty(PROP_ROCKSDB_DIR)); <END> System.out.println("RocksDB data dir: " + rocksdbDir); try { rocksDb = initRocksDB(); } catch (final IOException | RocksDBException e) { throw new DBException(e); } } references++; } }</code><technical_language>casing inconsistency: rocksDbDir</technical_language>

Target:
public void init() throws DBException { synchronized(RocksDBClient.class) { if(rocksDb == null) { rocksDbDir = Paths.get(getProperties().getProperty(PROPERTY_ROCKSDB_DIR)); LOGGER.info("RocksDB data dir: " + rocksDbDir); try { rocksDb = initRocksDB(); } catch (final IOException | RocksDBException e) { throw new DBException(e); } } references++; } }
Source:
<code>protected List<String> getRequiredBundles() { <START> String orgEclipseUiPluginId = getProjectInfo().isRapOption() ? "org.eclipse.rap.ui;resolution:=optional" : "org.eclipse.ui" ; <END> String orgEclipseEmfParsleyViewsPluginId = getProjectInfo().isRapOption() ? "org.eclipse.emf.parsley.rap.views;resolution:=optional" : EmfParsleyViewsActivator.PLUGIN_ID ; return Lists.newArrayList( "org.eclipse.core.runtime", orgEclipseUiPluginId, orgEclipseEmfParsleyViewsPluginId, "org.eclipse.xtext.xbase.lib"); }</code><technical_language>in case "RAP" button is selected need put .ui RCP bundles optional requirements, rap bundles, compile in RCP environment. Summarizing: - default is adding .ui bundles (NON optional) - RAP is selected, add .ui .rap.ui bundles optional</technical_language>

Target:
protected List<String> getRequiredBundles() { List<String> requiredBundles = Lists.newArrayList("org.eclipse.core.runtime"); if (getProjectInfo().isRapOption()) { requiredBundles.addAll( Lists.newArrayList( "org.eclipse.ui;resolution:=optional", "org.eclipse.rap.ui;resolution:=optional", EmfParsleyViewsActivator.PLUGIN_ID+";resolution:=optional", "org.eclipse.emf.parsley.rap.views;resolution:=optional") ); } else { requiredBundles.addAll( Lists.newArrayList( "org.eclipse.ui", EmfParsleyViewsActivator.PLUGIN_ID) ); } requiredBundles.add("org.eclipse.xtext.xbase.lib"); return requiredBundles; }
Source:
<code>public HeaderExchangeClient(Client client, boolean needHeartbeat) { <START> if (client == null) { <END> throw new IllegalArgumentException("client == null"); } this.client = client; this.channel = new HeaderExchangeChannel(client); String dubbo = client.getUrl().getParameter(Constants.DUBBO_VERSION_KEY); this.heartbeat = client.getUrl().getParameter(Constants.HEARTBEAT_KEY, dubbo != null && dubbo.startsWith("1.0.") ? Constants.DEFAULT_HEARTBEAT : 0); this.idleTimeout = client.getUrl().getParameter(Constants.HEARTBEAT_TIMEOUT_KEY, heartbeat * 3); if (idleTimeout < heartbeat * 2) { throw new IllegalStateException("idleTimeout < heartbeatInterval * 2"); } if (needHeartbeat) { long tickDuration = calculateLeastDuration(heartbeat); idleCheckTimer = new HashedWheelTimer(new NamedThreadFactory("dubbo-client-idleCheck", true), tickDuration, TimeUnit.MILLISECONDS, Constants.TICKS_PER_WHEEL); startIdleCheckTimer(); } }</code><technical_language>replace Assert.notNull(client, "Client null"); dubbo a util for this</technical_language>

Target:
public HeaderExchangeClient(Client client, boolean needHeartbeat) { Assert.notNull(client, "Client can't be null"); this.client = client; this.channel = new HeaderExchangeChannel(client); String dubbo = client.getUrl().getParameter(Constants.DUBBO_VERSION_KEY); this.heartbeat = client.getUrl().getParameter(Constants.HEARTBEAT_KEY, dubbo != null && dubbo.startsWith("1.0.") ? Constants.DEFAULT_HEARTBEAT : 0); this.idleTimeout = client.getUrl().getParameter(Constants.HEARTBEAT_TIMEOUT_KEY, heartbeat * 3); if (idleTimeout < heartbeat * 2) { throw new IllegalStateException("idleTimeout < heartbeatInterval * 2"); } if (needHeartbeat) { startIdleCheckTask(); } }
Source:
<code>private static FlatMapFunction<ReadShard, Tuple2<AssemblyRegion, SimpleInterval>> shardsToAssemblyRegions( final AuthHolder authHolder, final Broadcast<ReferenceMultiSource> reference, final Broadcast<HaplotypeCallerArgumentCollection> hcArgsBroadcast, final ShardingArgumentCollection assemblyArgs, final SAMFileHeader header) { return shard -> { final ReferenceMultiSource referenceMultiSource = reference.value(); final ReferenceMultiSourceToReferenceDataSourceAdaptor refDataSource = new ReferenceMultiSourceToReferenceDataSourceAdaptor(referenceMultiSource, authHolder); final ReferenceContext refContext = new ReferenceContext(refDataSource, shard.getPaddedInterval()); <START> final ReferenceMultiSourceToReferenceSequenceFileAdaptor referenceReader = new ReferenceMultiSourceToReferenceSequenceFileAdaptor(reference.getValue(), authHolder); <END> final FeatureContext features = new FeatureContext(); final Iterable<AssemblyRegion> assemblyRegions = AssemblyRegion.createFromReadShard( shard, header, refContext, features, new HaplotypeCallerEngine(hcArgsBroadcast.value(), header, referenceReader), assemblyArgs.minAssemblyRegionSize, assemblyArgs.maxAssemblyRegionSize, assemblyArgs.assemblyRegionPadding, assemblyArgs.activeProbThreshold, assemblyArgs.maxProbPropagationDistance); return StreamSupport.stream(assemblyRegions.spliterator(), false) .map( a -> new Tuple2<>(a, shard.getInterval())) .collect(Collectors.toList()); }; }</code><technical_language>reference.getValue() stored in referenceMultiSource reason get</technical_language>

Target:
private static FlatMapFunction<Iterator<Shard<GATKRead>>, Tuple2<AssemblyRegion, SimpleInterval>> shardsToAssemblyRegions( final AuthHolder authHolder, final Broadcast<ReferenceMultiSource> reference, final Broadcast<HaplotypeCallerArgumentCollection> hcArgsBroadcast, final ShardingArgumentCollection assemblyArgs, final SAMFileHeader header) { return shards -> { final ReferenceMultiSource referenceMultiSource = reference.value(); final ReferenceMultiSourceAdapter referenceSource = new ReferenceMultiSourceAdapter(referenceMultiSource, authHolder); final HaplotypeCallerEngine hcEngine = new HaplotypeCallerEngine(hcArgsBroadcast.value(), header, referenceSource); return iteratorToStream(shards).flatMap(shardToRegion(assemblyArgs, header, referenceSource, hcEngine)).iterator(); }; }
Source:
<code>private void testNonHealthCheckRequest(HttpMethod httpMethod, String uri) throws IOException { EmbeddedChannel channel = createChannel(); Random random = new Random(); HttpHeaders headers = new DefaultHttpHeaders(); headers.add(HttpHeaders.Names.CONTENT_LENGTH, new Random().nextLong()); String location = UtilsTest.getRandomString(60); int size = random.nextInt(10000); if (httpMethod == HttpMethod.POST) { headers.add(RestUtils.Headers.LOCATION, location); headers.add(RestUtils.Headers.BLOB_SIZE, size); } channel.writeInbound(RestTestUtils.createRequest(httpMethod, uri, headers)); channel.writeInbound(new DefaultLastHttpContent()); FullHttpResponse response = (FullHttpResponse) channel.readOutbound(); HttpResponseStatus responseStatus = null; if (httpMethod == HttpMethod.POST) { responseStatus = HttpResponseStatus.CREATED; } else if (httpMethod == HttpMethod.GET) { responseStatus = HttpResponseStatus.OK; } else if (httpMethod == HttpMethod.DELETE) { responseStatus = HttpResponseStatus.ACCEPTED; } assertEquals("Unexpected response status", responseStatus, response.getStatus()); assertEquals("Unexpected content", httpMethod.toString(), RestTestUtils.getContentString(response)); <START> assertFalse("Channel not closed", channel.isOpen()); <END> channel.close(); }</code><technical_language>is difference previous test? is channel closed in this case? of EchoMethodHandler? If is case, this line is testing a test</technical_language>

Target:
private void testNonHealthCheckRequest(HttpMethod httpMethod, String uri) throws IOException { EmbeddedChannel channel = createChannel(); HttpRequest request = RestTestUtils.createRequest(httpMethod, uri, null); FullHttpResponse response = sendRequestAndGetResponse(channel, request); assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus()); assertEquals("Unexpected content", httpMethod.toString(), RestTestUtils.getContentString(response)); channel.close(); }
Source:
<code>public Map<String, String> getUserClaims(String username, Map<String, Object> properties) throws APIManagementException { Map<String, String> map = new HashMap<String, String>(); String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username); UserInfoDTO userinfo = new UserInfoDTO(); userinfo.setUsername(tenantAwareUserName); if (tenantAwareUserName.contains(APIConstants.DOMAIN_SEPARATOR)) { userinfo.setDomain(tenantAwareUserName.split(APIConstants.DOMAIN_SEPARATOR)[0]); } if (properties.containsKey(APIConstants.KeyManager.AUTH_CODE)) { <START> userinfo.setAuthCode(properties.get(APIConstants.KeyManager.AUTH_CODE).toString()); <END> } if (properties.containsKey(APIConstants.KeyManager.ACCESS_TOKEN)) { userinfo.setAccessToken(properties.get(APIConstants.KeyManager.ACCESS_TOKEN).toString()); } if (properties.containsKey(APIConstants.KeyManager.CLAIM_DIALECT)) { userinfo.setDialectURI(properties.get(APIConstants.KeyManager.CLAIM_DIALECT).toString()); } try { ClaimsList claims = userClient.generateClaims(userinfo); if (claims != null && claims.getList() != null) { for (Claim claim : claims.getList()) { map.put(claim.getUri(), claim.getValue()); } } } catch (KeyManagerClientException e) { handleException("Error while getting user info", e); } return map; }</code><technical_language>this line needed</technical_language>

Target:
public Map<String, String> getUserClaims(String username, Map<String, Object> properties) throws APIManagementException { Map<String, String> map = new HashMap<String, String>(); String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username); UserInfoDTO userinfo = new UserInfoDTO(); userinfo.setUsername(tenantAwareUserName); if (tenantAwareUserName.contains(CarbonConstants.DOMAIN_SEPARATOR)) { userinfo.setDomain(tenantAwareUserName.split(CarbonConstants.DOMAIN_SEPARATOR)[0]); } if (properties.containsKey(APIConstants.KeyManager.ACCESS_TOKEN)) { userinfo.setAccessToken(properties.get(APIConstants.KeyManager.ACCESS_TOKEN).toString()); } if (properties.containsKey(APIConstants.KeyManager.CLAIM_DIALECT)) { userinfo.setDialectURI(properties.get(APIConstants.KeyManager.CLAIM_DIALECT).toString()); } try { ClaimsList claims = userClient.generateClaims(userinfo); if (claims != null && claims.getList() != null) { for (Claim claim : claims.getList()) { map.put(claim.getUri(), claim.getValue()); } } } catch (KeyManagerClientException e) { handleException("Error while getting user info", e); } return map; }
Source:
<code>protected boolean canDoAction() { if (!isVmExist() || !isDiskExist(getOldDisk())) { return false; } if (!canRunActionOnNonManagedVm()) { return false; } if (!vmsDiskOrSnapshotPluggedTo.isEmpty()) { if (isAtLeastOneVmIsNotDown(vmsDiskOrSnapshotPluggedTo) && shouldUpdatePropertiesOtherThanSize()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN); } boolean isUpdatedAsBootable = !getOldDisk().isBoot() && getNewDisk().isBoot(); if (isUpdatedAsBootable && !validate(noVmsContainBootableDisks(vmsDiskPluggedTo))) { return false; } boolean isDiskInterfaceUpdated = getOldDisk().getDiskInterface() != getNewDisk().getDiskInterface(); if (isDiskInterfaceUpdated && !validatePciAndIdeLimit(vmsDiskOrSnapshotPluggedTo)) { return false; } } if (DiskStorageType.IMAGE.equals(getOldDisk().getDiskStorageType()) && !validateCanResizeDisk()) { return false; } DiskValidator diskValidator = getDiskValidator(getNewDisk()); return validateCanUpdateShareable() && validate(diskValidator.isVirtIoScsiValid(getVm())) && <START> validate(diskValidator.isDiskInterfaceSupported(getVm())); <END> }</code><technical_language>rebased? code is different: DiskValidator diskValidator = getDiskValidator(getNewDisk()); return validateCanUpdateShareable() && validateCanUpdateReadOnly() && validate(diskValidator.isVirtIoScsiValid(getVm()));</technical_language>

Target:
protected boolean canDoAction() { if (!isVmExist() || !isDiskExist(getOldDisk())) { return false; } if (!canRunActionOnNonManagedVm()) { return false; } if (!vmsDiskOrSnapshotPluggedTo.isEmpty()) { if (isAtLeastOneVmIsNotDown(vmsDiskOrSnapshotPluggedTo) && shouldUpdatePropertiesOtherThanSize()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN); } boolean isUpdatedAsBootable = !getOldDisk().isBoot() && getNewDisk().isBoot(); if (isUpdatedAsBootable && !validate(noVmsContainBootableDisks(vmsDiskPluggedTo))) { return false; } boolean isDiskInterfaceUpdated = getOldDisk().getDiskInterface() != getNewDisk().getDiskInterface(); if (isDiskInterfaceUpdated && !validatePciAndIdeLimit(vmsDiskOrSnapshotPluggedTo)) { return false; } } if (DiskStorageType.IMAGE.equals(getOldDisk().getDiskStorageType()) && !validateCanResizeDisk()) { return false; } DiskValidator diskValidator = getDiskValidator(getNewDisk()); return validateCanUpdateShareable() && validateCanUpdateReadOnly() && validate(diskValidator.isVirtIoScsiValid(getVm())) && (getOldDisk().getDiskInterface() == getNewDisk().getDiskInterface() || validate(diskValidator.isDiskInterfaceSupported(getVm()))); }
Source:
<code><START> public Producer<K, V> getProducer() <END> { return producer; }</code><technical_language>reason this is public? accessed subclass.. protected</technical_language>

Target:
protected Producer<K, V> getProducer() { return producer; }
Source:
<code>protected void addReadBuffer(final ByteBuffer bb) { addReadStats(bb.remaining()); synchronized(readerLock) { final int start = readBuffers.remaining(); readBuffers.add(bb); if(readBuffers.remaining() > 0 && start == 0){ <START> readerListener.call().onRead(this); <END> } } }</code><technical_language>sense invoke read listeners while lock? (if needing pull thread sensitive data out), I worry add lock contention</technical_language>

Target:
protected void addReadBuffer(final ByteBuffer bb) { addReadStats(bb.remaining()); synchronized(readerLock) { final int start = readBuffers.remaining(); readBuffers.add(bb); if(this.readerListener.registeredListenerCount() > 0 && readBuffers.remaining() > 0 && start == 0){ callReader(); } } }
Source:
<code>protected Block computeSpan(SpanType type, Attributes attributes) { switch (type) { case LINK: if (attributes instanceof LinkAttributes) { <START> return new LinkBlock((LinkAttributes) attributes); <END> } case ITALIC: case EMPHASIS: return new ContentBlock("*", "*"); case BOLD: case STRONG: return new ContentBlock("**", "**"); case CODE: return new CodeSpan(); default: Logger.getLogger(getClass().getName()).warning("Unexpected block type: " + type); return new ContentBlock("", ""); } }</code><technical_language>If this if statement is false this fall ITALIC case below. pretty want that. great a test for case</technical_language>

Target:
protected Block computeSpan(SpanType type, Attributes attributes) { switch (type) { case LINK: if (attributes instanceof LinkAttributes) { return new LinkBlock((LinkAttributes) attributes); } else { return new ContentBlock("<", ">"); } case ITALIC: case EMPHASIS: return new ContentBlock("*", "*"); case BOLD: case STRONG: return new ContentBlock("**", "**"); case CODE: return new CodeSpan(); default: Logger.getLogger(getClass().getName()).warning("Unexpected block type: " + type); return new ContentBlock("", ""); } }
Source:
<code>public void test() throws Exception { connect(); waitResponse(); getActions().moveToElement(driver.findElement(jq(".z-rangeslider-track"))) .moveByOffset(15, 0) .clickAndHold() .moveByOffset(150, 0) .release() .perform(); waitResponse(); <START> Assert.assertEquals(jq(".z-rangeslider-track").width(), jq("@rangeslider .z-sliderbuttons-button").last().positionLeft(), 5); <END> getActions().moveToElement(driver.findElement(jq(".z-multislider-track"))) .moveByOffset(15, 0) .clickAndHold() .moveByOffset(-150, 0) .release() .perform(); waitResponse(); Assert.assertEquals(0, jq("@multislider .z-sliderbuttons-button").first().positionLeft()); }</code><technical_language>+ width</technical_language>

Target:
public void test() throws Exception { connect(); waitResponse(); getActions().moveToElement(driver.findElement(jq(".z-rangeslider-track"))) .moveByOffset(15, 0) .clickAndHold() .moveByOffset(150, 0) .release() .perform(); waitResponse(); Assert.assertEquals(jq(".z-rangeslider-track").width(), jq("@rangeslider .z-sliderbuttons-button").last().positionLeft(), 1); getActions().moveToElement(driver.findElement(jq(".z-multislider-track"))) .moveByOffset(15, 0) .clickAndHold() .moveByOffset(-150, 0) .release() .perform(); waitResponse(); Assert.assertEquals(0, jq("@multislider .z-sliderbuttons-button").first().positionLeft()); }
Source:
<code>public void testAllHomRefVCF() throws IOException { final File dbSnpFile = new File(TEST_DATA_DIR, "mini.dbsnp.vcf"); final File vcfFile = new File(TEST_DATA_DIR, "allHomRef.vcf"); final File outFile = new File(TEST_DATA_DIR, "vcmetrics_allHomRef"); final File summaryFile = new File(outFile + ".variant_calling_summary_metrics"); final File detailFile = new File(outFile + ".variant_calling_detail_metrics"); summaryFile.deleteOnExit(); detailFile.deleteOnExit(); final CollectVariantCallingMetrics program = new CollectVariantCallingMetrics(); program.INPUT = vcfFile; program.DBSNP = dbSnpFile; program.OUTPUT = outFile; Assert.assertEquals(program.doWork(), 0); final MetricsFile<CollectVariantCallingMetrics.VariantCallingDetailMetrics, Comparable<?>> detail = new MetricsFile<>(); detail.read(new FileReader(detailFile)); boolean seenSampleWithOnlyHomRefs = false; for (final CollectVariantCallingMetrics.VariantCallingDetailMetrics metrics : detail.getMetrics()) { <START> if(metrics.SAMPLE_ALIAS.equals("HG00116")) { <END> seenSampleWithOnlyHomRefs = true; Assert.assertEquals(metrics.TOTAL_SNPS, 0); } } Assert.assertTrue(seenSampleWithOnlyHomRefs); }</code><technical_language>space b/w if (</technical_language>

Target:
public void testAllHomRefVCF() throws IOException { final File dbSnpFile = new File(TEST_DATA_DIR, "mini.dbsnp.vcf"); final File vcfFile = new File(TEST_DATA_DIR, "allHomRef.vcf"); final File indexedVcfFile = VcfTestUtils.createTemporaryIndexedVcfFromInput(vcfFile, "allHomRef.tmp."); final File outFile = new File(TEST_DATA_DIR, "vcmetrics_allHomRef"); final File summaryFile = new File(outFile + ".variant_calling_summary_metrics"); final File detailFile = new File(outFile + ".variant_calling_detail_metrics"); outFile.deleteOnExit(); summaryFile.deleteOnExit(); detailFile.deleteOnExit(); final CollectVariantCallingMetrics program = new CollectVariantCallingMetrics(); program.INPUT = indexedVcfFile; program.DBSNP = dbSnpFile; program.OUTPUT = outFile; Assert.assertEquals(program.doWork(), 0); final MetricsFile<CollectVariantCallingMetrics.VariantCallingDetailMetrics, Comparable<?>> detail = new MetricsFile<>(); detail.read(new FileReader(detailFile)); boolean seenSampleWithOnlyHomRefs = false; for (final CollectVariantCallingMetrics.VariantCallingDetailMetrics metrics : detail.getMetrics()) { if (metrics.SAMPLE_ALIAS.equals("HG00116")) { seenSampleWithOnlyHomRefs = true; Assert.assertEquals(metrics.TOTAL_SNPS, 0); } } Assert.assertTrue(seenSampleWithOnlyHomRefs); }
Source:
<code>public static void setupConnection( H2PooledConnection conn, QueryContext qctx, boolean distributedJoins, boolean enforceJoinOrder, boolean lazy ) { Session s = session(conn); s.setForceJoinOrder(enforceJoinOrder); s.setJoinBatchEnabled(distributedJoins); s.setLazyQueryExecution(lazy); QueryContext oldCtx = (QueryContext)s.getVariable(QCTX_VARIABLE_NAME).getObject(); assert oldCtx == null || oldCtx == qctx : oldCtx; <START> s.setVariable("IGNITE_QUERY_CONTEXT", new ValueRuntimeSimpleObject<>(qctx)); <END> QueryContext.threadLocal(qctx); }</code><technical_language>Do QCTX_VARIABLE_NAME instead of "IGNITE_QUERY_CONTEXT" ? BTW 'QCTX_VARIABLE_NAME' constant is equals "IGNITE_QUERY_CONTEXT" Is a typo, missed smth</technical_language>

Target:
public static void setupConnection( H2PooledConnection conn, QueryContext qctx, boolean distributedJoins, boolean enforceJoinOrder, boolean lazy ) { Session s = session(conn); s.setForceJoinOrder(enforceJoinOrder); s.setJoinBatchEnabled(distributedJoins); s.setLazyQueryExecution(lazy); QueryContext oldCtx = (QueryContext)s.getVariable(QCTX_VARIABLE_NAME).getObject(); assert oldCtx == null || oldCtx == qctx : oldCtx; s.setVariable(QCTX_VARIABLE_NAME, new ValueRuntimeSimpleObject<>(qctx)); QueryContext.threadLocal(qctx); }
Source:
<code>protected void RefreshAllVdssInPool(boolean connect) { java.util.ArrayList<Guid> vdsIdsToSetNonOperational = new java.util.ArrayList<Guid>(); runSynchronizeOperation(new RefreshPoolSingleAsyncOperationFactory(), vdsIdsToSetNonOperational); for (Guid vdsId : vdsIdsToSetNonOperational) { SetNonOperationalVdsParameters tempVar = new SetNonOperationalVdsParameters(vdsId, <START> STORAGE_DOMAIN_UNREACHABLE, <END> null); tempVar.setSaveToDb(true); tempVar.setStorageDomainId(getStorageDomain().getId()); tempVar.setTransactionScopeOption(TransactionScopeOption.RequiresNew); Backend.getInstance().runInternalAction(VdcActionType.SetNonOperationalVds, tempVar); } }</code><technical_language>overload 2 params added null already</technical_language>

Target:
protected void RefreshAllVdssInPool(boolean connect) { java.util.ArrayList<Guid> vdsIdsToSetNonOperational = new java.util.ArrayList<Guid>(); runSynchronizeOperation(new RefreshPoolSingleAsyncOperationFactory(), vdsIdsToSetNonOperational); for (Guid vdsId : vdsIdsToSetNonOperational) { SetNonOperationalVdsParameters tempVar = new SetNonOperationalVdsParameters(vdsId, STORAGE_DOMAIN_UNREACHABLE); tempVar.setSaveToDb(true); tempVar.setStorageDomainId(getStorageDomain().getId()); tempVar.setTransactionScopeOption(TransactionScopeOption.RequiresNew); Backend.getInstance().runInternalAction(VdcActionType.SetNonOperationalVds, tempVar); } }
Source:
<code><START> private boolean applyTemplate(INarrativeTemplate theTemplate, IBaseResource theResource) { <END> if (templateDoesntApplyToResourceProfiles(theTemplate, theResource)) { return false; } boolean retVal = false; String resourceName = myFhirContext.getResourceDefinition(theResource).getName(); String contextPath = defaultIfEmpty(theTemplate.getContextPath(), resourceName); List<IBase> targets = findTargets(theResource, contextPath); for (IBase nextTargetContext : targets) { BaseRuntimeElementCompositeDefinition<?> targetElementDef = (BaseRuntimeElementCompositeDefinition<?>) getFhirContext().getElementDefinition(nextTargetContext.getClass()); BaseRuntimeChildDefinition targetTextChild = targetElementDef.getChildByName("text"); List<IBase> existing = targetTextChild.getAccessor().getValues(nextTargetContext); INarrative nextTargetNarrative; if (existing.isEmpty()) { nextTargetNarrative = (INarrative) getFhirContext().getElementDefinition("narrative").newInstance(); targetTextChild.getMutator().addValue(nextTargetContext, nextTargetNarrative); } else { nextTargetNarrative = (INarrative) existing.get(0); } String narrative = applyTemplate(theTemplate, nextTargetContext); narrative = cleanWhitespace(narrative); if (isNotBlank(narrative)) { try { nextTargetNarrative.setDivAsString(narrative); nextTargetNarrative.setStatusAsString("generated"); retVal = true; } catch (Exception e) { throw new InternalErrorException(e); } } } return retVal; }</code><technical_language>20 minutes understand this method. Methods this more approachable if broken smaller methods descriptive names</technical_language>

Target:
private boolean applyTemplate(INarrativeTemplate theTemplate, IBaseResource theResource) { if (templateDoesntApplyToResource(theTemplate, theResource)) { return false; } boolean retVal = false; String resourceName = myFhirContext.getResourceDefinition(theResource).getName(); String contextPath = defaultIfEmpty(theTemplate.getContextPath(), resourceName); List<IBase> targets = findElementsInResourceRequiringNarratives(theResource, contextPath); for (IBase nextTargetContext : targets) { INarrative nextTargetNarrative = getOrCreateNarrativeChildElement(nextTargetContext); String narrative = applyTemplate(theTemplate, nextTargetContext); narrative = cleanWhitespace(narrative); if (isNotBlank(narrative)) { try { nextTargetNarrative.setDivAsString(narrative); nextTargetNarrative.setStatusAsString("generated"); retVal = true; } catch (Exception e) { throw new InternalErrorException(e); } } } return retVal; }
Source:
<code>private DiscoverySubsystemDefinition() { super(new Parameters(DiscoveryExtension.SUBSYSTEM_PATH, DiscoveryExtension.getResourceDescriptionResolver()) <START> .setAddHandler(DiscoverySubsystemAddHandler.getInstance()) <END> ); }</code><technical_language>Needs a remove handler</technical_language>

Target:
private DiscoverySubsystemDefinition() { super(new Parameters(DiscoveryExtension.SUBSYSTEM_PATH, DiscoveryExtension.getResourceDescriptionResolver()) .setAddHandler(DiscoverySubsystemAddHandler.getInstance()) .setRemoveHandler(new TrivialRemoveStepHandler()) ); }
Source:
<code>private long getExtremeLogEntry(Function<PaxosStateLog<V>, Long> extractor) { lock.readLock().lock(); try { Long result = extractor.apply(currentLog); if (firstEntry.isDone()) { Long experimentalResult = safeReadFromExperimental(extractor::apply); if (!Objects.equals(result, experimentalResult) && result != PaxosAcceptor.NO_LOG_ENTRY <START> && result >= Futures.getUnchecked(firstEntry)) { <END> log.error("Mismatch in getting the extreme log entry between legacy and current implementations." + " Legacy result {}, current result {}.", SafeArg.of("legacy", result), SafeArg.of("current", experimentalResult)); } } return result; } finally { lock.readLock().unlock(); } }</code><technical_language>need term here, this is fine</technical_language>

Target:
private long getExtremeLogEntry(Function<PaxosStateLog<V>, Long> extractor) { lock.readLock().lock(); try { Long result = extractor.apply(currentLog); Long experimentalResult = safeReadFromExperimental(extractor::apply); if (!Objects.equals(result, experimentalResult) && result != PaxosAcceptor.NO_LOG_ENTRY) { OptionalLong firstWrittenSequence = firstEntry.isDone() ? OptionalLong.of(Futures.getUnchecked(firstEntry)) : OptionalLong.empty(); log.error("Mismatch in getting the extreme log entry between legacy and current implementations." + " Legacy result {}, current result {}. First written sequence was {}.", SafeArg.of("legacy", result), SafeArg.of("current", experimentalResult), SafeArg.of("firstWrittenSequence", firstWrittenSequence)); } return result; } finally { lock.readLock().unlock(); } }
Source:
<code>private String getSecondaryActionText() { switch (getSecondaryAction()) { case SAVE_AS_DRAFT: return getString(R.string.menu_save_as_draft); case SAVE: return getString(R.string.save); case PUBLISH_NOW: return getString(R.string.menu_publish_now); case NONE: throw new IllegalStateException("getSecondaryActionText shouldn't be called with that case"); } <START> throw new IllegalStateException("getSecondaryActionText shouldn't be called with that case"); <END> }</code><technical_language>NitPick: consider changing wording unreachable line - "Switch in getSecondaryActionText() is missing a required case case is missing "return" keyword" similar. Wdyt</technical_language>

Target:
private String getSecondaryActionText() { switch (getSecondaryAction()) { case SAVE_AS_DRAFT: return getString(R.string.menu_save_as_draft); case SAVE: return getString(R.string.save); case PUBLISH_NOW: return getString(R.string.menu_publish_now); case NONE: throw new IllegalStateException("Switch in `secondaryAction` shouldn't go through the NONE case"); } throw new IllegalStateException( "Switch in getSecondaryActionText is missing a required case or the case is missing \"return\" " + "keyword "); }
Source:
<code>public static void testDeleteSettlementAccount(SavingsAccount savingsAccount) throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println(methodName = "\nIn " + methodName); LoanAccount loanAccountToBeUpdated = newAccount; LoansService loanService = MambuAPIFactory.getLoanService(); boolean deleteResult = loanService.deleteSettlementAccount(loanAccountToBeUpdated.getEncodedKey(), savingsAccount.getEncodedKey()); <START> System.out.println("The delete resut is: " + deleteResult); <END> }</code><technical_language>missing "l" in "resut"</technical_language>

Target:
public static void testDeleteSettlementAccount(SavingsAccount savingsAccount) throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println(methodName = "\nIn " + methodName); LoanAccount loanAccountToBeUpdated = newAccount; LoansService loanService = MambuAPIFactory.getLoanService(); boolean deleteResult = loanService.deleteSettlementAccount(loanAccountToBeUpdated.getEncodedKey(), savingsAccount.getEncodedKey()); System.out.println("The delete result is: " + deleteResult); }
Source:
<code>synchronized void tryToProvidePreviewSurface() { if (mResolution == null || mSurfaceTexture == null || mSurfaceCompleter == null) { return; } mSurfaceTexture.setDefaultBufferSize(mResolution.getWidth(), mResolution.getHeight()); final Surface surface = new Surface(mSurfaceTexture); <START> mSurfaceCount.register(); <END> final ListenableFuture<Void> surfaceReleaseFuture = mSurfaceReleaseFuture; mSurfaceReleaseFuture.addListener( () -> onSurfaceReleaseFutureComplete(surface, surfaceReleaseFuture), ContextCompat.getMainExecutor(mTextureView.getContext())); mSurfaceCompleter.set(surface); mCompleterMap.remove(mSurfaceCompleter); mSurfaceCompleter = null; correctPreviewForCenterCrop(mParent, mTextureView, mResolution); }</code><technical_language>is point of this</technical_language>

Target:
void tryToProvidePreviewSurface() { Threads.checkMainThread(); if (mResolution == null || mSurfaceTexture == null || mSurfaceCompleter == null) { return; } mSurfaceTexture.setDefaultBufferSize(mResolution.getWidth(), mResolution.getHeight()); final Surface surface = new Surface(mSurfaceTexture); incrementSurfaceCount(); final ListenableFuture<Void> surfaceReleaseFuture = mSurfaceReleaseFuture; mSurfaceReleaseFuture.addListener( () -> onSurfaceReleaseFutureComplete(surface, surfaceReleaseFuture), ContextCompat.getMainExecutor(mTextureView.getContext())); mSurfaceCompleter.set(surface); mCompleterMap.remove(mSurfaceCompleter); mSurfaceCompleter = null; correctPreviewForCenterCrop(mParent, mTextureView, mResolution); }
Source:
<code>protected void executeQueryCommand() { final List<VdsNetworkInterface> vdsInterfaces = interfaceDao.getAllInterfacesForVds(getParameters().getId(), getUserID(), getParameters().isFiltered()); List<VdsNetworkInterface> interfaces = new ArrayList<>(vdsInterfaces.size()); if (!vdsInterfaces.isEmpty()) { VdsStatic vdsStatic = vdsStaticDao.get(getParameters().getId()); Map<String, Network> networks = Entities.entitiesByName(networkDao.getAllForCluster(vdsStatic.getClusterId())); for (final VdsNetworkInterface nic : vdsInterfaces) { if (!nic.isBond() || nicDoesHaveSlaves(vdsInterfaces, nic)) { interfaces.add(nic); Network network = networks.get(nic.getNetworkName()); NetworkImplementationDetails networkImplementationDetails = networkImplementationDetailsUtils.calculateNetworkImplementationDetails(nic, network); nic.setNetworkImplementationDetails(networkImplementationDetails); } <START> if (nic.isBond()) { boolean isAdPartnerInvalid = StringUtils.isEmpty(nic.getAdPartnerMac()) && InterfaceStatus.UP.equals(nic.getStatistics().getStatus()) && BondMode.BOND4.equals(BondMode.parseBondMode(nic.getBondOptions())); boolean isAdPartnerSupportedForCluster = FeatureSupported.adPartenerMacSupported(clusterDao.get(vdsStatic.getClusterId()).getCompatibilityVersion()); Bond bond = (Bond) nic; bond.setAdPartnerMacValid(!isAdPartnerSupportedForCluster || !isAdPartnerInvalid); } <END> } } getQueryReturnValue().setReturnValue(interfaces); }</code><technical_language>this for loop is long bond processed in if statements. I easier read if content of this 'then' clause is extracted separate method: 'if (nic.isBond()) {updatePartnerMacValidity((Bond)nic)}' similar. beneficial (reconsider yourself) if in for loop place, deal nic, isBond is true</technical_language>

Target:
protected void executeQueryCommand() { final List<VdsNetworkInterface> vdsInterfaces = interfaceDao.getAllInterfacesForVds(getParameters().getId(), getUserID(), getParameters().isFiltered()); List<VdsNetworkInterface> interfaces = new ArrayList<>(vdsInterfaces.size()); if (!vdsInterfaces.isEmpty()) { VdsStatic vdsStatic = vdsStaticDao.get(getParameters().getId()); Map<String, Network> networks = Entities.entitiesByName(networkDao.getAllForCluster(vdsStatic.getClusterId())); for (final VdsNetworkInterface nic : vdsInterfaces) { if (!nic.isBond() || nicDoesHaveSlaves(vdsInterfaces, nic)) { interfaces.add(nic); Network network = networks.get(nic.getNetworkName()); NetworkImplementationDetails networkImplementationDetails = networkImplementationDetailsUtils.calculateNetworkImplementationDetails(nic, network); nic.setNetworkImplementationDetails(networkImplementationDetails); } if (nic.isBond()) { Bond bond = (Bond) nic; bond.setAdPartnerMacValid(isAdPartnerMacValid(bond, vdsStatic)); } } } getQueryReturnValue().setReturnValue(interfaces); }
Source:
<code>public void renameWhileComputing() throws Exception { CoordinatedComputedFolder d = r.jenkins.createProject(CoordinatedComputedFolder.class, "d"); d.kids.addAll(Arrays.asList("A", "B")); QueueTaskFuture<Queue.Executable> future = d.scheduleBuild2(0).getFuture(); FolderComputation<FreeStyleProject> computation; while (Executor.of((computation = d.getComputation())) == null) { Thread.sleep(50); <START> } <END> try { d.checkRename("d2"); fail("Should be blocked while computation is in progress"); } catch (Failure f) { assertThat(f.getMessage(), is(Messages.ComputedFolder_ComputationInProgress())); } }</code><technical_language>I this work everytime. In cases I prefer foirce sync self. test in <LINK_0> I method waitForStart wait for a build start on. Secondly, I put a semaphore a custom build in order determine build finishes exactly, try rename job, receive error re-try end receive "success"</technical_language>

Target:
public void renameWhileComputing() throws Exception { CoordinatedComputedFolder d = r.jenkins.createProject(CoordinatedComputedFolder.class, "d"); d.kids.addAll(Arrays.asList("A", "B")); QueueTaskFuture<Queue.Executable> future = d.scheduleBuild2(0).getFuture(); future.waitForStart(); try { d.checkRename("d2"); fail("Should be blocked while computation is in progress"); } catch (Failure f) { assertThat(f.getMessage(), is(Messages.ComputedFolder_ComputationInProgress())); } d.onKid("B"); future.get(); waitUntilNoActivityIgnoringThreadDeathUpTo(10000); d.checkRename("d2"); }
Source:
<code>private Map<String, Entity> createUserEntites(List<String> userLines) { Map<String, Entity> users = new HashMap<String, Entity>(); for (String line : userLines) { String[] userParts = line.split(",", 3); if (userParts.length < 3 || userParts[0].trim().length() == 0) { <START> System.out.println("Skipping user: " + line); <END> } Entity user = new Entity(USER_KIND); user.setProperty(USER_EMAIL_FIELD, userParts[0].trim()); user.setProperty(USER_PERMISSION_FIELD, userParts[1].trim()); user.setProperty(USER_ROLE_FIELD, Boolean.valueOf(userParts[2].trim())); users.put(userParts[0].trim(), user); } return users; }</code><technical_language>I this is missing a continue</technical_language>

Target:
private Map<String, Entity> createUserEntites(List<String> userLines) { Map<String, Entity> users = new HashMap<String, Entity>(); for (String line : userLines) { String[] userParts = line.split(",", 3); if (userParts.length < 3 || userParts[0].trim().length() == 0) { System.out.println("Skipping user: " + line); continue; } Entity user = new Entity(USER_KIND); user.setProperty(USER_EMAIL_FIELD, userParts[0].trim()); user.setProperty(USER_PERMISSION_FIELD, userParts[1].trim()); user.setProperty(USER_ROLE_FIELD, Boolean.valueOf(userParts[2].trim())); users.put(userParts[0].trim(), user); } return users; }
Source:
<code>private void getAllSections(final int expectedNumberOfSections, final String title) throws Throwable { final CountDownLatch completionLatch = new CountDownLatch(1); startActivity(new Intent(), null, null); runTestOnUiThread(new Runnable() { @Override public void run() { <START> final WikipediaApp app = (WikipediaApp) <END> getInstrumentation().getTargetContext().getApplicationContext(); new SectionsFetchTask(app, new PageTitle(null, title, new Site("test.wikipedia.org")), "all") { @Override public void onFinish(List<Section> result) { assertNotNull(result); assertEquals(expectedNumberOfSections, result.size()); completionLatch.countDown(); } }.execute(); } }); assertTrue(completionLatch.await(TASK_COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS)); }</code><technical_language>Minor: consider WikipediaApp.getInstance() instead</technical_language>

Target:
private void getAllSections(final int expectedNumberOfSections, final String title) throws Throwable { final CountDownLatch completionLatch = new CountDownLatch(1); startActivity(new Intent(), null, null); runTestOnUiThread(new Runnable() { @Override public void run() { final WikipediaApp app = WikipediaApp.getInstance(); new SectionsFetchTask(app, new PageTitle(null, title, new Site("test.wikipedia.org")), "all") { @Override public void onFinish(List<Section> result) { assertNotNull(result); assertEquals(expectedNumberOfSections, result.size()); completionLatch.countDown(); } }.execute(); } }); assertTrue(completionLatch.await(TASK_COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS)); }
Source:
<code>public void respondOk_whenSearchMandatesRequest(Map<String, StringValuePattern> searchParams, SearchMandateConnectorResponse response, String gatewayAccountId) { try { String responseAsJson = new ObjectMapper().writeValueAsString(response); wireMockClassRule.stubFor(get(urlPathEqualTo(format(CONNECTOR_MOCK_MANDATES_PATH, gatewayAccountId))) .withHeader(ACCEPT, matching(APPLICATION_JSON)) .withQueryParams(searchParams) .willReturn(aResponse() .withStatus(200) .withHeader(CONTENT_TYPE, APPLICATION_JSON) .withBody(responseAsJson))); } catch (JsonProcessingException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>this is in tests, is reason this exception bubble top</technical_language>

Target:
public void respondOk_whenSearchMandatesRequest(Map<String, StringValuePattern> searchParams, SearchMandateConnectorResponse response, String gatewayAccountId) throws JsonProcessingException { String responseAsJson = new ObjectMapper().writeValueAsString(response); wireMockClassRule.stubFor(get(urlPathEqualTo(format(CONNECTOR_MOCK_MANDATES_PATH, gatewayAccountId))) .withHeader(ACCEPT, matching(APPLICATION_JSON)) .withQueryParams(searchParams) .willReturn(aResponse() .withStatus(200) .withHeader(CONTENT_TYPE, APPLICATION_JSON) .withBody(responseAsJson))); }