auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void updateTableStatistics(String databaseName, String tableName, Function<PartitionStatistics, PartitionStatistics> update) { PartitionStatistics currentStatistics = getTableStatistics(databaseName, tableName); PartitionStatistics updatedStatistics = update.apply(currentStatistics); if (!updatedStatistics.getColumnStatistics().isEmpty()) { throw new PrestoException(NOT_SUPPORTED, "glue metastore does not support column level statistics"); } Table table = getTableOrElseThrow(databaseName, tableName); try { TableInput tableInput = GlueInputConverter.convertTable(table); tableInput.setParameters(updateStatisticParameters(table.getParameters(), updatedStatistics.getBasicStatistics())); glueClient.updateTable(new UpdateTableRequest() .withDatabaseName(databaseName) .withTableInput(tableInput)); } catch (EntityNotFoundException e) { throw new TableNotFoundException(new SchemaTableName(databaseName, tableName)); } catch (AmazonServiceException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }

Target:
public void updateTableStatistics(String databaseName, String tableName, Function<PartitionStatistics, PartitionStatistics> update) { PartitionStatistics currentStatistics = getTableStatistics(databaseName, tableName); PartitionStatistics updatedStatistics = update.apply(currentStatistics); if (!updatedStatistics.getColumnStatistics().isEmpty()) { throw new PrestoException(NOT_SUPPORTED, "Glue metastore does not support column level statistics"); } Table table = getTableOrElseThrow(databaseName, tableName); try { TableInput tableInput = GlueInputConverter.convertTable(table); tableInput.setParameters(updateStatisticsParameters(table.getParameters(), updatedStatistics.getBasicStatistics())); glueClient.updateTable(new UpdateTableRequest() .withDatabaseName(databaseName) .withTableInput(tableInput)); } catch (EntityNotFoundException e) { throw new TableNotFoundException(new SchemaTableName(databaseName, tableName)); } catch (AmazonServiceException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }
Source:
public void shouldFailOnMultipleConcurrentSaves() throws Exception { final String key = "shouldFailOnMultipleConcurrentSaves"; final AtomicLong counter = new AtomicLong(); final AtomicLong optimisticLockCounter = new AtomicLong(); ExecutorService pool = Executors.newFixedThreadPool(5); Callable<Void> task = new Callable<Void>() { @Override public Void call() throws Exception { long counterValue = counter.incrementAndGet(); String data = "value-" + counterValue; VersionedData messageData = new VersionedData(key, data); try { versionedDataRepository.save(messageData); } catch (OptimisticLockingFailureException e) { optimisticLockCounter.incrementAndGet(); } return null; } }; Collection<Callable<Void>> tasks = Collections.nCopies(5, task); List<Future<Void>> futures = pool.invokeAll(tasks); for (Future future : futures) { future.get(5, TimeUnit.SECONDS); } versionedDataRepository.delete(key); assertEquals(4, optimisticLockCounter.intValue()); }

Target:
public void shouldFailOnMultipleConcurrentSaves() throws Exception { final String key = testName.getMethodName(); remove(key); final AtomicLong counter = new AtomicLong(); final AtomicLong optimisticLockCounter = new AtomicLong(); Callable<Void> task = new Callable<Void>() { @Override public Void call() throws Exception { long counterValue = counter.incrementAndGet(); VersionedData messageData = new VersionedData(key, "value-" + counterValue); try { versionedDataRepository.save(messageData); } catch (OptimisticLockingFailureException e) { optimisticLockCounter.incrementAndGet(); } return null; } }; AsyncUtils.executeConcurrently(5, task); assertEquals(4, optimisticLockCounter.intValue()); }
Source:
public byte[] readFileToByteArray(File file) throws IOException { InputStream in = null; try { in = org.apache.commons.io.FileUtils.openInputStream(file); return org.apache.commons.io.IOUtils.toByteArray(in); } finally { org.apache.commons.io.IOUtils.closeQuietly(in); } }

Target:
public byte[] readFileToByteArray(File file) throws IOException { InputStream in = org.apache.commons.io.FileUtils.openInputStream(file); try { return org.apache.commons.io.IOUtils.toByteArray(in); } finally { in.close(); } }
Source:
private static String checkName(String origName) { String newName = BaseNoGui.sanitizeName(origName); if (!newName.equals(origName)) { String msg = tr("The sketch name had to be modified. Sketch names can only consist of\n" + "ASCII characters and numbers, no spaces, and be less than 64 characters long."); System.out.println(msg); } return newName; }

Target:
private static String checkName(String origName) { String newName = BaseNoGui.sanitizeName(origName); if (!newName.equals(origName)) { String msg = tr("The sketch name had to be modified.\n" + "Sketch names must start with a letter or number, followed by letters,\n" + "numbers, dashes, dots and underscores. Maximum length is 63 characters."); System.out.println(msg); } return newName; }
Source:
public void onMatchmakerSearchStopped() { if (inMatchmakerQueue.get()) { fafService.stopSearchMatchmaker(); inMatchmakerQueue.set(false); } }

Target:
public void onMatchmakerSearchStopped() { if (inMatchmakerQueue.get()) { fafService.stopSearchMatchmaker(); inMatchmakerQueue.set(false); log.debug("Matchmaker search stopped"); } else { log.debug("Matchmaker search has already been stopped, ignoring call"); } }
Source:
public void testLockedStreamBlocked() throws InterruptedException, TimeoutException, BrokenBarrierException, ExecutionException { for (int i = 0; i < 10; i++) { cache.put(i, "value" + i); } CyclicBarrier barrier = new CyclicBarrier(2); int key = 4; Future<Object> putFuture = fork(() -> { TransactionManager tm = cache.getAdvancedCache().getTransactionManager(); try { tm.begin(); try { Object prev = cache.put(key, "value" + key + "-new"); barrier.await(10, TimeUnit.SECONDS); barrier.await(10, TimeUnit.SECONDS); tm.commit(); return prev; } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) { tm.rollback(); } } } catch (NotSupportedException | SystemException e) { throw new RuntimeException(e); } }); barrier.await(10, TimeUnit.SECONDS); LockedStream<Object, Object> stream = cache.getAdvancedCache().lockedStream(); Future<?> forEachFuture = fork(() -> stream.filter(e -> e.getKey().equals(key)).forEach((c, e) -> assertEquals("value" + key + "-new", c.put(e.getKey(), String.valueOf(e.getValue() + "-other"))))); try { forEachFuture.get(50, TimeUnit.MILLISECONDS); fail("Test should have thrown TimeoutException"); } catch (TimeoutException e) { } barrier.await(10, TimeUnit.SECONDS); forEachFuture.get(10, TimeUnit.MINUTES); assertEquals("value" + key, putFuture.get(10, TimeUnit.SECONDS)); assertEquals("value" + key + "-new-other", cache.get(key)); LockManager lockManager = cache.getAdvancedCache().getComponentRegistry().getComponent(LockManager.class); assertEquals(0, lockManager.getNumberOfLocksHeld()); }

