auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void checkMoveJavaClassInNewSourceFolder() { projectExplorer.waitProjectExplorer(); projectExplorer.waitItem(PROJECT_NAME); projectExplorer.quickExpandWithJavaScript(); projectExplorer.openItemByPath(PATH_TO_FILE); projectExplorer.waitAndSelectItem(PROJECT_NAME); createNewFolder(NEW_FOLDER_NAME); projectExplorer.waitAndSelectItem(PROJECT_NAME + "/" + NEW_FOLDER_NAME); createNewFolder(NEW_SOURCE_FOLDER); projectExplorer.waitAndSelectItem(PATH_NEW_SOURCE_FOLDER); projectExplorer.openContextMenuByPathSelectedItem(PROJECT_NAME + "/test/" + NEW_SOURCE_FOLDER); projectExplorer.clickOnItemInContextMenu(BUILD_PATH); projectExplorer.clickOnItemInContextMenu(USE_AS_SOURCE_FOLDER); projectExplorer.waitDefinedTypeOfFolder(PATH_NEW_SOURCE_FOLDER, JAVA_SOURCE_FOLDER); projectExplorer.waitAndSelectItem(PATH_NEW_SOURCE_FOLDER); projectExplorer.openContextMenuByPathSelectedItem(PATH_NEW_SOURCE_FOLDER); createPackage(); projectExplorer.waitItem(PROJECT_NAME); projectExplorer.waitAndSelectItem(PATH_TO_FILE); <START> WaitUtils.sleepQuietly(11); <END> projectExplorer.launchRefactorMoveByKeyboard(); refactor.waitMoveItemFormIsOpen(); refactor.clickOnExpandIconTree(PROJECT_NAME); refactor.clickOnExpandIconTree("/test/java"); loader.waitOnClosed(); refactor.chooseDestinationForItem(NEW_PACKAGE_NAME); refactor.clickOkButtonRefactorForm(); refactor.waitMoveItemFormIsClosed(); loader.waitOnClosed(); projectExplorer.waitItem(PROJECT_NAME + "/test/java/com/org/ltd/ATest.java"); }</code><technical_language>a condition wait for</technical_language>

Target:
public void checkMoveJavaClassInNewSourceFolder() { projectExplorer.waitProjectExplorer(); projectExplorer.waitItem(PROJECT_NAME); projectExplorer.quickExpandWithJavaScript(); projectExplorer.openItemByPath(PATH_TO_FILE); projectExplorer.waitAndSelectItem(PROJECT_NAME); createNewFolder(NEW_FOLDER_NAME); projectExplorer.waitAndSelectItem(PROJECT_NAME + "/" + NEW_FOLDER_NAME); createNewFolder(NEW_SOURCE_FOLDER); projectExplorer.waitAndSelectItem(PATH_NEW_SOURCE_FOLDER); projectExplorer.openContextMenuByPathSelectedItem(PROJECT_NAME + "/test/" + NEW_SOURCE_FOLDER); projectExplorer.clickOnItemInContextMenu(BUILD_PATH); projectExplorer.clickOnItemInContextMenu(USE_AS_SOURCE_FOLDER); projectExplorer.waitDefinedTypeOfFolder(PATH_NEW_SOURCE_FOLDER, JAVA_SOURCE_FOLDER); projectExplorer.waitAndSelectItem(PATH_NEW_SOURCE_FOLDER); projectExplorer.openContextMenuByPathSelectedItem(PATH_NEW_SOURCE_FOLDER); createPackage(); projectExplorer.waitItem(PROJECT_NAME); projectExplorer.waitAndSelectItem(PATH_TO_FILE); projectExplorer.launchRefactorMoveByKeyboard(); refactor.waitMoveItemFormIsOpen(); refactor.clickOnExpandIconTree(PROJECT_NAME); refactor.clickOnExpandIconTree("/test/java"); loader.waitOnClosed(); refactor.chooseDestinationForItem(NEW_PACKAGE_NAME); refactor.clickOkButtonRefactorForm(); refactor.waitMoveItemFormIsClosed(); loader.waitOnClosed(); projectExplorer.waitItem(PROJECT_NAME + "/test/java/com/org/ltd/ATest.java"); }
Source:
<code>public boolean isTeleportBackWhenFreedFromJail() { <START> return config.getBoolean("teleport-back-when-freed-from-jail", true); <END> }</code><technical_language>alter this consistent pre-existing Essentials settings, reading config returning stored config is reloaded</technical_language>

Target:
public boolean isTeleportBackWhenFreedFromJail() { return teleportBackWhenFreedFromJail; }
Source:
<code>public boolean isClusterProxyApplicable(String cloudPlatform) { <START> return clusterProxyConfiguration.isClusterProxyIntegrationEnabled() && !CloudPlatform.MOCK.name().equals(cloudPlatform); <END> }</code><technical_language>instead of a hard coded value, a configurable instead of a single item a set/list disable multiple platforms if necessary</technical_language>

Target:
public boolean isClusterProxyApplicable(String cloudPlatform) { return clusterProxyConfiguration.isClusterProxyIntegrationEnabled() && !clusterProxyDisabledPlatforms.contains(cloudPlatform); }
Source:
<code>private void startCswSource() throws Exception { getServiceManager().waitForHttpEndpoint(CSW_PATH + "?_wadl"); getServiceManager() .createManagedService( CSW_FEDERATED_SOURCE_FACTORY_PID, getCswSourceProperties(CSW_SOURCE_ID, CSW_PATH.getUrl(), getServiceManager())); await("Waiting for CSW source to initialize") .atMost(10, TimeUnit.MINUTES) .pollDelay(1, TimeUnit.SECONDS) .until( <START> () -> <END> getServiceManager() .getServiceReferences(FederatedSource.class, null) .stream() .map(getServiceManager()::getService) .filter(src -> CSW_SOURCE_ID.equals(src.getId())) .anyMatch(Source::isAvailable)); }</code><technical_language>This increase readablity moving lambda a private method</technical_language>

Target:
private void startCswSource() throws Exception { getServiceManager().waitForHttpEndpoint(CSW_PATH + "?_wadl"); getServiceManager() .createManagedService( CSW_FEDERATED_SOURCE_FACTORY_PID, getCswSourceProperties(CSW_SOURCE_ID, CSW_PATH.getUrl(), getServiceManager())); await("Waiting for CSW source to initialize") .atMost(10, TimeUnit.MINUTES) .pollDelay(1, TimeUnit.SECONDS) .until(this::areSourcesReady); }
Source:
<code><START> public void coalesceWhiteSpacesSingleLine() { <END> String text = " Text with extra spaces. In the start, middle and end "; String expected = "Text with extra spaces. In the start, middle and end"; String result = Util.coalesceWhiteSpaces(text); Assert.assertEquals("White spaces should be coalesce to single white space", expected, result); }</code><technical_language>Braces line</technical_language>

