auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public int compare(final ItemStack o1, final ItemStack o2) { <START> return Integer.signum(o1.getItem().getId().compareTo(o2.getItem().getId())); <END> }</code><technical_language>Is this signum call needed here? compareTo return correct value</technical_language>

Target:
public int compare(final ItemStack o1, final ItemStack o2) { return o1.getItem().getId().compareTo(o2.getItem().getId()); }
Source:
<code>public Matrix removeRow(int i) { <START> return removeRow(i, this.factory); <END> }</code><technical_language>Please, do this unnecessary. write factory</technical_language>

Target:
public Matrix removeRow(int i) { return removeRow(i, factory); }
Source:
<code>private static void loadPokeZPowers() { if (zpowerloaded) { return; } <START> testLoad();; <END> zpowerloaded = true; String path = "db/moves/" + thisGen + "G/zpower.txt"; InfoFiller.fill(path, new FillerByte() { @Override void fillByte(int i, byte b) { moveNames.get(i).zpower = b; } }); }</code><technical_language>a semicolon</technical_language>

Target:
private static void loadPokeZPowers() { if (zpowerloaded) { return; } testLoad(); zpowerloaded = true; String path = "db/moves/" + thisGen + "G/zpower.txt"; InfoFiller.fill(path, new FillerByte() { @Override void fillByte(int i, byte b) { moveNames.get(i).zpower = b; } }); }
Source:
<code>public void addRow( final TupleBatch from, final int fromRow, final MutableTupleBuffer to, final int toRow, final int offset) { ReadableColumn fromCol = from.asColumn(column); ReplaceableColumn toCol = to.getColumn(offset, toRow); <START> final int inColumRow = to.getInColumnIndex(toRow); <END> switch (aggOp) { case COUNT: toCol.replaceLong(toCol.getLong(inColumRow) + 1, inColumRow); break; case MAX: toCol.replaceInt(Math.max(fromCol.getInt(fromRow), toCol.getInt(inColumRow)), inColumRow); break; case MIN: toCol.replaceInt(Math.min(fromCol.getInt(fromRow), toCol.getInt(inColumRow)), inColumRow); break; case SUM: toCol.replaceLong( LongMath.checkedAdd((long) fromCol.getInt(fromRow), toCol.getLong(inColumRow)), inColumRow); break; case SUM_SQUARED: toCol.replaceLong( LongMath.checkedAdd( LongMath.checkedMultiply((long) fromCol.getInt(fromRow), fromCol.getInt(fromRow)), toCol.getLong(inColumRow)), inColumRow); break; default: throw new IllegalArgumentException(aggOp + " is invalid"); } }</code><technical_language>fix this typo, elsewhere</technical_language>

Target:
public void addRow( final TupleBatch from, final int fromRow, final MutableTupleBuffer to, final int toRow, final int offset) { ReadableColumn fromCol = from.asColumn(column); ReplaceableColumn toCol = to.getColumn(offset, toRow); final int inColumnRow = to.getInColumnIndex(toRow); switch (aggOp) { case COUNT: toCol.replaceLong(toCol.getLong(inColumnRow) + 1, inColumnRow); break; case MAX: toCol.replaceInt(Math.max(fromCol.getInt(fromRow), toCol.getInt(inColumnRow)), inColumnRow); break; case MIN: toCol.replaceInt(Math.min(fromCol.getInt(fromRow), toCol.getInt(inColumnRow)), inColumnRow); break; case SUM: toCol.replaceLong( LongMath.checkedAdd((long) fromCol.getInt(fromRow), toCol.getLong(inColumnRow)), inColumnRow); break; case SUM_SQUARED: toCol.replaceLong( LongMath.checkedAdd( LongMath.checkedMultiply((long) fromCol.getInt(fromRow), fromCol.getInt(fromRow)), toCol.getLong(inColumnRow)), inColumnRow); break; default: throw new IllegalArgumentException(aggOp + " is invalid"); } }
Source:
<code>public String createTopic(String topicName, int numberOfPartitions, Properties topicConfig) { <START> int replicationFactor = Integer.parseInt(topicConfig.getProperty("replicationFactor")); <END> AdminUtils.createTopic(new ZkClient(_zkAddress), topicName, numberOfPartitions, replicationFactor, topicConfig); return String.format(DESTINATION_URI_FORMAT, _zkAddress, topicName); }</code><technical_language>safer call getProperty("replicatorFactor", DEFAULT_REP_FACTOR). validate arguments well</technical_language>

Target:
public String createTopic(String topicName, int numberOfPartitions, Properties topicConfig) { Objects.requireNonNull(topicName, "topicName should not be null"); Objects.requireNonNull(topicConfig, "topicConfig should not be null"); int replicationFactor = Integer.parseInt(topicConfig.getProperty("replicationFactor", DEFAULT_REPLICATION_FACTOR)); LOG.info(String.format("Creating topic with name %s partitions %d with properties %s", topicConfig, numberOfPartitions, topicConfig)); try { if (!AdminUtils.topicExists(_zkClient, topicName)) { AdminUtils.createTopic(_zkClient, topicName, numberOfPartitions, replicationFactor, topicConfig); } else { LOG.warn(String.format("Topic with name %s already exists", topicName)); } } catch (Throwable e) { LOG.error(String.format("Creating topic %s failed with exception %s ", topicName, e)); throw e; } return String.format(DESTINATION_URI_FORMAT, _zkAddress, topicName); }
Source:
<code>private boolean areChildrenOptional(EntityDefinition entityDef) { Collection<? extends EntityDefinition> children = AlignmentUtil .getChildrenWithoutContexts(entityDef); if (children == null || children.isEmpty()) return true; for (EntityDefinition child : children) { Definition<?> def = child.getDefinition(); if (def instanceof GroupPropertyDefinition) { Cardinality cardinality = ((GroupPropertyDefinition) def) .getConstraint(Cardinality.class); if (cardinality.getMinOccurs() != 0) return false; else if (!areChildrenOptional(entityDef)) return false; } else if (def instanceof PropertyDefinition) { Cardinality cardinality = ((PropertyDefinition) def) .getConstraint(Cardinality.class); if (cardinality.getMinOccurs() != 0) <START> return false; <END> if (((PropertyDefinition) def).getConstraint(NillableFlag.class).isEnabled()) { if (!areChildrenOptional(child)) return false; } } } return true; }</code><technical_language>is wrong. If minOccurs is zero, check if is Nillable, if is zero check</technical_language>

