auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public QueryExplainer( List<PlanOptimizer> planOptimizers, PlanFragmenter planFragmenter, Metadata metadata, NodePartitioningManager nodePartitioningManager, AccessControl accessControl, SqlParser sqlParser, StatsCalculator statsCalculator, CostCalculator costCalculator, InternalNodeManager nodeManager, NodeSchedulerConfig nodeSchedulerConfig, Map<Class<? extends Statement>, DataDefinitionTask<?>> dataDefinitionTask) { this.planOptimizers = requireNonNull(planOptimizers, "planOptimizers is null"); this.planFragmenter = requireNonNull(planFragmenter, "planFragmenter is null"); this.metadata = requireNonNull(metadata, "metadata is null"); this.nodePartitioningManager = requireNonNull(nodePartitioningManager, "nodePartitioningManager is null"); this.accessControl = requireNonNull(accessControl, "accessControl is null"); this.sqlParser = requireNonNull(sqlParser, "sqlParser is null"); this.statsCalculator = requireNonNull(statsCalculator, "statsCalculator is null"); this.costCalculator = requireNonNull(costCalculator, "costCalculator is null"); this.nodeManager = requireNonNull(nodeManager, "nodeManager is null"); this.nodeSchedulerConfig = requireNonNull(nodeSchedulerConfig); this.dataDefinitionTask = ImmutableMap.copyOf(requireNonNull(dataDefinitionTask, "dataDefinitionTask is null")); }

Target:
public QueryExplainer( List<PlanOptimizer> planOptimizers, PlanFragmenter planFragmenter, Metadata metadata, NodePartitioningManager nodePartitioningManager, AccessControl accessControl, SqlParser sqlParser, StatsCalculator statsCalculator, CostCalculator costCalculator, InternalNodeManager nodeManager, NodeSchedulerConfig nodeSchedulerConfig, Map<Class<? extends Statement>, DataDefinitionTask<?>> dataDefinitionTask) { this.planOptimizers = requireNonNull(planOptimizers, "planOptimizers is null"); this.planFragmenter = requireNonNull(planFragmenter, "planFragmenter is null"); this.metadata = requireNonNull(metadata, "metadata is null"); this.nodePartitioningManager = requireNonNull(nodePartitioningManager, "nodePartitioningManager is null"); this.accessControl = requireNonNull(accessControl, "accessControl is null"); this.sqlParser = requireNonNull(sqlParser, "sqlParser is null"); this.statsCalculator = requireNonNull(statsCalculator, "statsCalculator is null"); this.costCalculator = requireNonNull(costCalculator, "costCalculator is null"); this.nodeManager = requireNonNull(nodeManager, "nodeManager is null"); this.nodeSchedulerConfig = requireNonNull(nodeSchedulerConfig, "nodeSchedulerConfig is null"); this.dataDefinitionTask = ImmutableMap.copyOf(requireNonNull(dataDefinitionTask, "dataDefinitionTask is null")); }
Source:
public FirmwareUpdateConsoleCommandExtension() { super("firmware", "Manage your thing´s firmwares."); }

Target:
public FirmwareUpdateConsoleCommandExtension() { super("firmware", "Manage your things' firmwares."); }
Source:
private boolean imageStorageValidation() { if (disk.getDiskStorageType() != DiskStorageType.IMAGE || (getVm().getStatus() != VMStatus.Up && getVm().getStatus() != VMStatus.Paused)) { return true; } DiskImage diskImage = (DiskImage) disk; StorageDomain storageDomain = getStorageDomainDAO().getForStoragePool( diskImage.getStorageIds().get(0), diskImage.getStoragePoolId()); StorageDomainValidator storageDomainValidator = new StorageDomainValidator(storageDomain); return validate(storageDomainValidator.isDomainExistAndActive()); }

Target:
private boolean imageStorageValidation() { if (disk.getDiskStorageType() != DiskStorageType.IMAGE || !getVm().getStatus().isRunningOrPaused()) { return true; } DiskImage diskImage = (DiskImage) disk; StorageDomain storageDomain = getStorageDomainDAO().getForStoragePool( diskImage.getStorageIds().get(0), diskImage.getStoragePoolId()); StorageDomainValidator storageDomainValidator = new StorageDomainValidator(storageDomain); return validate(storageDomainValidator.isDomainExistAndActive()); }
Source:
public TrackingToken createTokenAt(Instant dateTime) { List<Long> results = entityManager().createQuery("SELECT MAX(e.globalIndex) FROM " + domainEventEntryEntityName() + " e WHERE e.timeStamp < :dateTime", Long.class) .setParameter("dateTime", formatInstant(dateTime)) .getResultList(); if (results.size() == 0 || results.get(0) == null) { return null; } return GapAwareTrackingToken.newInstance(results.get(0), Collections.emptySet()); }

Target:
public TrackingToken createTokenAt(Instant dateTime) { List<Long> results = entityManager().createQuery("SELECT MIN(e.globalIndex) - 1 FROM " + domainEventEntryEntityName() + " e WHERE e.timeStamp >= :dateTime", Long.class) .setParameter("dateTime", formatInstant(dateTime)) .getResultList(); return createToken(results); }
Source:
public void onlyReadsRelevantIteratorScopeConfigurations() { Map<String,String> data = new HashMap<>(); data.put(Property.TABLE_ITERATOR_SCAN_PREFIX + "foo", "50," + SummingCombiner.class.getName()); data.put(Property.TABLE_ITERATOR_SCAN_PREFIX + "foo.opt.all", "true"); data.put(Property.TABLE_ITERATOR_PREFIX + ".fakescope.bar", "50," + SummingCombiner.class.getName()); data.put(Property.TABLE_ITERATOR_SCAN_PREFIX + "foo.opt.fakeopt", "fakevalue"); AccumuloConfiguration conf = new ConfigurationCopy(data); List<IterInfo> iterators = IterConfigUtil.parseIterConf(IteratorScope.scan, new ArrayList<>(), new HashMap<>(), conf); assertEquals(1, iterators.size()); IterInfo ii = iterators.get(0); assertEquals(new IterInfo(50, SummingCombiner.class.getName(), "foo"), ii); }