Target:
public void coalesceWhiteSpacesSingleLine() { String text = " Text with extra spaces. In the start, middle and end "; String expected = "Text with extra spaces. In the start, middle and end"; String result = Util.coalesceWhitespace(text); Assert.assertEquals("White spaces should be coalesce to single white space", expected, result); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } XmlEntry other = (XmlEntry) obj; if (fBaseQuark != other.fBaseQuark) { return false; } if (fDisplayQuark != other.fDisplayQuark) { return false; } if (!Objects.equals(fElement, other.fElement)) { return false; } if (!Objects.equals(fId, other.fId)) { return false; } if (!Objects.equals(fParentId, other.fParentId)) { return false; } if (!fSs.equals(other.fSs)) { return false; } if (!fTrace.equals(other.fTrace)) { return false; } if <START> (!Objects.equals(fType, other.fType)) <END> { return false; } return true; }</code><technical_language>@Nonnull</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } XmlEntry other = (XmlEntry) obj; if (fBaseQuark != other.fBaseQuark) { return false; } if (fDisplayQuark != other.fDisplayQuark) { return false; } if (!Objects.equals(fElement, other.fElement)) { return false; } if (!Objects.equals(fId, other.fId)) { return false; } if (!Objects.equals(fParentId, other.fParentId)) { return false; } if (!fSs.equals(other.fSs)) { return false; } if (!fTrace.equals(other.fTrace)) { return false; } if (fType != other.fType) { return false; } return true; }
Source:
<code>public void creationSucceedsIfGivenValue() { <START> new Authenticator(Mockito.mock(AuthenticationChecker.class), Mockito.mock(AuthenticationOptionChecker.class)); <END> }</code><technical_language>Needs some sort of assert show succeeded</technical_language>

Target:
public void creationSucceedsIfGivenValue() { Authenticator auth = new Authenticator(Mockito.mock(AuthenticationChecker.class), Mockito.mock(AuthenticationOptionChecker.class)); Assert.assertNotNull(auth); }
Source:
<code>public void testWillMessageIsReceivedWithNonRetain() throws Exception { getServer().createQueue(SimpleString.toSimpleString("will"), RoutingType.MULTICAST, SimpleString.toSimpleString("will"), null, true, false); MQTT mqtt = createMQTTConnection("1", false); mqtt.setKeepAlive((short) 1); mqtt.setWillMessage("test message with non-retain"); mqtt.setWillTopic("will"); mqtt.setWillQos(QoS.AT_LEAST_ONCE); mqtt.setWillRetain(false); final BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisfied() throws Exception { return connection.isConnected(); } }); connection.kill(); <START> Thread.sleep(10000); <END> MQTT mqtt2 = createMQTTConnection("2", false); BlockingConnection connection2 = mqtt2.blockingConnection(); connection2.connect(); connection2.subscribe(new Topic[]{new Topic("will", QoS.AT_LEAST_ONCE)}); Message m = connection2.receive(1000, TimeUnit.MILLISECONDS); assertNotNull(m); m.ack(); assertEquals("test message with non-retain", new String(m.getPayload())); }</code><technical_language>no!!!!!!!!!!!!!!!! :) 10 seconds a test.. eternety.. I get rid of sleeps testsuite, :)</technical_language>

Target:
public void testWillMessageIsReceivedWithNonRetain() throws Exception { getServer().createQueue(SimpleString.toSimpleString("will"), RoutingType.MULTICAST, SimpleString.toSimpleString("will"), null, true, false); MQTT mqtt = createMQTTConnection("1", false); mqtt.setKeepAlive((short) 1); mqtt.setWillMessage("test message with non-retain"); mqtt.setWillTopic("will"); mqtt.setWillQos(QoS.AT_LEAST_ONCE); mqtt.setWillRetain(false); final BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisfied() throws Exception { return connection.isConnected(); } }); final CountDownLatch latch = new CountDownLatch(1); server.getRemotingService().getConnections().iterator().next().addCloseListener(new CloseListener() { @Override public void connectionClosed() { latch.countDown(); } }); connection.kill(); latch.await(10, TimeUnit.SECONDS); MQTT mqtt2 = createMQTTConnection("2", false); BlockingConnection connection2 = mqtt2.blockingConnection(); connection2.connect(); connection2.subscribe(new Topic[]{new Topic("will", QoS.AT_LEAST_ONCE)}); Message m = connection2.receive(1000, TimeUnit.MILLISECONDS); assertNotNull(m); m.ack(); assertEquals("test message with non-retain", new String(m.getPayload())); }
Source:
<code>getProblems(@QueryParam("table") @Pattern(regexp = ALPHA_NUM_REGEX_BLANK_OK) String table) { Map<String,Object> model = getModel(); model.put("title", "Per-Table Problem Report"); model.put("template", "problems.ftl"); model.put("js", "problems.js"); <START> if (!table.isBlank()) { <END> model.put("table", table); } return model; }</code><technical_language>This null, I think</technical_language>

Target:
getProblems(@QueryParam("table") @Pattern(regexp = ALPHA_NUM_REGEX_BLANK_OK) String table) { Map<String,Object> model = getModel(); model.put("title", "Per-Table Problem Report"); model.put("template", "problems.ftl"); model.put("js", "problems.js"); if (table != null && !table.isBlank()) { model.put("table", table); } return model; }
Source:
<code>public void createCDIProjectWithoutBeansXml(){ <START> cleanUpTheWorkspace(); <END> CDIProjectWizard cw = new CDIProjectWizard(); cw.open(); WebProjectFirstPage fp = new WebProjectFirstPage(cw); fp.setProjectName(PROJECT_NAME); if (CDIVersion.equals("2.0")) { new DefaultCombo(2).setSelection("Dynamic Web Project with CDI 2.0 (Contexts and Dependency Injection)"); } assertEquals(sr.getRuntimeName(),fp.getTargetRuntime()); assertEquals("Dynamic Web Project with CDI "+CDIVersion+" (Contexts and Dependency Injection)",fp.getConfiguration()); if (isJavaLE8() || CDIVersion.equals("1.0")) { fp.activateFacet("1.8", "Java"); } else { fp.activateFacet("11", "Java"); } cw.next(); cw.next(); cw.next(); CDIInstallWizardPage ip = new CDIInstallWizardPage(cw); ip.toggleCreateBeansXml(false); cw.finish(); new WaitUntil(new JobIsRunning(), TimePeriod.DEFAULT, false); new WaitWhile(new JobIsRunning(), TimePeriod.LONG); setWorkspaceDefaultJREForJava8(); isCDISupportEnabled(PROJECT_NAME); isCDIFacetEnabled(PROJECT_NAME, CDIVersion); ProjectExplorer pe = new ProjectExplorer(); pe.open(); assertTrue(pe.containsProject(PROJECT_NAME)); assertFalse(pe.getProject(PROJECT_NAME).containsResource("WebContent","WEB-INF","beans.xml")); new WaitUntil(new ProblemExists(ProblemType.ALL), TimePeriod.LONG, false); if (CDIVersion.equals("1.0")) { assertTrue(new ProblemExists(ProblemType.ALL).test()); } else { new WaitWhile(new ProblemExists(ProblemType.ALL)); } }</code><technical_language>If want is project in beginning of test (test class) CleanWorkplace requirement instead of calling method in other way</technical_language>

