auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private ResettableRandomizedIterator<InternalNode> getRandomCandidates(int limit, NodeMap nodeMap, List<RemoteTask> existingTasks) { <START> Set<InternalNode> existingNodes = existingTasks.stream().map(remoteTask -> nodeMap.getNodesByNodeId().get(remoteTask.getNodeId())).collect(toSet()); <END> int alreadySelectedNodeCount = existingNodes.size(); int nodeCount = nodeMap.getNodesByNodeId().size(); if (alreadySelectedNodeCount < limit && alreadySelectedNodeCount < nodeCount) { List<InternalNode> moreNodes = selectNodes(limit - alreadySelectedNodeCount, randomizedNodes(nodeMap, includeCoordinator, existingNodes)); existingNodes.addAll(moreNodes); } return new ResettableRandomizedIterator<>(existingNodes); }</code><technical_language>suggestion: This code is gonna called for batch of splits. more efficient 1. Collecting a List 2. Create a set in "likely" branch: alreadySelectedNodeCount < limit, right passed selectNodes</technical_language>

Target:
private ResettableRandomizedIterator<InternalNode> getRandomCandidates(int limit, NodeMap nodeMap, List<RemoteTask> existingTasks) { List<InternalNode> existingNodes = existingTasks.stream() .map(remoteTask -> nodeMap.getNodesByNodeId().get(remoteTask.getNodeId())) .collect(toList()); int alreadySelectedNodeCount = existingTasks.size(); int nodeCount = nodeMap.getNodesByNodeId().size(); if (alreadySelectedNodeCount < limit && alreadySelectedNodeCount < nodeCount) { List<InternalNode> moreNodes = selectNodes(limit - alreadySelectedNodeCount, randomizedNodes(nodeMap, includeCoordinator, newHashSet(existingNodes))); existingNodes.addAll(moreNodes); } return new ResettableRandomizedIterator<>(existingNodes); }
Source:
<code>public void onCustomizedStateRootChange(String instanceName, List<String> customizedStateTypes, NotificationContext changeContext) { logger.info("START: GenericClusterController.onCustomizedStateRootChange()"); HelixManager manager = changeContext.getManager(); Builder keyBuilder = new Builder(manager.getClusterName()); synchronized (_lastSeenCustomizedStateTypes) { <START> Set<String> lastSeenCustomizedStateTypes = _lastSeenCustomizedStateTypes.get(); <END> for (String customizedState : customizedStateTypes) { try { if (lastSeenCustomizedStateTypes == null || !lastSeenCustomizedStateTypes .contains(customizedState)) { manager.addCustomizedStateChangeListener(this, instanceName, customizedState); logger.info( manager.getInstanceName() + " added customized state listener for " + instanceName + ", listener: " + this); } } catch (Exception e) { logger.error("Fail to add customized state listener for instance: " + instanceName, e); } } for (String previousCustomizedState : lastSeenCustomizedStateTypes) { if (!customizedStateTypes.contains(previousCustomizedState)) { manager.removeListener(keyBuilder.customizedStates(instanceName, previousCustomizedState), this); } } _lastSeenCustomizedStateTypes.set(new HashSet<>(customizedStateTypes)); } }</code><technical_language>If lock _lastSeenCustomizedStateTypes, do need AtomicReference</technical_language>

Target:
public void onCustomizedStateRootChange(String instanceName, List<String> customizedStateTypes, NotificationContext changeContext) { logger.info("START: GenericClusterController.onCustomizedStateRootChange()"); HelixManager manager = changeContext.getManager(); Builder keyBuilder = new Builder(manager.getClusterName()); if (customizedStateTypes.isEmpty()) { customizedStateTypes = manager.getHelixDataAccessor() .getChildNames(keyBuilder.customizedStatesRoot(instanceName)); } synchronized (_lastSeenCustomizedStateTypes) { Set<String> lastSeenCustomizedStateTypes = _lastSeenCustomizedStateTypes.get(); for (String customizedState : customizedStateTypes) { try { if (lastSeenCustomizedStateTypes == null || !lastSeenCustomizedStateTypes .contains(customizedState)) { manager.addCustomizedStateChangeListener(this, instanceName, customizedState); logger.info( manager.getInstanceName() + " added customized state listener for " + instanceName + ", listener: " + this); } } catch (Exception e) { logger.error("Fail to add customized state listener for instance: " + instanceName, e); } } for (String previousCustomizedState : lastSeenCustomizedStateTypes) { if (!customizedStateTypes.contains(previousCustomizedState)) { manager.removeListener(keyBuilder.customizedStates(instanceName, previousCustomizedState), this); } } _lastSeenCustomizedStateTypes.set(new HashSet<>(customizedStateTypes)); } }
Source:
<code>protected void executeCommand() { initConnectionList(true); for (Map.Entry<StorageType, List<StorageServerConnections>> connectionToType : getConnectionsTypeMap().entrySet()) { disconnectStorageByType(connectionToType.getKey(), connectionToType.getValue()); } <START> if (FeatureSupported.cinderProviderSupported(getStoragePool().getCompatibilityVersion())) { <END> unregisterLibvirtSecrets(); } }</code><technical_language>please move method consistent..</technical_language>

Target:
protected void executeCommand() { initConnectionList(true); for (Map.Entry<StorageType, List<StorageServerConnections>> connectionToType : getConnectionsTypeMap().entrySet()) { disconnectStorageByType(connectionToType.getKey(), connectionToType.getValue()); } unregisterLibvirtSecrets(); }
Source:
<code>public void testSetReadOnly() { <START> boolean arbitraryValue = false; <END> view.setReadOnly(arbitraryValue); verify(slaTimeDuration).setDisabled(arbitraryValue); }</code><technical_language>suggestion final boolean arbitraryValue = false;</technical_language>

Target:
public void testSetReadOnly() { final boolean arbitraryValue = false; view.setReadOnly(arbitraryValue); verify(slaTimeDuration).setDisabled(arbitraryValue); }
Source:
<code>public int populateContentTypeCache(int limit) { <START> if (limit > 1000) { <END> throw new IllegalArgumentException("Page limit cannot be more then 1000."); } if (limit <= 0) { throw new IllegalArgumentException("Page limit cannot be less or equal to 0."); } return observeContentTypeCachePopulation(limit).blockingFirst(); }</code><technical_language>want "Items page limit be..."</technical_language>