Target:
public void onlyReadsRelevantIteratorScopeConfigurations() { Map<String,String> data = new HashMap<>(); data.put(Property.TABLE_ITERATOR_SCAN_PREFIX + "foo", "50," + SummingCombiner.class.getName()); data.put(Property.TABLE_ITERATOR_SCAN_PREFIX + "foo.opt.all", "true"); data.put(Property.TABLE_ITERATOR_PREFIX + ".fakescope.bar", "50," + SummingCombiner.class.getName()); data.put(Property.TABLE_ITERATOR_SCAN_PREFIX + "foo.opt.fakeopt", "fakevalue"); AccumuloConfiguration conf = new ConfigurationCopy(data); List<IterInfo> iterators = IterConfigUtil.parseIterConf(IteratorScope.scan, EMPTY_ITERS, new HashMap<>(), conf); assertEquals(1, iterators.size()); IterInfo ii = iterators.get(0); assertEquals(new IterInfo(50, SummingCombiner.class.getName(), "foo"), ii); }
Source:
public void setPan(double x, double y) { resetZoom(); translateX(x); translateY(y); }

Target:
private void setPan(double x, double y) { scale.setTx(0); scale.setTy(0); translate.setX(x * scale.getMxx()); translate.setY(y * scale.getMxx()); updateStrain(); }
Source:
public CustomizedStateProvider buildCustomizedStateProvider(HelixManager helixManager, String instanceName) { synchronized (_customizedStateProviderMap) { if (_customizedStateProviderMap.get(instanceName) != null) { return _customizedStateProviderMap.get(instanceName); } else { CustomizedStateProvider customizedStateProvider = new CustomizedStateProvider(helixManager, instanceName); _customizedStateProviderMap.put(instanceName, customizedStateProvider); return customizedStateProvider; } } }

Target:
public CustomizedStateProvider buildCustomizedStateProvider(HelixManager helixManager, String instanceName) { synchronized (_customizedStateProviderMap) { if (_customizedStateProviderMap.get(instanceName) != null) { return _customizedStateProviderMap.get(instanceName); } CustomizedStateProvider customizedStateProvider = new CustomizedStateProvider(helixManager, instanceName); _customizedStateProviderMap.put(instanceName, customizedStateProvider); return customizedStateProvider; } }
Source:
public void handleLabelsFileUpload(FileUploadEvent event) { logger.fine("entering handleUpload method."); UploadedFile file = event.getFile(); if (file != null) { InputStream uploadStream = null; try { uploadStream = file.getInputstream(); } catch (IOException ioex) { logger.log(Level.WARNING, "the file {0} failed to upload!", file.getFileName()); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "upload failure", "the file " + file.getFileName() + " failed to upload!"); FacesContext.getCurrentInstance().addMessage(null, message); return; } savedLabelsTempFile = saveTempFile(uploadStream); logger.log(Level.FINE, "{0} is successfully uploaded.", file.getFileName()); FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " is uploaded."); FacesContext.getCurrentInstance().addMessage(null, message); } }

Target:
public void handleLabelsFileUpload(FileUploadEvent event) { logger.fine("entering handleUpload method."); UploadedFile file = event.getFile(); if (file != null) { InputStream uploadStream = null; try { uploadStream = file.getInputstream(); } catch (IOException ioex) { logger.log(Level.WARNING, ioex, ()->"the file "+file.getFileName()+" failed to upload!"); List<String> args = Arrays.asList(file.getFileName()); String msg = BundleUtil.getStringFromBundle("dataset.file.uploadFailure.detailmsg", args); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, BundleUtil.getStringFromBundle("dataset.file.uploadFailure"), msg); FacesContext.getCurrentInstance().addMessage(null, message); return; } savedLabelsTempFile = saveTempFile(uploadStream); logger.fine(()->file.getFileName() + " is successfully uploaded."); List<String> args = Arrays.asList(file.getFileName()); FacesMessage message = new FacesMessage(BundleUtil.getStringFromBundle("dataset.file.upload", args)); FacesContext.getCurrentInstance().addMessage(null, message); } }
Source:
protected void executeVdsIdCommand() { final SetVdsStatusVDSCommandParameters parameters = getParameters(); if (_vdsManager != null) { final VDS vds = getVds(); if (vds.getSpmStatus() != VdsSpmStatus.None && parameters.getStatus() != VDSStatus.Up) { log.infoFormat("VDS {0} is spm and moved from up calling resetIrs.", vds.getName()); getVDSReturnValue().setSucceeded( ResourceManager .getInstance() .runVdsCommand( VDSCommandType.ResetIrs, new ResetIrsVDSCommandParameters(vds.getStoragePoolId(), vds.getId())) .getSucceeded()); if (!getVDSReturnValue().getSucceeded()) { if (getParameters().isStopSpmFailureLogged()) { AuditLogableBase base = new AuditLogableBase(); base.setVds(vds); AuditLogDirector.log(base, AuditLogType.FAILED_TO_STOP_SPM_ON_HOST); } return; } } updateVdsFromParameters(parameters, vds); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { _vdsManager.setStatus(parameters.getStatus(), vds); _vdsManager.updateDynamicData(vds.getDynamicData()); _vdsManager.updateStatisticsData(vds.getStatisticsData()); return null; } }); } else { getVDSReturnValue().setSucceeded(false); } }

Target:
protected void executeVdsIdCommand() { final SetVdsStatusVDSCommandParameters parameters = getParameters(); if (_vdsManager != null) { final VDS vds = getVds(); if (vds.getSpmStatus() != VdsSpmStatus.None && parameters.getStatus() != VDSStatus.Up) { log.infoFormat("VDS {0} is spm and moved from up calling resetIrs.", vds.getName()); getVDSReturnValue().setSucceeded( ResourceManager .getInstance() .runVdsCommand( VDSCommandType.ResetIrs, new ResetIrsVDSCommandParameters(vds.getStoragePoolId(), vds.getId())) .getSucceeded()); if (!getVDSReturnValue().getSucceeded()) { if (getParameters().isStopSpmFailureLogged()) { AuditLogableBase base = new AuditLogableBase(); base.setVds(vds); AuditLogDirector.log(base, AuditLogType.VDS_STATUS_CHANGE_FAILED_DUE_TO_STOP_SPM_FAILURE); } if (parameters.getStatus() == VDSStatus.PreparingForMaintenance) { return; } } } updateVdsFromParameters(parameters, vds); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { _vdsManager.setStatus(parameters.getStatus(), vds); _vdsManager.updateDynamicData(vds.getDynamicData()); _vdsManager.updateStatisticsData(vds.getStatisticsData()); return null; } }); } else { getVDSReturnValue().setSucceeded(false); } }
Source:
protected Long getNextBackoff() { if (currentBackoff == null) { currentBackoff = exponentialRetryAlgorithm.createFirstAttempt(); } currentBackoff = exponentialRetryAlgorithm.createNextAttempt(currentBackoff); if (!exponentialRetryAlgorithm.shouldRetry(currentBackoff)) { long timeLeftNs = currentBackoff.getGlobalSettings().getTotalTimeout().toNanos() - (clock.nanoTime() - currentBackoff.getFirstAttemptStartTimeNanos()); long timeLeftMs = TimeUnit.NANOSECONDS.toMillis(timeLeftNs); if (timeLeftMs > currentBackoff.getGlobalSettings().getInitialRetryDelay().toMillis()) { return timeLeftMs; } else { return null; } } else { return Math.min(currentBackoff.getRetryDelay().toMillis(), currentBackoff.getRandomizedRetryDelay().toMillis()); } }