Target:
public void testLockedStreamBlocked() throws InterruptedException, TimeoutException, BrokenBarrierException, ExecutionException { for (int i = 0; i < 10; i++) { cache.put(i, "value" + i); } CyclicBarrier barrier = new CyclicBarrier(2); int key = 4; Future<Object> putFuture = fork(() -> TestingUtil.withTx(cache.getAdvancedCache().getTransactionManager(), () -> { Object prev = cache.put(key, "value" + key + "-new"); barrier.await(10, TimeUnit.SECONDS); barrier.await(10, TimeUnit.SECONDS); return prev; })); barrier.await(10, TimeUnit.SECONDS); LockedStream<Object, Object> stream = cache.getAdvancedCache().lockedStream(); Future<?> forEachFuture = fork(() -> stream.filter(e -> e.getKey().equals(key)).forEach((c, e) -> assertEquals("value" + key + "-new", c.put(e.getKey(), String.valueOf(e.getValue() + "-other"))))); Exceptions.expectException(TimeoutException.class, () -> forEachFuture.get(50, TimeUnit.MILLISECONDS)); barrier.await(10, TimeUnit.SECONDS); forEachFuture.get(10, TimeUnit.MINUTES); assertEquals("value" + key, putFuture.get(10, TimeUnit.SECONDS)); assertEquals("value" + key + "-new-other", cache.get(key)); LockManager lockManager = cache.getAdvancedCache().getComponentRegistry().getComponent(LockManager.class); assertEquals(0, lockManager.getNumberOfLocksHeld()); }
Source:
private void createListOfClustersByProvider(List<Cluster> clusters) { listOfClustersByProvider = new HashMap<>(); clusters.stream() .map(Cluster::getDefaultNetworkProviderId) .distinct() .forEach(providerId -> listOfClustersByProvider.put(providerId, getClusterIdsFilteredByProviderId(clusters, providerId))); }

Target:
private void createListOfClustersByProvider(List<Cluster> clusters) { listOfClustersByProvider = clusters.stream() .map(Cluster::getDefaultNetworkProviderId) .distinct() .collect(Collectors.toMap(providerId -> providerId, providerId -> getClusterIdsFilteredByProviderId(clusters, providerId))); }
Source:
public void testIsSymlink_onWindows_junction() throws Exception { Assume.assumeTrue(Functions.isWindows()); tmp.newFolder("targetDir"); File d = tmp.newFolder("dir"); Process p = new ProcessBuilder() .directory(d) .command("cmd.exe", "/C", "mklink /J junction ..\\targetDir") .start(); assertThat("unable to create junction", p.waitFor(), is(0)); assertTrue(Util.isSymlink(new File(d, "junction"))); }

Target:
public void testIsSymlink_onWindows_junction() throws Exception { Assume.assumeTrue("Uses Windows-specific features", Functions.isWindows()); tmp.newFolder("targetDir"); File d = tmp.newFolder("dir"); Process p = new ProcessBuilder() .directory(d) .command("cmd.exe", "/C", "mklink /J junction ..\\targetDir") .start(); Assume.assumeThat("unable to create junction", p.waitFor(), is(0)); assertTrue(Util.isSymlink(new File(d, "junction"))); }
Source:
public String getUsage() { StringBuilder help = new StringBuilder(String.format("Options:%n")); for(String arg : getUsageArguments()) { ParserArgument argument = this.arguments.get(arg); help.append( String.format( " --%s%n %s%n%n", arg + (argument.getType() != ArgumentType.no_argument ? "=[" + argument.getMetavar() + "]" : ""), argument.getHelp() ) ); } return String.format("%1$s%n%2$s%n%n%3$s%4$s%n", properties.getProperty( prefix + ".help.usage", (String)defaultProperties.get("help.usage") ), properties.getProperty( prefix + ".help.header", (String) defaultProperties.get("help.header") ), help.toString(), properties.getProperty( prefix + ".help.footer", (String) defaultProperties.get("help.footer") ) ); }

Target:
public String getUsage() { StringBuilder help = new StringBuilder(String.format("Options:%n")); for(String arg : getUsageArguments()) { ParserArgument argument = this.arguments.get(arg); help.append( String.format( " --%s%n" + " %s%n" + "%n", arg + (argument.getType() != ArgumentType.no_argument ? "=[" + argument.getMetavar() + "]" : ""), argument.getHelp() ) ); } return String.format("%1$s%n%2$s%n%n%3$s%4$s%n", properties.getProperty( prefix + ".help.usage", (String)defaultProperties.get("help.usage") ), properties.getProperty( prefix + ".help.header", (String) defaultProperties.get("help.header") ), help.toString(), properties.getProperty( prefix + ".help.footer", (String) defaultProperties.get("help.footer") ) ); }
Source:
public <T> T get(final String key, final Class<T> clazz) { @SuppressWarnings("unchecked") final T value = (T) properties.get(key); return value; }

Target:
public <T> T get(final String key, final Class<T> clazz) { return (T) properties.get(key); }
Source:
private MongoCodeListEntryImportJob(ProcessContext process) { super(fileParameter, ignoreEmptyParameter, importModeParameter, MongoCodeListEntry.class, getDictionary(), process); codeList = (MongoCodeList) process.require(codeListParameter); }

Target:
private MongoCodeListEntryImportJob(ProcessContext process) { super(fileParameter, ignoreEmptyParameter, importModeParameter, MongoCodeListEntry.class, getDictionary(), process); codeList = process.require(codeListParameter); }
Source:
public int compareTo(RealmInteger o) { long otherVal = o.val; return (val == otherVal) ? 0 : ((val > otherVal) ? 1 : -1); }

