auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testTopologicalSort() { List<ProcessorNode> sortedNodes1 = graph1.topologicalSort(); Map<String, Integer> idxMap1 = new HashMap<>(); for (int i = 0; i < sortedNodes1.size(); i++) { idxMap1.put(sortedNodes1.get(i).getId(), i); } assertTrue(idxMap1.size() == 8); assertTrue(idxMap1.get("11") > idxMap1.get("5")); assertTrue(idxMap1.get("11") > idxMap1.get("7")); assertTrue(idxMap1.get("8") > idxMap1.get("7")); assertTrue(idxMap1.get("8") > idxMap1.get("3")); assertTrue(idxMap1.get("2") > idxMap1.get("11")); assertTrue(idxMap1.get("9") > idxMap1.get("8")); assertTrue(idxMap1.get("9") > idxMap1.get("11")); assertTrue(idxMap1.get("10") > idxMap1.get("11")); assertTrue(idxMap1.get("10") > idxMap1.get("3")); List<ProcessorNode> sortedNodes2 = graph2.topologicalSort(); Map<String, Integer> idxMap2 = new HashMap<>(); for (int i = 0; i < sortedNodes2.size(); i++) { idxMap2.put(sortedNodes2.get(i).getId(), i); } assertTrue(idxMap2.size() == 7); assertTrue(idxMap2.get("2") > idxMap2.get("1")); assertTrue(idxMap2.get("3") > idxMap2.get("1")); assertTrue(idxMap2.get("4") > idxMap2.get("1")); assertTrue(idxMap2.get("6") > idxMap2.get("1")); assertTrue(idxMap2.get("5") > idxMap2.get("4")); assertTrue(idxMap2.get("7") > idxMap2.get("5")); <START> List<ProcessorNode> sortedNodes3 = graph3.topologicalSort(); <END> assertTrue(sortedNodes3.size() == 1); }</code><technical_language>This test proves new conditional "if (pNodes.size() == 1)" works, is another test validate visited node tracking is correct</technical_language>

Target:
public void testTopologicalSort() { List<ProcessorNode> sortedNodes1 = graph1.topologicalSort(); Map<String, Integer> idxMap1 = new HashMap<>(); for (int i = 0; i < sortedNodes1.size(); i++) { idxMap1.put(sortedNodes1.get(i).getId(), i); } assertTrue(idxMap1.size() == 8); assertTrue(idxMap1.get("11") > idxMap1.get("5")); assertTrue(idxMap1.get("11") > idxMap1.get("7")); assertTrue(idxMap1.get("8") > idxMap1.get("7")); assertTrue(idxMap1.get("8") > idxMap1.get("3")); assertTrue(idxMap1.get("2") > idxMap1.get("11")); assertTrue(idxMap1.get("9") > idxMap1.get("8")); assertTrue(idxMap1.get("9") > idxMap1.get("11")); assertTrue(idxMap1.get("10") > idxMap1.get("11")); assertTrue(idxMap1.get("10") > idxMap1.get("3")); List<ProcessorNode> sortedNodes2 = graph2.topologicalSort(); Map<String, Integer> idxMap2 = new HashMap<>(); for (int i = 0; i < sortedNodes2.size(); i++) { idxMap2.put(sortedNodes2.get(i).getId(), i); } assertTrue(idxMap2.size() == 7); assertTrue(idxMap2.get("2") > idxMap2.get("1")); assertTrue(idxMap2.get("3") > idxMap2.get("1")); assertTrue(idxMap2.get("4") > idxMap2.get("1")); assertTrue(idxMap2.get("6") > idxMap2.get("1")); assertTrue(idxMap2.get("5") > idxMap2.get("4")); assertTrue(idxMap2.get("7") > idxMap2.get("5")); List<ProcessorNode> sortedNodes3 = graph3.topologicalSort(); assertTrue(sortedNodes3.size() == 2); assertEquals(sortedNodes3.get(0).getId(), "1"); assertEquals(sortedNodes3.get(1).getId(), "2"); List<ProcessorNode> sortedNodes4 = graph4.topologicalSort(); assertTrue(sortedNodes4.size() == 1); assertEquals(sortedNodes4.get(0).getId(), "1"); }
Source:
<code>void decrement() { <START> set(get() - 1); <END> }</code><technical_language>assert get() > 0</technical_language>

Target:
void decrement() { int val = get(); assert val > 0; set(val - 1); }
Source:
<code>public long srem( ByteArrayWrapper key, ArrayList<ByteArrayWrapper> membersToRemove, AtomicBoolean setWasDeleted) { RedisSet redisSet = get(key); long l = redisSet.srem(key, membersToRemove, setWasDeleted); <START> if (get(key).scard(key) == 0) { <END> region.remove(key); } else { region.put(key, get(key)); } return l; }</code><technical_language>change "get(key)" "redisSet"</technical_language>

Target:
public long srem( ByteArrayWrapper key, ArrayList<ByteArrayWrapper> membersToRemove, AtomicBoolean setWasDeleted) { return getRedisSet(key).srem(membersToRemove, region, key, setWasDeleted); }
Source:
<code><START> public String getProtectedEnvironmentVariables() { <END> return protectedEnvironmentVariables; }</code><technical_language>Add CheckForNull. if null is passed UI, this field null build wrapper is loaded disk for existing jobs</technical_language>

Target:
public String getProtectedEnvironmentVariables() { if (protectedEnvironmentVariables == null) { return ""; } return protectedEnvironmentVariables; }
Source:
<code>public String getQuery(String action, Class<?> clazz, boolean extended) { String queryName; if (action.equals(ACTION_SELECT_ALL)) { queryName = "database.select" + clazz.getSimpleName() + "s"; } else { <START> queryName = "database." + action.toLowerCase() + clazz.getSimpleName() + (extended ? "Extended" : ""); <END> } String query = config.getString(queryName); if (query == null) { query = constructObjectQuery(action, clazz, extended); config.setString(queryName, query); } return query; }</code><technical_language>I split extended check a new line a regular if statement</technical_language>

Target:
public String getQuery(String action, Class<?> clazz, boolean extended) { String queryName; if (action.equals(ACTION_SELECT_ALL)) { queryName = "database.select" + clazz.getSimpleName() + "s"; } else { queryName = "database." + action.toLowerCase() + clazz.getSimpleName(); if (extended) { queryName += "Extended"; } } String query = config.getString(queryName); if (query == null) { query = constructObjectQuery(action, clazz, extended); config.setString(queryName, query); } return query; }
Source:
<code><START> public String getSystemOffsetDefault(String systemName) { <END> String perSystemResetValue = get(String.format("systems.%s.default.stream.samza.offset.default", systemName)); if (StringUtils.isBlank(perSystemResetValue)) { perSystemResetValue = get(String.format("systems.%s.samza.offset.default", systemName)); if (StringUtils.isBlank(perSystemResetValue)) { return SAMZA_SYSTEM_OFFSET_UPCOMING; } } return perSystemResetValue; }</code><technical_language>getDefaultSystemOffset exists in SystemConfig. remove that</technical_language>

