auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>SearchMandateConnectorResponse getMandatesFromDDConnector(Account account, DirectDebitSearchMandatesParams params) { WebTarget webTargetWithoutQuery = client.target(directDebitConnectorUriGenerator.mandatesURI(account)); WebTarget webTargetWithQuery = addQueryParams(params.paramsAsMap(), webTargetWithoutQuery); Response response = webTargetWithQuery .request() .accept(APPLICATION_JSON) .get(); if (response.getStatus() == HttpStatus.SC_OK) { return response.readEntity(SearchMandateConnectorResponse.class); } else { <START> throw new SearchMandatesException(response); <END> } }</code><technical_language>need explicit else clause here: java if (response.getStatus() == HttpStatus.SC_OK) { return response.readEntity(SearchMandateConnectorResponse.class); } throw new SearchMandatesException(response);</technical_language>

Target:
SearchMandateConnectorResponse getMandatesFromDDConnector(Account account, DirectDebitSearchMandatesParams params) { WebTarget webTargetWithoutQuery = client.target(directDebitConnectorUriGenerator.mandatesURI(account)); WebTarget webTargetWithQuery = addQueryParams(params.paramsAsMap(), webTargetWithoutQuery); Response response = webTargetWithQuery .request() .accept(APPLICATION_JSON) .get(); if (response.getStatus() != HttpStatus.SC_OK) { throw new SearchMandatesException(response); } return response.readEntity(SearchMandateConnectorResponse.class); }
Source:
<code>public static CoreException newCoreException(String s, Throwable e) { IStatus status; if (e instanceof CoreException) { if (s == null) s = ""; status = new MultiStatus("org.eclipse.update.configurator", 0, s, e); IStatus childrenStatus = ((CoreException) e).getStatus(); ((MultiStatus) status).add(childrenStatus); ((MultiStatus) status).addAll(childrenStatus); } else { StringBuilder completeString = new <START> StringBuilder(""); <END> if (s != null) completeString.append(s); if (e != null) { completeString.append(" ["); String msg = e.getLocalizedMessage(); completeString.append(msg!=null?msg:e.toString()); completeString.append("]"); } status = newStatus(completeString.toString(), e); } return new CoreException(status); }</code><technical_language>empty string neccesary here</technical_language>

Target:
public static CoreException newCoreException(String s, Throwable e) { IStatus status; if (e instanceof CoreException) { if (s == null) s = ""; status = new MultiStatus("org.eclipse.update.configurator", 0, s, e); IStatus childrenStatus = ((CoreException) e).getStatus(); ((MultiStatus) status).add(childrenStatus); ((MultiStatus) status).addAll(childrenStatus); } else { StringBuilder completeString = new StringBuilder(); if (s != null) completeString.append(s); if (e != null) { completeString.append(" ["); String msg = e.getLocalizedMessage(); completeString.append(msg!=null?msg:e.toString()); completeString.append("]"); } status = newStatus(completeString.toString(), e); } return new CoreException(status); }
Source:
<code>public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { final Consumer<DeviceCodeInfo> deviceCodeInfoConsumer; <START> if (deviceCodeConsumer != null) { deviceCodeInfoConsumer = deviceCodeConsumer; } else { deviceCodeInfoConsumer = deviceCodeInfo -> System.out.println(deviceCodeInfo.getMessage()); } <END> return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeInfoConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return pc.acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); }</code><technical_language>This consumer a static constant. I consumer tied lifetime of credential. private static final Consumer<DeviceCodeInfo> DEVICE_CODE_CONSUMER = deviceCodeInfo -> System.out.println(deviceCodeInfo.getMessage());</technical_language>

Target:
public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return pc.acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); }
Source:
<code>public void moveDown(){ <START> setY(getY() + 2.2); <END> setX(getX() + 0.7); }</code><technical_language>in DiagonalBulletLeft class</technical_language>

Target:
public void moveDown(){ setY(getY() + downspeed); setX(getX() + 0.7); }
Source:
<code>public boolean replaceValue(Object key, InternalCacheEntry cacheEntry) { <START> throw new CacheException("This context is immutable"); <END> }</code><technical_language>Some of unsupported methods do throw newUnsupportedMethod(); while others do throw new CacheException("This context is immutable");. identical</technical_language>

Target:
public boolean replaceValue(Object key, InternalCacheEntry cacheEntry) { throw newUnsupportedMethod(); }
Source:
<code>private String toShellFormat(String value) { <START> if (value.contains("\'") && value.contains("\"")) { <END> throw new RuntimeException("Spark property value could not contain both \" and '"); } else if (value.contains("'")) { return "\"" + value + "\""; } else { return "'" + value + "'"; } }</code><technical_language>"\'" -> "'"</technical_language>

Target:
private String toShellFormat(String value) { if (value.contains("'") && value.contains("\"")) { throw new RuntimeException("Spark property value could not contain both \" and '"); } else if (value.contains("'")) { return "\"" + value + "\""; } else { return "'" + value + "'"; } }
Source:
<code>public void testRunWithHeartbeatWithCancelRequestedTask() { TaskRequest taskRequest = OperatorTestingUtils.newTaskRequest(simpleConfig).withIsCancelRequested(true); OperatorManager om = spy(operatorManager); Operator op = mock(Operator.class); OperatorFactory of = mock(OperatorFactory.class); doReturn(of).when(registry).get(any(), any()); doReturn(op).when(of).newOperator(any()); om.runWithHeartbeat(taskRequest); verify(op, times(0)).run(); verify(op, times(1)).cleanup(any(TaskRequest.class)); <START> } <END></code><technical_language>need check if taskFailed is called</technical_language>