Target:
public void createCDIProjectWithoutBeansXml(){ CDIProjectWizard cw = new CDIProjectWizard(); cw.open(); WebProjectFirstPage fp = new WebProjectFirstPage(cw); fp.setProjectName(PROJECT_NAME); if (CDIVersion.equals("2.0")) { new DefaultCombo(2).setSelection("Dynamic Web Project with CDI 2.0 (Contexts and Dependency Injection)"); } assertEquals(sr.getRuntimeName(),fp.getTargetRuntime()); assertEquals("Dynamic Web Project with CDI "+CDIVersion+" (Contexts and Dependency Injection)",fp.getConfiguration()); activateFacets(fp); cw.next(); cw.next(); cw.next(); CDIInstallWizardPage ip = new CDIInstallWizardPage(cw); ip.toggleCreateBeansXml(false); cw.finish(); new WaitWhile(new JobIsRunning(), TimePeriod.LONG); isCDISupportEnabled(PROJECT_NAME); isCDIFacetEnabled(PROJECT_NAME, CDIVersion); ProjectExplorer pe = new ProjectExplorer(); pe.open(); assertTrue(pe.containsProject(PROJECT_NAME)); assertFalse(pe.getProject(PROJECT_NAME).containsResource("WebContent","WEB-INF","beans.xml")); new WaitUntil(new ProblemExists(ProblemType.ALL), TimePeriod.LONG, false); if (CDIVersion.equals("1.0")) { assertTrue(new ProblemExists(ProblemType.ALL).test()); } else { new WaitWhile(new ProblemExists(ProblemType.ALL)); } }
Source:
<code>private void updateActionTotals(Result result) { if(result.getAction().equals(Result.Action.INSERT)) { actionTotals.incrementTotalInsert(); } else if(result.getAction().equals(Result.Action.UPDATE)){ <START> actionTotals.incrementTotalUpdate(); <END> } else { actionTotals.incrementTotalError(); } }</code><technical_language>Please add else if clause for DELETE action is in DeleteTask, for completeness</technical_language>

Target:
private void updateActionTotals(Result result) { if(result.getAction().equals(Result.Action.INSERT)) { actionTotals.incrementTotalInsert(); } else if(result.getAction().equals(Result.Action.UPDATE)){ actionTotals.incrementTotalUpdate(); } else if(result.getStatus().equals(Result.Status.FAILURE)) { actionTotals.incrementTotalError(); } }
Source:
<code>public void getCountryShouldReturnCountry() { <START> Assert.assertEquals(Fixtures.loadUser(new HashMap<String, String>() {{ <END> put("country", "foobar"); }}).getCountry(), "foobar"); }</code><technical_language>declare a variable for user. do: Assert.assertEquals(user.getCountry(), "foobar"). Also, update tests right this change</technical_language>

Target:
public void getCountryShouldReturnCountry() { User user = Fixtures.loadUser(new HashMap<String, String>() {{ put("country", "foobar"); }}); Assert.assertEquals(user.getCountry(), "foobar"); }
Source:
<code>public Value toValue() { try { byte[] labelBytes = label.getBytes(CHARSET_NAME); int labelBytesLength = labelBytes.length; byte[] vertexIdBytes = vertexId.getBytes(CHARSET_NAME); int vertexIdBytesLength = vertexIdBytes.length; <START> int len = 4 + labelBytesLength + 4 + vertexIdBytesLength; <END> byte[] buffer = new byte[len]; int offset = 0; writeInt(labelBytesLength, buffer, offset); offset += 4; System.arraycopy(labelBytes, 0, buffer, offset, labelBytesLength); offset += labelBytesLength; writeInt(vertexIdBytesLength, buffer, offset); offset += 4; System.arraycopy(vertexIdBytes, 0, buffer, offset, vertexIdBytesLength); return new Value(buffer); } catch (UnsupportedEncodingException ex) { throw new VertexiumAccumuloIteratorException("Could not encode edge info", ex); } }</code><technical_language>4 a lot here. consider adding a descriptive constant this a more clear reading</technical_language>

Target:
public Value toValue() { byte[] labelBytes = label.getBytes(StandardCharsets.UTF_8); int labelBytesLength = labelBytes.length; byte[] vertexIdBytes = vertexId.getBytes(StandardCharsets.UTF_8); int vertexIdBytesLength = vertexIdBytes.length; int len = Integer.BYTES + labelBytesLength + Integer.BYTES + vertexIdBytesLength; byte[] buffer = new byte[len]; int offset = 0; writeInt(labelBytesLength, buffer, offset); offset += Integer.BYTES; System.arraycopy(labelBytes, 0, buffer, offset, labelBytesLength); offset += labelBytesLength; writeInt(vertexIdBytesLength, buffer, offset); offset += Integer.BYTES; System.arraycopy(vertexIdBytes, 0, buffer, offset, vertexIdBytesLength); return new Value(buffer); }
Source:
<code><START> public static Map<ManagedMemoryUseCase, Integer> getManagedMemoryUseCaseWeightsFromConfig(Configuration config) { <END> return config.get(TaskManagerOptions.MANAGED_MEMORY_CONSUMER_WEIGHTS) .entrySet().stream() .flatMap((entry) -> { final String consumer = entry.getKey(); final int weight = Integer.parseInt(entry.getValue()); if (weight < 0) { throw new IllegalConfigurationException(String.format( "Managed memory weight should not be negative. Configured weight for %s is %d.", consumer, weight)); } switch (consumer) { case TaskManagerOptions.ManagedMemoryConsumerNames.DATAPROC: return Stream.of( Tuple2.of(ManagedMemoryUseCase.BATCH_OP, weight), Tuple2.of(ManagedMemoryUseCase.ROCKSDB, weight)); case TaskManagerOptions.ManagedMemoryConsumerNames.PYTHON: return Stream.of(Tuple2.of(ManagedMemoryUseCase.PYTHON, weight)); default: throw new IllegalConfigurationException("Unknown managed memory consumer: " + consumer); } }) .collect(Collectors.toMap( (tuple2) -> tuple2.f0, (tuple2) -> tuple2.f1)); }</code><technical_language>this function package-private annotated "VisibleForTesting". other classes in future</technical_language>

