auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void shouldSaveProcess() throws Exception { Process parent = new Process(); parent.setTitle("Parent"); Process process = new Process(); process.setTitle("Child"); process.setParent(parent); parent.getChildren().add(process); processService.save(process); Process foundProcess = processService.getById(process.getId()); assertEquals("Child process was not found in database!", "Child", foundProcess.getTitle()); assertEquals("Parent process was not assigned to child!", "Parent", process.getParent().getTitle()); Integer parentId = foundProcess.getParent().getId(); processService.remove(parentId); }

Target:
public void shouldSaveProcess() throws Exception { Process parent = new Process(); parent.setTitle("Parent"); Process process = new Process(); process.setTitle("Child"); process.setParent(parent); parent.getChildren().add(process); processService.save(process); Process foundProcess = processService.getById(process.getId()); Process foundParent = foundProcess.getParent(); assertEquals("Child process was not found in database!", "Child", foundProcess.getTitle()); assertEquals("Parent process was not assigned to child!", "Parent", foundParent.getTitle()); foundParent.getChildren().clear(); foundProcess.setParent(null); processService.remove(foundProcess); processService.remove(foundParent.getId()); }
Source:
public boolean isExist(KEY key) throws IOException { if (cacheCleanupPolicy == TableCacheImpl.CacheCleanupPolicy.NEVER) { return isExistForCleanupPolicyNever(key); } return isExistForCleanupPolicyNever(key) || rawTable.isExist(codecRegistry.asRawData(key)); }

Target:
public boolean isExist(KEY key) throws IOException { CacheResult<CacheValue<VALUE>> cacheResult = cache.lookup(new CacheKey<>(key)); if (cacheResult.getCacheStatus() == EXISTS) { return true; } else if (cacheResult.getCacheStatus() == NOT_EXIST) { return false; } else { return rawTable.isExist(codecRegistry.asRawData(key)); } }
Source:
public CompletableFuture<List<Map<Address, InternalCacheEntry<K, V>>>> getAllReplicasForSegment(int segmentId, LocalizedCacheTopology topology) { return requestMap.computeIfAbsent(segmentId, id -> new SegmentRequest(id, topology)).requestState(); }

Target:
public synchronized CompletableFuture<List<Map<Address, CacheEntry<K, V>>>> getAllReplicasForSegment(int segmentId, LocalizedCacheTopology topology) { return requestMap.computeIfAbsent(segmentId, id -> new SegmentRequest(id, topology)).requestState(); }
Source:
public DatastreamEvent next() throws SQLException { if (!hasNext()) { throw new NoSuchElementException("No more elements in this iterator."); } try { Map<String, String> rowValues = new HashMap<>(); Map<String, String> keyValues = new HashMap<>(); for (ColumnInfo column : _columnInfo) { rowValues.put(column.getColumnName(), _rs.getString(column.getColumnName())); if (column.isKey()) { keyValues.put(column.getColumnName(), _rs.getString(column.getColumnName())); } } return buildDatastreamEvent(System.currentTimeMillis(), _source.getDatabaseName(), _source.getTableName(), JsonUtils.toJson(keyValues), JsonUtils.toJson(rowValues)); } finally { _next = false; } }

Target:
public DatastreamEvent next() throws SQLException { if (!_isEof || _closed) { String msg = "TableReader needs to be closed or it is closed already."; LOG.warn(msg); throw new DatastreamRuntimeException(msg); } if (!hasNext()) { throw new NoSuchElementException("No more elements in this iterator."); } try { Map<String, String> rowValues = new HashMap<>(); Map<String, String> keyValues = new HashMap<>(); for (ColumnInfo column : _columnInfo) { rowValues.put(column.getColumnName(), _rs.getString(column.getColumnName())); if (column.isKey()) { keyValues.put(column.getColumnName(), _rs.getString(column.getColumnName())); } } return buildDatastreamEvent(System.currentTimeMillis(), _source.getDatabaseName(), _source.getTableName(), JsonUtils.toJson(keyValues), JsonUtils.toJson(rowValues)); } finally { _next = false; } }
Source:
public void onTaskRefreshedEvent(@Observes final TaskRefreshedEvent event) { if (isSameTaskFromEvent().test(event)) { taskService.call( (TaskSummary task) -> { if (task != null) { setTaskDetails(translationService.format(task.getStatus()), task.getDescription(), task.getActualOwner(), task.getExpirationTime(), String.valueOf(task.getPriority()), task.getProcessInstanceId(), task.getProcessId(), task.getWorkItemId(), task.getSlaCompliance()); } }).getTaskWithSLA(getServerTemplateId(), getContainerId(), getTaskId(), view.getWorkItemId()); } }

Target:
public void onTaskRefreshedEvent(@Observes final TaskRefreshedEvent event) { if (isSameTaskFromEvent().test(event)) { taskService.call( (TaskSummary task) -> { if (task != null) { setTaskDetails(translationService.format(task.getStatus()), task.getDescription(), task.getActualOwner(), task.getExpirationTime(), String.valueOf(task.getPriority()), task.getProcessInstanceId(), task.getProcessId(), task.getSlaCompliance()); } }).getTask(getServerTemplateId(), getContainerId(), getTaskId()); } }
Source:
public static <T> Set<T> load(Class<T> contract, ClassLoader... loaders) { Map<String, T> services = new LinkedHashMap<>(); if (loaders.length == 0) { try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract); addServices( loadedServices, services ); } catch (Exception e) { } } else { for (ClassLoader loader : loaders) { if (loader == null) continue; try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract, loader); addServices( loadedServices, services ); } catch (Exception e) { } } } addOsgiServices( contract, services ); if (services.isEmpty()) { LOG.debugf("No service impls found: %s", contract.getSimpleName()); } return new LinkedHashSet<>(services.values()); }