Target:
private boolean areChildrenOptional(EntityDefinition entityDef) { Collection<? extends EntityDefinition> children = AlignmentUtil .getChildrenWithoutContexts(entityDef); if (children == null || children.isEmpty()) return true; for (EntityDefinition child : children) { Definition<?> def = child.getDefinition(); if (def instanceof GroupPropertyDefinition) { Cardinality cardinality = ((GroupPropertyDefinition) def) .getConstraint(Cardinality.class); if (cardinality.getMinOccurs() != 0 && !areChildrenOptional(entityDef)) return false; } else if (def instanceof PropertyDefinition) { Cardinality cardinality = ((PropertyDefinition) def) .getConstraint(Cardinality.class); if (cardinality.getMinOccurs() != 0 && ((PropertyDefinition) def) .getConstraint(NillableFlag.class).isEnabled()) { if (!areChildrenOptional(child)) return false; } } } return true; }
Source:
<code>public boolean equals(Object obj) { if (!(obj instanceof DependencyFoundEvent<?>)) { return false; } if (!((DependencyFoundEvent<?>)obj).getType().equals(clazz)) { return false; } @SuppressWarnings("unchecked") <START> DependencyFoundEvent<T> event = (DependencyFoundEvent<T>)obj; <END> if ((from == null) != (event.from == null)) { return false; } if ((to == null) != (event.to == null)) { return false; } if ((parent == null) != (event.parent == null)) { return false; } if (from != null && !from.equals(event.from)) { return false; } if (to != null && !to.equals(event.to)) { return false; } if (parent != null && !parent.equals(event.parent)) { return false; } return true; }</code><technical_language>.. replace this cast with: DependencyFoundEvent<?> event = (DependencyFoundEvent<?>)obj;</technical_language>

Target:
public boolean equals(Object obj) { if (!(obj instanceof DependencyFoundEvent<?>)) { return false; } DependencyFoundEvent<?> event = (DependencyFoundEvent<?>)obj; if ((from == null) != (event.from == null)) { return false; } if ((to == null) != (event.to == null)) { return false; } if ((parent == null) != (event.parent == null)) { return false; } if (from != null && !from.equals(event.from)) { return false; } if (to != null && !to.equals(event.to)) { return false; } if (parent != null && !parent.equals(event.parent)) { return false; } return true; }
Source:
<code>public void run() { try { serverChannel.register(nioSelector, SelectionKey.OP_ACCEPT); startupComplete(); int currentProcessor = 0; while (isRunning()) { <START> int ready = nioSelector.select(500); <END> if (ready > 0) { Set<SelectionKey> keys = nioSelector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext() && isRunning()) { SelectionKey key = null; try { key = iter.next(); iter.remove(); if (key.isAcceptable()) { accept(key, processors.get(currentProcessor)); } else { throw new IllegalStateException("Unrecognized key state for acceptor thread."); } currentProcessor = (currentProcessor + 1) % processors.size(); } catch (Exception e) { } } } } logger.debug("Closing server socket and selector."); serverChannel.close(); nioSelector.close(); shutdownComplete(); } catch (Exception e) { logger.error("Error during shutdown of acceptor thread {}", e); } }</code><technical_language>define values somewhere</technical_language>

Target:
public void run() { try { serverChannel.register(nioSelector, SelectionKey.OP_ACCEPT); startupComplete(); int currentProcessor = 0; while (isRunning()) { int ready = nioSelector.select(selectTimeOutMs); if (ready > 0) { Set<SelectionKey> keys = nioSelector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext() && isRunning()) { SelectionKey key = null; try { key = iter.next(); iter.remove(); if (key.isAcceptable()) { accept(key, processors.get(currentProcessor)); } else { throw new IllegalStateException("Unrecognized key state for acceptor thread."); } currentProcessor = (currentProcessor + 1) % processors.size(); } catch (Exception e) { } } } } logger.debug("Closing server socket and selector."); serverChannel.close(); nioSelector.close(); shutdownComplete(); } catch (Exception e) { logger.error("Error during shutdown of acceptor thread {}", e); } }
Source:
<code>static WaitStrategy createWaitStrategy(final String propertyName) { final String strategyStr = PropertiesUtil.getProperties().getStringProperty(propertyName, DisruptorWaitStrategy.TIMEOUT.toString()); LOGGER.trace("property {}={}", propertyName, strategyStr); <START> final DisruptorWaitStrategy strategy = DisruptorWaitStrategy.valueOf(Strings.toRootUpperCase(strategyStr)); <END> final long timeoutMillis = parseAdditionalLongProperty(propertyName, "Timeout", 10L); switch (strategy) { case SLEEP: final long sleepTimeNs = parseAdditionalLongProperty(propertyName, "SleepTimeNs", 100L); final String key = getFullPropertyKey(propertyName, "Retries"); final int retries = PropertiesUtil.getProperties().getIntegerProperty(key, 200); return new SleepingWaitStrategy(retries, sleepTimeNs); case YIELD: return new YieldingWaitStrategy(); case BLOCK: return new BlockingWaitStrategy(); case BUSYSPIN: return new BusySpinWaitStrategy(); case TIMEOUT: return new TimeoutBlockingWaitStrategy(timeoutMillis, TimeUnit.MILLISECONDS); default: return new TimeoutBlockingWaitStrategy(timeoutMillis, TimeUnit.MILLISECONDS); } }</code><technical_language>in favor of enum a valueOf lookup this way. This lookup means invalid (like "INVALID") result in IllegalArgumentException thrown. This is desirable. In previous code, invalid result in default case selected in switch statement, logic correctly fall default TimeoutBlockingWaitStrategy</technical_language>

Target:
static WaitStrategy createWaitStrategy(final String propertyName) { final String strategy = PropertiesUtil.getProperties().getStringProperty(propertyName, "Timeout"); LOGGER.trace("property {}={}", propertyName, strategy); final String strategyUp = Strings.toRootUpperCase(strategy); final long timeoutMillis = parseAdditionalLongProperty(propertyName, "Timeout", 10L); switch (strategyUp) { case "SLEEP": final long sleepTimeNs = parseAdditionalLongProperty(propertyName, "SleepTimeNs", 100L); final String key = getFullPropertyKey(propertyName, "Retries"); final int retries = PropertiesUtil.getProperties().getIntegerProperty(key, 200); return new SleepingWaitStrategy(retries, sleepTimeNs); case "YIELD": return new YieldingWaitStrategy(); case "BLOCK": return new BlockingWaitStrategy(); case "BUSYSPIN": return new BusySpinWaitStrategy(); case "TIMEOUT": return new TimeoutBlockingWaitStrategy(timeoutMillis, TimeUnit.MILLISECONDS); default: return new TimeoutBlockingWaitStrategy(timeoutMillis, TimeUnit.MILLISECONDS); } }
Source:
<code><START> public void close() throws Exception { <END> if (lowLevelClient != null) { lowLevelClient.close(); lowLevelClient = null; } client = null; }</code><technical_language>I missed in interface, throws Exception</technical_language>