Target:
public int populateContentTypeCache(int limit) { if (limit > 1000) { throw new IllegalArgumentException("Content types per page limit cannot be more then 1000."); } if (limit <= 0) { throw new IllegalArgumentException("Content types per page limit cannot be " + "less or equal to 0."); } return observeContentTypeCachePopulation(limit).blockingFirst(); }
Source:
<code>protected void createFieldEditors() { <START> stringEditor = new StringFieldEditor(ReqifPreferences.REQIF_ID_ATTRIBUTE, "ID attribute", <END> getFieldEditorParent()); addField(stringEditor); }</code><technical_language>Please externalise strings constants. Also, give this a more telling name? "Attribute ID" similar</technical_language>

Target:
protected void createFieldEditors() { stringEditor = new StringFieldEditor(ReqifPreferences.REQIF_ID_ATTRIBUTE, ID_ATTRIBUTE, getFieldEditorParent()); addField(stringEditor); }
Source:
<code>private void checkResourceRequirements() { final Map<JobID, Collection<ResourceRequirement>> missingResources = resourceTracker.getMissingResources(); if (missingResources.isEmpty()) { return; } final Map<JobID, ResourceCounter> outstandingRequirements = new LinkedHashMap<>(); for (Map.Entry<JobID, Collection<ResourceRequirement>> resourceRequirements : missingResources.entrySet()) { JobID jobId = resourceRequirements.getKey(); <START> for (ResourceRequirement resourceRequirement : resourceRequirements.getValue()) { int numMissingSlots = internalRequestSlots(jobId, jobMasterTargetAddresses.get(jobId), resourceRequirement); if (numMissingSlots > 0) { outstandingRequirements .computeIfAbsent(jobId, ignored -> new ResourceCounter()) .incrementCount(resourceRequirement.getResourceProfile(), numMissingSlots); } } } final ResourceCounter pendingSlots = new ResourceCounter(taskExecutorManager.getPendingTaskManagerSlots().stream().collect( Collectors.groupingBy( PendingTaskManagerSlot::getResourceProfile, Collectors.summingInt(x -> 1)))); for (Map.Entry<JobID, ResourceCounter> unfulfilledRequirement : outstandingRequirements.entrySet()) { tryFulfillRequirementsWithPendingOrNewSlots( unfulfilledRequirement.getKey(), unfulfilledRequirement.getValue().getResourceProfilesWithCount(), pendingSlots); } } <END></code><technical_language>I suggest factor this out a separate method requestsSlotsForJob so</technical_language>

Target:
private void checkResourceRequirements() { final Map<JobID, Collection<ResourceRequirement>> missingResources = resourceTracker.getMissingResources(); if (missingResources.isEmpty()) { return; } final Map<JobID, ResourceCounter> unfulfilledRequirements = new LinkedHashMap<>(); for (Map.Entry<JobID, Collection<ResourceRequirement>> resourceRequirements : missingResources.entrySet()) { final JobID jobId = resourceRequirements.getKey(); final ResourceCounter unfulfilledJobRequirements = tryAllocateSlotsForJob(jobId, resourceRequirements.getValue()); if (!unfulfilledJobRequirements.isEmpty()) { unfulfilledRequirements.put(jobId, unfulfilledJobRequirements); } } if (unfulfilledRequirements.isEmpty()) { return; } final ResourceCounter pendingSlots = new ResourceCounter(taskExecutorManager.getPendingTaskManagerSlots().stream().collect( Collectors.groupingBy( PendingTaskManagerSlot::getResourceProfile, Collectors.summingInt(x -> 1)))); for (Map.Entry<JobID, ResourceCounter> unfulfilledRequirement : unfulfilledRequirements.entrySet()) { tryFulfillRequirementsWithPendingSlots( unfulfilledRequirement.getKey(), unfulfilledRequirement.getValue().getResourceProfilesWithCount(), pendingSlots); } }
Source:
<code>private void scheduleOrRescheduleJob(ScheduledJob job) { JobBuilder jobBuilder = JobBuilder.newJob(job.getClazz()) .withIdentity(job.getJobKey()) .requestRecovery(job.isRequestsRecovery()) .storeDurably(job.isStoreDurably()); boolean exists = false; try { exists = scheduler.checkExists(job.getJobKey()); } catch (SchedulerException e) { log.error("error occured checking the job " + job.getJobKey().toString(), e); return; } if (!exists) { try { scheduler.scheduleJob(jobBuilder.build(), job.getTrigger()); } catch (SchedulerException e) { log.error("error occured scheduling the job " + job.getJobKey().toString(), e); <START> return; <END> } log.info("scheduled job with key " + job.getJobKey().toString()); } else { List<? extends Trigger> triggers = new ArrayList<>(); try { triggers = scheduler.getTriggersOfJob(job.getJobKey()); } catch (SchedulerException e) { log.error("error occured reading triggers of the job " + job.getJobKey().toString(), e); return; } if (triggers.size() == 1) { try { scheduler.rescheduleJob(triggers.get(0).getKey(), job.getTrigger()); } catch (SchedulerException e) { log.error("error occured re-scheduling the job " + job.getJobKey().toString(), e); return; } } else { try { scheduler.deleteJob(job.getJobKey()); scheduler.scheduleJob(jobBuilder.build(), job.getTrigger()); } catch (SchedulerException e) { log.error("error occured deleting/scheduling the job " + job.getJobKey().toString(), e); return; } } } log.info(job.getMessage()); }</code><technical_language>Avoid return statements this method</technical_language>

