auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void handleSaveInstanceStateRequest( REQID rid, SocketChannel channel, CheckpointManager.SaveInstanceStateRequest request ) { Checkpoint checkpoint = new Checkpoint(topologyName, request); LOG.info("Got a save checkpoint request for " + checkpoint.getCheckpointId() + " " + checkpoint.getComponent() + " " + checkpoint.getInstance() + " on connection: " + channel.socket().getRemoteSocketAddress()); Common.StatusCode statusCode = Common.StatusCode.OK; try { checkpointsBackend.store(checkpoint); LOG.info("Save checkpoint successful for " + checkpoint.getCheckpointId() + " " + checkpoint.getComponent() + " " + checkpoint.getInstance()); } catch (StatefulStorageException e) { LOG.info("Save checkpoint not successful for " + checkpoint.getCheckpointId() + " " + checkpoint.getComponent() + " " + checkpoint.getInstance() + " error: " + e); statusCode = Common.StatusCode.NOTOK; } CheckpointManager.SaveInstanceStateResponse.Builder responseBuilder = CheckpointManager.SaveInstanceStateResponse.newBuilder(); responseBuilder.setStatus(Common.Status.newBuilder().setStatus(statusCode)); responseBuilder.setCheckpointId(request.getCheckpoint().getCheckpointId()); responseBuilder.setInstance(request.getInstance()); sendResponse(rid, channel, responseBuilder.build()); }

Target:
protected void handleSaveInstanceStateRequest( REQID rid, SocketChannel channel, CheckpointManager.SaveInstanceStateRequest request ) { Checkpoint checkpoint = new Checkpoint(topologyName, request.getInstance(), request.getCheckpoint()); LOG.info(String.format("Got a save checkpoint request for checkpointId %s " + " component %s instance %s on connection %s", checkpoint.getCheckpointId(), checkpoint.getComponent(), checkpoint.getInstance(), channel.socket().getRemoteSocketAddress())); Common.StatusCode statusCode = Common.StatusCode.OK; String errorMessage = ""; try { statefulStorage.store(checkpoint); LOG.info(String.format("Saved checkpoint for checkpointId %s compnent %s instance %s", checkpoint.getCheckpointId(), checkpoint.getComponent(), checkpoint.getInstance())); } catch (StatefulStorageException e) { errorMessage = String.format("Save checkpoint not successful for checkpointId " + "%s component %s instance %s", checkpoint.getCheckpointId(), checkpoint.getComponent(), checkpoint.getInstance()); statusCode = Common.StatusCode.NOTOK; LOG.log(Level.WARNING, errorMessage, e); } CheckpointManager.SaveInstanceStateResponse.Builder responseBuilder = CheckpointManager.SaveInstanceStateResponse.newBuilder(); responseBuilder.setStatus(Common.Status.newBuilder().setStatus(statusCode) .setMessage(errorMessage)); responseBuilder.setCheckpointId(request.getCheckpoint().getCheckpointId()); responseBuilder.setInstance(request.getInstance()); sendResponse(rid, channel, responseBuilder.build()); }
Source:
public void propertyChange(PropertyChangeEvent evt) { if (renderingConfig.isDynamicShadows()) { int shadowMapResFromSettings = (int) evt.getNewValue(); shadowMapResolution = new FBO.Dimensions(shadowMapResFromSettings, shadowMapResFromSettings); for (Map.Entry<ResourceUrn, FBOConfig> entry : fboConfigs.entrySet()) { ResourceUrn resourceUrn = entry.getKey(); FBOConfig fboConfig = entry.getValue(); if (fboLookup.containsKey(resourceUrn)) { FBO fbo = fboLookup.get(resourceUrn); if (fbo != null) { fbo.dispose(); } } FBO shadowMapResDependentFBO = generateWithDimensions(fboConfig, shadowMapResolution); if (shadowMapResDependentFBO.getStatus() == FBO.Status.DISPOSED) { logger.warn("Failed to generate ShadowMap FBO. Turning off shadows."); renderingConfig.setDynamicShadows(false); break; } fboLookup.put(resourceUrn, shadowMapResDependentFBO); } } }

Target:
public void propertyChange(PropertyChangeEvent evt) { if (renderingConfig.isDynamicShadows()) { int shadowMapResFromSettings = (int) evt.getNewValue(); shadowMapResolution = new FBO.Dimensions(shadowMapResFromSettings, shadowMapResFromSettings); for (Map.Entry<ResourceUrn, FBOConfig> entry : fboConfigs.entrySet()) { ResourceUrn fboName = entry.getKey(); FBOConfig fboConfig = entry.getValue(); if (fboLookup.containsKey(fboName)) { FBO fbo = fboLookup.get(fboName); if (fbo != null) { fbo.dispose(); } } FBO shadowMapResDependentFBO = generateWithDimensions(fboConfig, shadowMapResolution); if (shadowMapResDependentFBO.getStatus() == FBO.Status.DISPOSED) { logger.warn("Failed to generate ShadowMap FBO. Turning off shadows."); renderingConfig.setDynamicShadows(false); break; } fboLookup.put(fboName, shadowMapResDependentFBO); } } }
Source:
public PageTitle getFirstResult() { if (totalResults != null) { return totalResults.get(0); } else { return null; } }

Target:
public PageTitle getFirstResult() { if (totalResults != null && !totalResults.isEmpty()) { return totalResults.get(0); } else { return null; } }
Source:
public void testTriggerRedisStopEffector() throws InterruptedException { ClientResponse response = client().resource("/v1/applications/redis-app/entities/redis-ent/effectors/stop") .post(ClientResponse.class, ImmutableMap.of()); assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode()); URI stateSensor = URI.create("/v1/applications/redis-app/entities/redis-ent/sensors/service.state"); String expectedStatus = String.format("\"%s\"", Lifecycle.STOPPED.toString()); String actualStatus = null; for (int iter = 0; iter < 30 && !expectedStatus.equals(actualStatus); iter++) { Thread.sleep(2000); actualStatus = client().resource(stateSensor).get(String.class); } assertEquals(actualStatus, expectedStatus); }