Target:
protected Long getNextBackoff() { if (currentBackoff == null) { currentBackoff = exponentialRetryAlgorithm.createFirstAttempt(); } currentBackoff = exponentialRetryAlgorithm.createNextAttempt(currentBackoff); if (!exponentialRetryAlgorithm.shouldRetry(currentBackoff)) { long timeLeftNs = currentBackoff.getGlobalSettings().getTotalTimeout().toNanos() - (clock.nanoTime() - currentBackoff.getFirstAttemptStartTimeNanos()); long timeLeftMs = TimeUnit.NANOSECONDS.toMillis(timeLeftNs); if (timeLeftMs > currentBackoff.getGlobalSettings().getInitialRetryDelay().toMillis()) { return timeLeftMs; } else { return null; } } else { return currentBackoff.getRandomizedRetryDelay().toMillis(); } }
Source:
public MobileEditModePageObject clickEdit() { editButton.click(); return new MobileEditModePageObject(driver); }

Target:
public MobileEditModePageObject clickEdit() { scrollAndClick(editButton); return new MobileEditModePageObject(driver); }
Source:
public static void main(String[] args) throws IOException { File mdlRsrc = IgniteUtils.resolveIgnitePath(MODEL_PATH); if (mdlRsrc == null) throw new IllegalArgumentException("Resource not found [resource_path=" + MODEL_PATH + "]"); InfModelReader reader = new DirectoryInfModelReader(mdlRsrc.getPath()); InfModelParser<double[], Long> parser = new TensorFlowSavedModelInfModelParser<double[], Long>("serve") .withInput("Placeholder", doubles -> { float[][][] reshaped = new float[1][28][28]; for (int i = 0; i < doubles.length; i++) reshaped[0][i / 28][i % 28] = (float)doubles[i]; return Tensor.create(reshaped); }) .withOutput(Collections.singletonList("ArgMax"), collectedTensors -> { return collectedTensors.get("ArgMax").copyTo(new long[1])[0]; }); List<MnistUtils.MnistLabeledImage> images = MnistUtils.mnistAsListFromResource( MNIST_IMG_PATH, MNIST_LBL_PATH, new Random(0), 10000 ); long t0 = System.currentTimeMillis(); try (InfModel<double[], Long> locMdl = new SingleInfModelBuilder().build(reader, parser)) { for (MnistUtils.MnistLabeledImage image : images) locMdl.predict(image.getPixels()); } long t1 = System.currentTimeMillis(); System.out.println("Threaded model throughput: " + 1.0 * images.size() / ((t1 - t0) / 1000) + " req/sec"); }

Target:
public static void main(String[] args) throws IOException { File mdlRsrc = IgniteUtils.resolveIgnitePath(MODEL_PATH); if (mdlRsrc == null) throw new IllegalArgumentException("Resource not found [resource_path=" + MODEL_PATH + "]"); InfModelReader reader = new FileSystemInfModelReader(mdlRsrc.getPath()); InfModelParser<double[], Long> parser = new TensorFlowSavedModelInfModelParser<double[], Long>("serve") .withInput("Placeholder", doubles -> { float[][][] reshaped = new float[1][28][28]; for (int i = 0; i < doubles.length; i++) reshaped[0][i / 28][i % 28] = (float)doubles[i]; return Tensor.create(reshaped); }) .withOutput(Collections.singletonList("ArgMax"), collectedTensors -> { return collectedTensors.get("ArgMax").copyTo(new long[1])[0]; }); List<MnistUtils.MnistLabeledImage> images = MnistUtils.mnistAsListFromResource( MNIST_IMG_PATH, MNIST_LBL_PATH, new Random(0), 10000 ); long t0 = System.currentTimeMillis(); try (InfModel<double[], Long> locMdl = new SingleInfModelBuilder().build(reader, parser)) { for (MnistUtils.MnistLabeledImage image : images) locMdl.predict(image.getPixels()); } long t1 = System.currentTimeMillis(); System.out.println("Threaded model throughput: " + 1.0 * images.size() / ((t1 - t0) / 1000) + " req/sec"); }
Source:
void enable() { if (compactionExecutor != null) { logger.info("Compaction thread started for {}", mountPath); compactionThread = Utils.newThread(THREAD_NAME_PREFIX + mountPath, compactionExecutor, true); compactionThread.start(); try { if (!compactionExecutor.startLatch.await(1, TimeUnit.SECONDS)) { throw new IllegalStateException("Compaction thread did not start in 1 second"); } } catch (InterruptedException e) { throw new IllegalStateException(e); } } }

Target:
void enable() { if (compactionExecutor != null) { logger.info("Compaction thread started for {}", mountPath); compactionThread = Utils.newThread(THREAD_NAME_PREFIX + mountPath, compactionExecutor, true); compactionThread.start(); } }
Source:
protected TupleBatch fetchNextReady() throws DbException { final Operator child = getChild(); for (TupleBatch tb = child.nextReady(); tb != null; tb = child.nextReady()) { List<ColumnBuilder<?>> colBuilders = new ArrayList<>(tb.numColumns()); for (int i = 0; i < tb.numColumns(); ++i) { if (i != splitColIdx) { colBuilders.add(ColumnFactory.allocateColumn(tb.asColumn(i).getType())); } } final ColumnBuilder<?> splitColBuilder = ColumnFactory.allocateColumn(Type.STRING_TYPE); colBuilders.add(splitColBuilder); for (int rowIdx = 0; rowIdx < tb.numTuples(); ++rowIdx) { try { String colValue = tb.asColumn(splitColIdx).getString(rowIdx); String[] splits = pattern.split(colValue, -1); for (String segment : splits) { splitColBuilder.appendString(segment); for (int inputColIdx = 0; inputColIdx < inputColIndexToOutputColIndex.length; ++inputColIdx) { int outputColIdx = inputColIndexToOutputColIndex[inputColIdx]; if (outputColIdx != -1) { TupleUtils.copyValue(tb.asColumn(inputColIdx), rowIdx, colBuilders.get(outputColIdx)); } } } } catch (Exception e) { throw new DbException(e); } } List<Column<?>> columns = new ArrayList<>(); for (ColumnBuilder<?> colBuilder : colBuilders) { columns.add(colBuilder.build()); } return new TupleBatch(outputSchema, columns); } return null; }