Target:
private void scheduleOrRescheduleJob(ScheduledJob job) { JobKey jobKey = job.getJobKey(); Trigger trigger = job.getTrigger(); JobBuilder jobBuilder = JobBuilder.newJob(job.getClazz()) .withIdentity(jobKey) .requestRecovery(job.isRequestsRecovery()) .storeDurably(job.isStoreDurably()); try { if (scheduler.checkExists(jobKey)) { List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey); if (triggers.size() == 1) { scheduler.rescheduleJob(triggers.get(0).getKey(), trigger); log.info(job.getMessage()); } else { scheduler.deleteJob(jobKey); scheduler.scheduleJob(jobBuilder.build(), trigger); log.info(job.getMessage()); } } else { scheduler.scheduleJob(jobBuilder.build(), trigger); log.info("scheduled job with key {}", jobKey.toString()); log.info(job.getMessage()); } } catch (SchedulerException e) { log.error(String.format("error occurred scheduling the job %s", jobKey), e); } }
Source:
<code>private static String exclusionReasonExpressionNotSatisfy(List<String> tagExpressions) { <START> return String.format("Test excluded Because it does not satisfy expression(s): [%s]", <END> formatToString(tagExpressions)); }</code><technical_language>suggestion return String.format("excluded tags do match tag expression [%s]",</technical_language>

Target:
private static String exclusionReasonExpressionNotSatisfy(List<String> tagExpressions) { return String.format("excluded because tags do not match tag expression(s): [%s]", formatToString(tagExpressions)); }
Source:
<code>static boolean isTransformSelectedFrom(Transform[] selected, Transform[] selectFrom) { if ((selected.length > 1) || (selected.length == 0) != (selectFrom.length == 0)) { return false; } if (selected.length == 0) return true; <START> Transform chosenTransform = selected[0]; <END> return Arrays.asList(selectFrom).contains(chosenTransform); }</code><technical_language>Nit: inline this if place</technical_language>

Target:
static boolean isTransformSelectedFrom(Transform[] selected, Transform[] selectFrom) { if ((selected.length > 1) || (selected.length == 0) != (selectFrom.length == 0)) { return false; } if (selected.length == 0) return true; return Arrays.asList(selectFrom).contains(selected[0]); }
Source:
<code>final V putIfAbsent(K key, V value, Metadata metadata, long explicitFlags, InvocationContext ctx) { assertKeyValueNotNull(key, value); DataWriteCommand command; if (value instanceof Delta) { command = createApplyDelta(key, (Delta) value, explicitFlags, ctx); <START> } if (value instanceof DeltaAware && (explicitFlags & FlagBitSets.CACHE_MODE_LOCAL) == 0) { <END> command = createApplyDelta(key, ((DeltaAware) value).delta(), explicitFlags, ctx); } else { command = createPutIfAbsentCommand(key, value, metadata, explicitFlags, ctx); } return (V) executeCommandAndCommitIfNeeded(ctx, command); }</code><technical_language>bug: else is missing</technical_language>

Target:
final V putIfAbsent(K key, V value, Metadata metadata, long explicitFlags, InvocationContext ctx) { assertKeyValueNotNull(key, value); DataWriteCommand command; if (value instanceof Delta) { command = createApplyDelta(key, (Delta) value, explicitFlags, ctx); } else if (value instanceof DeltaAware && (explicitFlags & FlagBitSets.CACHE_MODE_LOCAL) == 0) { command = createApplyDelta(key, ((DeltaAware) value).delta(), explicitFlags, ctx); } else { command = createPutIfAbsentCommand(key, value, metadata, explicitFlags, ctx); } return (V) executeCommandAndCommitIfNeeded(ctx, command); }
Source:
<code>public void MessageWall_006_writeReply() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userName, credentials.password, wikiURL); NewMessageWall wall = base.openMessageWall(credentials.userName, wikiURL); MiniEditorComponentObject mini = wall.triggerMessageArea(); String message = PageContent.MESSAGE_WALL_MESSAGE_PREFIX + wall.getTimeStamp(); <START> String title = PageContent.MESSAGE_WALL_TITLE_PREFIX+ wall.getTimeStamp(); <END> mini.switchAndWrite(message); wall.writeTitle(title); wall.submit(); wall.verifyMessageText(title, message, credentials.userName); MiniEditorComponentObject miniReply = wall.triggerReplyMessageArea(); String reply = PageContent.MESSAGE_WALL_QUOTE_PREFIX + wall.getTimeStamp(); miniReply.switchAndQuoteMessageWall(reply);; wall.submitQuote(); wall.verifyQuote(reply); }</code><technical_language>above. add space +</technical_language>

Target:
public void MessageWall_006_writeReply() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userName, credentials.password, wikiURL); NewMessageWall wall = base.openMessageWall(credentials.userName, wikiURL); MiniEditorComponentObject mini = wall.triggerMessageArea(); String message = PageContent.MESSAGE_WALL_MESSAGE_PREFIX + wall.getTimeStamp(); String title = PageContent.MESSAGE_WALL_TITLE_PREFIX + wall.getTimeStamp(); mini.switchAndWrite(message); wall.writeTitle(title); wall.submit(); wall.verifyMessageText(title, message, credentials.userName); MiniEditorComponentObject miniReply = wall.triggerReplyMessageArea(); String reply = PageContent.MESSAGE_WALL_QUOTE_PREFIX + wall.getTimeStamp(); miniReply.switchAndQuoteMessageWall(reply); wall.submitQuote(); wall.verifyQuote(reply); }
Source:
<code>public void finalizeDependencies() { if (dependencies != null) { List<Rule> scalaCompiler = Collections.singletonList( new JvmBinaryRule() .mainClassName("scala.tools.nsc.Main") .deps(BuckRuleComposer.external(dependencies)) .ruleType(RuleType.JAVA_BINARY.getBuckName()) .name("scala-compiler.jar") .defaultVisibility()); Multimap<String, String> loadStatements = LoadStatementsUtil.getLoadStatements(scalaCompiler, extension); <START> File buckFile = rootProject.file(SCALA_COMPILER_LOCATION).toPath().resolve("BUCK").toFile(); <END> FileUtil.writeToBuckFile(loadStatements, scalaCompiler, buckFile); } }</code><technical_language>constant - .resolve(OkBuckGradlePlugin.BUCK)</technical_language>