Target:
public void testTriggerRedisStopEffector() throws InterruptedException { ClientResponse response = client().resource("/v1/applications/redis-app/entities/redis-ent/effectors/stop") .post(ClientResponse.class, ImmutableMap.of()); assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode()); final URI stateSensor = URI.create("/v1/applications/redis-app/entities/redis-ent/sensors/service.state"); final String expectedStatus = String.format("\"%s\"", Lifecycle.STOPPED.toString()); Asserts.succeedsEventually(MutableMap.of("timeout", 60 * 1000), new Runnable() { public void run() { assertEquals(client().resource(stateSensor).get(String.class), expectedStatus); } }); }
Source:
public JSONObject getAnnouncements() { LOG.debug("get announcements"); final SqlSession session = factory.openSession(); JSONObject data = new JSONObject(); try { final AnnouncementsMapper mapper = session.getMapper(AnnouncementsMapper.class); data = parser.parseAnnouncementsMap(mapper.getAnnouncements()); session.commit(); } catch (Exception e) { throw new RuntimeException("Failed to get announcements", e); } finally { session.close(); } return data; }

Target:
public JSONObject getAnnouncements() { try (final SqlSession session = factory.openSession()) { final AnnouncementsMapper mapper = session.getMapper(AnnouncementsMapper.class); return parser.parseAnnouncementsMap(mapper.getAnnouncements(LocalDate.now())); } catch (Exception e) { throw new ServiceRuntimeException("Failed to get announcements", e); } }
Source:
public int getNumUnits(final String dataType) { if (typeToBlocks.containsKey(dataType)) { return 0; } int numUnits = 0; final Collection<Block> blocks = typeToBlocks.get(dataType).values(); for (final Block block : blocks) { numUnits += block.getNumUnits(); } return numUnits; }

Target:
public int getNumUnits(final String dataType) { if (!typeToBlocks.containsKey(dataType)) { return 0; } int numUnits = 0; final Collection<Block> blocks = typeToBlocks.get(dataType).values(); for (final Block block : blocks) { numUnits += block.getNumUnits(); } return numUnits; }
Source:
private void _putWithoutTag(Metric metric) { String rowKeyScopeTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), null, null, SCOPE_SCHEMA_TABLENAME); String rowKeyMetricTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), null, null, METRIC_SCHEMA_TABLENAME); boolean exists = false; if(_cacheEnabled) { exists = _trie.getValueForExactKey(rowKeyScopeTable) != null; } if(!exists) { _put(SCOPE_SCHEMA_TABLENAME, rowKeyScopeTable); _put(METRIC_SCHEMA_TABLENAME, rowKeyMetricTable); if(_cacheEnabled) { _trie.putIfAbsent(rowKeyScopeTable, VoidValue.SINGLETON); } _monitorService.modifyCounter(MonitorService.Counter.SCHEMARECORDS_WRITTEN, 2, null); } }

Target:
private void _putWithoutTag(Metric metric) { String rowKeyScopeTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), null, null, SCOPE_SCHEMA_TABLENAME); String rowKeyMetricTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), null, null, METRIC_SCHEMA_TABLENAME); _putIfAbsent(rowKeyScopeTable, rowKeyMetricTable); }
Source:
public SearchResults stepAll(int steps) throws KRunExecutionException { if (currentState == null) { throw new IllegalStateException("Cannot step without a current state to step from. " + "If you previously used the search command you must" + "first select a solution with the select command before executing steps of rewrites!"); } SearchResults results = executor.search(null, steps, SearchType.PLUS, defaultPattern, getState(currentState).getRawResult(), defaultPatternInfo, false); mergeSearchGraph(results.getGraph()); currentState = null; return results; }

Target:
public SearchResults stepAll(int steps) throws KRunExecutionException { if (currentState == null) { throw new IllegalStateException("Cannot step without a current state to step from. " + "If you previously used the search command you must" + "first select a solution with the select command before executing steps of rewrites!"); } SearchResults results = executor.search(null, steps, SearchType.PLUS, defaultPattern, getState(currentState).getRawResult(), defaultPatternInfo, true); mergeSearchGraph(results.getGraph()); currentState = null; return results; }
Source:
public void marshallAsElement(AttributeDefinition attribute, ModelNode resourceModel, boolean marshallDefault, XMLStreamWriter writer) throws XMLStreamException { if (!resourceModel.has(attribute.getName())) { return; } String wrapper = wrapperElement == null ? attribute.getName() : wrapperElement; resourceModel = resourceModel.get(attribute.getName()); if (!resourceModel.isDefined()){ writer.writeEmptyElement(wrapper); return; } if (wrapElement) { writer.writeStartElement(wrapper); } for (ModelNode property : resourceModel.asList()) { writer.writeEmptyElement(elementName); writer.writeAttribute(org.jboss.as.controller.parsing.Attribute.NAME.getLocalName(), property.asProperty().getName()); writer.writeAttribute(org.jboss.as.controller.parsing.Attribute.VALUE.getLocalName(), property.asProperty().getValue().asString()); } if (wrapElement) { writer.writeEndElement(); } }

Target:
public void marshallAsElement(AttributeDefinition attribute, ModelNode resourceModel, boolean marshallDefault, XMLStreamWriter writer) throws XMLStreamException { String wrapper = wrapperElement == null ? attribute.getName() : wrapperElement; resourceModel = resourceModel.get(attribute.getName()); if (!resourceModel.isDefined()){ writer.writeEmptyElement(wrapper); return; } if (wrapElement) { writer.writeStartElement(wrapper); } for (ModelNode property : resourceModel.asList()) { writer.writeEmptyElement(elementName); writer.writeAttribute(org.jboss.as.controller.parsing.Attribute.NAME.getLocalName(), property.asProperty().getName()); writer.writeAttribute(org.jboss.as.controller.parsing.Attribute.VALUE.getLocalName(), property.asProperty().getValue().asString()); } if (wrapElement) { writer.writeEndElement(); } }
Source:
public boolean hasCategoryMembers() { wait.forElementVisible(categoryMembers); return driver.findElements(categoryMembers).size() > 0; }

Target:
public boolean hasCategoryMembers() { wait.forElementVisible(categoryMembers); PageObjectLogging.logInfo("Category has members."); return driver.findElements(categoryMembers).size() > 0; }
Source:
public synchronized PrintWriter getWriter() { checkState(outputStream == null, "getOutputStream() already called"); if (writer == null) { writer = new PrintWriter(actualBody); } return writer; }

