auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public long tryReserveForCacheOnUpdate(K key, Data keyData) { checkAvailable(); if (evictionDisabled && evictionChecker.isEvictionRequired() && !containsRecordKey(key)) { return NOT_RESERVED; } long reservationId = nextReservationId(); R reservedRecord = reserveForCacheOnUpdate(key, keyData, reservationId); return reservedRecord == null ? NOT_RESERVED : (reservedRecord.getReservationId() == reservationId ? reservationId : NOT_RESERVED); }

Target:
public long tryReserveForCacheOnUpdate(K key, Data keyData) { return tryReserve0(key, keyData, true); }
Source:
public synchronized void forceNodeShutdown() { LOGGER.entering(); if (!isSupportedOnNode(NodeForceRestartServlet.class)) { LOGGER.exiting(); return; } stopNodeRecycleThread(); for (TestSlot slot : getTestSlots()) { if (slot.getSession() != null) { totalSessionsCompleted++; proxyLogger.info("Timing out session #" + totalSessionsCompleted + " (" + slot.getSession().toString() + ")"); getRegistry().forceRelease(slot, SessionTerminationReason.TIMEOUT); } } List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair(NodeForceRestartServlet.TOKEN_PARAMETER, NodeForceRestartServlet.CONFIGURED_TOKEN_VALUE)); HttpResponse response = sendToNodeServlet(NodeForceRestartServlet.class, nvps); if (response == null) { proxyLogger.warning("Node " + getId() + " failed to shutdown and returned a null response."); LOGGER.exiting(false); return; } final int responseStatusCode = response.getStatusLine().getStatusCode(); if (responseStatusCode != HttpStatus.SC_OK) { proxyLogger.info("Node " + getId() + " did not shutdown and returned HTTP " + responseStatusCode); LOGGER.exiting(false); return; } proxyLogger.info("Node " + getId() + " shutdown successfully."); getRegistry().removeIfPresent(this); LOGGER.exiting(); }

Target:
public synchronized void forceNodeShutdown() { LOGGER.entering(); stopNodeRecycleThread(); if (!isSupportedOnNode(NodeForceRestartServlet.class)) { LOGGER.exiting(); return; } for (TestSlot slot : getTestSlots()) { if (slot.getSession() != null) { totalSessionsCompleted++; proxyLogger.info("Timing out session #" + totalSessionsCompleted + " (" + slot.getSession().toString() + ")"); getRegistry().forceRelease(slot, SessionTerminationReason.TIMEOUT); } } List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair(NodeForceRestartServlet.TOKEN_PARAMETER, NodeForceRestartServlet.CONFIGURED_TOKEN_VALUE)); HttpResponse response = sendToNodeServlet(NodeForceRestartServlet.class, nvps); if (response == null) { proxyLogger.warning("Node " + getId() + " failed to shutdown and returned a null response."); LOGGER.exiting(false); return; } final int responseStatusCode = response.getStatusLine().getStatusCode(); if (responseStatusCode != HttpStatus.SC_OK) { proxyLogger.info("Node " + getId() + " did not shutdown and returned HTTP " + responseStatusCode); LOGGER.exiting(false); return; } proxyLogger.info("Node " + getId() + " shutdown successfully."); getRegistry().removeIfPresent(this); LOGGER.exiting(); }
Source:
protected void writeObject(Object object, JsonGenerator generator) throws IOException { try (Data.TraverseCallback callback = createTraverseCallback(generator)) { Data.traverse(object, callback); generator.flush(); } }

Target:
protected void writeObject(Object object, JsonGenerator generator) throws IOException { try (Data.TraverseCallback callback = createTraverseCallback(generator)) { Data.traverse(object, callback); } }
Source:
public RemoteFile readFileWithMode(String uri, String ref, String path) throws GitAPIException, IOException { File dir = FileUtils.createTempDir("jgit_", ".git", null); try (Git git = Git.cloneRepository().setBare(true).setDirectory(dir) .setURI(uri).call()) { Repository repo = git.getRepository(); return readFileWithMode(repo, ref, path); } finally { FileUtils.delete(dir, FileUtils.RECURSIVE); } }

Target:
public RemoteFile readFileWithMode(String uri, String ref, String path) throws GitAPIException, IOException { File dir = FileUtils.createTempDir("jgit_", ".git", null); try (Git git = Git.cloneRepository().setBare(true).setDirectory(dir) .setURI(uri).call()) { Repository repo = git.getRepository(); ObjectId refCommitId = sha1(uri, ref); if (refCommitId == null) { throw new InvalidRefNameException(MessageFormat .format(JGitText.get().refNotResolved, ref)); } RevCommit commit = repo.parseCommit(refCommitId); TreeWalk tw = TreeWalk.forPath(repo, path, commit.getTree()); return new RemoteFile( tw.getObjectReader().open(tw.getObjectId(0)) .getCachedBytes(Integer.MAX_VALUE), tw.getFileMode(0)); } finally { FileUtils.delete(dir, FileUtils.RECURSIVE); } }
Source:
public void run(final List<EventListenerDescriptor> listeners, EventBundle bundle) { if (bundle instanceof ReconnectedEventBundleImpl) { EventBundle connectedBundle = new EventBundleImpl(); Map<String, CoreSession> sessions = new HashMap<String, CoreSession>(); boolean txStarted = false; if (TransactionHelper.isNoTransaction()) { txStarted = TransactionHelper.startTransaction(); } List<Event> events = ((ReconnectedEventBundleImpl)bundle).getReconnectedEvents(); for (Event event : events) { connectedBundle.push(event); CoreSession session = event.getContext().getCoreSession(); if (!(sessions.keySet().contains(session.getRepositoryName()))) { sessions.put(session.getRepositoryName(), session); } } if (txStarted) { TransactionHelper.commitOrRollbackTransaction(); sessions.values().forEach(CoreSession::close); } bundle = connectedBundle; } for (EventListenerDescriptor listener : listeners) { EventBundle filtered = listener.filterBundle(bundle); if (filtered.isEmpty()) { continue; } getWorkManager().schedule(new ListenerWork(listener, filtered), true); } }

