auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void visitFunctionDef(FunctionDef functionDef) { String functionName = functionDef.name().name(); SymbolImpl symbol = (SymbolImpl) symbolsByName.get(functionName); if (symbol != null) { symbol.setKind(OTHER); } else { FunctionSymbolImpl functionSymbol = new FunctionSymbolImpl(functionName, functionName, false, false, false, Collections.emptyList(), null); TypeAnnotation returnTypeAnnotation = functionDef.returnTypeAnnotation(); if (returnTypeAnnotation != null) { functionSymbol.setInferredReturnType(InferredTypes.declaredType(returnTypeAnnotation)); } symbolsByName.put(functionName, functionSymbol); } }

Target:
public void visitFunctionDef(FunctionDef functionDef) { String functionName = functionDef.name().name(); SymbolImpl symbol = (SymbolImpl) symbolsByName.get(functionName); if (symbol != null) { symbol.setKind(OTHER); } else { FunctionSymbolImpl functionSymbol = new FunctionSymbolImpl(functionName, functionName, false, false, false, Collections.emptyList(), null); TypeAnnotation returnTypeAnnotation = functionDef.returnTypeAnnotation(); if (returnTypeAnnotation != null) { functionSymbol.setDeclaredReturnType(InferredTypes.declaredType(returnTypeAnnotation)); } symbolsByName.put(functionName, functionSymbol); } }
Source:
public void testStatsManagerCollectAggregateAndPublish() throws StoreException, IOException, InterruptedException { long[][] aggregatedTestData = new long[][]{{1110, 200, 300}, {350}, {500, 300}, {10, 20, 30, 40, 50}}; StatsSnapshot expectedSnapshot = generateStatsSnapshot(aggregatedTestData); StatsSnapshot actualSnapshot = new StatsSnapshot(0L, null); List<String> unreachableStores = new ArrayList<>(); for (PartitionId partitionId : storeMap.keySet()) { if (!statsManager.collectAndAggregate(actualSnapshot, partitionId)) { unreachableStores.add(partitionId.toString()); } } assertTrue("Aggregated StatsSnapshot does not match with expected snapshot", expectedSnapshot.equals(actualSnapshot)); assertEquals("Skipped store count mismatch with expected value", 1, unreachableStores.size()); StatsHeader statsHeader = new StatsHeader(Description.QUOTA, SystemTime.getInstance().milliseconds(), storeMap.keySet().size(), storeMap.keySet().size() - unreachableStores.size(), unreachableStores); File outputFile = new File(outputFileString); if (outputFile.exists()) { outputFile.createNewFile(); } long fileLengthBefore = outputFile.length(); statsManager.publish(new StatsWrapper(statsHeader, actualSnapshot)); assertTrue("Failed to publish stats to file", outputFile.length() > fileLengthBefore); }

Target:
public void testStatsManagerCollectAggregateAndPublish() throws IOException { StatsSnapshot actualSnapshot = new StatsSnapshot(0L, null); List<String> unreachableStores = Collections.EMPTY_LIST; for (PartitionId partitionId : storeMap.keySet()) { statsManager.collectAndAggregate(actualSnapshot, partitionId, unreachableStores); } assertTrue("Actual aggregated StatsSnapshot does not match with expected snapshot", preAggregatedSnapshot.equals(actualSnapshot)); StatsHeader statsHeader = new StatsHeader(Description.QUOTA, SystemTime.getInstance().milliseconds(), storeMap.keySet().size(), storeMap.keySet().size(), unreachableStores); File outputFile = new File(outputFileString); if (outputFile.exists()) { outputFile.createNewFile(); } long fileLengthBefore = outputFile.length(); statsManager.publish(new StatsWrapper(statsHeader, actualSnapshot)); assertTrue("Failed to publish stats to file", outputFile.length() > fileLengthBefore); }
Source:
public int getOpacity() { return PixelFormat.OPAQUE; }

Target:
public int getOpacity() { return PixelFormat.TRANSLUCENT; }
Source:
public FtSecure(final Take tks) throws IOException { this(new BkBasic(tks), 443); }

Target:
public FtSecure(final Take tks) throws IOException { this(tks, 443); }
Source:
private String decodeBase64EncodedHashWithHex(String base64EncodedHash) { try { return new String(Hex.encode(Base64.getDecoder().decode(Utf8.encode(base64EncodedHash)))); } catch (Exception ex) { logger.warn("Failed to do Base64Decoding " + ex.getMessage()); } return base64EncodedHash; }

Target:
private String decodeBase64EncodedHashWithHex(String base64EncodedHash) { try { return new String(Hex.encode(Base64.getDecoder().decode(Utf8.encode(base64EncodedHash)))); } catch (Exception ex) { logger.warn("decode hash using base64! " + ex.getMessage(), ex); } return base64EncodedHash; }
Source:
public String promptEmail() throws IOException, ConfigurationException { final String message = "Email Address: "; final String error = "Invalid email address."; EmailValidator validator = EmailValidator.getInstance(); String email = null; Console console = System.console(); if (console != null) { email = console.readLine(message); while (email == null || !validator.isValid(email)) { console.printf(error + "\n", email); email = console.readLine(message); } } else { email = IOUtils.toString(System.in); if (email == null || !validator.isValid(email)) { throw new ConfigurationException(error); } } return email; }

Target:
public String promptEmail() throws IOException, ConfigurationException { EmailValidator validator = EmailValidator.getInstance(); final String message = "Email Address: "; final String error = "Invalid email address."; return prompt(message, validator::isValid, error); }
Source:
private void verifyNoHeaderJunk(TaskListener listener) throws IOException, InterruptedException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); connection.exec("echo hello > null",baos); final String s; try { s = baos.toString(Charset.defaultCharset().name()); } catch (UnsupportedEncodingException ex) { throw new IOException("Default encoding is unsupported", ex); } if (s.length()!=0) { listener.getLogger().println(Messages.SSHLauncher_SSHHeaderJunkDetected()); listener.getLogger().println(s); throw new AbortException(); } }