Target:
public synchronized PrintWriter getWriter() { checkState(outputStream == null, "getOutputStream() already called"); if (writer == null) { writer = new PrintWriter(new OutputStreamWriter(actualBody, Charsets.UTF_8)); } return writer; }
Source:
public int deleteReport(final UUID identifier, final Organization organization) { assertIsOpen(); LOGGER.debug() .setMessage("Deleting report") .addData("uuid", identifier) .addData("organization.uuid", organization.getId()) .log(); final Optional<models.ebean.Report> report; try (Transaction transaction = _ebeanServer.beginTransaction()) { report = getBeanReport(identifier, organization); report.ifPresent(r -> { _ebeanServer.delete(r); LOGGER.debug() .setMessage("Deleted report") .addData("uuid", identifier) .addData("organization.uuid", organization.getId()) .log(); }); transaction.commit(); } catch (final RuntimeException e) { LOGGER.error() .setMessage("Failed to delete report") .addData("uuid", identifier) .addData("organization.uuid", organization.getId()) .setThrowable(e) .log(); throw new PersistenceException(e); } if (report.isPresent()) { return 1; } return 0; }

Target:
public int deleteReport(final UUID identifier, final Organization organization) { assertIsOpen(); LOGGER.debug() .setMessage("Deleting report") .addData("uuid", identifier) .addData("organization.uuid", organization.getId()) .log(); final int deleted = _ebeanServer.update(models.ebean.Report.class) .set("deleted", true) .where() .eq("uuid", identifier) .eq("organization.uuid", organization.getId()) .eq("deleted", false) .update(); if (deleted > 0) { LOGGER.debug() .setMessage("Deleted report") .addData("uuid", identifier) .addData("organization.uuid", organization.getId()) .log(); } return deleted; }
Source:
public void trackMap(String eventName, Map<String, Object> properties) { if (null == properties) { Log.e(LOGTAG, "trackMap does not accept null properties"); return; } track(eventName, new JSONObject(properties)); }

Target:
public void trackMap(String eventName, Map<String, Object> properties) { if (null == properties) { track(eventName, null); } else { try { track(eventName, new JSONObject(properties)); } catch (NullPointerException e) { Log.w(LOGTAG, "Can't have null keys in the properties of trackMap!"); } } }
Source:
public void shouldGenerateUpdatesForLabelAdditionWithExistingProperties() { NodeUpdates updates = NodeUpdates.forNode( nodeId, empty, labels ) .existing( propertyKeyId1, Values.of( "Neo" ) ) .existing( propertyKeyId2, Values.of( 100L ) ) .existing( propertyKeyId3, Values.of( Values.pointValue( CoordinateReferenceSystem.WGS84, 12.3, 45.6 ) ) ) .build(); assertThat( updates.forIndexKeys( indexes, propertyLoader( property1, property2, property3 ) ), containsInAnyOrder( IndexEntryUpdate.add( nodeId, index1, property1.value() ), IndexEntryUpdate.add( nodeId, index2, property2.value() ), IndexEntryUpdate.add( nodeId, index3, property3.value() ), IndexEntryUpdate.add( nodeId, index123, values123 ) ) ); }

Target:
public void shouldGenerateUpdatesForLabelAdditionWithExistingProperties() { NodeUpdates updates = NodeUpdates.forNode( nodeId, empty, labels ) .existing( propertyKeyId1, Values.of( "Neo" ) ) .existing( propertyKeyId2, Values.of( 100L ) ) .existing( propertyKeyId3, Values.pointValue( CoordinateReferenceSystem.WGS84, 12.3, 45.6 ) ) .build(); assertThat( updates.forIndexKeys( indexes, propertyLoader( property1, property2, property3 ) ), containsInAnyOrder( IndexEntryUpdate.add( nodeId, index1, property1.value() ), IndexEntryUpdate.add( nodeId, index2, property2.value() ), IndexEntryUpdate.add( nodeId, index3, property3.value() ), IndexEntryUpdate.add( nodeId, index123, values123 ) ) ); }
Source:
private List<Person> getOverviewPersonsForUser(Person signedInUser, List<Department> departments, String selectedDepartmentName) { if (departments.isEmpty() && (signedInUser.hasRole(BOSS) || signedInUser.hasRole(OFFICE))) { return personService.getActivePersons(); } return departments.stream() .filter(d -> d.getName().equals(selectedDepartmentName)) .map(Department::getMembers) .flatMap(List::stream) .sorted(comparing(Person::getFirstName)) .collect(toList()); }

Target:
private List<Person> getOverviewPersonsForUser(Person signedInUser, List<Department> departments, String selectedDepartmentName) { if (departments.isEmpty() && (signedInUser.hasRole(BOSS) || signedInUser.hasRole(OFFICE))) { return personService.getActivePersons(); } return departments.stream() .filter(department -> department.getName().equals(selectedDepartmentName)) .map(Department::getMembers) .flatMap(List::stream) .sorted(comparing(Person::getFirstName)) .collect(toList()); }
Source:
public static File createAppPackageFile() { buildOperators(); final String version = System.getProperty("apex.version"); final List<String> params = new LinkedList<>(); params.add("clean"); params.add("install"); params.add("-DskipTests"); if (version != null && version.length() > 0) { params.add("-Dapex.version=" + version); } Assert.assertEquals(0, mavenCli.doMain(params.toArray(new String[params.size()]), workingDirectory, System.out, System.err)); return new File(workingDirectory, "target/mydtapp-1.0-SNAPSHOT.apa"); }

Target:
public static File createAppPackageFile() { final String version = System.getProperty("apex.version"); final List<String> params = new LinkedList<>(); params.add("clean"); params.add("package"); params.add("-DskipTests"); if (version != null && version.length() > 0) { params.add("-Dapex.version=" + version); } Assert.assertEquals(0, mavenCli.doMain(params.toArray(new String[params.size()]), workingDirectory, System.out, System.err)); return new File(workingDirectory, "target/mydtapp-1.0-SNAPSHOT.apa"); }
Source:
public void testWriteAndPublisher(Method method) { String key = TestingUtil.k(method); String value = TestingUtil.v(method); IracMetadata metadata = createMetadata(); cacheStore.write(createEntry(key, value, metadata)); MarshallableEntrySubscriber<V> subscriber = new MarshallableEntrySubscriber<>(); cacheStore.entryPublisher(key::equals, true, true).subscribe(subscriber); List<MarshallableEntry<String, V>> entries = subscriber.cf.join(); AssertJUnit.assertEquals(1, entries.size()); assertCorrectEntry(entries.get(0), key, value, metadata); }

