auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ICPPExecution instantiate(InstantiationContext context, int maxDepth) { ICPPEvaluation newControllerExprEval = controllerExprEval != null ? controllerExprEval.instantiate(context, maxDepth) : null; ExecSimpleDeclaration newControllerDeclExec = controllerDeclExec != null ? (ExecSimpleDeclaration)controllerDeclExec.instantiate(context, maxDepth) : null; ICPPExecution[] newBodyStmtExecutions = new ICPPExecution[bodyStmtExecutions.length]; <START> boolean evaluationsDidChange = false; <END> for(int i = 0; i < bodyStmtExecutions.length; i++) { ICPPExecution bodyStmtExec = bodyStmtExecutions[i]; ICPPExecution newBodyStmtExec = bodyStmtExec.instantiate(context, maxDepth); if(newBodyStmtExec != bodyStmtExec) { evaluationsDidChange = true; } newBodyStmtExecutions[i] = newBodyStmtExec; } if (newControllerExprEval == controllerExprEval && newControllerDeclExec == controllerDeclExec && !evaluationsDidChange) { return this; } return new ExecSwitch(newControllerExprEval, newControllerDeclExec, newBodyStmtExecutions); }</code><technical_language>executionsDidChange</technical_language>

Target:
public ICPPExecution instantiate(InstantiationContext context, int maxDepth) { ICPPEvaluation newControllerExprEval = controllerExprEval != null ? controllerExprEval.instantiate(context, maxDepth) : null; ExecSimpleDeclaration newControllerDeclExec = controllerDeclExec != null ? (ExecSimpleDeclaration)controllerDeclExec.instantiate(context, maxDepth) : null; ICPPExecution[] newBodyStmtExecutions = new ICPPExecution[bodyStmtExecutions.length]; boolean executionsDidChange = false; for(int i = 0; i < bodyStmtExecutions.length; i++) { ICPPExecution bodyStmtExec = bodyStmtExecutions[i]; ICPPExecution newBodyStmtExec = bodyStmtExec.instantiate(context, maxDepth); if(newBodyStmtExec != bodyStmtExec) { executionsDidChange = true; } newBodyStmtExecutions[i] = newBodyStmtExec; } if (newControllerExprEval == controllerExprEval && newControllerDeclExec == controllerDeclExec && !executionsDidChange) { return this; } return new ExecSwitch(newControllerExprEval, newControllerDeclExec, newBodyStmtExecutions); }
Source:
<code>public void onClose(int closeCode, String message) { LOGGER.info("onClose( closeCode={}, message={})", connection, message); if (null != closeListener) { closeListener.onClose(closeCode, message, this.session); } <START> if (this.session != null) { <END> this.session.close(); this.session = null; } syncEventBus.unregister(this); asyncEventBus.unregister(this); }</code><technical_language>put this in a finally</technical_language>

Target:
public void onClose(int closeCode, String message) { LOGGER.info("onClose( closeCode={}, message={})", connection, message); try { if (null != closeListener) { closeListener.onClose(closeCode, message, this.session); } } finally { if (this.session != null) { this.session.close(); this.session = null; } syncEventBus.unregister(this); asyncEventBus.unregister(this); } }
Source:
<code>protected Set<Value.Immutable<?>> api$getVanillaValues() { Set<Value.Immutable<?>> vanillaValues = super.api$getVanillaValues(); <START> if (this.shadow$getOwnerUniqueId() != null) { <END> this.tamer().map(Value::asImmutable).ifPresent(vanillaValues::add); } return vanillaValues; }</code><technical_language>Delete if, ifPresent covers if</technical_language>

Target:
protected Set<Value.Immutable<?>> api$getVanillaValues() { final Set<Value.Immutable<?>> values = super.api$getVanillaValues(); this.tamer().map(Value::asImmutable).ifPresent(values::add); return values; }
Source:
<code>public String getGiverTypeForQuestion(int qnNumber) { <START> WebElement giverDropdownForQuestion= browser.driver.findElement(By.id("questionedittext-" + qnNumber)); <END> return giverDropdownForQuestion.getAttribute("value"); }</code><technical_language>Wrong id; forgot change copy-pasting. Also, add a space =</technical_language>

Target:
public String getGiverTypeForQuestion(int qnNumber) { WebElement giverDropdownForQuestion = browser.driver.findElement(By.id("givertype-" + qnNumber)); return giverDropdownForQuestion.getAttribute("value"); }
Source:
<code>public Map<String, String> load() { final Map<String, String> preferences = new HashMap<String, String>(); <START> final String property = System.getProperty( GuidedDecisionTableEditorService.DTABLE_VERIFICATION_ENABLED ); <END> log.info( "Setting preference '" + GuidedDecisionTableEditorService.DTABLE_VERIFICATION_ENABLED + "' to '" + property + "'." ); preferences.put( GuidedDecisionTableEditorService.DTABLE_VERIFICATION_ENABLED, property ); return preferences; }</code><technical_language>check if this is null set if non-null... IDK if code handles null differently</technical_language>

Target:
public Map<String, String> load() { final Map<String, String> preferences = new HashMap<String, String>(); final String property = getProperty(); log.info( "Setting preference '" + GuidedDecisionTableEditorService.DTABLE_VERIFICATION_ENABLED + "' to '" + property + "'." ); preferences.put( GuidedDecisionTableEditorService.DTABLE_VERIFICATION_ENABLED, property ); return preferences; }
Source:
<code>protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { logger.debug("Executed RebuildMetadataCronJob."); CronTaskConfiguration config = (CronTaskConfiguration) jobExecutionContext.getMergedJobDataMap().get("config"); try { String storageId = config.getProperty("storageId"); String repositoryId = config.getProperty("repositoryId"); String basePath = config.getProperty("basePath"); if (storageId == null) { List<String> storagesId = getStoragesId(); for (String storage : storagesId) { Path storagePath = Paths.get(getStoragesBasePath(), storage); List<String> repositoriesId = getRepositoriesId(storagePath); rebuildRepositories(repositoriesId, storage, basePath); } } else if (repositoryId == null) { Path storagePath = Paths.get(getStoragesBasePath(), storageId); <START> List<String> repositoriesId = getRepositoriesId(storagePath); <END> rebuildRepositories(repositoriesId, storageId, basePath); } else { artifactMetadataService.rebuildMetadata(storageId, repositoryId, basePath); } } catch (IOException | XmlPullParserException | NoSuchAlgorithmException e) { e.printStackTrace(); logger.error("IOException: ", e); } manager.addExecutedJob(config.getName(), true); }</code><technical_language>please change this repositories? Actually, I better, if pass storage a parameter rebuildRepositories (instead of a list)</technical_language>