Target:
public void run(final List<EventListenerDescriptor> listeners, EventBundle bundle) { if (!(bundle instanceof ReconnectedEventBundleImpl)) { scheduleListeners(listeners, bundle); } else { final EventBundle tmpBundle = bundle; TransactionHelper.runInTransaction(() -> { EventBundle connectedBundle = new EventBundleImpl(); Map<String, CoreSession> sessions = new HashMap<>(); List<Event> events = ((ReconnectedEventBundleImpl)tmpBundle).getReconnectedEvents(); for (Event event : events) { connectedBundle.push(event); CoreSession session = event.getContext().getCoreSession(); if (!(sessions.keySet().contains(session.getRepositoryName()))) { sessions.put(session.getRepositoryName(), session); } } sessions.values().forEach(CoreSession::close); scheduleListeners(listeners, connectedBundle); }); } }
Source:
private static EventFiringWebDriver getChromeInstance() { String chromeBinaryName; String OSName = System.getProperty("os.name").toUpperCase(); if (OSName.contains("WINDOWS")) { chromeBinaryName = "chromedriver.exe"; File chromeBinary = new File ( "." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ChromeDriver" + File.separator + chromeBinaryName ); System.setProperty("webdriver.chrome.driver", chromeBinary.getAbsolutePath()); } else if (OSName.contains("MAC")) { chromeBinaryName = "chromedriver"; File chromeBinary = new File ( "." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ChromeDriver" + File.separator + "ChromeDriver_OSX" + File.separator + chromeBinaryName ); System.setProperty("webdriver.chrome.driver", chromeBinary.getAbsolutePath()); } if (browserName.equals("CHROMEMOBILE")) { ChromeOptions options = new ChromeOptions(); options.addArguments( "--user-agent="+ "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) " + "AppleWebKit/420+ (KHTML, like Gecko) " + "Version/3.0 Mobile/1A543a Safari/419.3" ); return new EventFiringWebDriver(new ChromeDriver(options)); } return new EventFiringWebDriver(new ChromeDriver(caps)); }

