auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void setClasspath(IProject project, IFeatureModel model, IProgressMonitor monitor) throws JavaModelException { <START> IJavaProject jProject = JavaCore.create(project); <END> IClasspathEntry jreCPEntry = JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")); String libName = model.getFeature().getInstallHandler().getLibrary(); IClasspathEntry handlerCPEntry = JavaCore.newLibraryEntry(project.getFullPath().append(libName), null, null); jProject.setRawClasspath(new IClasspathEntry[] {jreCPEntry, handlerCPEntry}, monitor); }</code><technical_language>Consider allocating a local SubMonitor here</technical_language>

Target:
private void setClasspath(IProject project, IFeatureModel model, IProgressMonitor monitor) throws JavaModelException { SubMonitor subMonitor = SubMonitor.convert(monitor); IJavaProject jProject = JavaCore.create(project); IClasspathEntry jreCPEntry = JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")); String libName = model.getFeature().getInstallHandler().getLibrary(); IClasspathEntry handlerCPEntry = JavaCore.newLibraryEntry(project.getFullPath().append(libName), null, null); jProject.setRawClasspath(new IClasspathEntry[] { jreCPEntry, handlerCPEntry }, subMonitor); }
Source:
<code>private boolean isNewerFormVersionAvailable(String md5Hash) { if (md5Hash == null) { return false; } <START> return formRepository.getAll().stream().noneMatch(f -> f.getMD5Hash().equals(md5Hash)); <END> }</code><technical_language>Consider adding a repository method get a form md5hash? clearer more efficient</technical_language>

Target:
private boolean isNewerFormVersionAvailable(String md5Hash) { if (md5Hash == null) { return false; } return formRepository.getByMd5Hash(md5Hash) == null; }
Source:
<code>public void shouldMergeLimboPlayers() { Location newLocation = mock(Location.class); LimboPlayer newLimbo = new LimboPlayer(newLocation, false, Collections.singletonList("grp-new"), false, 0.0f, 0.0f); Location oldLocation = mock(Location.class); LimboPlayer oldLimbo = new LimboPlayer(oldLocation, true, Collections.singletonList("grp-old"), true, 0.1f, 0.8f); LimboPlayer result = limboServiceHelper.merge(newLimbo, oldLimbo); assertThat(result.getLocation(), equalTo(oldLocation)); assertThat(result.isOperator(), equalTo(true)); <START> assertThat(result.getGroups(), equalTo(Collections.singletonList("grp-new"))); <END> assertThat(result.isCanFly(), equalTo(true)); assertThat(result.getWalkSpeed(), equalTo(0.1f)); assertThat(result.getFlySpeed(), equalTo(0.8f)); }</code><technical_language>This rung alarm bell - this test caught a change in behavior meant test ;)</technical_language>

Target:
public void shouldMergeLimboPlayers() { Location newLocation = mock(Location.class); LimboPlayer newLimbo = new LimboPlayer(newLocation, false, Collections.singletonList("grp-new"), false, 0.0f, 0.0f); Location oldLocation = mock(Location.class); LimboPlayer oldLimbo = new LimboPlayer(oldLocation, true, Collections.singletonList("grp-old"), true, 0.1f, 0.8f); LimboPlayer result = limboServiceHelper.merge(newLimbo, oldLimbo); assertThat(result.getLocation(), equalTo(oldLocation)); assertThat(result.isOperator(), equalTo(true)); assertThat(result.getGroups(), contains("grp-old")); assertThat(result.isCanFly(), equalTo(true)); assertThat(result.getWalkSpeed(), equalTo(0.1f)); assertThat(result.getFlySpeed(), equalTo(0.8f)); }
Source:
<code>public void close() throws StreamingIOFailure { boolean haveError = false; String partition = null; if (LOG.isDebugEnabled()) { logStats("Stats before close:"); } for (Map.Entry<String, List<RecordUpdater>> entry : updaters.entrySet()) { partition = entry.getKey(); if (LOG.isDebugEnabled()) { LOG.debug("Closing updater for partitions: {}", partition); } for (RecordUpdater updater : entry.getValue()) { if (updater != null) { try { updater.close(false); } catch (Exception ex) { haveError = true; LOG.error("Unable to close " + updater + " due to: " + ex.getMessage(), ex); } } } entry.getValue().clear(); } updaters.clear(); if (LOG.isDebugEnabled()) { logStats("Stats after close:"); } try { this.fs.close(); } catch (IOException e) { <START> LOG.error("Error while closing FileSystem", e); <END> } if (haveError) { throw new StreamingIOFailure("Encountered errors while closing (see logs) " + getWatermark(partition)); } }</code><technical_language>I propagate this error a RuntimeException instead of swallowing it. If FileSystem fails close, signal a serious problem</technical_language>

Target:
public void close() throws StreamingIOFailure { boolean haveError = false; String partition = null; if (LOG.isDebugEnabled()) { logStats("Stats before close:"); } for (Map.Entry<String, List<RecordUpdater>> entry : updaters.entrySet()) { partition = entry.getKey(); if (LOG.isDebugEnabled()) { LOG.debug("Closing updater for partitions: {}", partition); } for (RecordUpdater updater : entry.getValue()) { if (updater != null) { try { updater.close(false); } catch (Exception ex) { haveError = true; LOG.error("Unable to close " + updater + " due to: " + ex.getMessage(), ex); } } } entry.getValue().clear(); } updaters.clear(); if (LOG.isDebugEnabled()) { logStats("Stats after close:"); } try { this.fs.close(); } catch (IOException e) { throw new StreamingIOFailure("Error while closing FileSystem", e); } if (haveError) { throw new StreamingIOFailure("Encountered errors while closing (see logs) " + getWatermark(partition)); } }
Source:
<code>public void runAll() { String cronExecutingUser = (String) getConfig().get("cronExecutingUser"); synchronized (paragraphs) { if (!paragraphs.isEmpty()) { setLastReplName(paragraphs.get(paragraphs.size() - 1)); } for (Paragraph p : paragraphs) { if (!p.isEnabled()) { continue; } AuthenticationInfo authenticationInfo = new AuthenticationInfo(); authenticationInfo.setUser(cronExecutingUser); p.setAuthenticationInfo(authenticationInfo); try { run(p.getId()); } catch (InterpreterException intpException) { throw intpException; <START> } <END> } } }</code><technical_language>is point of try..catch block here? please explain, is this code from: java run(p.getId());</technical_language>

Target:
public void runAll() { String cronExecutingUser = (String) getConfig().get("cronExecutingUser"); synchronized (paragraphs) { if (!paragraphs.isEmpty()) { setLastReplName(paragraphs.get(paragraphs.size() - 1)); } for (Paragraph p : paragraphs) { if (!p.isEnabled()) { continue; } AuthenticationInfo authenticationInfo = new AuthenticationInfo(); authenticationInfo.setUser(cronExecutingUser); p.setAuthenticationInfo(authenticationInfo); run(p.getId()); } } }
Source:
<code>public Mono<? extends AsyncKeyEncryptionKey> buildAsyncKeyEncryptionKey(JsonWebKey key) { if (key == null) { throw logger.logExceptionAsError(new IllegalStateException( "Json Web key value cannot be null and is required to create local key encryption key async client.")); } else if (key.getId() == null) { <START> throw logger.logExceptionAsError(new IllegalArgumentException( <END> "Json Web Key's id property is not configured")); } return Mono.defer(() -> Mono.just(new LocalKeyEncryptionKeyAsyncClient(key))); }</code><technical_language>Update docs reflect exception</technical_language>

Target:
public Mono<? extends AsyncKeyEncryptionKey> buildAsyncKeyEncryptionKey(JsonWebKey key) { if (key == null) { throw logger.logExceptionAsError(new IllegalStateException( "Json Web key value cannot be null and is required to create local key encryption key async client.")); } else if (key.getId() == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "Json Web Key's id property is not configured.")); } return Mono.defer(() -> Mono.just(new LocalKeyEncryptionKeyAsyncClient(key))); }
Source:
<code>protected Object handleRequestMessage(Message<?> requestMessage) { Message<?> theRequestMessage = requestMessage; try { theRequestMessage = embeddedHeadersMessageConverter.extractHeaders((Message<byte[]>) requestMessage); } <START> catch (Exception e) { <END> logger.error("Could not convert message", e); } Message<?> result = deserializePayloadIfNecessary(theRequestMessage); return result; }</code><technical_language>exception thrown message contents/headers extracted for logging</technical_language>