Target:
public static <T> Collection<T> load(Class<T> contract, ClassLoader... loaders) { Map<String, T> services = new LinkedHashMap<>(); if (loaders.length == 0) { try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract); addServices( loadedServices, services ); } catch (Exception e) { } } else { for (ClassLoader loader : loaders) { if (loader == null) continue; try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract, loader); addServices( loadedServices, services ); } catch (Exception e) { } } } addOsgiServices( contract, services ); if (services.isEmpty()) { LOG.debugf("No service impls found: %s", contract.getSimpleName()); } return services.values(); }
Source:
public Attributes getAttributes() { if (attrs != null) return attrs; if (attributesNodeProvider == null) { throw new IllegalStateException( "The tree walk should have one AttributesNodeProvider set in order to compute the git attributes."); } WorkingTreeIterator workingTreeIterator = getTree(WorkingTreeIterator.class); DirCacheIterator dirCacheIterator = getTree(DirCacheIterator.class); CanonicalTreeParser other = getTree(CanonicalTreeParser.class); if (workingTreeIterator == null && dirCacheIterator == null && other == null) { return new Attributes(); } String path = currentHead.getEntryPathString(); final boolean isDir = FileMode.TREE.equals(currentHead.mode); Attributes attributes = new Attributes(); try { AttributesNode globalNodeAttr = attributesNodeProvider .getGlobalAttributesNode(); AttributesNode infoNodeAttr = attributesNodeProvider .getInfoAttributesNode(); AttributesNode rootNodeAttr = getRootAttributesNode(operationType, workingTreeIterator, dirCacheIterator, other); macroExpander.updateWhenDifferent(globalNodeAttr, infoNodeAttr, rootNodeAttr); if (infoNodeAttr != null) { infoNodeAttr.getAttributes(macroExpander, path, isDir, attributes); } getPerDirectoryEntryAttributes(path, isDir, operationType, workingTreeIterator, dirCacheIterator, other, attributes); if (globalNodeAttr != null) { globalNodeAttr.getAttributes(macroExpander, path, isDir, attributes); } } catch (IOException e) { throw new JGitInternalException("Error while parsing attributes", e); } for (Attribute a : attributes.getAll()) { if (a.getState() == State.UNSPECIFIED) attributes.remove(a.getKey()); } return attributes; }

Target:
public Attributes getAttributes() { if (attrs != null) return attrs; if (attributesNodeProvider == null) { throw new IllegalStateException( "The tree walk should have one AttributesNodeProvider set in order to compute the git attributes."); } WorkingTreeIterator workingTreeIterator = getCurrentTreeNode( WorkingTreeIterator.class); DirCacheIterator dirCacheIterator = getCurrentTreeNode( DirCacheIterator.class); CanonicalTreeParser other = getCurrentTreeNode( CanonicalTreeParser.class); if (workingTreeIterator == null && dirCacheIterator == null && other == null) { return new Attributes(); } String path = currentHead.getEntryPathString(); final boolean isDir = FileMode.TREE.equals(currentHead.mode); Attributes attributes = new Attributes(); try { if (macroExpander == null) { AttributesNode globalNode = attributesNodeProvider .getGlobalAttributesNode(); AttributesNode infoNode = attributesNodeProvider .getInfoAttributesNode(); AttributesNode rootNode = getRootAttributesNode(); macroExpander = new MacroExpander(globalNode, infoNode, rootNode); } macroExpander.mergeInfoAttributes(path, isDir, attributes); getPerDirectoryEntryAttributes(path, isDir, operationType, workingTreeIterator, dirCacheIterator, other, attributes); macroExpander.mergeGlobalAttributes(path, isDir, attributes); } catch (IOException e) { throw new JGitInternalException("Error while parsing attributes", e); } for (Attribute a : attributes.getAll()) { if (a.getState() == State.UNSPECIFIED) attributes.remove(a.getKey()); } return attributes; }
Source:
public boolean validate() { getDescription().validateEntity(new IValidation[] { new SpecialAsciiI18NOrNoneValidation(), new LengthValidation(BusinessEntitiesDefinitions.DISK_DESCRIPTION_MAX_SIZE)}); Collection<IValidation> diskAliasValidation = new ArrayList<>(Arrays.asList( new I18NNameValidation(), new LengthValidation(BusinessEntitiesDefinitions.DISK_ALIAS_MAX_SIZE))); if (getVm() == null) { diskAliasValidation.add(new NotEmptyValidation()); } getAlias().validateEntity(diskAliasValidation.toArray(new IValidation[diskAliasValidation.size()])); StoragePool dataCenter = getDataCenter().getSelectedItem(); if (dataCenter != null && dataCenter.getQuotaEnforcementType() == QuotaEnforcementTypeEnum.HARD_ENFORCEMENT) { getQuota().validateSelectedItem(new IValidation[] { new NotEmptyQuotaValidation() }); } if (getCinderVolumeType().getIsAvailable()) { getCinderVolumeType().validateSelectedItem(new IValidation[]{new NotEmptyValidation()}); } return getAlias().getIsValid() && getDescription().getIsValid() && getQuota().getIsValid() && getDiskInterface().getIsValid() && getCinderVolumeType().getIsValid(); }

Target:
public boolean validate() { getDescription().validateEntity(new IValidation[] { new SpecialAsciiI18NOrNoneValidation(), new LengthValidation(BusinessEntitiesDefinitions.DISK_DESCRIPTION_MAX_SIZE)}); getAlias().validateEntity(getDiskAliasValidations()); StoragePool dataCenter = getDataCenter().getSelectedItem(); if (dataCenter != null && dataCenter.getQuotaEnforcementType() == QuotaEnforcementTypeEnum.HARD_ENFORCEMENT) { getQuota().validateSelectedItem(new IValidation[] { new NotEmptyQuotaValidation() }); } if (getCinderVolumeType().getIsAvailable()) { getCinderVolumeType().validateSelectedItem(new IValidation[]{new NotEmptyValidation()}); } return getAlias().getIsValid() && getDescription().getIsValid() && getQuota().getIsValid() && getDiskInterface().getIsValid() && getCinderVolumeType().getIsValid(); }
Source:
private void updateStatus(final String itemName, final ISYBindingConfig config) { if (this.logger.isDebugEnabled()) { this.logger.debug("updateStatus({},{}) is called!", itemName, config); } if (this.insteonClient != null && this.insteonClient.isISYReady()) { try { UDNode node = this.insteonClient.getNodes().get( config.getAddress()); if (node == null) { node = this.insteonClient.getGroups().get( config.getAddress()); } if (node != null) { Object value = this.insteonClient.getCurrValue(node, config .getControlCommand().name()); UDControl control = new UDControl(); control.name = config.getControlCommand().name(); onModelChanged(control, value, node); } } catch (Exception ex) { this.logger.error("Failed to update status of " + itemName, ex); } } else { if (this.logger.isInfoEnabled()) { this.logger.info("ISY is not ready yet"); } } }