Target:
private static EventFiringWebDriver getChromeInstance() { String chromeBinaryName; String OSName = System.getProperty("os.name").toUpperCase(); chromeBinaryName = (OSName.contains("MAC")) ? "chromedriver" : "chromedriver.exe"; File chromeBinary = new File ( "." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ChromeDriver" + File.separator + chromeBinaryName ); System.setProperty("webdriver.chrome.driver", chromeBinary.getAbsolutePath()); if (browserName.equals("CHROMEMOBILE")) { ChromeOptions options = new ChromeOptions(); options.addArguments( "--user-agent="+ "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) " + "AppleWebKit/420+ (KHTML, like Gecko) " + "Version/3.0 Mobile/1A543a Safari/419.3" ); return new EventFiringWebDriver(new ChromeDriver(options)); } return new EventFiringWebDriver(new ChromeDriver(caps)); }
Source:
public TargetAnnotationCollection createTargetAnnotationCollection(final DataLine dataLine) { if (annotationSet.size() == 0) { return TargetAnnotationCollection.NO_ANNOTATION; } return new TargetAnnotationCollection() { @Override public int size() { return annotationSet.size(); } @Override public boolean hasAnnotation(final TargetAnnotation annotation) { return annotationToColumnIndex[annotation.ordinal()] >= 0; } @Override public double getDouble(final TargetAnnotation annotation) { if (hasAnnotation(annotation)) { return dataLine.getDouble(annotationToColumnIndex[annotation.ordinal()], formatAnnotationExceptionFactory.apply(dataLine)); } else { throw formatAnnotationExceptionFactory.apply(dataLine).apply( String.format("not found expected target annotation '%s' in input", annotation.column)); } } @Override public String get(final TargetAnnotation annotation) { if (hasAnnotation(annotation)) { return dataLine.get(annotationToColumnIndex[annotation.ordinal()]); } else { throw formatAnnotationExceptionFactory.apply(dataLine).apply( String.format("not found expected target annotation '%s' in input", annotation.column)); } } @Override public Set<TargetAnnotation> annotationSet() { return annotationSet; } }; }

Target:
public TargetAnnotationCollection createTargetAnnotationCollection(final DataLine dataLine) { if (annotationSet.size() == 0) { return TargetAnnotationCollection.NO_ANNOTATION; } else { return new DataLineTargetAnnotationCollection(dataLine); } }
Source:
private List performVmCheckpointsOperation(VDSCommandType vdsCommandType, VdsAndVmIDVDSParametersBase params) { VDSReturnValue vdsRetVal; try { vdsRetVal = runVdsCommand(vdsCommandType, params); if (!vdsRetVal.getSucceeded()) { EngineException engineException = new EngineException(); engineException.setVdsError(vdsRetVal.getVdsError()); throw engineException; } } catch (EngineException e) { log.error("Failed to execute '{}': {}", vdsCommandType, e); throw e; } return (List) vdsRetVal.getReturnValue(); }

Target:
private List<Guid> performVmCheckpointsOperation(VDSCommandType vdsCommandType, VdsAndVmIDVDSParametersBase params) { VDSReturnValue vdsRetVal; try { vdsRetVal = runVdsCommand(vdsCommandType, params); if (!vdsRetVal.getSucceeded()) { EngineException engineException = new EngineException(); engineException.setVdsError(vdsRetVal.getVdsError()); throw engineException; } } catch (EngineException e) { log.error("Failed to execute '{}': {}", vdsCommandType, e); throw e; } return (List<Guid>) vdsRetVal.getReturnValue(); }
Source:
@Nonnull protected Policy parsePolicy() { Policy policy = new Policy(this.origin); while (this.hasNext()) { if (this.hasNext(PolicySeparatorToken.class)) break; if (this.eat(DirectiveSeparatorToken.class)) continue; try { policy.addDirective(this.parseDirective()); } catch (IllegalArgumentException e) { this.warn(this.tokens[index - 1], e.getMessage()); } catch (DirectiveParseException ignored) { } } return policy; }

Target:
@Nonnull protected Policy parsePolicy() { Policy policy = new Policy(this.origin); while (this.hasNext()) { if (this.hasNext(PolicySeparatorToken.class)) break; if (this.eat(DirectiveSeparatorToken.class)) continue; try { Directive<? extends DirectiveValue> directive = this.parseDirective(); if (policy.getDirectiveByType(directive.getClass()) == null) { policy.addDirective(directive); } else { this.warn(this.tokens[this.index - 2], "Policy contains more than one " + directive.name + " directive. All but the first instance will be ignored."); } } catch (DirectiveParseException ignored) { } } return policy; }
Source:
public Response intercept(Chain chain) throws IOException { Tags.AttemptSpan attemptSpanTag = chain.request().tag(Tags.AttemptSpan.class); if (attemptSpanTag == null) { return chain.proceed(chain.request()); } try { return addHeaders.intercept(chain); } finally { DetachedSpan waitForBody = chain.request().tag(Tags.AttemptSpan.class) .attemptSpan() .childDetachedSpan("OkHttp: wait-for-body", SpanType.CLIENT_OUTGOING); chain.request().tag(Tags.SettableWaitForBodySpan.class).setWaitForBodySpan(waitForBody); } }

Target:
public Response intercept(Chain chain) throws IOException { Tags.AttemptSpan attemptSpanTag = chain.request().tag(Tags.AttemptSpan.class); if (attemptSpanTag == null) { return chain.proceed(chain.request()); } try { return addHeaders.intercept(chain); } finally { DetachedSpan waitForBody = attemptSpanTag .attemptSpan() .childDetachedSpan("OkHttp: wait-for-body", SpanType.CLIENT_OUTGOING); chain.request().tag(Tags.SettableWaitForBodySpan.class).setWaitForBodySpan(waitForBody); } }
Source:
public List<Timeline> getTimelines(final String eventTypeName) throws AccessDeniedException, UnableProcessException, TimelineException, NotFoundException { if (!adminService.isAdmin(AuthorizationService.Operation.READ)) { throw new AccessDeniedException(AuthorizationService.Operation.ADMIN, new ResourceImpl<EventType>(eventTypeName, ResourceImpl.EVENT_TYPE_RESOURCE, null, null)); } try { final EventType eventType = eventTypeCache.getEventType(eventTypeName); authorizationValidator.authorizeEventTypeView(eventType); return timelineDbRepository.listTimelinesOrdered(eventType.getName()); } catch (final NoSuchEventTypeException e) { throw new NotFoundException("EventType \"" + eventTypeName + "\" does not exist"); } catch (final InternalNakadiException e) { throw new TimelineException("Could not get event type: " + eventTypeName, e); } }

Target:
public List<Timeline> getTimelines(final String eventTypeName) throws AccessDeniedException, UnableProcessException, TimelineException, NotFoundException { if (!adminService.isAdmin(AuthorizationService.Operation.READ)) { throw new AccessDeniedException(AuthorizationService.Operation.ADMIN, new ResourceImpl<EventType>(eventTypeName, ResourceImpl.EVENT_TYPE_RESOURCE, null, null)); } try { final EventType eventType = eventTypeCache.getEventType(eventTypeName); return timelineDbRepository.listTimelinesOrdered(eventType.getName()); } catch (final NoSuchEventTypeException e) { throw new NotFoundException("EventType \"" + eventTypeName + "\" does not exist"); } catch (final InternalNakadiException e) { throw new TimelineException("Could not get event type: " + eventTypeName, e); } }
Source:
protected String localizeText(String key) { String result = ""; if (this.i18nProvider != null && this.locale != null && I18nUtil.isConstant(key)) { result = this.i18nProvider.getText(this.bundleContext.getBundle(), I18nUtil.stripConstant(key), "", this.locale); } return result; }

Target:
protected String localizeText(String key) { String result = ""; if (I18nUtil.isConstant(key)) { result = this.i18nProvider.getText(this.bundleContext.getBundle(), I18nUtil.stripConstant(key), "", this.localeProvider.getLocale()); } return result; }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(FiltersHelper.Constants.SESSION_ENGINE_SESSION_ID_KEY); InitialContext ctx = null; if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryParametersBase parameters = new VdcQueryParametersBase(); parameters.setSessionId(engineSession); VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, parameters); if (!returnValue.getSucceeded()) { httpSession.removeAttribute(FiltersHelper.Constants.SESSION_ENGINE_SESSION_ID_KEY); } else { httpSession.setAttribute(FiltersHelper.Constants.SESSSION_USER_KEY, returnValue.getReturnValue()); } } finally { ctx.close(); } } } chain.doFilter(request, response); } catch (Exception ex) { String msg = String.format("An error has occurred while session validation. Message is %1$s", ex.getMessage()); log.error(msg); if (log.isDebugEnabled()) { log.debug("", ex); } ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean exceptionOccurred = false; try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(FiltersHelper.Constants.SESSION_ENGINE_SESSION_ID_KEY); InitialContext ctx = null; if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryParametersBase parameters = new VdcQueryParametersBase(); parameters.setSessionId(engineSession); VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, parameters); if (!returnValue.getSucceeded()) { httpSession.removeAttribute(FiltersHelper.Constants.SESSION_ENGINE_SESSION_ID_KEY); } else { request.setAttribute(FiltersHelper.Constants.REQUEST_USER_KEY, returnValue.getReturnValue()); } } finally { ctx.close(); } } } } catch (Exception ex) { exceptionOccurred = true; String msg = String.format("An error has occurred while session validation. Message is %1$s", ex.getMessage()); log.error(msg); if (log.isDebugEnabled()) { log.debug("", ex); } ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (!exceptionOccurred) { chain.doFilter(request, response); } }
Source:
public SolrClientAdapter(String core, Creator creator) { Validate.notNull(core, "invalid null core"); Validate.notNull(creator, "invalid null creator"); LOGGER.debug("Solr({}): Creating a Solr client adapter", core); this.core = core; this.creator = creator; try { setClient(new UnavailableSolrClient("initializing '" + core + "' core"), true); } catch (IOException e) { } }

Target:
public SolrClientAdapter(String core, Creator creator) { this(core, creator, Failsafe::with, Failsafe::with); }
Source:
public boolean isAutosizingConfig(String configParam) { switch (configParam) { case JOB_AUTOSIZING_CONTAINER_COUNT: case JOB_AUTOSIZING_CONTAINER_MAX_CORES: case JOB_AUTOSIZING_CONTAINER_MAX_HEAP_MB: case JOB_AUTOSIZING_CONTAINER_MEMORY_MB: case JOB_AUTOSIZING_CONTAINER_THREAD_POOL_SIZE: return true; default: return false; } }