Target:
static Map<ManagedMemoryUseCase, Integer> getManagedMemoryUseCaseWeightsFromConfig(Configuration config) { return config.get(TaskManagerOptions.MANAGED_MEMORY_CONSUMER_WEIGHTS) .entrySet().stream() .flatMap((entry) -> { final String consumer = entry.getKey(); final int weight = Integer.parseInt(entry.getValue()); if (weight < 0) { throw new IllegalConfigurationException(String.format( "Managed memory weight should not be negative. Configured weight for %s is %d.", consumer, weight)); } switch (consumer) { case TaskManagerOptions.ManagedMemoryConsumerNames.DATAPROC: return Stream.of( Tuple2.of(ManagedMemoryUseCase.BATCH_OP, weight), Tuple2.of(ManagedMemoryUseCase.ROCKSDB, weight)); case TaskManagerOptions.ManagedMemoryConsumerNames.PYTHON: return Stream.of(Tuple2.of(ManagedMemoryUseCase.PYTHON, weight)); default: throw new IllegalConfigurationException("Unknown managed memory consumer: " + consumer); } }) .collect(Collectors.toMap( (tuple2) -> tuple2.f0, (tuple2) -> tuple2.f1)); }
Source:
<code>public Collection<EObject> eRemoveInverseCrossReferences(EObject eObject, ECrossReferenceAdapter xref, EReferencePredicate isReferencesToIgnorePredicate) { <START> Collection<EObject> impactedEObjects = new ArrayList<EObject>(); <END> Collection<Setting> inverseReferences = xref.getInverseReferences(eObject, true); Collection<Setting> containmentReferences = getContainmentReferences(inverseReferences); Collection<Setting> otherReferences = getNonContainmentReferences(inverseReferences); for (EStructuralFeature.Setting setting : otherReferences) { boolean isChangeableFeature = setting.getEStructuralFeature().isChangeable(); boolean isFeatureToIgnore = isReferencesToIgnorePredicate != null && setting.getEStructuralFeature() instanceof EReference && isReferencesToIgnorePredicate.apply((EReference) setting.getEStructuralFeature()); if (isChangeableFeature && !isFeatureToIgnore) { EcoreUtil.remove(setting, eObject); impactedEObjects.add(setting.getEObject()); } } for (EStructuralFeature.Setting setting : containmentReferences) { boolean isChangeableFeature = setting.getEStructuralFeature().isChangeable(); boolean isFeatureToIgnore = isReferencesToIgnorePredicate != null && setting.getEStructuralFeature() instanceof EReference && isReferencesToIgnorePredicate.apply((EReference) setting.getEStructuralFeature()); if (isChangeableFeature && !isFeatureToIgnore) { EcoreUtil.remove(setting, eObject); impactedEObjects.add(setting.getEObject()); } } return impactedEObjects; }</code><technical_language>This a set, do want duplicates here. HashSet LinkedHashSet if order is required (or predictable order if iterate collection)</technical_language>

Target:
public Collection<EObject> eRemoveInverseCrossReferences(EObject eObject, ECrossReferenceAdapter xref, EReferencePredicate isReferencesToIgnorePredicate) { Collection<EObject> impactedEObjects = new LinkedHashSet<EObject>(); Collection<Setting> inverseReferences = xref.getInverseReferences(eObject, true); Collection<Setting> containmentReferences = getContainmentReferences(inverseReferences); Collection<Setting> otherReferences = getNonContainmentReferences(inverseReferences); for (EStructuralFeature.Setting setting : otherReferences) { boolean isChangeableFeature = setting.getEStructuralFeature().isChangeable(); boolean isFeatureToIgnore = isReferencesToIgnorePredicate != null && setting.getEStructuralFeature() instanceof EReference && isReferencesToIgnorePredicate.apply((EReference) setting.getEStructuralFeature()); if (isChangeableFeature && !isFeatureToIgnore) { EcoreUtil.remove(setting, eObject); impactedEObjects.add(setting.getEObject()); } } for (EStructuralFeature.Setting setting : containmentReferences) { boolean isChangeableFeature = setting.getEStructuralFeature().isChangeable(); boolean isFeatureToIgnore = isReferencesToIgnorePredicate != null && setting.getEStructuralFeature() instanceof EReference && isReferencesToIgnorePredicate.apply((EReference) setting.getEStructuralFeature()); if (isChangeableFeature && !isFeatureToIgnore) { EcoreUtil.remove(setting, eObject); impactedEObjects.add(setting.getEObject()); } } return impactedEObjects; }
Source:
<code>private void doHandleEmbedded(CommandContext ctx, ModelControllerClient client) throws CommandLineException { assert(embeddedServerRef != null); assert(embeddedServerRef.get() != null); final ModelNode op = this.buildRequestWithoutHeaders(ctx); <START> if (embeddedServerRef.get().isHostController()) { <END> op.get("admin-only").set(true); } try { final ModelNode response = client.execute(op); if(!Util.isSuccess(response)) { throw new CommandLineException(Util.getFailureDescription(response)); } } catch(IOException e) { StreamUtils.safeClose(client); throw new CommandLineException("Failed to execute :reload", e); } ensureServerRebootComplete(ctx, client); }</code><technical_language>WDYT adding some validation in this block? final ParsedCommandLine args = ctx.getParsedCommandLine(); if (this.adminOnly.isPresent(args) && "FALSE".equalsIgnoreCase(this.adminOnly.getValue(args)) { throw someExceptionCauseWeCantDoWhatTheyRequested; } Bonus is overriding canAppearNext() method of adminOnly returns false if embeddedServerRef.get() != null && embeddedServerRef.get().isHostController(). remove param tab completion</technical_language>

Target:
private void doHandleEmbedded(CommandContext ctx, ModelControllerClient client) throws CommandLineException { assert(embeddedServerRef != null); assert(embeddedServerRef.get() != null); final ModelNode op = this.buildRequestWithoutHeaders(ctx); if (embeddedServerRef.get().isHostController()) { final ParsedCommandLine args = ctx.getParsedCommandLine(); if (!this.adminOnly.isPresent(args) || "FALSE".equalsIgnoreCase(this.adminOnly.getValue(args))) { throw new CommandLineException("Reload into running mode is not supported, --admin-only=true must be specified."); } } try { final ModelNode response = client.execute(op); if(!Util.isSuccess(response)) { throw new CommandLineException(Util.getFailureDescription(response)); } } catch(IOException e) { StreamUtils.safeClose(client); throw new CommandLineException("Failed to execute :reload", e); } ensureServerRebootComplete(ctx, client); }
Source:
<code>public int getInt(String key, int default_value) { if (mPref.getAll().get(key) instanceof String) { try { return Integer.parseInt(mPref.getString(key, default_value + "")); } catch (NumberFormatException e) { Log.d(TAG, e.getMessage()); <START> return -1; <END> } } return mPref.getInt(key, default_value); }</code><technical_language>Minor improvement: Replace -1 default_value user get default if exception occurred</technical_language>

Target:
public int getInt(String key, int default_value) { if (mPref.getAll().get(key) instanceof String) { try { return Integer.parseInt(mPref.getString(key, default_value + "")); } catch (NumberFormatException e) { Log.d(TAG, e.getMessage()); return default_value; } } return mPref.getInt(key, default_value); }
Source:
<code>public void listNetworkSecurityRules() { final NetworkSecurityRule rule = createRule(); assertNotNull(rule); final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourcegroup, DEFAULT_NSG_NAME); List<NetworkSecurityRule> result = ruleApi.list(); assertNotNull(result); assertEquals(result.size(), 2); boolean rulePresent = false; for (int i = 0; i < result.size(); i++) { if (result.get(i).name().equals(rule.name())) { rulePresent = true; break; } } <START> assertTrue(rulePresent); <END> }</code><technical_language>for a more idiomatic approach Iterables.any</technical_language>