Target:
public void testRunWithHeartbeatWithCancelRequestedTask() { TaskRequest taskRequest = OperatorTestingUtils.newTaskRequest(simpleConfig).withIsCancelRequested(true); OperatorManager om = spy(operatorManager); Operator op = mock(Operator.class); OperatorFactory of = mock(OperatorFactory.class); doReturn(of).when(registry).get(any(), any()); doReturn(op).when(of).newOperator(any()); om.runWithHeartbeat(taskRequest); verify(op, times(0)).run(); verify(op, times(1)).cleanup(any(TaskRequest.class)); verify(callback, times(0)).taskSucceeded(any(), any(), any()); verify(callback, times(1)).taskFailed(eq(taskRequest), any(), any()); verify(callback, times(0)).retryTask(any(), any(), anyInt(), any(), any()); }
Source:
<code>public int compareTo(@NonNull Object aThat) { if (this == aThat) return 0; final Result that = (Result) aThat; int result; <START> for (int i = 0; i < Math.min(this.codePoints.length, that.codePoints.length); i += 1) { <END> if ((result = this.codePoints[i] - that.codePoints[i]) != 0) return result; } if (this.codePoints.length != that.codePoints.length) return this.codePoints.length - that.codePoints.length; if (BuildConfig.DEBUG && !this.equals(that)) throw new AssertionError("compareTo inconsistent with equals."); return 0; }</code><technical_language>compute min once? Seeme is calculated cycle right now</technical_language>

Target:
public int compareTo(@NonNull Object aThat) { if (this == aThat) return 0; final Result that = (Result) aThat; int result; int minLength = Math.min(this.codePoints.length, that.codePoints.length); for (int i = 0; i < minLength; i += 1) { if ((result = Character.toLowerCase(this.codePoints[i]) - Character.toLowerCase(that.codePoints[i])) != 0) return result; } if (this.codePoints.length != that.codePoints.length) return this.codePoints.length - that.codePoints.length; if (BuildConfig.DEBUG && !this.equals(that)) throw new AssertionError("compareTo inconsistent with equals."); return 0; }
Source:
<code>public void testLedgerDigests() throws Exception { DigestType[] types = new DigestType[] { <START> DigestType.CRC32, <END> DigestType.CRC32C, DigestType.DUMMY, DigestType.MAC }; for (DigestType type: types) { long lId; try (WriteHandle writer = result(newCreateLedgerOp() .withAckQuorumSize(1) .withWriteQuorumSize(2) .withEnsembleSize(3) .withDigestType(type) .withPassword(password) .execute())) { lId = writer.getId(); assertEquals(-1L, writer.getLastAddPushed()); result(writer.append(ByteBuffer.wrap(bigData))); assertEquals(bigData.length, writer.getLength()); } try (ReadHandle reader = result(newOpenLedgerOp() .withDigestType(type) .withPassword(password) .withLedgerId(lId) .execute())) { LedgerEntries entries = result(reader.read(0, 0)); checkEntries(entries, bigData); } result(newDeleteLedgerOp().withLedgerId(lId).execute()); } }</code><technical_language>Sine this is *enum* DigestType.values() cover new types in future</technical_language>

Target:
public void testLedgerDigests() throws Exception { for (DigestType type: DigestType.values()) { long lId; try (WriteHandle writer = result(newCreateLedgerOp() .withAckQuorumSize(1) .withWriteQuorumSize(2) .withEnsembleSize(3) .withDigestType(type) .withPassword(password) .execute())) { lId = writer.getId(); assertEquals(-1L, writer.getLastAddPushed()); result(writer.append(ByteBuffer.wrap(bigData))); assertEquals(bigData.length, writer.getLength()); } try (ReadHandle reader = result(newOpenLedgerOp() .withDigestType(type) .withPassword(password) .withLedgerId(lId) .execute())) { LedgerEntries entries = result(reader.read(0, 0)); checkEntries(entries, bigData); } result(newDeleteLedgerOp().withLedgerId(lId).execute()); } }
Source:
<code>public void assertSimilarity(final File actualFile, final double maxDistance) throws IOException { BufferedImage tempImg = ImageIO.read(actualFile); File tempFile = File.createTempFile("print-test", ".png"); ImageIO.write(tempImg, "png", tempFile); <START> assertSimilarity(ImageIO.read(tempFile), maxDistance); <END> }</code><technical_language>forgot revert</technical_language>

Target:
public void assertSimilarity(final File actualFile, final double maxDistance) throws IOException { assertSimilarity(ImageIO.read(actualFile), maxDistance); }
Source:
<code><START> public Collection<Filter> getFilters() { return filters; } <END></code><technical_language>Concern: changes filters-related methods breaking changes, pretty break existing code. (Unless missing something, is possible.)</technical_language>

Target:
public List<Map<String, Object>> getFilters() { RequestParameterCollection<Filter> requestFilterCollection = new RequestParameterCollection<Filter>(filters); Collection<Object> requestObjects = requestFilterCollection.constructParameterRequestArgs(); List<Map<String, Object>> result = new LinkedList<Map<String, Object>>(); for (Object object : requestObjects) { result.add((Map<String, Object>)object); } return result; }
Source:
<code>SyncToken(String syncToken) { String localId = null; String localValue = null; Long localSequenceNumber = null; <START> if (!CoreUtils.isNullOrEmpty(syncToken)) { <END> final String[] syncTokenParts = syncToken.split(";", 2); if (syncTokenParts.length == 2) { String[] idParts = syncTokenParts[0].split("=", 2); String[] snParts = syncTokenParts[1].split("=", 2); if (idParts.length == 2 && snParts.length == 2 && !idParts[0].isEmpty() && !idParts[1].isEmpty() && !snParts[0].isEmpty() && !snParts[1].isEmpty()) { try { localSequenceNumber = Long.parseLong(snParts[1]); localId = idParts[0]; localValue = idParts[1]; } catch (NumberFormatException ex) { } } } } this.sequenceNumber = localSequenceNumber; this.value = localValue; this.id = localId; }</code><technical_language>throw if is empty constructing invalid object</technical_language>