Target:
public void testWriteAndPublisher(Method method) { String key = TestingUtil.k(method); String value = TestingUtil.v(method); IracMetadata metadata = createMetadata(); cacheStore.write(createEntry(key, value, metadata)); MarshallableEntrySubscriber<V> subscriber = new MarshallableEntrySubscriber<>(); cacheStore.entryPublisher(key::equals, true, true).subscribe(subscriber); List<MarshallableEntry<String, V>> entries = subscriber.cf.join(); assertEquals(1, entries.size()); assertCorrectEntry(entries.get(0), key, value, metadata); }
Source:
public static List<SetupAction> getSetupActions(DeploymentUnit deploymentUnit) { final List<SetupAction> setupActions = new ArrayList<SetupAction>(); JavaNamespaceSetup naming = deploymentUnit.getAttachment(org.jboss.as.ee.naming.Attachments.JAVA_NAMESPACE_SETUP_ACTION); if (naming != null) { setupActions.add(naming); } final ConcurrentContextSetupAction concurrentContext = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.CONCURRENT_CONTEXT_SETUP_ACTION); if (concurrentContext != null) { setupActions.add(concurrentContext); } return setupActions; }

Target:
static List<SetupAction> getSetupActions(DeploymentUnit deploymentUnit) { final List<SetupAction> setupActions = new ArrayList<SetupAction>(); JavaNamespaceSetup naming = deploymentUnit.getAttachment(org.jboss.as.ee.naming.Attachments.JAVA_NAMESPACE_SETUP_ACTION); if (naming != null) { setupActions.add(naming); } final ConcurrentContextSetupAction concurrentContext = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.CONCURRENT_CONTEXT_SETUP_ACTION); if (concurrentContext != null) { setupActions.add(concurrentContext); } return setupActions; }
Source:
private void run() { assignConsumer(); try { while (true) { ConsumerRecords<String, String> records = kafkaConsumer.poll(pollingTimeout); processRecords(records); updateConsumerLag(); } } catch (WakeupException e) { LOG.info("Received shutdown signal."); } catch (Exception e) { LOG.error("An error occurred while processing feature states.", e); } finally { shutdown(); } }

Target:
private void run() { assignConsumer(); running = true; try { while (true) { ConsumerRecords<String, String> records = kafkaConsumer.poll(pollingTimeout); processRecords(records); updateConsumerLag(); } } catch (WakeupException e) { LOG.info("Received shutdown signal."); } catch (RuntimeException e) { LOG.error("An error occurred while processing feature states: KafkaConsumer will be closed.", e); } finally { running = false; shutdown(); } }
Source:
public void verify(VerificationData data) { try { mode.verify(data); for (VerificationListener listener : listeners) { listener.onVerificationSucceeded(new VerificationSucceededEvent(mock, mode, data)); } } catch (MockitoAssertionError e) { for (VerificationListener listener : listeners) { listener.onVerificationException(mock, mode, e); } throw e; } }

Target:
public void verify(VerificationData data) { try { mode.verify(data); notifyListeners(new VerificationEventImpl(mock, mode, data, null)); } catch (RuntimeException e) { notifyListeners(new VerificationEventImpl(mock, mode, data, e)); throw e; } catch (Error e) { notifyListeners(new VerificationEventImpl(mock, mode, data, e)); throw e; } }
Source:
void testAddStorageResourceWhenNameIsLongerThan24Chars() { String name = "thishasmorethan24characters"; DeploymentTemplateBuilder builder = getMockDeploymentTemplateBuilderWithEmptyOptions(name); DeploymentBody deploymentBody = builder.getDeploymentTemplate(); assertTrue(Iterables.contains(deploymentBody.template().variables().keySet(), "storageAccountName")); String storageAccountName = deploymentBody.template().variables().get("storageAccountName"); assertEquals(storageAccountName.length(), 24); assertEquals(storageAccountName.substring(0, 10), name.replaceAll("[^a-z0-9]", "").substring(0, 10)); assertEquals(storageAccountName.substring(storageAccountName.length() - 10, storageAccountName.length()), name.replaceAll("[^a-z0-9]", "").substring(name.length() - 10, name.length())); }

Target:
void testAddStorageResourceWhenNameIsLongerThan24Chars() { String name = "thishasmorethan24characters"; DeploymentTemplateBuilder builder = getMockDeploymentTemplateBuilderWithEmptyOptions(name); DeploymentBody deploymentBody = builder.getDeploymentTemplate(); assertTrue(Iterables.contains(deploymentBody.template().variables().keySet(), "storageAccountName")); String storageAccountName = deploymentBody.template().variables().get("storageAccountName"); assertEquals(storageAccountName.length(), 24); assertEquals(storageAccountName.substring(0, 10), "thishasmor"); assertEquals(storageAccountName.substring(storageAccountName.length() - 10, storageAccountName.length()), "characters"); }
Source:
public Attachment addAttachment(String assetId, AttachmentSummary attSummary) throws IOException, BadVersionException, RequestFailureException, SecurityException { return null; }

Target:
public Attachment addAttachment(String assetId, AttachmentSummary attSummary) throws IOException, BadVersionException, RequestFailureException, SecurityException { throw new UnsupportedOperationException("Attachment methods should not be invoked for Loose Repositories"); }
Source:
@Test public void sendSMSTest() { try { driver.sendSMS("11111111", "call"); } catch (Exception e) { assertFalse( "method works only in emulators", true); } }