Target:
protected Object handleRequestMessage(Message<?> requestMessage) { Message<?> theRequestMessage = requestMessage; try { theRequestMessage = embeddedHeadersMessageConverter.extractHeaders((Message<byte[]>) requestMessage); } catch (Exception e) { logger.error(EmbeddedHeadersMessageConverter.decodeExceptionMessage(requestMessage), e); } return deserializePayloadIfNecessary(theRequestMessage); }
Source:
<code>private void logContext(RelationshipOp operation, Environment environment) { List<Field> children = (environment.field.getSelectionSet() != null) ? (List) environment.field.getSelectionSet().getChildren() : new ArrayList<>(); String requestedFields = environment.field.getName() + (children.size() > 0 ? "(" + children.stream().map(Field::getName).collect(Collectors.toList()) + ")" : ""); GraphQLType parent = environment.parentType; if (log.isDebugEnabled()) { log.debug("{} fields with parent {}<{}>", <START> operation, requestedFields, parent.getClass().getSimpleName(), parent.getName()); <END> } }</code><technical_language>EntityDictionary.getSimpleName</technical_language>

Target:
private void logContext(RelationshipOp operation, Environment environment) { List<Field> children = (environment.field.getSelectionSet() != null) ? (List) environment.field.getSelectionSet().getChildren() : new ArrayList<>(); String requestedFields = environment.field.getName() + (children.size() > 0 ? "(" + children.stream().map(Field::getName).collect(Collectors.toList()) + ")" : ""); GraphQLType parent = environment.parentType; if (log.isDebugEnabled()) { log.debug("{} fields with parent {}<{}>", operation, requestedFields, EntityDictionary.getSimpleName(parent.getClass()), parent.getName()); } }
Source:
<code>public void testSyncDownForMetadataTarget() throws Exception { <START> trySyncDown(MergeMode.LEAVE_IF_CHANGED, new MetadataSyncDownTarget(Constants.ACCOUNT), ACCOUNTS_SOUP); <END> final QuerySpec smartStoreQuery = QuerySpec.buildAllQuerySpec(ACCOUNTS_SOUP, SyncTarget.SYNC_ID, QuerySpec.Order.ascending, 1); final JSONArray rows = smartStore.query(smartStoreQuery, 0); Assert.assertEquals("Number of rows should be 1", rows.length(), 1); }</code><technical_language>In a real app, setup a soup hold metadata. read check a keys json blob</technical_language>

Target:
public void testSyncDownForMetadataTarget() throws Exception { trySyncDown(MergeMode.LEAVE_IF_CHANGED, new MetadataSyncDownTarget(Constants.ACCOUNT), ACCOUNTS_SOUP); final QuerySpec smartStoreQuery = QuerySpec.buildAllQuerySpec(ACCOUNTS_SOUP, SyncTarget.SYNC_ID, QuerySpec.Order.ascending, 1); final JSONArray rows = smartStore.query(smartStoreQuery, 0); Assert.assertEquals("Number of rows should be 1", 1, rows.length()); final JSONObject metadata = rows.optJSONObject(0); Assert.assertNotNull("Metadata should not be null", metadata); final String keyPrefix = metadata.optString(Constants.KEYPREFIX_FIELD); final String label = metadata.optString(Constants.LABEL_FIELD); Assert.assertEquals("Key prefix should be 001", Constants.ACCOUNT_KEY_PREFIX, keyPrefix); Assert.assertEquals("Label should be " + Constants.ACCOUNT, Constants.ACCOUNT, label); }
Source:
<code>ColumnReaderBase(ColumnDescriptor path, PageReader pageReader, PrimitiveConverter converter, ParsedVersion writerVersion) { <START> this.path = Objects.requireNonNull(path, "path canot be null"); <END> this.pageReader = Objects.requireNonNull(pageReader, "pageReader canot be null"); this.converter = Objects.requireNonNull(converter, "converter canot be null"); this.writerVersion = writerVersion; this.maxDefinitionLevel = path.getMaxDefinitionLevel(); DictionaryPage dictionaryPage = pageReader.readDictionaryPage(); if (dictionaryPage != null) { try { this.dictionary = dictionaryPage.getEncoding().initDictionary(path, dictionaryPage); if (converter.hasDictionarySupport()) { converter.setDictionary(dictionary); } } catch (IOException e) { throw new ParquetDecodingException("could not decode the dictionary for " + path, e); } } else { this.dictionary = null; } this.totalValueCount = pageReader.getTotalValueCount(); if (totalValueCount <= 0) { throw new ParquetDecodingException("totalValueCount '" + totalValueCount + "' <= 0"); } }</code><technical_language>suggestion this.path = Objects.requireNonNull(path, "path null");</technical_language>

