auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } VID other = (VID) obj; if (annotationId != other.annotationId) { return false; } if (attribute != other.attribute) { return false; } if (extensionId == null) { if (other.extensionId != null) { return false; } } else if (!extensionId.equals(other.extensionId)) { return false; } <START> return slot == other.slot && subAnnotationId == other.subAnnotationId; <END> }</code><technical_language>previous code more verbose easier read</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } VID other = (VID) obj; if (annotationId != other.annotationId) { return false; } if (attribute != other.attribute) { return false; } if (extensionId == null) { if (other.extensionId != null) { return false; } } else if (!extensionId.equals(other.extensionId)) { return false; } if (slot != other.slot) { return false; } if (subAnnotationId != other.subAnnotationId) { return false; } return true; }
Source:
<code>private TwitterUserDetails getUserDetails(Twitter twitter, UserRef userRef) throws TwitterException { TwitterUserDetails userDetails = new TwitterUserDetails(userRef); long userIds[] = new long[1]; <START> userIds[0] = Long.valueOf(userRef.getUserId()); <END> ResponseList<twitter4j.User> lookupResult = twitter.lookupUsers(userIds); if (!lookupResult.isEmpty()) { twitter4j.User twUser = lookupResult.get(0); String homepageUrl = twUser.getURLEntity().getExpandedURL(); if (homepageUrl == null) { homepageUrl = twUser.getURLEntity().getURL(); } userDetails.withProfileImage(twUser.getProfileImageURLHttps()); userDetails.withHomepageUrl(homepageUrl); userDetails.withScreenName(twUser.getScreenName()); userDetails.withFullName(twUser.getName()); } return userDetails; }</code><technical_language>this lines of long userIds[] = new long[]{ Long.valueOf(userRef.getUserId()) };</technical_language>

Target:
private TwitterUserDetails getUserDetails(Twitter twitter, UserRef userRef) throws TwitterException { TwitterUserDetails userDetails = new TwitterUserDetails(userRef); long userIds[] = new long[]{ Long.valueOf(userRef.getUserId()) }; ResponseList<twitter4j.User> lookupResult = twitter.lookupUsers(userIds); if (!lookupResult.isEmpty()) { twitter4j.User twUser = lookupResult.get(0); String homepageUrl = twUser.getURLEntity().getExpandedURL(); if (homepageUrl == null) { homepageUrl = twUser.getURLEntity().getURL(); } userDetails.withProfileImage(twUser.getProfileImageURLHttps()); userDetails.withHomepageUrl(homepageUrl); userDetails.withScreenName(twUser.getScreenName()); userDetails.withFullName(twUser.getName()); } return userDetails; }
Source:
<code>public void normalizesInputSlashesToHyphens() { Param<LocalDate> localDate = Param.localDate("start", "export_start_date", "Export start date"); <START> assertThat(localDate.map("2018/01/20").isEqual(LocalDate.of(2018, 01,20)), is(true)); <END> }</code><technical_language>Change this assertion too</technical_language>

Target:
public void normalizesInputSlashesToHyphens() { Param<LocalDate> localDate = Param.localDate("start", "export_start_date", "Export start date"); assertThat(localDate.map("2018/01/20"), is(LocalDate.of(2018, 1, 20))); }
Source:
<code>public void onResume() { super.onResume(); final Uri uri = getIntent().getData(); if (uri != null) { final String verifier = uri.getQueryParameter("oauth_verifier"); if (!verifier.equals(lastVerifier)) { if (StringUtils.isNotBlank(verifier)) { exchangeTokens(verifier); } else { changeTokensHandler.sendEmptyMessage(NOT_AUTHENTICATED); } } <START> lastVerifier = verifier; <END> } }</code><technical_language>move this line if block</technical_language>

Target:
public void onResume() { super.onResume(); final Uri uri = getIntent().getData(); if (uri == null) { return; } final String verifier = uri.getQueryParameter("oauth_verifier"); if (StringUtils.isBlank(verifier)) { changeTokensHandler.sendEmptyMessage(NOT_AUTHENTICATED); return; } if (verifier.equals(lastVerifier)) { return; } lastVerifier = verifier; exchangeTokens(verifier); }
Source:
<code>public NettyServer start() { ServerBootstrap b = new ServerBootstrap(); if (secure) { b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) <START> .childHandler(new SeleniumHttpsInitializer(handler, sslCtx)); <END> } else { b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new SeleniumHttpInitializer(handler)); } try { channel = b.bind(port).sync().channel(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new UncheckedIOException(new IOException("Start up interrupted", e)); } return this; }</code><technical_language>modify existing SeleniumHttpInitializer accept a null sslCtx add SSL handler if is null</technical_language>

Target:
public NettyServer start() { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new SeleniumHttpInitializer(handler, sslCtx)); try { channel = b.bind(port).sync().channel(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new UncheckedIOException(new IOException("Start up interrupted", e)); } return this; }
Source:
<code>private void loadViewConfig(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ShrinkingLinearLayout); shrinkingViewId = typedArray.getResourceId(R.styleable.ShrinkingLinearLayout_shrinkable_view, -1); <START> } <END></code><technical_language>Linter wants include typedArray.recycle(); end of this method</technical_language>

Target:
private void loadViewConfig(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ShrinkingLinearLayout); shrinkingViewId = typedArray.getResourceId(R.styleable.ShrinkingLinearLayout_shrinkable_view, -1); typedArray.recycle(); }
Source:
<code>public void setInput(EObject eObject) { <START> Object selfValue = variableManager.getVariables().get(EEFExpressionUtils.SELF); <END> if (eObject != selfValue) { variableManager.clear(); variableManager.put(EEFExpressionUtils.SELF, eObject); for (EEFPage eefPage : eefPages) { String pageSemanticCandidateExpression = eefPage.getDescription().getSemanticCandidateExpression(); if (!isBlank(pageSemanticCandidateExpression)) { IEvaluationResult evaluationResult = interpreter.evaluateExpression(variableManager.getVariables(), pageSemanticCandidateExpression); if (Diagnostic.OK == evaluationResult.getDiagnostic().getSeverity() && evaluationResult.getValue() != null) { eefPage.getVariableManager().put(EEFExpressionUtils.SELF, evaluationResult.getValue()); } else { } } List<EEFGroup> groups = eefPage.getGroups(); for (EEFGroup eefGroup : groups) { String groupSemanticCandidateExpression = eefGroup.getDescription().getSemanticCandidateExpression(); if (!isBlank(groupSemanticCandidateExpression)) { IEvaluationResult evaluationResult = interpreter.evaluateExpression(eefPage.getVariableManager().getVariables(), groupSemanticCandidateExpression); if (Diagnostic.OK == evaluationResult.getDiagnostic().getSeverity() && evaluationResult.getValue() != null) { eefGroup.getVariableManager().put(EEFExpressionUtils.SELF, evaluationResult.getValue()); } else { } } } } } }</code><technical_language>removing "this."? I point</technical_language>