Target:
public int compareTo(RealmInteger o) { long otherValue = o.value; return (value == otherValue) ? 0 : ((value > otherValue) ? 1 : -1); }
Source:
public Object[] factory() { return new Object[] { new WriteSkewGetGroupKeysTest(TestCacheFactory.PRIMARY_OWNER).totalOrder(false).isolationLevel(IsolationLevel.REPEATABLE_READ), new WriteSkewGetGroupKeysTest(TestCacheFactory.PRIMARY_OWNER).totalOrder(true).isolationLevel(IsolationLevel.REPEATABLE_READ), new WriteSkewGetGroupKeysTest(TestCacheFactory.BACKUP_OWNER).totalOrder(false).isolationLevel(IsolationLevel.REPEATABLE_READ), new WriteSkewGetGroupKeysTest(TestCacheFactory.BACKUP_OWNER).totalOrder(true).isolationLevel(IsolationLevel.REPEATABLE_READ), new WriteSkewGetGroupKeysTest(TestCacheFactory.NON_OWNER).totalOrder(false).isolationLevel(IsolationLevel.REPEATABLE_READ), new WriteSkewGetGroupKeysTest(TestCacheFactory.NON_OWNER).totalOrder(true).isolationLevel(IsolationLevel.REPEATABLE_READ), }; }

Target:
public Object[] factory() { return new Object[] { new WriteSkewGetGroupKeysTest(TestCacheFactory.PRIMARY_OWNER).totalOrder(false), new WriteSkewGetGroupKeysTest(TestCacheFactory.PRIMARY_OWNER).totalOrder(true), new WriteSkewGetGroupKeysTest(TestCacheFactory.BACKUP_OWNER).totalOrder(false), new WriteSkewGetGroupKeysTest(TestCacheFactory.BACKUP_OWNER).totalOrder(true), new WriteSkewGetGroupKeysTest(TestCacheFactory.NON_OWNER).totalOrder(false), new WriteSkewGetGroupKeysTest(TestCacheFactory.NON_OWNER).totalOrder(true), }; }
Source:
private static boolean doesDescriptorMatchType(String descriptor, Class<?> type) { while (type != null) { if (doesTypeMatch(descriptor, type)) { return true; } type = type.getSuperclass(); } return false; }

Target:
private static boolean doesDescriptorMatchType(String descriptor, Class<?> type) { while (type != null) { if (doesDescriptorMatchTypeOrInterface(descriptor, type)) { return true; } type = type.getSuperclass(); } return false; }
Source:
public static File downloadFileFrom(Release release) throws IOException { URL url = new URL(release.getDownloadURL()); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); File file = new File(NamingUtils.buildNameFrom(release)); file.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(file); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); return file; }

Target:
public static File downloadFileFrom(Release release) throws IOException { File file = new File(NamingUtils.buildNameFrom(release)); if (!file.exists()) { obtainNewJarFrom(release, file); } return file; }
Source:
public static PAutomaton<PAutomatonState<String, String>, String> of(String s) { ArrayList<Transition<PAutomatonState<String, String>, String>> rules = new ArrayList<>(); ArrayList<PAutomatonState<String, String>> states = new ArrayList<>(); String[] stringTransitions = s.split("\\s*;\\s*"); int n = stringTransitions.length - 2; PAutomatonState<String,String> initialState = PAutomatonState.of(stringTransitions[n]); String[] finalStatesStrings = stringTransitions[n+1].trim().split("\\s+"); for (String state : finalStatesStrings) { states.add(PAutomatonState.ofString(state)); } for (int i = 0; i < n; i++) { Transition<PAutomatonState<String, String>, String> rule = Transition.of(stringTransitions[i]); rules.add(rule); } return new PAutomaton<>(rules, initialState, states); }

Target:
public static PAutomaton<PAutomatonState<String, String>, String> of(String s) { List<Transition<PAutomatonState<String, String>, String>> rules = new ArrayList<>(); List<PAutomatonState<String, String>> states = new ArrayList<>(); String[] stringTransitions = s.split("\\s*;\\s*"); int n = stringTransitions.length - 2; PAutomatonState<String,String> initialState = PAutomatonState.of(stringTransitions[n]); String[] finalStatesStrings = stringTransitions[n+1].trim().split("\\s+"); for (String state : finalStatesStrings) { states.add(PAutomatonState.ofString(state)); } for (int i = 0; i < n; i++) { Transition<PAutomatonState<String, String>, String> rule = Transition.of(stringTransitions[i]); rules.add(rule); } return new PAutomaton<>(rules, initialState, states); }
Source:
public void visitNode(Tree tree) { if (tree.is(Kind.CASE_CLAUSE)) { enterCase(); } else if (tree.is(Kind.LABELLED_STATEMENT)) { if (inCase()) { addIssue(((LabelledStatementTree) tree).label(), String.format(MESSAGE, ((LabelledStatementTree) tree).label().name())); } } else { stack.push(0); } }

Target:
public void visitNode(Tree tree) { if (tree.is(Kind.CASE_CLAUSE)) { enterCase(); } else if (tree.is(Kind.LABELLED_STATEMENT)) { if (inCase()) { IdentifierTree label = ((LabelledStatementTree) tree).label(); addIssue(label, String.format(MESSAGE, label.name())); } } else { stack.push(0); } }
Source:
public void disconnect() { logger.debug("Disconnecting"); if (readerThread != null) { logger.debug("Interrupt stream listener"); readerThread.interrupt(); } if (outWriter != null) { logger.debug("Close print writer stream"); IOUtils.closeQuietly(outWriter); } if (out != null) { logger.debug("Close tcp out stream"); IOUtils.closeQuietly(out); } if (in != null) { logger.debug("Close tcp in stream"); IOUtils.closeQuietly(in); } if (socket != null) { logger.debug("Close socket"); IOUtils.closeQuietly(socket); } readerThread = null; socket = null; out = null; in = null; logger.debug("Closed"); }