Target:
private void verifyNoHeaderJunk(TaskListener listener) throws IOException, InterruptedException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); connection.exec("exit 0",baos); final String s; try { s = baos.toString(Charset.defaultCharset().name()); } catch (UnsupportedEncodingException ex) { throw new IOException("Default encoding is unsupported", ex); } if (s.length()!=0) { listener.getLogger().println(Messages.SSHLauncher_SSHHeaderJunkDetected()); listener.getLogger().println(s); throw new AbortException(); } }
Source:
protected void augmentMultifactorProviderFlowRegistry(final FlowDefinitionRegistry mfaProviderFlowRegistry) { final String[] flowIds = mfaProviderFlowRegistry.getFlowDefinitionIds(); Arrays.stream(flowIds).forEach(id -> { final Flow flow = Flow.class.cast(mfaProviderFlowRegistry.getFlowDefinition(id)); if (containsFlowState(flow, CasWebflowConstants.STATE_ID_REAL_SUBMIT)) { final Collection<String> states = getCandidateStatesForMultifactorAuthentication(); states.forEach(s -> { final TransitionableState state = getState(flow, s); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.TRANSITION_ID_SUCCESS, CasWebflowConstants.STATE_ID_SUCCESS); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.TRANSITION_ID_SUCCESS_WITH_WARNINGS, CasWebflowConstants.TRANSITION_ID_SUCCESS_WITH_WARNINGS); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.STATE_ID_MFA_UNAVAILABLE, CasWebflowConstants.STATE_ID_MFA_UNAVAILABLE); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.STATE_ID_MFA_DENIED, CasWebflowConstants.STATE_ID_MFA_DENIED); }); } }); }

Target:
protected void augmentMultifactorProviderFlowRegistry(final FlowDefinitionRegistry mfaProviderFlowRegistry) { final String[] flowIds = mfaProviderFlowRegistry.getFlowDefinitionIds(); Arrays.stream(flowIds).forEach(id -> { final Flow flow = Flow.class.cast(mfaProviderFlowRegistry.getFlowDefinition(id)); if (containsFlowState(flow, CasWebflowConstants.STATE_ID_REAL_SUBMIT)) { final Collection<String> states = getCandidateStatesForMultifactorAuthentication(); states.forEach(s -> { final TransitionableState state = getState(flow, s); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.TRANSITION_ID_SUCCESS, CasWebflowConstants.STATE_ID_SUCCESS); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.TRANSITION_ID_SUCCESS_WITH_WARNINGS, CasWebflowConstants.TRANSITION_ID_SUCCESS_WITH_WARNINGS); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.TRANSITION_ID_UNAVAILABLE, CasWebflowConstants.STATE_ID_MFA_UNAVAILABLE); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.TRANSITION_ID_DENY, CasWebflowConstants.STATE_ID_MFA_DENIED); }); } }); }
Source:
protected void setThreadFocus(final IMIExecutionDMContext newThread, RequestMonitor rm) { if (newThread == null) { GdbPlugin.logErrorMessage("GdbSynchronizer unable to resolve thread context for the selected element"); rm.done(); return; } ICommandControlDMContext cmd = DMContexts.getAncestorOfType(newThread, ICommandControlDMContext.class); ICommand<MIInfo> command = fCommandFactory.createMIThreadSelect(cmd, getThreadIdFromContext(newThread)); fCommandControl.queueCommand(command, new ImmediateDataRequestMonitor<MIInfo> (rm) {}); }

Target:
protected void setThreadFocus(final IMIExecutionDMContext newThread, RequestMonitor rm) { if (newThread == null) { rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE, "GdbSynchronizer unable to resolve thread context for the selected element", null)); return; } ICommand<MIInfo> command = fCommandFactory.createMIThreadSelect(fGdbcontrol.getContext(), getThreadIdFromContext(newThread)); fGdbcontrol.queueCommand(command, new ImmediateDataRequestMonitor<MIInfo> (rm) {}); }
Source:
static ReplicationFactor fromString(String s) { if (s.contains("/")) { int slash = s.indexOf('/'); String allPart = s.substring(0, slash); String transientPart = s.substring(slash + 1); Preconditions.checkArgument( allPart != null && transientPart != null, "Replication factor format is <replicas> or <replicas>/<transient>"); return new ReplicationFactor(Integer.parseInt(allPart), Integer.parseInt(transientPart)); } else { return new ReplicationFactor(Integer.parseInt(s), 0); } }

Target:
static ReplicationFactor fromString(String s) { if (s.contains("/")) { int slash = s.indexOf('/'); String allPart = s.substring(0, slash); String transientPart = s.substring(slash + 1); return new ReplicationFactor(Integer.parseInt(allPart), Integer.parseInt(transientPart)); } else { return new ReplicationFactor(Integer.parseInt(s), 0); } }
Source:
public void testStartCommand() throws CarbonToolsIntegrationTestException, NoSuchFieldException, IllegalAccessException { String[] cmdArrayToStart; Process process; if (CarbonCommandToolsUtil.isCurrentOSWindows()) { throw new SkipException("Feature --start is not available for windows"); } else { cmdArrayToStart = new String[] {"sh", "wso2server.sh", "--start", "-DportOffset=" + portOffset}; process = CarbonCommandToolsUtil.runScript(carbonHome + "/bin", cmdArrayToStart); } boolean startupStatus = CarbonCommandToolsUtil.isServerStartedUp(context, portOffset); Field field = process.getClass().getDeclaredField("pid"); field.setAccessible(true); processId = field.get(process).toString(); log.info("process id for carbon server with offset 1 : " + processId); assertTrue(startupStatus, "Unsuccessful login"); }

Target:
public void testStartCommand() throws CarbonToolsIntegrationTestException, NoSuchFieldException, IllegalAccessException { String[] cmdArrayToStart; Process process; if (CarbonCommandToolsUtil.getCurrentOperatingSystem(). contains(OperatingSystems.WINDOWS.name().toLowerCase())) { throw new SkipException("Feature --start is not available for windows"); } else { cmdArrayToStart = new String[] {"sh", "wso2server.sh", "--start", "-DportOffset=" + portOffset}; process = CarbonCommandToolsUtil.runScript(carbonHome + "/bin", cmdArrayToStart); } boolean startupStatus = CarbonCommandToolsUtil.isServerStartedUp(context, portOffset); Field field = process.getClass().getDeclaredField("pid"); field.setAccessible(true); processId = field.get(process).toString(); log.info("process id for carbon server with offset 1 : " + processId); assertTrue(startupStatus, "Unsuccessful login"); }
Source:
private PhysicalSlot addOneSlot() { final PhysicalSlot slot = createPhysicalSlot(); slots.add(slot); return slot; }