Target:
public String getSystemOffsetDefault(String systemName) { String systemOffsetDefault = get(String.format("systems.%s.default.stream.samza.offset.default", systemName)); if (StringUtils.isBlank(systemOffsetDefault)) { systemOffsetDefault = get(String.format("systems.%s.samza.offset.default", systemName)); if (StringUtils.isBlank(systemOffsetDefault)) { return SAMZA_SYSTEM_OFFSET_UPCOMING; } } return systemOffsetDefault; }
Source:
<code>public FbStatus(final int code, final Scalar<Fallback> fallback) { this( new Filtered<Integer>( <START> (status) -> { <END> return code == status.intValue(); }, code ), fallback ); }</code><technical_language>@paulodamaso braces return needed</technical_language>

Target:
public FbStatus(final int code, final Scalar<Fallback> fallback) { this( new Filtered<Integer>( (status) -> code == status.intValue(), code ), fallback ); }
Source:
<code>public RegistryAuth authFor(final String imageName) throws DockerException { if (!configFileExists()) { return null; } final ImageRef ref = new ImageRef(imageName); try { final RegistryAuth registryAuth = reader.fromConfig(path, ref.getRegistryUrl()); if (registryAuth != null) { return registryAuth; } return reader.fromConfig(path, ref.getRegistryName()); } catch (IllegalArgumentException e) { log.debug("Failed first attempt to find auth for {}", ref.getRegistryUrl(), e); try { return reader.fromConfig(path, ref.getRegistryName()); } catch (IllegalArgumentException | IOException e2) { <START> throw new DockerException(e2); <END> } } catch (IOException e) { throw new DockerException(e); } }</code><technical_language>this throw exception, other code paths call authFor(image) expect a null response if config file / supplier authentication info for image name. necessarily error RegistryAuth info for a image</technical_language>

Target:
public RegistryAuth authFor(final String imageName) throws DockerException { if (!configFileExists()) { return null; } final ImageRef ref = new ImageRef(imageName); try { final RegistryAuth registryAuth = reader.fromConfig(path, ref.getRegistryUrl()); if (registryAuth != null) { return registryAuth; } return reader.fromConfig(path, ref.getRegistryName()); } catch (IllegalArgumentException e) { log.debug("Failed first attempt to find auth for {}", ref.getRegistryUrl(), e); try { return reader.fromConfig(path, ref.getRegistryName()); } catch (IllegalArgumentException e2) { log.debug("Failed second attempt to find auth for {}", ref.getRegistryName(), e2); return null; } catch (IOException e2) { throw new DockerException(e2); } } catch (IOException e) { throw new DockerException(e); } }
Source:
<code>public ResultScanner adapt( final com.google.cloud.bigtable.grpc.scanner.ResultScanner<Row> bigtableResultScanner) { return new AbstractClientScanner() { @Override public Result next() throws IOException { Row row = bigtableResultScanner.next(); if (row == null) { return null; } if (!hasMatchingLabels(row)) { return null; } return rowAdapter.adaptResponse(row); } @Override public void close() { try { bigtableResultScanner.close(); } catch (IOException ioe) { throw Throwables.propagate(ioe); } } public boolean renewLease() { <START> return false; <END> } }; }</code><technical_language>I if this is right implementation. If want this work existing hbase code, need implementation corresponds Bigtable behavior. If Bigtable allow scan lease renewed, return true. If do allow user call this method, throw exception</technical_language>

Target:
public ResultScanner adapt( final com.google.cloud.bigtable.grpc.scanner.ResultScanner<Row> bigtableResultScanner) { return new AbstractClientScanner() { @Override public Result next() throws IOException { Row row = bigtableResultScanner.next(); if (row == null) { return null; } if (!hasMatchingLabels(row)) { return null; } return rowAdapter.adaptResponse(row); } @Override public void close() { try { bigtableResultScanner.close(); } catch (IOException ioe) { throw Throwables.propagate(ioe); } } public boolean renewLease() { throw new UnsupportedOperationException("renewLease"); } }; }
Source:
<code>public KiiApp getApp() { <START> return thingIfApi.getApp(); <END> }</code><technical_language>Adding this a field is good manner</technical_language>

Target:
public KiiApp getApp() { return this.thingIfApi.getApp(); }
Source:
<code>public void testWaitContainerTimeout() throws Exception { CreateContainerResponse container = dockerClient.createContainerCmd("busybox").withCmd("sleep", "9999").exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); WaitContainerResultCallback callback = dockerClient.waitContainerCmd(container.getId()).exec( new WaitContainerResultCallback()); try { callback.awaitStatusCode(100, TimeUnit.MILLISECONDS); fail("Should throw exception on timeout."); } catch(DockerClientException e){ LOG.info(e.getMessage()); } <START> dockerClient.killContainerCmd(container.getId()).exec(); <END> InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); LOG.info("Container Inspect: {}", inspectContainerResponse.toString()); assertThat(inspectContainerResponse.getState().getRunning(), is(equalTo(false))); }</code><technical_language>killing container here? Container created while test removed automatically test</technical_language>

Target:
public void testWaitContainerTimeout() throws Exception { CreateContainerResponse container = dockerClient.createContainerCmd("busybox").withCmd("sleep", "10").exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); WaitContainerResultCallback callback = dockerClient.waitContainerCmd(container.getId()).exec( new WaitContainerResultCallback()); try { callback.awaitStatusCode(100, TimeUnit.MILLISECONDS); fail("Should throw exception on timeout."); } catch(DockerClientException e){ LOG.info(e.getMessage()); } }
Source:
<code>private List<Path> createTestStructure() throws IOException{ Path rootDir = Paths.get(folder.getRoot().toURI()); Path dataDir = rootDir.resolve("data"); File file1 = folder.newFile("file1.txt"); Path file1Path = Paths.get(file1.toURI()); file1.createNewFile(); File dir1 = folder.newFolder("folder1"); dir1.mkdir(); File file2 = folder.newFile("file2.txt"); Path file2Path = Paths.get(file2.toURI()); file2.createNewFile(); <START> boolean isWindows = System.getProperty("os.name").contains("Windows"); <END> File hiddenFile = folder.newFile(".hiddentFile.txt"); if (isWindows){ Files.setAttribute(Paths.get(hiddenFile.toURI()), "dos:hidden", true); } assertTrue(hiddenFile.isHidden()); File hiddenDirectory = folder.newFolder(".hiddenFolder"); if (isWindows){ Files.setAttribute(Paths.get(hiddenDirectory.toURI()), "dos:hidden", true); } assertTrue(hiddenDirectory + " should be hidden unless on windows", hiddenDirectory.isHidden()); File hiddenFile2 = new File(hiddenDirectory, ".hiddenFile2.txt"); hiddenFile2.createNewFile(); if (isWindows){ Files.setAttribute(Paths.get(hiddenFile2.toURI()), "dos:hidden", true); } File file3 = new File(hiddenDirectory, "file3.txt"); file3.createNewFile(); return Arrays.asList(dataDir.resolve(file1Path.getFileName()), dataDir.resolve(file2Path.getFileName())); }</code><technical_language>I this & thinking good hoist a util file else</technical_language>