Target:
public void disconnect() { logger.debug("Disconnecting"); if (readerThread != null) { logger.debug("Interrupt stream listener"); readerThread.interrupt(); readerThread = null; } if (outWriter != null) { logger.debug("Close print writer stream"); IOUtils.closeQuietly(outWriter); outWriter = null; } if (out != null) { logger.debug("Close tcp out stream"); IOUtils.closeQuietly(out); out = null; } if (in != null) { logger.debug("Close tcp in stream"); IOUtils.closeQuietly(in); in = null; } if (socket != null) { logger.debug("Close socket"); IOUtils.closeQuietly(socket); socket = null; } logger.debug("Disconnected"); }
Source:
public Operation exec(Prolog engine) { Term a1 = engine.areg1; Term a2 = engine.areg2; Term a3 = engine.areg3; Term a4 = engine.areg4; Term a5 = engine.areg5; a1.dereference(); a2.dereference(); a3.dereference(); a4.dereference(); a5.dereference(); String regex = a1.toString(); List<PatchListEntry> patches = (List<PatchListEntry>)((JavaObjectTerm)a5).object(); if (!patches.isEmpty()) { PatchListEntry patch = patches.get(0); String newName = patch.getNewName(); String oldName = patch.getOldName(); Patch.ChangeType changeType = patch.getChangeType(); if ((oldName != null && oldName.matches(regex)) || newName.matches(regex)) { SymbolTerm newSym = SymbolTerm.create(newName); SymbolTerm changeSym = SymbolTerm.intern(changeType.toString()); SymbolTerm oldSym = Prolog.Nil; if (oldName != null) { oldSym = SymbolTerm.create(oldName); } if (!a2.unify(newSym, engine.trail)) { return engine.fail(); } if (!a3.unify(changeSym, engine.trail)) { return engine.fail(); } if (!a4.unify(oldSym, engine.trail)) { return engine.fail(); } return engine.cont; } } return engine.fail(); }

Target:
public Operation exec(Prolog engine) { Term a1 = engine.areg1; Term a2 = engine.areg2; Term a3 = engine.areg3; Term a4 = engine.areg4; Term a5 = engine.areg5; Pattern regex = (Pattern)((JavaObjectTerm)a1).object(); Iterator<PatchListEntry> iter = (Iterator<PatchListEntry>)((JavaObjectTerm)a5).object(); if (iter.hasNext()) { PatchListEntry patch = iter.next(); String newName = patch.getNewName(); String oldName = patch.getOldName(); Patch.ChangeType changeType = patch.getChangeType(); if (regex.matcher(newName).matches() || (oldName != null && regex.matcher(oldName).matches())) { SymbolTerm changeSym = getTypeSymbol(changeType); SymbolTerm newSym = SymbolTerm.create(newName); SymbolTerm oldSym = Prolog.Nil; if (oldName != null) { oldSym = SymbolTerm.create(oldName); } if (!a2.unify(changeSym, engine.trail)) { return engine.fail(); } if (!a3.unify(newSym, engine.trail)) { return engine.fail(); } if (!a4.unify(oldSym, engine.trail)) { return engine.fail(); } return engine.cont; } } return engine.fail(); }
Source:
private String path(List<GroupType> path, Type type) { StringBuilder pathString = new StringBuilder(); if (path.size() > 0) { for (int i = 1; i < path.size(); i++) { pathString.append(path.get(i).getName()); pathString.append("."); } } pathString.append(type.getName()); pathString.append("."); return pathString.toString(); }

Target:
private String path(List<GroupType> path, Type type) { StringBuilder pathString = new StringBuilder(); if (path.size() > 0) { for (int i = 1; i < path.size(); i++) { pathString.append(path.get(i).getName()).append('.'); } } pathString.append(type.getName()).append('.'); return pathString.toString(); }
Source:
public void doesNotRetryOnNonRetriableTransactionFailedException() throws Exception { TransactionFailedNonRetriableException failure = new TransactionFailedNonRetriableException(""); when(task.run()).thenThrow(failure); assertThatThrownBy(this::run).isEqualTo(failure); }

Target:
public void doesNotRetryOnNonRetriableTransactionFailedException() throws Exception { TransactionFailedNonRetriableException failure = new TransactionFailedNonRetriableException(""); when(task.run()).thenThrow(failure).thenReturn("success"); assertThatThrownBy(this::runExponential).isEqualTo(failure); }
Source:
private HTMLOptionElement entryOption(final KieAssetsDropdownItem entry) { final HTMLOptionElement option = makeHTMLOptionElement(); option.text = entry.getText(); option.value = entry.getValue(); entry.getMetaData().forEach((key, value) -> option.setAttribute(data(key), value)); return option; }

Target:
private HTMLOptionElement entryOption(final KieAssetsDropdownItem entry) { final HTMLOptionElement option = makeHTMLOptionElement(); option.text = entry.getText(); option.value = entry.getValue(); option.setAttribute(SELECT_PICKER_SUBTEXT_ATTRIBUTE, entry.getSubText()); return option; }
Source:
private static void delete(List<ReceiveCommand> cmds, List<ReceiveCommand> createCmds) { for (ReceiveCommand c : createCmds) { ObjectId id = c.getNewId(); String n = c.getRefName(); cmds.add(new ReceiveCommand(id, ObjectId.zeroId(), n)); } }

Target:
private static void delete(List<ReceiveCommand> cmds, List<ReceiveCommand> createCmds) { for (ReceiveCommand cmd : createCmds) { ObjectId id = cmd.getNewId(); String name = cmd.getRefName(); cmds.add(new ReceiveCommand(id, ObjectId.zeroId(), name)); } }
Source:
public void markPlaying() { try { DownloadEntry v = videoModel; if (v != null) { if (v.watched == DownloadEntry.WatchedState.UNWATCHED) { videoModel.watched = DownloadEntry.WatchedState.PARTIALLY_WATCHED; db.addVideoData(videoModel, new DataCallback<Long>() { @Override public void onResult(Long result) { try { db.updateVideoWatchedState(videoModel.getVideoId(), DownloadEntry.WatchedState.PARTIALLY_WATCHED, setWatchedStateCallback); } catch (Exception ex) { logger.error(ex); } } @Override public void onFail(Exception ex) { logger.error(ex); } }); } } } catch (Exception ex) { logger.error(ex); } }

Target:
public void markPlaying() { storage.markVideoPlaying(videoModel, watchedStateCallback); }
Source:
public String forInstanceUpdateTags(String instanceName, List<String> tags) { return StringUtil.join("/", _baseUrl, "instances", instanceName, "updateTags?tags=" + Joiner.on(",").join(tags)); }