Target:
@Test public void sendSMSTest() { try { driver.sendSMS("11111111", "call"); } catch (Exception e) { fail("method works only in emulators"); } }
Source:
public void execute(IProgressMonitor m) throws CoreException { if (!results.isEmpty()) throw new CoreException(new Status(IStatus.ERROR, Activator .getPluginId(), CoreText.OperationAlreadyExecuted)); IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; monitor.beginTask(NLS.bind(CoreText.PullOperation_TaskName, Integer .valueOf(repositories.length)), repositories.length); IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor mymonitor) throws CoreException { for (int i = 0; i < repositories.length; i++) { Repository repository = repositories[i]; if (mymonitor.isCanceled()) throw new CoreException(Status.CANCEL_STATUS); PullCommand pull = new Git(repository).pull(); try { pull .setProgressMonitor(new EclipseGitProgressTransformer( new SubProgressMonitor(mymonitor, 1))); pull.setTimeout(timeout); results.put(repository, pull.call()); } catch (DetachedHeadException e) { results.put(repository, Activator.error( CoreText.PullOperation_DetachedHeadMessage, e)); } catch (InvalidConfigurationException e) { results .put( repository, Activator .error( CoreText.PullOperation_PullNotConfiguredMessage, e)); } catch (GitAPIException e) { results.put(repository, Activator.error(e.getMessage(), e)); } catch (JGitInternalException e) { results.put(repository, Activator.error(e.getMessage(), e)); } finally { mymonitor.worked(1); } } } }; ResourcesPlugin.getWorkspace().run(action, monitor); }

Target:
public void execute(IProgressMonitor m) throws CoreException { if (!results.isEmpty()) throw new CoreException(new Status(IStatus.ERROR, Activator .getPluginId(), CoreText.OperationAlreadyExecuted)); IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; monitor.beginTask(NLS.bind(CoreText.PullOperation_TaskName, Integer .valueOf(repositories.length)), repositories.length); IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor mymonitor) throws CoreException { for (int i = 0; i < repositories.length; i++) { Repository repository = repositories[i]; if (mymonitor.isCanceled()) throw new CoreException(Status.CANCEL_STATUS); PullCommand pull = new Git(repository).pull(); try { pull.setProgressMonitor(new EclipseGitProgressTransformer( new SubProgressMonitor(mymonitor, 1))); pull.setTimeout(timeout); results.put(repository, pull.call()); } catch (DetachedHeadException e) { results.put(repository, Activator.error( CoreText.PullOperation_DetachedHeadMessage, e)); } catch (InvalidConfigurationException e) { IStatus error = Activator .error(CoreText.PullOperation_PullNotConfiguredMessage, e); results.put(repository, error); } catch (GitAPIException e) { results.put(repository, Activator.error(e.getMessage(), e)); } catch (JGitInternalException e) { results.put(repository, Activator.error(e.getMessage(), e)); } finally { mymonitor.worked(1); } } } }; ResourcesPlugin.getWorkspace().run(action, monitor); }
Source:
public Action<?, ?> databaseBackupFailedAction() { return new AbstractBackupRestoreActions<>(DatabaseBackupFailedEvent.class) { @Override protected BackupRestoreContext createFlowContext(FlowParameters flowParameters, StateContext<FlowState, FlowEvent> stateContext, DatabaseBackupFailedEvent payload) { Flow flow = getFlow(flowParameters.getFlowId()); flow.setFlowFailed(payload.getException()); return BackupRestoreContext.from(flowParameters, payload, null, null, null); } @Override protected void doExecute(BackupRestoreContext context, DatabaseBackupFailedEvent payload, Map<Object, Object> variables) { backupRestoreStatusService.handleDatabaseBackupFailure(context.getStackId(), payload.getException().getMessage(), payload.getDetailedStatus()); sendEvent(context, DATABASE_BACKUP_FAIL_HANDLED_EVENT.event(), payload); } }; }

Target:
public Action<?, ?> databaseBackupFailedAction() { return new AbstractBackupRestoreActions<>(DatabaseBackupFailedEvent.class) { @Override protected BackupRestoreContext createFlowContext(FlowParameters flowParameters, StateContext<FlowState, FlowEvent> stateContext, DatabaseBackupFailedEvent payload) { Flow flow = getFlow(flowParameters.getFlowId()); flow.setFlowFailed(payload.getException()); return BackupRestoreContext.from(flowParameters, payload, null, null); } @Override protected void doExecute(BackupRestoreContext context, DatabaseBackupFailedEvent payload, Map<Object, Object> variables) { backupRestoreStatusService.handleDatabaseBackupFailure(context.getStackId(), payload.getException().getMessage(), payload.getDetailedStatus()); sendEvent(context, DATABASE_BACKUP_FAIL_HANDLED_EVENT.event(), payload); } }; }
Source:
public FormValidation doCheckMaxDaysOld(@QueryParameter int maxDaysOld) { if (maxDaysOld <= 0) { return FormValidation.warning("The maximum age of a commit should be greater than 0. Otherwise no branches are found"); } return FormValidation.ok(); }

Target:
public FormValidation doCheckMaxDaysOld(@QueryParameter int maxDaysOld) { if (maxDaysOld <= 0) { return FormValidation.warning("Setting maximum age to 0 or negative turns off this filter."); } return FormValidation.ok(); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UnregisteredDisk that = (UnregisteredDisk) o; if (!diskImage.equals(that.diskImage)) { return false; } return vms.equals(that.vms); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UnregisteredDisk that = (UnregisteredDisk) o; return Objects.equals(diskImage, that.diskImage) && Objects.equals(vms, that.vms) && Objects.equals(id, that.id); }
Source:
private void markEdit(CodeMirror cm, JsArrayString lines, JsArray<Span> edits, int startLine) { int pos = 0; LineIterator iter = new LineIterator(lines, startLine); Configuration diffOpt = Configuration.create() .set("className", diffTable.style.diff()) .set("readOnly", true); Configuration editOpt = Configuration.create() .set("className", diffTable.style.intraline()) .set("readOnly", true); LineCharacter last = LineCharacter.create(0, 0); for (int i = 0; i < edits.length(); i++) { Span span = edits.get(i); LineCharacter from = iter.advance(span.begin() - pos); LineCharacter to = iter.advance(span.length()); int fromLine = from.getLine(); pos = span.begin() + span.length(); if (last.getLine() == fromLine) { cm.markText(last, from, diffOpt); } else { cm.markText(LineCharacter.create(fromLine, 0), from, diffOpt); } cm.markText(from, to, editOpt); last = to; for (int line = fromLine; line < to.getLine(); line++) { cm.addLineClass(line, LineClassWhere.BACKGROUND, diffTable.style.intraline()); } } }