Target:
ColumnReaderBase(ColumnDescriptor path, PageReader pageReader, PrimitiveConverter converter, ParsedVersion writerVersion) { this.path = Objects.requireNonNull(path, "path cannot be null"); this.pageReader = Objects.requireNonNull(pageReader, "pageReader cannot be null"); this.converter = Objects.requireNonNull(converter, "converter cannot be null"); this.writerVersion = writerVersion; this.maxDefinitionLevel = path.getMaxDefinitionLevel(); DictionaryPage dictionaryPage = pageReader.readDictionaryPage(); if (dictionaryPage != null) { try { this.dictionary = dictionaryPage.getEncoding().initDictionary(path, dictionaryPage); if (converter.hasDictionarySupport()) { converter.setDictionary(dictionary); } } catch (IOException e) { throw new ParquetDecodingException("could not decode the dictionary for " + path, e); } } else { this.dictionary = null; } this.totalValueCount = pageReader.getTotalValueCount(); if (totalValueCount <= 0) { throw new ParquetDecodingException("totalValueCount '" + totalValueCount + "' <= 0"); } }
Source:
<code>private void downloadProjectList() { ApplicationManager.getApplication().assertIsDispatchThread(); SonarQubeServer selectedServer = getSelectedServer(); ServerDownloadProjectTask downloadTask = new ServerDownloadProjectTask(project, engine, selectedServer); try { downloadTask.queue(); Map<String, RemoteModule> map = downloadTask.getResult(); setProjectsInList(map.values()); <START> } catch (Exception e) { <END> String msg = e.getMessage() != null ? e.getMessage() : "Failed to download list of projects"; Messages.showErrorDialog(rootPanel, msg, "Error Downloading Project List"); } }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') log rethrow this exception. [![rule](<LINK_2>](<LINK_1></technical_language>

Target:
private void downloadProjectList() { ApplicationManager.getApplication().assertIsDispatchThread(); SonarQubeServer selectedServer = getSelectedServer(); if (selectedServer == null) { return; } ServerDownloadProjectTask downloadTask = new ServerDownloadProjectTask(project, engine, selectedServer); try { downloadTask.queue(); Map<String, RemoteModule> map = downloadTask.getResult(); setProjectsInList(map.values()); } catch (Exception e) { String msg = e.getMessage() != null ? e.getMessage() : "Failed to download list of projects"; Messages.showErrorDialog(rootPanel, msg, "Error Downloading Project List"); } }
Source:
<code>public static void writeMetadataFile(String jobName, String jobId, String containerId, Optional<String> execEnvContainerId, Config config) { Option<File> metadataFile = JobConfig.getMetadataFile(Option.apply(execEnvContainerId.orElse(null))); if (metadataFile.isDefined()) { StringBuilder metadata = new StringBuilder("Version: 1"); metadata.append(System.lineSeparator()); MetricsHeader metricsHeader = new MetricsHeader(jobName, jobId, "samza-container-" + containerId, execEnvContainerId.orElse(""), LocalContainerRunner.class.getName(), Util.getTaskClassVersion(config), Util.getSamzaVersion(), Util.getLocalHost().getHostName(), System.currentTimeMillis(), System.currentTimeMillis()); MetricsSnapshot metricsSnapshot = new MetricsSnapshot(metricsHeader, new Metrics()); <START> metadata.append("MetricsSnapshot: "); <END> metadata.append(new String(new MetricsSnapshotSerdeV2().toBytes(metricsSnapshot))); FileUtil.writeToTextFile(metadataFile.get(), metadata.toString(), false); } else { log.info("Skipping writing metadata file."); } }</code><technical_language>this "MetricsHeader" "ContainerMetadata" something? IIUC This is a snapshot of metrics themselves, related metrics. Also, serialize header (e.g. SamzaObjectMapper / ObjectMapper)</technical_language>

Target:
public static void writeMetadataFile(String jobName, String jobId, String containerId, Optional<String> execEnvContainerId, Config config) { Option<File> metadataFile = JobConfig.getMetadataFile(Option.apply(execEnvContainerId.orElse(null))); if (metadataFile.isDefined()) { StringBuilder metadata = new StringBuilder("Version: 1"); metadata.append(System.lineSeparator()); MetricsHeader metricsHeader = new MetricsHeader(jobName, jobId, "samza-container-" + containerId, execEnvContainerId.orElse(""), LocalContainerRunner.class.getName(), Util.getTaskClassVersion(config), Util.getSamzaVersion(), Util.getLocalHost().getHostName(), System.currentTimeMillis(), System.currentTimeMillis()); MetricsSnapshot metricsSnapshot = new MetricsSnapshot(metricsHeader, new Metrics()); metadata.append("ContainerMetadata: "); metadata.append(new String(new MetricsSnapshotSerdeV2().toBytes(metricsSnapshot))); FileUtil.writeToTextFile(metadataFile.get(), metadata.toString(), false); } else { log.info("Skipping writing metadata file."); } }
Source:
<code>private boolean isWindowPlatform() { <START> if (Platform.getOS().equals(Platform.WS_WIN32)) { <END> return true; } return false; }</code><technical_language>return Platform.getOS().equals(Platform.WS_WIN32)</technical_language>