Target:
private List<Path> createTestStructure() throws IOException{ Path rootDir = Paths.get(folder.getRoot().toURI()); Path dataDir = rootDir.resolve("data"); Path file1Path = createEmptyFile(folder, "file1.txt"); File dir1 = folder.newFolder("folder1"); dir1.mkdir(); Path file2Path = createEmptyFile(folder, "file2.txt"); File hiddenFile = folder.newFile(".hiddentFile.txt"); hideIfWindows(hiddenFile); assertTrue(hiddenFile.isHidden()); File hiddenDirectory = folder.newFolder(".hiddenFolder"); hideIfWindows(hiddenDirectory); assertTrue(hiddenDirectory + " should be hidden unless on windows", hiddenDirectory.isHidden()); File hiddenFile2 = new File(hiddenDirectory, ".hiddenFile2.txt"); hiddenFile2.createNewFile(); hideIfWindows(hiddenFile2); File file3 = new File(hiddenDirectory, "file3.txt"); file3.createNewFile(); return Arrays.asList(dataDir.resolve(file1Path.getFileName()), dataDir.resolve(file2Path.getFileName())); }
Source:
<code>if( !initialized && prefs.getApplicationId() != null && prefs.getApiKey() != null ) Backendless.initApplicationFromProperties( ContextHandler.getAppContext() ); } catch( IllegalStateException e ) { <START> if( !e.getMessage().equals( "Backendless application was not initialized" ) ) <END> throw e; }</code><technical_language>is a bad idea check if message equals some string message changed. In worst case, create a constant this message. independent exception</technical_language>

Target:
if( !initialized && prefs.getApplicationId() != null && prefs.getApiKey() != null ) Backendless.initApplicationFromProperties( ContextHandler.getAppContext() ); } catch( IllegalStateException e ) { if( !ExceptionMessage.NOT_INITIALIZED.equals( e.getMessage() ) ) throw e; }
Source:
<code><START> double getSumOfScores(Map<SoftConstraint, Float> originScoresMap) { <END> return originScoresMap.entrySet().stream().map(constraintToOriginScore -> { float score = MIN_MAX_SCALER.scale(constraintToOriginScore.getValue()); float weight = MODEL.get(constraintToOriginScore.getKey().getType()); return score * weight; }).mapToDouble(i -> i).sum(); }</code><technical_language>inconsistent data type? If float is more efficient, float return type. is mixing double/float in code</technical_language>

Target:
float getSumOfScores(Map<SoftConstraint, Float> originScoresMap) { float sum = 0; for (Map.Entry<SoftConstraint, Float> softConstraintScoreEntry : originScoresMap.entrySet()) { SoftConstraint softConstraint = softConstraintScoreEntry.getKey(); float score = softConstraint.getScalerFunction().scale(softConstraintScoreEntry.getValue()); float weight = MODEL.get(softConstraint); sum += score * weight; } return sum; }
Source:
<code>public WeightedRandomModel(ResourceLocation parent, VariantList variants) throws Exception { this.variants = variants.getVariantList(); this.locations = new ArrayList<>(); this.textures = Sets.newHashSet(); this.models = new ArrayList<>(); ImmutableList.Builder<Pair<IModel, IModelState>> builder = ImmutableList.builder(); for (Variant v : this.variants) { ResourceLocation loc = v.getModelLocation(); locations.add(loc); IModel model; if(loc.equals(MODEL_MISSING)) { model = ModelLoaderRegistry.getMissingModel(); } else { model = ModelLoaderRegistry.getModel(loc); } model = v.process(model); for(ResourceLocation location : model.getDependencies()) { ModelLoaderRegistry.getModelOrMissing(location); } textures.addAll(model.getTextures()); models.add(model); IModelState modelDefaultState = model.getDefaultState(); <START> if (modelDefaultState != null) <END> { builder.add(Pair.of(model, new ModelStateComposition(v.getState(), modelDefaultState))); } else { throw new NullPointerException("Model " + loc + " returned null as default state"); } } if (models.size() == 0) { IModel missing = ModelLoaderRegistry.getMissingModel(); models.add(missing); builder.add(Pair.of(missing, TRSRTransformation.identity())); } defaultState = new MultiModelState(builder.build()); }</code><technical_language>Preconditions.checkNotNull Guava here</technical_language>

Target:
public WeightedRandomModel(ResourceLocation parent, VariantList variants) throws Exception { this.variants = variants.getVariantList(); this.locations = new ArrayList<>(); this.textures = Sets.newHashSet(); this.models = new ArrayList<>(); ImmutableList.Builder<Pair<IModel, IModelState>> builder = ImmutableList.builder(); for (Variant v : this.variants) { ResourceLocation loc = v.getModelLocation(); locations.add(loc); IModel model; if(loc.equals(MODEL_MISSING)) { model = ModelLoaderRegistry.getMissingModel(); } else { model = ModelLoaderRegistry.getModel(loc); } model = v.process(model); for(ResourceLocation location : model.getDependencies()) { ModelLoaderRegistry.getModelOrMissing(location); } textures.addAll(model.getTextures()); models.add(model); IModelState modelDefaultState = model.getDefaultState(); Preconditions.checkNotNull(modelDefaultState, "Model %s returned null as default state", loc); builder.add(Pair.of(model, new ModelStateComposition(v.getState(), modelDefaultState))); } if (models.size() == 0) { IModel missing = ModelLoaderRegistry.getMissingModel(); models.add(missing); builder.add(Pair.of(missing, TRSRTransformation.identity())); } defaultState = new MultiModelState(builder.build()); }
Source:
<code>public void configure() { synchronized(hasSRAMPPackageDeployed) { KieSrampUtil kieSrampUtil = new KieSrampUtil(); Governance governance = new Governance(); String groupId = governance.getGovernanceWorkflowGroup(); String artifactId = governance.getGovernanceWorkflowName(); String version = null; try { version = SrampMavenUtil.getVersion(SRAMP_KIE_MODEL, groupId, artifactId, governance.getGovernanceWorkflowVersion()); } catch (SrampClientException e) { e.printStackTrace(); } catch (SrampAtomException e) { e.printStackTrace(); <START> } <END> if (kieSrampUtil.isSRAMPPackageDeployed(groupId, artifactId, version)) { KModuleDeploymentUnit unit = new KModuleDeploymentUnit( groupId, artifactId, version, Governance.DEFAULT_GOVERNANCE_WORKFLOW_PACKAGE, Governance.DEFAULT_GOVERNANCE_WORKFLOW_KSESSION); RuntimeManager runtimeManager = kieSrampUtil.getRuntimeManager(processEngineService, unit); RuntimeEngine runtime = runtimeManager.getRuntimeEngine(EmptyContext.get()); runtime.getTaskService().toString(); } } }</code><technical_language>need do exceptions. need re-throw runtime exceptions</technical_language>