Target:
private void markEdit(CodeMirror cm, JsArrayString lines, JsArray<Span> edits, int startLine) { int pos = 0; EditIterator iter = new EditIterator(lines, startLine); Configuration diffOpt = Configuration.create() .set("className", diffTable.style.diff()) .set("readOnly", true); Configuration editOpt = Configuration.create() .set("className", diffTable.style.intraline()) .set("readOnly", true); LineCharacter last = LineCharacter.create(0, 0); for (int i = 0; i < edits.length(); i++) { Span span = edits.get(i); LineCharacter from = iter.advance(span.begin() - pos); LineCharacter to = iter.advance(span.length()); int fromLine = from.getLine(); pos = span.end(); if (last.getLine() == fromLine) { cm.markText(last, from, diffOpt); } else { cm.markText(LineCharacter.create(fromLine, 0), from, diffOpt); } cm.markText(from, to, editOpt); last = to; for (int line = fromLine; line < to.getLine(); line++) { cm.addLineClass(line, LineClassWhere.BACKGROUND, diffTable.style.intraline()); } } }
Source:
public void updateNumberOfShards(int newNumber) { Preconditions.checkArgument(newNumber <= 128); increaseValue(NUMBER_OF_SHARDS_INDEX, true, newNumber); }

Target:
public void updateNumberOfShards(int newNumber) { Preconditions.checkArgument(newNumber <= 128); increaseValueToAtLeast(ShardAndStrategy.conservative(SHARD_COUNT_INDEX), newNumber); }
Source:
private PositionalBufferedStream initStream(final File inputFile, final long skip) { try { final FileInputStream fileStream = new FileInputStream(inputFile); final InputStream is; if (AbstractFeatureReader.hasBlockCompressedExtension(inputFile)) { final int bufferSize = Math.max(Defaults.BUFFER_SIZE, BlockCompressedStreamConstants.MAX_COMPRESSED_BLOCK_SIZE); final BufferedInputStream bufferedStream = new BufferedInputStream(fileStream, bufferSize); if (!BlockCompressedInputStream.isValidFile(bufferedStream)) { throw new TribbleException.MalformedFeatureFile("Input file is not in valid block compressed format.", inputFile.getAbsolutePath()); } final SeekableStream seekableStream = SeekableStreamFactory.getInstance().getBufferedStream( SeekableStreamFactory.getInstance().getStreamFor(inputFile.getAbsolutePath())); is = new BlockCompressedInputStream(seekableStream); } else { is = fileStream; } final PositionalBufferedStream pbs = new PositionalBufferedStream(is); if ( skip > 0 ) pbs.skip(skip); return pbs; } catch (final FileNotFoundException e) { throw new TribbleException.FeatureFileDoesntExist("Unable to open the input file, most likely the file doesn't exist.", inputFile.getAbsolutePath()); } catch (final IOException e) { throw new TribbleException.MalformedFeatureFile("Error initializing stream", inputFile.getAbsolutePath(), e); } }

Target:
private PositionalBufferedStream initStream(final File inputFile, final long skip) { try { final FileInputStream fileStream = new FileInputStream(inputFile); final InputStream is; if (AbstractFeatureReader.hasBlockCompressedExtension(inputFile)) { final int bufferSize = Math.max(Defaults.BUFFER_SIZE, BlockCompressedStreamConstants.MAX_COMPRESSED_BLOCK_SIZE); final BufferedInputStream bufferedStream = new BufferedInputStream(fileStream, bufferSize); if (!BlockCompressedInputStream.isValidFile(bufferedStream)) { throw new TribbleException.MalformedFeatureFile("Input file is not in valid block compressed format.", inputFile.getAbsolutePath()); } final ISeekableStreamFactory ssf = SeekableStreamFactory.getInstance(); final SeekableStream seekableStream = ssf.getBufferedStream(ssf.getStreamFor(inputFile.getAbsolutePath())); is = new BlockCompressedInputStream(seekableStream); } else { is = fileStream; } final PositionalBufferedStream pbs = new PositionalBufferedStream(is); if ( skip > 0 ) pbs.skip(skip); return pbs; } catch (final FileNotFoundException e) { throw new TribbleException.FeatureFileDoesntExist("Unable to open the input file, most likely the file doesn't exist.", inputFile.getAbsolutePath()); } catch (final IOException e) { throw new TribbleException.MalformedFeatureFile("Error initializing stream", inputFile.getAbsolutePath(), e); } }
Source:
default void setHelperComponent(Component component) { getElement().getChildren() .filter(child -> "helper".equals(child.getAttribute("slot"))) .collect(Collectors.toList()) .forEach(getElement()::removeChild); if (component != null) { component.getElement().setAttribute("slot", "helper"); getElement().appendChild(component.getElement()); } }

Target:
default void setHelperComponent(Component component) { getElement().getChildren() .filter(child -> "helper".equals(child.getAttribute("slot"))) .findAny() .ifPresent(getElement()::removeChild); if (component != null) { component.getElement().setAttribute("slot", "helper"); getElement().appendChild(component.getElement()); } }
Source:
public TransferObserver upload(String key, InputStream inputStream, UploadOptions options) throws IOException { File file = writeInputStreamToFile(inputStream); TransferObserver observer = upload( options.getBucket() != null ? options.getBucket() : getDefaultBucketOrThrow(), key, file, options.getMetadata() != null ? options.getMetadata() : new ObjectMetadata(), options.getCannedAcl(), options.getTransferListener() ); deleteTempFile(observer); return observer; }

Target:
public TransferObserver upload(String key, InputStream inputStream, UploadOptions options) throws IOException { File file = writeInputStreamToFile(inputStream); return upload( options.getBucket() != null ? options.getBucket() : getDefaultBucketOrThrow(), key, file, options.getMetadata() != null ? options.getMetadata() : new ObjectMetadata(), options.getCannedAcl(), options.getTransferListener() ); }
Source:
public Promise<Map<String, String>> loadPreferences() { if (!service.hasJDTLSInstallerAdded()) { return promiseProvider.resolve(newHashMap()); } List<String> options = new ArrayList<>(); for (ErrorWarningsOptions option : ErrorWarningsOptions.values()) { options.add(option.toString()); } return service .getJavaCoreOptions(options) .then( (Function<JavaCoreOptions, Map<String, String>>) javaCoreOptions -> { persistedPreferences.putAll(javaCoreOptions.getOptions()); return javaCoreOptions.getOptions(); }); }