Target:
private boolean isWindowPlatform() { return Platform.getOS().equals(Platform.WS_WIN32); }
Source:
<code>public static ObjectMapper createCustomMapper() { ObjectMapper result = new ObjectMapper(); result.configure(Feature.INDENT_OUTPUT, true); <START> SimpleModule module = new SimpleModule("hRavenModule", new Version(0, 4, 0, <END> null)); addJobMappings(module); module.addSerializer(Flow.class, new FlowSerializer()); module.addSerializer(AppSummary.class, new AppSummarySerializer()); module.addSerializer(TaskDetails.class, new TaskDetailsSerializer()); module.addSerializer(JobDetails.class, new JobDetailsSerializer()); result.registerModule(module); return result; }</code><technical_language>creating a simple hRavenModule is repeated in a other places. extract a method call instead</technical_language>

Target:
public static ObjectMapper createCustomMapper() { ObjectMapper result = new ObjectMapper(); result.configure(Feature.INDENT_OUTPUT, true); SimpleModule module = createhRavenModule(); addJobMappings(module); module.addSerializer(Flow.class, new FlowSerializer()); module.addSerializer(AppSummary.class, new AppSummarySerializer()); module.addSerializer(TaskDetails.class, new TaskDetailsSerializer()); module.addSerializer(JobDetails.class, new JobDetailsSerializer()); result.registerModule(module); return result; }
Source:
<code>private void closeStatementIfNeeded() throws SQLException { try { if (stmtHandle != null) { TCloseOperationReq closeReq = new TCloseOperationReq(stmtHandle); TCloseOperationResp closeResp = client.CloseOperation(closeReq); Utils.verifySuccessWithInfo(closeResp.getStatus()); stmtHandle = null; } } catch (SQLException e) { throw e; } catch (Exception e) { <START> if (e instanceof TApplicationException && ((TApplicationException)e) <END> .getType() == TApplicationException.BAD_SEQUENCE_ID) { String errorMsg = "Mismatch thrift sequence id, which usually is caused by an OutOfMemoryError " + "or a SocketTimeoutException, please check the memory status and previous calls."; throw new SQLException(errorMsg, "08S01", e); } throw new SQLException("Failed to close statement", "08S01", e); } }</code><technical_language>Please do instanceof here, create a new catch block for TApplicationException types</technical_language>

Target:
private void closeStatementIfNeeded() throws SQLException { try { if (stmtHandle != null) { TCloseOperationReq closeReq = new TCloseOperationReq(stmtHandle); TCloseOperationResp closeResp = client.CloseOperation(closeReq); Utils.verifySuccessWithInfo(closeResp.getStatus()); stmtHandle = null; } } catch (SQLException e) { throw e; } catch (TApplicationException tae) { String errorMsg = "Failed to close statement"; if (tae.getType() == TApplicationException.BAD_SEQUENCE_ID) { errorMsg = "Failed to close statement. Mismatch thrift sequence id. A previous call to the Thrift library" + " failed and now position within the input stream is lost. Please enable verbose error logging and" + " check the status of previous calls."; } throw new SQLException(errorMsg, "08S01", tae); } catch (Exception e) { throw new SQLException("Failed to close statement", "08S01", e); } }
Source:
<code>public ApplicationsClient applicationsClient() { return ApplicationsClientImpl.create( Configurer.get("applications.client.host").get(), <START> new MetricRegistry() <END> ); }</code><technical_language>need pass correct MetricRegistry autowiring metricsModule</technical_language>

Target:
public ApplicationsClient applicationsClient() { return ApplicationsClientImpl.create( applicationsClientHost, metricsModule.metrics() ); }
Source:
<code>public Blob run(DocumentModel doc) { BlobList blobs = null; if (collectionManager.isCollection(doc)) { blobs = getCollectionBlobs(doc.getAdapter(Collection.class)); } else if (doc.hasFacet("Folderish")) { blobs = getFolderishBlobs(doc); } else { log.warn("The operation only accepts folderish document or collection"); <START> return null; <END> } AutomationService as = Framework.getLocalService(AutomationService.class); try (OperationContext oc = new OperationContext(session)) { oc.push("filename", doc.getName()); oc.setInput(blobs); return (Blob) as.run(oc, CreateZip.ID); } catch (OperationException e) { throw new NuxeoException(e); } }</code><technical_language>sense throw exception a Bad Request http status</technical_language>

Target:
public Blob run(DocumentModel doc) throws IOException { if (maxDepth <= 0) { throw new NuxeoException("Maximum depth must greater or equal to 1."); } return processContainer(doc, 0); }
Source:
<code>private void resolveTargetTypeOrThrowException(String theResourceType) { <START> if (!theResourceType.equalsIgnoreCase("Patient") && !theResourceType.equalsIgnoreCase("Practitioner")) { <END> throw new InvalidRequestException(ProviderConstants.OPERATION_EMPI_BATCH_RUN + " does not support resource type: " + theResourceType); } }</code><technical_language>EmpiUtil.supportedTargetType()</technical_language>

Target:
private void resolveTargetTypeOrThrowException(String theResourceType) { if (!EmpiUtil.supportedTargetType(theResourceType)) { throw new InvalidRequestException(ProviderConstants.OPERATION_EMPI_BATCH_RUN + " does not support resource type: " + theResourceType); } }
Source:
<code>public void testCramSortFail(String file, String fileReference, SAMFileHeader.SortOrder order) throws Exception { final CRAMFileReader cramFileReader = getCramFileReader(file, fileReference); final SAMRecordIterator samRecordIterator = cramFileReader.getIterator().assertSorted(order); while (samRecordIterator.hasNext()) { samRecordIterator.next(); } <START> } <END></code><technical_language>please check records read</technical_language>