Target:
public boolean isAutosizingConfig(String configParam) { return configParam.startsWith(JOB_AUTOSIZING_CONFIG_PREFIX); }
Source:
protected void onInit() throws ServletException { Client client = getClient(); Publisher<RequestEvent> eventPublisher = getConfig().getInstance(EVENT_PUBLISHER); AccountStoreResolver accountStoreResolver = getConfig().getInstance(ACCOUNT_STORE_RESOLVER); VerifyController controller = new VerifyController(); controller.setNextUri(getConfig().getVerifyNextUrl()); controller.setLogoutUri(getConfig().getLogoutUrl()); controller.setLoginUri(getConfig().getLoginUrl()); controller.setAccountStoreResolver(accountStoreResolver); controller.setView("stormpath/verify"); controller.setNextUri("stormpath/verifyComplete"); controller.setAutoLogin(getConfig().getRegisterAutoLogin()); controller.setClient(client); controller.setEventPublisher(eventPublisher); controller.init(); setController(controller); super.onInit(); }

Target:
protected void onInit() throws ServletException { Client client = getClient(); Publisher<RequestEvent> eventPublisher = getConfig().getInstance(EVENT_PUBLISHER); Saver<AuthenticationResult> authenticationResultSaver = getConfig().getInstance(ACCOUNT_SAVER_PROP); AccountStoreResolver accountStoreResolver = getConfig().getInstance(ACCOUNT_STORE_RESOLVER); MessageSource messageSource = getConfig().getInstance(MESSAGE_SOURCE); Resolver<Locale> localeResolver = getConfig().getInstance(LOCALE_RESOLVER); VerifyController controller = new VerifyController(); controller.setUri(getConfig().getVerifyUrl()); controller.setNextUri(getConfig().getVerifyNextUrl()); controller.setLogoutUri(getConfig().getLogoutUrl()); controller.setLoginUri(getConfig().getLoginUrl()); controller.setAccountStoreResolver(accountStoreResolver); controller.setView("stormpath/verify"); controller.setAutoLogin(getConfig().getRegisterAutoLogin()); controller.setClient(client); controller.setEventPublisher(eventPublisher); controller.setAuthenticationResultSaver(authenticationResultSaver); controller.setMessageSource(messageSource); controller.setLocaleResolver(localeResolver); controller.init(); setController(controller); super.onInit(); }
Source:
public static void ingest(AccumuloClient c, Opts opts, BatchWriterOpts batchWriterOpts) throws MutationsRejectedException, IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException, TableExistsException { ingest(c, FileSystem.get(new Configuration()), opts, batchWriterOpts); }

Target:
public static void ingest(AccumuloClient c, Opts opts, BatchWriterOpts batchWriterOpts) throws MutationsRejectedException, IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException, TableExistsException { ClientContext cc = (ClientContext) c; ingest(c, FileSystem.get(cc.getHadoopConf()), opts, batchWriterOpts); }
Source:
private void generateXpath() { if (tree.getLastSelectedPathComponent() instanceof DetailAST) { try { final FileText fileText = new FileText(file, StandardCharsets.UTF_8.name()); final DetailAST rootAST = (DetailAST) tree.getModel().getRoot(); final DetailAST ast = (DetailAST) tree.getLastSelectedPathComponent(); final int defaultTabWidth = 4; final XpathQueryGenerator queryGenerator = new XpathQueryGenerator(rootAST, ast.getLineNo(), ast.getColumnNo(), fileText, defaultTabWidth); xpathEditor.setText(queryGenerator.generateXpathQuery(ast)); } catch (IOException ex) { xpathEditor.setText(ex.getMessage()); } } else { xpathEditor.setText("Xpath is not supported yet forr javadoc nodes"); } }

Target:
private void generateXpath() { if (tree.getLastSelectedPathComponent() instanceof DetailAST) { final DetailAST ast = (DetailAST) tree.getLastSelectedPathComponent(); final int beginPos = 4; String xpath = XpathQueryGenerator.generateXpathQuery(ast); final int length = xpath.length(); xpath = xpath.substring(beginPos, length); xpathEditor.setText(xpath); } else { xpathEditor.setText("Xpath is not supported yet for javadoc nodes"); } }
Source:
protected Object resolve(Object unresolved) { if (unresolved == null) { return null; } else if (unresolved == INTERRUPTED) { return new AltResult(new InterruptedException(invocation.op.getClass().getSimpleName() + " was interrupted. " + invocation)); } else if (unresolved == CALL_TIMEOUT) { return newOperationTimeoutException(false); } else if (unresolved == HEARTBEAT_TIMEOUT) { return newOperationTimeoutException(true); } else if (unresolved.getClass() == Packet.class) { unresolved = invocation.context.serializationService.toObject(unresolved); if (unresolved instanceof NormalResponse) { unresolved = ((NormalResponse) unresolved).getValue(); } } Object value = unresolved; if (deserialize && value instanceof Data) { value = invocation.context.serializationService.toObject(value); if (value == null) { return null; } } if (isErroneousState(value)) { Throwable throwable = ((ErrorResponse) value).getCause(); if (invocation.shouldFailOnIndeterminateOperationState() && (throwable instanceof MemberLeftException)) { String message = invocation + " failed because the target has left the cluster before response is received"; throwable = new IndeterminateOperationStateException(message, throwable); } fixAsyncStackTrace(throwable, Thread.currentThread().getStackTrace()); return exceptionally(throwable); } return value; }