Target:
private PhysicalSlot addOneSlot() { final PhysicalSlot slot = createPhysicalSlot(); CompletableFuture.runAsync(() -> slots.add(slot), mainThreadExecutor).join(); return slot; }
Source:
public void setIdpInitSLOReturnToURLs(String[] idpInitSLOReturnToURLs) { this.idpInitSLOReturnToURLs = idpInitSLOReturnToURLs; }

Target:
public void setIdpInitSLOReturnToURLs(String[] idpInitSLOReturnToURLs) { if(idpInitSLOReturnToURLs != null) { this.idpInitSLOReturnToURLs = idpInitSLOReturnToURLs.clone(); } else { this.idpInitSLOReturnToURLs = null; } }
Source:
private void flushAll() { populations.forEach( population -> flush( population, population.takeCurrentBatch() ) ); }

Target:
private void flushAll() { populations.forEach( population -> flush( population ) ); }
Source:
public void createLogTable(final String tableName, final String entryTypeName) { createTable( tableName, ImmutableList.of( StringUtils.format( "CREATE TABLE %1$s (\n" + " id %2$s NOT NULL,\n" + " %3$s_id VARCHAR(255) DEFAULT NULL,\n" + " log_payload_id VARCHAR(255) NOT NULL,\n" + " log_payload_order SMALLINT NOT NULL,\n" + " log_payload_part %4$s,\n" + " PRIMARY KEY (id)\n" + ")", tableName, getSerialType(), entryTypeName, getPayloadType() ), StringUtils.format("CREATE INDEX idx_%1$s_%2$s_id ON %1$s(%2$s_id)", tableName, entryTypeName) ) ); }

Target:
public void createLogTable(final String tableName, final String entryTypeName) { createTable( tableName, ImmutableList.of( StringUtils.format( "CREATE TABLE %1$s (\n" + " id %2$s NOT NULL,\n" + " %3$s_id VARCHAR(255) DEFAULT NULL,\n" + " log_payload_id VARCHAR(255) NOT NULL,\n" + " log_payload_order %4$s NOT NULL,\n" + " log_payload_part %5$s,\n" + " PRIMARY KEY (id)\n" + ")", tableName, getSerialType(), entryTypeName, getIntegerType(), getPayloadType() ), StringUtils.format("CREATE INDEX idx_%1$s_%2$s_id ON %1$s(%2$s_id)", tableName, entryTypeName) ) ); }
Source:
protected <T> T upload(String artifactId, File file, Class<T> clazz, String blobName) { Payload<?> payload = new FilePayload(file); Invocation<T> invocation = put(clazz,uri(ClientConstants.PATH_ARTIFACTS+ClientConstants.URI_SEP+ artifactType.value()+"/%s/%s",artifactId,blobName)); invocation.entity(payload); return invocation.execute(); }

Target:
protected <T> T upload(String artifactId, File file, Class<T> clazz, String blobName) { Payload<?> payload = new FilePayload(file); Invocation<T> invocation = put(clazz,uri(PATH_ARTIFACTS+URI_SEP+ artifactType.value()+"/%s/%s",artifactId,blobName)); invocation.entity(payload); return invocation.execute(); }
Source:
public void testWhenAnyFirstSuccess() { runTaskTest(new Callable<Task<?>>() { @Override public Task<?> call() throws Exception { final ArrayList<Task<Void>> tasks = new ArrayList<>(); final Task<Void> firstToCompleteSuccess = Task.callInBackground(new Callable<Void>() { @Override public Void call() throws Exception { Thread.sleep(50); return null; } }); tasks.addAll(launchTasksWithRandomCompletions(10)); tasks.add(firstToCompleteSuccess); return Task.whenAny(tasks).continueWith(new Continuation<Task<?>, Object>() { @Override public Object then(Task<Task<?>> task) throws Exception { assertTrue(task.isCompleted()); assertFalse(task.isFaulted()); assertFalse(task.isCancelled()); assertEquals(task.getResult(), firstToCompleteSuccess); assertTrue(task.getResult().isCompleted()); assertFalse(task.getResult().isCancelled()); assertFalse(task.getResult().isFaulted()); return null; } }); } }); }

Target:
public void testWhenAnyFirstSuccess() { runTaskTest(new Callable<Task<?>>() { @Override public Task<?> call() throws Exception { final ArrayList<Task<?>> tasks = new ArrayList<>(); final Task<String> firstToCompleteSuccess = Task.callInBackground(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(50); return "SUCCESS"; } }); tasks.addAll(launchTasksWithRandomCompletions(5)); tasks.add(firstToCompleteSuccess); tasks.addAll(launchTasksWithRandomCompletions(5)); return Task.whenAny(tasks).continueWith(new Continuation<Task<?>, Object>() { @Override public Object then(Task<Task<?>> task) throws Exception { assertTrue(task.isCompleted()); assertFalse(task.isFaulted()); assertFalse(task.isCancelled()); assertEquals(firstToCompleteSuccess, task.getResult()); assertTrue(task.getResult().isCompleted()); assertFalse(task.getResult().isCancelled()); assertFalse(task.getResult().isFaulted()); assertEquals("SUCCESS", task.getResult().getResult()); return null; } }); } }); }
Source:
protected boolean isAppConfiguredInSourceServerXml(String fileName) { boolean bConfigured = false; Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.contains(fileName)) { log.debug("Application configuration is found in server.xml : " + fileName); bConfigured = true; } return bConfigured; }

Target:
protected boolean isAppConfiguredInSourceServerXml(String fileName) { Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.contains(fileName)) { log.debug("Application configuration is found in server.xml : " + fileName); return true; } else { return false; } }
Source:
protected Configuration createConfiguration() { final Configuration conf = (null != mStandaloneConf) ? HBaseConfiguration.create(mStandaloneConf) : HBaseConfiguration.create(); conf.addResource("mapred-site.xml"); return conf; }