Target:
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { logger.debug("Executed RebuildMetadataCronJob."); CronTaskConfiguration config = (CronTaskConfiguration) jobExecutionContext.getMergedJobDataMap().get("config"); try { String storageId = config.getProperty("storageId"); String repositoryId = config.getProperty("repositoryId"); String basePath = config.getProperty("basePath"); if (storageId == null) { Map<String, Storage> storages = getStorages(); for (String storage : storages.keySet()) { rebuildRepositories(storage); } } else if (repositoryId == null) { rebuildRepositories(storageId); } else { artifactMetadataService.rebuildMetadata(storageId, repositoryId, basePath); } } catch (IOException | XmlPullParserException | NoSuchAlgorithmException e) { logger.error(e.getMessage(), e); } manager.addExecutedJob(config.getName(), true); }
Source:
<code>public ContentItemImpl( String id, String qualifier, ByteSource byteSource, String mimeTypeRawData, String filename, long size, Metacard metacard) { this.byteSource = byteSource; this.id = id; if (StringUtils.isNotBlank(qualifier)) { this.qualifier = qualifier; } else { this.qualifier = null; } this.mimeType = null; this.size = size; if (filename != null) { this.filename = filename; } else { this.filename = DEFAULT_FILE_NAME; } this.metacard = metacard; this.mimeTypeRawData = DEFAULT_MIME_TYPE; if (StringUtils.isNotBlank(mimeTypeRawData)) { this.mimeTypeRawData = mimeTypeRawData; } try { this.mimeType = new MimeType(this.mimeTypeRawData); uri = new URI(CONTENT_SCHEME, this.id, this.qualifier); } catch (MimeTypeParseException e) { LOGGER.debug("Unable to create MimeType from raw data {}", mimeTypeRawData); } catch (URISyntaxException e) { <START> throw new IllegalArgumentException("Unable to create content URI.", e); <END> } }</code><technical_language>this logic changed? If unable set this.mimeType do want continue set this.uri</technical_language>

Target:
public ContentItemImpl( String id, String qualifier, ByteSource byteSource, String mimeTypeRawData, String filename, long size, Metacard metacard) { this.byteSource = byteSource; this.id = id; if (StringUtils.isNotBlank(qualifier)) { this.qualifier = qualifier; } else { this.qualifier = null; } this.mimeType = null; this.size = size; if (filename != null) { this.filename = filename; } else { this.filename = DEFAULT_FILE_NAME; } this.metacard = metacard; this.mimeTypeRawData = DEFAULT_MIME_TYPE; if (StringUtils.isNotBlank(mimeTypeRawData)) { this.mimeTypeRawData = mimeTypeRawData; } try { this.mimeType = new MimeType(this.mimeTypeRawData); } catch (MimeTypeParseException e) { LOGGER.debug("Unable to create MimeType from raw data {}", mimeTypeRawData); } try { uri = new URI(CONTENT_SCHEME, this.id, this.qualifier); } catch (URISyntaxException e) { throw new IllegalArgumentException("Unable to create content URI.", e); } }
Source:
<code>public static ModelNode parseAttributeValue(final String value, final boolean isExpressionAllowed, final ModelType attributeType) { final String trimmed = value == null ? null : value.trim(); ModelNode node; if (trimmed != null) { if (isExpressionAllowed && isExpression(value)) { <START> node = new ModelNode(new ValueExpression(value)); <END> } else { if(attributeType == STRING || attributeType == PROPERTY) { node = new ModelNode().set(value); } else { node = new ModelNode().set(trimmed); } } if (node.getType() != ModelType.EXPRESSION) { try { switch (attributeType) { case BIG_DECIMAL: node.set(node.asBigDecimal()); break; case BIG_INTEGER: node.set(node.asBigInteger()); break; case BOOLEAN: node.set(node.asBoolean()); break; case BYTES: node.set(node.asBytes()); break; case DOUBLE: node.set(node.asDouble()); break; case INT: node.set(node.asInt()); break; case LONG: node.set(node.asLong()); break; } } catch (IllegalArgumentException iae) { } } } else { node = new ModelNode(); } return node; }</code><technical_language>This do test non-expression else block does, 'trimmed' attributeType is STRING PROPERTY. expression meant resolve a string convertible some other type leading/trailing whitespace stop helpful that</technical_language>

Target:
public static ModelNode parseAttributeValue(final String value, final boolean isExpressionAllowed, final ModelType attributeType) { final String trimmed = value == null ? null : value.trim(); ModelNode node; if (trimmed != null) { if (isExpressionAllowed && isExpression(value)) { if(attributeType == STRING || attributeType == PROPERTY) { node = new ModelNode(new ValueExpression(value)); } else { node = new ModelNode(new ValueExpression(trimmed)); } } else { if(attributeType == STRING || attributeType == PROPERTY) { node = new ModelNode().set(value); } else { node = new ModelNode().set(trimmed); } } if (node.getType() != ModelType.EXPRESSION) { try { switch (attributeType) { case BIG_DECIMAL: node.set(node.asBigDecimal()); break; case BIG_INTEGER: node.set(node.asBigInteger()); break; case BOOLEAN: node.set(node.asBoolean()); break; case BYTES: node.set(node.asBytes()); break; case DOUBLE: node.set(node.asDouble()); break; case INT: node.set(node.asInt()); break; case LONG: node.set(node.asLong()); break; } } catch (IllegalArgumentException iae) { } } } else { node = new ModelNode(); } return node; }
Source:
<code>public RandomNodeSelection( NodeMap nodeMap, boolean includeCoordinator, int minCandidates, int maxTasksPerStage, List<RemoteTask> existingTasks) { this.nodeMap = nodeMap; this.includeCoordinator = includeCoordinator; this.minCandidates = minCandidates; <START> randomCandidates = getRandomCandidates(maxTasksPerStage, this.nodeMap, existingTasks); <END> }</code><technical_language>this</technical_language>