Target:
private void updateStatus(final String itemName, final ISYBindingConfig config) { this.logger.debug("updateStatus({},{}) is called!", itemName, config); if (this.insteonClient != null && this.insteonClient.isISYReady()) { try { UDNode node = this.insteonClient.getNodes().get( config.getAddress()); if (node == null) { node = this.insteonClient.getGroups().get( config.getAddress()); } if (node != null) { Object value = this.insteonClient.getCurrValue(node, config .getControlCommand().name()); UDControl control = new UDControl(); control.name = config.getControlCommand().name(); onModelChanged(control, value, node); } } catch (Exception ex) { this.logger.error("Failed to update status of '{}' ", itemName, ex); } } else { this.logger.info("ISY is not ready yet"); } }
Source:
public void shouldThrowTimeoutExceptionWithCompletionStage() throws Exception { Duration timeoutDuration = Duration.ofSeconds(1); TimeLimiter timeLimiter = TimeLimiter.of(timeoutDuration); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); Supplier<CompletionStage<Integer>> supplier = () -> CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1500); } catch (InterruptedException e) { } return 0; }); CompletionStage<Integer> decorated = TimeLimiter.decorateCompletionStage(timeLimiter, scheduler, supplier).get(); Try<Integer> decoratedResult = Try.ofCallable(() -> decorated.toCompletableFuture().get()); assertThat(decoratedResult.isFailure()).isTrue(); assertThat(decoratedResult.getCause()).isInstanceOf(ExecutionException.class) .hasCauseExactlyInstanceOf(TimeoutException.class); }

Target:
public void shouldThrowTimeoutExceptionWithCompletionStage() throws Exception { Duration timeoutDuration = Duration.ofMillis(300); TimeLimiter timeLimiter = TimeLimiter.of(timeoutDuration); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); Supplier<CompletionStage<Integer>> supplier = () -> CompletableFuture.supplyAsync(() -> { try { Thread.sleep(500); } catch (InterruptedException e) { } return 0; }); CompletionStage<Integer> decorated = TimeLimiter.decorateCompletionStage(timeLimiter, scheduler, supplier).get(); Try<Integer> decoratedResult = Try.ofCallable(() -> decorated.toCompletableFuture().get()); assertThat(decoratedResult.isFailure()).isTrue(); assertThat(decoratedResult.getCause()).isInstanceOf(ExecutionException.class) .hasCauseExactlyInstanceOf(TimeoutException.class); }
Source:
public void testAssetsToImport() throws Exception { final String PAGE_ID = "page"; final String DS_CSV = "ds.csv"; final String DS = "ds.dset"; final String DS_CONTENT = "TEST_CONTENT"; final String DS_NAME = "test_dataset"; final String PAGE = PAGE_ID + "/perspective_layout"; final String PAGE_PLUGIN = PAGE_ID + "/perspective_layout.plugin"; DataSetDef dataSetDef = mock(DataSetDef.class); when(dataSetDef.isPublic()).thenReturn(true); when(dataSetDef.getName()).thenReturn(DS_NAME); when(dataSetDefJSONMarshaller.fromJson(DS_CONTENT)).thenReturn(dataSetDef); createFile(datasetsFS, DS, DS_CONTENT); createFile(datasetsFS, DS_CSV, ""); createFile(perspectivesFS, PAGE, ""); createFile(perspectivesFS, PAGE_PLUGIN, ""); ExportInfo assetsToExport = dataTransferServices.exportInfo(); assertEquals(1, assetsToExport.getDatasetsDefinitions().size()); assertEquals(DS_NAME, assetsToExport.getDatasetsDefinitions().get(0).getName()); assertEquals(1, assetsToExport.getPages().size()); assertEquals(PAGE_ID, assetsToExport.getPages().get(0)); cleanFileSystems(); }

Target:
public void testAssetsToImport() throws Exception { final String PAGE_ID = "page"; final String DS_CSV = "ds.csv"; final String DS = "ds.dset"; final String DS_CONTENT = "TEST_CONTENT"; final String DS_NAME = "test_dataset"; final String PAGE = PAGE_ID + "/perspective_layout"; final String PAGE_PLUGIN = PAGE_ID + "/perspective_layout.plugin"; DataSetDef dataSetDef = mock(DataSetDef.class); when(dataSetDef.isPublic()).thenReturn(true); when(dataSetDef.getName()).thenReturn(DS_NAME); when(dataSetDefJSONMarshaller.fromJson(DS_CONTENT)).thenReturn(dataSetDef); createFile(datasetsFS, DS, DS_CONTENT); createFile(datasetsFS, DS_CSV, ""); createFile(perspectivesFS, PAGE, ""); createFile(perspectivesFS, PAGE_PLUGIN, ""); ExportInfo exportInfo = dataTransferServices.exportInfo(); assertEquals(1, exportInfo.getDatasetsDefinitions().size()); assertEquals(DS_NAME, exportInfo.getDatasetsDefinitions().get(0).getName()); assertEquals(1, exportInfo.getPages().size()); assertEquals(PAGE_ID, exportInfo.getPages().get(0)); cleanFileSystems(); }
Source:
public StateItem(RGB stateColor, String stateString) { fStyleMap = new HashMap<>(); fReadOnlyStyleMap = Collections.unmodifiableMap(fStyleMap); fStyleMap.put(ITimeEventStyleStrings.fillStyle(), ITimeEventStyleStrings.solidColorFillStyle()); fStyleMap.put(ITimeEventStyleStrings.fillColor(), stateColor); fStyleMap.put(ITimeEventStyleStrings.label(), stateString); }