Target:
SyncToken(String syncToken) { if (CoreUtils.isNullOrEmpty(syncToken)) { throw logger.logExceptionAsError(new IllegalArgumentException(CANNOT_EMPTY_OR_NULL)); } final String[] syncTokenParts = syncToken.split(SEMICOLON, 2); if (syncTokenParts.length != 2) { throw logger.logExceptionAsError(new IllegalArgumentException(VALID_FORMAT_ERROR_MESSAGE)); } final String[] idParts = syncTokenParts[0].split(EQUAL, 2); final String[] snParts = syncTokenParts[1].split(EQUAL, 2); if (idParts.length != 2 || snParts.length != 2 || idParts[0].isEmpty() || idParts[1].isEmpty() || snParts[0].isEmpty() || snParts[1].isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException(VALID_FORMAT_ERROR_MESSAGE)); } try { this.sequenceNumber = Long.parseLong(snParts[1]); } catch (NumberFormatException ex) { throw logger.logExceptionAsError(new IllegalArgumentException(SEQUENCE_NUMBER_CANNOT_PARSED)); } this.id = idParts[0]; this.value = idParts[1]; }
Source:
<code>private List<String> ensureCardsHaveHomeDeck(Runnable notifyProgress, CheckDatabaseResult result) { notifyProgress.run(); Long[] dynDeckIds = getDecks().allDynamicDeckIds(); List<Long> dynIdsAndZero = new ArrayList<>(Arrays.asList(dynDeckIds)); dynIdsAndZero.add(0L); ArrayList<Long> cardIds = mDb.queryColumn(Long.class, "select id from cards where did in " + Utils.ids2str(dynDeckIds) + "and odid in " + Utils.ids2str(dynIdsAndZero) , 0); notifyProgress.run(); if (cardIds.isEmpty()) { return Collections.emptyList(); } <START> Timber.i("Found %d decks with no home deck", cardIds.size()); <END> int fixed = 0; for (long cardId : cardIds) { try { Card c = getCard(cardId); c.setDid(Consts.DEFAULT_DECK_ID); c.setODid(0L); c.note().addTag(mContext.getString(R.string.missing_home_deck_tag)); c.note().flush(); c.flush(); fixed++; } catch (Exception e) { Timber.e(e, "Failed to fix card '%d'", cardId); } } result.setCardsWithFixedHomeDeckCount(fixed); if (fixed == 0) { return Collections.emptyList(); } Timber.d("Completed"); String message = String.format(Locale.US, "Fixed %d decks with no home deck", fixed); return Collections.singletonList(message); }</code><technical_language>suggestion Timber.i("Found %d cards home deck", cardIds.size());</technical_language>

Target:
private List<String> ensureCardsHaveHomeDeck(Runnable notifyProgress, CheckDatabaseResult result) { Timber.d("ensureCardsHaveHomeDeck()"); notifyProgress.run(); Long[] dynDeckIds = getDecks().allDynamicDeckIds(); List<Long> dynIdsAndZero = new ArrayList<>(Arrays.asList(dynDeckIds)); dynIdsAndZero.add(0L); ArrayList<Long> cardIds = mDb.queryColumn(Long.class, "select id from cards where did in " + Utils.ids2str(dynDeckIds) + "and odid in " + Utils.ids2str(dynIdsAndZero) , 0); notifyProgress.run(); if (cardIds.isEmpty()) { return Collections.emptyList(); } String recoveredDeckName = "! " + mContext.getString(R.string.check_integrity_recovered_deck_name); Long nextDeckId = getDecks().id(recoveredDeckName , true); if (nextDeckId == null) { throw new IllegalStateException("Unable to create deck"); } getDecks().flush(); mDb.execute("update cards " + "set did = " + nextDeckId + ", " + "odid = 0," + "mod = " + Utils.intTime() + ", " + "usn = " + usn() + " " + "where did in " + Utils.ids2str(dynDeckIds) + "and odid in " + Utils.ids2str(dynIdsAndZero)); result.setCardsWithFixedHomeDeckCount(cardIds.size()); String message = String.format(Locale.US, "Fixed %d cards with no home deck", cardIds.size()); return Collections.singletonList(message); }
Source:
<code>public boolean isDuplicateDonorNumber(Donor donor) { String donorNumber = donor.getDonorNumber(); if (StringUtils.isBlank(donorNumber)) return false; <START> Donor existingDonor = donorRepository.findDonorByDonorNumber(donorNumber,false); <END> if (existingDonor != null && !existingDonor.getId().equals(donor.getId())) return true; return false; }</code><technical_language>this be: donorRepository.findDonorByDonorNumber(donorNumber,true); including deleted donors</technical_language>

Target:
public boolean isDuplicateDonorNumber(Donor donor) { String donorNumber = donor.getDonorNumber(); if (StringUtils.isBlank(donorNumber)) return false; Donor existingDonor = donorRepository.findDonorByDonorNumber(donorNumber,true); if (existingDonor != null && !existingDonor.getId().equals(donor.getId())) return true; return false; }
Source:
<code>public InputRow nextRow() { <START> while (true) { <END> final InputRow row = firehose.nextRow(); if (row.getTimestampFromEpoch() >= minTime.getMillis()) { return row; } } }</code><technical_language>This check needs done in hasMore(), nextRow(). hasMore() block, nextRow technically is another hasMore() minTime</technical_language>

Target:
public InputRow nextRow() { final InputRow row = savedInputRow; savedInputRow = null; return row; }
Source:
<code>private void testFindProcessInstanceWithQueryFilter(ProcessInstanceQueryFilterSpec filter, Long processInstanceId) { List<Long> resultsIds = new ArrayList<>(); List<ProcessInstance> results = null; results = searchServicesClient. findProcessInstancesWithFilters(filter, 0, 100); <START> resultsIds = new ArrayList<>(); <END> for (ProcessInstance res : results) { resultsIds.add(res.getId()); } Assertions.assertThat(results).isNotNull(); Assertions.assertThat(results.size()).isGreaterThanOrEqualTo(1); Assertions.assertThat(resultsIds).contains(processInstanceId); }</code><technical_language>collection initialized line 189</technical_language>