Target:
public void close() { if (lowLevelClient != null) { try { lowLevelClient.close(); } catch (IOException e) { log.warn("Fail to close the Elasticsearch low level RestClient: " + e.getMessage(), e); } lowLevelClient = null; } client = null; }
Source:
<code>public void authorizeEventTypeWrite(final EventType eventType) throws AccessDeniedException, ServiceTemporarilyUnavailableException { if (eventType.getAuthorization() == null) { return; } final EventTypeResource resource = new EventTypeResource( eventType.getName(), eventType.getAuthorization()); try { final boolean authorized = authorizationService.isAuthorized( AuthorizationService.Operation.WRITE, resource); if (!authorized) { if (!adminService.isAdmin(AuthorizationService.Operation.WRITE)) { throw new AccessDeniedException(AuthorizationService.Operation.WRITE, resource); <START> } <END> } } catch (final PluginException ex) { throw new ServiceTemporarilyUnavailableException("Error while checking authorization", ex); } }</code><technical_language>@lmontrieux fact I reading administrator is a wrong, valuable thing, I strongly WRITE operation forbidden for administrators</technical_language>

Target:
public void authorizeEventTypeWrite(final EventType eventType) throws AccessDeniedException, ServiceTemporarilyUnavailableException { if (eventType.getAuthorization() == null) { return; } final EventTypeResource resource = new EventTypeResource( eventType.getName(), eventType.getAuthorization()); try { final boolean authorized = authorizationService.isAuthorized( AuthorizationService.Operation.WRITE, resource); if (!authorized) { throw new AccessDeniedException(AuthorizationService.Operation.WRITE, resource); } } catch (final PluginException ex) { throw new ServiceTemporarilyUnavailableException("Error while checking authorization", ex); } }
Source:
<code>public void beginTree(DetailAST rootAST) { publicTypeFound = false; DetailAST currentNode = rootAST; while (currentNode != null) { if (isTypeDef(currentNode) && isPublic(currentNode)) { <START> publicTypeFound = true; <END> break; } currentNode = currentNode.getNextSibling(); } }</code><technical_language>code is trimmed a bare 2 methods, pretty do thing. beginTree checks for a public type finishTree final violations. Other do scan siblings connected root. I question if merge 2 methods remove fields, if do AST sibling scan once. is benefit of keeping in methods</technical_language>

Target:
public void beginTree(DetailAST rootAST) { DetailAST currentNode = rootAST; boolean publicTypeFound = false; DetailAST firstType = null; while (currentNode != null) { if (isTypeDef(currentNode)) { if (isPublic(currentNode)) { publicTypeFound = true; } if (firstType == null) { firstType = currentNode; } else if (!isPublic(currentNode)) { final String typeName = currentNode .findFirstToken(TokenTypes.IDENT).getText(); log(currentNode, MSG_KEY, typeName); } } currentNode = currentNode.getNextSibling(); } if (publicTypeFound && !isPublic(firstType)) { final String typeName = firstType .findFirstToken(TokenTypes.IDENT).getText(); log(firstType, MSG_KEY, typeName); } }
Source:
<code>public void testAPITagVisibilityAuthorisedUser() throws Exception { List<TagDTO> tagDtoList = apiStoreClientAllowedUser.getAllTags().getList(); List<String> tagList = new ArrayList<>(); for (TagDTO tempTagDTO : tagDtoList) { tagList.add(tempTagDTO.getValue()); } Assert.assertTrue(tagList.contains(TAGS_PUBLIC_API), "Public visibility tag is not available for authorised user"); int retry = 10; if (!tagList.contains(TAGS_RESTRICTED_API)) { Thread.sleep(3000); for (int i = 0; i < retry; i++) { tagDtoList = apiStoreClientAllowedUser.getAllTags().getList(); tagList = new ArrayList<>(); for (TagDTO tempTagDTO : tagDtoList) { tagList.add(tempTagDTO.getValue()); } if (!tagList.contains(TAGS_RESTRICTED_API)) { <START> retry++; <END> Thread.sleep(3000); log.info("Waiting for the API Tags"); } else { break; } } } Assert.assertTrue(tagList.contains(TAGS_RESTRICTED_API), "Restricted visibility tag is not available for authorised user"); }</code><technical_language>incrementing retry value? limiting retry count 10 here</technical_language>

Target:
public void testAPITagVisibilityAuthorisedUser() throws Exception { List<TagDTO> tagDtoList = apiStoreClientAllowedUser.getAllTags().getList(); List<String> tagList = new ArrayList<>(); for (TagDTO tempTagDTO : tagDtoList) { tagList.add(tempTagDTO.getValue()); } Assert.assertTrue(tagList.contains(TAGS_PUBLIC_API), "Public visibility tag is not available for authorised user"); int retry = 10; if (!tagList.contains(TAGS_RESTRICTED_API)) { Thread.sleep(3000); for (int i = 0; i < retry; i++) { tagDtoList = apiStoreClientAllowedUser.getAllTags().getList(); tagList = new ArrayList<>(); for (TagDTO tempTagDTO : tagDtoList) { tagList.add(tempTagDTO.getValue()); } if (!tagList.contains(TAGS_RESTRICTED_API)) { Thread.sleep(3000); log.info("Waiting for the API Tags"); } else { break; } } } Assert.assertTrue(tagList.contains(TAGS_RESTRICTED_API), "Restricted visibility tag is not available for authorised user"); }
Source:
<code>BCFInputStreamIterator(final InputStream inputStream) { <START> this.inputStream = new PositionalBufferedStream(inputStream); <END> this.vcfHeader = (VCFHeader) this.codec.readHeader(this.inputStream).getHeaderValue(); }</code><technical_language>here; delegate codec 's makeSourceFromStream method</technical_language>

