auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<AttestationValue> attestHosts(Set<String> hosts){ String pollURI = Config.<String> GetValue(ConfigValues.PollUri); List<AttestationValue> values = new ArrayList<AttestationValue>(); PostMethod postMethod = new PostMethod("/" +pollURI); try { postMethod.setRequestEntity(new StringRequestEntity(writeListJson(hosts))); postMethod.addRequestHeader("Accept",CONTENT_TYPE); postMethod.addRequestHeader("Content-type", CONTENT_TYPE); HttpClient httpClient = getClient(); int statusCode = httpClient.executeMethod(postMethod); String strResponse = postMethod.getResponseBodyAsString(); log.debug("return attested result:" +strResponse); if (statusCode == 200){ values = parsePostedResp(strResponse); } else{ String fault = strResponse; log.error("attestation error:" +fault); } }catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); }catch (IOException e) { <START> log.error(e.getMessage(), e); <END> }finally { postMethod.releaseConnection(); } return values; }</code><technical_language>I suggest include some message explaining failed, message of underlying exception: log.error("Failed attest hosts " + theListOfHosts, e);</technical_language>

Target:
public List<AttestationValue> attestHosts(Set<String> hosts) { String pollURI = Config.<String> GetValue(ConfigValues.PollUri); List<AttestationValue> values = new ArrayList<AttestationValue>(); PostMethod postMethod = new PostMethod("/" + pollURI); try { postMethod.setRequestEntity(new StringRequestEntity(writeListJson(hosts))); postMethod.addRequestHeader("Accept", CONTENT_TYPE); postMethod.addRequestHeader("Content-type", CONTENT_TYPE); HttpClient httpClient = getClient(); int statusCode = httpClient.executeMethod(postMethod); String strResponse = postMethod.getResponseBodyAsString(); log.debug("return attested result:" + strResponse); if (statusCode == 200) { values = parsePostedResp(strResponse); } else { String fault = strResponse; log.error("attestation error:" + fault); } } catch (JsonParseException e) { log.error(String.format("Failed to parse result: [%s]", e.getMessage()), e); } catch (IOException e) { log.error(String.format("Failed to attest hosts: [%s], make sure hosts are up and reachable", e.getMessage()), e); } finally { postMethod.releaseConnection(); } return values; }
Source:
<code>public static OsAppCredentials anonymous() { <START> return new OsAppCredentials(nativeCreate(TYPE_ANONYMOUS), Credentials.IdentityProvider.ANONYMOUS); <END> }</code><technical_language>I cleaner if Credentials.IdentityProvider.ANONYMOUS defined in factory constructor of AppCredentials. OsAppCredentials is map underlying type, making a shortcut is responsibility of Os class AppCredentials. else</technical_language>

Target:
public static OsAppCredentials anonymous() { return new OsAppCredentials(nativeCreate(TYPE_ANONYMOUS)); }
Source:
<code>private void updateNextRunConfiguration() { final VmStatic nextRunConfigurationStatic = runInternalQuery( <START> VdcQueryType.GetVmNextRunConfiguration, new <END> IdQueryParameters(getVmId())) .<VM>getReturnValue() .getStaticData(); final int newMemorySize = nextRunConfigurationStatic.getMemSizeMb() - getUnpluggedDeviceSize(); if (newMemorySize <= 0) { return; } if (getVm().getMemSizeMb() != nextRunConfigurationStatic.getMemSizeMb()) { return; } nextRunConfigurationStatic.setMemSizeMb(newMemorySize); if (newMemorySize < nextRunConfigurationStatic.getMinAllocatedMem()) { nextRunConfigurationStatic.setMinAllocatedMem(newMemorySize); } vmHandler.createNextRunSnapshot( getVm(), nextRunConfigurationStatic, null, getCompensationContext()); }</code><technical_language>query returns configuration vm_static snapshot of type next-run exists for vm, this command create next-run snapshot I think, right? is generally a good practice call queries commands, replace direct query database? btw, this ask update specific snapshot queried - if exists get error (which ignore) this command non-transactive again. for back-and-forth transaction scope changes - give some more thinking changing again</technical_language>

Target:
private void updateNextRunConfiguration() { final VmStatic nextRunConfigurationStatic = getNextRunConfiguration(); if (nextRunConfigurationStatic == null) { return; } final int newMemorySize = nextRunConfigurationStatic.getMemSizeMb() - getUnpluggedDeviceSize(); if (newMemorySize <= 0) { return; } if (getVm().getMemSizeMb() != nextRunConfigurationStatic.getMemSizeMb()) { return; } nextRunConfigurationStatic.setMemSizeMb(newMemorySize); if (newMemorySize < nextRunConfigurationStatic.getMinAllocatedMem()) { nextRunConfigurationStatic.setMinAllocatedMem(newMemorySize); } vmHandler.createNextRunSnapshot( getVm(), nextRunConfigurationStatic, null, getCompensationContext()); }
Source:
<code>private static boolean attemptInstantiation() { <START> if (instantiated == false) { <END> lock.lock(); try { if (instantiated == false) { asyncHttpClientImplClass = AsyncImplHelper .getAsyncImplClass(AsyncImplHelper.ASYNC_HTTP_CLIENT_IMPL_SYSTEM_PROPERTY); instantiated = true; } } finally { lock.unlock(); } } return (asyncHttpClientImplClass != null); }</code><technical_language>!instantiated</technical_language>

Target:
private static boolean attemptInstantiation() { if (!instantiated) { lock.lock(); try { if (!instantiated) { asyncHttpClientImplClass = AsyncImplHelper .getAsyncImplClass(AsyncImplHelper.ASYNC_HTTP_CLIENT_IMPL_SYSTEM_PROPERTY); instantiated = true; } } finally { lock.unlock(); } } return asyncHttpClientImplClass != null; }
Source:
<code>public void validate_shouldFailIfTheConceptClassIsNull() throws Exception { Concept concept = new Concept(); concept.addName(new ConceptName("some name",Context.getLocale())); concept.addDescription(new ConceptDescription("some description",null)); concept.setDatatype(new ConceptDatatype()); Errors errors = new BindException(concept, "concept"); new ConceptValidator().validate(concept, errors); <START> Assert.assertTrue(errors.hasErrors()); <END> }</code><technical_language>check if errors contains error key "Concept.conceptClass.empty"</technical_language>