Target:
public void configure() { synchronized(hasSRAMPPackageDeployed) { KieSrampUtil kieSrampUtil = new KieSrampUtil(); Governance governance = new Governance(); String groupId = governance.getGovernanceWorkflowGroup(); String artifactId = governance.getGovernanceWorkflowName(); String workflowVersion = governance.getGovernanceWorkflowVersion(); String version = null; try { version = SrampMavenUtil.getVersion(SRAMP_KIE_MODEL, groupId, artifactId, workflowVersion); } catch (SrampClientException e) { throw new RuntimeException(Messages.i18n.format("maven.version.not.found.error", groupId, artifactId, workflowVersion), e); } catch (SrampAtomException e) { throw new RuntimeException(Messages.i18n.format("maven.version.not.found.error", groupId, artifactId, workflowVersion), e); } if (StringUtils.isBlank(version)) { throw new RuntimeException(Messages.i18n.format("maven.version.not.found", groupId, artifactId, workflowVersion)); } if (kieSrampUtil.isSRAMPPackageDeployed(groupId, artifactId, version)) { KModuleDeploymentUnit unit = new KModuleDeploymentUnit( groupId, artifactId, version, Governance.DEFAULT_GOVERNANCE_WORKFLOW_PACKAGE, Governance.DEFAULT_GOVERNANCE_WORKFLOW_KSESSION); RuntimeManager runtimeManager = kieSrampUtil.getRuntimeManager(processEngineService, unit); RuntimeEngine runtime = runtimeManager.getRuntimeEngine(EmptyContext.get()); runtime.getTaskService().toString(); } } }
Source:
<code>void startLoadJob(ProjectWrapper projectWrapper, IExceptionHandler handler) { new Job("load project") { @Override protected IStatus run(IProgressMonitor monitor) { try { <START> WatchManager.getInstance().startWatch(projectWrapper.getResource()); <END> Collection<IResource> resources = new HashSet<>(); for (String kind : RESOURCE_KINDS) { resources.addAll(projectWrapper.getResource().getResources(kind)); } resources.forEach(r -> resourceCache.add(r)); projectWrapper.initWithResources(resources); projectWrapper.fireChanged(); } catch (OperationCanceledException e) { projectWrapper.setLoadingState(LoadingState.LOAD_STOPPED); } catch (Throwable e) { projectWrapper.setLoadingState(LoadingState.LOAD_STOPPED); handler.handleException(e); } return Status.OK_STATUS; } }.schedule(); }</code><technical_language>do this, this start a watch while loading resources in lines. I assume some logic handle duplicates? This is done this I suspect avoid gaps resources get added load watch start</technical_language>

Target:
void startLoadJob(ProjectWrapper projectWrapper, IExceptionHandler handler) { new Job("Load project contents") { @Override protected IStatus run(IProgressMonitor monitor) { try { IProject project = projectWrapper.getWrapped(); WatchManager.getInstance().startWatch(project); Collection<IResource> resources = new HashSet<>(); for (String kind : RESOURCE_KINDS) { resources.addAll(getWrapped().getResources(kind, project.getNamespace())); } resources.forEach(r -> resourceCache.add(r)); projectWrapper.initWithResources(resources); projectWrapper.fireChanged(); } catch (OperationCanceledException e) { projectWrapper.setLoadingState(LoadingState.LOAD_STOPPED); } catch (Throwable e) { projectWrapper.setLoadingState(LoadingState.LOAD_STOPPED); handler.handleException(e); } return Status.OK_STATUS; } }.schedule(); }
Source:
<code>public Collection<CacheEntry<K, K>> performOperationRehashAware( IntermediateCollector<Collection<CacheEntry<K, K>>> response) { BaseStream<?, ?> stream = supplier.get().sequential(); List<CacheEntry<K, K>> collectedValues = new ArrayList(batchSize); List<V> currentList = new ArrayList<>(); <START> ByRef<K> ref = new ByRef<>(null); <END> stream = ((Stream<Map.Entry<K, ?>>) stream).peek(e -> { if (!currentList.isEmpty()) { collectedValues.add(new ImmortalCacheEntry(ref.get(), null)); if (collectedValues.size() >= batchSize) { handleList(currentList); response.sendDataResonse(collectedValues); collectedValues.clear(); currentList.clear(); } } ref.set(e.getKey()); }); for (IntermediateOperation intermediateOperation : intermediateOperations) { stream = intermediateOperation.perform(stream); } S convertedStream = ((S) stream); handleStreamForEach(convertedStream, currentList); if (!currentList.isEmpty()) { handleList(currentList); collectedValues.add(new ImmortalCacheEntry(ref.get(), null)); } return collectedValues; }</code><technical_language>need change name of variable, I think</technical_language>

Target:
public Collection<CacheEntry<K, K>> performOperationRehashAware( IntermediateCollector<Collection<CacheEntry<K, K>>> response) { BaseStream<?, ?> stream = supplier.get().sequential(); List<CacheEntry<K, K>> collectedValues = new ArrayList(batchSize); List<V> currentList = new ArrayList<>(); ByRef<K> currentKey = new ByRef<>(null); stream = ((Stream<Map.Entry<K, ?>>) stream).peek(e -> { if (!currentList.isEmpty()) { collectedValues.add(new ImmortalCacheEntry(currentKey.get(), null)); if (collectedValues.size() >= batchSize) { handleList(currentList); response.sendDataResonse(collectedValues); collectedValues.clear(); currentList.clear(); } } currentKey.set(e.getKey()); }); for (IntermediateOperation intermediateOperation : intermediateOperations) { stream = intermediateOperation.perform(stream); } S convertedStream = ((S) stream); handleStreamForEach(convertedStream, currentList); if (!currentList.isEmpty()) { handleList(currentList); collectedValues.add(new ImmortalCacheEntry(currentKey.get(), null)); } return collectedValues; }
Source:
<code>public void loadState(HueState state, String... lightIdentifiers) { if (!hueFacade.bridgeAvailable()) { <START> throw new StateNotLoadedException("Hue bridge is not available"); <END> } String[] ids = getLightIdentifiers(lightIdentifiers); restoreState = () -> { new BlankState().execute(hueFacade, ids); state.execute(hueFacade, ids); log.debug("Light states restored!"); }; new BlankState().execute(hueFacade, ids); state.execute(hueFacade, ids); }</code><technical_language>nice move this e.g. annotation, for later</technical_language>