Target:
public Promise<Map<String, String>> loadPreferences() { List<String> options = new ArrayList<>(); for (ErrorWarningsOptions option : ErrorWarningsOptions.values()) { options.add(option.toString()); } return service .getJavaCoreOptions(options) .then( (Function<JavaCoreOptions, Map<String, String>>) javaCoreOptions -> { persistedPreferences.putAll(javaCoreOptions.getOptions()); return javaCoreOptions.getOptions(); }); }
Source:
public String toString() { final StringBuilder sb = new StringBuilder("LocalBias{"); sb.append("acq=").append(acquisitionTimestamp); sb.append(", last=").append(lastAccessTimestamp); sb.append('}'); return sb.toString(); }

Target:
public String toString() { return "LocalBias{acq=" + acquisitionTimestamp + ", last=" + lastAccessTimestamp + '}'; }
Source:
private static void updateForTabletDataFile(ServerContext context, KeyExtent extent, FileRef path, FileRef mergeFile, DataFileValue dfv, String time, Set<FileRef> filesInUseByScans, String address, ZooLock zooLock, Set<String> unusedWalLogs, TServerInstance lastLocation, long flushId) { TabletMutator tablet = context.getAmple().mutateTablet(extent); if (dfv.getNumEntries() > 0) { tablet.putFile(path, dfv); tablet.putTime(time); TServerInstance self = getTServerInstance(address, zooLock); tablet.putLocation(self, LocationType.LAST); if (lastLocation != null && !lastLocation.equals(self)) { tablet.deleteLocation(lastLocation, LocationType.LAST); } } tablet.putFlushId(flushId); if (mergeFile != null) { tablet.deleteFile(mergeFile); } if (unusedWalLogs != null) { unusedWalLogs.forEach(tablet::deleteWal); } filesInUseByScans.forEach(tablet::putScan); tablet.mutate(); }

Target:
private static void updateForTabletDataFile(ServerContext context, KeyExtent extent, FileRef path, FileRef mergeFile, DataFileValue dfv, String time, Set<FileRef> filesInUseByScans, String address, ZooLock zooLock, Set<String> unusedWalLogs, TServerInstance lastLocation, long flushId) { TabletMutator tablet = context.getAmple().mutateTablet(extent); if (dfv.getNumEntries() > 0) { tablet.putFile(path, dfv); tablet.putTime(time); TServerInstance self = getTServerInstance(address, zooLock); tablet.putLocation(self, LocationType.LAST); if (lastLocation != null && !lastLocation.equals(self)) { tablet.deleteLocation(lastLocation, LocationType.LAST); } } tablet.putFlushId(flushId); if (mergeFile != null) { tablet.deleteFile(mergeFile); } unusedWalLogs.forEach(tablet::deleteWal); filesInUseByScans.forEach(tablet::putScan); tablet.putZooLock(zooLock); tablet.mutate(); }
Source:
public MobileArticlePageObject openCategory(String wikiURL){ getUrl(wikiURL+ categoryPmg); waitForElementByElement(showAllButton); PageObjectLogging.log("openCategory", "category page was opened", true, driver); return new MobileArticlePageObject(driver); }

Target:
public MobileArticlePageObject openCategory(String wikiURL) { getUrl(wikiURL + URLsContent.categoryPmg); waitForElementByElement(showAllButton); PageObjectLogging.log("openCategory", "category page was opened", true, driver); return new MobileArticlePageObject(driver); }
Source:
public URI getServiceUri() throws URISyntaxException { return new URI("http://localhost:8087/mmx/merger/v1/action"); }

Target:
private URI getServiceUri() throws Exception { final ServiceInstance instance = serviceProvider.getInstance(); final String scheme; final String host; final int port; final String path = "/mmx/merger/v1/action"; host = instance.getAddress(); if (instance.getSslPort() != null && instance.getSslPort() > 0) { scheme = "https"; port = instance.getSslPort(); } else { scheme = "http"; port = instance.getPort(); } return new URI(scheme, null, host, port, path, null, null); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_basic); ButterKnife.bind(this); widget.setShowOtherDates(MaterialCalendarView.SHOW_ALL); widget.setArrowColor(getResources().getColor(R.color.sample_primary)); widget.setLeftArrowMask(getResources().getDrawable(R.drawable.ic_navigation_arrow_back)); widget.setRightArrowMask(getResources().getDrawable(R.drawable.ic_navigation_arrow_forward)); widget.setSelectionColor(getResources().getColor(R.color.sample_primary)); widget.setHeaderTextAppearance(R.style.TextAppearance_AppCompat_Medium); widget.setWeekDayTextAppearance(R.style.TextAppearance_AppCompat_Medium); widget.setDateTextAppearance(R.style.CustomTextAppearance); widget.setWeekDayTextAppearance(R.style.CustomTextAppearance); widget.setHeaderTextAppearance(R.style.CustomTextAppearance); widget.setDateTextAppearance(R.style.CustomTextAppearance); widget.setTitleFormatter(new MonthArrayTitleFormatter(getResources().getTextArray(R.array.custom_months))); widget.setWeekDayFormatter(new ArrayWeekDayFormatter(getResources().getTextArray(R.array.custom_weekdays))); widget.setTileSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 36, getResources().getDisplayMetrics())); widget.setTitleAnimationOrientation(MaterialCalendarView.VERTICAL); CalendarDay today = CalendarDay.from(2016, 5, 2); widget.setCurrentDate(today); widget.setSelectedDate(today); widget.state().edit() .setFirstDayOfWeek(Calendar.WEDNESDAY) .setMinimumDate(CalendarDay.from(2016, 4, 3)) .setMaximumDate(CalendarDay.from(2016, 5, 12)) .setCalendarDisplayMode(CalendarMode.WEEKS) .commit(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_basic); ButterKnife.bind(this); widget.setShowOtherDates(MaterialCalendarView.SHOW_ALL); widget.setArrowColor(getResources().getColor(R.color.sample_primary)); widget.setLeftArrowMask(getResources().getDrawable(R.drawable.ic_navigation_arrow_back)); widget.setRightArrowMask(getResources().getDrawable(R.drawable.ic_navigation_arrow_forward)); widget.setSelectionColor(getResources().getColor(R.color.sample_primary)); widget.setWeekDayTextAppearance(R.style.CustomTextAppearance); widget.setHeaderTextAppearance(R.style.CustomTextAppearance); widget.setDateTextAppearance(R.style.CustomTextAppearance); widget.setTitleFormatter(new MonthArrayTitleFormatter(getResources().getTextArray(R.array.custom_months))); widget.setWeekDayFormatter(new ArrayWeekDayFormatter(getResources().getTextArray(R.array.custom_weekdays))); widget.setTileSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 36, getResources().getDisplayMetrics())); widget.setTitleAnimationOrientation(MaterialCalendarView.VERTICAL); CalendarDay today = CalendarDay.from(2016, 5, 2); widget.setCurrentDate(today); widget.setSelectedDate(today); widget.state().edit() .setFirstDayOfWeek(Calendar.WEDNESDAY) .setMinimumDate(CalendarDay.from(2016, 4, 3)) .setMaximumDate(CalendarDay.from(2016, 5, 12)) .setCalendarDisplayMode(CalendarMode.WEEKS) .commit(); }
Source:
public ByteBuf getCommandLineBytes() throws ImapAsyncClientException { final ByteBuf sb = Unpooled.buffer(ENABLE_BUF_LEN); sb.writeBytes(ENABLE_SP_B); for (int i = 0, len = capabilities.length; i < len; i++) { sb.writeBytes(capabilities[i].getBytes(StandardCharsets.US_ASCII)); if (i < len - 1) { sb.writeByte(ImapClientConstants.SPACE); } } sb.writeBytes(CRLF_B); return sb; }