Target:
public void finalizeDependencies() { if (dependencies != null) { List<Rule> scalaCompiler = Collections.singletonList( new JvmBinaryRule() .mainClassName("scala.tools.nsc.Main") .deps(BuckRuleComposer.external(dependencies)) .ruleType(RuleType.JAVA_BINARY.getBuckName()) .name("scala-compiler.jar") .defaultVisibility()); Multimap<String, String> loadStatements = LoadStatementsUtil.getLoadStatements(scalaCompiler, extension); File buckFile = rootProject .file(SCALA_COMPILER_LOCATION) .toPath() .resolve(OkBuckGradlePlugin.BUCK) .toFile(); FileUtil.writeToBuckFile(loadStatements, scalaCompiler, buckFile); } }
Source:
<code>public void testGetEntryIdsOfTestEntries() { final List<ImportedGermplasm> importedGermplasmList = createImportedGermplasmList(); <START> importedGermplasmList.get(0).setEntryTypeCategoricalID(SystemDefinedEntryType.CHECK_ENTRY.getEntryTypeCategoricalId()); <END> importedGermplasmList.get(2).setEntryTypeCategoricalID(SystemDefinedEntryType.CHECK_ENTRY.getEntryTypeCategoricalId()); final Set<Integer> result = augmentedRandomizedBlockDesignServiceImpl.getEntryIdsOfTestEntries(importedGermplasmList); Assert.assertEquals("There should be 8 test entries in the list", 8, result.size()); Assert.assertTrue(!result.contains(1)); Assert.assertTrue(!result.contains(3)); }</code><technical_language>0 1 constants. FIRST_CHECK_ENTRY, THIRD_CHECK_ENTRY</technical_language>

Target:
public void testGetEntryIdsOfTestEntries() { final List<ImportedGermplasm> importedGermplasmList = createImportedGermplasmList(); importedGermplasmList.get(FIRST_CHECK_ENTRY).setEntryTypeCategoricalID(SystemDefinedEntryType.CHECK_ENTRY.getEntryTypeCategoricalId()); importedGermplasmList.get(THIRD_CHECK_ENTRY).setEntryTypeCategoricalID(SystemDefinedEntryType.CHECK_ENTRY.getEntryTypeCategoricalId()); final Set<Integer> result = augmentedRandomizedBlockDesignServiceImpl.getEntryIdsOfTestEntries(importedGermplasmList); Assert.assertEquals("There should be 8 test entries in the list", 8, result.size()); Assert.assertTrue(!result.contains(1)); Assert.assertTrue(!result.contains(3)); }
Source:
<code>protected void updateNotify(long sequence) { Object[] refs = null; try { if(PlatformAggregatorProvider.getPlatformAggregator() != null){ refs = PlatformAggregatorProvider.getPlatformAggregator().getServiceReferences(IOptionsListener.class.getName(),"(name=" + registrationName + ")"); if (refs != null) { for (Object ref : refs) { IOptionsListener listener = (IOptionsListener)PlatformAggregatorProvider.getPlatformAggregator().getService(ref); if (listener != null) { try { listener.optionsUpdated(this, sequence); } catch (Throwable ignore) { } finally { PlatformAggregatorProvider.getPlatformAggregator().ungetService(ref); } } } } } <START> } catch (Exception e) { <END> if (log.isLoggable(Level.SEVERE)) { log.log(Level.SEVERE, e.getMessage(), e); } } }</code><technical_language>this a typed exception (e.g. PlatformServicesException)</technical_language>

Target:
protected void updateNotify (long sequence) { Object[] refs = null; try { if(aggregator != null && aggregator.getPlatformServices() != null){ refs = aggregator.getPlatformServices().getServiceReferences(IOptionsListener.class.getName(),"(name=" + registrationName + ")"); if (refs != null) { for (Object ref : refs) { IOptionsListener listener = (IOptionsListener)aggregator.getPlatformServices().getService(ref); if (listener != null) { try { listener.optionsUpdated(this, sequence); } catch (Throwable ignore) { } finally { aggregator.getPlatformServices().ungetService(ref); } } } } } } catch (PlatformServicesException e) { if (log.isLoggable(Level.SEVERE)) { log.log(Level.SEVERE, e.getMessage(), e); } } }
Source:
<code>private String doResolvePath(final String nodePath, final String parameterReference) { if (".".equals(parameterReference)) { return nodePath; } if (parameterReference.startsWith("..")) { String current = nodePath; String ref = parameterReference; while (ref.startsWith("..")) { final int lastDot = current.lastIndexOf('.'); if (lastDot < 0) { <START> return null; END> } current = current.substring(0, lastDot); ref = ref.substring(2 ); if (ref.startsWith("/")) { ref = ref.substring(1); } } return current + (!ref.isEmpty() ? "." : "") + ref.replace('/', '.'); } if (parameterReference.startsWith(".") || parameterReference.startsWith("./")) { return nodePath + '.' + parameterReference.replaceFirst("\\./?", "").replace('/', '.'); } return parameterReference; }</code><technical_language>is worth change return type Optional<String> return Optional.empty() here. This force implement "null check" in client code</technical_language>

Target:
private Optional<String> doResolvePath(final String nodePath, final String parameterReference) { if (".".equals(parameterReference)) { return Optional.of(nodePath); } if (parameterReference.startsWith("..")) { String current = nodePath; String ref = parameterReference; while (ref.startsWith("..")) { final int lastDot = current.lastIndexOf('.'); if (lastDot < 0) { return Optional.empty(); } current = current.substring(0, lastDot); ref = ref.substring(2 ); if (ref.startsWith("/")) { ref = ref.substring(1); } } return Optional.of(current + (!ref.isEmpty() ? "." : "") + ref.replace('/', '.')); } if (parameterReference.startsWith(".") || parameterReference.startsWith("./")) { return Optional.of(nodePath + '.' + parameterReference.replaceFirst("\\./?", "").replace('/', '.')); } return Optional.of(parameterReference); }
Source:
<code><START> @Override public boolean trackVmHostChange() { <END> return true; }</code><technical_language>format stuff: annotations moved line method's firm class</technical_language>

Target:
public boolean trackVmHostChange() { return true; }
Source:
<code>public void visitCatchBlock(CatchBlockTree tree) { complexity.addComplexityWithNesting(tree.catchToken()); <START> complexity.incNesting(); <END> super.visitCatchBlock(tree); complexity.decNesting(); }</code><technical_language>This a perfect case for FP, I propose remove this duplication a wrapper in CognitiveComplexity : public void nestAndDo(Runnable action) { level++; action.run(); level--;} replace calls complexity.nestAndDo(() -> super.visitCatchBlock(tree));</technical_language>