Target:
public void loadState(HueState state, String... lightIdentifiers) { if (!hueFacade.isBridgeAvailable()) { throw new StateNotLoadedException("Hue bridge is not available"); } String[] ids = getLightIdentifiers(lightIdentifiers); restoreState = () -> { new BlankState().execute(hueFacade, ids); state.execute(hueFacade, ids); log.debug("Light states restored!"); }; new BlankState().execute(hueFacade, ids); state.execute(hueFacade, ids); }
Source:
<code>public void testCantSetChangeDetectionOnIndex() throws Exception { Assume.assumeTrue(HbaseCompatCapabilities.hasPreWALAppend()); try (Connection conn = DriverManager.getConnection(getUrl())) { SchemaBuilder builder = new SchemaBuilder(getUrl()); builder.withTableDefaults().build(); try { String badIndexSql = "CREATE INDEX IDX_SHOULD_FAIL" + " ON " + builder.getEntityTableName() + "(COL1) " + CHANGE_DETECTION_ENABLED + "=TRUE"; conn.createStatement().execute(badIndexSql); <START> Assert.fail("Didn't throw a SQLException for setting change detection on an " + <END> "index at create time!"); } catch (SQLException se) { TestUtil.assertSqlExceptionCode( SQLExceptionCode.CHANGE_DETECTION_SUPPORTED_FOR_TABLES_AND_VIEWS_ONLY, se); } } }</code><technical_language>nit: static import fail()</technical_language>

Target:
public void testCantSetChangeDetectionOnIndex() throws Exception { Assume.assumeTrue(HbaseCompatCapabilities.hasPreWALAppend()); try (Connection conn = DriverManager.getConnection(getUrl())) { SchemaBuilder builder = new SchemaBuilder(getUrl()); builder.withTableDefaults().build(); try { String badIndexSql = "CREATE INDEX IDX_SHOULD_FAIL" + " ON " + builder.getEntityTableName() + "(COL1) " + CHANGE_DETECTION_ENABLED + "=TRUE"; conn.createStatement().execute(badIndexSql); fail("Didn't throw a SQLException for setting change detection on an " + "index at create time!"); } catch (SQLException se) { TestUtil.assertSqlExceptionCode( SQLExceptionCode.CHANGE_DETECTION_SUPPORTED_FOR_TABLES_AND_VIEWS_ONLY, se); } } }
Source:
<code>public void testClientsConnections() throws Exception { String host = ignite.configuration().getClientConnectorConfiguration().getHost(); if (host == null) host = ignite.configuration().getLocalHost(); int port = ignite.configuration().getClientConnectorConfiguration().getPort(); try (IgniteClient client = Ignition.startClient(new ClientConfiguration().setAddresses(host + ":" + port))) { <START> <END> try (Connection conn = new IgniteJdbcThinDriver().connect("jdbc:ignite:thin://" + host, new Properties())) { TabularDataSupport conns = systemView(CLI_CONN_SYS_VIEW); Consumer<CompositeData> checkThin = c -> { assertEquals("THIN", c.get("type")); assertTrue(c.get("localAddress").toString().endsWith(Integer.toString(port))); assertEquals(c.get("version"), DEFAULT_VER.asString()); }; Consumer<CompositeData> checkJdbc = c -> { assertEquals("JDBC", c.get("type")); assertTrue(c.get("localAddress").toString().endsWith(Integer.toString(port))); assertEquals(c.get("version"), CURRENT_VER.asString()); }; CompositeData c0 = conns.get(new Object[] {0}); CompositeData c1 = conns.get(new Object[] {1}); if (c0.get("type").equals("JDBC")) { checkJdbc.accept(c0); checkThin.accept(c1); } else { checkJdbc.accept(c1); checkThin.accept(c0); } assertEquals(2, conns.size()); } } }</code><technical_language>Redundant NL</technical_language>

Target:
public void testClientsConnections() throws Exception { String host = ignite.configuration().getClientConnectorConfiguration().getHost(); if (host == null) host = ignite.configuration().getLocalHost(); int port = ignite.configuration().getClientConnectorConfiguration().getPort(); try (IgniteClient client = Ignition.startClient(new ClientConfiguration().setAddresses(host + ":" + port))) { try (Connection conn = new IgniteJdbcThinDriver().connect("jdbc:ignite:thin://" + host, new Properties())) { TabularDataSupport conns = systemView(CLI_CONN_SYS_VIEW); Consumer<CompositeData> checkThin = c -> { assertEquals("THIN", c.get("type")); assertTrue(c.get("localAddress").toString().endsWith(Integer.toString(port))); assertEquals(c.get("version"), ProtocolVersion.CURRENT_VER.toString()); }; Consumer<CompositeData> checkJdbc = c -> { assertEquals("JDBC", c.get("type")); assertTrue(c.get("localAddress").toString().endsWith(Integer.toString(port))); assertEquals(c.get("version"), JdbcConnectionContext.CURRENT_VER.asString()); }; CompositeData c0 = conns.get(new Object[] {0}); CompositeData c1 = conns.get(new Object[] {1}); if (c0.get("type").equals("JDBC")) { checkJdbc.accept(c0); checkThin.accept(c1); } else { checkJdbc.accept(c1); checkThin.accept(c0); } assertEquals(2, conns.size()); } } boolean res = GridTestUtils.waitForCondition(() -> systemView(CLI_CONN_SYS_VIEW).isEmpty(), 5_000); assertTrue(res); }
Source:
<code>public void enqueueSuspended(ScheduledTaskDescriptor descriptor, boolean force) { if (logger.isFinestEnabled()) { log(FINEST, "Enqueuing suspended, i.e., backup: " + descriptor.getDefinition()); } boolean keyExists = tasks.containsKey(descriptor.getDefinition().getName()); <START> if (force || !(keyExists)) { <END> taskLifecycleHook.preSuspendedEnqueue(name, descriptor, !keyExists); tasks.put(descriptor.getDefinition().getName(), descriptor); taskLifecycleHook.postSuspendedEnqueue(name, descriptor, !keyExists); } }</code><technical_language>minor: unnecessary parentheses</technical_language>