Target:
private void testFindProcessInstanceWithQueryFilter(ProcessInstanceQueryFilterSpec filter, Long processInstanceId) { List<Long> resultsIds = new ArrayList<>(); List<ProcessInstance> results; results = searchServicesClient. findProcessInstancesWithFilters(filter, 0, 100); for (ProcessInstance res : results) { resultsIds.add(res.getId()); } Assertions.assertThat(results).isNotNull(); Assertions.assertThat(results).isNotEmpty(); Assertions.assertThat(resultsIds).contains(processInstanceId); }
Source:
<code>private Set<String> dependantsToCheck(PluginDisableStrategy strategy) { Set<String> dependantsToCheck; switch (strategy) { case MANDATORY: dependantsToCheck = Sets.difference(this.getDependants(), this.getOptionalDependants()); break; case ALL: dependantsToCheck = this.getDependants(); break; <START> case NONE: <END> default: dependantsToCheck = Sets.difference(this.getDependants(), this.getOptionalDependants()); } return dependantsToCheck; }</code><technical_language>putting MANDATORY together</technical_language>

Target:
private Set<String> dependantsToCheck(PluginDisableStrategy strategy) { Set<String> dependantsToCheck; switch (strategy) { case ALL: dependantsToCheck = this.getDependants(); break; default: dependantsToCheck = Sets.difference(this.getDependants(), this.getOptionalDependants()); } return dependantsToCheck; }
Source:
<code>public void testDeserializationWithIdleReason() throws Exception { <START> Response.MediaStatus response = (Response.MediaStatus) jsonMapper.readValue("{\"responseType\":\"MEDIA_STATUS\",\"status\":[{\"mediaSessionId\":1,\"playbackRate\":1,\"playerState\":\"IDLE\",\"currentTime\":0,\"supportedMediaCommands\":15,\"volume\":{\"level\":1,\"muted\":false,\"increment\":0.04},\"media\":{\"contentId\":\"/public/Videos/Movies/FileB.mp4\",\"contentType\":\"video/transcode\",\"streamType\":\"buffered\",\"duration\":null},\"idleReason\":\"ERROR\"}],\"requestId\":28}", Response.class); <END> assertEquals(1, response.statuses.length); MediaStatus mediaStatus = response.statuses[0]; assertEquals(MediaStatus.IdleReason.ERROR, mediaStatus.idleReason); }</code><technical_language>updated this test instead of writing new one</technical_language>

Target:
public void testDeserializationWithIdleReason() throws Exception { Response.MediaStatus response = (Response.MediaStatus) jsonMapper.readValue("{\"responseType\":\"MEDIA_STATUS\",\"status\":[{\"mediaSessionId\":1,\"playbackRate\":1,\"playerState\":\"IDLE\",\"currentTime\":0,\"supportedMediaCommands\":15,\"volume\":{\"level\":1,\"muted\":false},\"media\":{\"contentId\":\"/public/Videos/Movies/FileB.mp4\",\"contentType\":\"video/transcode\",\"streamType\":\"buffered\",\"duration\":null},\"idleReason\":\"ERROR\"}],\"requestId\":28}", Response.class); assertEquals(1, response.statuses.length); MediaStatus mediaStatus = response.statuses[0]; assertEquals(MediaStatus.IdleReason.ERROR, mediaStatus.idleReason); }
Source:
<code>public void getState_active() { SyncUser user = UserFactory.createUniqueUser(Constants.AUTH_URL); SyncConfiguration syncConfiguration = configFactory .createSyncConfigurationBuilder(user, Constants.SYNC_SERVER_URL) .waitForInitialRemoteData() .build(); Realm realm = Realm.getInstance(syncConfiguration); SyncSession session = SyncManager.getSession(syncConfiguration); <START> assertEquals(SyncSession.State.STATE_ACTIVE, session.getState()); <END> realm.close(); }</code><technical_language>a timing issue involved here, e.g if server is slow returning access token? solve this</technical_language>

Target:
public void getState_active() { SyncUser user = UserFactory.createUniqueUser(Constants.AUTH_URL); SyncConfiguration syncConfiguration = configFactory .createSyncConfigurationBuilder(user, Constants.SYNC_SERVER_URL) .waitForInitialRemoteData() .build(); Realm realm = Realm.getInstance(syncConfiguration); SyncSession session = SyncManager.getSession(syncConfiguration); SystemClock.sleep(TimeUnit.SECONDS.toMillis(2)); assertEquals(SyncSession.State.ACTIVE, session.getState()); realm.close(); }
Source:
<code>void receiveSlowMultipleMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { int count = 3; setSenderAndReceiver(entityType, isSessionEnabled); Duration delayPublishing = Duration.ofMillis(1000); final String messageId = UUID.randomUUID().toString(); AtomicReference<List<ServiceBusReceivedMessage>> receivedMessages = new AtomicReference<>(); receivedMessages.set(new ArrayList<>()); Flux.just( getMessage(messageId, isSessionEnabled), getMessage(messageId, isSessionEnabled), getMessage(messageId, isSessionEnabled) ) .delayElements(delayPublishing) <START> .map(message -> sender.send(message).subscribe()) <END> .subscribe(); StepVerifier.create(receiver.receive()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receivedMessages.get().add(receivedMessage); }) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receivedMessages.get().add(receivedMessage); }) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); receivedMessages.get().add(receivedMessage); }) .thenCancel() .verify(); for (int index = 0; index < count; ++index) { messagesPending.decrementAndGet(); } assertEquals(count, receivedMessages.get().size()); }</code><technical_language>a double subscribe here</technical_language>