Target:
public void visitCatchBlock(CatchBlockTree tree) { complexity.addComplexityWithNesting(tree.catchToken()); visitWithNesting(()-> super.visitCatchBlock(tree)); }
Source:
<code>public void testReportingBuckets() throws Exception { createIndex("test"); LatencyStatsAction.LatencyStatsNodesResponse statsResponse = client().prepareExecute(LatencyStatsAction.INSTANCE).execute().get(); statsResponse.getNodes().stream().map(n -> n.statDetails).forEach(stat -> assertEquals(0, stat.getLatencies().size())); LatencyStatsAction.StatDetails allNodes = statsResponse.getAllNodes(); assertEquals(0, allNodes.getLatencies().size()); SearchRequestBuilder builder = client().prepareSearch("test").setQuery(new MatchAllQueryBuilder()) .setStats("integration"); client().search(builder.request()).get(); Thread.sleep(5200); statsResponse = client().prepareExecute(LatencyStatsAction.INSTANCE).execute().get(); assertEquals(4, statsResponse.getAllNodes().getLatencies().size()); statsResponse.getAllNodes().getLatencies().stream().forEach(stat -> assertEquals("integration", stat.getBucket())); assertNotEquals(0, statsResponse.getNodes().stream() .map(n -> n.statDetails) .filter(stat -> stat.getLatencies().size() > 0).count()); statsResponse.getNodes().stream() .flatMap(n -> n.statDetails.getLatencies().stream()) .forEach(stat -> assertEquals("integration", stat.getBucket())); }</code><technical_language>this need REST api test framework is a pain run elastic gradle tools</technical_language>

Target:
public void testReportingBuckets() throws Exception { createIndex("test"); LatencyStatsAction.LatencyStatsNodesResponse statsResponse = client().prepareExecute(LatencyStatsAction.INSTANCE).execute().get(); statsResponse.getNodes().stream() .map(n -> n.statDetails) .forEach(stat -> assertEquals(0, stat.getLatencies().size())); LatencyStatsAction.StatDetails allNodes = statsResponse.getAllNodes(); assertEquals(0, allNodes.getLatencies().size()); SearchRequestBuilder builder = client() .prepareSearch("test") .setQuery(new MatchAllQueryBuilder()) .setStats("integration"); client().search(builder.request()).get(); Thread.sleep(5200); statsResponse = client().prepareExecute(LatencyStatsAction.INSTANCE).execute().get(); assertEquals(4, statsResponse.getAllNodes().getLatencies().size()); statsResponse.getAllNodes().getLatencies() .forEach(stat -> assertEquals("integration", stat.getBucket())); assertNotEquals(0, statsResponse.getNodes().stream() .map(n -> n.statDetails) .filter(stat -> stat.getLatencies().size() > 0) .count()); statsResponse.getNodes().stream() .flatMap(n -> n.statDetails.getLatencies().stream()) .forEach(stat -> assertEquals("integration", stat.getBucket())); }
Source:
<code>private void checkConnectorPort() { if (null != connector) { int cp = ((ServerConnector)connector).getPort(); if (port != cp) { <START> throw new IllegalStateException("Error: Connector port " + cp + " does not match" <END> + " with the server engine port " + port); } } }</code><technical_language>UncheckedIOException replacement for IOException</technical_language>

Target:
private void checkConnectorPort() { if (null != connector) { int cp = ((ServerConnector)connector).getPort(); if (port != cp) { throw new UncheckedIOException(new IOException("Error: Connector port " + cp + " does not match" + " with the server engine port " + port)); } } }
Source:
<code>@Override protected void afterTest() throws Exception { super.afterTest(); <START> indexingDisabled = false; <END> }</code><technical_language>return of GridQueryProcessor.idxCls null (in case startGrid fails)</technical_language>

Target:
@Override protected void afterTest() throws Exception { super.afterTest(); indexingDisabled = false; GridQueryProcessor.idxCls = null; }
Source:
<code>public void updateCollisionFormulasToNewVersion() { for (Script script : getScriptList()) { Brick scriptBrick = script.getScriptBrick(); if (scriptBrick instanceof FormulaBrick) { FormulaBrick formulaBrick = (FormulaBrick) scriptBrick; for (Formula formula : formulaBrick.getFormulas()) { formula.updateCollisionFormulasToNewVersion(); } } for (Brick brick : script.getBrickList()) { if (brick instanceof UserBrick) { UserBrick formulaBrick = (UserBrick) brick; for (Formula formula : formulaBrick.getFormulas()) { formula.updateCollisionFormulasToNewVersion(); } } <START> if (brick instanceof FormulaBrick) { <END> FormulaBrick formulaBrick = (FormulaBrick) brick; for (Formula formula : formulaBrick.getFormulas()) { formula.updateCollisionFormulasToNewVersion(); } } } } }</code><technical_language>This "else if"</technical_language>

Target:
public void updateCollisionFormulasToNewVersion() { for (Script script : getScriptList()) { Brick scriptBrick = script.getScriptBrick(); if (scriptBrick instanceof FormulaBrick) { FormulaBrick formulaBrick = (FormulaBrick) scriptBrick; for (Formula formula : formulaBrick.getFormulas()) { formula.updateCollisionFormulasToNewVersion(); } } for (Brick brick : script.getBrickList()) { if (brick instanceof UserBrick) { UserBrick formulaBrick = (UserBrick) brick; for (Formula formula : formulaBrick.getFormulas()) { formula.updateCollisionFormulasToNewVersion(); } } else if (brick instanceof FormulaBrick) { FormulaBrick formulaBrick = (FormulaBrick) brick; for (Formula formula : formulaBrick.getFormulas()) { formula.updateCollisionFormulasToNewVersion(); } } } } }
Source:
<code>private void deliverPendingReports() { lock.lock(); try { File outDir = new File(reportDirectory); if (outDir.exists()) { File[] fileList = outDir.listFiles(); if (fileList != null) { for (final File file : fileList) { deliverReportAtPath(file.getAbsolutePath()); } } } else { warn("Report directory does not exist, cannot read pending reports"); } } catch (Exception ex) { warn("Failed to parse/write pending reports: " + ex); } <START> lock.unlock(); <END> }</code><technical_language>general recommendation for unlocking (and cleaning closeables) is do a finally clause</technical_language>