Target:
public void listNetworkSecurityRules() { final NetworkSecurityRule rule = createRule(); assertNotNull(rule); final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourcegroup, DEFAULT_NSG_NAME); List<NetworkSecurityRule> result = ruleApi.list(); assertNotNull(result); assertEquals(result.size(), 2); boolean rulePresent = Iterables.any(result, new Predicate<NetworkSecurityRule>() { public boolean apply(NetworkSecurityRule input) { return input.name().equals(rule.name()); } }); assertTrue(rulePresent); }
Source:
<code>private void renderOwner(ChangeInfo info) { String name = info.owner().name() != null ? info.owner().name() : Gerrit.getConfig().getAnonymousCowardName(); <START> ownerPanel.insert(new AvatarImage(info.owner()), 0); <END> ownerLink.setText(name); ownerLink.setTitle(info.owner().email() != null ? info.owner().email() : name); ownerLink.setTargetHistoryToken(PageLinks.toAccountQuery( info.owner().name() != null ? info.owner().name() : info.owner().email() != null ? info.owner().email() : String.valueOf(info.owner()._account_id()), Change.Status.NEW)); }</code><technical_language>insert image if owner a URL: AvatarInfo img = owner.avatar(AvatarInfo.DEFAULT_SIZE); if (img != null) { ownerPanel.insert(..., 0); } matches behavior Reviewer/"cc" chips next line in info table</technical_language>

Target:
private void renderOwner(ChangeInfo info) { String name = info.owner().name() != null ? info.owner().name() : Gerrit.getConfig().getAnonymousCowardName(); if (info.owner().avatar(AvatarInfo.DEFAULT_SIZE) != null) { ownerPanel.insert(new AvatarImage(info.owner()), 0); } ownerLink.setText(name); ownerLink.setTitle(info.owner().email() != null ? info.owner().email() : name); ownerLink.setTargetHistoryToken(PageLinks.toAccountQuery( info.owner().name() != null ? info.owner().name() : info.owner().email() != null ? info.owner().email() : String.valueOf(info.owner()._account_id()), Change.Status.NEW)); }
Source:
<code>public void genericValues() { final CEPWindow cepWindow = new CEPWindow(); cepWindow.setOperator("over window:time"); cepWindow.setParameters(new HashMap<>()); <START> assertNotNull(cepWindow.hashCode()); <END> }</code><technical_language>License please</technical_language>

Target:
public void genericValues() { final CEPWindow other = new CEPWindow(); other.setOperator("over window:time"); other.setParameters(makeTestParameters()); assertNotNull(cepWindowAllFieldsFilled.hashCode()); assertNotNull(other.hashCode()); assertEquals(cepWindowAllFieldsFilled.hashCode(), other.hashCode()); }
Source:
<code>public Scope getScope(Token token) { if (token.length() != tokenSize) { return Scope.SHORT_TERM_CLIENT_LOCAL; } int scope = token.getBytes()[0] & 0x3; switch (scope) { case 0: return Scope.SHORT_TERM_CLIENT_LOCAL; case 2: return Scope.SHORT_TERM; } <START> return Scope.LONG_TERM; <END> }</code><technical_language>binary notation in switch</technical_language>

Target:
public Scope getScope(Token token) { if (token.length() != tokenSize) { return Scope.SHORT_TERM_CLIENT_LOCAL; } int scope = token.getBytes()[0] & 0b11; switch (scope) { case 0b00: return Scope.SHORT_TERM_CLIENT_LOCAL; case 0b10: return Scope.SHORT_TERM; } return Scope.LONG_TERM; }
Source:
<code>public static EffectiveTLD getEffectiveTLD(String hostname, boolean excludePrivate) { if (getInstance().domains.containsKey(hostname)) { EffectiveTLD foundTld = getInstance().domains.get(hostname); if (!excludePrivate || !foundTld.isPrivate) { return foundTld; <START> } <END> } String[] parts = hostname.split(DOT_REGEX); for (int i = 1; i < parts.length; i++) { String[] slice = Arrays.copyOfRange(parts, i, parts.length); String tryTld = join(slice); if (LOGGER.isDebugEnabled()) { LOGGER.debug(hostname + " [" + i + ".." + parts.length + "]: " + Arrays.toString(slice) + " => " + tryTld); } if (getInstance().domains.containsKey(tryTld)) { EffectiveTLD foundTld = getInstance().domains.get(tryTld); if (excludePrivate && foundTld.isPrivate) { continue; } if (foundTld.isException() || !foundTld.isWild()) { return foundTld; } slice = Arrays.copyOfRange(parts, i - 1, parts.length); String retryTld = join(slice); foundTld = new EffectiveTLD(retryTld, foundTld.isPrivate); return foundTld; } } return null; }</code><technical_language>minor nit, !(excludePrivate && foundTld.isPrivate) is clearer me</technical_language>