Target:
public void enqueueSuspended(ScheduledTaskDescriptor descriptor, boolean force) { if (logger.isFinestEnabled()) { log(FINEST, "Enqueuing suspended, i.e., backup: " + descriptor.getDefinition()); } boolean keyExists = tasks.containsKey(descriptor.getDefinition().getName()); if (force || !keyExists) { tasks.put(descriptor.getDefinition().getName(), descriptor); } }
Source:
<code>public List<Integer> getHistoryIds(long sessionId) throws DatabaseException { <START> return getHistoryIdsByParams(sessionId,0, true, null); <END> }</code><technical_language>This change is necessary</technical_language>

Target:
public List<Integer> getHistoryIds(long sessionId) throws DatabaseException { return getHistoryIdsOfHistType(sessionId, null); }
Source:
<code>public void bindView(View view, Context context, Cursor cursor) { <START> view.setBackgroundResource(R.drawable.selectable_item_background); <END> TextView title = (TextView) view.findViewById(R.id.page_list_item_title); ImageView thumbnail = (ImageView) view.findViewById(R.id.page_list_item_image); HistoryEntry entry = HistoryEntry.PERSISTENCE_HELPER.fromCursor(cursor); title.setText(entry.getTitle().getDisplayText()); view.setTag(entry); if (app.isImageDownloadEnabled()) { Picasso.with(getActivity()) .load(cursor.getString(HistoryEntryContentProvider.COL_INDEX_IMAGE)) .placeholder(R.drawable.ic_pageimage_placeholder) .error(R.drawable.ic_pageimage_placeholder) .into(thumbnail); } else { Picasso.with(getActivity()) .load(R.drawable.ic_pageimage_placeholder) .into(thumbnail); } String curTime, prevTime = ""; if (cursor.getPosition() != 0) { Cursor prevCursor = (Cursor) getItem(cursor.getPosition() - 1); HistoryEntry prevEntry = HistoryEntry.PERSISTENCE_HELPER.fromCursor(prevCursor); prevTime = getDateString(prevEntry.getTimestamp()); } curTime = getDateString(entry.getTimestamp()); TextView sectionHeader = (TextView) view.findViewById(R.id.page_list_header_text); if (!curTime.equals(prevTime)) { sectionHeader.setText(curTime); sectionHeader.setVisibility(View.VISIBLE); } else { sectionHeader.setVisibility(View.GONE); } }</code><technical_language>this in newView? question for SavedPagesFragment</technical_language>

Target:
public void bindView(View view, Context context, Cursor cursor) { TextView title = (TextView) view.findViewById(R.id.page_list_item_title); ImageView thumbnail = (ImageView) view.findViewById(R.id.page_list_item_image); HistoryEntry entry = HistoryEntry.PERSISTENCE_HELPER.fromCursor(cursor); title.setText(entry.getTitle().getDisplayText()); view.setTag(entry); if (app.isImageDownloadEnabled()) { Picasso.with(getActivity()) .load(cursor.getString(HistoryEntryContentProvider.COL_INDEX_IMAGE)) .placeholder(R.drawable.ic_pageimage_placeholder) .error(R.drawable.ic_pageimage_placeholder) .into(thumbnail); } else { Picasso.with(getActivity()) .load(R.drawable.ic_pageimage_placeholder) .into(thumbnail); } String curTime, prevTime = ""; if (cursor.getPosition() != 0) { Cursor prevCursor = (Cursor) getItem(cursor.getPosition() - 1); HistoryEntry prevEntry = HistoryEntry.PERSISTENCE_HELPER.fromCursor(prevCursor); prevTime = getDateString(prevEntry.getTimestamp()); } curTime = getDateString(entry.getTimestamp()); TextView sectionHeader = (TextView) view.findViewById(R.id.page_list_header_text); if (!curTime.equals(prevTime)) { sectionHeader.setText(curTime); sectionHeader.setVisibility(View.VISIBLE); } else { sectionHeader.setVisibility(View.GONE); } }
Source:
<code>public void groupForOrphanItemsTest() { final String ORPHAN_ITEM = "orphanitem"; NavTreeBuilder builder = new NavTreeBuilder(); LayoutTemplate lt = new LayoutTemplate("lt1"); LayoutTemplate lt2 = new LayoutTemplate(ORPHAN_ITEM); final String ITEM = "item1"; final String ITEM_TO_REMOVE = "item2"; final String GROUP = "group"; builder.group(GROUP, GROUP, "", false); builder.item(ITEM, ITEM, "", false, NavWorkbenchCtx.perspective(lt.getName())); builder.item(ITEM_TO_REMOVE, ITEM_TO_REMOVE, "", false); builder.endGroup(); <START> List<LayoutTemplate> templates = new ArrayList<>(); templates.add(lt); templates.add(lt2); <END> NavTree originalTree = builder.build(); assertNull(originalTree.getItemById(RuntimeNavigationBuilder.ORPHAN_GROUP_ID)); assertEquals(1, originalTree.getRootItems().size()); NavTree runtimeTree = runtimeNavigationBuilder.buildRuntimeTree(originalTree, templates); assertEquals(2, runtimeTree.getRootItems().size()); NavGroup orphanItemsGroup = (NavGroup) runtimeTree.getItemById(RuntimeNavigationBuilder.ORPHAN_GROUP_ID); assertNotNull(orphanItemsGroup); assertEquals(1, orphanItemsGroup.getChildren().size()); NavItem orphanItem = runtimeTree.getItemById(ORPHAN_ITEM); String resourceId = NavWorkbenchCtx.get(orphanItem).getResourceId(); assertEquals(ORPHAN_ITEM, resourceId); assertEquals(orphanItemsGroup, orphanItem.getParent()); }</code><technical_language>suggestion List<LayoutTemplate> templates = Arrays.asList(lt, lt2); a suggestion shorter :)</technical_language>