Target:
protected Object resolve(Object unresolved) { if (unresolved == null) { return null; } else if (unresolved == INTERRUPTED) { return new AltResult(new InterruptedException(invocation.op.getClass().getSimpleName() + " was interrupted. " + invocation)); } else if (unresolved == CALL_TIMEOUT) { return newOperationTimeoutException(false); } else if (unresolved == HEARTBEAT_TIMEOUT) { return newOperationTimeoutException(true); } else if (unresolved.getClass() == Packet.class) { unresolved = invocation.context.serializationService.toObject(unresolved); if (unresolved instanceof NormalResponse) { unresolved = ((NormalResponse) unresolved).getValue(); } } Object value = unresolved; if (deserialize && value instanceof Data) { value = invocation.context.serializationService.toObject(value); if (value == null) { return null; } } if (isErroneousState(value)) { Throwable throwable = ((ErrorResponse) value).getCause(); if (invocation.shouldFailOnIndeterminateOperationState() && (throwable instanceof MemberLeftException)) { String message = invocation + " failed because the target has left the cluster before response is received"; throwable = new IndeterminateOperationStateException(message, throwable); } fixAsyncStackTrace(throwable, Thread.currentThread().getStackTrace()); return new AltResult(throwable); } return value; }
Source:
private void setValue(final DTCellValue52 cell, final DataType.DataTypes dataType) { switch (dataType) { case STRING: if (isTheRealCellValueString(sourceColumnIndex) && cell.getStringValue() != null) { if (cell.getStringValue() != null && !cell.getStringValue().isEmpty()) { xlsRow.createCell(targetColumnIndex) .setCellValue(String.format("\"%s\"", fixStringValue(cell))); } } else { if (Objects.equals(DataType.DataTypes.STRING, cell.getDataType())) { xlsRow.createCell(targetColumnIndex) .setCellValue(cell.getStringValue()); } else { setValue(cell, cell.getDataType()); } } break; case NUMERIC: case NUMERIC_BIGDECIMAL: case NUMERIC_BIGINTEGER: case NUMERIC_BYTE: case NUMERIC_DOUBLE: case NUMERIC_FLOAT: case NUMERIC_INTEGER: case NUMERIC_LONG: case NUMERIC_SHORT: final Number numericValue = cell.getNumericValue(); if (numericValue != null) { xlsRow.createCell(targetColumnIndex) .setCellValue(numericValue.toString()); } break; case DATE: final Date dateValue = cell.getDateValue(); if (dateValue != null) { final SimpleDateFormat formatter = new SimpleDateFormat(getDateFormat()); xlsRow.createCell(targetColumnIndex) .setCellValue(formatter.format(dateValue)); } break; case BOOLEAN: final Boolean booleanValue = cell.getBooleanValue(); if (booleanValue != null) { xlsRow.createCell(targetColumnIndex) .setCellValue(booleanValue); } break; } }

Target:
private void setValue(final DTCellValue52 cell, final DataType.DataTypes dataType) { switch (dataType) { case STRING: setStringValue(cell); break; case NUMERIC: case NUMERIC_BIGDECIMAL: case NUMERIC_BIGINTEGER: case NUMERIC_BYTE: case NUMERIC_DOUBLE: case NUMERIC_FLOAT: case NUMERIC_INTEGER: case NUMERIC_LONG: case NUMERIC_SHORT: setNumericValue(cell); break; case DATE: setDateValue(cell); break; case BOOLEAN: setBooleanValue(cell); break; } }
Source:
private String calculateCommitMessage(Collection<String> paths) { if (commitMessage != null) { return commitMessage; } if (amending) return previousCommitMessage; StringBuilder calculatedCommitMessage = new StringBuilder(); Set<IResource> resources = new HashSet<>(); for (String path : paths) { IFile file = findFile(path); if (file != null) resources.add(file.getProject()); } if (resources.size() == 0 && repository != null) { resources .addAll(Arrays.asList(ProjectUtil.getProjects(repository))); } try { List<ICommitMessageProvider> messageProviders = getCommitMessageProviders(); IResource[] resourcesArray = resources .toArray(new IResource[0]); String providedMessageSeparator = "\n\n"; for (ICommitMessageProvider messageProvider : messageProviders) { String message = null; try { message = messageProvider.getMessage(resourcesArray); } catch (RuntimeException e) { Activator.logError(e.getMessage(), e); } if (message != null && !"".equals(message.trim())) { if (calculatedCommitMessage.length() > 0) { calculatedCommitMessage .append(providedMessageSeparator); } calculatedCommitMessage.append(providedMessageSeparator) .append((message.trim())); } } } catch (CoreException coreException) { Activator.logError(coreException.getLocalizedMessage(), coreException); } return calculatedCommitMessage.toString(); }

Target:
String calculateCommitMessage(Collection<String> paths) { if (commitMessage != null) { return commitMessage; } if (amending) return previousCommitMessage; StringBuilder calculatedCommitMessage = new StringBuilder(); Set<IResource> resources = new HashSet<>(); for (String path : paths) { IFile file = findFile(path); if (file != null) resources.add(file.getProject()); } if (resources.size() == 0 && repository != null) { resources .addAll(Arrays.asList(ProjectUtil.getProjects(repository))); } try { List<ICommitMessageProvider> messageProviders = getCommitMessageProviders(); IResource[] resourcesArray = resources .toArray(new IResource[0]); String providedMessageSeparator = "\n\n"; for (ICommitMessageProvider messageProvider : messageProviders) { String message = null; try { message = messageProvider.getMessage(resourcesArray); } catch (RuntimeException e) { Activator.logError(e.getMessage(), e); } if (message != null && !"".equals(message.trim())) { if (calculatedCommitMessage.length() > 0) { calculatedCommitMessage .append(providedMessageSeparator); } calculatedCommitMessage.append((message.trim())); } } } catch (CoreException coreException) { Activator.logError(coreException.getLocalizedMessage(), coreException); } return calculatedCommitMessage.toString(); }
Source:
public static RepositoryMapping getMapping(@NonNull IPath path) { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() .getProjects(); IPath bestWorkingTree = null; RepositoryMapping bestMapping = null; for (IProject project : projects) { if (isNonWorkspace(project)) { continue; } Map<IPath, RepositoryMapping> mappings = getMappings(project); for (RepositoryMapping mapping : mappings.values()) { File workTree = mapping.getWorkTree(); if (workTree == null) { continue; } IPath workingTree = new Path(workTree.toString()); if (workingTree.isPrefixOf(path)) { if (bestWorkingTree == null || workingTree .segmentCount() > bestWorkingTree.segmentCount()) { bestWorkingTree = workingTree; bestMapping = mapping; } } } } return bestMapping; }

Target:
public static RepositoryMapping getMapping(@NonNull IPath path) { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() .getProjects(); IPath bestWorkingTree = null; RepositoryMapping bestMapping = null; for (IProject project : projects) { if (isNonWorkspace(project)) { continue; } for (RepositoryMapping mapping : getMappings(project).values()) { File workTree = mapping.getWorkTree(); if (workTree == null) { continue; } IPath workingTree = new Path(workTree.toString()); if (workingTree.isPrefixOf(path)) { if (bestWorkingTree == null || workingTree .segmentCount() > bestWorkingTree.segmentCount()) { bestWorkingTree = workingTree; bestMapping = mapping; } } } } return bestMapping; }
Source:
public Coordinator(CoordinatorConfig config) throws Exception { _config = config; _adapter = new ZkAdapter(_config.getZkAddress(), _config.getCluster(), _config.getZkSessionTimeout(), _config.getZkConnectionTimeout(), this); _adapter.setListener(this); _eventCollectorFactory = new DatastreamEventCollectorFactory(config.getConfigProperties()); }