Target:
public static EffectiveTLD getEffectiveTLD(String hostname, boolean excludePrivate) { if (getInstance().domains.containsKey(hostname)) { EffectiveTLD foundTld = getInstance().domains.get(hostname); if (!(excludePrivate && foundTld.isPrivate)) { return foundTld; } } String[] parts = hostname.split(DOT_REGEX); for (int i = 1; i < parts.length; i++) { String[] slice = Arrays.copyOfRange(parts, i, parts.length); String tryTld = join(slice); if (LOGGER.isDebugEnabled()) { LOGGER.debug(hostname + " [" + i + ".." + parts.length + "]: " + Arrays.toString(slice) + " => " + tryTld); } if (getInstance().domains.containsKey(tryTld)) { EffectiveTLD foundTld = getInstance().domains.get(tryTld); if (excludePrivate && foundTld.isPrivate) { continue; } if (foundTld.isException() || !foundTld.isWild()) { return foundTld; } slice = Arrays.copyOfRange(parts, i - 1, parts.length); String retryTld = join(slice); foundTld = new EffectiveTLD(retryTld, foundTld.isPrivate); return foundTld; } } return null; }
Source:
<code>protected static void saveToFile(ProjectMetadata projectMeta, File metadataFile) throws IOException { <START> Writer writer = new OutputStreamWriter(new FileOutputStream(metadataFile), StandardCharsets.UTF_8); <END> try { ParsingUtilities.defaultWriter.writeValue(writer, projectMeta); } finally { writer.close(); } }</code><technical_language>making deserializer more flexible respect encoding issues (just configured accept unescaped tabs)? I checked if is though</technical_language>

Target:
protected static void saveToFile(ProjectMetadata projectMeta, File metadataFile) throws IOException { Writer writer = new OutputStreamWriter(new FileOutputStream(metadataFile), StandardCharsets.UTF_8); try { ParsingUtilities.saveWriter.writeValue(writer, projectMeta); } finally { writer.close(); } }
Source:
<code>public abstract long getRemoteVersion(ClientBlobStore store) throws KeyNotFoundException, AuthorizationException; public abstract long fetchUnzipToTemp(ClientBlobStore store) throws IOException, KeyNotFoundException, AuthorizationException; public abstract void commitNewVersion(long version) throws IOException; public abstract void cleanupOrphanedData() throws IOException; public abstract void completelyRemove() throws IOException; public abstract long getSizeOnDisk(); protected static long getSizeOnDisk(Path p) throws IOException { if (!Files.exists(p)) { return 0; } else if (Files.isRegularFile(p)) { return Files.size(p); } else { return Files.walk(p) .filter((subp) -> Files.isRegularFile(subp, LinkOption.NOFOLLOW_LINKS)) .mapToLong((subp) -> { try { return Files.size(subp); } catch (IOException e) { <START> LOG.warn("Could not get the size of "); <END> } return 0; }).sum(); } }</code><technical_language>This is complete. get size of what</technical_language>

Target:
public abstract long getRemoteVersion(ClientBlobStore store) throws KeyNotFoundException, AuthorizationException; public abstract long fetchUnzipToTemp(ClientBlobStore store) throws IOException, KeyNotFoundException, AuthorizationException; public abstract void commitNewVersion(long version) throws IOException; public abstract void cleanupOrphanedData() throws IOException; public abstract void completelyRemove() throws IOException; public abstract long getSizeOnDisk(); protected static long getSizeOnDisk(Path p) throws IOException { if (!Files.exists(p)) { return 0; } else if (Files.isRegularFile(p)) { return Files.size(p); } else { return Files.walk(p) .filter((subp) -> Files.isRegularFile(subp, LinkOption.NOFOLLOW_LINKS)) .mapToLong((subp) -> { try { return Files.size(subp); } catch (IOException e) { LOG.warn("Could not get the size of {}", subp); } return 0; }).sum(); } }
Source:
<code>public Response intercept(Chain chain) throws IOException { Request request = chain.request(); OpenSpan callState = Tracer.startSpan(request.method() + " " + request.urlString()); Request.Builder instrumentedRequest = new Request.Builder() .headers(request.headers()) .url(request.url()) .method(request.method(), request.body()) .header(TraceHttpHeaders.TRACE_ID, Tracer.getTraceId()) <START> .header(TraceHttpHeaders.SPAN_ID, callState.getSpanId()); <END> if (callState.getParentSpanId().isPresent()) { instrumentedRequest.header(TraceHttpHeaders.PARENT_SPAN_ID, callState.getParentSpanId().get()); } Response response; try { response = chain.proceed(instrumentedRequest.build()); } finally { Tracer.completeSpan(); } return response; }</code><technical_language>need encode sampling header here</technical_language>

Target:
public Response intercept(Chain chain) throws IOException { Request request = chain.request(); OpenSpan callState = Tracer.startSpan(request.method() + " " + request.urlString()); Request.Builder instrumentedRequest = new Request.Builder() .headers(request.headers()) .url(request.url()) .method(request.method(), request.body()) .header(TraceHttpHeaders.TRACE_ID, Tracer.getTraceId()) .header(TraceHttpHeaders.SPAN_ID, callState.getSpanId()) .header(TraceHttpHeaders.IS_SAMPLED, Tracer.isTraceObservable() ? "1" : "0"); if (callState.getParentSpanId().isPresent()) { instrumentedRequest.header(TraceHttpHeaders.PARENT_SPAN_ID, callState.getParentSpanId().get()); } Response response; try { response = chain.proceed(instrumentedRequest.build()); } finally { Tracer.completeSpan(); } return response; }
Source:
<code>public void onError(final String reason) { logger.warn("Error on delivery: {}", variant.getType().getTypeName(), reason); pushMessageMetricsService.appendError(pushMessageInformation, variant, reason); <START> pushMessageSendingMetricsProducer.send(KAFKA_PUSH_MESSAGE_SENDING_METRICS_TOPIC, KAFKA_PUSH_MESSAGE_SENDING_FAILURE); <END> }</code><technical_language>sense jobId key ? (e.g. .getId FlatPMI ?)</technical_language>