Target:
void receiveSlowMultipleMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { int count = 3; setSenderAndReceiver(entityType, isSessionEnabled); Duration delayPublishing = Duration.ofMillis(1000); final String messageId = UUID.randomUUID().toString(); Flux.just( getMessage(messageId, isSessionEnabled), getMessage(messageId, isSessionEnabled), getMessage(messageId, isSessionEnabled) ) .delayElements(delayPublishing) .flatMap(message -> sender.send(message).then()) .subscribe(); StepVerifier.create(receiver.receive()) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled)) .thenCancel() .verify(); for (int index = 0; index < count; ++index) { messagesPending.incrementAndGet(); } }
Source:
<code><START> private static String readHexString(ProtoReader input) throws IOException { <END> ByteString bytes = input.readBytes(); int length = bytes.size() * 2; if (length > 32) { throw new AssertionError("hex field greater than 32 chars long: " + length); } char[] result = THIRTY_TWO_CHARS.get(); for (int i = 0; i < bytes.size(); i ++) { byte b = bytes.getByte(i); result[2 * i] = HEX_DIGITS[(b >> 4) & 0xf]; result[2 * i + 1] = HEX_DIGITS[b & 0xf]; } return new String(result, 0, length); }</code><technical_language>suggestion // <LINK_0> private static String readHexString(ProtoReader input) throws IOException {</technical_language>

Target:
private static String readHexString(ProtoReader input) throws IOException { ByteString bytes = input.readBytes(); int length = bytes.size() * 2; if (length > 32) { throw new AssertionError("hex field greater than 32 chars long: " + length); } char[] result = Platform.get().idBuffer(); for (int i = 0; i < bytes.size(); i ++) { byte b = bytes.getByte(i); result[2 * i] = HEX_DIGITS[(b >> 4) & 0xf]; result[2 * i + 1] = HEX_DIGITS[b & 0xf]; } return new String(result, 0, length); }
Source:
<code>private static int buildHashCode(ConstraintDescriptorImpl<?> constraintDescriptor, ConstraintLocation location, List<ValueExtractorDescriptor> valueExtractorDescriptors) { final int prime = 31; int result = 1; <START> result = prime * result + ( constraintDescriptor != null ? constraintDescriptor.hashCode() : 0 ); <END> result = prime * result + ( location != null ? location.hashCode() : 0 ); return result; }</code><technical_language>null checks needed</technical_language>

Target:
private static int buildHashCode(ConstraintDescriptorImpl<?> constraintDescriptor, ConstraintLocation location, List<ValueExtractorDescriptor> valueExtractorDescriptors) { final int prime = 31; int result = 1; result = prime * result + constraintDescriptor.hashCode(); result = prime * result + location.hashCode(); return result; }
Source:
<code>public MSKConcept getByOncotreeCode(String oncotreeCode) <START> throws CrosswalkException { <END> return queryCVS("ONCOTREE", oncotreeCode, null, null); }</code><technical_language>This is a confusing -- attempting a query (or working a static resource) querying disabled. relying a separate boolean check throw exception. In this case is a reason retain (DISABLE_CVS_QUERYING) check</technical_language>

Target:
public MSKConcept getByOncotreeCode(String oncotreeCode) { parseCrosswalkResourceFileIfNeeded(); MSKConcept concept = parsedStaticResource.get(oncotreeCode); return concept; }
Source:
<code>private void updateListing(CertifiedProductSearchDetails cpd, CertificationStatus cs, Date effectiveDate) { cpd.getCertificationEvents().add(getCertifiectionStatusEvent(cs, effectiveDate)); ListingUpdateRequest updateRequest = new ListingUpdateRequest(); updateRequest.setListing(cpd); try { certifiedProductManager.update( Long.parseLong(updateRequest.getListing().getCertifyingBody().get("id").toString()), updateRequest); } catch (ValidationException e) { <START> LOGGER.error("Error validating {" + cpd.getId() + "}: " + cpd.getChplProductNumber()); <END> e.getErrorMessages().stream() .forEach(msg -> LOGGER.error(msg)); } catch (Exception e) { LOGGER.error(e); } LOGGER.info("Completed Updating certified product {" + updateRequest.getListing().getId() + "}: " + updateRequest.getListing().getChplProductNumber()); }</code><technical_language>Talked this stand-up today, desire get this out PROD Monday decision hold emailing stuff 2014 ticket</technical_language>

Target:
private void updateListing(CertifiedProductSearchDetails cpd, CertificationStatus cs, Date effectiveDate) { cpd.getCertificationEvents().add(getCertifiectionStatusEvent(cs, effectiveDate)); ListingUpdateRequest updateRequest = new ListingUpdateRequest(); updateRequest.setListing(cpd); try { certifiedProductManager.update( Long.parseLong(updateRequest.getListing().getCertifyingBody().get("id").toString()), updateRequest); LOGGER.info("Completed Updating certified product {" + updateRequest.getListing().getId() + "}: " + updateRequest.getListing().getChplProductNumber()); } catch (ValidationException e) { LOGGER.error("Error validating {" + cpd.getId() + "}: " + cpd.getChplProductNumber()); e.getErrorMessages().stream() .forEach(msg -> LOGGER.error(msg)); LOGGER.info("Unsuccessful Update certified product {" + updateRequest.getListing().getId() + "}: " + updateRequest.getListing().getChplProductNumber()); } catch (Exception e) { LOGGER.error("An unexpected error occurred", e); LOGGER.info("Unsuccessful Update certified product {" + updateRequest.getListing().getId() + "}: " + updateRequest.getListing().getChplProductNumber()); } }
Source:
<code>private void buildVmVideoDeviceOverridden() { <START> if (vm.getDefaultDisplayType() != null && vm.getDefaultDisplayType() != DisplayType.none) { <END> Map<String, Object> struct = new HashMap<>(); struct.put(VdsProperties.Type, VmDeviceGeneralType.VIDEO.getValue()); struct.put(VdsProperties.Device, vm.getDefaultDisplayType().getDefaultVmDeviceType().getName()); struct.put(VdsProperties.DeviceId, String.valueOf(Guid.newGuid())); devices.add(struct); } }</code><technical_language>true</technical_language>