Target:
BCFInputStreamIterator(final InputStream inputStream) { this.inputStream = this.codec.makeSourceFromStream(inputStream); this.vcfHeader = (VCFHeader) this.codec.readHeader(this.inputStream).getHeaderValue(); }
Source:
<code>protected void addUserAgentHeader(HttpRequest request) { <START> request.headers().set(HttpHeaderNames.USER_AGENT, "Bazel/" + BlazeVersionInfo.instance().getReleaseName()); <END> }</code><technical_language>getVersion() instead of getReleaseName() e.g. "bazel " + BlazeVersionInfo.instance().getVersion(). This produce bazel 0.23 for 0.23 release bazel HEAD for a development version</technical_language>

Target:
protected void addUserAgentHeader(HttpRequest request) { request.headers().set(HttpHeaderNames.USER_AGENT, USER_AGENT_VALUE); }
Source:
<code>public void unsubscribeOthers(AmbSubscriber<T> notThis) { for (AmbSubscriber<T> other : ambSubscribers) { if (other != notThis) { other.unsubscribe(); } <START> ambSubscribers.clear(); <END> } }</code><technical_language>ambSubscribers.clear(); out of loop</technical_language>

Target:
public void unsubscribeOthers(AmbSubscriber<T> notThis) { for (AmbSubscriber<T> other : ambSubscribers) { if (other != notThis) { other.unsubscribe(); } } ambSubscribers.clear(); }
Source:
<code>private int findKeyInRedeem(ECKey key) { <START> Preconditions.checkArgument(chunks.get(0).isOpCode()); END> int numKeys = chunks.get(chunks.size() - 2).opcode - ScriptOpCodes.OP_1 + 1; for (int i = 0 ; i < numKeys ; i++) { if (Arrays.equals(chunks.get(1 + i).data, key.getPubKey())) { return i; } } throw new RuntimeException("Could not find matching key " + key.toString() + " in script " + this); }</code><technical_language>simplified checkArgument(... in findSigInRedeem</technical_language>

Target:
private int findKeyInRedeem(ECKey key) { checkArgument(chunks.get(0).isOpCode()); int numKeys = Script.decodeFromOpN(chunks.get(chunks.size() - 2).opcode); for (int i = 0 ; i < numKeys ; i++) { if (Arrays.equals(chunks.get(1 + i).data, key.getPubKey())) { return i; } } throw new IllegalStateException("Could not find matching key " + key.toString() + " in script " + this); }
Source:
<code>public void comparisonBytesVsString() throws IOException { List<String> addrs = new LinkedList<>(); List<String> addrs1; List<String> addrs2; BufferedReader dataSetReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("LegacyAddressTestDataset.txt"))); String line; <START> while ((line = dataSetReader.readLine()) != null) addrs.add(line); <END> addrs1 = addrs.subList(0, addrs.size() / 2); addrs2 = addrs.subList(addrs.size() / 2, addrs.size() ); for(int i = 0; i >= addrs1.size(); i++){ int resultBytes = LegacyAddress.fromBase58(MAINNET ,addrs1.get(i)) .compareTo(LegacyAddress.fromBase58(MAINNET, addrs2.get(i))); int resultsString = LegacyAddress.fromBase58(MAINNET, addrs1.get(i)).toString(). compareTo(LegacyAddress.fromBase58(MAINNET, addrs2.get(i)).toString()); assertTrue( resultBytes < 0 ); assertTrue( resultsString < 0 ); } }</code><technical_language>I easier loop do tests while reading file</technical_language>

Target:
public void comparisonBytesVsString() throws IOException { BufferedReader dataSetReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("LegacyAddressTestDataset.txt"))); String line; while ((line = dataSetReader.readLine()) != null) { String addr[] = line.replaceAll("\\n", "").split(","); LegacyAddress one =LegacyAddress.fromBase58(MAINNET, addr[0]); LegacyAddress second = LegacyAddress.fromBase58(MAINNET, addr[1]); int resultBytes = one.compareTo(second); int resultsString = one.toString(). compareTo(second.toString()); assertTrue(resultBytes < 0); assertTrue(resultsString < 0); } }
Source:
<code>private void registerShutDownFuture() { FutureUtils.forward(dispatcherRunner.getShutDownFuture(), shutDownFuture); <START> BiConsumer<Object, Throwable> terminateAction = (ignored, throwable) -> { if (throwable != null) { shutDownFuture.completeExceptionally(throwable); } else { shutDownFuture.complete(ApplicationStatus.SUCCEEDED); } if (isRunning.get()) { fatalErrorHandler.onFatalError(throwable); } }; dispatcherRunner.getTerminationFuture().whenComplete(terminateAction); resourceManager.getTerminationFuture().whenComplete(terminateAction); <END> }</code><technical_language>move this a failOnPrematureTermination method combine termination Futures CompletableFuture.any. Moreover, complete shutDownFuture. Simply calling fatalErrorHandler is good enough</technical_language>

Target:
private void registerShutDownFuture() { FutureUtils.forward(dispatcherRunner.getShutDownFuture(), shutDownFuture); }
Source:
<code>public byte[] getCacheKey() { <START> final byte[] excludeBytes = bound.getBytes(); <END> return ByteBuffer.allocate(1 + excludeBytes.length) .put(CACHE_TYPE_ID) .put(excludeBytes) .array(); }</code><technical_language>boundBytes? need charset for getBytes</technical_language>

Target:
public byte[] getCacheKey() { final byte[] boundBytes = bound.getBytes(Charsets.UTF_8); return ByteBuffer.allocate(1 + boundBytes.length) .put(CACHE_TYPE_ID) .put(boundBytes) .array(); }
Source:
<code>public void test_symbolic_engine_performance() throws IOException { ORCHESTRATOR.getServer().provisionProject("se-project", "se-project"); ORCHESTRATOR.getServer().associateProjectToQualityProfile("se-project", "js", "se-profile"); SonarScanner build = getSonarScanner(); <START> ORCHESTRATOR.executeBuild(getSonarScanner()); <END> double time = sensorTime(build.getProjectDir(), SENSOR); double expected = 140.0; Assertions.assertThat(time).isEqualTo(expected, offset(expected * 0.04)); }</code><technical_language>@vilchik-elena do call getSonarScanner() twice</technical_language>