Target:
public RandomNodeSelection( NodeMap nodeMap, boolean includeCoordinator, int minCandidates, int maxTasksPerStage, List<RemoteTask> existingTasks) { requireNonNull(nodeMap, "nodeMap is null"); requireNonNull(existingTasks, "existingTasks is null"); this.includeCoordinator = includeCoordinator; this.minCandidates = minCandidates; this.randomCandidates = getRandomCandidates(maxTasksPerStage, nodeMap, existingTasks); }
Source:
<code>public void send_telemetry_data_at_startup() throws Exception { String serverId = randomAlphanumeric(40); orchestrator = Orchestrator.builderEnv() .addPlugin(xooPlugin()) .setServerProperty("sonar.telemetry.url", url) .setServerProperty("sonar.telemetry.frequency", "1") <START> .setServerProperty("sonar.core.id", serverId) <END> .build(); orchestrator.start(); RecordedRequest request = server.takeRequest(1, TimeUnit.SECONDS); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getBody().readUtf8()).contains(serverId); assertThat(request.getHeader(HttpHeaders.USER_AGENT)).contains("SonarQube"); orchestrator.stop(); }</code><technical_language>surprized define this property (which is a property)</technical_language>

Target:
public void send_telemetry_data_at_startup() throws Exception { String serverId = randomAlphanumeric(40); orchestrator = Orchestrator.builderEnv() .addPlugin(xooPlugin()) .setServerProperty("sonar.telemetry.url", url) .setServerProperty("sonar.telemetry.frequencyInSeconds", "1") .setServerProperty("sonar.core.id", serverId) .build(); orchestrator.start(); RecordedRequest request = server.takeRequest(1, TimeUnit.SECONDS); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getBody().readUtf8()).contains(serverId); assertThat(request.getHeader(HttpHeaders.USER_AGENT)).contains("SonarQube"); orchestrator.stop(); }
Source:
<code>protected RemoteOperationResult<ShareParserResult> run(OwnCloudClient client) { CreateRemoteShareOperation createOp = new CreateRemoteShareOperation( mPath, ShareType.PUBLIC_LINK, "", mPublicUpload, mPassword, mPermissions ); createOp.setGetShareDetails(true); createOp.setName(mName); createOp.setPublicUpload(mPublicUpload); createOp.setPermissions(mPermissions); createOp.setExpirationDate(mExpirationDateInMillis); RemoteOperationResult<ShareParserResult> result = createOp.execute(client); if (result.isSuccess()) { if (result.getData().getShares().size() > 0) { ShareParserResult shareParserResult = result.getData(); <START> if(shareParserResult.getShares().size() != 0) { <END> updateData(shareParserResult.getShares().get(0)); } else { result = new RemoteOperationResult<>( RemoteOperationResult.ResultCode.SHARE_NOT_FOUND); result.setData(shareParserResult); } } else { result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND); } } return result; }</code><technical_language>simplified. allways != 0, this check is neccessary</technical_language>

Target:
protected RemoteOperationResult<ShareParserResult> run(OwnCloudClient client) { CreateRemoteShareOperation createOp = new CreateRemoteShareOperation( mPath, ShareType.PUBLIC_LINK, "", mPublicUpload, mPassword, mPermissions ); createOp.setGetShareDetails(true); createOp.setName(mName); createOp.setPublicUpload(mPublicUpload); createOp.setPermissions(mPermissions); createOp.setExpirationDate(mExpirationDateInMillis); RemoteOperationResult<ShareParserResult> result = createOp.execute(client); if (result.isSuccess()) { if (result.getData() != null && result.getData().getShares() != null && result.getData().getShares().size() > 0) { ShareParserResult shareParserResult = result.getData(); updateData(shareParserResult.getShares().get(0)); } else { result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND); } } return result; }
Source:
<code>public void logRetry(Logger log, String message, Throwable t) { long now = System.nanoTime(); <START> if (lastRetryLog < 0) { <END> if (log.isDebugEnabled()) { log.debug(getMessage(message, t)); } lastRetryLog = now; } else if ((now - lastRetryLog) > logIntervalNanoSec) { log.warn(getMessage(message), t); lastRetryLog = now; } else { if (log.isTraceEnabled()) { log.trace(getMessage(message, t)); } } }</code><technical_language>this check hasNeverLogged</technical_language>

Target:
public void logRetry(Logger log, String message, Throwable t) { long now = System.nanoTime(); if (hasNeverLogged) { if (log.isDebugEnabled()) { log.debug(getMessage(message, t)); } hasNeverLogged = false; lastRetryLog = now; } else if ((now - lastRetryLog) > logIntervalNanoSec) { log.warn(getMessage(message), t); lastRetryLog = now; } else { if (log.isTraceEnabled()) { log.trace(getMessage(message, t)); } } }
Source:
<code>public static MemoryPool map(Mempool poolEntity) { MemoryPool poolModel = new MemoryPool(); if (poolEntity == null) return null; <START> poolModel.setName(poolEntity.getName()); <END> poolModel.setAllocCount(poolEntity.getAllocCount()); poolModel.setColdCount(poolEntity.getColdCount()); poolModel.setHotCount(poolEntity.getHotCount()); poolModel.setMaxAlloc(poolEntity.getMaxAlloc()); poolModel.setMaxStdAlloc(poolEntity.getMaxStdAlloc()); poolModel.setPaddedSize(poolEntity.getPadddedSize()); poolModel.setPoolMisses(poolEntity.getPoolMisses()); return poolModel; }</code><technical_language>Is StringUtils.isNotEmpty() check required also</technical_language>