Target:
public void groupForOrphanItemsTest() { final String ORPHAN_ITEM = "orphanitem"; NavTreeBuilder builder = new NavTreeBuilder(); LayoutTemplate lt = new LayoutTemplate("lt1"); LayoutTemplate lt2 = new LayoutTemplate(ORPHAN_ITEM); final String ITEM_TO_REMOVE = "item2"; builder.group(GROUP, GROUP, "", false); builder.item(ITEM, ITEM, "", false, NavWorkbenchCtx.perspective(lt.getName())); builder.item(ITEM_TO_REMOVE, ITEM_TO_REMOVE, "", false); builder.endGroup(); List<LayoutTemplate> templates = Arrays.asList(lt, lt2); NavTree originalTree = builder.build(); assertNull(originalTree.getItemById(RuntimeNavigationBuilder.ORPHAN_GROUP_ID)); assertEquals(1, originalTree.getRootItems().size()); NavTree runtimeTree = runtimeNavigationBuilder.buildRuntimeTree(originalTree, templates); assertEquals(2, runtimeTree.getRootItems().size()); NavGroup orphanItemsGroup = (NavGroup) runtimeTree.getItemById(RuntimeNavigationBuilder.ORPHAN_GROUP_ID); assertNotNull(orphanItemsGroup); assertEquals(1, orphanItemsGroup.getChildren().size()); NavItem orphanItem = runtimeTree.getItemById(ORPHAN_ITEM); String resourceId = NavWorkbenchCtx.get(orphanItem).getResourceId(); assertEquals(ORPHAN_ITEM, resourceId); assertEquals(orphanItemsGroup, orphanItem.getParent()); }
Source:
<code>public void accept(Event<CollectLoadBalancerMetadataRequest> collectLBMetadataRequestEvent) { LOGGER.debug("Received event: {}", collectLBMetadataRequestEvent); CollectLoadBalancerMetadataRequest request = collectLBMetadataRequestEvent.getData(); try { CloudConnector<Object> connector = cloudPlatformConnectors.get(request.getCloudContext().getPlatformVariant()); AuthenticatedContext ac = connector.authentication().authenticate(request.getCloudContext(), request.getCloudCredential()); <START> List<CloudLoadBalancerMetadata> loadBalancerStatuses = connector.metadata() .collectLoadBalancer(ac, request.getGatewayGroupNames()); <END> CollectLoadBalancerMetadataResult collectLBMetadataResult = new CollectLoadBalancerMetadataResult(request.getResourceId(), loadBalancerStatuses); request.getResult().onNext(collectLBMetadataResult); eventBus.notify(collectLBMetadataResult.selector(), new Event<>(collectLBMetadataRequestEvent.getHeaders(), collectLBMetadataResult)); LOGGER.debug("Load balancer metadata collection successfully finished"); } catch (RuntimeException e) { LOGGER.error("Collecting metadata failed", e); CollectLoadBalancerMetadataResult failure = new CollectLoadBalancerMetadataResult(e, request.getResourceId()); request.getResult().onNext(failure); eventBus.notify(failure.selector(), new Event<>(collectLBMetadataRequestEvent.getHeaders(), failure)); } }</code><technical_language>Nit: remove unnecessary space metadata()</technical_language>

Target:
public void accept(Event<CollectLoadBalancerMetadataRequest> collectLBMetadataRequestEvent) { LOGGER.debug("Received event: {}", collectLBMetadataRequestEvent); CollectLoadBalancerMetadataRequest request = collectLBMetadataRequestEvent.getData(); try { CloudConnector<Object> connector = cloudPlatformConnectors.get(request.getCloudContext().getPlatformVariant()); AuthenticatedContext ac = connector.authentication().authenticate(request.getCloudContext(), request.getCloudCredential()); List<CloudLoadBalancerMetadata> loadBalancerStatuses = connector.metadata().collectLoadBalancer(ac, request.getTypesPresentInStack()); CollectLoadBalancerMetadataResult collectLBMetadataResult = new CollectLoadBalancerMetadataResult(request.getResourceId(), loadBalancerStatuses); request.getResult().onNext(collectLBMetadataResult); eventBus.notify(collectLBMetadataResult.selector(), new Event<>(collectLBMetadataRequestEvent.getHeaders(), collectLBMetadataResult)); LOGGER.debug("Load balancer metadata collection successfully finished"); } catch (RuntimeException e) { LOGGER.error("Collecting metadata failed", e); CollectLoadBalancerMetadataResult failure = new CollectLoadBalancerMetadataResult(e, request.getResourceId()); request.getResult().onNext(failure); eventBus.notify(failure.selector(), new Event<>(collectLBMetadataRequestEvent.getHeaders(), failure)); } }
Source:
<code>public CompletableFuture<ClientResponse> run(byte[] jarfileBytes, String classesToDeleteSelector) { if (!allowPausedModeWork(false, isAdminConnection())) { return makeQuickResponse( ClientResponse.SERVER_UNAVAILABLE, "Server is paused and is available in read-only mode - please try again later."); } boolean useDDLSchema = VoltDB.instance().getCatalogContext().cluster.getUseddlschema(); if (!useDDLSchema) { return makeQuickResponse( ClientResponse.GRACEFUL_FAILURE, "Cluster is configured to use @UpdateApplicationCatalog " + "to change application schema. Use of @UpdateClasses is forbidden."); } logCatalogUpdateInvocation("@UpdateClasses"); return updateApplication("@UpdateClasses", jarfileBytes, classesToDeleteSelector, <START> new String[0], new ArrayList<>(), <END> null, false, useDDLSchema); }</code><technical_language>Collections.emptyList() argument formatting is inconsistent</technical_language>

Target:
public CompletableFuture<ClientResponse> run(byte[] jarfileBytes, String classesToDeleteSelector) { if (!allowPausedModeWork(false, isAdminConnection())) { return makeQuickResponse( ClientResponse.SERVER_UNAVAILABLE, "Server is paused and is available in read-only mode - please try again later."); } boolean useDDLSchema = VoltDB.instance().getCatalogContext().cluster.getUseddlschema(); if (!useDDLSchema) { return makeQuickResponse( ClientResponse.GRACEFUL_FAILURE, "Cluster is configured to use @UpdateApplicationCatalog " + "to change application schema. Use of @UpdateClasses is forbidden."); } logCatalogUpdateInvocation("@UpdateClasses"); return updateApplication("@UpdateClasses", jarfileBytes, classesToDeleteSelector, new String[0], Collections.emptyList(), null, false, useDDLSchema); }
Source:
<code>public GatewayResponse authorise(AuthorisationGatewayRequest request) { logger.info("Calling Stripe for authorisation of charge [{}]", request.getChargeExternalId()); Response sourceResponse = client.postRequest( request.getGatewayAccount(), AUTHORISE, URI.create(stripeGatewayConfig.getUrl() + "/v1/tokens"), <START> stripeUrlEncodedSourcePayload(request), <END> getAuthHeaderValue(), APPLICATION_FORM_URLENCODED_TYPE); String token = sourceResponse.readEntity(Map.class).get("id").toString(); Response authorisationResponse = client.postRequest( request.getGatewayAccount(), AUTHORISE, URI.create(stripeGatewayConfig.getUrl() + "/v1/charges"), stripeAuthoriseJsonPayload(request, token), getAuthHeaderValue(), APPLICATION_JSON_TYPE); GatewayResponse.GatewayResponseBuilder<BaseResponse> responseBuilder = GatewayResponse.GatewayResponseBuilder.responseBuilder(); return responseBuilder.withResponse(StripeAuthorisationResponse.of(authorisationResponse)).build(); }</code><technical_language>sending a url encoded payload</technical_language>