Target:
protected Configuration createConfiguration() { return (null != mStandaloneConf) ? HBaseConfiguration.create(mStandaloneConf) : HBaseConfiguration.create(); }
Source:
public String toString() { return "KafkaIndexTaskTuningConfig{" + "maxRowsInMemory=" + getMaxRowsInMemory() + ", maxRowsPerSegment=" + getMaxRowsPerSegment() + ", maxBytesInMemory=" + getMaxBytesInMemory() + ", intermediatePersistPeriod=" + getIntermediatePersistPeriod() + ", basePersistDirectory=" + getBasePersistDirectory() + ", maxPendingPersists=" + getMaxPendingPersists() + ", indexSpec=" + getIndexSpec() + ", reportParseExceptions=" + isReportParseExceptions() + ", handoffConditionTimeout=" + getHandoffConditionTimeout() + ", resetOffsetAutomatically=" + isResetOffsetAutomatically() + ", segmentWriteOutMediumFactory=" + getSegmentWriteOutMediumFactory() + ", intermediateHandoffPeriod=" + getIntermediateHandoffPeriod() + ", logParseExceptions=" + isLogParseExceptions() + ", maxParseExceptions=" + getMaxParseExceptions() + ", maxSavedParseExceptions=" + getMaxSavedParseExceptions() + '}'; }

Target:
public String toString() { return "KafkaIndexTaskTuningConfig{" + "maxRowsInMemory=" + getMaxRowsInMemory() + ", maxRowsPerSegment=" + getMaxRowsPerSegment() + ", maxTotalRows=" + getMaxTotalRows() + ", maxBytesInMemory=" + getMaxBytesInMemory() + ", intermediatePersistPeriod=" + getIntermediatePersistPeriod() + ", basePersistDirectory=" + getBasePersistDirectory() + ", maxPendingPersists=" + getMaxPendingPersists() + ", indexSpec=" + getIndexSpec() + ", reportParseExceptions=" + isReportParseExceptions() + ", handoffConditionTimeout=" + getHandoffConditionTimeout() + ", resetOffsetAutomatically=" + isResetOffsetAutomatically() + ", segmentWriteOutMediumFactory=" + getSegmentWriteOutMediumFactory() + ", intermediateHandoffPeriod=" + getIntermediateHandoffPeriod() + ", logParseExceptions=" + isLogParseExceptions() + ", maxParseExceptions=" + getMaxParseExceptions() + ", maxSavedParseExceptions=" + getMaxSavedParseExceptions() + '}'; }
Source:
public static String[] getEnvironmentVariables() { ArrayList vars = new ArrayList(); String[] envVars = null; String var; int i; if(null == SystemTapGUIPlugin.getDefault() || null == SystemTapGUIPlugin.getDefault().getPreferenceStore()) { return null; } IPreferenceStore p = SystemTapGUIPlugin.getDefault().getPreferenceStore(); for(i=0; i<PreferenceConstants.P_ENV.length; i++) { var = p.getString(PreferenceConstants.P_ENV[i][0]).trim(); if(!var.equals("")) { vars.add(PreferenceConstants.P_ENV[i][0] + "=" + var); } } if(vars.size() > 0) { envVars = new String[vars.size()]; for(i = 0; i<vars.size(); i++) envVars[i] = (String)vars.get(i); } return envVars; }

Target:
public static String[] getEnvironmentVariables() { ArrayList vars = new ArrayList(); String[] envVars = null; String var; int i; if(null == SystemTapGUIPlugin.getDefault() || null == SystemTapGUIPlugin.getDefault().getPreferenceStore()) { return null; } IPreferenceStore p = SystemTapGUIPlugin.getDefault().getPreferenceStore(); for(i=0; i<PreferenceConstants.P_ENV.length; i++) { var = p.getString(PreferenceConstants.P_ENV[i][0]).trim(); if(!var.equals("")) { vars.add(PreferenceConstants.P_ENV[i][0] + "=" + var); } } if(vars.size() > 0) { envVars = new String[vars.size()]; for (i = 0; i < vars.size(); i++) { envVars[i] = (String) vars.get(i); } } return envVars; }
Source:
public void obtain_current_OffsetDateTime_using_ZoneOffset() { final int expectedSeconds = 3*Timestamps.SECONDS_PER_HOUR; final ZoneOffset inKiev = ZoneOffsets.ofHours(3); final OffsetDateTime today = OffsetDateTimes.now(inKiev); final Calendar calendar = Calendar.getInstance(); assertEquals(calendar.get(Calendar.YEAR), today.getDate().getYear()); assertEquals(calendar.get(Calendar.MONTH) + 1, today.getDate().getMonthValue()); assertEquals(calendar.get(Calendar.DAY_OF_MONTH), today.getDate().getDay()); final Timestamp time = Timestamps.getCurrentTime(); calendar.setTimeInMillis(time.getSeconds() / 1000); assertEquals(calendar.get(Calendar.HOUR), today.getTime().getHours()); assertEquals(calendar.get(Calendar.MINUTE), today.getTime().getMinutes()); assertEquals(calendar.get(Calendar.SECOND), today.getTime().getSeconds()); assertEquals(expectedSeconds, today.getOffset().getAmountSeconds()); }

Target:
public void obtain_current_OffsetDateTime_using_ZoneOffset() { final OffsetDateTime now = OffsetDateTimes.now(ZONE_OFFSET); final Calendar cal = Calendars.nowAt(ZONE_OFFSET); final LocalDate today = now.getDate(); assertEquals(getYear(cal), today.getYear()); assertEquals(getMonth(cal), today.getMonthValue()); assertEquals(getDay(cal), today.getDay()); final LocalTime time = now.getTime(); assertEquals(getHours(cal), time.getHours()); assertEquals(getMinutes(cal), time.getMinutes()); assertEquals(getSeconds(cal), time.getSeconds()); assertEquals(getZoneOffset(cal), now.getOffset() .getAmountSeconds()); }
Source:
public DisruptorAutobatcher<I, O> build() { Preconditions.checkArgument(purpose != null, "purpose must be provided"); EventHandler<BatchElement<I, O>> handler = this.handlerFactory.apply(DEFAULT_BUFFER_SIZE); EventHandler<BatchElement<I, O>> tracingHandler = (event, sequence, endOfBatch) -> { if (endOfBatch) { Tracers.wrapWithNewTrace(purpose, observability, (Callable<Void>) () -> { handler.onEvent(event, sequence, true); return null; }).call(); } else { handler.onEvent(event, sequence, false); } }; EventHandler<BatchElement<I, O>> profiledHandler = new ProfilingEventHandler<>(tracingHandler, purpose, safeTags.build()); return DisruptorAutobatcher.create(profiledHandler, DEFAULT_BUFFER_SIZE, purpose); }