Target:
public void test_symbolic_engine_performance() throws IOException { test_performance("se-project", "se-profile", true, 175.0); }
Source:
<code>public void initialize(float currentX, float currentY) { <START> minX = Math.round(currentX * DSTFileConstants.STITCH_POINT_UNIT_FACTOR); <END> maxX = Math.round(currentX * DSTFileConstants.STITCH_POINT_UNIT_FACTOR); minY = Math.round(currentY * DSTFileConstants.STITCH_POINT_UNIT_FACTOR); maxY = Math.round(currentY * DSTFileConstants.STITCH_POINT_UNIT_FACTOR); firstX = Math.round(currentX * DSTFileConstants.STITCH_POINT_UNIT_FACTOR); firstY = Math.round(currentY * DSTFileConstants.STITCH_POINT_UNIT_FACTOR); lastX = Math.round(currentX * DSTFileConstants.STITCH_POINT_UNIT_FACTOR); lastY = Math.round(currentY * DSTFileConstants.STITCH_POINT_UNIT_FACTOR); colorChangeCount = 1; pointAmount = 1; }</code><technical_language>Replace repetition helper function. E.g.: private int toEmbroideryUnit(float value) { return Math.round(value * DSTFileConstants.STITCH_POINT_UNIT_FACTOR); }</technical_language>

Target:
public void initialize(float currentX, float currentY) { minX = toEmbroideryUnit(currentX); maxX = toEmbroideryUnit(currentX); minY = toEmbroideryUnit(currentY); maxY = toEmbroideryUnit(currentY); firstX = toEmbroideryUnit(currentX); firstY = toEmbroideryUnit(currentY); lastX = toEmbroideryUnit(currentX); lastY = toEmbroideryUnit(currentY); colorChangeCount = 1; pointAmount = 1; }
Source:
<code>public FormValidation doCheckLabelExpr(@AncestorInPath AbstractProject<?,?> project, @QueryParameter String value) { AbstractProject.AbstractProjectDescriptor desc = projectDescriptor(); if (Util.fixEmptyAndTrim(value) == null) return FormValidation.error("No expressions provided"); List<FormValidation> validations = new ArrayList<FormValidation>(); for (String expr: getExprValues(value)) { validations.add( <START> desc.doCheckAssignedLabelString(project, expr) <END> ); } return aggregateValidations(validations); }</code><technical_language>FYI this is moving @Restricted(DoNoUse) in cores renamed. If update core new name is doCheckLabel</technical_language>

Target:
public FormValidation doCheckLabelExpr(@AncestorInPath AbstractProject<?,?> project, @QueryParameter String value) { if (Util.fixEmptyAndTrim(value) == null) return FormValidation.error("No expressions provided"); List<FormValidation> validations = new ArrayList<FormValidation>(); for (String expr: getExprValues(value)) { final FormValidation validation = AbstractProjectDescriptor.validateLabelExpression(expr, project); validations.add(validation); } return FormValidation.aggregate(validations); }
Source:
<code>public static String fromColumn(String columnName) { <START> return DruidQuery.format("%s", columnName); <END> }</code><technical_language>I understand __time is "__time", equal. run a test soon possible</technical_language>

Target:
public static String fromColumn(String columnName) { return DruidQuery.format("\"%s\"", columnName); }
Source:
<code><START> public CellValueRecordInterface getCellValueRecord() <END> { return _record; }</code><technical_language>Is reason getCellValueRecord() needs public? I usages of this method in diff</technical_language>

Target:
protected CellValueRecordInterface getCellValueRecord() { return _record; }
Source:
<code>public Page<SiteRest> findAll(Context context, Pageable pageable) { List<Site> sites = new ArrayList<Site>(); <START> int total = 0; <END> try { sites.add(sitesv.findSite(context)); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } Page<SiteRest> page = new PageImpl<Site>(sites, pageable, total).map(converter); return page; }</code><technical_language>this set 1 increased manually add site return list</technical_language>

Target:
public Page<SiteRest> findAll(Context context, Pageable pageable) { List<Site> sites = new ArrayList<Site>(); int total = 1; try { sites.add(sitesv.findSite(context)); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } Page<SiteRest> page = new PageImpl<Site>(sites, pageable, total).map(converter); return page; }
Source:
<code>public Bitmap get() throws IOException { checkNotMain(); if (deferred) { throw new IllegalStateException("Fit cannot be used with get."); } if (!data.hasImage()) { return null; } Request finalData = picasso.transformRequest(data.build()); String key = createKey(finalData); Action<Void> action = new GetAction(picasso, finalData, skipMemoryCache, key); BitmapHunter hunter = forRequest(picasso.context, picasso, picasso.dispatcher, picasso.cache, picasso.stats, action, picasso.dispatcher.downloader); Bitmap bitmap = hunter.hunt(); <START> picasso.cache.set(action.getKey(), bitmap); <END> return bitmap; }</code><technical_language>key initialized above</technical_language>

Target:
public Bitmap get() throws IOException { checkNotMain(); if (deferred) { throw new IllegalStateException("Fit cannot be used with get."); } if (!data.hasImage()) { return null; } Request finalData = picasso.transformRequest(data.build()); String key = createKey(finalData); Action<Void> action = new GetAction(picasso, finalData, skipMemoryCache, key); BitmapHunter hunter = forRequest(picasso.context, picasso, picasso.dispatcher, picasso.cache, picasso.stats, action, picasso.dispatcher.downloader); Bitmap bitmap = hunter.hunt(); picasso.cache.set(key, bitmap); return bitmap; }
Source:
<code><START> public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) { <END> if (patterns == null) { patterns = getPatterns(); } if (msg.getResponseBody().length() > 0 && msg.getResponseHeader().isText()) { StringBuilder evidence = new StringBuilder(); Element el; int offset = 0; while ((el = source.getNextElement(offset, HTMLElementName.SCRIPT)) != null) { String elStr = el.toString(); for (Pattern pattern : patterns) { if (pattern.matcher(elStr).find()) { evidence.append(elStr); evidence.append("\n"); break; } } offset = el.getEnd(); } if (evidence.length() > 0) { this.raiseAlert(msg, id, evidence.toString()); } } }</code><technical_language>suggestion public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) { if (!msg.getResponseHeader().isHtml() && !msg.getResponseHeader().isJavaScript()) { return; }</technical_language>

Target:
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) { if (msg.getResponseBody().length() <= 0 || (!msg.getResponseHeader().isHtml() && !msg.getResponseHeader().isJavaScript())) { return; } if (defaultPatterns == null) { createDefaultPatterns(); } loadPayload(); StringBuilder evidence = new StringBuilder(); if (msg.getResponseHeader().isHtml()) { Element el; int offset = 0; while ((el = source.getNextElement(offset, HTMLElementName.SCRIPT)) != null) { String elStr = el.toString(); searchPatterns(evidence, elStr); if (evidence.length() != 0) { break; } offset = el.getEnd(); } } else if (msg.getResponseHeader().isJavaScript()) { String content = msg.getResponseBody().toString(); searchPatterns(evidence, content); } if (evidence.length() > 0) { this.raiseAlert(msg, id, evidence.toString()); } }
Source:
<code>private static JsonRpcClient createClient(String hostname, int port, ClientPolicy connectionPolicy, ClientPolicy clientPolicy, boolean isSecure, ReactorType type, String protocol, int parallelism) { ManagerProvider provider = null; if (isSecure) { provider = new EngineManagerProvider(protocol); } try { final Reactor reactor = ReactorFactory.getReactor(provider, type); return getJsonClient(reactor, hostname, port, connectionPolicy, clientPolicy, parallelism); } catch (ClientConnectionException e) { <START> log.error("Exception occured during building ssl context or obtaining selector"); <END> log.debug("Exception", e); throw new IllegalStateException(e); } }</code><technical_language>Please change to: log.error("Exception occurred building ssl context obtaining selector for '{}': {}", hostname, e.getMessage());</technical_language>