Target:
public static GlusterMemoryPool map(Mempool poolEntity) { GlusterMemoryPool poolModel = new GlusterMemoryPool(); if (poolEntity == null) return null; if (StringUtils.isNotEmpty(poolEntity.getName())) poolModel.setName(poolEntity.getName()); poolModel.setAllocCount(poolEntity.getAllocCount()); poolModel.setColdCount(poolEntity.getColdCount()); poolModel.setHotCount(poolEntity.getHotCount()); poolModel.setMaxAlloc(poolEntity.getMaxAlloc()); poolModel.setMaxStdAlloc(poolEntity.getMaxStdAlloc()); poolModel.setPaddedSize(poolEntity.getPadddedSize()); poolModel.setPoolMisses(poolEntity.getPoolMisses()); return poolModel; }
Source:
<code>protected long getPreferredWeight(final ProductSummary summary) { <START> Regions regions = ANSSRegionsFactory.getFactory().getRegions(); <END> long preferredWeight = DEFAULT_PREFERRED_WEIGHT; String source = summary.getId().getSource(); String eventSource = summary.getEventSource(); BigDecimal latitude = summary.getEventLatitude(); BigDecimal longitude = summary.getEventLongitude(); Point location = null; if (latitude != null && longitude != null) { location = new Point(longitude.doubleValue(), latitude.doubleValue()); } if (location != null) { if (regions.isAuthor(source, location)) { preferredWeight += AUTHORITATIVE_WEIGHT; } if (eventSource != null && regions.isAuthor(eventSource, location)) { preferredWeight += AUTHORITATIVE_EVENT_WEIGHT; } } if (eventSource != null && eventSource.equalsIgnoreCase(source)) { preferredWeight += SAME_SOURCE_WEIGHT; } return preferredWeight; }</code><technical_language>timing concerns here? Is for regions null slow connections this block</technical_language>