Target:
protected TupleBatch fetchNextReady() throws DbException { while (!outputBuffer.hasFilledTB()) { TupleBatch inputTuples = getChild().nextReady(); if (inputTuples != null) { for (int rowIdx = 0; rowIdx < inputTuples.numTuples(); ++rowIdx) { String colValue = inputTuples.getString(splitColumnIndex, rowIdx); String[] splits = pattern.split(colValue, -1); for (String segment : splits) { outputBuffer.putString(getSchema().numColumns() - 1, segment); for (int colIdx = 0; colIdx < inputTuples.numColumns(); ++colIdx) { TupleUtils.copyValue(inputTuples.asColumn(colIdx), rowIdx, outputBuffer, colIdx); } } } } else { break; } } return outputBuffer.popAny(); }
Source:
public List getSubscriberClaims(String subscriber) throws APIManagementException { String tenantDomain = MultitenantUtils.getTenantDomain(subscriber); int tenantId = 0; List claimList = new ArrayList(); try { tenantId = getTenantId(tenantDomain); SortedMap<String, String> subscriberClaims = APIUtil.getClaims(subscriber, tenantId, ClaimsRetriever.DEFAULT_DIALECT_URI); APIManagerConfiguration configuration = getAPIManagerConfiguration(); String configuredClaims = configuration .getFirstProperty(APIConstants.API_PUBLISHER_SUBSCRIBER_CLAIMS); if (subscriberClaims != null) { for (String claimURI : configuredClaims.split(",")) { Map<String, String> claimMap = new HashMap<>(); claimMap.put(claimURI, subscriberClaims.get(claimURI)); claimList.add(claimMap); } } } catch (UserStoreException e) { throw new APIManagementException("Error while retrieving tenant id for tenant domain " + tenantDomain, e); } return claimList; }

Target:
public Map<String, String> getSubscriberClaims(String subscriber) throws APIManagementException { String tenantDomain = MultitenantUtils.getTenantDomain(subscriber); int tenantId = 0; Map<String, String> claimMap = new HashMap<>(); try { tenantId = getTenantId(tenantDomain); SortedMap<String, String> subscriberClaims = APIUtil.getClaims(subscriber, tenantId, ClaimsRetriever.DEFAULT_DIALECT_URI); APIManagerConfiguration configuration = getAPIManagerConfiguration(); String configuredClaims = configuration .getFirstProperty(APIConstants.API_PUBLISHER_SUBSCRIBER_CLAIMS); if (subscriberClaims != null) { for (String claimURI : configuredClaims.split(",")) { claimMap.put(claimURI, subscriberClaims.get(claimURI)); } } } catch (UserStoreException e) { throw new APIManagementException("Error while retrieving tenant id for tenant domain " + tenantDomain, e); } return claimMap; }
Source:
private List<String> readAllLines(File f) { List<String> list = new ArrayList(); try { BufferedReader br = new BufferedReader(new FileReader(f)); String line; while ((line = br.readLine()) != null) { list.add(line); } }catch (Exception e) { e.printStackTrace(); } return list; }

Target:
private List<String> readAllLines(File f) throws FileNotFoundException, IOException { List<String> list = new ArrayList(); BufferedReader br = new BufferedReader(new FileReader(f)); String line; while ((line = br.readLine()) != null) { list.add(line); } return list; }
Source:
private boolean check(File fingerprintFile, TaskListener listener) { try { Fingerprint fp = loadFingerprint(fingerprintFile); if (fp == null || (!fp.isAlive() && !fp.isFingerprintDeletionBlocked()) ) { listener.getLogger().println("deleting obsolete " + fingerprintFile); fingerprintFile.delete(); return true; } else { fp = getFingerprint(fp); return fp.trim(); } } catch (IOException e) { Functions.printStackTrace(e, listener.error("Failed to process " + fingerprintFile)); return false; } }

Target:
private boolean check(File fingerprintFile, TaskListener listener) { try { Fingerprint fp = loadFingerprint(fingerprintFile); if (fp == null || (!fp.isAlive() && fp.getFacetBlockingDeletion() == null) ) { listener.getLogger().println("deleting obsolete " + fingerprintFile); fingerprintFile.delete(); return true; } else { if (!fp.isAlive()) { FingerprintFacet deletionBlockerFacet = fp.getFacetBlockingDeletion(); listener.getLogger().println(deletionBlockerFacet.getClass().getName() + " created on " + DATE_CONVERTER.toString(deletionBlockerFacet.getTimestamp()) + " blocked deletion of " + fingerprintFile); } fp = getFingerprint(fp); return fp.trim(); } } catch (IOException e) { Functions.printStackTrace(e, listener.error("Failed to process " + fingerprintFile)); return false; } }
Source:
public void onEmission(TextureOffsetGeneratorComponent component, ParticleData particleData, Random random) { if (component.validOffsets.size() == 0) { return; } final int randomOffsetIndex = random.nextInt(component.validOffsets.size()); final Vector2f randomOffset = component.validOffsets.get(randomOffsetIndex); particleData.textureOffset.set(randomOffset.x(), randomOffset.y()); }

Target:
public void onEmission(TextureOffsetGeneratorComponent component, ParticleData particleData, Random random) { if (component.validOffsets.size() == 0) { return; } final int randomOffsetIndex = random.nextInt(component.validOffsets.size()); final Vector2f randomOffset = component.validOffsets.get(randomOffsetIndex); particleData.textureOffset.set(randomOffset); }
Source:
public void testManyStartNotNull() throws IOException { final CompressionCodec codec = Algorithm.GZ.getCodec(); Assert.assertNotNull(codec); ExecutorService service = Executors.newFixedThreadPool(10); for (int i = 0; i < 30; i++) { service.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { Assert.assertNotNull(Compression.Algorithm.GZ.getCodec()); return true; } }); } service.shutdown(); Assert.assertNotNull(codec); }