Target:
public StateItem(RGB stateColor, String stateString) { int stateColorInt = stateColor.red << 24 | stateColor.green << 16 | stateColor.blue << 8 | 0xff; fStyleMap = new HashMap<>(); fReadOnlyStyleMap = Collections.unmodifiableMap(fStyleMap); fStyleMap.put(ITimeEventStyleStrings.fillStyle(), ITimeEventStyleStrings.solidColorFillStyle()); fStyleMap.put(ITimeEventStyleStrings.fillColor(), stateColorInt); fStyleMap.put(ITimeEventStyleStrings.label(), stateString); }
Source:
private static boolean validateRemote(String node, String target, String name, CommandLine cmd) throws InterruptedException { System.out.format("Validating %s environment on %s...%n", target, node); if (!CommonUtils.isAddressReachable(node, 22)) { System.err.format("Unable to reach ssh port 22 on node %s.%n", node); return false; } String argStr = String.join(" ", cmd.getArgs()); String homeDir = InstancedConfiguration.defaults().get(PropertyKey.HOME); String remoteCommand = String.format( "%s/bin/alluxio validateEnv %s %s %s", homeDir, target, name == null ? "" : name, argStr); String localCommand = String.format( "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand); String[] command = {"bash", "-c", localCommand}; try { ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); builder.redirectOutput(ProcessBuilder.Redirect.INHERIT); builder.redirectInput(ProcessBuilder.Redirect.INHERIT); Process process = builder.start(); process.waitFor(); return process.exitValue() == 0; } catch (IOException e) { System.err.format("Unable to validate on node %s: %s.%n", node, e.getMessage()); return false; } }

Target:
private static boolean validateRemote(String node, String target, String name, CommandLine cmd) throws InterruptedException { System.out.format("Validating %s environment on %s...%n", target, node); if (!CommonUtils.isAddressReachable(node, 22)) { System.err.format("Unable to reach ssh port 22 on node %s.%n", node); return false; } String argStr = String.join(" ", cmd.getArgs()); String homeDir = CONF.get(PropertyKey.HOME); String remoteCommand = String.format( "%s/bin/alluxio validateEnv %s %s %s", homeDir, target, name == null ? "" : name, argStr); String localCommand = String.format( "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand); String[] command = {"bash", "-c", localCommand}; try { ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); builder.redirectOutput(ProcessBuilder.Redirect.INHERIT); builder.redirectInput(ProcessBuilder.Redirect.INHERIT); Process process = builder.start(); process.waitFor(); return process.exitValue() == 0; } catch (IOException e) { System.err.format("Unable to validate on node %s: %s.%n", node, e.getMessage()); return false; } }
Source:
public OperatorImplGraph(StreamGraphImpl streamGraph, Config config, TaskContext context, Clock clock) { this.clock = clock; TaskContextImpl taskContext = (TaskContextImpl) context; Map<SystemStream, Integer> producerTaskCounts = hasIntermediateStreams(streamGraph) ? getProducerTaskCountForIntermediateStreams(getStreamToConsumerTasks(taskContext.getJobModel()), getIntermediateToInputStreams(streamGraph)) : Collections.EMPTY_MAP; producerTaskCounts.forEach((stream, count) -> { LOG.info("{} has producer tasks.", stream, count); }); taskContext.registerObject(EndOfStreamStates.class.getName(), new EndOfStreamStates(context.getSystemStreamPartitions(), producerTaskCounts)); taskContext.registerObject(WatermarkStates.class.getName(), new WatermarkStates(context.getSystemStreamPartitions(), producerTaskCounts)); streamGraph.getInputOperators().forEach((streamSpec, inputOpSpec) -> { SystemStream systemStream = new SystemStream(streamSpec.getSystemName(), streamSpec.getPhysicalName()); InputOperatorImpl inputOperatorImpl = (InputOperatorImpl) createAndRegisterOperatorImpl(null, inputOpSpec, config, context); this.inputOperators.put(systemStream, inputOperatorImpl); }); }

Target:
public OperatorImplGraph(StreamGraphImpl streamGraph, Config config, TaskContext context, Clock clock) { this.clock = clock; TaskContextImpl taskContext = (TaskContextImpl) context; Map<SystemStream, Integer> producerTaskCounts = hasIntermediateStreams(streamGraph) ? getProducerTaskCountForIntermediateStreams(getStreamToConsumerTasks(taskContext.getJobModel()), getIntermediateToInputStreamsMap(streamGraph)) : Collections.EMPTY_MAP; producerTaskCounts.forEach((stream, count) -> { LOG.info("{} has producer tasks.", stream, count); }); taskContext.registerObject(EndOfStreamStates.class.getName(), new EndOfStreamStates(context.getSystemStreamPartitions(), producerTaskCounts)); taskContext.registerObject(WatermarkStates.class.getName(), new WatermarkStates(context.getSystemStreamPartitions(), producerTaskCounts)); streamGraph.getInputOperators().forEach((streamSpec, inputOpSpec) -> { SystemStream systemStream = new SystemStream(streamSpec.getSystemName(), streamSpec.getPhysicalName()); InputOperatorImpl inputOperatorImpl = (InputOperatorImpl) createAndRegisterOperatorImpl(null, inputOpSpec, systemStream, config, context); this.inputOperators.put(systemStream, inputOperatorImpl); }); }
Source:
public void tearDownDocker() { tdc.killAndRemoveContainer(); }

Target:
public void tearDownDocker() throws Exception { client.killAndRemoveContainer(); }
Source:
public void execute(IProgressMonitor m) throws CoreException { IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor pm) throws CoreException { preExecute(pm); IProject[] validProjects = ProjectUtil .getValidOpenProjects(repository); pm.beginTask(NLS.bind( CoreText.BranchOperation_performingBranch, target), 1); CheckoutCommand co = new Git(repository).checkout(); co.setName(target); try { co.call(); } catch (JGitInternalException e) { if(e.getCause() instanceof CheckoutConflictException) { return; } else { throw new CoreException(Activator.error(e.getMessage(), e)); } } catch (GitAPIException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } finally { BranchOperation.this.result = co.getResult(); } if (result.getStatus() == Status.NONDELETED) retryDelete(result.getUndeletedList()); pm.worked(1); ProjectUtil.refreshValidProjects(validProjects, delete, new SubProgressMonitor(pm, 1)); pm.worked(1); postExecute(pm); pm.done(); } }; ResourcesPlugin.getWorkspace().run(action, monitor); }

Target:
public void execute(IProgressMonitor m) throws CoreException { IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor pm) throws CoreException { preExecute(pm); IProject[] validProjects = ProjectUtil .getValidOpenProjects(repository); pm.beginTask(NLS.bind( CoreText.BranchOperation_performingBranch, target), 1); CheckoutCommand co = new Git(repository).checkout(); co.setName(target); try { co.call(); } catch (JGitInternalException e) { if (e.getCause() instanceof CheckoutConflictException) return; else throw new CoreException(Activator.error(e.getMessage(), e)); } catch (GitAPIException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } finally { BranchOperation.this.result = co.getResult(); } if (result.getStatus() == Status.NONDELETED) retryDelete(result.getUndeletedList()); pm.worked(1); ProjectUtil.refreshValidProjects(validProjects, delete, new SubProgressMonitor(pm, 1)); pm.worked(1); postExecute(pm); pm.done(); } }; ResourcesPlugin.getWorkspace().run(action, monitor); }
Source:
public Optional<ServiceInstance> getLocalInstance(String serviceName) { return Optional.ofNullable(serviceInstances.values().stream() .filter(ServiceInstance::isLocal) .filter(serviceInstance -> serviceInstance.serviceName().equals(serviceName)) .findFirst() .orElse(null)); }