Target:
private void deliverPendingReports() { lock.lock(); try { File outDir = new File(reportDirectory); if (outDir.exists()) { File[] fileList = outDir.listFiles(); if (fileList != null) { for (final File file : fileList) { deliverReportAtPath(file.getAbsolutePath()); } } } else { warn("Report directory does not exist, cannot read pending reports"); } } catch (Exception ex) { warn("Failed to parse/write pending reports: " + ex); } finally { lock.unlock(); } }
Source:
<code>boolean containsStops(JSONObject jsonObject) { Boolean hasStops = false; Set<?> keySet = jsonObject.keySet(); Iterator<?> keys = keySet.iterator(); while (keys.hasNext()) { String key = (String) keys.next(); if (jsonObject.get(key) instanceof JSONObject) { JSONObject child = (JSONObject) jsonObject.get(key); <START> if (child.containsKey("stops") && ((JSONArray)((JSONArray)child.get("stops")).get(0)).get(0) instanceof JSONObject) { <END> hasStops = true; } } } return hasStops; }</code><technical_language>This brittle, possibly wrong. of examples "stops": [ [10000, "red"], [100000, "blue"], [1000000, "green"], [1000000000, "black"] ] stops.get(0) = [10000, "red"] stops.get(0).get(0) = 10000, a number, a JSONObject. If want do more checks, do some instanceof JSONArray checks too, blindly casting</technical_language>

Target:
boolean containsStops(JSONObject jsonObject) { Boolean hasStops = false; Set<?> keySet = jsonObject.keySet(); Iterator<?> keys = keySet.iterator(); while (keys.hasNext()) { String key = (String) keys.next(); if (jsonObject.get(key) instanceof JSONObject) { JSONObject child = (JSONObject) jsonObject.get(key); if (child.containsKey("stops")) { if (!child.containsKey("property")) { hasStops = true; } else if (child.get("stops") instanceof JSONArray) { JSONArray stops = (JSONArray) child.get("stops"); if (stops.get(0) instanceof JSONObject && ((JSONObject)stops.get(0)).containsKey("zoom")) { hasStops = true; } } } } } return hasStops; }
Source:
<code>public void start(Listener<RespT> listener, Metadata metadata) { ClientCall<ReqT, RespT> call = delegate(); synchronized (lock) { Preconditions.checkState(state == null, "Already started"); <START> state = (pendingCount == 0) ? State.IDLE : State.WAITING; <END> lastActivityAt = clock.currentTimeMillis(); } openStreams.put(this, PRESENT); call.start(new SimpleForwardingClientCallListener<RespT>(listener) { @Override public void onMessage(RespT message) { synchronized (lock) { state = State.DELIVERING; } try { super.onMessage(message); } finally { synchronized (lock) { pendingCount--; lastActivityAt = clock.currentTimeMillis(); state = (pendingCount > 0) ? State.WAITING : State.IDLE; } } } @Override public void onClose(Status status, Metadata trailers) { openStreams.remove(WatchedCall.this); if (status.getCause() instanceof StreamWaitTimeoutException) { status = Status.ABORTED .withDescription(status.getDescription()) .withCause(status.getCause()); } super.onClose(status, trailers); } }, metadata); }</code><technical_language>I request(n) called start()</technical_language>

Target:
public void start(Listener<RespT> listener, Metadata metadata) { ClientCall<ReqT, RespT> call = delegate(); synchronized (lock) { Preconditions.checkState(state == null, "Already started"); lastActivityAt = clock.currentTimeMillis(); } openStreams.put(this, PRESENT); call.start(new SimpleForwardingClientCallListener<RespT>(listener) { @Override public void onMessage(RespT message) { synchronized (lock) { state = State.DELIVERING; } try { super.onMessage(message); } finally { synchronized (lock) { pendingCount--; lastActivityAt = clock.currentTimeMillis(); state = (pendingCount > 0) ? State.WAITING : State.IDLE; } } } @Override public void onClose(Status status, Metadata trailers) { openStreams.remove(WatchedCall.this); super.onClose(status, trailers); } }, metadata); }
Source:
<code>View findScrollingChild(View view) { if (ViewCompat.isNestedScrollingEnabled(view)) { return view; } if (view instanceof ViewPager2) { <START> ViewPager2 viewPager = (ViewPager2) view; View currentViewPagerChild = viewPager.getChildAt(viewPager.getCurrentItem()); <END> if (currentViewPagerChild != null) { return findScrollingChild(currentViewPagerChild); } } else if (view instanceof ViewGroup) { ViewGroup group = (ViewGroup) view; for (int i = 0, count = group.getChildCount(); i < count; i++) { View scrollingChild = findScrollingChild(group.getChildAt(i)); if (scrollingChild != null) { return scrollingChild; } } } return null; }</code><technical_language>changes, is longer scroll in chapters list shownotes list (because time scrolling up, slide-up sheet is closed). helps. recycler.findViewHolderForAdapterPosition, longer need rely setOffscreenPageLimit. I happy getChildAt(0), another idea that, (IDs?). suggestion ViewPager2 viewPager = (ViewPager2) view; RecyclerView recycler = (RecyclerView) viewPager.getChildAt(0); View currentViewPagerChild = recycler.getChildAt(viewPager.getCurrentItem());</technical_language>

Target:
View findScrollingChild(View view) { if (ViewCompat.isNestedScrollingEnabled(view)) { return view; } if (view instanceof ViewPager2) { ViewPager2 viewPager = (ViewPager2) view; RecyclerView recycler = (RecyclerView) viewPager.getChildAt(0); View currentViewPagerChild = recycler.getChildAt(viewPager.getCurrentItem()); if (currentViewPagerChild != null) { return findScrollingChild(currentViewPagerChild); } } else if (view instanceof ViewGroup) { ViewGroup group = (ViewGroup) view; for (int i = 0, count = group.getChildCount(); i < count; i++) { View scrollingChild = findScrollingChild(group.getChildAt(i)); if (scrollingChild != null) { return scrollingChild; } } } return null; }
Source:
<code>public final void setPath(final String location) { <START> AudioPlayer.path = location; <END> }</code><technical_language>path is set a path? initializeTune(path) called setting path? <logic</technical_language>

Target:
public final void setPath(final String location) { path = location; initializeTune(path); }
Source:
<code>public void tsv_entriesAreEscaped() { TsvEntity csvEntity = new TsvEntity(); Map jsonMap = ImmutableMap.of( "hash", "hash1", "entry", ImmutableMap.of( "key1", "value1", "key2", "val\tue2", "key3", "val\"ue3", "key4", "val\nue4" ) ); JsonNode node = JsonObjectMapper.convert(jsonMap, JsonNode.class); AbstractView view = new SingleResultView("someTemplate", node); Object result = csvEntity.convert(view); <START> assertThat(result.toString(), equalTo("hash\tkey1\tkey2\tkey3\tkey4\nhash1\tvalue1\t\"val\tue2\"\t\"val\"\"ue3\"\t\"val\nue4\"")); <END> }</code><technical_language>a uneasy supporting newlines in data in tsv -- of benefits of tsv is fits tools cut(1) awk(1); this breaks data newlines</technical_language>