Target:
protected long getPreferredWeight(final ProductSummary summary) throws Exception { Regions regions = ANSSRegionsFactory.getFactory().getRegions(); if (regions == null) { throw new ContinuableListenerException( "Unable to load ANSS Authoritative Regions"); } long preferredWeight = DEFAULT_PREFERRED_WEIGHT; String source = summary.getId().getSource(); String eventSource = summary.getEventSource(); BigDecimal latitude = summary.getEventLatitude(); BigDecimal longitude = summary.getEventLongitude(); Point location = null; if (latitude != null && longitude != null) { location = new Point(longitude.doubleValue(), latitude.doubleValue()); } if (location != null) { if (regions.isAuthor(source, location)) { preferredWeight += AUTHORITATIVE_WEIGHT; } if (eventSource != null && regions.isAuthor(eventSource, location)) { preferredWeight += AUTHORITATIVE_EVENT_WEIGHT; } } if (eventSource != null && eventSource.equalsIgnoreCase(source)) { preferredWeight += SAME_SOURCE_WEIGHT; } return preferredWeight; }
Source:
<code><START> public Component(Package pkg, String component){ <END> mPackage = pkg; mComponent = component; }</code><technical_language>Space {</technical_language>

Target:
public Component(Package pkg, String component) { this.pkg = pkg; this.component = component; }
Source:
<code>public List<UserCouponDto> getInvestUserCoupons(String loginName, long loanId) { if (loanDetailsMapper.getByLoanId(loanId).getNonUseCoupon()){ <START> return null; <END> } List<UserCouponModel> userCouponModels = userCouponMapper.findByLoginName(loginName, null); List<UserCouponDto> dtoList = Lists.transform(userCouponModels, new Function<UserCouponModel, UserCouponDto>() { @Override public UserCouponDto apply(UserCouponModel userCouponModel) { return new UserCouponDto(couponMapper.findById(userCouponModel.getCouponId()), userCouponModel, couponLockSeconds); } }); return Lists.newArrayList(Iterators.filter(dtoList.iterator(), new Predicate<UserCouponDto>() { @Override public boolean apply(UserCouponDto dto) { return dto.isUnused(); } })); }</code><technical_language>Lists.new</technical_language>

Target:
public List<UserCouponDto> getInvestUserCoupons(String loginName, long loanId) { if (loanDetailsMapper.getByLoanId(loanId).getDisableCoupon()){ return new ArrayList<UserCouponDto>(); } List<UserCouponModel> userCouponModels = userCouponMapper.findByLoginName(loginName, null); List<UserCouponDto> dtoList = Lists.transform(userCouponModels, new Function<UserCouponModel, UserCouponDto>() { @Override public UserCouponDto apply(UserCouponModel userCouponModel) { return new UserCouponDto(couponMapper.findById(userCouponModel.getCouponId()), userCouponModel, couponLockSeconds); } }); return Lists.newArrayList(Iterators.filter(dtoList.iterator(), new Predicate<UserCouponDto>() { @Override public boolean apply(UserCouponDto dto) { return dto.isUnused(); } })); }
Source:
<code>public MethodSource<JavaInterfaceSource> setConstructor(boolean constructor) { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>Add error message</technical_language>

Target:
public MethodSource<JavaInterfaceSource> setConstructor(boolean constructor) { throw new UnsupportedOperationException("An interface couldn't have a constructor"); }
Source:
<code>ClientSession getClientSession() throws Exception { if (this.session == null || this.session.isClosed()) { log.debug("Creating new ActiveMQ session for async job messages..."); <START> ClientSessionFactory csf = this.getClientSessionFactory(); <END> this.session = csf.createSession(); log.debug("Created new ActiveMQ session: {}", this.session); } return this.session; }</code><technical_language>This is i connection play: this.connection.getSenderSession()</technical_language>

Target:
protected ClientSession getClientSession() throws Exception { if (this.session == null || this.session.isClosed()) { log.debug("Creating new ActiveMQ session for sending async job messages..."); this.session = this.sessionFactory.getEgressSession(); log.debug("Created new ActiveMQ session: {}", this.session); } return this.session; }
Source:
<code>public void run() { try { APILocator.getDistributedJournalAPI().processJournalEntries(); } <START> catch (Exception e) <END> { Logger.error(this, "Error ocurred while trying to process journal entries.", e); } }</code><technical_language>remove this try catch prevent annotation get exception do rollback</technical_language>

Target:
public void run() { try { APILocator.getDistributedJournalAPI().processJournalEntries(); } catch (Exception e) { Logger.error(this, "Error ocurred while trying to process journal entries.", e); throw new DotRuntimeException(e); } }
Source:
<code>private List<SourceRecord> checkpointsForGroup(String group) throws InterruptedException { try { long timestamp = System.currentTimeMillis(); List<Checkpoint> checkpoints = listConsumerGroupOffsets(group).entrySet().stream() .filter(x -> shouldCheckpointTopic(x.getKey().topic())) .map(x -> checkpoint(group, x.getKey(), x.getValue())) .filter(x -> x.downstreamOffset() > 0) .collect(Collectors.toList()); if (groupOffsetSyncEnabled) { DescribeConsumerGroupsResult describedGroups = targetAdminClient.describeConsumerGroups( Lists.newArrayList(group)); for (Map.Entry<String, KafkaFuture<ConsumerGroupDescription>> entry : describedGroups.describedGroups().entrySet()) { ConsumerGroupDescription consumerGroupDescription = entry.getValue().get(); if (consumerGroupDescription.state().equals(ConsumerGroupState.EMPTY)) { <START> alterGroupOffset(group, checkpoints); <END> } } } return checkpoints.stream().map(x -> checkpointRecord(x, timestamp)).collect(Collectors.toList()); } catch (ExecutionException e) { log.error("Error querying offsets for consumer group on cluster {}.", group, sourceClusterAlias, e); return Collections.emptyList(); } }</code><technical_language>This a side-effect in pure function</technical_language>

Target:
private List<Checkpoint> checkpointsForGroup(String group) throws ExecutionException, InterruptedException { return listConsumerGroupOffsets(group).entrySet().stream() .filter(x -> shouldCheckpointTopic(x.getKey().topic())) .map(x -> checkpoint(group, x.getKey(), x.getValue())) .filter(x -> x.downstreamOffset() > 0) .collect(Collectors.toList()); }
Source:
<code>public void postsTweetWithLanguages() throws Exception { final Repo repo = this.repo(); final List<Language> langs = Lists.newArrayList( this.lang("Java"), this.lang("Python") ); Mockito.when(repo.languages()).thenReturn(langs); final Twitter twitter = Mockito.mock(Twitter.class); <START> final Agent agent = new Tweets(repo.github(), twitter); <END> final Talk talk = this.talk(repo, this.issue(repo)); agent.execute(talk); Mockito.verify(twitter).post( Matchers.contains( String.format("#%s #%s", langs.get(0), langs.get(1)) ) ); }</code><technical_language>one-time variable</technical_language>

Target:
public void postsTweetWithLanguages() throws Exception { final Repo repo = new MkGithub().randomRepo(); final Twitter twitter = Mockito.mock(Twitter.class); new Tweets(repo.github(), twitter).execute( TweetsTest.talk(repo, repo.issues().create("", "")) ); Mockito.verify(twitter).post( Matchers.contains( Joiner.on(' ').join( Iterables.transform( repo.languages(), new Function<Language, String>() { @Override public String apply(final Language lang) { return String.format("#%s", lang.name()); } } ) ) ) ); }
Source:
<code>public boolean isScanMarkerRow(Result result) { if (result instanceof RowResult) { return ((RowResult) result).isMarkerRow(); } <START> return result.isEmpty(); <END> }</code><technical_language>I add a Precondition for Result instanceof RowResult if assumption is in correct</technical_language>

Target:
public boolean isScanMarkerRow(Result result) { Preconditions.checkState(result instanceof RowResult, "Should be an instance of RowResult"); return ((RowResult) result).isMarkerRow(); }
Source:
<code>public void testMonitor() throws IOException, InterruptedException { ArrayList<Field> fields = new ArrayList<>(Arrays.asList( new Field("version", String.class), new Field("avg_latency", Double.class), new Field("max_latency", Long.class), new Field("min_latency", Long.class), new Field("packets_received", Long.class), new Field("packets_sent", Long.class), new Field("num_alive_connections", Integer.class), new Field("outstanding_requests", Long.class), new Field("server_state", String.class), new Field("znode_count", Integer.class), new Field("watch_count", Integer.class), new Field("ephemerals_count", Integer.class), new Field("approximate_data_size", Long.class), new Field("open_file_descriptor_count", Long.class), new Field("max_file_descriptor_count", Long.class), new Field("last_client_response_size", Integer.class), new Field("max_client_response_size", Integer.class), new Field("min_client_response_size", Integer.class), new Field("uptime", Long.class), new Field("global_sessions", Long.class), new Field("local_sessions", Long.class), new Field("connection_drop_probability", Double.class) )); Map<String, Object> metrics = new HashMap<>(); ServerMetrics .getMetrics() .getMetricsProvider() .dump( (metric, value)-> { metrics.put(metric, value); }); <START> for (String metric : metrics.keySet()) { <END> if (metric.startsWith("avg_")) { fields.add(new Field(metric, Double.class)); } else { fields.add(new Field(metric, Long.class)); } } Field fieldsArray[] = fields.toArray(new Field[0]); testCommand("monitor", fieldsArray); }</code><technical_language>nit: remove this for loop put dump callback</technical_language>

Target:
public void testMonitor() throws IOException, InterruptedException { ArrayList<Field> fields = new ArrayList<>(Arrays.asList( new Field("version", String.class), new Field("avg_latency", Double.class), new Field("max_latency", Long.class), new Field("min_latency", Long.class), new Field("packets_received", Long.class), new Field("packets_sent", Long.class), new Field("num_alive_connections", Integer.class), new Field("outstanding_requests", Long.class), new Field("server_state", String.class), new Field("znode_count", Integer.class), new Field("watch_count", Integer.class), new Field("ephemerals_count", Integer.class), new Field("approximate_data_size", Long.class), new Field("open_file_descriptor_count", Long.class), new Field("max_file_descriptor_count", Long.class), new Field("last_client_response_size", Integer.class), new Field("max_client_response_size", Integer.class), new Field("min_client_response_size", Integer.class), new Field("uptime", Long.class), new Field("global_sessions", Long.class), new Field("local_sessions", Long.class), new Field("connection_drop_probability", Double.class) )); Map<String, Object> metrics = MetricsUtils.currentServerMetrics(); for (String metric : metrics.keySet()) { if (metric.startsWith("avg_")) { fields.add(new Field(metric, Double.class)); } else { fields.add(new Field(metric, Long.class)); } } Field fieldsArray[] = fields.toArray(new Field[0]); testCommand("monitor", fieldsArray); }
Source:
<code>public void approveSelection() { File selectedFile = getSelectedFile(); if (selectedFile.length() > selectedFile.getUsableSpace()) { <START> JOptionPane.showMessageDialog(this, "Not enough disk space!"); <END> return; } if (!java.nio.file.Files.isWritable(selectedFile.getParentFile().toPath())) { JOptionPane.showMessageDialog(this, MessageFormat.format(Constant.messages.getString("report.write.permission.dialog.message"), selectedFile.getAbsolutePath()), Constant.messages.getString("report.write.permission.dialog.title"), JOptionPane.ERROR_MESSAGE); return; } if (selectedFile.exists()) { int result = JOptionPane.showConfirmDialog(this, Constant.messages.getString("report.write.overwrite.dialog.message"), Constant.messages.getString("report.write.overwrite.dialog.title"), JOptionPane.YES_NO_OPTION); switch (result) { case JOptionPane.YES_OPTION: super.approveSelection(); return; case JOptionPane.NO_OPTION: case JOptionPane.CLOSED_OPTION: return; } } Model.getSingleton().getOptionsParam().setUserDirectory(getCurrentDirectory()); super.approveSelection(); }</code><technical_language>message internationalized (as others in WritableFileChooser). change align commit message (or commit message reworded. interactive rebase correctly portray change)</technical_language>

Target:
public void approveSelection() { File selectedFile = getSelectedFile(); File checkFile = selectedFile; boolean fileExists = checkFile.exists(); if (!fileExists) { checkFile = checkFile.getParentFile(); } if (checkFile.getUsableSpace() < MINIMUM_SPACE_REQUIREMENT_MB) { int result = JOptionPane.showConfirmDialog(this, Constant.messages.getString("report.write.diskspace.warning.dialog.message"), Constant.messages.getString("report.write.diskspace.warning.dialog.title"), JOptionPane.YES_NO_OPTION); if (result != JOptionPane.YES_OPTION) { return; } } if (!Files.isWritable(selectedFile.getParentFile().toPath())) { warnNotWritable("report.write.permission.dir.dialog.message", selectedFile.getParentFile().getAbsolutePath()); return; } if (fileExists) { if (!Files.isWritable(selectedFile.toPath())) { warnNotWritable("report.write.permission.file.dialog.message", selectedFile.getAbsolutePath()); return; } int result = JOptionPane.showConfirmDialog(this, Constant.messages.getString("report.write.overwrite.dialog.message"), Constant.messages.getString("report.write.overwrite.dialog.title"), JOptionPane.YES_NO_OPTION); switch (result) { case JOptionPane.YES_OPTION: super.approveSelection(); return; case JOptionPane.NO_OPTION: case JOptionPane.CLOSED_OPTION: return; } } Model.getSingleton().getOptionsParam().setUserDirectory(getCurrentDirectory()); super.approveSelection(); }
Source:
<code>public ItemStack getStackInSlot(int slot) { <START> ItemStack[] stacks = this.stacks; <END> validateSlotIndex(slot, stacks); return stacks[slot]; }</code><technical_language>minor, a bit redundant</technical_language>

Target:
public ItemStack getStackInSlot(int slot) { validateSlotIndex(slot); return this.stacks[slot]; }
Source:
<code><START> public void testRegistrySystemProperty() throws Exception { <END> System.setProperty("registry.username","roland"); System.setProperty("registry.password", "secret"); System.setProperty("registry.email", "roland@jolokia.org"); try { AuthConfig config = factory.createAuthConfig(true, false, null, settings, null, null); verifyAuthConfig(config,"roland","secret","roland@jolokia.org"); } finally { System.clearProperty("registry.username"); System.clearProperty("registry.password"); System.clearProperty("registry.email"); } }</code><technical_language>please avoid copy & pasting test ? extract a common method is called "docker" "registry" individual test. Helpful a test ensures "docker" precedence "registry" default behaviour</technical_language>

Target:
public void testRegistrySystemProperty() throws Exception { testSystemProperty("registry"); }
Source:
<code>public void writeStuffToFile(Path path) throws IOException { try { <START> writer = new FileWriter(new File(path.toString())); <END> Random random = new Random(); for (int i = 0; i < 20; i++) { writer.append(random.nextBoolean() + "\n"); } } catch (IOException ex) { fail("writer failed to init"); } writer.close(); }</code><technical_language>path.toFile() simpler</technical_language>

Target:
public void writeStuffToFile(Path path) throws IOException { try { writer = new FileWriter(path.toFile()); Random random = new Random(); for (int i = 0; i < 20; i++) { writer.append(random.nextBoolean() + "\n"); } } catch (IOException ex) { fail("writer failed to init"); } writer.close(); }
Source:
<code>private static final Collection<Operation> filterOperations(final Collection<Operation> operations, final boolean ignoreVoidOperations, final boolean ignoreOperationsWithParameters) { if <START> (!ignoreOperationsWithParameters && !ignoreOperationsWithParameters) { <END> return Collections.unmodifiableCollection(operations); } final Collection<Operation> filteredOperation = new HashSet<>(); for (Operation current : operations) { final Collection<Parameter> returnParameters = new ArrayList<>(); final Collection<Parameter> othersParameters = new ArrayList<>(); for (final Parameter p : current.getOwnedParameters()) { if (p.getDirection() == ParameterDirectionKind.RETURN_LITERAL) { returnParameters.add(p); } else { othersParameters.add(p); } } if (ignoreVoidOperations == !returnParameters.isEmpty()) { if (ignoreOperationsWithParameters == othersParameters.isEmpty()) { filteredOperation.add(current); } } } return filteredOperation; }</code><technical_language>Invalid condition. branches of condition evaluates result</technical_language>

Target:
private static final Collection<Operation> filterOperations(final Collection<Operation> operations, final boolean ignoreVoidOperations, final boolean ignoreOperationsWithParameters) { if (!ignoreOperationsWithParameters && !ignoreVoidOperations) { return Collections.unmodifiableCollection(operations); } final Collection<Operation> filteredOperation = new HashSet<>(); for (Operation current : operations) { final Collection<Parameter> returnParameters = new ArrayList<>(); final Collection<Parameter> othersParameters = new ArrayList<>(); for (final Parameter p : current.getOwnedParameters()) { if (p.getDirection() == ParameterDirectionKind.RETURN_LITERAL) { returnParameters.add(p); } else { othersParameters.add(p); } } if ((ignoreVoidOperations && !returnParameters.isEmpty()) && (ignoreOperationsWithParameters && othersParameters.isEmpty())) { filteredOperation.add(current); } } return filteredOperation; }
Source:
<code>public ChargeEntity updateChargeStatus(ChargeEntity chargeEntity, ChargeStatus chargeStatus) { chargeEntity.setStatus(chargeStatus); chargeEventDao.persistChargeEventOf(chargeEntity, Optional.empty()); <START> logger.info("{} for charge [charge_external_id={}]", chargeStatus, chargeEntity.getExternalId()); <END> return chargeEntity; }</code><technical_language>this line copied else I message improved, for Charge charge_external_id={} updated <old status> <new status></technical_language>

Target:
private ChargeEntity updateChargeStatus(ChargeEntity chargeEntity, ChargeStatus chargeStatus) { chargeEntity.setStatus(chargeStatus); chargeEventDao.persistChargeEventOf(chargeEntity, Optional.empty()); return chargeEntity; }
Source:
<code>private void startConnect(InetSocketAddress addr) throws IOException { saslLoginFailed = false; if (!isFirstConnect) { try { Thread.sleep(r.nextInt(1000)); } catch (InterruptedException e) { LOG.warn("Unexpected exception", e); } } if (!state.isAlive()) { throw new RuntimeException("Already closed"); } state = States.CONNECTING; String hostPort = addr.getHostString() + ":" + addr.getPort(); <START> MDC.put("myid", hostPort); <END> setName(getName().replaceAll("\\(.*\\)", "(" + hostPort + ")")); if (clientConfig.isSaslClientEnabled()) { try { if (zooKeeperSaslClient != null) { zooKeeperSaslClient.shutdown(); } zooKeeperSaslClient = new ZooKeeperSaslClient(SaslServerPrincipal.getServerPrincipal(addr, clientConfig), clientConfig); } catch (LoginException e) { LOG.warn( "SASL configuration failed. " + "Will continue connection to Zookeeper server without " + "SASL authentication, if Zookeeper server allows it.", e); eventThread.queueEvent(new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.AuthFailed, null)); saslLoginFailed = true; } } logStartConnect(addr); clientCnxnSocket.connect(addr); }</code><technical_language>said, this issue network is broken, IOException is better? e.g. throw new IOException("Socket closed reconnecting "+ addr);</technical_language>

Target:
private void startConnect(InetSocketAddress addr) throws IOException { saslLoginFailed = false; if (!isFirstConnect) { try { Thread.sleep(r.nextInt(1000)); } catch (InterruptedException e) { LOG.warn("Unexpected exception", e); } } changeZkState(States.CONNECTING); String hostPort = addr.getHostString() + ":" + addr.getPort(); MDC.put("myid", hostPort); setName(getName().replaceAll("\\(.*\\)", "(" + hostPort + ")")); if (clientConfig.isSaslClientEnabled()) { try { if (zooKeeperSaslClient != null) { zooKeeperSaslClient.shutdown(); } zooKeeperSaslClient = new ZooKeeperSaslClient(SaslServerPrincipal.getServerPrincipal(addr, clientConfig), clientConfig); } catch (LoginException e) { LOG.warn( "SASL configuration failed. " + "Will continue connection to Zookeeper server without " + "SASL authentication, if Zookeeper server allows it.", e); eventThread.queueEvent(new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.AuthFailed, null)); saslLoginFailed = true; } } logStartConnect(addr); clientCnxnSocket.connect(addr); }
Source:
<code>private synchronized Future closeSession(State finalState) { <START> if (isClosed.compareAndSet(false, true)) <END> { state(finalState); List<Future> futures = new ArrayList<>(); if (finalState == State.FAILED) futures.add(ScheduledExecutors.nonPeriodicTasks.submit(this::abortTasks)); logger.debug("[Stream #{}] Will close attached inbound channels {}", planId(), incomingChannels); incomingChannels.values().forEach(channel -> futures.add(channel.close())); messageSender.close(); streamResult.handleSessionComplete(this); closeFuture = FBUtilities.allOf(futures); } return closeFuture != null ? closeFuture : Futures.immediateFuture(null); }</code><technical_language>isClosed is in closeSession method is synchronized. consequence, is real need AtomicBoolean a boolean variable enough</technical_language>