Target:
public String forInstanceUpdateTags(String instanceName, List<String> tags) { return StringUtil.join("/", _baseUrl, "instances", instanceName, "updateTags?tags=" + StringUtils.join(tags, ",")); }
Source:
public long getLastStoredEntryId() { Long lastEntry = LedgerHandle.INVALID_ENTRY_ID; for (int bookieIndex : bookieIndexes) { Long lastStoredEntryIdForBookie = getLastStoredEntryId(bookieIndex); if (lastStoredEntryIdForBookie != LedgerHandle.INVALID_ENTRY_ID) { if (lastEntry == LedgerHandle.INVALID_ENTRY_ID) { lastEntry = lastStoredEntryIdForBookie; } else { lastEntry = Math.max(lastEntry, lastStoredEntryIdForBookie); } } } return lastEntry; }

Target:
public long getLastStoredEntryId() { long lastEntry = LedgerHandle.INVALID_ENTRY_ID; for (int bookieIndex : bookieIndexes) { Long lastStoredEntryIdForBookie = getLastStoredEntryId(bookieIndex); if (lastStoredEntryIdForBookie != LedgerHandle.INVALID_ENTRY_ID) { if (lastEntry == LedgerHandle.INVALID_ENTRY_ID) { lastEntry = lastStoredEntryIdForBookie; } else { lastEntry = Math.max(lastEntry, lastStoredEntryIdForBookie); } } } return lastEntry; }
Source:
protected void allowableSessionsExceeded(List<SessionInformation> sessions, int allowableSessions, SessionRegistry registry) throws SessionAuthenticationException { if (exceptionIfMaximumExceeded || (sessions == null)) { throw new SessionAuthenticationException(messages.getMessage( "ConcurrentSessionControlAuthenticationStrategy.exceededAllowed", new Object[] {allowableSessions}, "Maximum sessions of {0} for this principal exceeded")); } sessions.sort(Comparator.comparing(SessionInformation::getLastRequest)); int maximumSessionsExceededBy = sessions.size() - allowableSessions + 1; for (int i = 0; i < maximumSessionsExceededBy; i++) { sessions.get(i).expireNow(); } }

Target:
protected void allowableSessionsExceeded(List<SessionInformation> sessions, int allowableSessions, SessionRegistry registry) throws SessionAuthenticationException { if (exceptionIfMaximumExceeded || (sessions == null)) { throw new SessionAuthenticationException(messages.getMessage( "ConcurrentSessionControlAuthenticationStrategy.exceededAllowed", new Object[] {allowableSessions}, "Maximum sessions of {0} for this principal exceeded")); } sessions.sort(Comparator.comparing(SessionInformation::getLastRequest)); int maximumSessionsExceededBy = sessions.size() - allowableSessions + 1; List<SessionInformation> sessionsToBeExpired = sessions.subList(0, maximumSessionsExceededBy); for (SessionInformation session: sessionsToBeExpired) { session.expireNow(); } }
Source:
public void theActivityCalendarProfilesAreSetOnTheDevice(final Map<String, String> settings) throws Throwable { final SetActivityCalendarAsyncRequest setActivityCalendarAsyncRequest = SetActivityCalendarRequestFactory .fromScenarioContext(); final SetActivityCalendarResponse setActivityCalendarResponse = this.smartMeteringConfigurationClient .getSetActivityCalendarResponse(setActivityCalendarAsyncRequest); LOGGER.info("Set activity calendar with result: {}", setActivityCalendarResponse.getResult().name()); assertNotNull("Set activity calendar response is null", setActivityCalendarResponse.getResult()); }

Target:
public void theActivityCalendarProfilesAreSetOnTheDevice(final Map<String, String> settings) throws Throwable { final SetActivityCalendarAsyncRequest setActivityCalendarAsyncRequest = SetActivityCalendarRequestFactory .fromScenarioContext(); final SetActivityCalendarResponse setActivityCalendarResponse = this.smartMeteringConfigurationClient .getSetActivityCalendarResponse(setActivityCalendarAsyncRequest); LOGGER.info("Set activity calendar with result: {}", setActivityCalendarResponse.getResult().name()); assertNotNull("Set activity calendar response is null", setActivityCalendarResponse.getResult()); assertEquals("Set activity calendar response should be OK", OsgpResultType.OK, setActivityCalendarResponse.getResult()); }
Source:
protected void endWithFailure() { setSucceeded(true); }

Target:
protected void endWithFailure() { super.endWithFailure(); }
Source:
protected DeploymentBuilder loadProjectManifest(DeploymentBuilder deploymentBuilder) { if (applicationUpgradeContextService != null && applicationUpgradeContextService.hasProjectManifest()) { try { deploymentBuilder.setProjectManifest(applicationUpgradeContextService.loadProjectManifest()); } catch (IOException e) { LOGGER.warn("Manifest of application not found. Project release version will not be set for deployment."); } } if(applicationUpgradeContextService != null && applicationUpgradeContextService.hasEnforcedAppVersion()){ deploymentBuilder.setEnforcedAppVersion(applicationUpgradeContextService.getEnforcedAppVersion()); LOGGER.warn("Enforced application version set to" + applicationUpgradeContextService.getEnforcedAppVersion().toString()); }else{ LOGGER.warn("Enforced application version not set."); } return deploymentBuilder; }

Target:
private void loadProjectManifest(DeploymentBuilder deploymentBuilder) { if (applicationUpgradeContextService.hasProjectManifest()) { try { deploymentBuilder.setProjectManifest(applicationUpgradeContextService.loadProjectManifest()); } catch (IOException e) { LOGGER.warn("Manifest of application not found. Project release version will not be set for deployment."); } } }
Source:
public List<StructuredNotificationEvent> cloudbreakEventsForStack(Long stackId) { List<StructuredNotificationEvent> events = new ArrayList<>(); if (stackId != null) { events = structuredEventService.getEventsWithTypeAndResourceId(StructuredNotificationEvent.class, CloudbreakEventService.DATAHUB_RESOURCE_TYPE, stackId); } return events; }

Target:
public List<StructuredNotificationEvent> cloudbreakEventsForStack(Long stackId) { List<StructuredNotificationEvent> events = new ArrayList<>(); if (stackId != null) { StackView stackView = stackService.getViewByIdWithoutAuth(stackId); events = structuredEventService.getEventsWithTypeAndResourceId(StructuredNotificationEvent.class, stackView.getType().getResourceType(), stackId); } return events; }
Source:
public NameAndDataTypeHeaderMetaData(final HasExpression hasExpression, final Optional<E> expression, final Optional<HasName> hasName, final Consumer<HasName> clearDisplayNameConsumer, final BiConsumer<HasName, Name> setDisplayNameConsumer, final BiConsumer<HasTypeRef, QName> setTypeRefConsumer, final CellEditorControlsView.Presenter cellEditorControls, final NameAndDataTypeEditorView.Presenter headerEditor) { super(cellEditorControls, headerEditor); this.hasName = hasName; this.clearDisplayNameConsumer = clearDisplayNameConsumer; this.setDisplayNameConsumer = setDisplayNameConsumer; this.setTypeRefConsumer = setTypeRefConsumer; HasTypeRef hasTypeRef = expression.get(); final DMNModelInstrumentedBase base = hasExpression.asDMNModelInstrumentedBase(); if (base instanceof HasVariable) { final HasVariable hasVariable = (HasVariable) base; hasTypeRef = hasVariable.getVariable(); } this.hasTypeRef = hasTypeRef; }