Target:
public Optional<ServiceInstance> getLocalInstance(String serviceName) { return serviceInstances.values().stream() .filter(ServiceInstance::isLocal) .filter(serviceInstance -> serviceInstance.serviceName().equals(serviceName)) .findFirst(); }
Source:
public Integer performTask() throws Throwable { String elUrl = WikipediaApp.getInstance().getSslFailCount() < 2 ? EVENTLOG_URL : EVENTLOG_URL.replace("https", "http"); String dataURL = Uri.parse(elUrl) .buildUpon().query(data.toString()) .build().toString(); Log.d(Funnel.ANALYTICS_TAG, "hitting " + dataURL); return HttpRequest.get(dataURL).header("User-Agent", userAgent).code(); }

Target:
public Integer performTask() throws Throwable { String elUrl = WikipediaApp.getInstance().getSslFailCount() < 2 ? EVENTLOG_URL : EVENTLOG_URL.replace("https", "http"); String dataURL = Uri.parse(elUrl) .buildUpon().query(data.toString()) .build().toString(); return HttpRequest.get(dataURL).header("User-Agent", userAgent).code(); }
Source:
public boolean hasTextMaxAngle() throws MBFormatException { return parse.isPropertyDefined(layout, "text-max-angle"); }

Target:
private boolean hasTextMaxAngle() throws MBFormatException { return parse.isPropertyDefined(layout, "text-max-angle"); }
Source:
private Response.ResponseBuilder calculateContentDisposition( Response.ResponseBuilder response, IAsyncReportState state ) { String extension = MimeHelper.getExtension( state.getMimeType() ); String path = state.getPath(); String fileName = path.substring( path.lastIndexOf( "/" ) + 1, path.lastIndexOf( "." ) ); if ( fileName == null || fileName.isEmpty() ) { fileName = "content"; } String disposition = "inline; filename*=UTF-8''" + RepositoryPathEncoder .encode( RepositoryPathEncoder.encodeRepositoryPath( fileName + extension ) ); response.header( "Content-Disposition", disposition ); response.header( "Content-Description", fileName ); return response; }

Target:
private Response.ResponseBuilder calculateContentDisposition( Response.ResponseBuilder response, IAsyncReportState state ) { org.pentaho.reporting.libraries.base.util.IOUtils utils = org.pentaho.reporting.libraries .base.util.IOUtils.getInstance(); String extension = MimeHelper.getExtension( state.getMimeType() ); String path = state.getPath(); String reportExtension = utils.stripFileExtension( path ); String fileName = utils.getFileName( path ); if ( fileName == null || fileName.isEmpty() ) { fileName = "content"; } String disposition = "inline; filename*=UTF-8''" + RepositoryPathEncoder .encode( RepositoryPathEncoder.encodeRepositoryPath( fileName + extension ) ); response.header( "Content-Disposition", disposition ); response.header( "Content-Description", fileName + reportExtension ); return response; }
Source:
public void testVisitDWithin() throws Exception { getRootJsonFilterNode("spatial-distance-ops", "DWithin.json").accept(visitor); forElement(visitor.getResult()) .withBinding(FilterType.class) .forElement(FilterType::getSpatialOps) .withBinding(DistanceBufferType.class) .verifyExpressionOrAny(DistanceBufferType::getExpressionOrAny) .withData("anyGeo", "WKT()"); }

Target:
public void testVisitDWithin() throws Exception { getRootJsonFilterNode("spatial-distance-ops", "DWithin.json").accept(visitor); forElement(visitor.getResult()) .withBinding(FilterType.class) .forElement(FilterType::getSpatialOps) .withBinding(DistanceBufferType.class) .verifyDistanceBuffer() .withDistance(123.45) .withData("anyGeo", "WKT()"); }
Source:
protected Direction columnDirection(ResultSet rs) throws SQLException { Direction columnDir = getColumnDirection(rs); if (columnDir == null) { throw new SQLException("Invalid column/parameter type"); } return columnDir; }

Target:
protected Direction columnDirection(ResultSet rs) throws SQLException { return requireNonNull(getColumnDirection(rs), "Invalid type for column/parameter " + getColumnName(rs)); }
Source:
public QuantityType<Time> getDuration() { if (start == null || end == null) { return null; } if (start.after(end)) { return new QuantityType<Time>(0, SmartHomeUnits.MINUTE); } long diff = end.getTimeInMillis() - start.getTimeInMillis(); return new QuantityType<Time>(diff / 60000, SmartHomeUnits.MINUTE); }

Target:
public QuantityType<Time> getDuration() { if (start == null || end == null) { return null; } if (start.after(end)) { return new QuantityType<Time>(0, SmartHomeUnits.MINUTE); } return new QuantityType<Time>(end.getTimeInMillis() - start.getTimeInMillis(), MILLI(SmartHomeUnits.SECOND)) .toUnit(SmartHomeUnits.MINUTE); }
Source:
public ContainerInfo getMatchingContainer(final long sizeRequired, String owner, Pipeline pipeline) { try { NavigableSet<ContainerID> containerIDs = pipelineManager.getContainersInPipeline(pipeline.getId()); if (containerIDs == null) { LOG.error("Container list is null for pipeline=", pipeline.getId()); return null; } containerIDs = getContainersForOwner(containerIDs, owner); if (containerIDs.size() < numContainerPerOwnerInPipeline) { synchronized (pipeline) { containerIDs = getContainersForOwner( pipelineManager.getContainersInPipeline(pipeline.getId()), owner); if (containerIDs.size() < numContainerPerOwnerInPipeline) { ContainerInfo containerInfo = containerStateManager.allocateContainer(pipelineManager, owner, pipeline); addContainerToDB(containerInfo); containerStateManager.updateLastUsedMap(pipeline.getId(), containerInfo.containerID(), owner); return containerInfo; } } } ContainerInfo containerInfo = containerStateManager.getMatchingContainer(sizeRequired, owner, pipeline.getId(), containerIDs); if (containerInfo == null) { synchronized (pipeline) { containerInfo = containerStateManager.allocateContainer(pipelineManager, owner, pipeline); addContainerToDB(containerInfo); containerStateManager.updateLastUsedMap(pipeline.getId(), containerInfo.containerID(), owner); } } else { containerStateManager.updateLastUsedMap(pipeline.getId(), containerInfo.containerID(), owner); } return containerInfo; } catch (Exception e) { LOG.warn("Container allocation failed for pipeline={} requiredSize={} {}", pipeline, sizeRequired, e); return null; } }