Target:
public void setInput(EObject eObject) { Object selfValue = this.variableManager.getVariables().get(EEFExpressionUtils.SELF); if (eObject != selfValue) { this.variableManager.clear(); this.variableManager.put(EEFExpressionUtils.SELF, eObject); for (EEFPage eefPage : this.eefPages) { String pageSemanticCandidateExpression = eefPage.getDescription().getSemanticCandidateExpression(); if (!isBlank(pageSemanticCandidateExpression)) { IEvaluationResult evaluationResult = this.interpreter.evaluateExpression(this.variableManager.getVariables(), pageSemanticCandidateExpression); if (Diagnostic.OK == evaluationResult.getDiagnostic().getSeverity() && evaluationResult.getValue() != null) { eefPage.getVariableManager().put(EEFExpressionUtils.SELF, evaluationResult.getValue()); } else { } } List<EEFGroup> groups = eefPage.getGroups(); for (EEFGroup eefGroup : groups) { String groupSemanticCandidateExpression = eefGroup.getDescription().getSemanticCandidateExpression(); if (!isBlank(groupSemanticCandidateExpression)) { IEvaluationResult evaluationResult = this.interpreter.evaluateExpression(eefPage.getVariableManager().getVariables(), groupSemanticCandidateExpression); if (Diagnostic.OK == evaluationResult.getDiagnostic().getSeverity() && evaluationResult.getValue() != null) { eefGroup.getVariableManager().put(EEFExpressionUtils.SELF, evaluationResult.getValue()); } else { } } } } } }
Source:
<code>public List<OSThread> getThreadDetails() { <START> return this.threadDetails; <END> }</code><technical_language>Wrap this in a Collections.unmodifiableList()</technical_language>

Target:
public List<OSThread> getThreadDetails() { List<OSThread> threadDetails = ProcessStat.getThreadIds(getProcessID()).stream() .map(id -> new LinuxOSThread(getProcessID(), id)).collect(Collectors.toList()); return Collections.unmodifiableList(threadDetails); }
Source:
<code>private boolean stopTransferIfNecessary(ImageTransfer entity, long ts) { if (transferImageInactivityTimeoutInSeconds > 0 && (entity.getPhase() == ImageTransferPhase.INITIALIZING || entity.getPhase() == ImageTransferPhase.TRANSFERRING) && (entity.getLastUpdated().getTime() / 1000) + transferImageInactivityTimeoutInSeconds < ts) { <START> ImageTransferPhase phase = ImageTransferPhase.PAUSED_SYSTEM; if (getParameters().getTransferType() == TransferType.Download) { phase = ImageTransferPhase.CANCELLED; } <END> log.warn("Transfer phase was changed to due to no updates in seconds. {}", phase.toString(), ts - (entity.getLastUpdated().getTime() / 1000), getTransferDescription()); updateEntityPhase(phase); return true; } return false; }</code><technical_language>consider - ImageTransferPhase phase = getParameters().getTransferType() == TransferType.Download ? ImageTransferPhase.CANCELLED : ImageTransferPhase.PAUSED_SYSTEM</technical_language>

Target:
private boolean stopTransferIfNecessary(ImageTransfer entity, long ts) { if (getTransferImageClientInactivityTimeoutInSeconds() > 0 && (entity.getPhase() == ImageTransferPhase.INITIALIZING || entity.getPhase() == ImageTransferPhase.TRANSFERRING) && (entity.getLastUpdated().getTime() / 1000) + getTransferImageClientInactivityTimeoutInSeconds() < ts) { ImageTransferPhase phase = ImageTransferPhase.PAUSED_SYSTEM; if (getParameters().getTransferType() == TransferType.Download) { phase = ImageTransferPhase.CANCELLED; } log.warn("Transfer phase was changed to due to no updates in seconds. {}", phase.toString(), ts - (entity.getLastUpdated().getTime() / 1000), getTransferDescription()); updateEntityPhase(phase); return true; } return false; }
Source:
<code>private String canonicalizeAmzHeaders( final Multimap<String, String> customHeaders) { String ret = ""; for (final Map.Entry<String, Collection<String>> header : customHeaders .asMap().entrySet()) { <START> final String key = header.getKey().toLowerCase(); <END> if (key.startsWith(PutObjectRequest.AMZ_META_HEADER) && header.getValue().size() > 0) { ret += key + ":"; ret += Joiner.on(",").join(header.getValue()); ret += '\n'; } } System.out.println(ret); return ret; }</code><technical_language>forcing metadata key names lowercase? spec is restriction</technical_language>

Target:
private String canonicalizeAmzHeaders( final Multimap<String, String> customHeaders) { StringBuilder ret = new StringBuilder(); for (final Map.Entry<String, Collection<String>> header : customHeaders .asMap().entrySet()) { final String key = header.getKey().toLowerCase(); if (key.startsWith(PutObjectRequest.AMZ_META_HEADER) && header.getValue().size() > 0) { ret.append(key).append(":"); ret.append(Joiner.on(",").join(header.getValue())); ret.append('\n'); } } return ret.toString(); }
Source:
<code>public Builder() { <START> this(15 * 60 * 1000L, 524288000L, 100, 5, 15, 10, 1, false, null, -1); <END> }</code><technical_language>DEFAULT_LOADING_THROTTLE_LIMIT</technical_language>

Target:
public Builder() { this(15 * 60 * 1000L, 524288000L, 100, 5, 15, 10, 1, false, null, DEFAULT_LOADING_THROTTLE_LIMIT); }
Source:
<code><START> public FormValidation doCheckUnstableReturn(@QueryParameter String value) { <END> value = Util.fixEmptyAndTrim(value); if (value == null) { return FormValidation.ok(); } long unstableReturn; try { unstableReturn = Long.parseLong(value); } catch (NumberFormatException e) { return FormValidation.error(hudson.model.Messages.Hudson_NotANumber()); } if (unstableReturn < Integer.MIN_VALUE || unstableReturn > Integer.MAX_VALUE) { return FormValidation.error(hudson.tasks.Messages.BatchFile_invalid_exit_code_range(unstableReturn)); } return FormValidation.ok(); }</code><technical_language>@Restricted(DoNotUse.class) a bad idea</technical_language>