Target:
public void testManyStartNotNull() throws IOException, InterruptedException, ExecutionException { for (final Algorithm al : Algorithm.values()) { if (isSupported.get(al) != null && isSupported.get(al) == true) { Assert.assertTrue(al + " is not supported, but should be", al.isSupported()); final CompressionCodec codec = al.getCodec(); Assert.assertNotNull(al + " should not be null", codec); ExecutorService service = Executors.newFixedThreadPool(10); ArrayList<Future<Boolean>> results = Lists.newArrayList(); for (int i = 0; i < 30; i++) { results.add(service.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { Assert.assertNotNull(al + " should not be null", al.getCodec()); return true; } })); } service.shutdown(); Assert.assertNotNull(al + " should not be null", codec); while (!service.awaitTermination(1, TimeUnit.SECONDS)) { } for (Future<Boolean> result : results) { Assert.assertTrue(al + " resulted in a failed call to getcodec within the thread pool", result.get()); } } } }
Source:
private Set<String> parse(HttpServletRequest req) { String includedParam = req.getParameter("names[]"); if(includedParam == null) { return Collections.emptySet(); } else { return new HashSet<String>(Arrays.asList(includedParam.split(","))); } }

Target:
private Set<String> parse(HttpServletRequest req) { String[] includedParam = req.getParameterValues("names[]"); if (includedParam == null) { return Collections.emptySet(); } else { return new HashSet<String>(Arrays.asList(includedParam)); } }
Source:
public GapBuffer(String content) { this(content, 1); }

Target:
public GapBuffer(String content) { this(content, 0); }
Source:
public int getRevisionAmount() { LOG.log(Level.WARNING, "Paging is not implemented for agents, yet!"); return -1; }

Target:
public int getRevisionAmount() { LOG.log(Level.INFO, "Paging is not implemented for agents, yet!"); return -1; }
Source:
static <T> WorkProcessor<T> create(WorkProcessor.Process<T> process) { return new WorkProcessor<T>() { ProcessorState<T> state; @Override public boolean process() { if (isBlocked()) { return false; } if (isFinished()) { return true; } state = requireNonNull(process.process()); return state.type == ProcessorState.Type.RESULT || state.type == ProcessorState.Type.FINISHED; } @Override public boolean isBlocked() { return state != null && state.type == ProcessorState.Type.BLOCKED && !state.blocked.get().isDone(); } @Override public ListenableFuture<?> getBlockedFuture() { checkState(state != null && state.type == ProcessorState.Type.BLOCKED, "Must be blocked to get blocked future"); return state.blocked.get(); } @Override public boolean isFinished() { return state != null && state.type == ProcessorState.Type.FINISHED; } @Override public T getResult() { checkState(state != null && state.type == ProcessorState.Type.RESULT, "process() must return true and must not be finished"); return state.result.get(); } }; }

Target:
static <T> WorkProcessor<T> create(WorkProcessor.Process<T> process) { return new WorkProcessor<T>() { ProcessorState<T> state; @Override public boolean process() { if (isBlocked()) { return false; } if (isFinished()) { return true; } state = requireNonNull(process.process()); checkState(state.getType() != NEEDS_MORE_DATA, "Unexpected state: NEEDS_MORE_DATA"); return state.getType() == RESULT || state.getType() == FINISHED; } @Override public boolean isBlocked() { return state != null && state.getType() == BLOCKED && !state.getBlocked().get().isDone(); } @Override public ListenableFuture<?> getBlockedFuture() { checkState(state != null && state.getType() == BLOCKED, "Must be blocked to get blocked future"); return state.getBlocked().get(); } @Override public boolean isFinished() { return state != null && state.getType() == FINISHED; } @Override public T getResult() { checkState(state != null && state.getType() == RESULT, "process() must return true and must not be finished"); return state.getResult().get(); } }; }
Source:
private void returnToSyncStateFromOperationHistory() { IProgressMonitor pm = new NullProgressMonitor(); try { IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory(); IUndoContext undoCtx = getUndoContext(); while (operationHistory != null && operationHistory.canUndo(undoCtx) && session.getStatus() != SessionStatus.SYNC) { IUndoableOperation toUndo = operationHistory.getUndoOperation(undoCtx); operationHistory.undoOperation(toUndo, new NullProgressMonitor(), null); if (marker == toUndo) { break; } } setResourcesBackToSync(); } catch (ExecutionException e) { reloadTheResources(); String sessionLabel = SiriusEditPlugin.getPlugin().getUiCallback().getSessionNameToDisplayWhileSaving(session); SiriusPlugin.getDefault().warning(sessionLabel + " modified resources were reloaded. An error occurs while attempting to cancel all modifications.", e); } }

Target:
private void returnToSyncStateFromOperationHistory() { try { IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory(); IUndoContext undoCtx = getUndoContext(); while (operationHistory != null && operationHistory.canUndo(undoCtx) && session.getStatus() != SessionStatus.SYNC) { IUndoableOperation toUndo = operationHistory.getUndoOperation(undoCtx); operationHistory.undoOperation(toUndo, new NullProgressMonitor(), null); if (marker == toUndo) { break; } } setResourcesBackToSync(); } catch (ExecutionException e) { reloadTheResources(); String sessionLabel = SiriusEditPlugin.getPlugin().getUiCallback().getSessionNameToDisplayWhileSaving(session); SiriusPlugin.getDefault().warning(sessionLabel + " modified resources were reloaded. An error occurs while attempting to cancel all modifications.", e); } }
Source:
public void timerExpired(Object callbackData) { State newState = state; switch (state) { case STATE_DOORS_CLOSED: localDoorMotor.set(DoorCommand.STOP); mDoorMotor.setDoorCommand(DoorCommand.STOP); if ((mAtFloors.getCurrentFloor() == mDesiredFloor.getFloor() && ((mDriveSpeed.getSpeed()-0.0)<EPSILON || mDriveSpeed.getDirection()==Direction.STOP)) || (mCarWeight.getValue() >= Elevator.MaxCarCapacity && mDoorOpenedFront.getBothOpened() == false && mDoorOpenedBack.getBothOpened() == false)) { newState = State.STATE_DOORS_OPENING; } else { newState = state; } break; case STATE_DOORS_OPENING: localDoorMotor.set(DoorCommand.OPEN); mDoorMotor.setDoorCommand(DoorCommand.OPEN); countdown = dwell; if (mDoorOpenedFront.getBothOpened() && mDoorOpenedBack.getBothOpened()) { newState = State.STATE_DOORS_OPENED; } else { newState = state; } break; case STATE_DOORS_OPENED: localDoorMotor.set(DoorCommand.STOP); mDoorMotor.setDoorCommand(DoorCommand.STOP); countdown = SimTime.subtract(countdown, period); if (countdown.isLessThanOrEqual(SimTime.ZERO)) { newState = State.STATE_DOORS_NUDGE; } else { newState = state; } break; case STATE_DOORS_NUDGE: localDoorMotor.set(DoorCommand.NUDGE); mDoorMotor.setDoorCommand(DoorCommand.NUDGE); if (mDoorClosedFront.getBothClosed() && mDoorClosedBack.getBothClosed()) { newState = State.STATE_DOORS_CLOSED; } else { newState = state; } break; default: throw new RuntimeException("State " + state + " was not recognized."); } }