Target:
public ContainerInfo getMatchingContainer(final long sizeRequired, String owner, Pipeline pipeline) { try { NavigableSet<ContainerID> containerIDs = pipelineManager.getContainersInPipeline(pipeline.getId()); containerIDs = getContainersForOwner(containerIDs, owner); if (containerIDs.size() < numContainerPerOwnerInPipeline) { synchronized (pipeline) { containerIDs = getContainersForOwner( pipelineManager.getContainersInPipeline(pipeline.getId()), owner); if (containerIDs.size() < numContainerPerOwnerInPipeline) { ContainerInfo containerInfo = containerStateManager.allocateContainer(pipelineManager, owner, pipeline); addContainerToDB(containerInfo); containerStateManager.updateLastUsedMap(pipeline.getId(), containerInfo.containerID(), owner); return containerInfo; } } } ContainerInfo containerInfo = containerStateManager.getMatchingContainer(sizeRequired, owner, pipeline.getId(), containerIDs); if (containerInfo == null) { synchronized (pipeline) { containerInfo = containerStateManager.allocateContainer(pipelineManager, owner, pipeline); addContainerToDB(containerInfo); } } containerStateManager.updateLastUsedMap(pipeline.getId(), containerInfo.containerID(), owner); return containerInfo; } catch (Exception e) { LOG.warn("Container allocation failed for pipeline={} requiredSize={} {}", pipeline, sizeRequired, e); return null; } }
Source:
public void testSetup() { ZkClient zkClient = new ZkClient(testZkConnectionString, ZkConfig.DEFAULT_SESSION_TIMEOUT_MS, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS); ZkJobCoordinatorMetrics metrics = new ZkJobCoordinatorMetrics(new MetricsRegistryMap()); this.zkUtils = new ZkUtils(new ZkKeyBuilder("group1"), zkClient, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS, metrics); ZkClient zkClient1 = new ZkClient(testZkConnectionString, ZkConfig.DEFAULT_SESSION_TIMEOUT_MS, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS); this.zkUtils1 = new ZkUtils(new ZkKeyBuilder("group1"), zkClient1, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS, metrics); }

Target:
public void testSetup() { ZkClient zkClient = new ZkClient(testZkConnectionString, ZkConfig.DEFAULT_SESSION_TIMEOUT_MS, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS); this.zkUtils = new ZkUtils(new ZkKeyBuilder("group1"), zkClient, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS, new ZkJobCoordinatorMetrics(new NoOpMetricsRegistry())); ZkClient zkClient1 = new ZkClient(testZkConnectionString, ZkConfig.DEFAULT_SESSION_TIMEOUT_MS, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS); this.zkUtils1 = new ZkUtils(new ZkKeyBuilder("group1"), zkClient1, ZkConfig.DEFAULT_CONNECTION_TIMEOUT_MS, new ZkJobCoordinatorMetrics(new NoOpMetricsRegistry())); }
Source:
protected TypedString(String name) { this.name = ArgChecker.notNull(name, "name"); }

Target:
protected TypedString(String name) { this.name = ArgChecker.notEmpty(name, "name"); }
Source:
@Override public boolean isSampled(long ignoredTraceId) { long now = System.nanoTime(); long updateAt = nextReset.get(); long nanosUntilReset = -(now - updateAt); if (nanosUntilReset <= 0) { if (nextReset.compareAndSet(updateAt, updateAt + NANOS_PER_SECOND)) usage.set(0); return isSampled(ignoredTraceId); } int max = maxFunction.max(nanosUntilReset); int prev, next; do { prev = usage.get(); next = prev + 1; if (next > max) return false; } while (!usage.compareAndSet(prev, next)); return true; }

Target:
@Override public boolean isSampled(long ignoredTraceId) { long now = System.nanoTime(); long updateAt = nextReset.get(); long nanosUntilReset = -(now - updateAt); if (nanosUntilReset <= 0) { if (nextReset.compareAndSet(updateAt, now + NANOS_PER_SECOND)) usage.set(0); return isSampled(ignoredTraceId); } int max = maxFunction.max(nanosUntilReset); int prev, next; do { prev = usage.get(); next = prev + 1; if (next > max) return false; } while (!usage.compareAndSet(prev, next)); return true; }
Source:
private boolean hasEntryPoint(final Pattern52 pattern) { return pattern.getEntryPointName() != null && !pattern.getEntryPointName().trim().isEmpty(); }

Target:
private boolean hasEntryPoint(final Pattern52 pattern) { return !StringUtils.isEmpty(pattern.getEntryPointName()); }
Source:
public void updateUseHostCpuAvailability() { boolean clusterSupportsHostCpu = getCompatibilityVersion() != null; boolean nonMigratable = MigrationSupport.PINNED_TO_HOST == getModel().getMigrationMode().getSelectedItem(); boolean usingPpcArch = hostHasPpcArchitecture(); if (clusterSupportsHostCpu && nonMigratable && !usingPpcArch) { getModel().getHostCpu().setIsChangeable(true); } else { getModel().getHostCpu().setEntity(false); getModel().getHostCpu().setChangeProhibitionReason(constants.hosCPUUnavailable()); getModel().getHostCpu().setIsChangeable(false); } }