Target:
public DisruptorAutobatcher<I, O> build() { Preconditions.checkArgument(purpose != null, "purpose must be provided"); EventHandler<BatchElement<I, O>> handler = this.handlerFactory.apply(DEFAULT_BUFFER_SIZE); EventHandler<BatchElement<I, O>> tracingHandler = new TracingEventHandler<>(handler, purpose, observability); EventHandler<BatchElement<I, O>> profiledHandler = new ProfilingEventHandler<>(tracingHandler, purpose, safeTags.build()); return DisruptorAutobatcher.create(profiledHandler, DEFAULT_BUFFER_SIZE, purpose); }
Source:
public void handleCompleteTransactionResponseMessage(CompleteTransactionResponseMessage msg) { TransactionState txn = m_outstandingTxns.get(msg.getTxnId()); DuplicateCounter counter = m_duplicateCounters.get(new DuplicateCounterKey(msg.getTxnId(), msg.getSpHandle())); if (txn != null) { if (!msg.isRestart()) { m_outstandingTxns.remove(msg.getTxnId()); boolean duplicateCounterDone = true; if (counter != null) { duplicateCounterDone = counter.offer(msg) == DuplicateCounter.DONE; } if (m_isLeader && duplicateCounterDone) { assert txn.isDone(); setRepairLogTruncationHandle(txn.m_spHandle); } } } if (!m_isLeader) { m_mailbox.send(msg.getSPIHSId(), msg); } }

Target:
public void handleCompleteTransactionResponseMessage(CompleteTransactionResponseMessage msg) { TransactionState txn = m_outstandingTxns.get(msg.getTxnId()); final DuplicateCounterKey duplicateCounterKey = new DuplicateCounterKey(msg.getTxnId(), msg.getSpHandle()); DuplicateCounter counter = m_duplicateCounters.get(duplicateCounterKey); boolean txnDone = true; if (msg.isRestart()) { txnDone = false; } if (counter != null) { txnDone = counter.offer(msg) == DuplicateCounter.DONE; } if (txnDone) { m_outstandingTxns.remove(msg.getTxnId()); m_duplicateCounters.remove(duplicateCounterKey); if (txn != null) { assert txn.isDone(); setRepairLogTruncationHandle(txn.m_spHandle); } } if (!m_isLeader) { m_mailbox.send(msg.getSPIHSId(), msg); } }
Source:
public CommandLineParser getCommandLineParser() { if (commandLineParser == null) { commandLineParser = useLegacyParser(getClass()) ? new LegacyCommandLineArgumentParser(this) : new CommandLineArgumentParser(this, Collections.emptyList(), new HashSet<>(Collections.singleton(CommandLineParserOptions.APPEND_TO_COLLECTIONS))); } return commandLineParser; }

Target:
public CommandLineParser getCommandLineParser() { if (commandLineParser == null) { commandLineParser = useLegacyParser() ? new LegacyCommandLineArgumentParser(this) : new CommandLineArgumentParser(this, Collections.EMPTY_LIST, Collections.singleton(CommandLineParserOptions.APPEND_TO_COLLECTIONS)); } return commandLineParser; }
Source:
private Object deleteObjects(Environment context) { if (context.data.isPresent()) { throw new BadRequestException("DELETE must not include data argument"); } if (!context.ids.isPresent()) { throw new BadRequestException("DELETE must include ids argument"); } Set<PersistentResource> toDelete = ((ConnectionContainer) fetchObjects(context)).getPersistentResources(); toDelete.forEach(PersistentResource::deleteResource); return new ConnectionContainer(toDelete, Optional.empty(), "TODO"); }

Target:
private Object deleteObjects(Environment context) { if (context.data.isPresent()) { throw new BadRequestException("DELETE must not include data argument"); } if (!context.ids.isPresent()) { throw new BadRequestException("DELETE must include ids argument"); } ConnectionContainer connection = (ConnectionContainer) fetchObjects(context); Set<PersistentResource> toDelete = connection.getPersistentResources(); toDelete.forEach(PersistentResource::deleteResource); return new ConnectionContainer(toDelete, Optional.empty(), connection.getTypeName()); }
Source:
void addEntriesAndRotateLogs(EntryLogger entryLogger, int numOfRotations) throws IOException { EntryLogManagerBase entryLogManager = (EntryLogManagerBase) entryLogger.getEntryLogManager(); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); Random rand = new Random(); for (int i = 0; i < numOfRotations; i++) { addEntries(entryLogger, 10); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); } addEntries(entryLogger, 10); }

Target:
void addEntriesAndRotateLogs(EntryLogger entryLogger, int numOfRotations) throws IOException { EntryLogManagerBase entryLogManager = (EntryLogManagerBase) entryLogger.getEntryLogManager(); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); for (int i = 0; i < numOfRotations; i++) { addEntries(entryLogger, 10); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); } addEntries(entryLogger, 10); }
Source:
public Map<EventTypePartition, Duration> getTimeLags(final Collection<NakadiCursor> committedPositions, final List<PartitionEndStatistics> endPositions) throws ErrorGettingCursorTimeLagException, InconsistentStateException, LimitReachedException, TimeLagStatsTimeoutException { final TimeLagRequestHandler timeLagHandler = new TimeLagRequestHandler(timelineService, threadPool); final Map<EventTypePartition, Duration> timeLags = new HashMap<>(); final Map<EventTypePartition, CompletableFuture<Duration>> futureTimeLags = new HashMap<>(); try { for (final NakadiCursor cursor : committedPositions) { if (isCursorAtTail(cursor, endPositions)) { timeLags.put(cursor.getEventTypePartition(), Duration.ZERO); } else { final CompletableFuture<Duration> timeLagFuture = timeLagHandler.getCursorTimeLagFuture(cursor); futureTimeLags.put(cursor.getEventTypePartition(), timeLagFuture); } } CompletableFuture .allOf(futureTimeLags.values().toArray(new CompletableFuture[futureTimeLags.size()])) .get(timeLagHandler.getRemainingTimeoutMs(), TimeUnit.MILLISECONDS); for (final EventTypePartition partition : futureTimeLags.keySet()) { timeLags.put(partition, futureTimeLags.get(partition).get()); } } catch (RejectedExecutionException|TimeoutException | ExecutionException e) { LOG.warn("caught exception the timelag stats are not complete"); } catch (Throwable e){ LOG.warn("caught throwable the timelag stats are not complete"); } return timeLags; }