Target:
public FormValidation doCheckUnstableReturn(@QueryParameter String value) { value = Util.fixEmptyAndTrim(value); if (value == null) { return FormValidation.ok(); } long unstableReturn; try { unstableReturn = Long.parseLong(value); } catch (NumberFormatException e) { return FormValidation.error(hudson.model.Messages.Hudson_NotANumber()); } if (unstableReturn == 0) { return FormValidation.warning(hudson.tasks.Messages.BatchFile_invalid_exit_code_zero()); } if (unstableReturn < Integer.MIN_VALUE || unstableReturn > Integer.MAX_VALUE) { return FormValidation.error(hudson.tasks.Messages.BatchFile_invalid_exit_code_range(unstableReturn)); } return FormValidation.ok(); }
Source:
<code>public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 2) { <START> throw new RuntimeException("function 'nvl' needs 2 argument"); <END> } ExprEval eval = args.get(0).eval(bindings); if (eval.value() == null || (eval.type() == ExprType.STRING && Strings.isNullOrEmpty(eval.stringValue()))) { return args.get(1).eval(bindings); } return eval; }</code><technical_language>IllegalArgumentException for consistency, needs 2 _arguments_</technical_language>

Target:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 2) { throw new IAE("function 'nvl' needs 2 arguments"); } final ExprEval eval = args.get(0).eval(bindings); return eval.isNull() ? args.get(1).eval(bindings) : eval; }
Source:
<code>public Instant softDeleteCourse(String courseId) <START> throws InvalidParametersException, EntityDoesNotExistException { <END> CourseAttributes course = getCourse(courseId); course.setDeletedAt(); updateCourse(course); return course.deletedAt; }</code><technical_language>right, soft deletion result in InvalidParametersException</technical_language>

Target:
public Instant softDeleteCourse(String courseId) throws EntityDoesNotExistException { Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseId); Course courseEntity = getCourseEntity(courseId); if (courseEntity == null) { throw new EntityDoesNotExistException(ERROR_UPDATE_NON_EXISTENT_COURSE); } courseEntity.setDeletedAt(Instant.now()); saveEntity(courseEntity); return courseEntity.getDeletedAt(); }
Source:
<code>public String toText() { <START> return "{@" + type.keyword + this.content; <END> }</code><technical_language>a closing brace here</technical_language>

Target:
public String toText() { return "@" + tagName + this.content; }
Source:
<code>private boolean checkCanPerformPlugUnPlugDisk() { if (getVm().getStatus().isUpOrPaused()) { setVdsId(getVm().getRunOnVds()); if (!isHotPlugSupported() || !isOsSupportingHotPlug() || !isInterfaceSupportedForPlugUnPlug(disk)) { return false; } } oldVmDevice = getVmDeviceDao().get(new VmDeviceId(disk.getId(), getVmId())); if (getPlugAction() == VDSCommandType.HotPlugDisk && oldVmDevice.getIsPlugged()) { <START> return failCanDoAction(VdcBllMessages.HOT_PLUG_DISK_IS_NOT_UNPLUGGED); <END> } if (getPlugAction() == VDSCommandType.HotUnPlugDisk && !oldVmDevice.getIsPlugged()) { return failCanDoAction(VdcBllMessages.HOT_UNPLUG_DISK_IS_NOT_PLUGGED); } return true; }</code><technical_language>formatter</technical_language>