Target:
public Coordinator(CoordinatorConfig config) throws DatastreamException { _config = config; _adapter = new ZkAdapter(_config.getZkAddress(), _config.getCluster(), _config.getZkSessionTimeout(), _config.getZkConnectionTimeout(), this); _adapter.setListener(this); _eventCollectorFactory = new DatastreamEventCollectorFactory(config.getConfigProperties()); }
Source:
public TmfViewsElement getParent() { for (TmfAnalysisElement analysis : fContainedAnalyses) { if (analysis.hasChildren()) { return super.getParent(); } } return super.getParent(); }

Target:
public TmfViewsElement getParent() { return fExperimentParent.getChildElementViews(); }
Source:
private static ObjectStream<POSSample> createSampleStream() throws IOException { MarkableFileInputStreamFactory sampleDataIn; try { sampleDataIn = new MarkableFileInputStreamFactory( new File(POSTaggerFactory.class.getResource( "/AnnotatedSentences.txt").toURI().getPath())); } catch (URISyntaxException e) { throw new IOException(e); } ObjectStream<String> lineStream = null; try { lineStream = new PlainTextByLineStream(sampleDataIn, "UTF-8"); } catch (IOException ex) { CmdLineUtil.handleCreateObjectStreamError(ex); } return new WordTagSampleStream(lineStream); }

Target:
private static ObjectStream<POSSample> createSampleStream() throws IOException { MarkableFileInputStreamFactory sampleDataIn; try { sampleDataIn = new MarkableFileInputStreamFactory( new File(POSTaggerFactory.class.getResource( "/AnnotatedSentences.txt").toURI().getPath())); } catch (URISyntaxException e) { throw new IOException(e); } ObjectStream<String> lineStream = null; try { lineStream = new PlainTextByLineStream(sampleDataIn, StandardCharsets.UTF_8); } catch (IOException ex) { CmdLineUtil.handleCreateObjectStreamError(ex); } return new WordTagSampleStream(lineStream); }
Source:
public void testDescribeImages() { String region = getFirst(ec2Api.getConfiguredRegions(), null); if (region != null) { Set<? extends Image> allResults = client.describeImagesInRegion(region); assertNotNull(allResults); assert allResults.size() >= 2 : allResults.size(); Iterator<? extends Image> iterator = allResults.iterator(); String id1 = iterator.next().getId(); String id2 = iterator.next().getId(); Set<? extends Image> twoResults = client.describeImagesInRegion(region, imageIds(id1, id2)); assertNotNull(twoResults); assertEquals(twoResults.size(), 2); iterator = twoResults.iterator(); assertEquals(iterator.next().getId(), id1); assertEquals(iterator.next().getId(), id2); } }

Target:
public void testDescribeImages() { String region = getFirst(ec2Api.getConfiguredRegions(), null); assertNotNull(region, "region should not be null"); Set<? extends Image> allResults = client.describeImagesInRegion(region); assertNotNull(allResults); assertTrue(allResults.size() >= 2); Iterator<? extends Image> iterator = allResults.iterator(); String id1 = iterator.next().getId(); String id2 = iterator.next().getId(); Set<? extends Image> twoResults = client.describeImagesInRegion(region, imageIds(id1, id2)); assertNotNull(twoResults); assertEquals(twoResults.size(), 2); iterator = twoResults.iterator(); assertEquals(iterator.next().getId(), id1); assertEquals(iterator.next().getId(), id2); }
Source:
private void showLocationPicker() { if (!isAdded()) { return; } PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder(); LatLng latLng = null; if (mPostLocation != null) { latLng = new LatLng(mPostLocation.getLatitude(), mPostLocation.getLongitude()); } else if (mPost.hasLocation()) { PostLocation location = mPost.getLocation(); latLng = new LatLng(location.getLatitude(), location.getLongitude()); } if (latLng != null) { builder.setLatLngBounds(new LatLngBounds(latLng, latLng)); } try { startActivityForResult(builder.build(getActivity()), ACTIVITY_REQUEST_CODE_PICK_LOCATION); } catch (GooglePlayServicesNotAvailableException nae) { ToastUtils.showToast(getActivity(), R.string.post_settings_error_placepicker_missing_play_services); } catch (GooglePlayServicesRepairableException re) { GooglePlayServicesUtil.getErrorDialog(re.getConnectionStatusCode(), getActivity(), 0); } }

Target:
private void showLocationPicker() { if (!isAdded()) { return; } PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder(); LatLng latLng = null; if (mPostLocation != null) { latLng = new LatLng(mPostLocation.getLatitude(), mPostLocation.getLongitude()); } else if (mPost.hasLocation()) { PostLocation location = mPost.getLocation(); latLng = new LatLng(location.getLatitude(), location.getLongitude()); } if (latLng != null) { builder.setLatLngBounds(new LatLngBounds(latLng, latLng)); } try { startActivityForResult(builder.build(getActivity()), ACTIVITY_REQUEST_CODE_PICK_LOCATION); } catch (GooglePlayServicesNotAvailableException nae) { ToastUtils.showToast(getActivity(), R.string.post_settings_error_placepicker_missing_play_services); } catch (GooglePlayServicesRepairableException re) { GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), re.getConnectionStatusCode(), ACTIVITY_REQUEST_PLAY_SERVICES_RESOLUTION); } }
Source:
protected Object getExportResult(final URI address, final String serviceName, final Object... args) { final String scheme = address.getScheme() == null ? "irc" : address.getScheme(); try { final Service service = serviceManager.getService("parser", scheme); if (service != null && !service.getProviders().isEmpty()) { final ServiceProvider provider = service.getProviders().get(0); if (provider != null) { provider.activateServices(); return provider.getExportedService(serviceName) .execute(args); } } } catch (NoSuchProviderException nspe) { LOG.warn(USER_ERROR, "No parser found for " + address.getScheme(), nspe); } return null; }