Target:
public Map<EventTypePartition, Duration> getTimeLags(final Collection<NakadiCursor> committedPositions, final List<PartitionEndStatistics> endPositions) { final TimeLagRequestHandler timeLagHandler = new TimeLagRequestHandler(timelineService, threadPool); final Map<EventTypePartition, Duration> timeLags = new HashMap<>(); final Map<EventTypePartition, CompletableFuture<Duration>> futureTimeLags = new HashMap<>(); try { for (final NakadiCursor cursor : committedPositions) { if (isCursorAtTail(cursor, endPositions)) { timeLags.put(cursor.getEventTypePartition(), Duration.ZERO); } else { final CompletableFuture<Duration> timeLagFuture = timeLagHandler.getCursorTimeLagFuture(cursor); futureTimeLags.put(cursor.getEventTypePartition(), timeLagFuture); } } CompletableFuture .allOf(futureTimeLags.values().toArray(new CompletableFuture[futureTimeLags.size()])) .get(timeLagHandler.getRemainingTimeoutMs(), TimeUnit.MILLISECONDS); for (final EventTypePartition partition : futureTimeLags.keySet()) { timeLags.put(partition, futureTimeLags.get(partition).get()); } } catch (RejectedExecutionException | TimeoutException | ExecutionException e) { LOG.warn("caught exception the timelag stats are not complete - " + e); } catch (Throwable e) { LOG.warn("caught throwable the timelag stats are not complete - " + e); } return timeLags; }
Source:
public void deleteModelValidModelIdWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); StepVerifier.create(client.deleteModelWithResponse(createdModel.getModelId())) .assertNext(response -> assertEquals(response.getStatusCode(), HttpResponseStatus.NO_CONTENT.code())) .verifyComplete(); StepVerifier.create(client.getCustomModelWithResponse(createdModel.getModelId())) .verifyErrorSatisfies(throwable -> { assertEquals(HttpResponseException.class, throwable.getClass()); final FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) ((HttpResponseException) throwable).getValue(); assertEquals("1022", errorInformation.getErrorCode()); }); }); }

Target:
public void deleteModelValidModelIdWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); StepVerifier.create(client.deleteModelWithResponse(createdModel.getModelId())) .assertNext(response -> assertEquals(response.getStatusCode(), HttpResponseStatus.NO_CONTENT.code())) .verifyComplete(); StepVerifier.create(client.getCustomModelWithResponse(createdModel.getModelId())) .verifyErrorSatisfies(throwable -> { assertEquals(HttpResponseException.class, throwable.getClass()); final FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) ((HttpResponseException) throwable).getValue(); assertEquals(EXPECTED_MODEL_ID_NOT_FOUND_ERROR_CODE, errorInformation.getErrorCode()); }); }); }
Source:
boolean requiresBracketWithSimpleAlgorithm(ProductionReference outer, ProductionReference leftCapture, ProductionReference rightCapture, ProductionReference inner) { boolean priority = isPriorityWrong(outer, inner, getPosition(inner, outer)); boolean inversePriority; EnumSet<Fixity> fixity = getFixity(inner, outer); EnumSet<Fixity> innerFixity = getFixity(inner); Tag parentLabel = new Tag(outer.production().klabel().get().name()); Tag localLabel = new Tag(inner.production().klabel().get().name()); if (parentLabel.equals(localLabel) && m.attributesFor().apply(inner.production().klabel().get()).contains(Attribute.ASSOCIATIVE_KEY)) return false; if (inner instanceof Constant) return false; if (fixity.size() == 0) return false; if (priority) return true; if (inner.production().isSyntacticSubsort()) return false; if (innerFixity.contains(Fixity.BARE_RIGHT) && rightCapture != null) { inversePriority = isPriorityWrong(inner, rightCapture, inner.production().items().size() - 1); EnumSet<Fixity> rightCaptureFixity = getFixity(rightCapture); if (!inversePriority && rightCaptureFixity.contains(Fixity.BARE_LEFT)) { return true; } } if (innerFixity.contains(Fixity.BARE_LEFT) && leftCapture != null) { inversePriority = isPriorityWrong(inner, leftCapture, 0); EnumSet<Fixity> leftCaptureFixity = getFixity(leftCapture); if (!inversePriority && leftCaptureFixity.contains(Fixity.BARE_RIGHT)) { return true; } } return false; }

Target:
boolean requiresBracketWithSimpleAlgorithm(ProductionReference outer, ProductionReference leftCapture, ProductionReference rightCapture, ProductionReference inner) { boolean priority = isPriorityWrong(outer, inner, getPosition(inner, outer)); boolean inversePriority; EnumSet<Fixity> fixity = getFixity(inner, outer); EnumSet<Fixity> innerFixity = getFixity(inner); if (inner.production().klabel().equals(outer.production().klabel()) && inner.production().klabel().isDefined() && m.attributesFor().apply(inner.production().klabel().get()).contains(Attribute.ASSOCIATIVE_KEY)) return false; if (inner instanceof Constant) return false; if (fixity.size() == 0) return false; if (priority) return true; if (inner.production().isSyntacticSubsort()) return false; if (innerFixity.contains(Fixity.BARE_RIGHT) && rightCapture != null) { inversePriority = isPriorityWrong(inner, rightCapture, inner.production().items().size() - 1); EnumSet<Fixity> rightCaptureFixity = getFixity(rightCapture); if (!inversePriority && rightCaptureFixity.contains(Fixity.BARE_LEFT)) { return true; } } if (innerFixity.contains(Fixity.BARE_LEFT) && leftCapture != null) { inversePriority = isPriorityWrong(inner, leftCapture, 0); EnumSet<Fixity> leftCaptureFixity = getFixity(leftCapture); if (!inversePriority && leftCaptureFixity.contains(Fixity.BARE_RIGHT)) { return true; } } return false; }
Source:
public final void run(final int iteration) { posNum = 0; negNum = 0; final Set<LongRange> ranges = workloadQuota.get(dataType); if (ranges == null) { LOG.log(Level.INFO, "No {0} type data assigned to this task", dataType); return; } for (final LongRange range : ranges) { final Map<?, Row> rows = memoryStore.getElasticStore().getRange(dataType, range.getMinimumLong(), range.getMaximumLong()); for (final Row row : rows.values()) { final double output = row.getOutput(); final double predict = model.predict(row.getFeature()); if (output * predict > 0) { posNum++; } else { negNum++; } } for (final Row row : rows.values()) { final double output = row.getOutput(); final Vector input = row.getFeature(); final Vector gradient = loss.gradient(input, model.predict(input), output).plus(regularization.gradient(model)); model.setParameters(model.getParameters().minus(gradient.times(stepSize))); } } }