Target:
private void buildVmVideoDeviceOverridden() { Map<String, Object> struct = new HashMap<>(); struct.put(VdsProperties.Type, VmDeviceGeneralType.VIDEO.getValue()); struct.put(VdsProperties.Device, vm.getDefaultDisplayType().getDefaultVmDeviceType().getName()); struct.put(VdsProperties.DeviceId, String.valueOf(Guid.newGuid())); devices.add(struct); }
Source:
<code>private void checkIfSlaveIsAddedToBondWithUnmanagedNetwork(VdsNetworkInterface nicWithUnmanagedNetwork, Bond newOrModifiedBond, Bond existingBond, Collection<String> addedSlaves) throws ValidationException{ if(nicWithUnmanagedNetwork.getName().equals(existingBond.getName())){ if (!addedSlaves.isEmpty()){ throw new ValidationException(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_ADD_TO_UNMANAGED_BOND, ReplacementUtils.createSetVariableString(NIC, addedSlaves.iterator().next()), <START> ReplacementUtils.createSetVariableString(BOND, newOrModifiedBond.getName())); <END> } } }</code><technical_language>do need 'existingBond' 'newOrModifiedBond' parameters? of get name, is of them</technical_language>

Target:
private ValidationResult checkIfSlaveIsAddedToBondWithUnmanagedNetwork(VdsNetworkInterface nicWithUnmanagedNetwork, Bond newOrModifiedBond, Bond existingBond, Collection<String> addedSlaves) { if(nicWithUnmanagedNetwork.getName().equals(existingBond.getName())){ if (!addedSlaves.isEmpty()){ return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_ADD_TO_UNMANAGED_BOND, ReplacementUtils.createSetVariableString(NIC, addedSlaves.iterator().next()), ReplacementUtils.createSetVariableString(BOND, newOrModifiedBond.getName())); } } return ValidationResult.VALID; }
Source:
<code>public void testClientTagsBasedSelection() throws Exception { <START> try (DistributedQueryRunner queryRunner = TpchQueryRunner.createQueryRunner(ImmutableMap.of(), ImmutableMap.of("experimental.resource-groups-enabled", "true"))) { <END> queryRunner.installPlugin(new ResourceGroupManagerPlugin()); queryRunner.getCoordinator().getResourceGroupManager().get() .setConfigurationManager("file", ImmutableMap.of("resource-groups.config-file", getResourceFilePath("resource_groups_client_tags_based_config.json"))); assertResourceGroup(queryRunner, newSessionWithTags(ImmutableSet.of("a")), LONG_LASTING_QUERY, "global.a.default"); assertResourceGroup(queryRunner, newSessionWithTags(ImmutableSet.of("b")), LONG_LASTING_QUERY, "global.b"); assertResourceGroup(queryRunner, newSessionWithTags(ImmutableSet.of("a", "c")), LONG_LASTING_QUERY, "global.a.c"); } }</code><technical_language>In other unit tests in this class TestQueryRunnerUtil::createQueryRunner(), installs tpch catalog. If reasons TpchQueryRunner::createQueryRunner() other tests consistent other</technical_language>

Target:
public void testClientTagsBasedSelection() throws Exception { try (DistributedQueryRunner queryRunner = createQueryRunner(ImmutableMap.of("experimental.resource-groups-enabled", "true"))) { queryRunner.installPlugin(new ResourceGroupManagerPlugin()); queryRunner.getCoordinator().getResourceGroupManager().get() .setConfigurationManager("file", ImmutableMap.of("resource-groups.config-file", getResourceFilePath("resource_groups_client_tags_based_config.json"))); assertResourceGroup(queryRunner, newSessionWithTags(ImmutableSet.of("a")), LONG_LASTING_QUERY, "global.a.default"); assertResourceGroup(queryRunner, newSessionWithTags(ImmutableSet.of("b")), LONG_LASTING_QUERY, "global.b"); assertResourceGroup(queryRunner, newSessionWithTags(ImmutableSet.of("a", "c")), LONG_LASTING_QUERY, "global.a.c"); } }
Source:
<code>protected void collectParameters(Consumer<Parameter<?, ?>> parameterCollector) { if (stringParameter == null) { <START> stringParameter = new StringParameter("destination", NLS.get("MoveIndexAliasJobFactory.destinationParameter")); <END> stringParameter.markRequired(); } if (entityDescriptorParameter == null) { entityDescriptorParameter = new ElasticEntityDescriptorParameter("ed", NLS.get("MoveIndexAliasJobFactory.descriptorParameter")); entityDescriptorParameter.markRequired(); } parameterCollector.accept(stringParameter); parameterCollector.accept(entityDescriptorParameter); }</code><technical_language>do cache parameter here, NLS.get is dependent user locale - user determine parameter name for successive calls</technical_language>

Target:
protected void collectParameters(Consumer<Parameter<?, ?>> parameterCollector) { parameterCollector.accept(destinationParameter); parameterCollector.accept(entityDescriptorParameter); }
Source:
<code>public void returnFalseInHasNextValueOnEmptyList() { <START> final List<String> EMPTY_LIST = Arrays.asList(); <END> final String NO_NEXT_VALUE_ERROR = "Empty Error Message"; MatcherAssert.assertThat( new VerboseIterable<String>( EMPTY_LIST, NO_NEXT_VALUE_ERROR) .iterator().hasNext(), equalTo(false)); }</code><technical_language>@m4solutions unnecessery variable - Collections.emptyList()</technical_language>

Target:
public final void returnFalseInHasNextValueOnEmptyList() { MatcherAssert.assertThat( new VerboseIterable<String>( Collections.<String>emptyList(), "Non used Error Message" ).iterator().hasNext(), Matchers.equalTo(false) ); }
Source:
<code>public List<JobID> run(final DispatcherGateway dispatcherGateway, final PackagedProgram program, final Configuration configuration) { <START> requireNonNull(dispatcherGateway); <END> requireNonNull(program); requireNonNull(configuration); return tryExecuteJobs(dispatcherGateway, program, configuration); }</code><technical_language>Flink Preconditions#checkNotNull, curious this choose for checking nonnull value</technical_language>