Target:
public void testCramSortFail(String file, String fileReference, SAMFileHeader.SortOrder order) throws Exception { final CRAMFileReader cramFileReader = getCramFileReader(file, fileReference); final SAMRecordIterator samRecordIterator = cramFileReader.getIterator().assertSorted(order); Assert.assertTrue(samRecordIterator.hasNext()); while (samRecordIterator.hasNext()) { Assert.assertNotNull(samRecordIterator.next()); } }
Source:
<code>protected void sendResponse(Channel channel, Address replyTo, Message messageIn) { Message message = messageIn; if (this.beforeSendReplyPostProcessors != null) { for (MessagePostProcessor postProcessor : this.beforeSendReplyPostProcessors) { message = postProcessor.postProcessMessage(message); } } postProcessChannel(channel, message); try { this.logger.debug("Publishing response to exchange = [" + replyTo.getExchangeName() + "], routingKey = [" + replyTo.getRoutingKey() + "]"); if (this.retryTemplate == null) { doPublish(channel, replyTo, message); } else { final Message messageToSend = message; final AtomicBoolean first = new AtomicBoolean(true); this.retryTemplate.execute(ctx -> { if (this.recoveryCallback != null && first.getAndSet(false)) { ctx.setAttribute(SendRetryContextAccessor.MESSAGE, messageToSend); ctx.setAttribute(SendRetryContextAccessor.ADDRESS, replyTo); } doPublish(channel, replyTo, messageToSend); return null; <START> }, this.recoveryCallback); <END> } } catch (Exception ex) { throw RabbitExceptionTranslator.convertRabbitAccessException(ex); } }</code><technical_language>do a wrapping populate attributes instead of AtomicBoolean logic in RetryCallback impl above? no: extra object for message... So, WDYT</technical_language>

Target:
protected void sendResponse(Channel channel, Address replyTo, Message messageIn) { Message message = messageIn; if (this.beforeSendReplyPostProcessors != null) { for (MessagePostProcessor postProcessor : this.beforeSendReplyPostProcessors) { message = postProcessor.postProcessMessage(message); } } postProcessChannel(channel, message); try { this.logger.debug("Publishing response to exchange = [" + replyTo.getExchangeName() + "], routingKey = [" + replyTo.getRoutingKey() + "]"); if (this.retryTemplate == null) { doPublish(channel, replyTo, message); } else { final Message messageToSend = message; this.retryTemplate.execute(ctx -> { doPublish(channel, replyTo, messageToSend); return null; }, ctx -> { if (this.recoveryCallback != null) { ctx.setAttribute(SendRetryContextAccessor.MESSAGE, messageToSend); ctx.setAttribute(SendRetryContextAccessor.ADDRESS, replyTo); this.recoveryCallback.recover(ctx); return null; } else { throw RabbitExceptionTranslator.convertRabbitAccessException(ctx.getLastThrowable()); } }); } } catch (Exception ex) { throw RabbitExceptionTranslator.convertRabbitAccessException(ex); } }
Source:
<code>public void closesDeleteExecutorOnClosingTransactionManager() { snapshotTransactionManager.close(); <START> assertThat(executorService.isTerminated()).isTrue(); <END> }</code><technical_language>nit: rename this executor service deleteExecutor (if for)</technical_language>

Target:
public void closesDeleteExecutorOnClosingTransactionManager() { snapshotTransactionManager.close(); assertThat(deleteExecutor.isTerminated()).isTrue(); }
Source:
<code><START> public boolean equals(Object o) { <END> if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SyncDomainCommand that = (SyncDomainCommand) o; if (_toAdd != that._toAdd) return false; if (_toRemove != that._toRemove) return false; if (_domainName != null ? !_domainName.equals(that._domainName) : that._domainName != null) return false; if (_domainPath != null ? !_domainPath.equals(that._domainPath) : that._domainPath != null) return false; if (_domainUuid != null ? !_domainUuid.equals(that._domainUuid) : that._domainUuid != null) return false; return true; }</code><technical_language>This equals implementation include attributes Command super class</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof SyncDomainCommand)) return false; if (!super.equals(o)) return false; SyncDomainCommand that = (SyncDomainCommand) o; if (_toAdd != that._toAdd) return false; if (_toRemove != that._toRemove) return false; if (_domainName != null ? !_domainName.equals(that._domainName) : that._domainName != null) return false; if (_domainPath != null ? !_domainPath.equals(that._domainPath) : that._domainPath != null) return false; if (_domainUuid != null ? !_domainUuid.equals(that._domainUuid) : that._domainUuid != null) return false; return true; }
Source:
<code>protected boolean onOK(Metadata trailers) { rowMerger.onCompleted(); <START> if (!completionFuture.isDone()) { <END> completionFuture.set(""); } return true; }</code><technical_language>This is unnecessary. A future's state set</technical_language>

Target:
protected boolean onOK(Metadata trailers) { rowMerger.onCompleted(); completionFuture.set(""); return true; }
Source:
<code>public void setStatus(final String message) { boolean processing = getLegacyService().setProcessingEvents(true); if (processing) return; try { final IJ1Helper ij1helper = helper(); if (ij1helper != null) ij1helper.setStatus(message); } finally { <START> final LegacyService LegacyService = getLegacyService(); <END> if (LegacyService != null) LegacyService.setProcessingEvents(processing); } }</code><technical_language>Please start variables a capital letter: final LegacyService legacyService = getLegacyService();</technical_language>

Target:
public void setStatus(final String message) { boolean processing = getLegacyService().setProcessingEvents(true); if (processing) return; try { final IJ1Helper ij1Helper = helper(); if (ij1Helper != null) ij1Helper.setStatus(message); } finally { final LegacyService legacyService = getLegacyService(); if (legacyService != null) legacyService.setProcessingEvents(processing); } }
Source:
<code>public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { processInternal(annotations, roundEnv); } catch (DeepLinkProcessorException e) { error(e.getElement(), e.getMessage()); } <START> return true; <END> }</code><technical_language>change this return true? I in general is return false other processors annotations</technical_language>