Target:
public void onError(final String reason) { logger.warn("Error on '{}' delivery: {}", variant.getType().getTypeName(), reason); pushMessageMetricsService.appendError(pushMessageInformation, variant, reason); pushDeliveryMetricsProducer.send(KAFKA_PUSH_DELIVERY_METRICS_TOPIC, pushMessageInformation.getId(), KAFKA_METRICS_ON_DELIVERY_FAILURE); }
Source:
<code>public static String relativize(String base, String other) { if (base.equals(other)) return ""; final String[] baseSegments = base.split(Pattern.quote(File.separator)); final String[] otherSegments = other.split(Pattern .quote(File.separator)); int commonPrefix = 0; while (commonPrefix < baseSegments.length && commonPrefix < otherSegments.length) { <START> if (baseSegments[commonPrefix].equals(otherSegments[commonPrefix])) <END> commonPrefix++; else break; } final StringBuilder builder = new StringBuilder(); for (int i = commonPrefix; i < baseSegments.length; i++) builder.append("..").append(File.separator); for (int i = commonPrefix; i < otherSegments.length; i++) { builder.append(otherSegments[i]); if (i < otherSegments.length - 1) builder.append(File.separator); } return builder.toString(); }</code><technical_language>If interprete base other Strings in current filesystem care case sensitivity. E.g. Windows base="C:\git\jgit" ours="C:\Git\test\d\f.txt" lead "..\test\d\f.txt". current implementation return "..\..\Git\test\d\f.txt". Windows "C:\Git" "C:\git" refer folder. a shame Java7. is Path.relativize(). I need some tests here</technical_language>

Target:
public static String relativize(String base, String other) { if (base.equals(other)) return ""; final boolean ignoreCase = SystemReader.getInstance().isWindows(); final String[] baseSegments = base.split(Pattern.quote(File.separator)); final String[] otherSegments = other.split(Pattern .quote(File.separator)); int commonPrefix = 0; while (commonPrefix < baseSegments.length && commonPrefix < otherSegments.length) { if (ignoreCase && baseSegments[commonPrefix] .equalsIgnoreCase(otherSegments[commonPrefix])) commonPrefix++; else if (!ignoreCase && baseSegments[commonPrefix] .equals(otherSegments[commonPrefix])) commonPrefix++; else break; } final StringBuilder builder = new StringBuilder(); for (int i = commonPrefix; i < baseSegments.length; i++) builder.append("..").append(File.separator); for (int i = commonPrefix; i < otherSegments.length; i++) { builder.append(otherSegments[i]); if (i < otherSegments.length - 1) builder.append(File.separator); } return builder.toString(); }
Source:
<code><START> protected void testExecute_withInvalidInstructorId_shouldFail() { <END> InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); String[] submissionParams = new String[] { Const.ParamsNames.INSTRUCTOR_ID, "invalid-instructor-id", Const.ParamsNames.COURSE_ID, instructor1OfCourse1.getCourseId(), }; InstructorPrivilegeUpdateRequest reqBody = new InstructorPrivilegeUpdateRequest(); reqBody.setCanViewStudentInSections(true); reqBody.setCanSubmitSessionInSections(true); reqBody.setFeedbackSessionName("session1"); UpdateInstructorPrivilegeAction action = getAction(reqBody, submissionParams); JsonResult result = getJsonResult(action); assertEquals(HttpStatus.SC_NOT_FOUND, result.getStatusCode()); MessageOutput msg = (MessageOutput) result.getOutput(); assertEquals("Instructor does not exist.", msg.getMessage()); }</code><technical_language>for invalid id</technical_language>