Target:
public void timerExpired(Object callbackData) { State newState = state; switch (state) { case STATE_DOORS_CLOSED: localDoorMotor.set(DoorCommand.STOP); mDoorMotor.setDoorCommand(DoorCommand.STOP); if ((mAtFloors.getCurrentFloor() == mDesiredFloor.getFloor() && ((mDriveSpeed.getSpeed()==Speed.STOP) || mDriveSpeed.getDirection()==Direction.STOP)) || (mCarWeight.getValue() >= Elevator.MaxCarCapacity && mDoorOpenedFront.getBothOpened() == false && mDoorOpenedBack.getBothOpened() == false)) { newState = State.STATE_DOORS_OPENING; } else { newState = state; } break; case STATE_DOORS_OPENING: localDoorMotor.set(DoorCommand.OPEN); mDoorMotor.setDoorCommand(DoorCommand.OPEN); countdown = dwell; if (mDoorOpenedFront.getBothOpened() && mDoorOpenedBack.getBothOpened()) { newState = State.STATE_DOORS_OPENED; } else { newState = state; } break; case STATE_DOORS_OPENED: localDoorMotor.set(DoorCommand.STOP); mDoorMotor.setDoorCommand(DoorCommand.STOP); countdown = SimTime.subtract(countdown, period); if (countdown.isLessThanOrEqual(SimTime.ZERO)) { newState = State.STATE_DOORS_NUDGE; } else { newState = state; } break; case STATE_DOORS_NUDGE: localDoorMotor.set(DoorCommand.NUDGE); mDoorMotor.setDoorCommand(DoorCommand.NUDGE); if (mDoorClosedFront.getBothClosed() && mDoorClosedBack.getBothClosed()) { newState = State.STATE_DOORS_CLOSED; } else { newState = state; } break; default: throw new RuntimeException("State " + state + " was not recognized."); } }
Source:
private ValueSnak getValueSnak(JSONArray jsonValueSnak) throws JSONException { ValueSnak result; int intId = jsonValueSnak.getInt(1); PropertyIdValue propertyId = (PropertyIdValue) this.getEntityId(intId, DocumentType.PROPERTY); String valueString = jsonValueSnak.getString(2); Value value; switch (valueString) { case "time": value = this.getTimeValue(jsonValueSnak.getJSONObject(3)); break; case "wikibase-entityid": value = this.getEntityIdValue(jsonValueSnak.getJSONObject(3)); break; case "string": value = this.getStringIdValue(jsonValueSnak.getString(3)); break; case "globecoordinate": value = this.getGlobeCoordinatesValue(jsonValueSnak .getJSONObject(3)); break; case "quantity": value = this.getQuantityValue(jsonValueSnak.getJSONObject(3)); break; default: throw new JSONException("Unknown value type " + valueString + "in value snak JSON"); } result = this.factory.getValueSnak(propertyId, value); return result; }

Target:
private ValueSnak getValueSnak(JSONArray jsonValueSnak) throws JSONException { int intPropertyId = jsonValueSnak.getInt(1); PropertyIdValue propertyIdValue = this .getPropertyIdValue(PREFIX_PROPERTY + intPropertyId); String valueType = jsonValueSnak.getString(2); Value value; switch (valueType) { case "time": value = this.getTimeValue(jsonValueSnak.getJSONObject(3)); break; case "wikibase-entityid": value = this.getEntityIdValue(jsonValueSnak.getJSONObject(3)); break; case "string": value = this.getStringValue(jsonValueSnak.getString(3)); break; case "globecoordinate": value = this.getGlobeCoordinatesValue(jsonValueSnak .getJSONObject(3)); break; case "quantity": value = this.getQuantityValue(jsonValueSnak.getJSONObject(3)); break; default: throw new JSONException("Unknown value type " + valueType + " in value snak JSON"); } return this.factory.getValueSnak(propertyIdValue, value); }
Source:
private void maybeRemapOrphanedAllocation( final AllocationID allocationIdOfRequest, final AllocationID allocationIdOfSlot) { final AllocationID orphanedAllocationId = allocationIdOfRequest.equals(allocationIdOfSlot) ? null : allocationIdOfRequest; if (orphanedAllocationId != null) { final SlotRequestId requestIdOfAllocatedSlot = pendingRequests.getKeyA(allocationIdOfSlot); if (requestIdOfAllocatedSlot != null) { final PendingRequest requestOfAllocatedSlot = pendingRequests.getByKeyA(requestIdOfAllocatedSlot); requestOfAllocatedSlot.setAllocationId(orphanedAllocationId); pendingRequests.put(requestIdOfAllocatedSlot, orphanedAllocationId, requestOfAllocatedSlot); } else { resourceManagerGateway.cancelSlotRequest(orphanedAllocationId); } } }

Target:
private void maybeRemapOrphanedAllocation( final AllocationID allocationIdOfRequest, final AllocationID allocationIdOfSlot) { if (!allocationIdOfRequest.equals(allocationIdOfSlot)) { final SlotRequestId requestIdOfAllocatedSlot = pendingRequests.getKeyAByKeyB(allocationIdOfSlot); if (requestIdOfAllocatedSlot != null) { final PendingRequest requestOfAllocatedSlot = pendingRequests.getValueByKeyA(requestIdOfAllocatedSlot); requestOfAllocatedSlot.setAllocationId(allocationIdOfRequest); pendingRequests.put(requestIdOfAllocatedSlot, allocationIdOfRequest, requestOfAllocatedSlot); } else { resourceManagerGateway.cancelSlotRequest(allocationIdOfRequest); } } }
Source:
private ClassifiedClasses classes2singletons(final Application application, final BeanManager beanManager) { final ClassifiedClasses classified = new ClassifiedClasses(); Set<Class<?>> classes = application.getClasses(); if (!classes.isEmpty()) { classified.addProviders(loadProviders(beanManager, classes)); classified.addFeatures(loadFeatures(beanManager, classes)); for (final Bean< ? > bean: serviceBeans) { if (classes.contains(bean.getBeanClass())) { final CdiResourceProvider provider = new CdiResourceProvider(beanManager, bean); if (provider.isSingleton() && Dependent.class == bean.getScope()) { disposableResourceProviders.add(provider); } classified.addResourceProvider(provider); } } } return classified; }