Target:
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { processInternal(annotations, roundEnv); } catch (DeepLinkProcessorException e) { error(e.getElement(), e.getMessage()); } return false; }
Source:
<code>public void setRemoteException(Throwable remoteException) { StringBuilder sb = new StringBuilder(); Set<Throwable> causes = new HashSet(); while (remoteException != null) { sb.append(remoteException.toString()); StackTraceElement[] stackTraceElements = remoteException.getStackTrace(); if (stackTraceElements != null && stackTraceElements.length > 0) { for (StackTraceElement ste : stackTraceElements) { sb.append("\n\t at ").append(ste.toString()); } sb.append("\nsuppressed: "); <START> sb.append(remoteException.getSuppressed().toString()); <END> if (remoteException.getCause() != null) { sb.append("\ncaused by: "); remoteException = remoteException.getCause(); if (!causes.add(remoteException)) { break; } } else { break; } } } remoteExceptionString = sb.append('\n').toString(); }</code><technical_language>I need Arrays.toString iterate elements print individual StackTraceElements if want more detailed message (I'd opt for option no. 2)</technical_language>

Target:
public void setRemoteException(Throwable remoteException) { StringBuilder sb = new StringBuilder(); Set<Throwable> causes = new HashSet(); while (remoteException != null) { sb.append(remoteException.toString()); StackTraceElement[] stackTraceElements = remoteException.getStackTrace(); if (stackTraceElements != null && stackTraceElements.length > 0) { for (StackTraceElement ste : stackTraceElements) { sb.append("\n\t at ").append(ste.toString()); } sb.append("\nsuppressed: "); sb.append(Arrays.toString(remoteException.getSuppressed())); if (remoteException.getCause() != null) { sb.append("\ncaused by: "); remoteException = remoteException.getCause(); if (!causes.add(remoteException)) { break; } } else { break; } } } remoteExceptionString = sb.append('\n').toString(); }
Source:
<code>public long getMaxIdle() { <START> return 0; <END> }</code><technical_language>this return RecordStore.DEFAULT_TTL (-1 --> MapConfig's default) instead of 0 (--> infinite max idle)</technical_language>

Target:
public Long getMaxIdle() { return null; }
Source:
<code>private void openFetchRequest() { try { if (messageAndOffsetIterator == null) { long threadId = Thread.currentThread().getId(); if (this.consumer == null) { this.consumer = consumerManager.createConsumer(threadId, split.getLeader()); } <START> TopicPartition tp = new TopicPartition(split.getTopicName(), split.getPartitionId()); <END> this.consumer.assign(ImmutableList.of(tp)); this.consumer.seek(tp, cursorOffset); ConsumerRecords<ByteBuffer, ByteBuffer> records = this.consumer.poll(3000); this.consumer.commitSync(); messageAndOffsetIterator = records.records(tp).iterator(); } } catch (Exception e) { if (e instanceof PrestoException) { throw e; } throw new PrestoException( KAFKA_SPLIT_ERROR, format( "Cannot read data from topic '%s', partition '%s', startOffset %s, endOffset %s, leader %s ", split.getTopicName(), split.getPartitionId(), split.getStart(), split.getEnd(), split.getLeader()), e); } }</code><technical_language>variable abbreviation, s/tp/topicPartition/g</technical_language>

Target:
private void openFetchRequest() { try { if (messageAndOffsetIterator == null) { String threadName = Thread.currentThread().getName(); if (consumer == null) { consumer = consumerManager.createConsumer(threadName, split.getLeader()); } TopicPartition topicPartition = new TopicPartition(split.getTopicName(), split.getPartitionId()); consumer.assign(ImmutableList.of(topicPartition)); consumer.seek(topicPartition, cursorOffset); ConsumerRecords<ByteBuffer, ByteBuffer> records = consumer.poll(POLL_TIMEOUT); messageAndOffsetIterator = records.records(topicPartition).iterator(); } } catch (Exception e) { if (e instanceof PrestoException) { throw e; } throw new PrestoException( KAFKA_SPLIT_ERROR, format( "Cannot read data from topic '%s', partition '%s', startOffset %s, endOffset %s, leader %s ", split.getTopicName(), split.getPartitionId(), split.getStart(), split.getEnd(), split.getLeader()), e); } }
Source:
<code><START> public SpringBasedHttpClient() { } <END></code><technical_language>init clientParams is null</technical_language>

Target:
public SpringBasedHttpClient() { clientParams = new HashMap<>(); restTemplate = new RestTemplate(); restTemplate.setRequestFactory(getSslAllTrustRequestFactory()); }
Source:
<code>public void onChapterSelected(Chapter selectedChapter) { <START> updateSelectionFor(selectedChapter.getGplusId()); <END> }</code><technical_language>here, convert a chapter id a chapter. more performant</technical_language>

Target:
public void onChapterSelected(Chapter selectedChapter) { updateSelectionFor(selectedChapter); }
Source:
<code>public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c, MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException { Mutation m = miniBatchOp.getOperation(0); if (!codec.isEnabled(m)) { super.preBatchMutate(c, miniBatchOp); return; } Map<String,byte[]> updateAttributes = m.getAttributesMap(); PhoenixIndexMetaData indexMetaData = new PhoenixIndexMetaData(c.getEnvironment(),updateAttributes); byte[] txRollbackAttribute = m.getAttribute(TxConstants.TX_ROLLBACK_ATTRIBUTE_KEY); Collection<Pair<Mutation, byte[]>> indexUpdates = null; try (TraceScope scope = Trace.startSpan("Starting to build index updates")) { Span current = scope.getSpan(); if (current == null) { current = NullSpan.INSTANCE; } indexUpdates = getIndexUpdates(c.getEnvironment(), indexMetaData, getMutationIterator(miniBatchOp), txRollbackAttribute); IndexUtil.addLocalUpdatesToCpOperations(c, miniBatchOp, indexUpdates, <START> m.getDurability() != Durability.SKIP_WAL); <END> current.addTimelineAnnotation("Built index updates, doing preStep"); TracingUtils.addAnnotation(current, "index update count", indexUpdates.size()); if (!indexUpdates.isEmpty()) { this.writer.write(indexUpdates); } } catch (Throwable t) { String msg = "Failed to update index with entries:" + indexUpdates; LOG.error(msg, t); ServerUtil.throwIOException(msg, t); } }</code><technical_language>conditionally _not_ run this code depending HBase version</technical_language>

Target:
public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c, MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException { Mutation m = miniBatchOp.getOperation(0); if (!codec.isEnabled(m)) { super.preBatchMutate(c, miniBatchOp); return; } Map<String,byte[]> updateAttributes = m.getAttributesMap(); PhoenixIndexMetaData indexMetaData = new PhoenixIndexMetaData(c.getEnvironment(),updateAttributes); byte[] txRollbackAttribute = m.getAttribute(TxConstants.TX_ROLLBACK_ATTRIBUTE_KEY); Collection<Pair<Mutation, byte[]>> indexUpdates = null; try (TraceScope scope = Trace.startSpan("Starting to build index updates")) { Span current = scope.getSpan(); if (current == null) { current = NullSpan.INSTANCE; } indexUpdates = getIndexUpdates(c.getEnvironment(), indexMetaData, getMutationIterator(miniBatchOp), txRollbackAttribute); current.addTimelineAnnotation("Built index updates, doing preStep"); TracingUtils.addAnnotation(current, "index update count", indexUpdates.size()); if (!indexUpdates.isEmpty()) { this.writer.write(indexUpdates, true); } } catch (Throwable t) { String msg = "Failed to update index with entries:" + indexUpdates; LOG.error(msg, t); ServerUtil.throwIOException(msg, t); } }
Source:
<code>protected void onRestoreInstanceState(Bundle savedInstanceState) { <START> super.onRestoreInstanceState(savedInstanceState); <END> eye = savedInstanceState.getInt("eyeNum"); eye_setter(eye); face = savedInstanceState.getInt("faceNum"); face_setter(face); cloth = savedInstanceState.getInt("clothNum"); cloth_setter(cloth); hair = savedInstanceState.getInt("hairNum"); hair_setter(hair); }</code><technical_language>Put values in integer.xml</technical_language>

Target:
protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); eye = savedInstanceState.getInt("eyeNum"); face = savedInstanceState.getInt("faceNum"); cloth = savedInstanceState.getInt("clothNum");; hair = savedInstanceState.getInt("hairNum"); resourceSetter(eye,getResources().getString(R.string.eye)); resourceSetter(face,getResources().getString(R.string.face)); resourceSetter(hair,getResources().getString(R.string.hair)); resourceSetter(cloth,getResources().getString(R.string.cloth)); }
Source:
<code>public DiscountFactors discountFactors(Currency currency) { <START> Curve curve = marketData.getValue(DiscountCurveKey.of(currency)); <END> if (curve == null) { throw new IllegalArgumentException("Unable to find discount curve: " + currency); } return DiscountFactors.of(currency, getValuationDate(), curve); }</code><technical_language>MarketData.getValue returns null. throws IllegalArgumentException for unknown key</technical_language>