Target:
private synchronized Future closeSession(State finalState) { if (closeFuture != null) return closeFuture; state(finalState); List<Future> futures = new ArrayList<>(); if (finalState == State.FAILED) futures.add(ScheduledExecutors.nonPeriodicTasks.submit(this::abortTasks)); if (!isFollower || state != State.COMPLETE) { logger.debug("[Stream #{}] Will close attached channels {}", planId(), channels); channels.values().forEach(channel -> futures.add(channel.close())); } sink.onClose(peer); streamResult.handleSessionComplete(this); closeFuture = FBUtilities.allOf(futures); return closeFuture; }
Source:
<code>private static Druids.ScanQueryBuilder basicD(final BenchmarkSchemaInfo basicSchema) { final QuerySegmentSpec intervalSpec = new MultipleIntervalSegmentSpec( Collections.singletonList(basicSchema.getDataInterval()) ); <START> final List<String> dimUniformFilterVals = new ArrayList<>(); <END> final int resultNum = (int) (100000 * 0.1); final int step = 100000 / resultNum; for (int i = 1; i < 100001 && dimUniformFilterVals.size() < resultNum; i += step) { dimUniformFilterVals.add(String.valueOf(i)); } final String dimName = "dimUniform"; return Druids.newScanQueryBuilder() .filters(new BoundDimFilter(dimName, "100", "10000", true, true, true, null, null)) .intervals(intervalSpec); }</code><technical_language>dimUniformFilterVals is unused</technical_language>