Target:
private static JsonRpcClient createClient(String hostname, int port, ClientPolicy connectionPolicy, ClientPolicy clientPolicy, boolean isSecure, ReactorType type, String protocol, int parallelism) { ManagerProvider provider = null; if (isSecure) { provider = new EngineManagerProvider(protocol); } try { final Reactor reactor = ReactorFactory.getReactor(provider, type); return getJsonClient(reactor, hostname, port, connectionPolicy, clientPolicy, parallelism); } catch (ClientConnectionException e) { log.error("Exception occurred during building ssl context or obtaining selector for '{}': {}", hostname, e.getMessage()); log.debug("Exception", e); throw new IllegalStateException(e); } }
Source:
<code>protected void handlePropertyChangeEvent(PropertyChangeEvent event) { String key= event.getProperty(); if (key.equals(ICompareUIConstants.PROP_ANCESTOR_VISIBLE)) { fAncestorVisible= Utilities.getBoolean(getCompareConfiguration(), ICompareUIConstants.PROP_ANCESTOR_VISIBLE, fAncestorVisible); fComposite.layout(true); updateCursor(fLeftLabel, VERTICAL); updateCursor(fDirectionLabel, HORIZONTAL | VERTICAL); updateCursor(fRightLabel, VERTICAL); return; } if (key.equals(ICompareUIConstants.PROP_IGNORE_ANCESTOR)) { setAncestorVisibility(false, !Utilities.getBoolean(getCompareConfiguration(), ICompareUIConstants.PROP_IGNORE_ANCESTOR, false)); return; } if (key.equals(ComparePreferencePage.LAYOUT)) { leftToRight = <START> event.getNewValue().equals(ICompareUIConstants.PREF_VALUE_LEFT_TO_RIGHT); <END> updateContentProvider(); return; } }</code><technical_language>here. If new is null, exchange equals arguments</technical_language>

Target:
protected void handlePropertyChangeEvent(PropertyChangeEvent event) { String key= event.getProperty(); if (key.equals(ICompareUIConstants.PROP_ANCESTOR_VISIBLE)) { fAncestorVisible= Utilities.getBoolean(getCompareConfiguration(), ICompareUIConstants.PROP_ANCESTOR_VISIBLE, fAncestorVisible); fComposite.layout(true); updateCursor(fLeftLabel, VERTICAL); updateCursor(fDirectionLabel, HORIZONTAL | VERTICAL); updateCursor(fRightLabel, VERTICAL); return; } if (key.equals(ICompareUIConstants.PROP_IGNORE_ANCESTOR)) { setAncestorVisibility(false, !Utilities.getBoolean(getCompareConfiguration(), ICompareUIConstants.PROP_IGNORE_ANCESTOR, false)); return; } if (key.equals(ComparePreferencePage.LAYOUT)) { leftToRight = ICompareUIConstants.PREF_VALUE_LEFT_TO_RIGHT .equals(event.getNewValue()); updateContentProvider(); return; } }
Source:
<code>public void run() { try { updateFile(); lastJobSucceeded = true; lastException = null; } catch (Exception e) { <START> log.warn("Failed to run fetch file job for {}: {}", config.remoteUrl(), e.getMessage()); <END> lastException = e; lastJobSucceeded = false; } }</code><technical_language>@joerghoh stack trace, this exception is swallowed otherwise</technical_language>

Target:
public void run() { try { updateFile(); lastJobSucceeded = true; lastException = null; } catch (Exception e) { log.warn("Failed to run fetch file job for {}", config.remoteUrl(), e); lastException = e; lastJobSucceeded = false; } }
Source:
<code><START> TmfXmlStateChange(Element statechange, XmlStateProvider provider) { <END> fProvider = provider; Node ifNode = statechange.getElementsByTagName(TmfXmlStrings.IF).item(0); if (ifNode != null) { fChange = new XmlConditionalChange(statechange); } else { fChange = new XmlStateValueChange(statechange); } }</code><technical_language>public/default constructor</technical_language>

Target:
public TmfXmlStateChange(Element statechange, XmlStateProvider provider) { fProvider = provider; Node ifNode = statechange.getElementsByTagName(TmfXmlStrings.IF).item(0); if (ifNode != null) { fChange = new XmlConditionalChange(statechange); } else { fChange = new XmlStateValueChange(statechange); } }
Source:
<code>private void updateExternalNics(){ Map<VmDeviceId, VmDevice> nicDevices = Entities.businessEntitiesById(vmDeviceDao.getVmDeviceByVmIdAndType(getVmId(), VmDeviceGeneralType.INTERFACE)); for (VmNetworkInterface nic : vmNetworkInterfaceDao.getAllForVm(getVmId())) { VnicProfile vnicProfile = vnicProfileDao.get(nic.getVnicProfileId()); Network network = networkDao.get(vnicProfile.getNetworkId()); <START> if (network.isExternal()) <END> { Provider<?> provider = providerDao.get(network.getProvidedBy().getProviderId()); NetworkProviderProxy providerProxy = providerProxyFactory.create(provider); Map<String, String> deviceProperties = providerProxy.allocate(network, vnicProfile, nic, destinationVds, true); VmDevice vmDevice = nicDevices.get(new VmDeviceId(nic.getId(), getVmId())); getVm().getRuntimeDeviceCustomProperties().put(vmDevice.getId(), deviceProperties); } } }</code><technical_language>is unplugged NIC bind migration, running VM? a common method initParametersForExternalNetworks()</technical_language>