Target:
public GatewayResponse authorise(AuthorisationGatewayRequest request) { logger.info("Calling Stripe for authorisation of charge [{}]", request.getChargeExternalId()); Response sourceResponse = client.postRequest( request.getGatewayAccount(), AUTHORISE, URI.create(stripeGatewayConfig.getUrl() + "/v1/tokens"), sourcePayload(request), getAuthHeaderValue(), APPLICATION_FORM_URLENCODED_TYPE); String token = sourceResponse.readEntity(Map.class).get("id").toString(); Response authorisationResponse = client.postRequest( request.getGatewayAccount(), AUTHORISE, URI.create(stripeGatewayConfig.getUrl() + "/v1/charges"), authorisePayload(request, token), getAuthHeaderValue(), APPLICATION_FORM_URLENCODED_TYPE); GatewayResponse.GatewayResponseBuilder<BaseResponse> responseBuilder = GatewayResponse.GatewayResponseBuilder.responseBuilder(); return responseBuilder.withResponse(StripeAuthorisationResponse.of(authorisationResponse)).build(); }
Source:
<code>private void writeRecoveryStates(CorfuPayloadMsg<LogRecoveryStateWriteMsg> msg, ChannelHandlerContext ctx, IServerRouter r) { LogRecoveryStateWriteMsg recoveryState = msg.getPayload(); log.debug("writeRecoveryStates: Writing log entries, garbage entries, " + "compaction mark: {}", recoveryState.getLogEntries().size(), recoveryState.getLogEntries().size(), recoveryState.getCompactionMark()); batchWriter.addTask(RECOVERY_STATE_WRITE, msg) .thenRunAsync(() -> { <START> streamLog.updateCommittedTail(recoveryState.getCompactionMark()); <END> r.sendResponse(ctx, msg, CorfuMsgType.WRITE_OK.msg()); }) .exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); }</code><technical_language>I forget this correct. discuss offline</technical_language>

Target:
private void writeRecoveryStates(CorfuPayloadMsg<LogRecoveryStateWriteMsg> msg, ChannelHandlerContext ctx, IServerRouter r) { LogRecoveryStateWriteMsg recoveryState = msg.getPayload(); log.debug("writeRecoveryStates: Writing log entries, garbage entries, " + "compaction mark: {}", recoveryState.getLogEntries().size(), recoveryState.getLogEntries().size(), recoveryState.getCompactionMark()); streamLog.updateGlobalCompactionMark(recoveryState.getCompactionMark()); batchWriter.addTask(RECOVERY_STATE_WRITE, msg) .thenRunAsync(() -> r.sendResponse(ctx, msg, CorfuMsgType.WRITE_OK.msg())) .exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); }
Source:
<code>public void refreshTimeEstimation(List<ScriptGeneratorAction> scriptGenContent, ScriptDefinitionWrapper scriptDefinition) throws InterruptedException, ExecutionException, PythonNotReadyException { if (pythonReady) { CompletableFuture.supplyAsync(() -> { try { return scriptDefinitionsWrapper.estimateTime(convertScriptGenContentToPython(scriptGenContent), scriptDefinition); } catch (Py4JException e) { LOG.error(e); handlePythonReadinessChange(false); return false; } }, THREAD).thenAccept(timeEstimate -> firePropertyChange(TIME_ESTIMATE_PROPERTY, null, timeEstimate) ); } else { handlePythonReadinessChange(false); throw new PythonNotReadyException("When getting time estimation"); } <START> if (!pythonReady) { throw new PythonNotReadyException("When getting time estimation"); } <END> }</code><technical_language>This check is in</technical_language>

Target:
public void refreshTimeEstimation(List<ScriptGeneratorAction> scriptGenContent, ScriptDefinitionWrapper scriptDefinition) throws InterruptedException, ExecutionException, PythonNotReadyException { if (pythonReady) { CompletableFuture.supplyAsync(() -> { try { return scriptDefinitionsWrapper.estimateTime(convertScriptGenContentToPython(scriptGenContent), scriptDefinition); } catch (Py4JException e) { LOG.error(e); handlePythonReadinessChange(false); return false; } }, THREAD).thenAccept(timeEstimate -> firePropertyChange(TIME_ESTIMATE_PROPERTY, null, timeEstimate) ); } else { handlePythonReadinessChange(false); throw new PythonNotReadyException("When getting time estimation"); } }
Source:
<code>private void handleTokenQuery(CorfuPayloadMsg<TokenRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { TokenRequest req = msg.getPayload(); List<UUID> streams = req.getStreams(); List<Long> streamTails; Token token; if (req.getStreams().isEmpty()) { token = new Token(sequencerEpoch, globalLogTail - 1); streamTails = Collections.emptyList(); } else { <START> token = new Token(sequencerEpoch, globalLogTail - 1); <END> streamTails = new ArrayList<>(streams.size()); for (UUID stream : streams) { streamTails.add(streamTailToGlobalTailMap.getOrDefault(stream, Address.NON_EXIST)); } } r.sendResponse(ctx, msg, CorfuMsgType.TOKEN_RES.payloadMsg(new TokenResponse( TokenType.NORMAL, TokenResponse.NO_CONFLICT_KEY, TokenResponse.NO_CONFLICT_STREAM, token, Collections.emptyMap(), streamTails))); }</code><technical_language>I a map is a more data structure. consumer maintain a uuid -> index</technical_language>

Target:
private void handleTokenQuery(CorfuPayloadMsg<TokenRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { TokenRequest req = msg.getPayload(); List<UUID> streams = req.getStreams(); Map<UUID, Long> streamTails; Token token; if (req.getStreams().isEmpty()) { token = new Token(sequencerEpoch, globalLogTail - 1); streamTails = Collections.emptyMap(); } else { token = new Token(sequencerEpoch, globalLogTail - 1); streamTails = new HashMap<>(streams.size()); for (UUID stream : streams) { streamTails.put(stream, streamTailToGlobalTailMap.getOrDefault(stream, Address.NON_EXIST)); } } r.sendResponse(ctx, msg, CorfuMsgType.TOKEN_RES.payloadMsg(new TokenResponse( TokenType.NORMAL, TokenResponse.NO_CONFLICT_KEY, TokenResponse.NO_CONFLICT_STREAM, token, Collections.emptyMap(), streamTails))); }