Target:
private static Druids.ScanQueryBuilder basicD(final BenchmarkSchemaInfo basicSchema) { final QuerySegmentSpec intervalSpec = new MultipleIntervalSegmentSpec( Collections.singletonList(basicSchema.getDataInterval()) ); final String dimName = "dimUniform"; return Druids.newScanQueryBuilder() .filters(new BoundDimFilter(dimName, "100", "10000", true, true, true, null, null)) .intervals(intervalSpec); }
Source:
<code>public Optional<ResponseBody> convert(ResponseBody value) { <START> return Optional.ofNullable(value); <END> }</code><technical_language>change of get 204, this called, instead expect CoerceNullValuesCallAdapterFactory return Optional.empty()</technical_language>

Target:
public Optional<ResponseBody> convert(ResponseBody value) { return Optional.of(value); }
Source:
<code>public HostListCommand(final Subparser parser) { super(parser); parser.help("list hosts"); patternArg = parser.addArgument("pattern") .nargs("?") .setDefault("") .help("Pattern to filter hosts with"); quietArg = parser.addArgument("-q") .action(storeTrue()) .help("only print host names"); fullArg = parser.addArgument("-f") .action(storeTrue()) .help("Print full host names."); statusArg = parser.addArgument("--status") .nargs("?") <START> .help("Filter hosts by its status, i.e. \"UP\" or \"DOWN\"."); <END> labelsArg = parser.addArgument("-l", "--labels") .action(append()) .setDefault(new ArrayList<String>()) .nargs("+") .help("Only include hosts that match all of these labels. Labels need to be in the format " + "key=value."); }</code><technical_language>want check out built-in choices() method. E.g. .choices(Collections2.transform( Arrays.asList(HostStatus.Status.values()), new Function<HostStatus.Status, String>() { @Override public String apply(final HostStatus.Status input) { return input.toString(); } }).toArray(new String[0])); (it's icky in java 7, nicer in java 8)</technical_language>

Target:
public HostListCommand(final Subparser parser) { super(parser); Collection<String> statusChoices = Collections2.transform( Arrays.asList(HostStatus.Status.values()), new Function<HostStatus.Status, String>() { @Override public String apply(final HostStatus.Status input) { return input.toString(); } }); statusChoicesString = Joiner.on(", ").join(statusChoices); parser.help("list hosts"); patternArg = parser.addArgument("pattern") .nargs("?") .setDefault("") .help("Pattern to filter hosts with"); quietArg = parser.addArgument("-q") .action(storeTrue()) .help("only print host names"); fullArg = parser.addArgument("-f") .action(storeTrue()) .help("Print full host names."); statusArg = parser.addArgument("--status") .nargs("?") .choices(statusChoices.toArray(new String[statusChoices.size()])) .help("Filter hosts by its status. Valid statuses are: " + statusChoicesString); labelsArg = parser.addArgument("-l", "--labels") .action(append()) .setDefault(new ArrayList<String>()) .nargs("+") .help("Only include hosts that match all of these labels. Labels need to be in the format " + "key=value."); }
Source:
<code>public String getQuestionResultStatisticsCsv( List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, FeedbackSessionResultsBundle bundle) { if (responses.isEmpty()) { return ""; } Map<String, Integer> answerFrequency = new LinkedHashMap<String, Integer>(); int numChoicesSelected = getNumberOfResponses(responses, answerFrequency); if (numChoicesSelected == -1) { return ""; } DecimalFormat df = new DecimalFormat("#.##"); StringBuilder fragments = new StringBuilder(); for (Entry<String, Integer> entry : answerFrequency.entrySet()) { fragments.append(SanitizationHelper.sanitizeForCsv(entry.getKey()) + ',' + entry.getValue().toString() + ',' <START> + df.format(100 * divideOrReturnZero((double) entry.getValue(), numChoicesSelected)) <END> + Const.EOL); } return "Choice, Response Count, Percentage" + Const.EOL + fragments + Const.EOL; }</code><technical_language>Need remove casting for this too</technical_language>

Target:
public String getQuestionResultStatisticsCsv( List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, FeedbackSessionResultsBundle bundle) { if (responses.isEmpty()) { return ""; } Map<String, Integer> answerFrequency = new LinkedHashMap<String, Integer>(); int numChoicesSelected = getNumberOfResponses(responses, answerFrequency); if (numChoicesSelected == -1) { return ""; } DecimalFormat df = new DecimalFormat("#.##"); StringBuilder fragments = new StringBuilder(); for (Entry<String, Integer> entry : answerFrequency.entrySet()) { fragments.append(SanitizationHelper.sanitizeForCsv(entry.getKey()) + ',' + entry.getValue().toString() + ',' + df.format(100 * divideOrReturnZero(entry.getValue(), numChoicesSelected)) + Const.EOL); } return "Choice, Response Count, Percentage" + Const.EOL + fragments + Const.EOL; }
Source:
<code><START> public synchronized static DbFacade getDbFacade() { <END> if (dbFacade != null) { return dbFacade; } loadDbFacadeConfig(); DbEngineDialect dialect = loadDbEngineDialect(); long timeStarted = System.currentTimeMillis(); DataSource datasource = null; for (;;) { datasource = EjbUtils.findResource(ContainerManagedResourceType.DATA_SOURCE); if (datasource != null) { break; } long timeNow = System.currentTimeMillis(); long timeWaited = timeNow - timeStarted; if (timeWaited > connectionTimeout) { log.errorFormat( "The data source can't be located after wating for more " + "than {0} seconds, giving up.", connectionTimeout / 1000 ); return null; } log.warnFormat( "The data source can't be located after waiting for {0} " + "seconds, will try again.", timeWaited / 1000 ); try { Thread.sleep(checkInterval); } catch (InterruptedException exception) { log.warnFormat( "Interrupted while waiting for data source.", exception ); } } dbFacade = new DbFacade(); dbFacade.setOnStartConnectionTimeout(connectionTimeout); dbFacade.setConnectionCheckInterval(checkInterval); dbFacade.setDbEngineDialect(dialect); JdbcTemplate jdbcTemplate = dialect.createJdbcTemplate(datasource); SQLErrorCodeSQLExceptionTranslator tr = new CustomSQLErrorCodeSQLExceptionTranslator(datasource); jdbcTemplate.setExceptionTranslator(tr); dbFacade.setTemplate(jdbcTemplate); return dbFacade; }</code><technical_language>This method synchronized. means expensive locking (performance decrease) is involved time entering it, dbFacade initialization. do double locking method improve this situation. (with volatile)</technical_language>

Target:
public static DbFacade getDbFacade() { if (dbFacade == null) { synchronized(DbFacadeLocator.class) { if (dbFacade == null) { dbFacade = createDbFacade(); } } } return dbFacade; }