Target:
private void updateExternalNics(){ Map<VmDeviceId, VmDevice> nicDevices = Entities.businessEntitiesById(vmDeviceDao.getVmDeviceByVmIdAndType(getVmId(), VmDeviceGeneralType.INTERFACE)); for (VmNetworkInterface nic : vmNetworkInterfaceDao.getAllForVm(getVmId())) { VnicProfile vnicProfile = vnicProfileDao.get(nic.getVnicProfileId()); Network network = networkDao.get(vnicProfile.getNetworkId()); if (network.isExternal() && nic.isPlugged()) { Provider<?> provider = providerDao.get(network.getProvidedBy().getProviderId()); NetworkProviderProxy providerProxy = providerProxyFactory.create(provider); Map<String, String> deviceProperties = providerProxy.allocate(network, vnicProfile, nic, destinationVds, true); VmDevice vmDevice = nicDevices.get(new VmDeviceId(nic.getId(), getVmId())); getVm().getRuntimeDeviceCustomProperties().put(vmDevice.getId(), deviceProperties); } } }
Source:
<code>public boolean renameFolder(final Folder folder, final String newName, final User user, final boolean respectFrontEndPermissions) throws DotDataException, DotSecurityException { boolean renamed = false; if (!permissionAPI.doesUserHavePermission(folder, PermissionAPI.PERMISSION_EDIT, user, respectFrontEndPermissions)) { throw new DotSecurityException("User " + (user.getUserId() != null?user.getUserId() : BLANK) + " does not have permission to edit folder" + folder.getPath()); } try { renamed = folderFactory.renameFolder(folder, newName, user, respectFrontEndPermissions); CacheLocator.getNavToolCache().removeNav(folder.getHostId(), folder.getInode()); Identifier folderId = APILocator.getIdentifierAPI().find(folder); CacheLocator.getNavToolCache().removeNavByPath(folderId.getHostId(), folderId.getParentPath()); return renamed; } catch (InvalidFolderNameException e) { <START> Logger.error(FolderAPIImpl.class, e.getMessage()); <END> throw e; } catch (Exception e) { throw new DotDataException(e.getMessage(),e); } }</code><technical_language>part of PR, include more useful logging data please</technical_language>

Target:
public boolean renameFolder(final Folder folder, final String newName, final User user, final boolean respectFrontEndPermissions) throws DotDataException, DotSecurityException { boolean renamed; if (!permissionAPI.doesUserHavePermission(folder, PermissionAPI.PERMISSION_EDIT, user, respectFrontEndPermissions)) { throw new DotSecurityException("User " + (user.getUserId() != null?user.getUserId() : BLANK) + " does not have permission to edit folder" + folder.getPath()); } try { renamed = folderFactory.renameFolder(folder, newName, user, respectFrontEndPermissions); CacheLocator.getNavToolCache().removeNav(folder.getHostId(), folder.getInode()); Identifier folderId = APILocator.getIdentifierAPI().find(folder); CacheLocator.getNavToolCache().removeNavByPath(folderId.getHostId(), folderId.getParentPath()); return renamed; } catch (InvalidFolderNameException e) { Logger.error(FolderAPIImpl.class, "Error renaming folder '" + folder.getPath() + "' with id: " + folder.getIdentifier() + " to name: " + newName + ". Error: " + e.getMessage()); throw e; } catch (Exception e) { Logger.error(FolderAPIImpl.class, "Error renaming folder '" + folder.getPath() + "' with id: " + folder.getIdentifier() + " to name: " + newName + ". Error: " + e.getMessage()); throw new DotDataException(e.getMessage(),e); } }
Source:
<code>public void testDefaults() { assertRecordedDefaults(recordDefaults(DruidConfig.class) .setDruidBrokerUrl(null) .setDruidCoordinatorUrl(null) .setDruidSchema("druid") .setComputePushdownEnabled(false) .setHadoopConfiguration("") <START> .setDruidAuthenticationType(null)); <END> }</code><technical_language>DruidAuthenticationType.NONE</technical_language>

Target:
public void testDefaults() { assertRecordedDefaults(recordDefaults(DruidConfig.class) .setDruidBrokerUrl(null) .setDruidCoordinatorUrl(null) .setDruidSchema("druid") .setComputePushdownEnabled(false) .setHadoopConfiguration("") .setDruidAuthenticationType(NONE) .setBasicAuthenticationUsername(null) .setBasicAuthenticationPassword(null)); }
Source:
<code>private void updateMatchedEntries() { if (preferencesService.getDisplayGroupCount()) { BackgroundTask <START> .wrap(() -> groupNode.calculateNumberOfMatches(databaseContext.getDatabase())) <END> .onSuccess(hits::setValue) .executeWith(taskExecutor); BackgroundTask .wrap(() -> groupNode.findMatches(databaseContext.getDatabase())) .onSuccess(entries -> { matchedEntries.clear(); matchedEntries.addAll(entries); }) .executeWith(taskExecutor); } }</code><technical_language>I this duplication of code is a result a merge conflict</technical_language>

Target:
private void updateMatchedEntries() { if (preferencesService.getDisplayGroupCount()) { BackgroundTask .wrap(() -> groupNode.findMatches(databaseContext.getDatabase())) .onSuccess(entries -> { matchedEntries.clear(); matchedEntries.addAll(entries); }) .executeWith(taskExecutor); } }
Source:
<code>public TaskLock lock(final Task task, final Interval interval, long timeoutMs) throws InterruptedException { <START> long nanos = TIME_UNIT.toNanos(timeoutMs); <END> giant.lockInterruptibly(); try { Optional<TaskLock> taskLock; while (!(taskLock = tryLock(task, interval)).isPresent()) { if (nanos <= 0) { return null; } nanos = lockReleaseCondition.awaitNanos(nanos); } return taskLock.get(); } finally { giant.unlock(); } }</code><technical_language>Milliseconds hardcoded (parameter name timeout**Ms**) IMO is point in constant TIME_UNIT, TimeUnit.MILLISECONDS.toNanos(timeoutMs)</technical_language>