Target:
public void validate_shouldFailIfTheConceptClassIsNull() throws Exception { Concept concept = new Concept(); concept.addName(new ConceptName("some name",Context.getLocale())); concept.addDescription(new ConceptDescription("some description",null)); concept.setDatatype(new ConceptDatatype(1)); Errors errors = new BindException(concept, "concept"); new ConceptValidator().validate(concept, errors); Assert.assertEquals(errors.getFieldError("conceptClass").getCode(), "Concept.conceptClass.empty"); }
Source:
<code>public void testMetricsCacheClientService() throws Exception { MetricsCacheSink metricsCacheSink = new MetricsCacheSink(); Map<String, Object> serviceConfig = buildServiceConfig(); metricsCacheSink.createSimpleMetricsCacheClientService(serviceConfig); metricsCacheSink.startNewMetricsCacheClient(getMetricsCacheLocation(0)); SysUtils.sleep(RESTART_WAIT_INTERVAL); assertTrue(metricsCacheSink.getMetricsCacheStartedAttempts() <START> >= (RESTART_WAIT_INTERVAL.getSeconds() - 2 * RECONNECT_INTERVAL.getSeconds())); <END> metricsCacheSink.close(); }</code><technical_language>metricsCacheStartedAttempts number of attempts</technical_language>

Target:
public void testMetricsCacheClientService() throws Exception { MetricsCacheSink metricsCacheSink = new MetricsCacheSink(); Map<String, Object> serviceConfig = buildServiceConfig(); metricsCacheSink.createSimpleMetricsCacheClientService(serviceConfig); metricsCacheSink.startNewMetricsCacheClient(getMetricsCacheLocation(0)); SysUtils.sleep(RESTART_WAIT_INTERVAL); assertTrue(metricsCacheSink.getMetricsCacheStartedAttempts() >= (RESTART_WAIT_INTERVAL.getSeconds() / RECONNECT_INTERVAL.getSeconds() / 2)); metricsCacheSink.close(); }
Source:
<code>public Key(Text row) { <START> this(row.getBytes()); <END> }</code><technical_language>This is wrong. Text.getBytes() return backing array for Text object, contents of data in Text object length of array. initial position of 0 a length of Text.getLength()</technical_language>

Target:
public Key(Text row) { init(row.getBytes(), 0, row.getLength(), EMPTY_BYTES, 0, 0, EMPTY_BYTES, 0, 0, EMPTY_BYTES, 0, 0, Long.MAX_VALUE, false, true); }
Source:
<code>public void setUp() throws Exception { ApplicationConfiguration configuration = ApplicationConfiguration.defaultConfiguration() .withSource(Publisher.METABROADCAST, SourceStatus.AVAILABLE_ENABLED) .copyWithWritableSources(ImmutableList.of(Publisher.METABROADCAST)); inputBytes = "{ content: }".getBytes(); DelegatingServletInputStream inputStream = new DelegatingServletInputStream( new ByteArrayInputStream(inputBytes) ); Item content = new Item(); content.setCanonicalUri("uri"); content.setPublisher(Publisher.METABROADCAST); inputContent = new ContentWriteExecutor.InputContent(content, "item"); contentId = 0L; when(configurationFetcher.configurationFor(request)).thenReturn(Maybe.just(configuration)); when(request.getInputStream()).thenReturn(inputStream); when(writeExecutor.parseInputStream(any(InputStream.class), anyBoolean())).thenReturn(inputContent); when(idGenerator.getId(any(Content.class))).thenReturn(contentId); when(response.getOutputStream()).thenReturn(outputStream); when(lookupEntry.uri()).thenReturn(uri); <START> ArrayList<LookupEntry> entryList = new ArrayList<>(); <END> entryList.add(lookupEntry); when(lookupEntryStore.entriesForIds(anyList())) .thenReturn(entryList); when(contentResolver.findByCanonicalUris(Lists.newArrayList(uri))) .thenReturn(resolvedContent); controller = new ContentWriteController( configurationFetcher, writeExecutor, idGenerator, messageSender, modelWriter, lookupEntryStore, contentResolver, contentWriter ); }</code><technical_language>do for short; ImmutableList<LookupEntry> entryList = ImmutableList.of(lookupEntry);</technical_language>