Target:
public void tsv_entriesAreEscaped() { TsvEntity csvEntity = new TsvEntity(); Map jsonMap = ImmutableMap.of( "hash", "hash1", "entry", ImmutableMap.of( "key1", "value1", "key2", "val\tue2", "key3", "val\"ue3", "key4", "val\nue4" ) ); JsonNode node = JsonObjectMapper.convert(jsonMap, JsonNode.class); AbstractView view = new SingleResultView("someTemplate", node); Object result = csvEntity.convert(view); assertThat(result.toString(), equalTo("hash\tkey1\tkey2\tkey3\tkey4\r\nhash1\tvalue1\t\"val\tue2\"\t\"val\"\"ue3\"\t\"val\nue4\"")); }
Source:
<code>public int compareTo(PickerMilestone milestone) { if (isHighlighted) return -1; if (milestone.isHighlighted()) return 1; if (this.getDueDate().equals(milestone.getDueDate())) return 0; if (this.isOpen() != milestone.isOpen()) { return this.isOpen() ? -1 : 1; } if (!this.getDueDate().isPresent()) return -1; if (!milestone.getDueDate().isPresent()) return 1; return this.getDueDate().get() <START> .isAfter(milestone.getDueDate().get()) ? -1 : 1; <END> }</code><technical_language>Milestone a compareTo method? In case, is logic duplicated</technical_language>

Target:
public int compareTo(PickerMilestone milestone) { if (isSelected != milestone.isSelected()) { return isSelected ? -1 : 1; } if (this.isOpen() != milestone.isOpen()) { return this.isOpen() ? -1 : 1; } if (this.getDueDate().equals(milestone.getDueDate())) return 0; if (!this.getDueDate().isPresent()) return 1; if (!milestone.getDueDate().isPresent()) return -1; return this.getDueDate().get() .isBefore(milestone.getDueDate().get()) ? -1 : 1; }
Source:
<code>public Iterable<VirtualMachine> listNodes() { ImmutableList.Builder<VirtualMachine> nodes = builder(); <START> for (final String location : regionIds.get()) { <END> nodes.addAll(api.getVirtualMachineApi(null).listByLocation(location)); } return nodes.build(); }</code><technical_language>If regionIds is empty (no region constraint) this return nodes. currently returns nothing</technical_language>

Target:
public Iterable<VirtualMachine> listNodes() { ImmutableList.Builder<VirtualMachine> nodes = builder(); if (regionIds.get().isEmpty()) { nodes.addAll(api.getVirtualMachineApi(null).listAll()); } else { for (final String location : regionIds.get()) { nodes.addAll(api.getVirtualMachineApi(null).listByLocation(location)); } } return nodes.build(); }
Source:
<code>protected final void removeGroup(String groupName, EnumSet<Flag> explicitFlags, ClassLoader explicitClassLoader) { final Transaction tx = suspendOngoingTransactionIfExists(); try { Set<K> keys = getGroup(groupName, explicitFlags, explicitClassLoader); tryBegin(); try { InvocationContext context = getInvocationContextWithImplicitTransaction(false, explicitClassLoader, keys.size()); for (K key : keys) { <START> removeInternal(key, explicitFlags, context); <END> } tryCommit(); } catch (RuntimeException e) { tryRollback(); throw e; } } finally { resumePreviousOngoingTransaction(tx, false, "Error while trying to resume a transaction after removeGroup()"); } }</code><technical_language>Thinking put a IGNORE_RETURN_VALUES flag for this. return previous values caller, more performant</technical_language>

Target:
protected final void removeGroup(String groupName, EnumSet<Flag> explicitFlags, ClassLoader explicitClassLoader) { if (transactionManager == null) { nonTransactionalRemoveGroup(groupName, explicitFlags, explicitClassLoader); } else { transactionalRemoveGroup(groupName, explicitFlags, explicitClassLoader); } }
Source:
<code>private void dispatchAssignmentChangeIfNeeded(String connectorType, DatastreamContext context, Map<String, List<DatastreamTask>> currentAssignment) { if (!_allStreamsByConnectorType.containsKey(connectorType)) { _connectors.get(connectorType).onAssignmentChange(context, currentAssignment.get(connectorType)); } else if (_allStreamsByConnectorType.get(connectorType).size() != currentAssignment.get(connectorType).size()) { _connectors.get(connectorType).onAssignmentChange(context, currentAssignment.get(connectorType)); } else { List<DatastreamTask> oldList = _allStreamsByConnectorType.get(connectorType); List<DatastreamTask> newList = currentAssignment.get(connectorType); <START> List<DatastreamTask> diffList1 = new ArrayList<>(oldList); <END> List<DatastreamTask> diffList2 = new ArrayList<>(newList); diffList1.removeAll(newList); diffList2.removeAll(oldList); if(diffList1.size() > 0 || diffList2.size() > 0) { _connectors.get(connectorType).onAssignmentChange(context, currentAssignment.get(connectorType)); } } }</code><technical_language>I Set/HashSet faster ArrayList, assuming assignment big road</technical_language>

Target:
private void dispatchAssignmentChangeIfNeeded(String connectorType, DatastreamContext context, Map<String, List<DatastreamTask>> currentAssignment) { if (!_allStreamsByConnectorType.containsKey(connectorType)) { _connectors.get(connectorType).onAssignmentChange(context, currentAssignment.get(connectorType)); } else if (_allStreamsByConnectorType.get(connectorType).size() != currentAssignment.get(connectorType).size()) { _connectors.get(connectorType).onAssignmentChange(context, currentAssignment.get(connectorType)); } else { Set<DatastreamTask> oldSet = new HashSet<>(_allStreamsByConnectorType.get(connectorType)); Set<DatastreamTask> newSet = new HashSet<>(currentAssignment.get(connectorType)); Set<DatastreamTask> diffList1 = new HashSet<>(oldSet); Set<DatastreamTask> diffList2 = new HashSet<>(newSet); diffList1.removeAll(newSet); diffList2.removeAll(oldSet); if(diffList1.size() > 0 || diffList2.size() > 0) { _connectors.get(connectorType).onAssignmentChange(context, currentAssignment.get(connectorType)); } } }
Source:
<code>public void setup() { ctx = new SessionContext(); headers = new Headers(); headers.add("lah", "deda"); params = new HttpQueryParams(); params.add("k1", "v1"); request = new HttpRequestMessageImpl(ctx, "HTTP/1.1", "post", "/some/where", <START> params, headers, "9.9.9.9", "https", 80, "localhost",new InetSocketAddress("api.netflix.com", 443)); <END> request.setBodyAsText("some text"); request.storeInboundRequest(); response = new HttpResponseMessageImpl(ctx, headers, request, 200); response.setBodyAsText("response text"); }</code><technical_language>This is ideal, do a DNS lookup part of test, making possibly more flaky, slower</technical_language>