Target:
protected void testExecute_withInvalidInstructorId_shouldFail() { InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); String[] submissionParams = new String[] { Const.ParamsNames.INSTRUCTOR_EMAIL, "invalid-instructor-email", Const.ParamsNames.COURSE_ID, instructor1OfCourse1.getCourseId(), }; InstructorPrivilegeUpdateRequest reqBody = new InstructorPrivilegeUpdateRequest(); reqBody.setCanViewStudentInSections(true); reqBody.setCanSubmitSessionInSections(true); reqBody.setFeedbackSessionName("session1"); UpdateInstructorPrivilegeAction action = getAction(reqBody, submissionParams); JsonResult result = getJsonResult(action); assertEquals(HttpStatus.SC_NOT_FOUND, result.getStatusCode()); MessageOutput msg = (MessageOutput) result.getOutput(); assertEquals("Instructor does not exist.", msg.getMessage()); }
Source:
<code>default B with(BigDecimal data) { byte[] value = data.unscaledValue().toByteArray(); <START> return with( ByteBuffer.allocate( Integer.BYTES+value.length ) <END> .putInt( data.scale() ).put( value ).array() ); }</code><technical_language>return with( ByteBuffer.allocate( Integer.BYTES + value.length )</technical_language>

Target:
default B with(BigDecimal data) { byte[] value = data.unscaledValue().toByteArray(); byte[] scale = new byte[] {(byte) (data.scale() ), (byte) (data.scale() >> 8), (byte) (data.scale() >> 16), (byte) (data.scale() >> 24)}; byte[] buff = new byte[value.length + scale.length]; System.arraycopy( scale, 0, buff, 0, scale.length); System.arraycopy( value, 0, buff, scale.length, value.length); return with( buff ); }
Source:
<code>public static void main(String args[]) throws Exception { VerifiableProperties properties = ToolUtils.getVerifiableProperties(args); ConsistencyCheckerToolConfig config = new ConsistencyCheckerToolConfig(properties); ClusterMapConfig clusterMapConfig = new ClusterMapConfig(properties); ServerConfig serverConfig = new ServerConfig(properties); try (ClusterMap clusterMap = new StaticClusterAgentsFactory(clusterMapConfig, config.hardwareLayoutFilePath, config.partitionLayoutFilePath).getClusterMap()) { StoreToolsMetrics metrics = new StoreToolsMetrics(clusterMap.getMetricRegistry()); StoreConfig storeConfig = new StoreConfig(properties); BlobIdFactory blobIdFactory = new BlobIdFactory(clusterMap); Set<StoreKey> filterKeySet = new HashSet<>(); for (String key : config.filterSet) { filterKeySet.add(new BlobId(key, clusterMap)); } Time time = SystemTime.getInstance(); Throttler throttler = new Throttler(config.indexEntriesToProcessPerSec, 1000, true, time); <START> StoreKeyConverterFactory storeKeyConverterFactory = Utils.getObj(serverConfig.serverStoreKeyConverterFactory, properties, null); <END> ConsistencyCheckerTool consistencyCheckerTool = new ConsistencyCheckerTool(clusterMap, blobIdFactory, storeConfig, filterKeySet, throttler, metrics, time, storeKeyConverterFactory.getStoreKeyConverter()); boolean success = consistencyCheckerTool.checkConsistency(config.pathOfInput.listFiles(File::isDirectory)).getFirst(); System.exit(success ? 0 : 1); } }</code><technical_language>pass metric registry? clusterMap.getMetricRegistry()</technical_language>

Target:
public static void main(String args[]) throws Exception { VerifiableProperties properties = ToolUtils.getVerifiableProperties(args); ConsistencyCheckerToolConfig config = new ConsistencyCheckerToolConfig(properties); ClusterMapConfig clusterMapConfig = new ClusterMapConfig(properties); ServerConfig serverConfig = new ServerConfig(properties); try (ClusterMap clusterMap = new StaticClusterAgentsFactory(clusterMapConfig, config.hardwareLayoutFilePath, config.partitionLayoutFilePath).getClusterMap()) { StoreToolsMetrics metrics = new StoreToolsMetrics(clusterMap.getMetricRegistry()); StoreConfig storeConfig = new StoreConfig(properties); BlobIdFactory blobIdFactory = new BlobIdFactory(clusterMap); Set<StoreKey> filterKeySet = new HashSet<>(); for (String key : config.filterSet) { filterKeySet.add(new BlobId(key, clusterMap)); } Time time = SystemTime.getInstance(); Throttler throttler = new Throttler(config.indexEntriesToProcessPerSec, 1000, true, time); StoreKeyConverterFactory storeKeyConverterFactory = Utils.getObj(serverConfig.serverStoreKeyConverterFactory, properties, clusterMap.getMetricRegistry()); ConsistencyCheckerTool consistencyCheckerTool = new ConsistencyCheckerTool(clusterMap, blobIdFactory, storeConfig, filterKeySet, throttler, metrics, time, storeKeyConverterFactory.getStoreKeyConverter()); boolean success = consistencyCheckerTool.checkConsistency(config.pathOfInput.listFiles(File::isDirectory)).getFirst(); System.exit(success ? 0 : 1); } }
Source:
<code><START> private boolean shouldLogToAuditLog() { <END> boolean retValue = (getParameters().getNamesOfVms() == null || getParameters().getNamesOfVms().isEmpty()) ? false : true; return retValue; }</code><technical_language>this method simplified return CollectionUtils.isNotEmpty(getParameters().getNamesOfVms());</technical_language>

Target:
private boolean shouldLogToAuditLog() { return CollectionUtils.isNotEmpty(getParameters().getNamesOfVms()); }
Source:
<code>public String toString() { <START> return Arrays.stream(value).map(String::valueOf).collect(Collectors.joining(", ")); <END> }</code><technical_language>suggestion return Arrays.toString(value);</technical_language>

Target:
public String toString() { return Arrays.toString(value); }
Source:
<code>protected void executeCommand() { <START> getDbFacade().getDiskProfileDao().remove(getParameters().getProfileId()); <END> }</code><technical_language>setSucceeded</technical_language>

Target:
protected void executeCommand() { getDbFacade().getDiskProfileDao().remove(getParameters().getProfileId()); setSucceeded(true); }
Source:
<code>public void testApplyBlockUpdatesToTrainingDataWhenEpochBegins() { final int numInitialInstances = MINI_BATCH_SIZE * 10; final int blockId = generateBlockIdNotInLocalStore().get(0); final Map<Long, Integer> dataSet = generateDataSetForBlock(blockId, MAX_BLOCK_SIZE); <START> final MoveHandler moveHandler = (MoveHandler) memoryStore; <END> createTrainingData(numInitialInstances); trainingDataProvider.prepareDataForEpoch(); moveHandler.putBlock(blockId, (Map) dataSet); operationRouter.updateOwnership(blockId, REMOTE_STORE_ID, LOCAL_STORE_ID); kvMapBackingMemoryStore.putAll(dataSet); testGetNextTrainingData(numInitialInstances + dataSet.size()); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); trainingDataProvider.prepareDataForEpoch(); moveHandler.removeBlock(blockId); operationRouter.updateOwnership(blockId, LOCAL_STORE_ID, REMOTE_STORE_ID); for (final Long key : dataSet.keySet()) { kvMapBackingMemoryStore.remove(key); } testGetNextTrainingData(numInitialInstances); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); }</code><technical_language>please a separate MoveHandler moveHandler, a global variable</technical_language>

Target:
public void testApplyBlockUpdatesToTrainingDataWhenEpochBegins() { final int numMiniBatches = 10; final int numInitialInstances = MINI_BATCH_SIZE * numMiniBatches; final int blockId = generateBlockIdNotInLocalStore().get(0); final Map<Long, Integer> dataSet = generateDataSetForBlock(blockId, BLOCK_SIZE); createTrainingData(numInitialInstances); trainingDataProvider.prepareDataForEpoch(); putBlockToMemoryStore(blockId, dataSet); testGetNextTrainingData(numInitialInstances + dataSet.size()); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); trainingDataProvider.prepareDataForEpoch(); removeBlockFromMemoryStore(blockId); testGetNextTrainingData(numInitialInstances); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); }
Source:
<code>private int readLastBlock(final byte[] b, final int off, final int len) throws IOException { int validation = validate(b, off, len); if (validation < 1) { return validation; } buffer = new byte[bufferSize]; bCursor = (int) (((contentLength < bufferSize) ? contentLength : bufferSize) - FOOTER_SIZE); long lastBlockStartPos = (contentLength < bufferSize) ? 0 : contentLength - bufferSize; int bytesRead = readInternal(lastBlockStartPos, buffer, 0, bufferSize, <START> true); <END> firstRead = false; if (bytesRead == -1) { return -1; } fCursorAfterLastRead = fCursor; limit = bytesRead; fCursor = lastBlockStartPos + bytesRead; return copyToUserBuffer(b, off, len); }</code><technical_language>In new handling, bypassing readAheads. (Unless readAhead is disabled) if read.request.size is configured 100MB, data read store in 4MB chunks is readAhead buffer size. If of logics determines more data earlier offset needs read, is triggering reads bypassing readAheads. wont end in a 100MB direct read store</technical_language>

Target:
private int readLastBlock(final byte[] b, final int off, final int len) throws IOException { if (len == 0) { return 0; } if (!validate(b, off, len)) { return -1; } savePointerState(); long lastBlockStart = max(0, contentLength - bufferSize); bCursor = (int) (fCursor - lastBlockStart); long actualLenToRead = min(bufferSize, contentLength); return optimisedRead(b, off, len, lastBlockStart, actualLenToRead); }