Target:
public NameAndDataTypeHeaderMetaData(final HasExpression hasExpression, final Optional<E> expression, final Optional<HasName> hasName, final Consumer<HasName> clearDisplayNameConsumer, final BiConsumer<HasName, Name> setDisplayNameConsumer, final BiConsumer<HasTypeRef, QName> setTypeRefConsumer, final CellEditorControlsView.Presenter cellEditorControls, final NameAndDataTypeEditorView.Presenter headerEditor) { this(hasName, getTypeRefOfExpression(expression, hasExpression), clearDisplayNameConsumer, setDisplayNameConsumer, setTypeRefConsumer, cellEditorControls, headerEditor); }
Source:
private List<ISegmentAspect> getAspectsFromColumnsId(List<Long> desiredColumns) { if (!desiredColumns.isEmpty()) { List<ISegmentAspect> segmentAspects = new ArrayList<>(); for (Long columnId : desiredColumns) { ISegmentAspect segmentAspect = fAspectMap.get(columnId); if (segmentAspect != null) { segmentAspects.add(segmentAspect); } } return segmentAspects; } return new ArrayList<>(fAspectMap.values()); }

Target:
private Map<Long, ISegmentAspect> getAspectsFromColumnsId(List<Long> desiredColumns) { Map<Long, ISegmentAspect> aspects = new LinkedHashMap<>(); if (!desiredColumns.isEmpty()) { for (Long columnsId : desiredColumns) { ISegmentAspect segmentAspect = fAspectMap.get(columnsId); if (segmentAspect != null) { aspects.put(columnsId, segmentAspect); } } return aspects; } return fAspectMap; }
Source:
public OpenShiftProject create(String workspaceId) throws InfrastructureException { boolean isPredefined = !isNullOrEmpty(this.projectName); final String projectName = isPredefined ? this.projectName : workspaceId; OpenShiftProject osProject = new OpenShiftProject(clientFactory, projectName, workspaceId); osProject.prepare(); if (!isPredefined && !isNullOrEmpty(serviceAccountName)) { WorkspaceServiceAccount workspaceServiceAccount = new WorkspaceServiceAccount(workspaceId, projectName, serviceAccountName, clientFactory); workspaceServiceAccount.prepare(); } return osProject; }

Target:
public OpenShiftProject create(String workspaceId) throws InfrastructureException { final String projectName = isPredefined() ? this.projectName : workspaceId; OpenShiftProject osProject = doCreateProject(workspaceId, projectName); osProject.prepare(); if (!isPredefined() && !isNullOrEmpty(serviceAccountName)) { WorkspaceServiceAccount workspaceServiceAccount = doCreateServiceAccount(workspaceId, projectName); workspaceServiceAccount.prepare(); } return osProject; }
Source:
private ActivationKey fetchActivationKey(String keyId) { if (keyId == null || keyId.isEmpty()) { throw new BadRequestException(i18n.tr("activation key ID is null or empty")); } ActivationKey key = this.activationKeyCurator.secureGet(keyId); if (key == null) { throw new BadRequestException(i18n.tr("ActivationKey with id {0} could not be found.", keyId)); } return key; }

Target:
private ActivationKey fetchActivationKey(String keyId) { if (keyId == null || keyId.isEmpty()) { throw new IllegalArgumentException(i18n.tr("activation key ID is null or empty")); } ActivationKey key = this.activationKeyCurator.secureGet(keyId); if (key == null) { throw new NotFoundException(i18n.tr("ActivationKey with id {0} could not be found.", keyId)); } return key; }
Source:
private static Field tryGetOnHierarchyChangeListenerField() { try { Field field = ViewGroup.class.getDeclaredField("mOnHierarchyChangeListener"); field.setAccessible(true); return field; } catch (NoSuchFieldException e) { return null; } }

Target:
private static Field tryGetOnHierarchyChangeListenerField() { Field field = ReflectionUtil.tryGetDeclaredField( ViewGroup.class, "mOnHierarchyChangeListener"); if (field != null) { field.setAccessible(true); } return field; }
Source:
private void onSafeDelete() { if (context.getEditorModelContent().getOriginalClassName() != null) { final String className = context.getEditorModelContent().getOriginalClassName(); showAssetUsagesDisplayer.showAssetUsages(Constants.INSTANCE.modelEditor_confirm_deletion_of_used_class(className), versionRecordManager.getCurrentPath(), className, ResourceType.JAVA, () -> onDelete(versionRecordManager.getPathToLatest()), () -> { }); } else { onDelete(versionRecordManager.getPathToLatest()); } }

Target:
public void onSafeDelete() { if (context.getEditorModelContent().getOriginalClassName() != null) { final String className = context.getEditorModelContent().getOriginalClassName(); showAssetUsagesDisplayer.showAssetUsages(Constants.INSTANCE.modelEditor_confirm_deletion_of_used_class(className), versionRecordManager.getCurrentPath(), className, ResourceType.JAVA, () -> onDelete(versionRecordManager.getPathToLatest()), () -> { }); } else { onDelete(versionRecordManager.getPathToLatest()); } }
Source:
public static void main(final String[] args) { LauncherStatus status; try { status = run(args); } catch (final Exception e) { LOG.log(Level.SEVERE, "Fatal exception occurred: ", e); status = LauncherStatus.failed(e); } LOG.log(Level.INFO, "REEF job completed: {0}", status); }