Target:
protected Object getExportResult(final URI address, final String serviceName, final Object... args) { final String scheme = address.getScheme() == null ? "irc" : address.getScheme(); try { final Service service = serviceManager.getService("parser", scheme); if (service != null && !service.getProviders().isEmpty()) { final ServiceProvider provider = service.getProviders().get(0); if (provider != null) { provider.activateServices(); return provider.getExportedService(serviceName) .execute(args); } } } catch (NoSuchProviderException nspe) { LOG.warn(USER_ERROR, "No parser found for {}", address.getScheme(), nspe); } return null; }
Source:
public void deleteBucketJson() throws Exception { final String bucketName = "test_delete_bucket_json"; try { final String expected = "\"Message\" : \"Success: Deleted " + bucketName + " and all the objects contained in it.\"\n}"; Util.createBucket(client, bucketName); final Arguments args = new Arguments(new String[]{"--http", "-c", "delete_bucket", "-b", bucketName, "--force", "--output-format", "json"}); final CommandResponse response = Util.command(client, args); assertTrue(response.getMessage().endsWith(expected)); } finally { } }

Target:
public void deleteBucketJson() throws Exception { final String bucketName = "test_delete_bucket_json"; final String expected = "\"Message\" : \"Success: Deleted " + bucketName + " and all the objects contained in it.\"\n}"; Util.createBucket(client, bucketName); final Arguments args = new Arguments(new String[]{"--http", "-c", "delete_bucket", "-b", bucketName, "--force", "--output-format", "json"}); final CommandResponse response = Util.command(client, args); assertTrue(response.getMessage().endsWith(expected)); }
Source:
public static Variant makeVariant(String referenceName, long start, long end, String referenceBases, List<String> alternateBases, Call... calls) { Variant variant = new Variant().setReferenceName(referenceName).setStart(start).setEnd(end) .setReferenceBases(referenceBases).setAlternateBases(alternateBases); if (null != calls) { variant.setCalls(newArrayList(calls)); } return variant; }

Target:
public static Variant makeVariant(String referenceName, long start, long end, String referenceBases, List<String> alternateBases, Call... calls) { Variant variant = new Variant().setReferenceName(referenceName).setStart(start).setEnd(end) .setReferenceBases(referenceBases).setAlternateBases(alternateBases); if (null != calls) { variant.setCalls(Arrays.asList(calls)); } return variant; }
Source:
public void testBaselineAdjusment() throws Exception { byte[] buckets = new byte[] {0x45, 0x23, 0x01, 0x31, 0x22, 0x05, 0x04, 0x01}; Slice expected = new DynamicSliceOutput(1) .appendByte(3) .appendByte(4) .appendByte(2) .appendBytes(buckets) .appendByte(0) .appendByte(0) .slice(); DenseHll hll = new DenseHll(4); for (int i = 0; i < 100; i++) { hll.insertHash(Murmur3Hash128.hash64((long) i)); } assertSlicesEqual(hll.serialize(), expected); }

Target:
public void testBaselineAdjusment() throws Exception { byte[] buckets = new byte[] {0x45, 0x23, 0x01, 0x31, 0x22, 0x05, 0x04, 0x01}; Slice expected = new DynamicSliceOutput(1) .appendByte(3) .appendByte(4) .appendByte(2) .appendBytes(buckets) .appendByte(0) .appendByte(0) .slice(); DenseHll hll = new DenseHll(4); for (int i = 0; i < 100; i++) { hll.insertHash(Murmur3Hash128.hash64(i)); } assertSlicesEqual(hll.serialize(), expected); }
Source:
public void unbuffer() { buffer = null; fCursor = fCursor - limit + bCursor; fCursorAfterLastRead = -1; bCursor = 0; limit = 0; }

Target:
public synchronized void unbuffer() { buffer = null; fCursor = fCursor - limit + bCursor; fCursorAfterLastRead = -1; bCursor = 0; limit = 0; }
Source:
void validateFileDetails(FormDataContentDisposition fileDetail) { FileValidator validator = new FileValidator(); boolean validName = validator.isValidFileName("validating uploaded file name", fileDetail.getFileName(), true); if (!validName) { throw new IllegalArgumentException("File name is invalid"); } boolean validSize = validator.getMaxFileUploadSize() >= fileDetail.getSize(); if (!validSize) { throw new IllegalArgumentException("File size is invalid. Max size is: " + validator.getMaxFileUploadSize()/1000000 + " MB"); } }

Target:
protected void validateFileDetails(FormDataContentDisposition fileDetail) { FileValidator validator = new FileValidator(); boolean validName = validator.isValidFileName("validating uploaded file name", fileDetail.getFileName(), true); if (!validName) { throw new IllegalArgumentException("File name is invalid"); } boolean validSize = validator.getMaxFileUploadSize() >= fileDetail.getSize(); if (!validSize) { throw new IllegalArgumentException("File size is invalid. Max size is: " + validator.getMaxFileUploadSize()/1000000 + " MB"); } }
Source:
public synchronized DataSize getTotalPendingSize() { return new DataSize(pendingPages.stream().mapToLong(DataSize::toBytes).sum(), BYTE); }

Target:
public synchronized long getTotalPendingSize() { return pendingPageSizesInBytes.stream().mapToLong(Long::longValue).sum(); }
Source:
private boolean userRequestedSpecificFile(MIBreakpoint miBpt) { assert isFunctionBreakpoint(miBpt); String originalLocation = miBpt.getOriginalLocation(); boolean userRequestedSpecificFile = originalLocation != null && originalLocation.contains(":"); return userRequestedSpecificFile; }

Target:
private boolean userRequestedSpecificFile(MIBreakpoint miBpt) { assert isFunctionBreakpoint(miBpt); String originalLocation = miBpt.getOriginalLocation(); return originalLocation != null && originalLocation.contains(":"); }
Source:
private boolean areNetworksValid(QualifiedNetworks networks) { if (networks.qualifiedNetworks == null) { return true; } for (int network : networks.qualifiedNetworks) { if (!ACCESS_NETWORK_TRANSPORT_TYPE_MAP.containsKey(network)) { return false; } } return true; }