Target:
public final void run(final int iteration) { posNum = 0; negNum = 0; final Map<?, Row> rows = workloadPartition.getAllData(dataType); for (final Row row : rows.values()) { final double output = row.getOutput(); final double predict = model.predict(row.getFeature()); if (output * predict > 0) { posNum++; } else { negNum++; } } for (final Row row : rows.values()) { final double output = row.getOutput(); final Vector input = row.getFeature(); final Vector gradient = loss.gradient(input, model.predict(input), output).plus(regularization.gradient(model)); model.setParameters(model.getParameters().minus(gradient.times(stepSize))); } }
Source:
protected synchronized void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner) { if(numberOfPrameters ==2){ processFor2Prameters(streamEventChunk,nextProcessor,streamEventCloner); } else if(numberOfPrameters == 3){ processFor3Prameters(streamEventChunk,nextProcessor,streamEventCloner); } }

Target:
protected synchronized void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner) { if (!isStartTimeEnabled) { processWithoutStartTime(streamEventChunk, nextProcessor, streamEventCloner); } else { processWithStartTime(streamEventChunk, nextProcessor, streamEventCloner); } }
Source:
public void moveToRecycleBin(FeedbackSessionAttributes sessionToDelete) { int rowId = getFeedbackSessionRowId(sessionToDelete.getCourseId(), sessionToDelete.getFeedbackSessionName()); clickAndConfirm(browser.driver.findElement(By.id("btn-soft-delete-" + rowId))); ThreadHelper.waitFor(1000); }

Target:
public void moveToRecycleBin(FeedbackSessionAttributes sessionToDelete) { int rowId = getFeedbackSessionRowId(sessionToDelete.getCourseId(), sessionToDelete.getFeedbackSessionName()); clickAndConfirm(browser.driver.findElement(By.id("btn-soft-delete-" + rowId))); waitUntilAnimationFinish(); }
Source:
public void releaseConsumerFor(Channel channel, boolean cancelConsumer, String message) { SimpleConsumer consumer = this.inUseConsumerChannels.remove(channel); if (consumer != null && cancelConsumer) { this.logger.error("Consumer canceled by client" + consumer); consumer.cancelConsumer("Consumer " + this + " canceled due to " + message); } }

Target:
public void releaseConsumerFor(Channel channel, boolean cancelConsumer, String message) { SimpleConsumer consumer = this.inUseConsumerChannels.remove(channel); if (consumer != null && cancelConsumer) { Assert.isTrue(message != null, "A 'message' is required when 'cancelConsumer' is 'true'"); consumer.cancelConsumer("Consumer " + this + " canceled due to " + message); } }
Source:
private void doTransfers (RaptorState state) { final int walkSpeedMillimetersPerSecond = (int) (request.walkSpeed * 1000); final int maxWalkMillimeters = walkSpeedMillimetersPerSecond * (request.maxWalkTime * SECONDS_PER_MINUTE); for (int stop = state.nonTransferStopsUpdated.nextSetBit(0); stop > -1; stop = state.nonTransferStopsUpdated.nextSetBit(stop + 1) ) { TIntList transfersFromStop = transit.transfersForStop.get(stop); if (transfersFromStop != null) { for (int i = 0; i < transfersFromStop.size(); i += 2) { int targetStop = transfersFromStop.get(i); int distanceToTargetStopMillimeters = transfersFromStop.get(i + 1); if (distanceToTargetStopMillimeters < maxWalkMillimeters) { int walkTimeToTargetStopSeconds = distanceToTargetStopMillimeters / walkSpeedMillimetersPerSecond; checkState(walkTimeToTargetStopSeconds >= 0, "Transfer walk time must be positive."); int timeAtTargetStop = state.bestNonTransferTimes[stop] + walkTimeToTargetStopSeconds; state.setTimeAtStop(targetStop, timeAtTargetStop, -1, stop, 0, 0, true); } } } } }

Target:
private void doTransfers (RaptorState state) { final int walkSpeedMillimetersPerSecond = (int) (request.walkSpeed * 1000); final int maxWalkMillimeters = walkSpeedMillimetersPerSecond * (request.maxWalkTime * SECONDS_PER_MINUTE); for (int stop = state.nonTransferStopsUpdated.nextSetBit(0); stop >= 0; stop = state.nonTransferStopsUpdated.nextSetBit(stop + 1) ) { TIntList transfersFromStop = transit.transfersForStop.get(stop); if (transfersFromStop != null) { for (int i = 0; i < transfersFromStop.size(); i += 2) { int targetStop = transfersFromStop.get(i); int distanceToTargetStopMillimeters = transfersFromStop.get(i + 1); if (distanceToTargetStopMillimeters < maxWalkMillimeters) { int walkTimeToTargetStopSeconds = distanceToTargetStopMillimeters / walkSpeedMillimetersPerSecond; checkState(walkTimeToTargetStopSeconds >= 0, "Transfer walk time must be positive."); int timeAtTargetStop = state.bestNonTransferTimes[stop] + walkTimeToTargetStopSeconds; state.setTimeAtStop(targetStop, timeAtTargetStop, -1, stop, 0, 0, true); } } } } }
Source:
protected String createPassFile(String value) throws IOException { File temp = File.createTempFile("ovirt", ".tmp"); String filePath = temp.getAbsolutePath(); BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write(value); out.close(); if (new File("/usr/bin/chmod").exists()) { Runtime.getRuntime().exec("/usr/bin/chmod " + filePath); } return filePath; }

Target:
protected String createPassFile(String value) throws IOException { File temp = File.createTempFile("ovirt", ".tmp"); String filePath = temp.getAbsolutePath(); temp.setReadable(true, true); temp.setWritable(true, true); temp.setExecutable(false); BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write(value); out.close(); return filePath; }
Source:
public void verifyDeleteViaVideoNotPresent() { addVideoViaAjax(VideoContent.youtubeVideoURL2); refreshPage(); refreshPage(); deleteVideo(); verifyNotificationMessage(); Assertion.assertNotEquals(VideoContent.youtubeVideoURL2name, getNewestVideoTitle()); PageObjectLogging.log("verifyDeleteVideoNotPresent", "verify video " + VideoContent.youtubeVideoURL2name + " was deleted", true); }