Target:
public static void main(final String[] args) { LauncherStatus status; try { status = run(args); } catch (final Exception e) { LOG.log(Level.SEVERE, "Fatal exception occurred.", e); status = LauncherStatus.failed(e); } LOG.log(Level.INFO, "REEF job completed: {0}", status); }
Source:
private List<CloudResource> persistCloudResources( AuthenticatedContext ac, CloudStack stack, PersistenceNotifier notifier, CloudContext cloudContext, String stackName, String resourceGroupName, Deployment templateDeployment) { List<CloudResource> allResourcesToPersist = new ArrayList<>(); List<CloudResource> instances; try { List<CloudResource> templateResources = azureCloudResourceService.getDeploymentCloudResources(templateDeployment); allResourcesToPersist.addAll(templateResources); instances = azureCloudResourceService.getInstanceCloudResources(stackName, templateResources, stack.getGroups(), resourceGroupName); List<CloudResource> osDiskResources = azureCloudResourceService.getAttachedOsDiskResources(ac, instances, resourceGroupName); allResourcesToPersist.addAll(osDiskResources); } finally { azureCloudResourceService.deleteCloudResources(notifier, cloudContext, allResourcesToPersist); azureCloudResourceService.saveCloudResources(notifier, cloudContext, allResourcesToPersist); } return instances; }

Target:
private List<CloudResource> persistCloudResources( AuthenticatedContext ac, CloudStack stack, PersistenceNotifier notifier, CloudContext cloudContext, String stackName, String resourceGroupName, Deployment templateDeployment) { List<CloudResource> allResourcesToPersist = new ArrayList<>(); List<CloudResource> instances; try { List<CloudResource> templateResources = azureCloudResourceService.getDeploymentCloudResources(templateDeployment); LOGGER.debug("Template resources retrieved: {}", templateResources); allResourcesToPersist.addAll(templateResources); instances = azureCloudResourceService.getInstanceCloudResources(stackName, templateResources, stack.getGroups(), resourceGroupName); List<CloudResource> osDiskResources = azureCloudResourceService.getAttachedOsDiskResources(ac, instances, resourceGroupName); LOGGER.debug("OS disk resources retrieved: {}", osDiskResources); allResourcesToPersist.addAll(osDiskResources); } finally { azureCloudResourceService.deleteCloudResources(notifier, cloudContext, allResourcesToPersist); azureCloudResourceService.saveCloudResources(notifier, cloudContext, allResourcesToPersist); LOGGER.info("Resources persisted: {}", allResourcesToPersist); } return instances; }
Source:
private AlluxioCachingFileSystem cachingFileSystem(CacheConfig cacheConfig, AlluxioCacheConfig alluxioCacheConfig) throws URISyntaxException, IOException { Map<Path, byte[]> files = new HashMap<>(); files.put(new Path(testFilePath), data); Configuration configuration = getHdfsConfiguration(cacheConfig, alluxioCacheConfig); ExtendedFileSystem testFs = new TestingFileSystem(files, configuration); URI uri = new URI("hdfs://test:8020/"); AlluxioCachingFileSystem cachingFs = new AlluxioCachingFileSystem(configuration, uri, testFs, new CacheFactory()); cachingFs.initialize(uri, configuration); return cachingFs; }

Target:
private AlluxioCachingFileSystem cachingFileSystem(CacheConfig cacheConfig, AlluxioCacheConfig alluxioCacheConfig) throws URISyntaxException, IOException { Map<Path, byte[]> files = new HashMap<>(); files.put(new Path(testFilePath), data); Configuration configuration = getHdfsConfiguration(cacheConfig, alluxioCacheConfig); ExtendedFileSystem testingFileSystem = new TestingFileSystem(files, configuration); URI uri = new URI("hdfs://test:8020/"); AlluxioCachingFileSystem cachingFileSystem = new AlluxioCachingFileSystem(testingFileSystem, uri); cachingFileSystem.initialize(uri, configuration); return cachingFileSystem; }
Source:
public void includeStatsFalseShouldNotIncludeStatistics() throws Exception { Variant variant = buildVariant("12", 3, 4, "A", "T", "fileId", "studyId"); VariantMongoWriter variantMongoWriter = new VariantMongoWriter(collectionName, mongoOperations, false, true); variantMongoWriter.write(Collections.singletonList(variant)); DBCollection dbCollection = mongoOperations.getCollection(collectionName); assertEquals(1, dbCollection.count()); final DBObject storedVariant = dbCollection.findOne(); assertNull(storedVariant.get(STATISTICS_FIELD)); }

Target:
public void includeStatsFalseShouldNotIncludeStatistics() throws Exception { Variant variant = buildVariantWithStats("12", 3, 4, "A", "T", "fileId", "studyId"); VariantMongoWriter variantMongoWriter = new VariantMongoWriter(collectionName, mongoOperations, false, false); variantMongoWriter.write(Collections.singletonList(variant)); DBCollection dbCollection = mongoOperations.getCollection(collectionName); assertEquals(1, dbCollection.count()); final DBObject storedVariant = dbCollection.findOne(); assertNull(storedVariant.get(STATISTICS_FIELD)); }
Source:
private void write(final String string) { if (logIsLooping()) { unbindStdOutAndErrToLog(); System.err.println(string); bindStdOutAndErrToLog(); } else { logger.log(this.level, string); } }

Target:
private void write(final String string) { logger.log(this.level, string); }
Source:
public void testAssumptionFailure(Failure failure) { ignoreCount.getAndIncrement(); }

Target:
public void testAssumptionFailure(Failure failure) { }
Source:
public void parse(InputStream stream, boolean includeRecommends, String sumProperty) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); String next = reader.readLine(); while (true) { String line = next; for (next = reader.readLine(); next != null && next.length() > 1 && next.charAt(0) == ' '; next = reader.readLine()) { line = line + next.substring(1); } if (line == null) { validateAndAddIU(); break; } if (line.trim().length() == 0) { validateAndAddIU(); continue; } if (line.startsWith("#") || line.startsWith("preamble: ") || line.startsWith("property: ") || line.startsWith("univ-checksum: ")) { } else if (line.startsWith("package: ")) { handlePackage(line); } else if (line.startsWith("version: ")) { handleVersion(line); } else if (line.startsWith("depends: ")) { handleDepends(line); } else if (line.startsWith("provides: ")) { handleProvides(line); } else if (line.startsWith("singleton:")) { handleSingleton(line); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } } if (TIMING) if (DEBUG) for (IInstallableUnit iInstallableUnit : allIUs) debug((InstallableUnit) iInstallableUnit); }