Target:
public DiscountFactors discountFactors(Currency currency) { Curve curve = marketData.getValue(DiscountCurveKey.of(currency)); return DiscountFactors.of(currency, getValuationDate(), curve); }
Source:
<code>public void markJobEnded(boolean result) { if (status == ExecutionStatus.STARTED) { <START> Date endJobTime = new Date(); <END> endTime = endJobTime; lastUpdateTime = endJobTime; if (result) { status = ExecutionStatus.FINISHED; } else { status = ExecutionStatus.FAILED; } } }</code><technical_language>do need endJobTime local variable</technical_language>

Target:
public void markJobEnded(boolean result) { if (status == JobExecutionStatus.STARTED) { endTime = lastUpdateTime = new Date(); if (result) { status = JobExecutionStatus.FINISHED; } else { status = JobExecutionStatus.FAILED; } } }
Source:
<code>public MorphiaSerializer(Morphia morphia) { <START> this.morphia = morphia == null ? new Morphia() : morphia; <END> this.geometryQueryConverter = new GeometryQueryConverter(this.morphia.getMapper()); }</code><technical_language>this implies null a valid argument constructor,</technical_language>

Target:
public MorphiaSerializer(Morphia morphia) { Preconditions.checkNotNull(morphia); this.morphia = morphia; this.geometryQueryConverter = new GeometryQueryConverter(morphia.getMapper()); }
Source:
<code>public Optional<RoamingGroup> findById(ID id) { RoamingGroupEntity entity = datastore.findOne(RoamingGroupEntity.class, Filter.where("_id").is(id.value)); if (entity == null) { return Optional.absent(); } <START> List<OperatorEntity> operatorEntities = datastore.findAllObjectsByFilter(OperatorEntity.class, Filter.where("_id").in(Lists.newArrayList(entity.operatorIDs))); <END> return Optional.of(adapt(entity, operatorEntities)); }</code><technical_language>Lists.newArrayList(entity.operatorIDs)) operatorIDs represents</technical_language>

Target:
public Optional<RoamingGroup> findById(ID id) { RoamingGroupEntity entity = datastore.findOne(RoamingGroupEntity.class, Filter.where("_id").is(id.value)); if (entity == null) { return Optional.absent(); } List<OperatorEntity> operatorEntities = datastore.findAllObjectsByFilter(OperatorEntity.class, Filter.where("_id").in(entity.operatorIDs)); return Optional.of(adapt(entity, operatorEntities)); }
Source:
<code>public static Sensor expiredWindowRecordDropSensor(final String threadId, final String taskId, final String storeType, final String storeName, final StreamsMetricsImpl streamsMetrics) { <START> final Sensor sensor = streamsMetrics.storeLevelSensor( <END> threadId, taskId, storeName, EXPIRED_WINDOW_RECORD_DROP, RecordingLevel.INFO ); final Version version = streamsMetrics.version(); if (version == Version.FROM_0100_TO_24) { addInvocationRateAndCountToSensor( sensor, "stream-" + storeType + "-metrics", streamsMetrics.storeLevelTagMap(threadId, taskId, storeType, storeName), EXPIRED_WINDOW_RECORD_DROP, EXPIRED_WINDOW_RECORD_DROP_RATE_DESCRIPTION, EXPIRED_WINDOW_RECORD_DROP_TOTAL_DESCRIPTION ); } return sensor; }</code><technical_language>I in KIP-444 this metric replaced task-level dropped-records right</technical_language>