Target:
public void verifyDeleteViaVideoNotPresent() { addVideoViaAjax(VideoContent.youtubeVideoURL2); refreshUntilElementOnPage(newestVideo2, refreshLimit); deleteVideo(); verifyNotificationMessage(); Assertion.assertNotEquals(VideoContent.youtubeVideoURL2name, getNewestVideoTitle()); PageObjectLogging.log("verifyDeleteVideoNotPresent", "verify video " + VideoContent.youtubeVideoURL2name + " was deleted", true); }
Source:
public void onClick(DuNativeAd duNativeAd) { if (mNativeListener != null) { DuAdMediation.d(TAG, "Dap NativeAd clicked."); mNativeListener.onAdClicked(mAdapter); } }

Target:
public void onClick(DuNativeAd duNativeAd) { if (mNativeListener != null) { DuAdMediation.d(TAG, "Dap NativeAd clicked."); mNativeListener.onAdClicked(mAdapter); mNativeListener.onAdOpened(mAdapter); mNativeListener.onAdLeftApplication(mAdapter); } }
Source:
public void testRemovePrefixToDs3ObjectsList() throws IOException, SignatureException { final List<Ds3Object> ds3ObjectList = Lists.newArrayList(new Ds3Object("foo/bar"), new Ds3Object("foo/baz")); final Ds3ClientHelpers helper = Ds3ClientHelpers.wrap(buildDs3ClientForBulk()); final Iterable<Ds3Object> modifiedDs3ObjectList = helper.removePrefixFromDs3ObjectsList(ds3ObjectList, "foo/"); boolean foundBar = false; boolean foundBaz = false; for (Ds3Object obj : modifiedDs3ObjectList) { if (obj.getName().equals("bar")) { foundBar = true; } else if (obj.getName().equals("baz")) { foundBaz = true; } } assertTrue(foundBar); assertTrue(foundBaz); }

Target:
public void testRemovePrefixToDs3ObjectsList() throws IOException, SignatureException { final List<Ds3Object> ds3ObjectList = Lists.newArrayList(new Ds3Object("foo/bar"), new Ds3Object("foo/baz")); final Ds3ClientHelpers helper = Ds3ClientHelpers.wrap(buildDs3ClientForBulk()); final Iterable<Ds3Object> modifiedDs3ObjectList = helper.removePrefixFromDs3ObjectsList(ds3ObjectList, "foo/"); boolean foundBar = false; boolean foundBaz = false; for (final Ds3Object obj : modifiedDs3ObjectList) { if (obj.getName().equals("bar")) { foundBar = true; } else if (obj.getName().equals("baz")) { foundBaz = true; } } assertTrue(foundBar); assertTrue(foundBaz); }
Source:
public void setHeartbeat(final int heartbeat) throws IOException { this.client.getConfig().put( LuaCommand.HEARTBEAT.toString(), heartbeat); }

Target:
public void setHeartbeat(final int heartbeat) throws IOException { this.client.getConfig().put( this.getHeartbeatConfigName(), heartbeat); }
Source:
public void initWithHosts(Map<Host, HostConnectionPool<CL>> hPools) { List<HostToken> allHostTokens = tokenSupplier.getTokens(hPools.keySet()); Map<HostToken, HostConnectionPool<CL>> tokenPoolMap = new HashMap<HostToken, HostConnectionPool<CL>>(); for (HostToken hToken : allHostTokens) { hostTokens.put(hToken.getHost(), hToken); tokenPoolMap.put(hToken, hPools.get(hToken.getHost())); } Set<String> remoteDCs = new HashSet<String>(); this.hashtag = hPools.keySet().iterator().next().getHashtag(); for (Host host : hPools.keySet()) { String dc = host.getRack(); if (localRack != null && !localRack.isEmpty() && dc != null && !dc.isEmpty() && !localRack.equals(dc)) { remoteDCs.add(dc); } if(this.hashtag != null) { String hashtagNew = host.getHashtag(); if (!this.hashtag.equals(hashtagNew)){ throw new RuntimeException("Hashtags are different across hosts"); } this.hashtag = hashtagNew; } } Map<HostToken, HostConnectionPool<CL>> localPools = getHostPoolsForDC(tokenPoolMap, localRack); localSelector.initWithHosts(localPools); if (localSelector.isTokenAware() && localRack != null) { replicationFactor.set(calculateReplicationFactor(allHostTokens)); } for (String dc : remoteDCs) { Map<HostToken, HostConnectionPool<CL>> dcPools = getHostPoolsForDC(tokenPoolMap, dc); HostSelectionStrategy<CL> remoteSelector = selectorFactory.vendPoolSelectionStrategy(); remoteSelector.initWithHosts(dcPools); remoteDCSelectors.put(dc, remoteSelector); } remoteDCNames.swapWithList(remoteDCSelectors.keySet()); topology.set(getTokenPoolTopology()); }

Target:
public void initWithHosts(Map<Host, HostConnectionPool<CL>> hPools) { List<HostToken> allHostTokens = tokenSupplier.getTokens(hPools.keySet()); Map<HostToken, HostConnectionPool<CL>> tokenPoolMap = new HashMap<HostToken, HostConnectionPool<CL>>(); for (HostToken hToken : allHostTokens) { hostTokens.put(hToken.getHost(), hToken); tokenPoolMap.put(hToken, hPools.get(hToken.getHost())); } Set<String> remoteRacks = new HashSet<String>(); for (Host host : hPools.keySet()) { String rack = host.getRack(); if (localRack != null && !localRack.isEmpty() && rack != null && !rack.isEmpty() && !localRack.equals(rack)) { remoteRacks.add(rack); } } Map<HostToken, HostConnectionPool<CL>> localPools = getHostPoolsForDC(tokenPoolMap, localRack); localSelector.initWithHosts(localPools); if (localSelector.isTokenAware() && localRack != null) { replicationFactor.set(calculateReplicationFactor(allHostTokens)); } for (String rack : remoteRacks) { Map<HostToken, HostConnectionPool<CL>> dcPools = getHostPoolsForDC(tokenPoolMap, rack); HostSelectionStrategy<CL> remoteSelector = selectorFactory.vendPoolSelectionStrategy(); remoteSelector.initWithHosts(dcPools); remoteRackSelectors.put(rack, remoteSelector); } remoteDCNames.swapWithList(remoteRackSelectors.keySet()); topology.set(getTokenPoolTopology()); }