Target:
public void parse(InputStream stream, boolean includeRecommends, String sumProperty) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); String next = reader.readLine(); while (true) { String line = next; for (next = reader.readLine(); next != null && next.length() > 1 && next.charAt(0) == ' '; next = reader.readLine()) { line = line + next.substring(1); } if (line == null) { validateAndAddIU(); break; } if (line.trim().length() == 0) { validateAndAddIU(); continue; } if (line.startsWith("#") || line.startsWith("preamble: ") || line.startsWith("property: ") || line.startsWith("univ-checksum: ")) { } else if (line.startsWith("package: ")) { handlePackage(line); } else if (line.startsWith("version: ")) { handleVersion(line); } else if (line.startsWith("depends: ")) { handleDepends(line); } else if (line.startsWith("provides: ")) { handleProvides(line); } else if (line.startsWith("singleton:")) { handleSingleton(line); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } } if (TIMING) if (DEBUG) for (IInstallableUnit iu : allIUs) debug((InstallableUnit) iu); }
Source:
public static Object[][] rtProvider() { return new Object[][]{ {"TEST STRING".getBytes(), new Version[]{CramVersions.CRAM_v2_1, CramVersions.CRAM_v3}} }; }

Target:
public static Object[][] rtProvider() { return new Object[][]{ {"TEST STRING".getBytes(), CramVersions.CRAM_v2_1}, {"TEST STRING".getBytes(), CramVersions.CRAM_v3} }; }
Source:
public String generateLogMessage() { return Const.ActivityLog.TEAMMATESLOG + Const.ActivityLog.FIELD_SEPERATOR + servletName + Const.ActivityLog.FIELD_SEPERATOR + action + Const.ActivityLog.FIELD_SEPERATOR + (toShow ? "true" : "false") + Const.ActivityLog.FIELD_SEPERATOR + role + Const.ActivityLog.FIELD_SEPERATOR + name + Const.ActivityLog.FIELD_SEPERATOR + googleId + Const.ActivityLog.FIELD_SEPERATOR + email + Const.ActivityLog.FIELD_SEPERATOR + message + Const.ActivityLog.FIELD_SEPERATOR + url + Const.ActivityLog.FIELD_SEPERATOR + id; }

Target:
public String generateLogMessage() { return Const.ActivityLog.TEAMMATESLOG + Const.ActivityLog.FIELD_SEPARATOR + servletName + Const.ActivityLog.FIELD_SEPARATOR + action + Const.ActivityLog.FIELD_SEPARATOR + toShow + Const.ActivityLog.FIELD_SEPARATOR + role + Const.ActivityLog.FIELD_SEPARATOR + name + Const.ActivityLog.FIELD_SEPARATOR + googleId + Const.ActivityLog.FIELD_SEPARATOR + email + Const.ActivityLog.FIELD_SEPARATOR + message + Const.ActivityLog.FIELD_SEPARATOR + url + Const.ActivityLog.FIELD_SEPARATOR + id; }
Source:
public BinaryValue getQueryInfo() { StringBuilder sb = new StringBuilder("DELETE "); sb.append("{ "); int numKeys = this.builder.keyValues.size(); for (int i = 0; i < numKeys; i++) { if(this.builder.keyValues.get(i) == null) { sb.append("NULL"); } else { sb.append(this.builder.keyValues.get(i).toString()); } if(i < numKeys-1) { sb.append(", "); } } sb.append(" } FROM TABLE "); sb.append(this.builder.tableName.toStringUtf8()); return BinaryValue.create(sb.toString()); }

Target:
public BinaryValue getQueryInfo() { if (this.queryInfoMessage == null) { this.queryInfoMessage = createQueryInfoMessage(); } return this.queryInfoMessage; }
Source:
public void equalMinorFractionsTest() { final double[] weights = new double[] {0.2, 0.3, 0.5}; final double[] minorAlleleFractions = new double[] {0.3, 0.3, 0.3}; final double memoryLength = 1e3; final AllelicBiasParameters params = new AllelicBiasParameters(0.1, 0.01, 0.03); AlleleFractionHiddenMarkovModel model = new AlleleFractionHiddenMarkovModel(minorAlleleFractions, weights, memoryLength, AllelicPanelOfNormals.EMPTY_PON, params); final Random random = new Random(13); final int chainLength = 10000; final List<SimpleInterval> positions = new ArrayList<>(); final List<AllelicCount> data = new ArrayList<>(); int position = 1; for (int n = 0; n < chainLength; n++) { position += random.nextInt((int) (2*memoryLength)); final SimpleInterval interval = new SimpleInterval("chr1", position, position); positions.add(interval); data.add(new AllelicCount(interval, random.nextInt(30) + 1, random.nextInt(30) + 1)); } final ForwardBackwardAlgorithm.Result<AllelicCount, SimpleInterval, Integer> fbResult = ForwardBackwardAlgorithm.apply(data, positions, model); for (int pos = 0; pos < chainLength; pos++) { for (int state = 0; state < weights.length; state++) { Assert.assertEquals(fbResult.logProbability(pos, state), Math.log(weights[state]), 1e-5); } } }

Target:
public void equalMinorFractionsTest() { final double[] weights = new double[] {0.2, 0.3, 0.5}; final double[] minorAlleleFractions = new double[] {0.3, 0.3, 0.3}; final double memoryLength = 1e3; final AlleleFractionGlobalParameters params = new AlleleFractionGlobalParameters(0.1, 0.01, 0.03); final AlleleFractionHiddenMarkovModel model = new AlleleFractionHiddenMarkovModel(minorAlleleFractions, weights, memoryLength, AllelicPanelOfNormals.EMPTY_PON, params); final Random random = new Random(13); final int chainLength = 10000; final List<SimpleInterval> positions = new ArrayList<>(); final List<AllelicCount> data = new ArrayList<>(); int position = 1; for (int n = 0; n < chainLength; n++) { position += random.nextInt((int) (2*memoryLength)); final SimpleInterval interval = new SimpleInterval("chr1", position, position); positions.add(interval); data.add(new AllelicCount(interval, random.nextInt(30) + 1, random.nextInt(30) + 1)); } final ForwardBackwardAlgorithm.Result<AllelicCount, SimpleInterval, Integer> fbResult = ForwardBackwardAlgorithm.apply(data, positions, model); for (int pos = 0; pos < chainLength; pos++) { for (int state = 0; state < weights.length; state++) { Assert.assertEquals(fbResult.logProbability(pos, state), Math.log(weights[state]), 1e-5); } } }