Target:
public static Sensor expiredWindowRecordDropSensor(final String threadId, final String taskId, final String storeType, final String storeName, final StreamsMetricsImpl streamsMetrics) { final Sensor sensor = streamsMetrics.storeLevelSensor( threadId, taskId, storeName, EXPIRED_WINDOW_RECORD_DROP, RecordingLevel.INFO ); addInvocationRateAndCountToSensor( sensor, "stream-" + storeType + "-metrics", streamsMetrics.storeLevelTagMap(threadId, taskId, storeType, storeName), EXPIRED_WINDOW_RECORD_DROP, EXPIRED_WINDOW_RECORD_DROP_RATE_DESCRIPTION, EXPIRED_WINDOW_RECORD_DROP_TOTAL_DESCRIPTION ); return sensor; }
Source:
<code>public static RedisConnectionFactory newRedisConnectionFactory(final BaseRedisProperties redis) { LOGGER.debug("Loaded Redis configuration {}", redis); <START> final RedisConfiguration redisConfiguration = redis.getSentinel() == null <END> ? getStandaloneConfig(redis) : getSentinelConfig(redis); val factory = new LettuceConnectionFactory(redisConfiguration, getRedisPoolConfig(redis)); return factory; }</code><technical_language>val var</technical_language>

Target:
public static RedisConnectionFactory newRedisConnectionFactory(final BaseRedisProperties redis) { val redisConfiguration = redis.getSentinel() == null ? (RedisConfiguration) getStandaloneConfig(redis) : getSentinelConfig(redis); val factory = new LettuceConnectionFactory(redisConfiguration, getRedisPoolConfig(redis)); return factory; }
Source:
<code>private CharSequence getStatementName(long lo, long hi) { CharacterStoreEntry e = portalCharacterStore.newEntry(); CharSequence statementName = null; <START> if (hi - lo > 0 && Chars.utf8Decode(lo, hi, e)) { <END> statementName = portalCharacterStore.toImmutable(); } return statementName; }</code><technical_language>utf8Decode returns decoding status. corrupt message. uff8 decoded BadProtocolException is thrown</technical_language>

Target:
private CharSequence getStatementName(long lo, long hi) throws BadProtocolException { CharacterStoreEntry e = portalCharacterStore.newEntry(); CharSequence statementName = null; if (hi - lo > 0) { if (Chars.utf8Decode(lo, hi, e)) { statementName = portalCharacterStore.toImmutable(); } else { LOG.error().$("invalid UTF8 bytes in statement name").$(); throw BadProtocolException.INSTANCE; } } return statementName; }
Source:
<code>public <T> T getObject(String propertyName, Class<T> c, boolean... convertFromCamelCase) { if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) { JsonNode jsonObj = propertyBag.get(propertyName); if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c) || Boolean.class.isAssignableFrom(c) || Object.class == c) { return c.cast(getValue(jsonObj)); } else if (Enum.class.isAssignableFrom(c)) { try { String value = String.class.cast(getValue(jsonObj)); value = convertFromCamelCase.length > 0 && convertFromCamelCase[0] ? Strings.fromCamelCaseToUpperCase(value) : value; return c.cast(c.getMethod("valueOf", String.class).invoke(null, value)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalStateException("Failed to create enum.", e); } } else if (JsonSerializable.class.isAssignableFrom(c)) { return (T) ModelBridgeInternal.instantiateJsonSerializable((ObjectNode) jsonObj, c); } else if (containsJsonSerializable(c)) { <START> return ModelBridgeInternal.instantiateByJsonString(Utils.toJson(Utils.getSimpleObjectMapper(), (ObjectNode) jsonObj), c); <END> } else { JsonSerializable.checkForValidPOJO(c); try { return this.getMapper().treeToValue(jsonObj, c); } catch (IOException e) { throw new IllegalStateException("Failed to get POJO.", e); } } } return null; }</code><technical_language>this result in double json serialization/deserialization? pass ObjectNode instead? this serialize string class deserialize string ObjectNode</technical_language>

Target:
public <T> T getObject(String propertyName, Class<T> c, boolean... convertFromCamelCase) { if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) { JsonNode jsonObj = propertyBag.get(propertyName); if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c) || Boolean.class.isAssignableFrom(c) || Object.class == c) { return c.cast(getValue(jsonObj)); } else if (Enum.class.isAssignableFrom(c)) { try { String value = String.class.cast(getValue(jsonObj)); value = convertFromCamelCase.length > 0 && convertFromCamelCase[0] ? Strings.fromCamelCaseToUpperCase(value) : value; return c.cast(c.getMethod("valueOf", String.class).invoke(null, value)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalStateException("Failed to create enum.", e); } } else if (JsonSerializable.class.isAssignableFrom(c)) { return (T) ModelBridgeInternal.instantiateJsonSerializable((ObjectNode) jsonObj, c); } else if (containsJsonSerializable(c)) { return ModelBridgeInternal.instantiateByObjectNode((ObjectNode) jsonObj, c); } else { JsonSerializable.checkForValidPOJO(c); try { return this.getMapper().treeToValue(jsonObj, c); } catch (IOException e) { throw new IllegalStateException("Failed to get POJO.", e); } } } return null; }
Source:
<code>void rebuildTokenMap() { <START> lock.lock(); <END> try { if (tokenMap == null) return; Token.Factory factory = getTokenFactory(partitioner); if (factory == null) return; this.tokenMap = TokenMap.build( factory, tokenMap.primaryToTokens, keyspaces.values(), tokenMap.ring, tokenMap.tokenRanges, tokenMap.tokenToPrimary); } finally { lock.unlock(); } }</code><technical_language>nice</technical_language>

Target:
void rebuildTokenMap() { lock.lock(); try { if (tokenMap == null) return; this.tokenMap = TokenMap.build( tokenMap.factory, tokenMap.primaryToTokens, keyspaces.values(), tokenMap.ring, tokenMap.tokenRanges, tokenMap.tokenToPrimary); } finally { lock.unlock(); } }