Target:
private ClassifiedClasses classes2singletons(final Application application, final BeanManager beanManager) { final ClassifiedClasses classified = new ClassifiedClasses(); Set<Class<?>> classes = application.getClasses(); if (!classes.isEmpty()) { classified.addProviders(loadProviders(beanManager, classes)); classified.addFeatures(loadFeatures(beanManager, classes)); for (final Bean< ? > bean: serviceBeans) { if (classes.contains(bean.getBeanClass())) { final ResourceProvider resourceProvider; if (isCxfSingleton(beanManager, bean)) { final Lifecycle lifecycle = new Lifecycle(beanManager, bean); resourceProvider = new SingletonResourceProvider(lifecycle, bean.getBeanClass()); if (Dependent.class == bean.getScope()) { disposableLifecycles.add(lifecycle); } } else { resourceProvider = new PerRequestResourceProvider( () -> new Lifecycle(beanManager, bean), bean.getBeanClass()); } classified.addResourceProvider(resourceProvider); } } } return classified; }
Source:
public ODatabaseExport(final ODatabaseDocumentInternal iDatabase, final String iFileName, final OCommandOutputListener iListener) throws IOException { super(iDatabase, iFileName, iListener); if (fileName == null) throw new IllegalArgumentException("file name missing"); if (!fileName.endsWith(".gz")) { fileName += ".gz"; } final File f = new File(fileName); if (f.getParentFile() != null) f.getParentFile().mkdirs(); if (f.exists()) f.delete(); this.tempFileName = fileName + ".tmp"; final File tempFile = new File(tempFileName); if (tempFile.getParentFile() != null) tempFile.getParentFile().mkdirs(); if (tempFile.exists()) tempFile.delete(); final GZIPOutputStream gzipOS = new GZIPOutputStream(new FileOutputStream(tempFileName), compressionBuffer) { { def.setLevel(compressionLevel); } }; writer = new OJSONWriter(new OutputStreamWriter(gzipOS)); writer.beginObject(); }

Target:
public ODatabaseExport(final ODatabaseDocumentInternal iDatabase, final String iFileName, final OCommandOutputListener iListener) throws IOException { super(iDatabase, iFileName, iListener); if (fileName == null) throw new IllegalArgumentException("file name missing"); if (!fileName.endsWith(".gz")) { fileName += ".gz"; } OFileUtils.prepareForFileCreationOrReplacement(Paths.get(fileName), this, "exporting"); this.tempFileName = fileName + ".tmp"; OFileUtils.prepareForFileCreationOrReplacement(Paths.get(tempFileName), this, "exporting"); final GZIPOutputStream gzipOS = new GZIPOutputStream(new FileOutputStream(tempFileName), compressionBuffer) { { def.setLevel(compressionLevel); } }; writer = new OJSONWriter(new OutputStreamWriter(gzipOS)); writer.beginObject(); }
Source:
public double priceDerivativeForward(double strike, PutCall putCall) { double priceDerivative; if (strike <= cutOffStrike) { ValueDerivatives volatilityA = sabrFunction.getVolatilityAdjoint(forward, strike, timeToExpiry, sabrData); BlackFunctionData dataBlack = BlackFunctionData.of(forward, 1d, volatilityA.getValue()); EuropeanVanillaOption option = EuropeanVanillaOption.of(strike, timeToExpiry, putCall); ValueDerivatives pA = BLACK_FUNCTION.getPriceAdjoint(option, dataBlack); priceDerivative = pA.getDerivative(0) + pA.getDerivative(1) * volatilityA.getDerivative(0); } else { if (!parameterDerivativeForwardComputed) { parameterDerivativeForward = computesParametersDerivativeForward(); parameterDerivativeForwardComputed = true; } double f = extrapolation(strike); double fDa = f; double fDb = f / strike; double fDc = fDb / strike; priceDerivative = fDa * parameterDerivativeForward[0] + fDb * parameterDerivativeForward[1] + fDc * parameterDerivativeForward[2]; if (putCall.isPut()) { priceDerivative -= 1; } } return priceDerivative; }

Target:
public double priceDerivativeForward(double strike, PutCall putCall) { if (strike <= cutOffStrike) { ValueDerivatives volatilityA = sabrFunction.getVolatilityAdjoint(forward, strike, timeToExpiry, sabrData); BlackFunctionData dataBlack = BlackFunctionData.of(forward, 1d, volatilityA.getValue()); EuropeanVanillaOption option = EuropeanVanillaOption.of(strike, timeToExpiry, putCall); ValueDerivatives pA = BLACK_FUNCTION.getPriceAdjoint(option, dataBlack); return pA.getDerivative(0) + pA.getDerivative(1) * volatilityA.getDerivative(0); } if (parameterDerivativeForward == null) { parameterDerivativeForward = computesParametersDerivativeForward(); } double f = extrapolation(strike); double fDa = f; double fDb = f / strike; double fDc = fDb / strike; double priceDerivative = fDa * parameterDerivativeForward[0] + fDb * parameterDerivativeForward[1] + fDc * parameterDerivativeForward[2]; if (putCall.isPut()) { priceDerivative -= 1; } return priceDerivative; }
Source:
public HmRsHeader(final Matcher<String> hdrm, final Matcher<Iterable<String>> vlm) { super(); this.headerm = hdrm; this.valuem = vlm; }

Target:
public HmRsHeader(final Matcher<String> hdrm, final Matcher<Iterable<String>> vlm) { super(); this.header = hdrm; this.value = vlm; }
Source:
public BigintValues(long[] values, boolean nullAllowed) { super(nullAllowed); requireNonNull(values, "values is null"); checkArgument(values.length > 1, "values must contain at least 2 entries"); this.originalValues = values; this.size = Integer.highestOneBit(values.length * 3); this.longs = new long[size]; Arrays.fill(longs, EMPTY_MARKER); for (long value : values) { if (value == EMPTY_MARKER) { containsEmptyMarker = true; } else { int position = (int) ((value * M) & (size - 1)); for (int i = position; i < position + size; i++) { int index = i & (size - 1); if (longs[index] == EMPTY_MARKER) { longs[index] = value; break; } } } } }