Target:
public void updateUseHostCpuAvailability() { boolean clusterSupportsHostCpu = getCompatibilityVersion() != null; boolean nonMigratable = MigrationSupport.PINNED_TO_HOST == getModel().getMigrationMode().getSelectedItem(); if (clusterSupportsHostCpu && nonMigratable && !clusterHasPpcArchitecture()) { getModel().getHostCpu().setIsChangeable(true); } else { getModel().getHostCpu().setEntity(false); getModel().getHostCpu().setChangeProhibitionReason(constants.hosCPUUnavailable()); getModel().getHostCpu().setIsChangeable(false); } }
Source:
private void populate() { final VBox toolsPane = new VBox(); final Text title = new TextWithStyle(tr("Tools"), TITLE_CSS_CLASS); toolsPane.getStyleClass().add(CONFIGURATION_PANE_CSS_CLASS); toolsPane.getChildren().add(title); final TilePane toolsContentPane = new TilePane(); toolsContentPane.setPrefColumns(3); toolsContentPane.getStyleClass().add("grid"); Button runExecutable = new Button(tr("Run executable")); runExecutable.getStyleClass().addAll("toolButton", "runExecutable"); runExecutable.setOnMouseClicked(event -> { this.lockAll(); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(tr("Choose executable…")); File containerDir = new File(this.container.getPath()); if (containerDir.canRead()) { fileChooser.setInitialDirectory(containerDir); } File file = fileChooser.showOpenDialog(this.getContent().getScene().getWindow()); if (file != null) { containerEngineController.runInContainer(container, file.getAbsolutePath(), this::unlockAll, e -> Platform.runLater(() -> new ErrorMessage("Error", e).show())); } else { this.unlockAll(); } }); this.lockableElements.add(runExecutable); toolsContentPane.getChildren().add(runExecutable); toolsPane.getChildren().addAll(toolsContentPane); this.setContent(toolsPane); }

Target:
private void populate() { final VBox toolsPane = new VBox(); final Text title = new TextWithStyle(tr("Tools"), TITLE_CSS_CLASS); toolsPane.getStyleClass().add(CONFIGURATION_PANE_CSS_CLASS); toolsPane.getChildren().add(title); final TilePane toolsContentPane = new TilePane(); toolsContentPane.setPrefColumns(3); toolsContentPane.getStyleClass().add("grid"); Button runExecutable = new Button(tr("Run executable")); runExecutable.getStyleClass().addAll("toolButton", "runExecutable"); runExecutable.setOnMouseClicked(event -> { this.lockAll(); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(tr("Choose executable ...")); File containerDir = new File(this.container.getPath()); if (containerDir.canRead()) { fileChooser.setInitialDirectory(containerDir); } File file = fileChooser.showOpenDialog(this.getContent().getScene().getWindow()); if (file != null) { containerEngineController.runInContainer(container, file.getAbsolutePath(), this::unlockAll, e -> Platform.runLater(() -> new ErrorMessage("Error", e).show())); } else { this.unlockAll(); } }); this.lockableElements.add(runExecutable); toolsContentPane.getChildren().add(runExecutable); toolsPane.getChildren().addAll(toolsContentPane); this.setContent(toolsPane); }
Source:
private int getNumOfPrestartedVmsInPool(VmPool pool) { List<VM> vmsInPool = getVmDao().getAllForVmPool(pool.getVmPoolId()); return vmsInPool == null ? 0 : vmsInPool.stream() .filter(vm -> vm.isStartingOrUp() && vmPoolHandler.isPrestartedVmFree(vm.getId(), pool.isStateful(), null)) .collect(Collectors.counting()) .intValue(); }

Target:
private int getNumOfPrestartedVmsInPool(VmPool pool) { List<VM> vmsInPool = vmDao.getAllForVmPool(pool.getVmPoolId()); return vmsInPool == null ? 0 : vmsInPool.stream() .filter(vm -> vm.isStartingOrUp() && vmPoolHandler.isPrestartedVmFree(vm.getId(), pool.isStateful(), null)) .collect(Collectors.counting()) .intValue(); }
Source:
public List<Role> getRoles(final RoleSearchDto roleSearchDto) { final List<Role> toReturn; try { final Criteria criteria = this.getSession().createCriteria(Role.class); if (roleSearchDto != null) { if (roleSearchDto.getRoleIds() != null && !roleSearchDto.getRoleIds().isEmpty()) { criteria.add(Restrictions.in("id", roleSearchDto.getRoleIds())); } if (roleSearchDto.getAssignable() != null) { criteria.add(Restrictions.eq("assignable", roleSearchDto.getAssignable())); } if (roleSearchDto.getRoleTypeId() != null) { criteria.createAlias("roleType", "roleType"); criteria.add(Restrictions.eq("roleType.id", roleSearchDto.getRoleTypeId())); } if(roleSearchDto.getName() != null && StringUtils.isNotBlank(roleSearchDto.getName())) { criteria.add(Restrictions.eq("name", roleSearchDto.getName())); } if(roleSearchDto.getDescription() != null && StringUtils.isNotBlank(roleSearchDto.getDescription())) { criteria.add(Restrictions.eq("description", roleSearchDto.getDescription())); } } criteria.addOrder(Order.asc("id")); toReturn = criteria.list(); } catch (final HibernateException e) { final String message = "Error with getRoles query from RoleDAO: " + e.getMessage(); RoleDAO.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } return toReturn; }

Target:
public List<Role> getRoles(final RoleSearchDto roleSearchDto) { final List<Role> toReturn; try { final Criteria criteria = this.getSession().createCriteria(Role.class); if (roleSearchDto != null) { if (roleSearchDto.getRoleIds() != null && !roleSearchDto.getRoleIds().isEmpty()) { criteria.add(Restrictions.in("id", roleSearchDto.getRoleIds())); } if (roleSearchDto.getAssignable() != null) { criteria.add(Restrictions.eq("assignable", roleSearchDto.getAssignable())); } if (roleSearchDto.getRoleTypeId() != null) { criteria.createAlias("roleType", "roleType"); criteria.add(Restrictions.eq("roleType.id", roleSearchDto.getRoleTypeId())); } if (StringUtils.isNotBlank(roleSearchDto.getName())) { criteria.add(Restrictions.eq("name", roleSearchDto.getName())); } } criteria.addOrder(Order.asc("id")); toReturn = criteria.list(); } catch (final HibernateException e) { final String message = "Error with getRoles query from RoleDAO: " + e.getMessage(); RoleDAO.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } return toReturn; }
Source:
public void onNext(final RunningTask runningTask) { LOG.log(Level.INFO, "Task {0} is running", runningTask.getId()); taskSelector.addRunningTask(runningTask); }