Target:
public void setup() { ctx = new SessionContext(); headers = new Headers(); headers.add("lah", "deda"); params = new HttpQueryParams(); params.add("k1", "v1"); request = new HttpRequestMessageImpl(ctx, "HTTP/1.1", "post", "/some/where", params, headers, "9.9.9.9", "https", 80, "localhost", new SocketAddress() {}); request.setBodyAsText("some text"); request.storeInboundRequest(); response = new HttpResponseMessageImpl(ctx, headers, request, 200); response.setBodyAsText("response text"); }
Source:
<code>public List<Index> listIndexes() throws QueryException { try { return dbQueue.submit(new ListIndexesCallable()).get(); } catch (InterruptedException e) { <START> String msg = "Failed to list indexes"; <END> logger.log(Level.SEVERE, msg, e); throw new QueryException(msg, e); } catch (ExecutionException e) { String msg = "Failed to list indexes"; logger.log(Level.SEVERE, msg, e); throw new QueryException(msg, e); } }</code><technical_language>Thoughts putting log messages in a Utils class</technical_language>

Target:
public List<Index> listIndexes() throws QueryException { try { return DatabaseImpl.get(dbQueue.submit(new ListIndexesCallable())); } catch (ExecutionException e) { String msg = "Failed to list indexes"; logger.log(Level.SEVERE, msg, e); throw new QueryException(msg, e); } }
Source:
<code>protected void fillMacAddressIfMissing(VmNic iface) { <START> final MacPoolManagerStrategy pool = getMacPool(); <END> if (StringUtils.isEmpty(iface.getMacAddress()) && (pool.getAvailableMacsCount() >= 1)) { iface.setMacAddress(pool.allocateNewMac()); } }</code><technical_language>need extract variable</technical_language>

Target:
protected void fillMacAddressIfMissing(VmNic iface) { if (StringUtils.isEmpty(iface.getMacAddress()) && (getMacPool().getAvailableMacsCount() >= 1)) { iface.setMacAddress(getMacPool().allocateNewMac()); } }
Source:
<code>public String getDisplayName() { <START> return "Build GitHub pull request"; <END> }</code><technical_language>this changed</technical_language>

Target:
public String getDisplayName() { return "Build GitHub pull requests"; }
Source:
<code>public void before() { when(source.getBeanNameGenerator()).thenReturn( <START> new RepositoryBeanNameGenerator(Thread.currentThread().getContextClassLoader()) <END> ); }</code><technical_language>reason this getClass().getClassLoader()</technical_language>

Target:
public void before() { RepositoryBeanNameGenerator generator = new RepositoryBeanNameGenerator(getClass().getClassLoader()); Answer<Object> answer = invocation -> generator.generateBeanName((BeanDefinition) invocation.getArguments()[0]); when(source.generateBeanName(Mockito.any(BeanDefinition.class))).then(answer); }
Source:
<code>public void onLiquidFlow(BlockFromToEvent e) { Block block = e.getToBlock(); <START> Material type = block.getType(); <END> if (SlimefunTag.FLUID_SENSITIVE_MATERIALS.isTagged(block.getType())) { if (BlockStorage.hasBlockInfo(block)) { e.setCancelled(true); } else { Location loc = block.getLocation(); if (SlimefunPlugin.getTickerTask().isReserved(loc)) { e.setCancelled(true); } } } }</code><technical_language>variable is</technical_language>

Target:
public void onLiquidFlow(BlockFromToEvent e) { Block block = e.getToBlock(); Material type = block.getType(); if (SlimefunTag.FLUID_SENSITIVE_MATERIALS.isTagged(type)) { if (BlockStorage.hasBlockInfo(block)) { e.setCancelled(true); } else { Location loc = block.getLocation(); if (SlimefunPlugin.getTickerTask().isReserved(loc)) { e.setCancelled(true); } } } }
Source:
<code>public void testNotifyAsyncMetadata() throws Exception { MetaData metaData = new MetaData(); metaData.addToTab("animals", "dog", true); client.notify(new RuntimeException("Foo"), metaData); <START> apiClient.awaitReport(); <END> assertNotNull(apiClient.report); MetaData data = apiClient.report.getError().getMetaData(); assertTrue((Boolean) data.getTab("animals").get("dog")); }</code><technical_language>testing purpose of Async functionality i.e. call client.notify is non-blocking anywhere</technical_language>

Target:
public void testNotifyAsyncMetadata() throws Exception { MetaData metaData = new MetaData(); metaData.addToTab("animals", "dog", true); client.notify(new RuntimeException("Foo"), metaData); assertNull(apiClient.report); apiClient.awaitReport(); assertNotNull(apiClient.report); MetaData data = apiClient.report.getError().getMetaData(); assertTrue((Boolean) data.getTab("animals").get("dog")); }
Source:
<code><START> @Override <END> protected Map<String, Pair<String, String>> getExclusiveLocks() { final LockMessage lockMessage = createLockMessage(); return templatesLockedForUpdate.stream() .collect(Collectors.toMap( template -> template.getId().toString(), template -> LockMessagesMatchUtil.makeLockingPair(LockingGroup.TEMPLATE, lockMessage))); }</code><technical_language>please put @Override annotation line</technical_language>

Target:
protected Map<String, Pair<String, String>> getExclusiveLocks() { final LockMessage lockMessage = createLockMessage(); return templatesLockedForUpdate.stream() .collect(Collectors.toMap( template -> template.getId().toString(), template -> LockMessagesMatchUtil.makeLockingPair(LockingGroup.TEMPLATE, lockMessage))); }