Target:
public void setUp() throws Exception { ApplicationConfiguration configuration = ApplicationConfiguration.defaultConfiguration() .withSource(Publisher.METABROADCAST, SourceStatus.AVAILABLE_ENABLED) .copyWithWritableSources(ImmutableList.of(Publisher.METABROADCAST)); inputBytes = "{ content: }".getBytes(); DelegatingServletInputStream inputStream = new DelegatingServletInputStream( new ByteArrayInputStream(inputBytes) ); Item content = new Item(); content.setCanonicalUri("uri"); content.setPublisher(Publisher.METABROADCAST); inputContent = new ContentWriteExecutor.InputContent(content, "item"); contentId = 0L; when(configurationFetcher.configurationFor(request)).thenReturn(Maybe.just(configuration)); when(request.getInputStream()).thenReturn(inputStream); when(writeExecutor.parseInputStream(any(InputStream.class), anyBoolean())).thenReturn(inputContent); when(idGenerator.getId(any(Content.class))).thenReturn(contentId); when(response.getOutputStream()).thenReturn(outputStream); when(lookupEntry.uri()).thenReturn(uri); ImmutableList<LookupEntry> entryList = ImmutableList.of(lookupEntry); when(lookupEntryStore.entriesForIds(anyList())) .thenReturn(entryList); when(contentResolver.findByCanonicalUris(Lists.newArrayList(uri))) .thenReturn(resolvedContent); controller = ContentWriteController.create( configurationFetcher, writeExecutor, idGenerator, messageSender, modelWriter, lookupEntryStore, contentResolver, contentWriter ); }
Source:
<code>public void onLoaded() { wa.contextDestroyed(null); <START> throw new Error(); <END> }</code><technical_language>work fix ItemListener catch errors onLoaded implementations, is true of InduceBootFailure. :bug: is fact needed do this suggests regressed logic in WebAppMain.contextDestroyed is supposed interrupting initThread this test (from #1950) verifying</technical_language>

Target:
public void onLoaded() { wa.contextDestroyed(null); }
Source:
<code>public void run() { if(thread == null || !Thread.currentThread().equals(thread)) { <START> thread = new Thread(this); <END> thread.start(); } else { try { if (logger.isInfoEnabled()) logger.info("Start reconnecting " + provider); provider.register( getUIService().getDefaultSecurityAuthority(provider)); } catch (OperationFailedException ex) { logger.error("cannot re-register provider will keep going", ex); } } }</code><technical_language>thinking new thread is needed for reconnect task. This thread dead time a new reconnect is needed I Timer instance serving purpose of this thread. do think</technical_language>

Target:
public void run() { try { if (logger.isInfoEnabled()) logger.info("Start reconnecting " + provider); provider.register( getUIService().getDefaultSecurityAuthority(provider)); } catch (OperationFailedException ex) { logger.error("cannot re-register provider will keep going", ex); } }
Source:
<code>public long saveSequencerPartitionContainer(SequencerPartitionContainer<SequencerPoolPartition>container) throws IOException { if (sequencerPartitionContainerStore != null) { if (container.getId() == AbstractSequencerPartitionContainer.UNSAVED_ID) { return sequencerPartitionContainerStore.save(container); } else { SequencerPartitionContainer<SequencerPoolPartition> managed = getSequencerPartitionContainerById(container.getId()); managed.setIdentificationBarcode(container.getIdentificationBarcode()); managed.setLocationBarcode(container.getLocationBarcode()); managed.setValidationBarcode(container.getValidationBarcode()); Collection<Run> runs = new HashSet<>(); for (Run run : container.getRuns()) { if (run != null) runs.add(getRunById(run.getId())); } <START> managed.setRuns(runs); <END> managed.setPlatform(container.getPlatform()); updatePartitionPools(container, managed); return sequencerPartitionContainerStore.save(managed); } } else { throw new IOException("No sequencerPartitionContainerStore available. Check that it has been declared in the Spring config."); } }</code><technical_language>cascade SequencerPartitionContainer.runs relationship SequencerPartitionContainer Runs is managed Runs, sense. Copying runs container managed effect</technical_language>

Target:
public long saveSequencerPartitionContainer(SequencerPartitionContainer<SequencerPoolPartition>container) throws IOException { if (sequencerPartitionContainerStore != null) { if (container.getId() == AbstractSequencerPartitionContainer.UNSAVED_ID) { return sequencerPartitionContainerStore.save(container); } else { SequencerPartitionContainer<SequencerPoolPartition> managed = getSequencerPartitionContainerById(container.getId()); managed.setIdentificationBarcode(container.getIdentificationBarcode()); managed.setLocationBarcode(container.getLocationBarcode()); managed.setValidationBarcode(container.getValidationBarcode()); updatePartitionPools(container, managed); return sequencerPartitionContainerStore.save(managed); } } else { throw new IOException("No sequencerPartitionContainerStore available. Check that it has been declared in the Spring config."); } }
Source:
<code>public Observable<MessageConnection> connect() { return resolver.resolve() .take(1) .map(new Func1<Server, RxClient<Object, Object>>() { @Override public RxClient<Object, Object> call(Server server) { RxClient<Object, Object> client = clients.get(server); if (null == client) { client = RxNetty.createTcpClient(server.getHost(), server.getPort(), pipelineConfigurator); clients.put(server, client); } logger.info("Connecting to server {}", server); return client; } }) .flatMap(new Func1<RxClient<Object, Object>, Observable<MessageConnection>>() { @Override public Observable<MessageConnection> call(final RxClient<Object, Object> client) { return client.connect() .map(new Func1<ObservableConnection<Object, Object>, MessageConnection>() { @Override public MessageConnection call( ObservableConnection<Object, Object> conn) { return new SelfClosingConnection( new HeartBeatConnection( <START> new BaseMessageConnection(clientId, conn, metrics), <END> config.getHeartbeatIntervalMs(), 3, Schedulers.computation() ), config.getConnectionAutoTimeoutMs() ); } }); } }); }</code><technical_language>If this is purely for testing purposes, useful define a counting id in client, append counting id end of this differentiate channel generations</technical_language>

Target:
public Observable<MessageConnection> connect() { return resolver.resolve() .take(1) .map(new Func1<Server, RxClient<Object, Object>>() { @Override public RxClient<Object, Object> call(Server server) { RxClient<Object, Object> client = clients.get(server); if (null == client) { client = RxNetty.createTcpClient(server.getHost(), server.getPort(), pipelineConfigurator); clients.put(server, client); } logger.info("Connecting to server {}", server); return client; } }) .flatMap(new Func1<RxClient<Object, Object>, Observable<MessageConnection>>() { @Override public Observable<MessageConnection> call(final RxClient<Object, Object> client) { return client.connect() .map(new Func1<ObservableConnection<Object, Object>, MessageConnection>() { @Override public MessageConnection call( ObservableConnection<Object, Object> conn) { String clientInstanceId = clientId + '#' + clientInstanceIdx.incrementAndGet(); return new SelfClosingConnection( new HeartBeatConnection( new BaseMessageConnection(clientInstanceId, conn, metrics), config.getHeartbeatIntervalMs(), 3, Schedulers.computation() ), config.getConnectionAutoTimeoutMs() ); } }); } }); }
Source:
<code>private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForMemoryDumpImage( Guid containerID, Guid storageDomainId, Guid imageId, Guid volumeId) { MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, imageId, volumeId, getParameters().getStorageDomainId(), getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setSourceDomainId(storageDomainId); params.setEntityInfo(getParameters().getEntityInfo()); params.setParentParameters(getParameters()); <START> if (getStorageDomain().getStorageType().isBlockDomain()) { <END> params.setUseCopyCollapse(true); params.setVolumeType(VolumeType.Sparse); params.setVolumeFormat(VolumeFormat.RAW); } return params; }</code><technical_language>getStorageDomain is TARGET domain - get SOURCE domain storageDomainId parameter passed</technical_language>

Target:
private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForMemoryDumpImage( Guid containerID, Guid storageDomainId, Guid imageId, Guid volumeId) { MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, imageId, volumeId, getParameters().getStorageDomainId(), getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setSourceDomainId(storageDomainId); params.setEntityInfo(getParameters().getEntityInfo()); params.setParentParameters(getParameters()); StorageDomainStatic sourceDomain = getStorageDomainStaticDAO().get(storageDomainId); if (sourceDomain.getStorageType().isBlockDomain()) { params.setUseCopyCollapse(true); params.setVolumeType(VolumeType.Sparse); params.setVolumeFormat(VolumeFormat.RAW); } return params; }
Source:
<code>public HttpResponse doPlatformPluginList() throws IOException { jenkins.install.SetupWizard setupWizard = Jenkins.getInstance().getSetupWizard(); if (setupWizard != null) { if (InstallState.UPGRADE.equals(Jenkins.getInstance().getInstallState())) { JSONArray initialPluginData = getPlatformPluginUpdates(); if(initialPluginData != null) { return hudson.util.HttpResponses.okJSON(initialPluginData); } <START> } else { <END> JSONArray initialPluginData = getPlatformPluginList(); if(initialPluginData != null) { return hudson.util.HttpResponses.okJSON(initialPluginData); } } } return hudson.util.HttpResponses.okJSON(); }</code><technical_language>is want do in other state? in case of InstallStates contributed plugins</technical_language>

Target:
public HttpResponse doPlatformPluginList() throws IOException { jenkins.install.SetupWizard setupWizard = Jenkins.getInstance().getSetupWizard(); if (setupWizard != null) { if (InstallState.UPGRADE.equals(Jenkins.getInstance().getInstallState())) { JSONArray initialPluginData = getPlatformPluginUpdates(); if(initialPluginData != null) { return HttpResponses.okJSON(initialPluginData); } } else { JSONArray initialPluginData = getPlatformPluginList(); if(initialPluginData != null) { return HttpResponses.okJSON(initialPluginData); } } } return HttpResponses.okJSON(); }
Source:
<code>private void testVerifyAtLeastOneInstructorIsDisplayed() throws Exception { ______TS("success: at least one instructor is displayed to students"); String courseId = "idOfTypicalCourse1"; String courseIdWithNoInstructorsDisplayed = "idOfTestingInstructorsDisplayedCourse"; boolean isEditedInstructorDisplayed = true; <START> boolean isOriginalInstructorDisplayed = true; <END> instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(isOriginalInstructorDisplayed, courseId, isEditedInstructorDisplayed); instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(isOriginalInstructorDisplayed, courseId, !isEditedInstructorDisplayed); instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(!isOriginalInstructorDisplayed, courseId, !isEditedInstructorDisplayed); instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(!isOriginalInstructorDisplayed, courseIdWithNoInstructorsDisplayed, !isEditedInstructorDisplayed); ______TS("failure: No instructors displayed to students"); InvalidParametersException ive = assertThrows(InvalidParametersException.class, () -> instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(isOriginalInstructorDisplayed, courseIdWithNoInstructorsDisplayed, !isEditedInstructorDisplayed)); assertEquals("At least one instructor must be displayed to students", ive.getMessage()); ______TS("failure: null parameter"); AssertionError ae = assertThrows(AssertionError.class, () -> instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(isOriginalInstructorDisplayed, null, isEditedInstructorDisplayed)); AssertHelper.assertContains("Supplied parameter was null", ae.getMessage()); }</code><technical_language>do need variables if changing? Readers find more confusing up. me, changing variables actual boolean counterparts this set of test case more readable</technical_language>

Target:
private void testVerifyAtLeastOneInstructorIsDisplayed() throws Exception { ______TS("success: at least one instructor is displayed to students"); String courseId = "idOfTypicalCourse1"; String courseIdWithNoInstructorsDisplayed = "idOfTestingInstructorsDisplayedCourse"; instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(courseId, true, true); instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(courseId, true, false); instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(courseId, false, false); instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(courseIdWithNoInstructorsDisplayed, false, false); ______TS("failure: No instructors displayed to students"); InvalidParametersException ive = assertThrows(InvalidParametersException.class, () -> instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(courseIdWithNoInstructorsDisplayed, true, false)); assertEquals("At least one instructor must be displayed to students", ive.getMessage()); ______TS("failure: null parameter"); AssertionError ae = assertThrows(AssertionError.class, () -> instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(null, true, true)); AssertHelper.assertContains("Supplied parameter was null", ae.getMessage()); }
Source:
<code>private void testUpdate(Checksum checksum, ByteBufChecksum wrapped, ByteBuf buf, int off, int len) { checksum.reset(); wrapped.reset(); checksum.update(BYTE_ARRAY, off, len); wrapped.update(buf, off, len); <START> assertEquals(checksum.getValue(), wrapped.getValue()); <END> }</code><technical_language>put of this in a try {...} finally { buf.release(); } block</technical_language>

Target:
private static void testUpdate(Checksum checksum, ByteBufChecksum wrapped, ByteBuf buf, int off, int len) { checksum.reset(); wrapped.reset(); checksum.update(BYTE_ARRAY, off, len); wrapped.update(buf, off, len); assertEquals(checksum.getValue(), wrapped.getValue()); }
Source:
<code>default Optional<float[]> getFloatArrayAttribute(final String tag) { final Optional<Object> attr = getAttribute(tag); if (!attr.isPresent()) { return Optional.empty(); } final Object val = attr.get(); if (val instanceof float[]) { return Optional.of((float[])val); } <START> throw new SAMException("Value for tag " + tag + " is not a byte[]: " + val.getClass()); <END> }</code><technical_language>~byte~ float</technical_language>

Target:
default Optional<float[]> getFloatArrayAttribute(final String tag) { final Optional<Object> attr = getAttribute(tag); if (!attr.isPresent()) { return Optional.empty(); } final Object val = attr.get(); if (val instanceof float[]) { return Optional.of((float[])val); } throw new SAMException("Value for tag " + tag + " is not a float[]: " + val.getClass()); }
Source:
<code>public InputReader(InputStream inputStream) { fResult = new StringBuilder(); fReader = new InputStreamReader(inputStream); fThread = new Thread() { @Override public void run() { final char[] buffer = new <START> char[1024]; <END> int read; try { while (!fDone && (read = fReader.read(buffer)) > 0) { fResult.append(buffer, 0, read); } } catch (IOException e) { } } }; fThread.start(); }</code><technical_language>bring constants back</technical_language>

Target:
public InputReader(InputStream inputStream) { fResult = new StringBuilder(); fReader = new InputStreamReader(inputStream); fThread = new Thread() { @Override public void run() { final char[] buffer = new char[BYTES_PER_KB]; int read; try { while (!fDone && (read = fReader.read(buffer)) > 0) { fResult.append(buffer, 0, read); } } catch (IOException e) { } } }; fThread.start(); }
Source:
<code>public TmfRGB(short red, short green, short blue) { if ((red > 255) || (red < 0) || (green > 255) || (green < 0) || (blue > 255) || (blue < 0)) { <START> throw new IllegalArgumentException("Red, green and blue component must be between 0 and 255"); END> } fRed = red; fGreen = green; fBlue = blue; }</code><technical_language>need describe argument is bad, tracking errors</technical_language>

Target:
public TmfRGB(short red, short green, short blue) { if ((red > 255) || (red < 0)) { throw new IllegalArgumentException("Red component must be between 0 and 255"); } if ((green > 255) || (green < 0)) { throw new IllegalArgumentException("Green component must be between 0 and 255"); } if ((blue > 255) || (blue < 0)) { throw new IllegalArgumentException("Blue component must be between 0 and 255"); } fRed = red; fGreen = green; fBlue = blue; }
Source:
<code>public void setHits(long hits) { <START> this.hits = hits; <END> }</code><technical_language>This method protected updater instead of direct field access</technical_language>

Target:
protected void setHits(long hits) { HITS_UPDATER.set(this, hits); }
Source:
<code>public static byte[] buildAndSaveKeystore(final String alias, final String cert, final String privateKey, final String storePassword) throws KeyStoreException, CertificateException, <START> NoSuchAlgorithmException, InvalidKeySpecException, IOException { <END> final KeyStore ks = buildKeystore(alias, cert, privateKey, storePassword); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { ks.store(os, storePassword != null ? storePassword.toCharArray() : null); return os.toByteArray(); } }</code><technical_language>Please consider adding Preconditions.checkArgument checks: * alias is blank * cert is blank * privateKey is blank</technical_language>

Target:
public static byte[] buildAndSaveKeystore(final String alias, final String cert, final String privateKey, final String storePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, IOException { Preconditions.checkArgument(!Strings.isNullOrEmpty(alias), "Certificate alias cannot be blank"); Preconditions.checkArgument(!Strings.isNullOrEmpty(cert), "Certificate cannot be blank"); Preconditions.checkArgument(!Strings.isNullOrEmpty(privateKey), "Private key cannot be blank"); final KeyStore ks = buildKeystore(alias, cert, privateKey, storePassword); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { ks.store(os, storePassword != null ? storePassword.toCharArray() : null); return os.toByteArray(); } }
Source:
<code>public AppendBlobItem(final String eTag, final OffsetDateTime lastModified, final byte[] contentMd5, final boolean isServerEncrypted, final String encryptionKeySha256, final String blobAppendOffset, final Integer blobCommittedBlockCount) { this.eTag = eTag; this.lastModified = lastModified; this.contentMd5 = CoreUtils.clone(contentMd5); <START> this.isServerEncrypted = isServerEncrypted; <END> this.encryptionKeySha256 = encryptionKeySha256; this.encryptionScope = null; this.blobAppendOffset = blobAppendOffset; this.blobCommittedBlockCount = blobCommittedBlockCount; }</code><technical_language>I is preferable if this overload calls next one</technical_language>

Target:
public AppendBlobItem(final String eTag, final OffsetDateTime lastModified, final byte[] contentMd5, final boolean isServerEncrypted, final String encryptionKeySha256, final String blobAppendOffset, final Integer blobCommittedBlockCount) { this(eTag, lastModified, contentMd5, isServerEncrypted, encryptionKeySha256, null, blobAppendOffset, blobCommittedBlockCount); }
Source:
<code>private List<String> getErrors() { List<String> errors = new ArrayList<>(); if (!exportDir.isPresent()) errors.add("Export directory was not specified."); if (!exportDir.filter(path -> Files.exists(path)).isPresent()) errors.add(DIR_NOT_EXIST); if (!exportDir.filter(path -> Files.isDirectory(path)).isPresent()) errors.add(DIR_NOT_DIRECTORY); if (!exportDir.filter(path -> !isUnderODKFolder(path.toFile())).isPresent()) errors.add(DIR_INSIDE_ODK_DEVICE_DIRECTORY); if (!exportDir.filter(path -> !isUnderBriefcaseFolder(path.toFile())).isPresent()) errors.add(DIR_INSIDE_BRIEFCASE_STORAGE); if (startDate.isPresent() && !endDate.isPresent()) errors.add("Missing date range end definition"); if (!startDate.isPresent() && endDate.isPresent()) errors.add("Missing date range start definition"); if (!isDateRangeValid()) errors.add(INVALID_DATE_RANGE_MESSAGE); <START> if (!isPemFilePresent()) <END> errors.add(INVALID_PEM_FILE); return errors; }</code><technical_language>This right is: ExportConfiguration is valid a PEM file. Pem file is required for encrypted forms. ExportConfiguration if a configuration for encrypted form compute validness</technical_language>

Target:
private List<String> getErrors() { List<String> errors = new ArrayList<>(); if (!exportDir.isPresent()) errors.add("Export directory was not specified."); if (!exportDir.filter(path -> Files.exists(path)).isPresent()) errors.add(DIR_NOT_EXIST); if (!exportDir.filter(path -> Files.isDirectory(path)).isPresent()) errors.add(DIR_NOT_DIRECTORY); if (!exportDir.filter(path -> !isUnderODKFolder(path.toFile())).isPresent()) errors.add(DIR_INSIDE_ODK_DEVICE_DIRECTORY); if (!exportDir.filter(path -> !isUnderBriefcaseFolder(path.toFile())).isPresent()) errors.add(DIR_INSIDE_BRIEFCASE_STORAGE); if (startDate.isPresent() && !endDate.isPresent()) errors.add("Missing date range end definition"); if (!startDate.isPresent() && endDate.isPresent()) errors.add("Missing date range start definition"); if (!isDateRangeValid()) errors.add(INVALID_DATE_RANGE_MESSAGE); if (formNeedsPrivateKey.orElse(false) && !isPemFilePresent()) errors.add(INVALID_PEM_FILE); return errors; }
Source:
<code><START> private void addGroups(Map<String, Map<ServerLocationAndMemberId, LoadHolder>> map, <END> String[] groups, LoadHolder holder, String memberId) { for (String group : groups) { Map<ServerLocationAndMemberId, LoadHolder> groupMap = map.computeIfAbsent(group, k -> new HashMap<>()); groupMap.put(new ServerLocationAndMemberId(holder.getLocation(), memberId), holder); } if (!(groups.length > 0 && groups[0].equals(GatewayReceiver.RECEIVER_GROUP))) { Map<ServerLocationAndMemberId, LoadHolder> groupMap = map.computeIfAbsent(null, k -> new HashMap<>()); groupMap.put(new ServerLocationAndMemberId(holder.getLocation(), memberId), holder); } }</code><technical_language>This is a new method be, leat, unit tested. package private, annotate @VisibleForTesting access LocatorLoadSnapshotJUnitTest and/or LocatorLoadSnapshotIntegrationTest</technical_language>

Target:
void addGroups(Map<String, Map<ServerLocationAndMemberId, LoadHolder>> map, String[] groups, LoadHolder holder, String memberId) { for (String group : groups) { Map<ServerLocationAndMemberId, LoadHolder> groupMap = map.computeIfAbsent(group, k -> new HashMap<>()); groupMap.put(new ServerLocationAndMemberId(holder.getLocation(), memberId), holder); } if (!(groups.length > 0 && groups[0].equals(GatewayReceiver.RECEIVER_GROUP))) { Map<ServerLocationAndMemberId, LoadHolder> groupMap = map.computeIfAbsent(null, k -> new HashMap<>()); groupMap.put(new ServerLocationAndMemberId(holder.getLocation(), memberId), holder); } }
Source:
<code><START> public List<TileEntity> getBaseTilesFor(TileEntity tile) { <END> List<TileEntity> tiles = new ArrayList<TileEntity>(1); tiles.add(tile); return tiles; }</code><technical_language>This controller interface. is identify If LP is connected fluid providing structure support a provider pipe a supplier pipe structure causing a loop</technical_language>

Target:
public List<TileEntity> getBaseTilesFor(TileEntity tile) { List<TileEntity> tiles = new ArrayList<TileEntity>(1); if(tile instanceof IGridHost){ IGridHost host = (IGridHost) tile; IGridNode node = host.getGridNode(ForgeDirection.UNKNOWN); if(node != null){ TileEntity base = getBaseTileEntity(node); if(base != null){ tiles.add(base); return tiles; } } } tiles.add(tile); return tiles; }
Source:
<code>private Planner getPlanner(List<RelTraitDef> traitDefs, SqlParser.Config parserConfig, Program... programs) { final SchemaPlus rootSchema = Frameworks.createRootSchema(true); final FrameworkConfig config = Frameworks.newConfigBuilder() .parserConfig(parserConfig) .defaultSchema( <START> CalciteAssert.addSchema(rootSchema, SchemaSpec.HR)) <END> .traitDefs(traitDefs) .programs(programs) .build(); return Frameworks.getPlanner(config); }</code><technical_language>this is a spurious change. out</technical_language>

Target:
private Planner getPlanner(List<RelTraitDef> traitDefs, SqlParser.Config parserConfig, Program... programs) { final SchemaPlus rootSchema = Frameworks.createRootSchema(true); final FrameworkConfig config = Frameworks.newConfigBuilder() .parserConfig(parserConfig) .defaultSchema( CalciteAssert.addSchema(rootSchema, CalciteAssert.SchemaSpec.HR)) .traitDefs(traitDefs) .programs(programs) .build(); return Frameworks.getPlanner(config); }
Source:
<code>public URI uploadSegment(File segmentFile, LLCSegmentName segmentName) { if (_segmentStoreUriStr == null || _segmentStoreUriStr.isEmpty()) { return null; } Callable<URI> uploadTask = () -> { try { PinotFS pinotFS = PinotFSFactory.create(new URI(_segmentStoreUriStr).getScheme()); URI destUri = new URI(StringUtil .join(File.separator, _segmentStoreUriStr, segmentName.getTableName(), segmentName.getSegmentName())); if (pinotFS.exists(destUri)) { pinotFS.delete(destUri, true); } pinotFS.copyFromLocalFile(segmentFile, destUri); return destUri; } catch (Exception e) { <START> LOGGER.warn("Failed copy segment tar file to segment store {}: {}", segmentFile.getName(), e); <END> } return null; }; Future<URI> future = _executorService.submit(uploadTask); try { URI segmentLocation = future.get(_timeoutInMs, TimeUnit.MILLISECONDS); return segmentLocation; } catch (InterruptedException e) { LOGGER.info("Interrupted while waiting for segment upload."); Thread.currentThread().interrupt(); } catch (Exception e) { LOGGER .warn("Failed to upload file of segment for table ", segmentFile.getAbsolutePath(), segmentName, e); } return null; }</code><technical_language>include segment destUri in log</technical_language>

Target:
public URI uploadSegment(File segmentFile, LLCSegmentName segmentName) { if (_segmentStoreUriStr == null || _segmentStoreUriStr.isEmpty()) { return null; } Callable<URI> uploadTask = () -> { URI destUri = new URI(StringUtil .join(File.separator, _segmentStoreUriStr, segmentName.getTableName(), segmentName.getSegmentName())); try { PinotFS pinotFS = PinotFSFactory.create(new URI(_segmentStoreUriStr).getScheme()); if (pinotFS.exists(destUri)) { pinotFS.delete(destUri, true); } pinotFS.copyFromLocalFile(segmentFile, destUri); return destUri; } catch (Exception e) { LOGGER.warn("Failed copy segment tar file to segment store {}: {}", segmentFile.getName(), destUri, e); } return null; }; Future<URI> future = _executorService.submit(uploadTask); try { URI segmentLocation = future.get(_timeoutInMs, TimeUnit.MILLISECONDS); return segmentLocation; } catch (InterruptedException e) { LOGGER.info("Interrupted while waiting for segment upload of to {}.", segmentName, _segmentStoreUriStr); Thread.currentThread().interrupt(); } catch (Exception e) { LOGGER .warn("Failed to upload file of segment for table ", segmentFile.getAbsolutePath(), segmentName, e); } return null; }
Source:
<code>private AllocatedEvaluator launchContainerForExecutor(final HeronWorker worker) { Future<AllocatedEvaluator> result = executor.submit(new Callable<AllocatedEvaluator>() { @Override public AllocatedEvaluator call() throws Exception { AllocatedEvaluator evaluator = allocateContainer(worker.workerId, worker.cores, worker.mem); if (evaluator == null) { LOG.log(Level.WARNING, "Could not allocate container for id {0}", worker.workerId); return null; } Configuration context = createContextConfig(worker.workerId); LOG.log(Level.INFO, "Activating container {0} for heron executor, id: {1}", new Object[]{evaluator.getId(), worker.workerId}); evaluator.submitContext(context); multiKeyWorkerMap.assignEvaluatorToWorker(worker, evaluator); return evaluator; } }); try { return result.get(); } catch (InterruptedException e) { LOG.log(Level.SEVERE, "Interrupted while waiting for container", e); } catch (ExecutionException e) { LOG.log(Level.SEVERE, "Error while waiting for container", e); } <START> return null; <END> }</code><technical_language>appears returning null mask exceptional condition. instead throw exception</technical_language>

Target:
private AllocatedEvaluator launchContainerForExecutor(final HeronWorker worker) throws ContainerAllocationException { Future<AllocatedEvaluator> result = executor.submit(new Callable<AllocatedEvaluator>() { @Override public AllocatedEvaluator call() throws Exception { AllocatedEvaluator evaluator = allocateContainer(worker.workerId, worker.cores, worker.mem); Configuration context = createContextConfig(worker.workerId); LOG.log(Level.INFO, "Activating container {0} for heron executor, id: {1}", new Object[]{evaluator.getId(), worker.workerId}); evaluator.submitContext(context); multiKeyWorkerMap.assignEvaluatorToWorker(worker, evaluator); return evaluator; } }); try { return result.get(); } catch (InterruptedException e) { throw new ContainerAllocationException("Interrupted while waiting for container", e); } catch (ExecutionException e) { throw new ContainerAllocationException("Error while allocating container", e); } }
Source:
<code>public Iterable<SignedIdentifier> getAccessPolicy() { <START> return client.getAccessPolicy().collectList().block(); <END> }</code><technical_language>toIterable() here</technical_language>

Target:
public Iterable<SignedIdentifier> getAccessPolicy() { return client.getAccessPolicy().toIterable(); }
Source:
<code>public void testRoomDoesNotAllowsBlankTextForDisplayName() { HomeAdminPage homeAdminPage = new HomeAdminPage(); roomsPage = homeAdminPage.clickConferenceRoomsLink(); JsonReader jsonReader = new JsonReader(); <START> String roomJsonFilePath = "\\src\\tests\\Room1.json"; <END> String specialCharacters = jsonReader.readJsonFile("customName" , roomJsonFilePath); roomsPage.clickConferenceRoomsLink(); roomInfoPage = roomsPage.doubleClickOverRoomName(roomName); roomsPage = roomInfoPage.setDisplayName(specialCharacters) .clickSaveBtn(); roomInfoPage = roomsPage.doubleClickOverRoomName(specialCharacters); Assert.assertTrue(roomsPage.getRoomDisplayName(specialCharacters).contains(specialCharacters)); }</code><technical_language>add this path global variables</technical_language>

Target:
public void testRoomDoesNotAllowsBlankTextForDisplayName() { HomeAdminPage homeAdminPage = new HomeAdminPage(); roomsPage = homeAdminPage.clickConferenceRoomsLink(); JsonReader jsonReader = new JsonReader(); String specialCharacters = jsonReader.readJsonFile("customName" , ROOM1_PATH); roomsPage.clickConferenceRoomsLink(); roomInfoPage = roomsPage.doubleClickOverRoomName(roomName); roomsPage = roomInfoPage.setDisplayName(specialCharacters) .clickSaveBtn(); roomInfoPage = roomsPage.doubleClickOverRoomName(specialCharacters); Assert.assertTrue(roomsPage.getRoomDisplayName(specialCharacters).contains(specialCharacters)); }
Source:
<code>public DatabaseRow poll() throws SQLException { <START> if (_queryResultSet == null) { END> executeFirstChunkedQuery(); _queryStmt = _connection.prepareStatement(_chunkedQuery); _queryStmt.setFetchSize(_fetchSize); _queryStmt.setQueryTimeout(_queryTimeoutSecs); } if (!_queryResultSet.next()) { if (_endOfFile) { return null; } if (numRowsInResult < _chunkSize) { _endOfFile = true; return null; } numRowsInResult = 0; prepareChunkedQuery(); executeChunkedQuery(); if (!_queryResultSet.next()) { _endOfFile = true; return null; } } return getNextRow(); }</code><technical_language>I suggest move logic start() Throw exception if queryResultSet is null here, asking user call start() poll()</technical_language>

Target:
public DatabaseRow poll() throws SQLException { if (!_initialized) { throw new DatastreamRuntimeException("call start before calling poll for records"); } if (_queryResultSet == null) { executeFirstChunkedQuery(); _queryStmt = _connection.prepareStatement(_chunkedQuery); _queryStmt.setFetchSize(_fetchSize); _queryStmt.setQueryTimeout(_queryTimeoutSecs); } if (!_queryResultSet.next()) { if (numRowsInResult < _chunkSize) { return null; } numRowsInResult = 0; prepareChunkedQuery(); executeChunkedQuery(); if (!_queryResultSet.next()) { return null; } } return getNextRow(); }
Source:
<code>public boolean processStateMessage(Message message) { if (super.processStateMessage(message) == HANDLED) { return HANDLED; } switch (message.what) { case CMD_HANDLE_RECEIVED_RESPONSE: try { ReceivedResponse resp = (ReceivedResponse) message.obj; validateDeleteRespPayloadAndExchangeType( resp.responsePayloads, resp.exchangeType); boolean currentSaSpiFound = hasRemoteChildSpiForDelete( resp.responsePayloads, mCurrentChildSaRecord); if (!currentSaSpiFound) { loge( "Found no remote SPI for current SA in received Delete" + " response. Shutting down anyways."); } } catch (IkeProtocolException e) { loge( "Received Delete response with invalid syntax or error" + " notifications. <START> Shutting down anyways.", <END> e); } finishRekey(); transitionTo(mIdle); return HANDLED; default: return NOT_HANDLED; } }</code><technical_language>Is this correct? is this "Finishing rekey" end in a consistent state</technical_language>

Target:
public boolean processStateMessage(Message message) { if (super.processStateMessage(message) == HANDLED) { return HANDLED; } switch (message.what) { case CMD_HANDLE_RECEIVED_RESPONSE: try { ReceivedResponse resp = (ReceivedResponse) message.obj; validateDeleteRespPayloadAndExchangeType( resp.responsePayloads, resp.exchangeType); boolean currentSaSpiFound = hasRemoteChildSpiForDelete( resp.responsePayloads, mCurrentChildSaRecord); if (!currentSaSpiFound) { loge( "Found no remote SPI for current SA in received Delete" + " response. Shutting down old SA and finish rekey."); } } catch (IkeProtocolException e) { loge( "Received Delete response with invalid syntax or error" + " notifications. Shutting down old SA and finish rekey.", e); } finishRekey(); transitionTo(mIdle); return HANDLED; default: return NOT_HANDLED; } }
Source:
<code>public void testConnectTimeout() throws IOException, StripeException { <START> Stripe.overrideApiBase("<LINK_0>"); <END> thrown.expect(APIConnectionException.class); thrown.expectMessage("connect timed out"); final RequestOptions options = RequestOptions.builder().setConnectTimeout(1).build(); Balance.retrieve(options); }</code><technical_language>Damn, I done</technical_language>

Target:
public void testConnectTimeout() throws IOException, StripeException { Stripe.overrideApiBase("<LINK_1>"); thrown.expect(APIConnectionException.class); thrown.expectMessage("connect timed out"); final RequestOptions options = RequestOptions.builder().setConnectTimeout(1).build(); Balance.retrieve(options); }
Source:
<code>public void agentStatus() { <START> LinkedBlockingQueue<Message> agentQueue = this.messagingClient.getMessageProcessor().getMessageQueue(); <END> if( agentQueue.isEmpty() ) { System.out.println( "There is no message being processed in agent queue" ); } else { System.out.println( "The number total of messages in agent queue is : "+agentQueue.size() ); System.out.println( "The types of messages being processed are : " ); for( Message msg : agentQueue ) { System.out.println( msg.getClass().getSimpleName() ); } } }</code><technical_language>unit tests? IMO, easier for this method return a string (built a StringBuilder object). This way, is easy verify decide do want result</technical_language>

Target:
public String agentStatus() { StringBuilder sb = new StringBuilder(); LinkedBlockingQueue<Message> agentQueue = this.messagingClient.getMessageProcessor().getMessageQueue(); if( agentQueue.isEmpty() ) { sb.append( "There is no message being processed in agent queue\n" ); } else { sb.append( "Agent " + getScopedInstancePath() + " (" + getApplicationName() + ")\n" ); sb.append( "The number total of messages in agent queue is : " + agentQueue.size() + "\n" ); sb.append( "The types of messages being processed are : " + "\n"); for( Message msg : agentQueue ) { sb.append( msg.getClass().getSimpleName() + "\n" ); } } return sb.toString(); }
Source:
<code>public static void testSetInts() { byte[] destination = new byte[POSITIONS_PER_PAGE * ARRAY_INT_INDEX_SCALE]; int copiedBytes = setInts(destination, 0, IntStream.range(0, POSITIONS_PER_PAGE).toArray(), 0, POSITIONS_PER_PAGE); assertEquals(copiedBytes, POSITIONS_PER_PAGE * ARRAY_INT_INDEX_SCALE); assertCopied( <START> IntStream.range(0, POSITIONS_PER_PAGE).boxed().collect(Collectors.toList()), <END> destination, ARRAY_INT_INDEX_SCALE, ByteArrays::getInt); }</code><technical_language>toImmutableList()? -- this in presto-main Guava right? ditto for other Collectors.toList() in this test BlockAssertions</technical_language>

Target:
public static void testSetInts() { byte[] destination = new byte[POSITIONS_PER_PAGE * ARRAY_INT_INDEX_SCALE]; int copiedBytes = setInts(destination, 0, IntStream.range(0, POSITIONS_PER_PAGE).toArray(), 0, POSITIONS_PER_PAGE); assertEquals(copiedBytes, POSITIONS_PER_PAGE * ARRAY_INT_INDEX_SCALE); assertCopied( IntStream.range(0, POSITIONS_PER_PAGE).boxed().collect(toImmutableList()), destination, ARRAY_INT_INDEX_SCALE, ByteArrays::getInt); }