Target:
private BigintValues(long[] values, boolean nullAllowed) { super(nullAllowed); requireNonNull(values, "values is null"); checkArgument(values.length > 1, "values must contain at least 2 entries"); this.values = values; this.size = Integer.highestOneBit(values.length * 3); this.hashTable = new long[size]; Arrays.fill(hashTable, EMPTY_MARKER); for (long value : values) { if (value == EMPTY_MARKER) { containsEmptyMarker = true; } else { int position = (int) ((value * M) & (size - 1)); for (int i = position; i < position + size; i++) { int index = i & (size - 1); if (hashTable[index] == EMPTY_MARKER) { hashTable[index] = value; break; } } } } }
Source:
private Timestamp(BigDecimal millis, Integer localOffset) { if (millis == null) throw new NullPointerException("millis is null"); if(millis.compareTo(MINIMUM_ALLOWED_FRACTIONAL_MILLIS) < 0 || millis.compareTo(MAXIMUM_ALLOWED_FRACTIONAL_MILLIS) > 0) { throw new IllegalArgumentException("millis: " + millis + " is outside of valid the range: from " + MINIMUM_ALLOWED_FRACTIONAL_MILLIS + " to " + MAXIMUM_ALLOWED_FRACTIONAL_MILLIS + " both inclusive"); } if(Math.abs(millis.scale()) >= MAXIMUM_ALLOWED_MILLIS_SCALE) { throw new IllegalArgumentException("millis: " + millis + " has a scale outside the valid range:" + "from" + -MAXIMUM_ALLOWED_MILLIS_SCALE + "to" + MAXIMUM_ALLOWED_MILLIS_SCALE + "both inclusive"); } long ms = millis.longValue(); set_fields_from_millis(ms); this._precision = Precision.SECOND; int scale = millis.scale(); if (scale <= -3) { this._fraction = null; } else { BigDecimal secs = millis.movePointLeft(3); BigDecimal secsDown = secs.setScale(0, RoundingMode.FLOOR); this._fraction = secs.subtract(secsDown); } this._offset = localOffset; }

Target:
private Timestamp(BigDecimal millis, Integer localOffset) { if (millis == null) throw new NullPointerException("millis is null"); if(millis.compareTo(MINIMUM_ALLOWED_FRACTIONAL_MILLIS) < 0 || FRACTIONAL_MILLIS_UPPER_BOUND.compareTo(millis) < 0) { throw new IllegalArgumentException("millis: " + millis + " is outside of valid the range: from " + MINIMUM_ALLOWED_FRACTIONAL_MILLIS + " (0001T)" + ", inclusive, to " + FRACTIONAL_MILLIS_UPPER_BOUND + " (10000T)" + " , exclusive"); } long ms = isIntegralZero(millis) ? 0 : millis.longValue(); set_fields_from_millis(ms); this._precision = Precision.SECOND; int scale = millis.scale(); if (scale <= -3) { this._fraction = null; } else { BigDecimal secs = millis.movePointLeft(3); BigDecimal secsDown = isIntegralZero(secs) ? BigDecimal.ZERO : secs.setScale(0, BigDecimal.ROUND_FLOOR); this._fraction = secs.subtract(secsDown); } this._offset = localOffset; }
Source:
private static ImmutableList<PaymentEvent> createFxResetEvents( List<RatePaymentPeriod> payPeriods, LocalDate initialExchangeDate) { ImmutableList.Builder<PaymentEvent> events = ImmutableList.builder(); for (int i = 0; i < payPeriods.size(); i++) { RatePaymentPeriod period = payPeriods.get(i); LocalDate startPaymentDate = i == 0 ? initialExchangeDate : payPeriods.get(i - 1).getPaymentDate(); if (period.getFxReset().isPresent()) { FxReset fxReset = period.getFxReset().get(); events.add(FxResetNotionalExchange.builder() .paymentDate(startPaymentDate) .referenceCurrency(fxReset.getReferenceCurrency()) .notional(-period.getNotional()) .index(fxReset.getIndex()) .fixingDate(fxReset.getFixingDate()) .build()); events.add(FxResetNotionalExchange.builder() .paymentDate(period.getPaymentDate()) .referenceCurrency(fxReset.getReferenceCurrency()) .notional(period.getNotional()) .index(fxReset.getIndex()) .fixingDate(fxReset.getFixingDate()) .build()); } else { events.add(NotionalExchange.builder() .paymentDate(startPaymentDate) .paymentAmount(CurrencyAmount.of(period.getCurrency(), -period.getNotional())) .build()); events.add(NotionalExchange.builder() .paymentDate(period.getPaymentDate()) .paymentAmount(CurrencyAmount.of(period.getCurrency(), period.getNotional())) .build()); } } return events.build(); }

Target:
private static ImmutableList<PaymentEvent> createFxResetEvents( List<RatePaymentPeriod> payPeriods, LocalDate initialExchangeDate) { ImmutableList.Builder<PaymentEvent> events = ImmutableList.builder(); for (int i = 0; i < payPeriods.size(); i++) { RatePaymentPeriod period = payPeriods.get(i); LocalDate startPaymentDate = (i == 0 ? initialExchangeDate : payPeriods.get(i - 1).getPaymentDate()); if (period.getFxReset().isPresent()) { FxReset fxReset = period.getFxReset().get(); events.add(FxResetNotionalExchange.builder() .paymentDate(startPaymentDate) .referenceCurrency(fxReset.getReferenceCurrency()) .notional(-period.getNotional()) .index(fxReset.getIndex()) .fixingDate(fxReset.getFixingDate()) .build()); events.add(FxResetNotionalExchange.builder() .paymentDate(period.getPaymentDate()) .referenceCurrency(fxReset.getReferenceCurrency()) .notional(period.getNotional()) .index(fxReset.getIndex()) .fixingDate(fxReset.getFixingDate()) .build()); } else { events.add(NotionalExchange.builder() .paymentDate(startPaymentDate) .paymentAmount(CurrencyAmount.of(period.getCurrency(), -period.getNotional())) .build()); events.add(NotionalExchange.builder() .paymentDate(period.getPaymentDate()) .paymentAmount(CurrencyAmount.of(period.getCurrency(), period.getNotional())) .build()); } } return events.build(); }