Target:
public void onNext(final RunningTask runningTask) { LOG.log(Level.INFO, "Task {0} is running", runningTask.getId()); taskSelector.registerRunningTask(runningTask); }
Source:
public SettingsDto(String host, String port, String user, String password, Properties additionalProperties, String logAddress, String logSubject, String logBody, String logPurgeEnable, String logPurgeTime, String logPurgeTimeMultiplier) { this.host = host; this.port = port; this.username = user; this.password = password; Map<String, String> props = new HashMap<>(); for (Entry<Object, Object> entry : additionalProperties.entrySet()) { props.put((String) entry.getKey(), (String) entry.getValue()); } this.additionalProperties = props; this.logAddress = logAddress; this.logSubject = logSubject; this.logBody = logBody; this.logPurgeEnable = logPurgeEnable; this.logPurgeTime = logPurgeTime; this.logPurgeTimeMultiplier = logPurgeTimeMultiplier; }

Target:
public SettingsDto(String host, String port, String user, String password, Properties additionalProperties, String logAddress, String logSubject, String logBody, String logPurgeEnable, String logPurgeTime, String logPurgeTimeMultiplier) { this(host, port, user, password, new HashMap<String, String>(), logAddress, logSubject, logBody, logPurgeEnable, logPurgeTime, logPurgeTimeMultiplier); if (additionalProperties != null) { for (Entry<Object, Object> entry : additionalProperties.entrySet()) { this.additionalProperties.put((String) entry.getKey(), (String) entry.getValue()); } } }
Source:
public Response(int status, String reason, List<Header> headers, byte[] body) { if (status < 100) { throw new IllegalArgumentException("Invalid status code: " + status); } if (reason == null) { throw new IllegalArgumentException("Reason must not be null."); } if (headers == null) { throw new IllegalArgumentException("Headers must not be null."); } if (body == null) { throw new IllegalArgumentException("Body must not be null."); } this.body = body; this.status = status; this.reason = reason; this.headers = Collections.unmodifiableList(headers); }

Target:
public Response(int status, String reason, List<Header> headers, byte[] body) { if (status < 200) { throw new IllegalArgumentException("Invalid status code: " + status); } if (reason == null) { throw new IllegalArgumentException("reason == null"); } if (headers == null) { throw new IllegalArgumentException("headers == null"); } this.status = status; this.reason = reason; this.headers = Collections.unmodifiableList(new ArrayList<Header>(headers)); this.body = body; }
Source:
static double minSizeRequiredToRespectSpacing(final double spacing, final double firstRatio, final double secondRatio) { assert secondRatio >= firstRatio; if (secondRatio - firstRatio == 0) { return 0; } else { return (spacing) / (secondRatio - firstRatio); } }

Target:
static double minSizeRequiredToRespectSpacing(final double spacing, final double firstRatio, final double secondRatio) { assert secondRatio >= firstRatio; if (DoubleMath.fuzzyEquals(firstRatio, secondRatio, EQUALITY_TOLERANCE)) { return 0; } else { return spacing / (secondRatio - firstRatio); } }
Source:
public void setValue(final Boolean value, final boolean fireEvents) { if (isAttached()) { switchState(getElement(), value, true); } else { onChange(value, fireEvents); } }

Target:
public void setValue(final Boolean value, final boolean fireEvents) { Boolean oldValue = getValue(); if (isAttached()) { switchState(getElement(), value, true); } else { element.setChecked(value); } if (fireEvents) { ValueChangeEvent.fireIfNotEqual(ToggleSwitchBase.this, oldValue, value); } }
Source:
public void testNestedNonTerminals3() throws Exception { Grammar.NonTerminalId ntistart = new Grammar.NonTerminalId("StartNT"); Grammar.StateId stistart = new Grammar.StateId("StartState"); Grammar.StateId stiend = new Grammar.StateId("EndState"); Grammar.NonTerminal nt1 = new Grammar.NonTerminal(ntistart, stistart, new Grammar.State.OrderingInfo(0), stiend, new Grammar.State.OrderingInfo(100)); Grammar.RegExState resx = new Grammar.RegExState(new Grammar.StateId("RegExStidx"), nt1, new Grammar.State.OrderingInfo(1), Pattern.compile("x")); Grammar.NonTerminalState nts = new Grammar.NonTerminalState(new Grammar.StateId("NT"), nt1, new Grammar.State.OrderingInfo(2), nt1, false); nt1.entryState.next.add(resx); nt1.entryState.next.add(nt1.exitState); resx.next.add(nts); nts.next.add(nt1.exitState); { Term result = new Parser(new ParseState("")).parse(nt1, 0); Term expected = amb(klist(amb(KList.EMPTY))); assertEquals("EmtpyString check: ", expected, result); } { Term result = new Parser(new ParseState("xx")).parse(nt1, 0); Term expected = amb(klist(amb(klist(Token.kAppOf("K", "x"), amb(klist(Token.kAppOf("K", "x"), amb(KList.EMPTY))))))); assertEquals("x^n check: ", expected, result); } assertEquals("Expected Nullable NTs", 1, NullabilityCheck.getReachableNullableNT(nt1).size()); }

Target:
public void testNestedNonTerminals3() throws Exception { Grammar.NonTerminalId ntistart = new Grammar.NonTerminalId("StartNT"); Grammar.StateId stistart = new Grammar.StateId("StartState"); Grammar.StateId stiend = new Grammar.StateId("EndState"); Grammar.NonTerminal nt1 = new Grammar.NonTerminal(ntistart, stistart, new Grammar.State.OrderingInfo(0), stiend, new Grammar.State.OrderingInfo(100)); Grammar.RegExState resx = new Grammar.RegExState(new Grammar.StateId("RegExStidx"), nt1, new Grammar.State.OrderingInfo(1), Pattern.compile("x")); Grammar.NonTerminalState nts = new Grammar.NonTerminalState(new Grammar.StateId("NT"), nt1, new Grammar.State.OrderingInfo(2), nt1, false); nt1.entryState.next.add(resx); nt1.entryState.next.add(nt1.exitState); resx.next.add(nts); nts.next.add(nt1.exitState); { Term result = new Parser(new ParseState("")).parse(nt1, 0); Term expected = amb(klist(amb(KList.EMPTY))); Assert.assertEquals("EmtpyString check: ", expected, result); } { Term result = new Parser(new ParseState("xx")).parse(nt1, 0); Term expected = amb(klist(amb(klist(Token.kAppOf("K", "x"), amb(klist(Token.kAppOf("K", "x"), amb(KList.EMPTY))))))); Assert.assertEquals("x^n check: ", expected, result); } Assert.assertEquals("Expected Nullable NTs", nt1, NullabilityCheck.getReachableNullableNT(nt1).iterator().next()); }