Target:
private boolean checkCanPerformPlugUnPlugDisk() { if (getVm().getStatus().isUpOrPaused()) { setVdsId(getVm().getRunOnVds()); if (!canPerformHotPlug() || !isInterfaceSupportedForPlugUnPlug(disk)) { return false; } } oldVmDevice = getVmDeviceDao().get(new VmDeviceId(disk.getId(), getVmId())); if (getPlugAction() == VDSCommandType.HotPlugDisk && oldVmDevice.getIsPlugged()) { return failCanDoAction(VdcBllMessages.HOT_PLUG_DISK_IS_NOT_UNPLUGGED); } if (getPlugAction() == VDSCommandType.HotUnPlugDisk && !oldVmDevice.getIsPlugged()) { return failCanDoAction(VdcBllMessages.HOT_UNPLUG_DISK_IS_NOT_PLUGGED); } return true; }
Source:
<code>public void knows_how_to_clone_an_instance() { ExportConfiguration clonedConfig = validConfig.clone(); <START> assertThat(clonedConfig == validConfig, is(false)); <END> assertThat(clonedConfig, is(validConfig)); assertThat(clonedConfig.getExportDir(), is(validConfig.getExportDir())); assertThat(clonedConfig.getPemFile(), is(validConfig.getPemFile())); assertThat(clonedConfig.getStartDate(), is(validConfig.getStartDate())); assertThat(clonedConfig.getEndDate(), is(validConfig.getEndDate())); }</code><technical_language>I suppose differently. I simplicity brevity, e.g., assertSame(a, b) assertThat(a, is(sameReferenceAs(b)) of eye scanning line, tokens (6 vs. 11), understanding it. 16 characters vs. 36</technical_language>

Target:
public void knows_how_to_clone_an_instance() { ExportConfiguration clonedConfig = validConfig.copy(); assertThat(clonedConfig == validConfig, is(false)); assertThat(clonedConfig, is(validConfig)); assertThat(clonedConfig.getExportDir(), is(validConfig.getExportDir())); assertThat(clonedConfig.getPemFile(), is(validConfig.getPemFile())); assertThat(clonedConfig.getStartDate(), is(validConfig.getStartDate())); assertThat(clonedConfig.getEndDate(), is(validConfig.getEndDate())); }
Source:
<code>public void setBufferLineLimit(int bufferLines) { int chars = bufferLines * CHARS_PER_LINE_AVG; <START> setWaterMarks(chars, chars); <END> }</code><technical_language>turns-out this is permitted. I get IllegalArgumentExcexception, high watermark higher low. I add a small high watermark buffer, then</technical_language>

Target:
public void setBufferLineLimit(int bufferLines) { int chars = bufferLines * CHARS_PER_LINE_AVG; setWaterMarks(chars, chars + HIGH_WATERMARK_OFFSET_BYTES); }
Source:
<code>public void clearThreadLocalCache() { String canonicalPath = cachedRealm.getPath(); localCount.set(null); globalCount--; if (globalCount < 0) { <START> throw new IllegalStateException("Global reference counter of Realm" + canonicalPath + " got corrupted."); <END> } }</code><technical_language>suggestion throw new IllegalStateException("Global reference counter of Realm" + canonicalPath + " negative.");</technical_language>

Target:
public void clearThreadLocalCache() { String canonicalPath = cachedRealm.getPath(); localCount.set(null); cachedRealm = null; if (globalCount.decrementAndGet() < 0) { throw new IllegalStateException("Global reference counter of Realm" + canonicalPath + " not be negative."); } }
Source:
<code>private void visitBlock(BlockTree block) { boolean hasLabel = currentLabel != null; if (hasLabel) { <START> addBreakable(null); <END> currentBlock = createSimpleBlock(currentBlock); } build(block.statements()); if (hasLabel) { breakables.removeFirst(); } }</code><technical_language>@pynicolas explain add breakable for block loops</technical_language>

Target:
private void visitBlock(BlockTree block) { boolean hasLabel = currentLabel != null; if (hasLabel) { addBreakable(null); currentBlock = createSimpleBlock(currentBlock); } build(block.statements()); if (hasLabel) { removeBreakable(); } }
Source:
<code>public void openFlowView_navigateToTsView_navigationSuccessful() { getDriver().get(getRootURL() + "/hello"); waitForDevServer(); Assert.assertThat(getDriver().getCurrentUrl(), CoreMatchers.endsWith("/hello")); $(NativeButtonElement.class).id(NAVIGATE_ABOUT).click(); waitUntil( <START> input -> getInShadowRoot(findElement(By.tagName("about-view")), <END> By.id("navigate-hello")).isDisplayed()); Assert.assertThat(getDriver().getCurrentUrl(), CoreMatchers.endsWith("/about")); Assert.assertTrue(getInShadowRoot(findElement(By.tagName("about-view")), By.id("navigate-hello")).isDisplayed()); }</code><technical_language>avoid getInShadowRoot usage. $("about-view").id("navigate-hello")</technical_language>

Target:
public void openFlowView_navigateToTsView_navigationSuccessful() { getDriver().get(getRootURL() + "/hello"); waitForDevServer(); Assert.assertThat(getDriver().getCurrentUrl(), CoreMatchers.endsWith("/hello")); $(NativeButtonElement.class).id(NAVIGATE_ABOUT).click(); waitUntil(input -> $("about-view").first().$("a").id("navigate-hello") .isDisplayed()); Assert.assertThat(getDriver().getCurrentUrl(), CoreMatchers.endsWith("/about")); Assert.assertTrue(getInShadowRoot(findElement(By.tagName("about-view")), By.id("navigate-hello")).isDisplayed()); }
Source:
<code>public void handleCommand(ChannelUID channelUID, Command command) { <START> <END> logger.debug("Received channel: {}, command: {}", channelUID, command); if (remoteName == null) { logger.error("Remote name is not set in {}", getThing().getUID()); return; } if (channelUID.getId().equals(CHANNEL_BUTTON)) { if (command instanceof RefreshType) { } else if (command instanceof StringType) { bridgeHandler.transmit(remoteName, command.toString()); } } }</code><technical_language>blank line</technical_language>

Target:
public void handleCommand(ChannelUID channelUID, Command command) { logger.debug("Received channel: {}, command: {}", channelUID, command); if (remoteName == null) { logger.error("Remote name is not set in {}", getThing().getUID()); return; } if (channelUID.getId().equals(LIRCBindingConstants.CHANNEL_TRANSMIT)) { if (command instanceof RefreshType) { } else if (command instanceof StringType) { bridgeHandler.transmit(remoteName, command.toString()); } } }
Source:
<code>public HadoopOutputFormatWrapper(org.apache.hadoop.mapred.OutputFormat<K,V> hadoopFormat, JobConf job, StratosphereTypeConverter<K,V> conv) { super(); this.hadoopOutputFormat = hadoopFormat; this.hadoopOutputFormatName = hadoopFormat.getClass().getName(); this.converter = conv; <START> org.apache.hadoop.conf.Configuration hadoopConf = DistributedFileSystem.getHadoopConfiguration(); <END> for (Map.Entry<String, String> e : hadoopConf) { job.set(e.getKey(), e.getValue()); } this.fileOutputCommitterWrapper = new FileOutputCommitterWrapper(); this.jobConf = job; }</code><technical_language>I this code is copy-pasted HadoopInputFormatWrapper. move method Wrappers</technical_language>

Target:
public HadoopOutputFormatWrapper(org.apache.hadoop.mapred.OutputFormat<K,V> hadoopFormat, JobConf job, StratosphereTypeConverter<K,V> conv) { super(); this.hadoopOutputFormat = hadoopFormat; this.hadoopOutputFormatName = hadoopFormat.getClass().getName(); this.converter = conv; this.fileOutputCommitterWrapper = new FileOutputCommitterWrapper(); HadoopConfiguration.mergeHadoopConf(job); this.jobConf = job; }
Source:
<code>private Runnable createProxyThreadRunnable() { return () -> { isRunning = true; try { consumerPollThreadStartLatch.countDown(); LOG.info("Starting consumer poll thread for system {}", consumerPollThread.getName(), systemName); initializeLags(); while (isRunning) { fetchMessages(); } } catch (Throwable throwable) { LOG.error(String.format("Error in KafkaConsumerProxy poll thread for system: %s.", systemName), throwable); failureCause = throwable; isRunning = false; <START> ((KafkaSystemConsumer) this.kafkaConsumer).setProxyFailureCause(this.failureCause); <END> } if (!isRunning) { LOG.info("KafkaConsumerProxy for system has stopped.", systemName); } }; }</code><technical_language>set isRunning = false</technical_language>

Target:
private Runnable createProxyThreadRunnable() { return () -> { isRunning = true; try { consumerPollThreadStartLatch.countDown(); LOG.info("Starting consumer poll thread for system {}", consumerPollThread.getName(), systemName); initializeLags(); while (isRunning) { fetchMessages(); } } catch (Throwable throwable) { LOG.error(String.format("Error in KafkaConsumerProxy poll thread for system: %s.", systemName), throwable); failureCause = throwable; isRunning = false; kafkaSystemConsumer.setFailureCause(this.failureCause); } if (!isRunning) { LOG.info("KafkaConsumerProxy for system has stopped.", systemName); } }; }
Source:
<code>public boolean start() throws IOException { MarkLogicConnection connection = (MarkLogicConnection) getCurrentSource(); result = new Result(); connectionClient = connection.connect(container); if (connectionClient == null) { return false; } docManager = connectionClient.newDocumentManager(); boolean isDocContentFieldPresent = (settings.outputSchema.getFields().size() >= 2); if (isDocContentFieldPresent) { docContentField = settings.outputSchema.getFields().get(1); } docContentReader = new DocContentReader(docManager, settings.outputSchema, docContentField); if (settings.useQueryOption && StringUtils.isNotEmpty(settings.queryOptionName)) { prepareQueryOption(); } queryManager = connectionClient.newQueryManager(); stringQueryDefinition = (settings.useQueryOption) ? queryManager.newStringDefinition(settings.queryOptionName) : queryManager.newStringDefinition(); stringQueryDefinition.setCriteria(settings.criteria); <START> searchHandle = queryManager.search(stringQueryDefinition, new SearchHandle()); <END> matchedDocuments = searchHandle.getTotalResults(); pageSize = (settings.pageSize <= 0) ? DEFAULT_PAGE_SIZE : settings.pageSize; maxRetrieve = settings.maxRetrieve; queryManager.setPageLength(pageSize); documentCounter = 1; readNextPage(); return (matchedDocuments > 0); }</code><technical_language>Please recheck this change break runtime</technical_language>

Target:
public boolean start() throws IOException { MarkLogicConnection connection = (MarkLogicConnection) getCurrentSource(); result = new ResultWithLongNB(); connectionClient = connection.connect(container); if (connectionClient == null) { return false; } docManager = connectionClient.newDocumentManager(); boolean isDocContentFieldPresent = (settings.outputSchema.getFields().size() >= 2); if (isDocContentFieldPresent) { docContentField = settings.outputSchema.getFields().get(1); } docContentReader = new DocContentReader(docManager, settings.outputSchema, docContentField); if (settings.useQueryOption && StringUtils.isNotEmpty(settings.queryOptionName)) { prepareQueryOption(); } queryManager = connectionClient.newQueryManager(); stringQueryDefinition = (settings.useQueryOption) ? queryManager.newStringDefinition(settings.queryOptionName) : queryManager.newStringDefinition(); stringQueryDefinition.setCriteria(settings.criteria); searchHandle = queryManager.search(stringQueryDefinition, new SearchHandle()); matchedDocuments = searchHandle.getTotalResults(); pageSize = (settings.pageSize <= 0) ? matchedDocuments : settings.pageSize; maxRetrieve = settings.maxRetrieve; queryManager.setPageLength(pageSize); documentCounter = 1; readNextPage(); return (matchedDocuments > 0); }
Source:
<code>public void executeConstantAction( Activation activation ) throws StandardException { LanguageConnectionContext lcc = activation.getLanguageConnectionContext(); TransactionController tc = lcc.getTransactionExecute(); Manager manager = EngineDriver.driver().manager(); <START> if (privileges instanceof TablePrivilegeInfo) { <END> TablePrivilegeInfo info = (TablePrivilegeInfo) privileges; if (!manager.isEnabled() && info.hasColumns()) { throw StandardException.newException(SQLState.COLS_PERMS_EXCEPTION); } } List <PermissionsDescriptor> permissionsDescriptors = privileges.executeGrantRevoke( activation, grant, grantees); for (PermissionsDescriptor permissionsDescriptor : permissionsDescriptors) { DDLMessage.DDLChange ddlChange = createDDLChange(((SpliceTransactionManager) tc).getActiveStateTxn().getTxnId(), permissionsDescriptor); tc.prepareDataDictionaryChange(DDLUtils.notifyMetadataChange(ddlChange)); } }</code><technical_language>Try get ColPermsManager Manager. If enterprise code is enabled, exception thrown, need add another exception</technical_language>

Target:
public void executeConstantAction( Activation activation ) throws StandardException { LanguageConnectionContext lcc = activation.getLanguageConnectionContext(); TransactionController tc = lcc.getTransactionExecute(); Manager manager = EngineDriver.driver().manager(); if (privileges instanceof TablePrivilegeInfo) { TablePrivilegeInfo info = (TablePrivilegeInfo) privileges; if (!manager.isEnabled() && info.hasColumns()) { throw StandardException.newException(SQLState.MANAGER_DISABLED); } } List <PermissionsDescriptor> permissionsDescriptors = privileges.executeGrantRevoke( activation, grant, grantees); for (PermissionsDescriptor permissionsDescriptor : permissionsDescriptors) { DDLMessage.DDLChange ddlChange = createDDLChange(((SpliceTransactionManager) tc).getActiveStateTxn().getTxnId(), permissionsDescriptor); tc.prepareDataDictionaryChange(DDLUtils.notifyMetadataChange(ddlChange)); } }
Source:
<code>private static DiskVmElement buildDiskVmElementWithDiskInterfaceFromExternalProvider(Map<String, Object> map, DiskImage image, Guid vmId) { DiskVmElement dve = new DiskVmElement(image.getId(), vmId); String diskDevName = (String) map.get(VdsProperties.DISK_TARGET_DEV_NAME); diskDevName = (diskDevName == null || diskDevName.length() < 3) ? "" : diskDevName.substring(0, 2); switch (diskDevName) { case "sd": dve.setDiskInterface(DiskInterface.VirtIO_SCSI); break; case "hd": dve.setDiskInterface(DiskInterface.IDE); break; case "vd": default: dve.setDiskInterface(DiskInterface.VirtIO); <START> break; <END> } return dve; }</code><technical_language>redundant</technical_language>

Target:
private static DiskVmElement buildDiskVmElementWithDiskInterfaceFromExternalProvider(Map<String, Object> map, DiskImage image, Guid vmId) { DiskVmElement dve = new DiskVmElement(image.getId(), vmId); String diskDevName = (String) map.get(VdsProperties.DISK_TARGET_DEV_NAME); diskDevName = (diskDevName == null || diskDevName.length() < 3) ? "" : diskDevName.substring(0, 2); switch (diskDevName) { case "sd": dve.setDiskInterface(DiskInterface.VirtIO_SCSI); break; case "hd": dve.setDiskInterface(DiskInterface.IDE); break; case "vd": default: dve.setDiskInterface(DiskInterface.VirtIO); } return dve; }
Source:
<code>public boolean isEditable() { BranchState state = getBranchState(); return !state.isCommitInProgress() && !state.isCommitted() && !state.isRebaselined() && !state.isDeleted() && !state.isCreationInProgress() && <START> !getArchiveState().isArchived() && !isPurged() && !isDeleteInProgress() && !isPurgeInProgress(); <END> }</code><technical_language>A here. For one, inconsistent in creating local boolean methods isDeleteInProgress. mix a local copy of BranchState locally created methods do thing. This consistent. Secondly, This adequately dealing branch states, I UNKNOWN REBASELINE_IN_PROGRESS result in editable. Finally, of is sort of moot in in reality I isEditable simply result of branch state CREATED MODIFIED, is a smaller set of tests, easier read maintain, positive negative assertions</technical_language>

Target:
public boolean isEditable() { BranchState state = getBranchState(); return (state.isCreated() || state.isModified() || state.isRebaselineInProgress()) && getArchiveState().isUnArchived(); }
Source:
<code>public void accept(E entry) { Cache<?, ?> cache = getForEachObject(cacheOffset); <START> if (cache != null && this.cache != null && cache.getName().equals(this.cache.getName())) { <END> ((AtomicInteger) getForEachObject(atomicOffset)).addAndGet(function.applyAsInt(entry)); } }</code><technical_language>throw exception if get right cache</technical_language>

Target:
public void accept(E entry) { Cache<?, ?> cache = getForEachObject(cacheOffset); if (cache != null && this.cache != null && cache.getName().equals(this.cache.getName())) { ((AtomicInteger) getForEachObject(atomicOffset)).addAndGet(function.applyAsInt(entry)); } else { fail("Did not receive correct cache!"); } }
Source:
<code>public void save(Patient patient, DocumentModelBridge doc) { <START> PatientData<Disorder> features = patient.getData(this.getName()); <END> if (features == null || !features.isIndexed()) { return; } if (doc == null) { throw new NullPointerException(ERROR_MESSAGE_NO_PATIENT_CLASS); } XWikiDocument docX = (XWikiDocument) doc; BaseObject data = docX.getXObject(Patient.CLASS_REFERENCE); XWikiContext context = this.xcontextProvider.get(); List<String> disorderValues = new LinkedList<>(); Iterator<Disorder> iterator = features.iterator(); while (iterator.hasNext()) { Disorder disorder = iterator.next(); disorderValues.add(disorder.getValue()); } data.set(DISORDER_PROPERTIES_OMIMID, null, context); data.set(DISORDER_PROPERTIES_OMIMID, disorderValues, context); }</code><technical_language>called disorders, features</technical_language>

Target:
public void save(Patient patient, DocumentModelBridge doc) { PatientData<Disorder> disorders = patient.getData(this.getName()); if (disorders == null || !disorders.isIndexed()) { return; } if (doc == null) { throw new NullPointerException(ERROR_MESSAGE_NO_PATIENT_CLASS); } XWikiDocument docX = (XWikiDocument) doc; BaseObject data = docX.getXObject(Patient.CLASS_REFERENCE); XWikiContext context = this.xcontextProvider.get(); List<String> disorderValues = new LinkedList<>(); Iterator<Disorder> iterator = disorders.iterator(); while (iterator.hasNext()) { Disorder disorder = iterator.next(); disorderValues.add(disorder.getValue()); } data.set(DISORDER_PROPERTIES_OMIMID, null, context); data.set(DISORDER_PROPERTIES_OMIMID, disorderValues, context); }
Source:
<code>public ExportUserActivityStream(String[] args){ this.connectionsUrl = args[0]; this.USERNAME = args[1]; this.PASSWORD = args[2]; this.USER_ID = args[3]; this.resultCount = args[4]; this.filePath = args[5]; this.serviceMap = args[6]; System.out.println("Initialising environment and authenticating with connections..."); this.initEnvironment(); <START> endpoint = (BasicEndpoint) EndpointFactory.getEndpoint(this.endpointName); <END> System.out.println("endpoint created"+endpoint.toString()); this.setBaseUrl(this.connectionsUrl); Map<String,String> map = new HashMap<String,String>(); map.put("connections", this.serviceMap); this.setServiceMaps(map); if (StringUtil.isNotEmpty(this.USERNAME)) { try { endpoint.login(this.USERNAME, this.PASSWORD); System.out.println("Login Successful"); } catch (AuthenticationException e) { System.out.println("Error authenticating with connections"); e.printStackTrace(); } } this.getUserActivityStream(); this.getProfileProperties(); System.out.println("Done"); }</code><technical_language>For stand-alone applications started creating endpoint factories deal managed-beans.xml etc. a pattern in this sample: SocialSDK\samples\java\sbt.sample.app\src\main\java\com\ibm\sbt\sample\app\ExportWiki.java. This is a simpler pattern use</technical_language>

Target:
public ExportUserActivityStream(String[] args){ this.connectionsUrl = args[0]; this.USERNAME = args[1]; this.PASSWORD = args[2]; this.USER_ID = args[3]; this.resultCount = args[4]; this.filePath = args[5]; this.serviceMap = args[6]; System.out.println("Initialising environment and authenticating with connections..."); this.initEnvironment(); endpoint = new BasicEndpoint(); endpoint.setUrl(this.connectionsUrl); endpoint.setForceTrustSSLCertificate(true); endpoint.setUser(this.USERNAME); endpoint.setPassword(this.PASSWORD); Map<String,String> map = new HashMap<String,String>(); map.put("connections", this.serviceMap); endpoint.setServiceMappings(map); this.getUserActivityStream(); this.getProfileProperties(); System.out.println("Done"); }
Source:
<code>public void onClose(final WebSocket conn, final int code, final String reason, final boolean remote) { FailIf.isNull(conn); log.info("Connection closed."); if (code == CloseFrame.REFUSE) { <START> return; <END> } this.controllers.get(conn).dispose(); this.controllers.remove(conn); }</code><technical_language>Return statements in middle of if is bad practice</technical_language>

Target:
public void onClose(final WebSocket conn, final int code, final String reason, final boolean remote) { FailIf.isNull(conn); log.info("Connection closed."); if (code != CloseFrame.REFUSE) { this.controllers.get(conn).dispose(); this.controllers.remove(conn); } }
Source:
<code>public static long getMaxBytesInMemoryOrDefault(final long maxBytesInMemory) { long newMaxBytesInMemory = maxBytesInMemory; if (maxBytesInMemory == 0) { newMaxBytesInMemory = TuningConfig.DEFAULT_MAX_BYTES_IN_MEMORY; <START> } else if (maxBytesInMemory == -1) { <END> newMaxBytesInMemory = Long.MAX_VALUE; } return newMaxBytesInMemory; }</code><technical_language>else if maxBytesInMemory < 0</technical_language>

Target:
public static long getMaxBytesInMemoryOrDefault(final long maxBytesInMemory) { long newMaxBytesInMemory = maxBytesInMemory; if (maxBytesInMemory == 0) { newMaxBytesInMemory = TuningConfig.DEFAULT_MAX_BYTES_IN_MEMORY; } else if (maxBytesInMemory < 0) { newMaxBytesInMemory = Long.MAX_VALUE; } return newMaxBytesInMemory; }
Source:
<code>public LogFilePath(String prefix, String path) { assert path.startsWith(prefix): path + ".startsWith(" + prefix + ")"; mPrefix = prefix; int prefixLength = prefix.length(); if (!prefix.endsWith("/")) { prefixLength++; } String suffix = path.substring(prefixLength); String[] pathElements = suffix.split("/"); assert pathElements.length >= 3: Arrays.toString(pathElements) + ".length >= 3"; mTopic = pathElements[0]; mPartitions = subArray(pathElements, 1, pathElements.length - 2); String basename = pathElements[pathElements.length - 1]; <START> String suffixPattern = "\\.[^\\.]*$"; <END> Matcher matcher = Pattern.compile(suffixPattern).matcher(basename); if (matcher.find()) { mSuffix = matcher.group(0); } else { mSuffix = ""; } basename = basename.split(suffixPattern)[0]; String[] basenameElements = basename.split("_"); assert basenameElements.length == 3: Integer.toString(basenameElements.length) + " == 3"; mGeneration = Integer.parseInt(basenameElements[0]); mKafkaPartition = Integer.parseInt(basenameElements[1]); mOffset = Long.parseLong(basenameElements[2]); }</code><technical_language>I split dot, capture extensions .tar.gz. Also, regexes expensive. String.indexOf() String.substring() instead</technical_language>

Target:
public LogFilePath(String prefix, String path) { assert path.startsWith(prefix): path + ".startsWith(" + prefix + ")"; mPrefix = prefix; int prefixLength = prefix.length(); if (!prefix.endsWith("/")) { prefixLength++; } String suffix = path.substring(prefixLength); String[] pathElements = suffix.split("/"); assert pathElements.length >= 3: Arrays.toString(pathElements) + ".length >= 3"; mTopic = pathElements[0]; mPartitions = subArray(pathElements, 1, pathElements.length - 2); String basename = pathElements[pathElements.length - 1]; int lastIndexOf = basename.lastIndexOf('.'); if (lastIndexOf >= 0) { mExtension = basename.substring(lastIndexOf, basename.length()); basename = basename.substring(0, lastIndexOf); } else { mExtension = ""; } String[] basenameElements = basename.split("_"); assert basenameElements.length == 3: Integer.toString(basenameElements.length) + " == 3"; mGeneration = Integer.parseInt(basenameElements[0]); mKafkaPartition = Integer.parseInt(basenameElements[1]); mOffset = Long.parseLong(basenameElements[2]); }
Source:
<code><START> @Override protected void onDestroy() { <END> mUnbinder.unbind(); super.onDestroy(); }</code><technical_language>nit: @override in a line</technical_language>

Target:
protected void onDestroy() { mUnbinder.unbind(); super.onDestroy(); }
Source:
<code>private Set<EventHandlerInfo> selectEventHandlers(Class<? extends Event> eventType, EntityRef entity) { Set<EventHandlerInfo> result = Sets.newHashSet(); result.addAll(generalHandlers.get(eventType)); SetMultimap<Class<? extends Component>, EventHandlerInfo> handlers = componentSpecificHandlers.get(eventType); if (handlers == null) { return result; } handlers.keySet().stream().filter(compClass -> entity.hasComponent(compClass)).forEach(compClass -> { for (EventHandlerInfo eventHandler : handlers.get(compClass)) { if (eventHandler.isValidFor(entity)) { result.add(eventHandler); <START> } <END> } }); return result; }</code><technical_language>This method is called often. I leave code as-is, I simple iteration is more performant conversion lambda-based filtering</technical_language>

Target:
private Set<EventHandlerInfo> selectEventHandlers(Class<? extends Event> eventType, EntityRef entity) { Set<EventHandlerInfo> result = Sets.newHashSet(); result.addAll(generalHandlers.get(eventType)); SetMultimap<Class<? extends Component>, EventHandlerInfo> handlers = componentSpecificHandlers.get(eventType); if (handlers == null) { return result; } for (Class<? extends Component> compClass : handlers.keySet()) { if (entity.hasComponent(compClass)) { for (EventHandlerInfo eventHandler : handlers.get(compClass)) { if (eventHandler.isValidFor(entity)) { result.add(eventHandler); } } } } return result; }
Source:
<code>public Void execute(K k, Rewriter rewriter, CompiledDefinition compiledDefinition) { KDebug debugger = new KoreKDebug(k, rewriter, checkpointInterval, files, kem, kRunOptions, compiledDefinition); ConsoleReader reader = getConsoleReader(); while (true) { try { String input = reader.readLine("KDebug> "); <START> if (input.isEmpty()) { <END> continue; } Command command = parseCommand(input); if (command instanceof Commands.QuitCommand) { break; } if (command instanceof Commands.SourceCommand) { String source = ((Commands.SourceCommand) command).getSourceFile(); processSourceCommand(source, debugger, compiledDefinition); System.out.println("File " + source + " Sourced"); } command.runCommand(debugger, compiledDefinition, false); } catch (KEMException e) { System.out.println(e.getMessage()); } catch (ParseException parseException) { System.out.println(parseException.getMessage()); } catch (NumberFormatException numberException) { System.out.println("Could not parse \"foo\" as number"); } catch (FileNotFoundException fileNotFound) { System.out.println(fileNotFound.getMessage()); } catch (IOException inputException) { KEMException.criticalError("Failed to read input from console"); } } return null; }</code><technical_language>is this handling ^D case? ^D exit debugger, ^C eventually terminate current command print a new prompt</technical_language>

Target:
public Void execute(K k, Rewriter rewriter, CompiledDefinition compiledDefinition) { KDebug debugger = new KoreKDebug(k, rewriter, checkpointInterval, files, kem, kRunOptions, compiledDefinition); ConsoleReader reader = getConsoleReader(); while (true) { try { String input = reader.readLine("KDebug> "); if (input == null) { return null; } if (input.isEmpty()) { continue; } Command command = parseCommand(input); if (command instanceof Commands.QuitCommand) { break; } if (command instanceof Commands.SourceCommand) { String source = ((Commands.SourceCommand) command).getSourceFile(); processSourceCommand(source, debugger, compiledDefinition); System.out.println("File " + source + " Sourced"); } command.runCommand(debugger, compiledDefinition, false); } catch (KEMException e) { System.out.println(e.getMessage()); } catch (ParseException parseException) { System.out.println(parseException.getMessage()); } catch (NumberFormatException numberException) { System.out.println("Could not parse \"foo\" as number"); } catch (FileNotFoundException fileNotFound) { System.out.println(fileNotFound.getMessage()); } catch (IOException inputException) { KEMException.criticalError("Failed to read input from console"); } catch (UserInterruptException interrupt) { return null; } } return null; }
Source:
<code>private DocStructInterface parseIssueAssignment(DocStructInterface dsPeriodicalVolume, String right, DigitalDocumentInterface inDigitalDocument) <START> throws TypeNotAllowedForParentException, MetadataTypeNotAllowedException, TypeNotAllowedAsChildException { <END> DocStructTypeInterface dst; MetadataTypeInterface mdt = this.myPrefs.getMetadataTypeByName("CurrentNo"); DocStructInterface dsPeriodicalIssue = null; List<DocStructInterface> myList = dsPeriodicalVolume.getAllChildrenByTypeAndMetadataType("PeriodicalIssue", "CurrentNo"); if (myList != null && myList.size() != 0) { for (DocStructInterface dsIntern : myList) { MetadataInterface metadata = dsIntern.getAllMetadataByType(mdt).get(0); if (metadata.getValue().equals(right)) { dsPeriodicalIssue = dsIntern; } } } if (dsPeriodicalIssue == null) { dst = this.myPrefs.getDocStrctTypeByName("PeriodicalIssue"); dsPeriodicalIssue = inDigitalDocument.createDocStruct(dst); MetadataInterface myMD = UghImplementation.INSTANCE.createMetadata(mdt); myMD.setStringValue(right); dsPeriodicalIssue.addMetadata(myMD); dsPeriodicalVolume.addChild(dsPeriodicalIssue); } return dsPeriodicalIssue; }</code><technical_language>TypeNotAllowedForParentException - exception</technical_language>

Target:
private DocStructInterface parseIssueAssignment(DocStructInterface dsPeriodicalVolume, String right, DigitalDocumentInterface inDigitalDocument) throws MetadataTypeNotAllowedException, TypeNotAllowedAsChildException { DocStructTypeInterface dst; MetadataTypeInterface mdt = this.myPrefs.getMetadataTypeByName("CurrentNo"); DocStructInterface dsPeriodicalIssue = null; List<DocStructInterface> myList = dsPeriodicalVolume.getAllChildrenByTypeAndMetadataType("PeriodicalIssue", "CurrentNo"); if (myList != null && myList.size() != 0) { for (DocStructInterface dsIntern : myList) { MetadataInterface metadata = dsIntern.getAllMetadataByType(mdt).get(0); if (metadata.getValue().equals(right)) { dsPeriodicalIssue = dsIntern; } } } if (dsPeriodicalIssue == null) { dst = this.myPrefs.getDocStrctTypeByName("PeriodicalIssue"); dsPeriodicalIssue = inDigitalDocument.createDocStruct(dst); MetadataInterface myMD = UghImplementation.INSTANCE.createMetadata(mdt); myMD.setStringValue(right); dsPeriodicalIssue.addMetadata(myMD); dsPeriodicalVolume.addChild(dsPeriodicalIssue); } return dsPeriodicalIssue; }
Source:
<code>private ImmutableSet<ModelWithPayload<Item>> mergeItemsWithExisting( ImmutableSet<ModelWithPayload<Item>> fetchedItems, Set<ModelWithPayload<Item>> existingItems) { Map<String, ModelWithPayload<Item>> fetchedIndex = LocalOrRemoteNitroFetcher.getIndex(fetchedItems); ImmutableSet.Builder<ModelWithPayload<Item>> merged = ImmutableSet.builder(); for (ModelWithPayload<Item> existing : existingItems) { ModelWithPayload<Item> fetched = fetchedIndex.remove(existing.getModel().getCanonicalUri()); if (fetched != null) { Item mergedItem = contentMerger.merge(existing.getModel(), fetched.getModel()); merged.add(new ModelWithPayload(mergedItem, fetched.getPayload())); } else { merged.add(existing); } } ImmutableSet<ModelWithPayload<Item>> all = <START> ImmutableSet.copyOf(Iterables.concat(merged.build(), fetchedIndex.values())); <END> return all; }</code><technical_language>do return merged.addAll(fetchedIndex.values()).build(); save extra churn</technical_language>

Target:
private ImmutableSet<ModelWithPayload<Item>> mergeItemsWithExisting( ImmutableSet<ModelWithPayload<Item>> fetchedItems, Set<ModelWithPayload<Item>> existingItems) { Map<String, ModelWithPayload<Item>> fetchedIndex = LocalOrRemoteNitroFetcher.getIndex(fetchedItems); ImmutableSet.Builder<ModelWithPayload<Item>> merged = ImmutableSet.builder(); for (ModelWithPayload<Item> existing : existingItems) { ModelWithPayload<Item> fetched = fetchedIndex.remove(existing.getModel().getCanonicalUri()); if (fetched != null) { Item mergedItem = contentMerger.merge(existing.getModel(), fetched.getModel()); merged.add(new ModelWithPayload(mergedItem, fetched.getPayload())); } else { merged.add(existing); } } return ImmutableSet.copyOf(Iterables.concat(merged.build(), fetchedIndex.values())); }