Target:
public List<JobID> run(final DispatcherGateway dispatcherGateway, final PackagedProgram program, final Configuration configuration) { checkNotNull(dispatcherGateway); checkNotNull(program); checkNotNull(configuration); return tryExecuteJobs(dispatcherGateway, program, configuration); }
Source:
<code>protected void onBind() { super.onBind(); registerHandler(getEventBus().addHandler(ManualRefreshEvent.getType(), new ManualRefreshHandler() { @Override public void onManualRefresh(ManualRefreshEvent event) { if (SubTabHostInterfacePresenter.this.isVisible() <START> && SubTabHostInterfacePresenter.this.getModelProvider().getModel().equals(event.getSource())) { <END> getView().removeContent(); } } })); getModelProvider().getModel().getTimer().addValueChangeHandler(new ValueChangeHandler<Integer>() { @Override public void onValueChange(ValueChangeEvent<Integer> event) { getView().setRefreshButtonVisibility(!getModelProvider().getModel().getTimer().isActive()); } }); }</code><technical_language>Hm, == for comparison, custom equals() implementation for model classes. (IIRC, of GWTP infra code working models compares references.) Current code change is OK too</technical_language>

Target:
protected void onBind() { super.onBind(); registerHandler(getEventBus().addHandler(ManualRefreshEvent.getType(), new ManualRefreshHandler() { @Override public void onManualRefresh(ManualRefreshEvent event) { if (SubTabHostInterfacePresenter.this.isVisible() && SubTabHostInterfacePresenter.this.getModelProvider().getModel().equals(event.getSource())) { getView().removeContent(); } } })); getModelProvider().getModel().getTimer().addGridTimerStateChangeEventHandler(new GridTimerStateChangeEventHandler() { @Override public void onGridTimerStateChange(GridTimerStateChangeEvent event) { getView().setRefreshButtonVisibility(!getModelProvider().getModel().getTimer().isActive()); } }); }
Source:
<code>public void run() { try { ApplicationInfoManager.getInstance() .refreshDataCenterInfoIfRequired(); InstanceInfo discoveryServer = getCoordinatingServer(); if ((discoveryServer != null) && (Name.Amazon.equals(discoveryServer .getDataCenterInfo()))) { String amiId = ((AmazonInfo) discoveryServer .getDataCenterInfo()).get(MetaDataKey.amiId); if (discoveryServerAMIId == null) { discoveryServerAMIId = amiId; } else if (!discoveryServerAMIId.equals(amiId)) { logger.info("The eureka AMI ID changed from " + discoveryServerAMIId + " to " + amiId + ". Pushing the appinfo to eureka"); instanceInfo.setIsDirty(true); discoveryServerAMIId = amiId; } } <START> if (isHealthCheckEnabled()) { <END> InstanceStatus status = healthCheckHandler.getStatus(instanceInfo.getStatus()); if (null != status) { instanceInfo.setStatus(status); } } if (instanceInfo.isDirty()) { logger.info(PREFIX + appPathIdentifier + " - retransmit instance info with status " + instanceInfo.getStatus().toString()); register(); instanceInfo.setIsDirty(false); } } catch (Throwable t) { logger.error( "There was a problem with the instance info replicator :", t); } }</code><technical_language>get rid of this check a DefaultHealthCheckHandler returns</technical_language>

Target:
public void run() { try { ApplicationInfoManager.getInstance() .refreshDataCenterInfoIfRequired(); InstanceInfo discoveryServer = getCoordinatingServer(); if ((discoveryServer != null) && (Name.Amazon.equals(discoveryServer .getDataCenterInfo()))) { String amiId = ((AmazonInfo) discoveryServer .getDataCenterInfo()).get(MetaDataKey.amiId); if (discoveryServerAMIId == null) { discoveryServerAMIId = amiId; } else if (!discoveryServerAMIId.equals(amiId)) { logger.info("The eureka AMI ID changed from " + discoveryServerAMIId + " to " + amiId + ". Pushing the appinfo to eureka"); instanceInfo.setIsDirty(true); discoveryServerAMIId = amiId; } } final HealthCheckHandler handler = getHealthCheckHandler(); InstanceStatus status = handler.getStatus(instanceInfo.getStatus()); if (null != status) { instanceInfo.setStatus(status); } if (instanceInfo.isDirty()) { logger.info(PREFIX + appPathIdentifier + " - retransmit instance info with status " + instanceInfo.getStatus().toString()); register(); instanceInfo.setIsDirty(false); } } catch (Throwable t) { logger.error("There was a problem with the instance info replicator :", t); } }
Source:
<code>protected void persistExtraConfigVmware(String decodedUrl, UserVm vm) { boolean isValidConfig = isValidKeyValuePair(decodedUrl); if (isValidConfig) { String[] extraConfigs = decodedUrl.split("\\r?\\n"); for (String cfg : extraConfigs) { String[] allowedKeyList = VmwareAdditionalConfigAllowList.value().split(","); boolean validXenOrVmwareConfiguration = isValidXenOrVmwareConfiguration(cfg, allowedKeyList); String[] paramArray = cfg.split("="); if (validXenOrVmwareConfiguration && paramArray.length == 2) { try { userVmDetailsDao.addDetail(vm.getId(), paramArray[0].trim(), paramArray[1].trim(), true); } catch (ArrayIndexOutOfBoundsException e) { <START> throw new CloudRuntimeException("Issue occurred during parsing of:" + cfg); <END> } } else { throw new CloudRuntimeException("Extra config " + cfg + " is not on the list of allowed keys for VMware hypervisor hosts."); } } } else { throw new CloudRuntimeException("The passed extra config string " + decodedUrl + "contains an invalid key/value pair pattern"); } }</code><technical_language>keeping a secret issue cfg is ArrayIndexOutOfBoundsException! add log nest exception</technical_language>