Target:
private static boolean areNetworksValid(QualifiedNetworks networks) { if (networks.qualifiedNetworks == null) { return false; } for (int network : networks.qualifiedNetworks) { if (!ACCESS_NETWORK_TRANSPORT_TYPE_MAP.containsKey(network)) { return false; } } return true; }
Source:
public int getGarbageSizeUpTo(long addressUpTo) { return streamIdToGarbageMap.values().stream() .flatMap(multiSMRGarbage -> multiSMRGarbage.values().stream()) .map(smrRecordGarbage -> smrRecordGarbage.getSmrEntrySize()) .reduce(0, (a, b) -> a + b); }

Target:
public int getGarbageSizeUpTo(long addressUpTo) { return streamIdToGarbageMap.values().stream() .flatMap(multiSMRGarbage -> multiSMRGarbage.values().stream()) .map(smrRecordGarbage -> smrRecordGarbage.getGarbageSizeUpTo(addressUpTo)) .reduce(0, (a, b) -> a + b); }
Source:
public void run_cukes() { runtime.run(); if (!runtime.getErrors().isEmpty()) { throw new RuntimeException(runtime.getErrors().get(0)); } }

Target:
public void run_cukes() { runtime.run(); if (!runtime.getErrors().isEmpty()) { throw new CucumberException(runtime.getErrors().get(0)); } }
Source:
public boolean adjustSelection(final SelectionExtension direction, final boolean isShiftKeyDown) { final boolean selectionChanged = super.adjustSelection(direction, isShiftKeyDown); scenarioGridPanel.signalRightPanelNoHeaderCellSelected(); if (getModel().getSelectedHeaderCells().size() > 0) { final GridData.SelectedCell cell = getModel().getSelectedHeaderCells().get(0); final int uiColumnIndex = ColumnIndexUtilities.findUiColumnIndex(getModel().getColumns(), cell.getColumnIndex()); final int uiRowIndex = cell.getRowIndex(); setSelectedColumnAndHeader(uiRowIndex, uiColumnIndex); final GridColumn column = getModel().getColumns().get(uiColumnIndex); if (uiRowIndex > 0 && column instanceof ScenarioGridColumn) { final EnableRightPanelEvent enableRightPanelEvent = enableRightPanelEvent((ScenarioGridColumn) column, cell, uiColumnIndex); scenarioGridPanel.signalRightPanelHeaderCellSelected(enableRightPanelEvent); } } return selectionChanged; }

Target:
public boolean adjustSelection(final SelectionExtension direction, final boolean isShiftKeyDown) { final boolean selectionChanged = super.adjustSelection(direction, isShiftKeyDown); signalRightPanelAboutSelectedHeaderCells(); return selectionChanged; }
Source:
public void testMergeSimilarSegmentsWithoutRefitting() { final boolean doRefit = false; final JavaSparkContext ctx = SparkContextFactory.getTestSparkContext(); LoggingUtils.setLoggingLevel(Log.LogLevel.INFO); final String tempDir = publicTestDir + "similar-segment-test-without-refitting"; final File tempDirFile = createTempDir(tempDir); final Genome genome = new Genome(COVERAGES_FILE, TUMOR_ALLELIC_COUNTS_FILE, SAMPLE_NAME); final SegmentedModel segmentedModel = new SegmentedModel(SEGMENT_FILE, genome); final ACNVModeller modeller = new ACNVModeller(segmentedModel, NUM_SAMPLES, NUM_BURN_IN, NUM_SAMPLES, NUM_BURN_IN, ctx); Assert.assertTrue(modeller.isModelFit()); int prevNumSegments; for (int numIterations = 1; numIterations <= MAX_SIMILAR_SEGMENT_MERGE_ITERATIONS; numIterations++) { prevNumSegments = modeller.getACNVModeledSegments().size(); modeller.performSimilarSegmentMergingIteration(INTERVAL_THRESHOLD, INTERVAL_THRESHOLD, doRefit); if (modeller.getACNVModeledSegments().size() == prevNumSegments) { break; } } Assert.assertTrue(!modeller.isModelFit()); final File finalModeledSegmentsFile = new File(tempDirFile.getAbsolutePath() + "/test-" + FINAL_SEG_FILE_TAG + ".seg"); modeller.writeACNVModeledSegmentFile(finalModeledSegmentsFile); Assert.assertTrue(modeller.isModelFit()); final int expectedNumberOfSegments = 31; final List<SimpleInterval> segmentsResult = SegmentUtils.readIntervalsFromSegmentFile(finalModeledSegmentsFile); Assert.assertEquals(segmentsResult.size(), expectedNumberOfSegments); }

Target:
public void testMergeSimilarSegmentsWithoutRefitting() { final boolean doRefit = false; final JavaSparkContext ctx = SparkContextFactory.getTestSparkContext(); LoggingUtils.setLoggingLevel(Log.LogLevel.INFO); final String tempDir = publicTestDir + "similar-segment-test-without-refitting"; final File tempDirFile = createTempDir(tempDir); final Genome genome = new Genome(COVERAGES_FILE, TUMOR_ALLELIC_COUNTS_FILE, SAMPLE_NAME); final SegmentedModel segmentedModel = new SegmentedModel(SEGMENT_FILE, genome); final ACNVModeller modeller = new ACNVModeller(segmentedModel, NUM_SAMPLES, NUM_BURN_IN, NUM_SAMPLES, NUM_BURN_IN, ctx); Assert.assertTrue(modeller.isModelFit()); int prevNumSegments; for (int numIterations = 1; numIterations <= MAX_SIMILAR_SEGMENT_MERGE_ITERATIONS; numIterations++) { prevNumSegments = modeller.getACNVModeledSegments().size(); modeller.performSimilarSegmentMergingIteration(INTERVAL_THRESHOLD, INTERVAL_THRESHOLD, doRefit); if (modeller.getACNVModeledSegments().size() == prevNumSegments) { break; } } Assert.assertTrue(!modeller.isModelFit()); final File finalModeledSegmentsFile = new File(tempDirFile.getAbsolutePath() + "/test-" + FINAL_SEG_FILE_TAG + ".seg"); modeller.writeACNVModeledSegmentFile(finalModeledSegmentsFile); Assert.assertTrue(modeller.isModelFit()); final List<SimpleInterval> segmentsResult = SegmentUtils.readIntervalsFromSegmentFile(finalModeledSegmentsFile); Assert.assertEquals(segmentsResult.size(), SEGMENTS_TRUTH.size(), DELTA_NUM_SEGMENTS_WITHOUT_REFITTING); }