Target:
public TaskLock lock(final Task task, final Interval interval, long timeoutMs) throws InterruptedException { long nanos = TimeUnit.MILLISECONDS.toNanos(timeoutMs); giant.lockInterruptibly(); try { Optional<TaskLock> taskLock; while (!(taskLock = tryLock(task, interval)).isPresent()) { if (nanos <= 0) { return null; } nanos = lockReleaseCondition.awaitNanos(nanos); } return taskLock.get(); } finally { giant.unlock(); } }
Source:
<code>private void checkpointNote(NotebookSocket conn, Notebook notebook, Message fromMessage) throws IOException { String noteId = (String) fromMessage.get("noteId"); String commitMessage = (String) fromMessage.get("commitMessage"); AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal); Revision revision = notebook.checkpointNote(noteId, commitMessage, subject); <START> if (!Revision.EMPTY.equals(revision)) { <END> List<Revision> revisions = notebook.listRevisionHistory(noteId, subject); conn.send(serializeMessage(new Message(OP.LIST_REVISION_HISTORY) .put("revisionList", revisions))); } }</code><technical_language>a implementation revision.isEmpty() Revision.isEmpty(revision) do</technical_language>

Target:
private void checkpointNote(NotebookSocket conn, Notebook notebook, Message fromMessage) throws IOException { String noteId = (String) fromMessage.get("noteId"); String commitMessage = (String) fromMessage.get("commitMessage"); AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal); Revision revision = notebook.checkpointNote(noteId, commitMessage, subject); if (!Revision.isEmpty(revision)) { List<Revision> revisions = notebook.listRevisionHistory(noteId, subject); conn.send(serializeMessage(new Message(OP.LIST_REVISION_HISTORY) .put("revisionList", revisions))); } else { conn.send(serializeMessage(new Message(OP.ERROR_INFO).put("info", "Couldn't checkpoint note revision: possibly storage doesn't support versioning. " + "Please check the logs for more details."))); } }
Source:
<code>public static Collection<Object[]> namesParams() { return Arrays.asList(new Object[][] { <START> { null, false, false, true }, END> { "", false, false, false }, { "a.a.a.a", false, false, false }, { "255.255.0", false, false, false }, { "255.255.0", false, false, false }, { "255.255.0.0.0", false, false, false }, { "255.255.0.0.", false, false, false }, { "31 ", false, false, false }, { "33", false, false, false }, { "33", false, false, false }, { "31/", false, false, false }, { "31*", false, false, false }, { " { "/31 ", false, false, false }, { "01", false, false, true }, { "01/", false, false, false }, { "33", false, false, false }, { "/33", false, false, false }, { "255.255.0.1", true, false, false }, { "255.255.0.1", true, false, false }, { "255.0.255.0", true, false, false }, { "255.0.0.255", true, false, false }, { "224.0.255.0", true, false, false }, { "255.255.0.0", true, true, false }, { "255.255.0.0", true, true, false }, { "255.255.255.255", true, true, false }, { "31", false, true, true }, { "/31", false, true, true }, { "7", false, true, true }, { "/7", false, true, true }, { "255.255.0.1", true, false, true }, { "255.255.0.1", true, false, false }, { "255.255.0.0", true, true, false }, }); }</code><technical_language>null a valid prefix</technical_language>

Target:
public static Collection<Object[]> namesParams() { Random random = new Random(); return Arrays.asList(new Object[][] { { null, false, random.nextBoolean(), false }, { "", false, random.nextBoolean(), false }, { "a.a.a.a", false, random.nextBoolean(), false }, { "255.255.0", false, random.nextBoolean(), false }, { "255.255.0.0.0", false, random.nextBoolean(), false }, { "255.255.0.0.", false, random.nextBoolean(), false }, { "31 ", false, random.nextBoolean(), false }, { "/31 ", false, random.nextBoolean(), false }, { "31/", false, random.nextBoolean(), false }, { "31*", false, random.nextBoolean(), false }, { " { "33", false, random.nextBoolean(), false }, { "/33", false, random.nextBoolean(), false }, { "01", false, random.nextBoolean(), false }, { "01/", false, random.nextBoolean(), false }, { "255.255.0.1", true, false, false }, { "255.0.255.0", true, false, false }, { "255.0.0.255", true, false, false }, { "224.0.255.0", true, false, false }, { "255.255.0.0", true, true, false }, { "255.255.255.255", true, true, false }, { "31", false, random.nextBoolean(), true }, { "/31", false, random.nextBoolean(), true }, { "7", false, random.nextBoolean(), true }, { "/7", false, random.nextBoolean(), true }, }); }
Source:
<code>private static <T> Set<T> findDuplicates(Collection<T> list) { Set<T> duplicates = new HashSet<>(); Set<T> uniques = new HashSet<>(); <START> for(T t : list) { <END> if(!uniques.add(t)) { duplicates.add(t); } } return duplicates; }</code><technical_language>list.stream().forEach</technical_language>

Target:
private static <T> Set<T> findDuplicates(Collection<T> list) { Set<T> duplicates = new HashSet<>(); Set<T> uniques = new HashSet<>(); list.stream().forEach(t -> { if (!uniques.add(t)) { duplicates.add(t); } }); return duplicates; }
Source:
<code>private static Iterable<List<List<Object>>> asBatches(Iterator<List<Object>> dataRows) { return () -> new Iterator<List<List<Object>>>() { @Override public boolean hasNext() { return dataRows.hasNext(); } @Override public List<List<Object>> next() { List<List<Object>> batch = new ArrayList<>(); <START> while (dataRows.hasNext() || batch.size() < BATCH_SIZE) { <END> batch.add(ImmutableList.copyOf(dataRows.next())); } return batch; } }; }</code><technical_language>If dataRows is empty (hasNext() = false) batch.size() < BATCH_SIZE, NoSuchElementException thrown in next line</technical_language>

Target:
private static Iterable<List<List<Object>>> asBatches(Iterator<List<Object>> dataRows) { return () -> new Iterator<List<List<Object>>>() { @Override public boolean hasNext() { return dataRows.hasNext(); } @Override public List<List<Object>> next() { List<List<Object>> batch = new ArrayList<>(); while (dataRows.hasNext() && batch.size() < BATCH_SIZE) { batch.add(dataRows.next()); } return batch; } }; }