Target:
public ByteBuf getCommandLineBytes() throws ImapAsyncClientException { final ByteBuf sb = Unpooled.buffer(ENABLE_BUF_LEN); sb.writeBytes(ENABLE_B); for (int i = 0; i < capabilities.length; i++) { sb.writeByte(ImapClientConstants.SPACE); sb.writeBytes(capabilities[i].getBytes(StandardCharsets.US_ASCII)); } sb.writeBytes(CRLF_B); return sb; }
Source:
public String getTokenValue() { String value = tokenValue.toString(); if ( isEL ) { value = value.replace( "\\{", "{" ); value = value.replace( "\\}", "}" ); } return value; }

Target:
public String getTokenValue() { if ( !terminated ) { throw new IllegalStateException( "Trying to retrieve token value for unterminated token" ); } return value; }
Source:
public long getCurrentSize() { long size = -1; try { this.putCountsLock.readLock().lock(); try { this.takeCountsLock.readLock().lock(); size = this.elementsAdded - this.elementsRemoved; } finally { this.takeCountsLock.readLock().unlock(); } } finally { this.putCountsLock.readLock().unlock(); } return size; }

Target:
public long getCurrentSize() { return this.elementsAdded.get() - this.elementsRemoved.get(); }
Source:
public boolean quotaExceeded(IOException e) { ErrorInfo errorInfo = getErrorInfo(e); if (errorInfo != null) { return QUOTA_EXCEEDED_REASON.equals(errorInfo.getReason()); } return false; }

Target:
public boolean quotaExceeded(IOException e) { ErrorInfo errorInfo = getErrorInfo(e); return errorInfo != null && QUOTA_EXCEEDED_REASON.equals(errorInfo.getReason()); }
Source:
private void applyRebalanceOverwrite(Map<String, IdealState> idealStateMap, ResourceControllerDataProvider clusterData, Map<String, Resource> resourceMap, Map<HelixConstants.ChangeType, Set<String>> clusterChanges, Map<String, ResourceAssignment> baseline) throws HelixRebalanceException { Set<String> enabledLiveInstances = clusterData.getEnabledLiveInstances(); Map<String, IdealState> activeIdealStates = convertResourceAssignment(clusterData, calculateAssignment(clusterData, clusterChanges, resourceMap, enabledLiveInstances, Collections.emptyMap(), baseline)); for (String resourceName : idealStateMap.keySet()) { IdealState is = idealStateMap.get(resourceName); if (!activeIdealStates.containsKey(resourceName)) { throw new HelixRebalanceException( "Failed to calculate the complete partition assignment with all active nodes. Cannot find the resource assignment for " + resourceName, HelixRebalanceException.Type.FAILED_TO_CALCULATE); } IdealState newActiveIdealState = activeIdealStates.get(resourceName); IdealState currentIdealState = clusterData.getIdealState(resourceName); int numReplica = currentIdealState.getReplicaCount(enabledLiveInstances.size()); int minActiveReplica = DelayedRebalanceUtil.getMinActiveReplica(currentIdealState, numReplica); Map<String, List<String>> finalPreferenceLists = DelayedRebalanceUtil .getFinalDelayedMapping(newActiveIdealState.getPreferenceLists(), is.getPreferenceLists(), enabledLiveInstances, Math.min(minActiveReplica, numReplica)); is.setPreferenceLists(finalPreferenceLists); } }

Target:
private void applyRebalanceOverwrite(Map<String, IdealState> idealStateMap, ResourceControllerDataProvider clusterData, Map<String, Resource> resourceMap, Map<HelixConstants.ChangeType, Set<String>> clusterChanges, Map<String, ResourceAssignment> baseline) throws HelixRebalanceException { Set<String> enabledLiveInstances = clusterData.getEnabledLiveInstances(); Map<String, IdealState> activeIdealStates = convertResourceAssignment(clusterData, calculateAssignment(clusterData, clusterChanges, resourceMap, enabledLiveInstances, Collections.emptyMap(), baseline)); for (String resourceName : idealStateMap.keySet()) { IdealState newIdealState = idealStateMap.get(resourceName); if (!activeIdealStates.containsKey(resourceName)) { throw new HelixRebalanceException( "Failed to calculate the complete partition assignment with all active nodes. Cannot find the resource assignment for " + resourceName, HelixRebalanceException.Type.FAILED_TO_CALCULATE); } IdealState newActiveIdealState = activeIdealStates.get(resourceName); IdealState currentIdealState = clusterData.getIdealState(resourceName); int numReplica = currentIdealState.getReplicaCount(enabledLiveInstances.size()); int minActiveReplica = DelayedRebalanceUtil.getMinActiveReplica(currentIdealState, numReplica); Map<String, List<String>> finalPreferenceLists = DelayedRebalanceUtil .getFinalDelayedMapping(newActiveIdealState.getPreferenceLists(), newIdealState.getPreferenceLists(), enabledLiveInstances, Math.min(minActiveReplica, numReplica)); newIdealState.setPreferenceLists(finalPreferenceLists); } }