Target:
protected void persistExtraConfigVmware(String decodedUrl, UserVm vm) { boolean isValidConfig = isValidKeyValuePair(decodedUrl); if (isValidConfig) { String[] extraConfigs = decodedUrl.split("\\r?\\n"); for (String cfg : extraConfigs) { String[] allowedKeyList = VmwareAdditionalConfigAllowList.value().split(","); boolean validXenOrVmwareConfiguration = isValidXenOrVmwareConfiguration(cfg, allowedKeyList); String[] paramArray = cfg.split("="); if (validXenOrVmwareConfiguration && paramArray.length == 2) { userVmDetailsDao.addDetail(vm.getId(), paramArray[0].trim(), paramArray[1].trim(), true); } else { throw new CloudRuntimeException("Extra config " + cfg + " is not on the list of allowed keys for VMware hypervisor hosts."); } } } else { throw new CloudRuntimeException("The passed extra config string " + decodedUrl + "contains an invalid key/value pair pattern"); } }
Source:
<code>public JSONObject generateJSONObject(String fileName) { JSONObject jsonObject = new JSONObject(); try { String jsonString = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8); jsonObject = new JSONObject(jsonString); } catch (IOException e) { <START> LOG.info(e.getMessage(), e); <END> } return jsonObject; }</code><technical_language>I add proper custom error message in this case</technical_language>

Target:
public static JSONObject generateJSONObject(String fileName) { JSONObject jsonObject = new JSONObject(); try { String jsonString = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8); jsonObject = new JSONObject(jsonString); } catch (IOException e) { LOG.info("There is a problem generating JSON object\n {}", e.getMessage(), e); } return jsonObject; }
Source:
<code>private void commit(boolean pushUpstream) { boolean reEnable = false; enableAllWidgets(false); try { boolean jobScheduled = <START> !internalCommit(pushUpstream, <END> () -> enableAllWidgets(true)); reEnable = !jobScheduled; } catch (RuntimeException e) { reEnable = true; Activator.handleError(e.getLocalizedMessage(), e, true); } finally { if (reEnable) { enableAllWidgets(true); } } }</code><technical_language>? I internalCommit() returns true if a job scheduled</technical_language>

Target:
private void commit(boolean pushUpstream) { boolean reEnable = false; enableAllWidgets(false); try { boolean jobScheduled = internalCommit(pushUpstream, () -> enableAllWidgets(true)); reEnable = !jobScheduled; } catch (RuntimeException e) { reEnable = true; Activator.handleError(e.getLocalizedMessage(), e, true); } finally { if (reEnable) { enableAllWidgets(true); } } }
Source:
<code>public double getTimeSpentOnPutRequest() { <START> return ioStatisticsStore.getMeanStatistic(getStatName(TIME_TAKEN_TO_PUT_REQUEST) + ".mean").mean(); <END> }</code><technical_language>StoreStatisticsNames.SUFFIX_MEAN string</technical_language>

Target:
public double getTimeSpentOnPutRequest() { return ioStatisticsStore.meanStatistics().get(getStatName(TIME_SPENT_ON_PUT_REQUEST) + StoreStatisticNames.SUFFIX_MEAN).mean(); }
Source:
<code>public void deactivateDevice(final String organisationIdentification, @Identification final String deviceIdentification, final String correlationUid, final String messageType) <START> throws FunctionalException { <END> LOGGER.info("deactivateDevice for organisationIdentification: for deviceIdentification: {}", organisationIdentification, deviceIdentification); final Device device = this.deviceRepository.findByDeviceIdentification(deviceIdentification); device.setActivated(false); this.deviceRepository.save(device); final ResponseMessage responseMessage = new ResponseMessage(correlationUid, organisationIdentification, deviceIdentification, ResponseMessageResultType.OK, null); this.webServiceResponseMessageSender.send(responseMessage); }</code><technical_language>I this method throws a FunctionalException</technical_language>

Target:
public void deactivateDevice(final String organisationIdentification, @Identification final String deviceIdentification, final String correlationUid, final String messageType) { LOGGER.info("deactivateDevice for organisationIdentification: for deviceIdentification: {}", organisationIdentification, deviceIdentification); final Device device = this.deviceRepository.findByDeviceIdentification(deviceIdentification); device.setActivated(false); this.deviceRepository.save(device); final ResponseMessage responseMessage = new ResponseMessage(correlationUid, organisationIdentification, deviceIdentification, ResponseMessageResultType.OK, null); this.webServiceResponseMessageSender.send(responseMessage); }
Source:
<code><START> @Override public synchronized final String toString() { <END> readLock.lock(); try { return map.toString(); } finally { readLock.unlock(); } }</code><technical_language>is synchronized needed considering readLock</technical_language>

Target:
@Override public final String toString() { readLock.lock(); try { return map.toString(); } finally { readLock.unlock(); } }
Source:
<code>@NonNull <START> @Override public <END> CardType type() { return CardType.ANNOUNCEMENT; }</code><technical_language>I guess consistent codebase method annotations line method signature line(s). pick other stick a per-class basis, though</technical_language>

Target:
public CardType type() { return CardType.ANNOUNCEMENT; }
Source:
<code>private MongoInstitution(final String url) { MongoClient mongoClient = null; try { mongoClient = new MongoClient(url); } catch (UnknownHostException e) { <START> LOG.info(LoggingConstants.EXCEPTION_MESSAGE, e); <END> } if (mongoClient == null) { return; } database = mongoClient.getDB(DATABASE); }</code><technical_language>this error</technical_language>

Target:
private MongoInstitution(final String url) { MongoClient mongoClient = null; try { mongoClient = new MongoClient(url); } catch (UnknownHostException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); } if (mongoClient == null) { return; } database = mongoClient.getDB(DATABASE); }