auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Object[] getElements(Object inputElement) { if (inputElement instanceof Object[]) { List<Object> result = new ArrayList<Object>(); for (Object next : (Object[]) inputElement) { if (next instanceof String) { String diagramCategory = (String) next; for (ModelTemplateDescription template : getTemplatesDescription()) { if ((diagramCategory == null || diagramCategory.equals(template.getLanguage())) && template.getDi_path() != null) { result.add(template); } } } } result.add(0, new Object()); return result.toArray(); } return new Object[0]; }

Target:
public Object[] getElements(Object inputElement) { if (inputElement instanceof Object[]) { List<Object> result = new ArrayList<Object>(); for (Object next : (Object[]) inputElement) { if (next instanceof String) { String diagramCategory = (String) next; for (ModelTemplateDescription template : getTemplatesDescription()) { if ((diagramCategory == null || diagramCategory.equals(template.getLanguage())) && template.getDi_path() != null) { result.add(template); } } } } result.add(0, UnsetObject.instance); return result.toArray(); } return new Object[0]; }
Source:
protected void configure() { bind(Tracer.class).toInstance(NoopTracerFactory.create()); }

Target:
protected void configure() { bind(Tracer.class).toProvider(new TracerProvider(NoopTracerFactory.create())); }
Source:
private static Node constructAddOrStringNode(Iterator<CharSequence> partsIterator, Node argListNode) throws MalformedException { if (partsIterator.hasNext()) { CharSequence part = partsIterator.next(); Node partNode = null; if (part instanceof JsMessage.PlaceholderReference) { JsMessage.PlaceholderReference phRef = (JsMessage.PlaceholderReference) part; for (Node node : argListNode.children()) { if (node.isName()) { String arg = node.getString(); if (arg.equalsIgnoreCase(phRef.getName())) { partNode = IR.name(arg); } } } if (partNode == null) { throw new MalformedException( "Unrecognized message placeholder referenced: " + phRef.getName(), argListNode); } } else { partNode = IR.string(part.toString()); } if (partsIterator.hasNext()) { return IR.add(partNode, constructAddOrStringNode(partsIterator, argListNode)); } else { return partNode; } } else { return IR.string(""); } }

Target:
private static Node constructAddOrStringNode(Iterator<CharSequence> partsIterator, Node argListNode) throws MalformedException { if (!partsIterator.hasNext()) { return IR.string(""); } CharSequence part = partsIterator.next(); Node partNode = null; if (part instanceof JsMessage.PlaceholderReference) { JsMessage.PlaceholderReference phRef = (JsMessage.PlaceholderReference) part; for (Node node : argListNode.children()) { if (node.isName()) { String arg = node.getString(); if (arg.equalsIgnoreCase(phRef.getName())) { partNode = IR.name(arg); } } } if (partNode == null) { throw new MalformedException( "Unrecognized message placeholder referenced: " + phRef.getName(), argListNode); } } else { partNode = IR.string(part.toString()); } if (partsIterator.hasNext()) { return IR.add(partNode, constructAddOrStringNode(partsIterator, argListNode)); } else { return partNode; } }
Source:
public IStatus validate(IProject project, String path) { File dir = new File(path); int confidence = 0; if (dir.isDirectory()) { confidence += 5; List<String> data = Arrays.asList(dir.list()); for (String file : data) { if (file.endsWith(".dat")) { try { DatParser dp = new DatParser(new File(file)); dp.iterator().next(); } catch (IllegalArgumentException e) { confidence = Integer.MIN_VALUE; } confidence += 4; } if (file.endsWith(".map")) { try { if (MapParser.create(new File(file)) != null) { confidence += 4; } } catch (IOException e) { confidence = Integer.MIN_VALUE; } } if (file.endsWith("*.sym")) { confidence += 3; } } } if (confidence > 10) { return new TraceValidationStatus(confidence, Activator.class.getCanonicalName()); } return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Most probably not a UFTrace"); }

Target:
public IStatus validate(IProject project, String path) { File dir = new File(path); int confidence = 0; if (dir.isDirectory()) { confidence += 5; List<File> data = Arrays.asList(dir.listFiles()); for (File file : data) { String extension = FilenameUtils.getExtension(file.getName()); if (extension.equals(".dat")) { try { DatParser dp = new DatParser(file); dp.iterator().next(); } catch (IllegalArgumentException e) { confidence = Integer.MIN_VALUE; } confidence += 4; } if (extension.equals(".map")) { try { if (MapParser.create(file) != null) { confidence += 4; } } catch (IOException e) { confidence = Integer.MIN_VALUE; } } if (extension.equals("*.sym")) { confidence += 3; } } } if (confidence > 10) { return new TraceValidationStatus(confidence, Activator.class.getCanonicalName()); } return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Most probably not a UFTrace"); }
Source:
public void validate(JobParameters parameters) throws JobParametersInvalidException { String configRestartabilityAllowValue = parameters.getString(JobParametersNames.STATISTICS_OVERWRITE); ParametersValidatorUtil.checkIsNotNullOrEmptyString( configRestartabilityAllowValue, JobParametersNames.STATISTICS_OVERWRITE); ParametersValidatorUtil.checkIsBoolean( configRestartabilityAllowValue,JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); }

Target:
public void validate(JobParameters parameters) throws JobParametersInvalidException { String statisticsOverwriteValue = parameters.getString(JobParametersNames.STATISTICS_OVERWRITE); ParametersValidatorUtil.checkIsNotNullOrEmptyString( statisticsOverwriteValue, JobParametersNames.STATISTICS_OVERWRITE); ParametersValidatorUtil.checkIsBoolean( statisticsOverwriteValue,JobParametersNames.STATISTICS_OVERWRITE); }
Source:
public UndertowSecurityProvider getSecurityProvider() { if (this.securityProvider == null) { return getComponent().getSecurityProvider(); } return this.securityProvider; }

Target:
public UndertowSecurityProvider getSecurityProvider() { return this.securityProvider; }
Source:
public String toString() { return getId(); }

Target:
public String toString() { return "Context: " + getId(); }
Source:
default boolean anyExists() { return entities(Pager.builder().withPageSize(1).orderBy(Order.unspecified()).build()).hasNext(); }

Target:
default boolean anyExists() { return entities(Pager.single()).hasNext(); }
Source:
public static void killRunningImageJobs() { Job[] currentJobs = Job.getJobManager().find(null); for (Job job : currentJobs) { if (job.getName().startsWith(JOB_PULLING_DOCKER_IMAGE) || job.getName().startsWith(JOB_TAGGING_IMAGE) || job.getName().startsWith(JOB_PUSHING_DOCKER_IMAGE)|| job.getName().startsWith(JOB_OPENNING_CONNECTION)) { job.cancel(); } } }

Target:
public static void killRunningImageJobs() { Job[] currentJobs = Job.getJobManager().find(null); for (Job job : currentJobs) { String jobName = job.getName(); if (jobName.startsWith(JOB_PULLING_DOCKER_IMAGE) || jobName.startsWith(JOB_TAGGING_IMAGE) || jobName.startsWith(JOB_PUSHING_DOCKER_IMAGE)|| jobName.startsWith(JOB_OPENNING_CONNECTION)) { job.cancel(); } } }
Source:
public DRCatalogDiffEngine(Catalog localCatalog, Catalog remoteCatalog) { super(localCatalog, remoteCatalog); localCatalog.getClusters().get("cluster").getDrclusterid(); }

Target:
public DRCatalogDiffEngine(Catalog localCatalog, Catalog remoteCatalog) { super(localCatalog, remoteCatalog); }
Source:
public SchedulableEntityInstanceResult getFeedSLAMissPendingAlerts(String feedName, String startStr, String endStr, String colo) { Set<SchedulableEntityInstance> instances = new HashSet<>(); try { checkColo(colo); Date start = EntityUtil.parseDateUTC(startStr); Date end = (endStr == null) ? new Date() : EntityUtil.parseDateUTC(endStr); if (StringUtils.isBlank(feedName)) { instances.addAll(EntitySLAMonitoringService.get().getFeedSLAMissPendingAlerts(start, end)); } else { for (String clusterName : DeploymentUtil.getCurrentClusters()) { instances.addAll(EntitySLAMonitoringService.get().getFeedSLAMissPendingAlerts(feedName, clusterName, start, end, EntityType.FEED.toString())); } } } catch (FalconException e) { throw FalconWebException.newAPIException(e); } SchedulableEntityInstanceResult result = new SchedulableEntityInstanceResult(APIResult.Status.SUCCEEDED, "Success!"); result.setCollection(instances.toArray()); return result; }

Target:
public SchedulableEntityInstanceResult getFeedSLAMissPendingAlerts(String feedName, String startStr, String endStr, String colo) { Set<SchedulableEntityInstance> instances = new HashSet<>(); try { checkColo(colo); Date start = EntityUtil.parseDateUTC(startStr); Date end = (endStr == null) ? new Date() : EntityUtil.parseDateUTC(endStr); if (StringUtils.isBlank(feedName)) { instances.addAll(EntitySLAMonitoringService.get().getEntitySLAMissPendingAlerts(start, end)); } else { for (String clusterName : DeploymentUtil.getCurrentClusters()) { instances.addAll(EntitySLAMonitoringService.get().getEntitySLAMissPendingAlerts(feedName, clusterName, start, end, EntityType.FEED.toString())); } } } catch (FalconException e) { throw FalconWebException.newAPIException(e); } SchedulableEntityInstanceResult result = new SchedulableEntityInstanceResult(APIResult.Status.SUCCEEDED, "Success!"); result.setCollection(instances.toArray()); return result; }
Source:
protected void upgradeFrom(UpdateUI ui, CurrentSchemaVersion curr, ReviewDb db, boolean toTargetVersion) throws OrmException { throw new OrmException("Cannot upgrade from " + curr.versionNbr + "; manually run scripts from" + " <LINK_0>" + " and restart."); }

Target:
protected void upgradeFrom(UpdateUI ui, CurrentSchemaVersion curr, ReviewDb db, boolean toTargetVersion) throws OrmException { throw new OrmException("Cannot upgrade from " + curr.versionNbr + "; run first gerrit version 2.1.5 or 2.1.4 to upgrade the" + " schema at least to version 34" + "; then restart this new gerrit version."); }
Source:
public void waitForSchemaUpdates(Session session, String keyspace, long delay, int maxRetries) throws InterruptedException { String configId = "org.hawkular.metrics"; String configName = "schema-version"; int retries = 0; PreparedStatement getVersion = null; SchemaService schemaService = new SchemaService(session, keyspace); String version = schemaService.getSchemaVersion(); while (maxRetries > retries) { try { if (getVersion == null) { getVersion = session.prepare("SELECT value FROM " + keyspace + ".sys_config " + "WHERE config_id = ? AND name = ?"); } ResultSet resultSet = session.execute(getVersion.bind(configId, configName)); if (!resultSet.isExhausted()) { String schemaVersion = resultSet.one().getString(0); if(version.equals(schemaVersion)) { logger.infof("Hawkular Metrics is up to date at version %s", version); return; } else { logger.infof("Hawkular Metrics schema version does not match," + " should be %s, present: %s, Trying again in %d ms", version, schemaVersion, delay); } } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Version check failed", e); } else { logger.infof("Version check failed: %s", e.getMessage()); } logger.infof("Trying again in %d ms", delay); } retries++; Thread.sleep(delay); } throw new SchemaVersionCheckException("Version check unsuccessful after " + maxRetries + " attempts"); }

Target:
public void waitForSchemaUpdates(Session session, String keyspace, long delay, int maxRetries) throws InterruptedException { String configId = "org.hawkular.metrics"; String configName = "schema-version"; int retries = 0; PreparedStatement getVersion = null; SchemaService schemaService = new SchemaService(session, keyspace); String version = schemaService.getSchemaVersion(); while (maxRetries > retries) { try { if (getVersion == null) { getVersion = session.prepare("SELECT value FROM " + keyspace + ".sys_config " + "WHERE config_id = ? AND name = ?"); } ResultSet resultSet = session.execute(getVersion.bind(configId, configName)); if (!resultSet.isExhausted()) { String schemaVersion = resultSet.one().getString(0); if(version.equals(schemaVersion)) { logger.infof("Hawkular Metrics schema is up to date at version %s", version); return; } else { logger.infof("Hawkular Metrics schema version does not match," + " should be %s, present: %s, Trying again in %d ms", version, schemaVersion, delay); } } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Version check failed", e); } else { logger.infof("Version check failed: %s", e.getMessage()); } logger.infof("Trying again in %d ms", delay); } retries++; Thread.sleep(delay); } throw new SchemaVersionCheckException("Version check unsuccessful after " + maxRetries + " attempts"); }
Source:
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception { Long startId = getParam(parameters, "start_id").orElse(0); final OptionalLong maybeMaxId = getParam(parameters, "max_id"); Long patchBackfillParam = getParam(parameters, "force_patch").orElse(0); boolean forcePatchBackfill = patchBackfillParam != 0; logger.info("Execute called start_id={} max_id={} - processing", startId, maybeMaxId); try { logger.info("Request accepted"); if (forcePatchBackfill) { executor.execute(() -> worker.executePatchCreatedAndDetailsEntered(startId, maybeMaxId)); } else { executor.execute(() -> worker.execute(startId, maybeMaxId)); } output.println("Accepted"); } catch (java.util.concurrent.RejectedExecutionException e) { logger.info("Rejected request, worker already running"); output.println("Rejected request, worker already running"); } }

Target:
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception { Long startId = getLongParam(parameters, "start_id").orElse(0); final OptionalLong maybeMaxId = getLongParam(parameters, "max_id"); Boolean patchBackfill = getBoolParam(parameters, "force_patch").orElse(false); logger.info("Execute called start_id={} max_id={} - processing", startId, maybeMaxId); try { logger.info("Request accepted"); if (patchBackfill) { executor.execute(() -> worker.executePatchCreatedAndDetailsEntered(startId, maybeMaxId)); } else { executor.execute(() -> worker.execute(startId, maybeMaxId)); } output.println("Accepted"); } catch (java.util.concurrent.RejectedExecutionException e) { logger.info("Rejected request, worker already running"); output.println("Rejected request, worker already running"); } }
Source:
public void testFindLiveVersionFile() throws Exception{ String folderName = "/testOldFile"+UUIDGenerator.generateUuid(); Folder ff = APILocator.getFolderAPI().createFolders(folderName, host, user, false); java.io.File tmp=new java.io.File(APILocator.getFileAPI().getRealAssetPathTmpBinary()+java.io.File.separator+"testOldFile"); if(!tmp.exists()) tmp.mkdirs(); java.io.File data=new java.io.File(tmp, "test-"+UUIDGenerator.generateUuid()+".txt"); FileWriter fw=new FileWriter(data,true); fw.write("file content"); fw.close(); File file = new File(); file.setFileName("legacy.txt"); file.setFriendlyName("legacy.txt"); file.setMimeType("text/plain"); file.setTitle("legacy.txt"); file.setSize((int)data.length()); file.setModUser(user.getUserId()); file.setModDate(Calendar.getInstance().getTime()); file = APILocator.getFileAPI().saveFile(file, data, ff, user, false); APILocator.getFileAPI().publishFile(file, user, false); Versionable verAPI = APILocator.getVersionableAPI().findLiveVersion(file.getIdentifier(), user, false); assertEquals(verAPI.getTitle(),file.getTitle()); assertEquals(verAPI.getInode(),file.getInode()); APILocator.getFileAPI().delete(file, user, false); APILocator.getFolderAPI().delete(ff, user, false); }

Target:
public void testFindLiveVersionFile() throws Exception{ File file = createLegacyFile(); APILocator.getFileAPI().publishFile(file, user, false); Versionable verAPI = APILocator.getVersionableAPI().findLiveVersion(file.getIdentifier(), user, false); assertEquals(verAPI.getTitle(),file.getTitle()); assertEquals(verAPI.getInode(),file.getInode()); Folder folder = APILocator.getFileAPI().getFileFolder(file, host, user, false); APILocator.getFileAPI().delete(file, user, false); APILocator.getFolderAPI().delete(folder, user, false); }
Source:
public Void perform( Task task, TaskActionToolbox toolbox ) throws IOException { toolbox.verifyTaskLocksAndSinglePartitionSettitude(task, segments, true); toolbox.getIndexerMetadataStorageCoordinator().updateSegmentMetadata(segments); final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder() .setDimension("dataSource", task.getDataSource()) .setDimension("taskType", task.getType()); for (DataSegment segment : segments) { metricBuilder.setDimension("interval", segment.getInterval().toString()); toolbox.getEmitter().emit(metricBuilder.build("segmentMoved/bytes", segment.getSize())); } return null; }

Target:
public Void perform( Task task, TaskActionToolbox toolbox ) throws IOException { toolbox.verifyTaskLocksAndSinglePartitionSettitude(task, segments, true); toolbox.getIndexerMetadataStorageCoordinator().updateSegmentMetadata(segments); final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder() .setDimension(DruidMetrics.DATASOURCE, task.getDataSource()) .setDimension(DruidMetrics.TASK_TYPE, task.getType()); for (DataSegment segment : segments) { metricBuilder.setDimension(DruidMetrics.INTERVAL, segment.getInterval().toString()); toolbox.getEmitter().emit(metricBuilder.build("segment/moved/bytes", segment.getSize())); } return null; }
Source:
private long persistVersionId(long articlePk, int revisionNumber) { return parentService.hibernateTemplate.execute(session -> { SQLQuery blankOtherRevisions = session.createSQLQuery("" + "UPDATE articleVersion SET revisionNumber = NULL, lastModified = NOW() " + "WHERE articleId=:articleId AND revisionNumber=:revisionNumber"); blankOtherRevisions.setParameter("articleId", articlePk); blankOtherRevisions.setParameter("revisionNumber", revisionNumber); blankOtherRevisions.executeUpdate(); SQLQuery insertEvent = session.createSQLQuery("" + "INSERT INTO articleVersion (articleId, revisionNumber, publicationState, lastModified) " + "VALUES (:articleId, :revisionNumber, :publicationState, NOW())"); insertEvent.setParameter("articleId", articlePk); insertEvent.setParameter("revisionNumber", revisionNumber); insertEvent.setParameter("publicationState", ArticleItem.PublicationState.INGESTED.getValue()); insertEvent.executeUpdate(); return getLastInsertId(session); }); }

Target:
private long persistVersionId(long articlePk, int revisionNumber) { return parentService.hibernateTemplate.execute(session -> { SQLQuery replaceOtherRevisions = session.createSQLQuery("" + "UPDATE articleVersion SET publicationState = :replaced, lastModified = NOW() " + "WHERE articleId = :articleId AND revisionNumber = :revisionNumber " + " AND publicationState != :replaced"); replaceOtherRevisions.setParameter("articleId", articlePk); replaceOtherRevisions.setParameter("revisionNumber", revisionNumber); replaceOtherRevisions.setParameter("replaced", ArticleItem.PublicationState.REPLACED.getValue()); replaceOtherRevisions.executeUpdate(); SQLQuery insertEvent = session.createSQLQuery("" + "INSERT INTO articleVersion (articleId, revisionNumber, publicationState, lastModified) " + "VALUES (:articleId, :revisionNumber, :publicationState, NOW())"); insertEvent.setParameter("articleId", articlePk); insertEvent.setParameter("revisionNumber", revisionNumber); insertEvent.setParameter("publicationState", ArticleItem.PublicationState.INGESTED.getValue()); insertEvent.executeUpdate(); return getLastInsertId(session); }); }
Source:
public static void setServeReadTips(boolean serveReadTips) { log(LogUtil.info("setServiceReadTips = '" + serveReadTips + "'")); IEclipsePreferences node = getPreferences(); node.putBoolean(PREF_SERVE_READ_TIPS, serveReadTips); try { node.flush(); } catch (BackingStoreException e) { throw new RuntimeException(e); } }

Target:
public static void setServeReadTips(boolean serveReadTips) { log(LogUtil.info("Entering method setServeReadTips with boolean parameter = '" + serveReadTips + "'")); IEclipsePreferences node = getPreferences(); node.putBoolean(PREF_SERVE_READ_TIPS, serveReadTips); try { node.flush(); } catch (BackingStoreException e) { log(LogUtil.error(e)); } }
Source:
public static void workflowGarbageCollection(final WorkflowControllerDataProvider dataProvider, final HelixManager manager) { Set<String> toBeDeletedWorkflows = new HashSet<>(); try { Set<String> existingWorkflowContexts = new HashSet<>(dataProvider.getContexts().keySet()); for (String entry : existingWorkflowContexts) { if (entry != null) { WorkflowConfig cfg = dataProvider.getWorkflowConfig(entry); WorkflowContext ctx = dataProvider.getWorkflowContext(entry); if (ctx != null && ctx.getId().equals(TaskUtil.WORKFLOW_CONTEXT_KW)) { if (cfg == null) { toBeDeletedWorkflows.add(entry); } } } } } catch (Exception e) { LOG.warn(String.format( "Exception occurred while creating a list of all existing contexts with missing config!! Reason: %s"), e.getMessage()); } HelixDataAccessor accessor = manager.getHelixDataAccessor(); HelixPropertyStore<ZNRecord> propertyStore = manager.getHelixPropertyStore(); for (String workflowName : toBeDeletedWorkflows) { LOG.warn(String.format( "WorkflowContext exists for workflow %s. However, Workflow Config is missing! Deleting the WorkflowConfig and IdealState!!", workflowName)); if (!cleanupWorkflowIdealStateExtView(accessor, workflowName)) { LOG.warn(String.format( "Error occurred while trying to remove workflow idealstate/externalview for %s.", workflowName)); continue; } if (!removeWorkflowContext(propertyStore, workflowName)) { LOG.warn(String.format("Error occurred while trying to remove workflow context for %s.", workflowName)); continue; } } }

Target:
public static void workflowGarbageCollection(final WorkflowControllerDataProvider dataProvider, final HelixManager manager) { Set<String> existingContexts; try { existingContexts = new HashSet<>(dataProvider.getContexts().keySet()); } catch (Exception e) { LOG.warn( "Exception occurred while creating a list of all workflow/job context names!", e); return; } Set<String> toBeDeletedWorkflows = new HashSet<>(); for (String entry : existingContexts) { WorkflowConfig cfg = dataProvider.getWorkflowConfig(entry); WorkflowContext ctx = dataProvider.getWorkflowContext(entry); if (ctx != null && ctx.getId().equals(TaskUtil.WORKFLOW_CONTEXT_KW) && cfg == null) { toBeDeletedWorkflows.add(entry); } } HelixDataAccessor accessor = manager.getHelixDataAccessor(); HelixPropertyStore<ZNRecord> propertyStore = manager.getHelixPropertyStore(); for (String workflowName : toBeDeletedWorkflows) { LOG.warn(String.format( "WorkflowContext exists for workflow %s. However, Workflow Config is missing! Deleting the WorkflowConfig and IdealState!!", workflowName)); if (!cleanupWorkflowIdealStateExtView(accessor, workflowName)) { LOG.warn(String.format( "Error occurred while trying to remove workflow idealstate/externalview for %s.", workflowName)); continue; } if (!removeWorkflowContext(propertyStore, workflowName)) { LOG.warn(String.format("Error occurred while trying to remove workflow context for %s.", workflowName)); continue; } } }
Source:
default String getPreferenceKey() { return getClass().getCanonicalName(); }

Target:
default String getPreferenceKey() { return getClass().getName(); }
Source:
public void testEmptyPasswordWithNonRootUser() { thrown.expect(RuntimeException.class); MySQLContainer container = (MySQLContainer) new MySQLContainer("mysql:5.5") .withDatabaseName("TEST") .withUsername("test") .withPassword("") .withEnv("MYSQL_ROOT_HOST", "%"); container.start(); container.stop(); }

Target:
public void testEmptyPasswordWithNonRootUser() { MySQLContainer container = (MySQLContainer) new MySQLContainer("mysql:5.5").withDatabaseName("TEST") .withUsername("test").withPassword("").withEnv("MYSQL_ROOT_HOST", "%"); try { container.start(); fail("ContainerLaunchException expected to be thrown"); } catch (ContainerLaunchException e) { } finally { container.stop(); } }
Source:
public void mergeStatisticsCorenerCaseNodesTest() { SegmentStoreStatistics expected = new SegmentStoreStatistics(); SegmentStoreStatistics a = new SegmentStoreStatistics(); SegmentStoreStatistics b = new SegmentStoreStatistics(); SegmentStoreStatistics c = new SegmentStoreStatistics(); SegmentStoreStatistics d = new SegmentStoreStatistics(); SegmentStoreStatistics e = new SegmentStoreStatistics(); SegmentStoreStatistics f = new SegmentStoreStatistics(); List<@NonNull ISegment> fixture = new ArrayList<>(); c.merge(d); f.update(new BasicSegment(1, 2)); e.update(new BasicSegment(1, 2)); for (int i = 0; i < 10; i++) { BasicSegment seg = new BasicSegment(i, i * 2 + 2); expected.update(seg); a.update(seg); fixture.add(seg); } validate(d, c); e.merge(d); validate(f, e); c.merge(f); validate(f, c); a.merge(b); OfflineStatisticsCalculator offlineExpected = new OfflineStatisticsCalculator(fixture); validate(offlineExpected, expected); validate(expected, a); }

Target:
public void mergeStatisticsCorenerCaseNodesTest() { ISegment segment = new BasicSegment(1, 5); SegmentStoreStatistics noSegments = new SegmentStoreStatistics(); SegmentStoreStatistics oneSegment = new SegmentStoreStatistics(); oneSegment.update(segment); SegmentStoreStatistics testStats = new SegmentStoreStatistics(); SegmentStoreStatistics testStats2 = new SegmentStoreStatistics(); testStats.update(segment); testStats.merge(testStats2); validate(oneSegment, testStats); validate(noSegments, testStats2); testStats2.merge(testStats); validate(oneSegment, testStats); validate(oneSegment, testStats2); SegmentStoreStatistics expected = fillSmallStatistics(); expected.update(segment); testStats = fillSmallStatistics(); testStats.merge(testStats2); validate(oneSegment, testStats2); validate(expected, testStats); testStats = fillSmallStatistics(); testStats2.merge(testStats); validate(fillSmallStatistics(), testStats); validate(expected, testStats2); }
Source:
private Bundle getBundleFromBundlesArray(String bundleSymbolicName) { Bundle[] bundles = bundleContext.getBundles(); for(int i = 0; i < bundles.length; i++) { if(bundles[i].getSymbolicName() == null) { continue; } else if (bundles[i].getSymbolicName().equals(bundleSymbolicName)) { return bundles[i]; } } return null; }

Target:
private Bundle getBundleFromBundlesArray(String bundleSymbolicName) { Bundle[] bundles = bundleContext.getBundles(); for(Bundle bundle : bundles) { if (bundle.getSymbolicName() == null) { continue; } else if (bundle.getSymbolicName().equals(bundleSymbolicName)) { return bundle; } } return null; }
Source:
private static WebArchive createDeploymentWithSpringMvcDispatcher() { WebArchive archive = ShrinkWrap.create(WebArchive.class, deploymentWithSpringMvcDispatcherSpringIncluded + ".war") .addClass(TestResource.class) .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/web.xml", "web.xml") .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/mvc-dispatcher-servlet.xml", "mvc-dispatcher-servlet.xml") .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/applicationContext.xml", "applicationContext.xml"); archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( new PropertyPermission("arquillian.*", "read"), new ReflectPermission("suppressAccessChecks"), new RuntimePermission("accessDeclaredMembers"), new RuntimePermission("getClassLoader"), new FilePermission("<<ALL FILES>>", "read"), new LoggingPermission("control", "") ), "permissions.xml"); TestUtilSpring.addSpringLibraries(archive); archive.as(ZipExporter.class).exportTo(new File("target", deploymentWithSpringMvcDispatcherSpringIncluded + ".war"), true); return archive; }

Target:
private static WebArchive createDeploymentWithSpringMvcDispatcher() { WebArchive archive = ShrinkWrap.create(WebArchive.class, deploymentWithSpringMvcDispatcherSpringIncluded + ".war") .addClass(TestResource.class) .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/web.xml", "web.xml") .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/mvc-dispatcher-servlet.xml", "mvc-dispatcher-servlet.xml") .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/applicationContext.xml", "applicationContext.xml"); archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( new ReflectPermission("suppressAccessChecks"), new RuntimePermission("accessDeclaredMembers"), new RuntimePermission("getClassLoader"), new FilePermission("<<ALL FILES>>", "read"), new LoggingPermission("control", "") ), "permissions.xml"); TestUtilSpring.addSpringLibraries(archive); archive.as(ZipExporter.class).exportTo(new File("target", deploymentWithSpringMvcDispatcherSpringIncluded + ".war"), true); return archive; }
Source:
public Mono<PollResponse<T>> poll() { return pollOperation.apply(pollResponse.get()) .doOnEach(pollResponseSignal -> { if (pollResponseSignal.get() != null) { pollResponse.set(pollResponseSignal.get()); } }); }

Target:
public Mono<PollResponse<T>> poll() { return pollOperation.apply(this.pollResponse) .doOnEach(pollResponseSignal -> { if (pollResponseSignal.get() != null) { this.pollResponse = pollResponseSignal.get(); } }); }
Source:
public Monitor getPrimaryMonitor () { checkDevice (); if (OS.IsWinCE || OS.WIN32_VERSION < OS.VERSION (4, 10)) { Monitor monitor = new Monitor(); int width = OS.GetSystemMetrics (OS.SM_CXSCREEN); int height = OS.GetSystemMetrics (OS.SM_CYSCREEN); monitor.width = width; monitor.height = height; RECT rect = new RECT (); OS.SystemParametersInfo (OS.SPI_GETWORKAREA, 0, rect, 0); monitor.clientX = rect.left; monitor.clientY = rect.top; monitor.clientWidth = rect.right - rect.left; monitor.clientHeight = rect.bottom - rect.top; long hDC = internal_new_GC (null); monitor.dpi = (OS.GetDeviceCaps (hDC, OS.LOGPIXELSX)); monitor.imageSelectorIndex = DpiUtil.mapDpiToImageSelectorIndex (monitor.dpi); internal_dispose_GC (hDC, null); return monitor; } monitors = new Monitor [4]; Callback callback = new Callback (this, "monitorEnumProc", 4); long lpfnEnum = callback.getAddress (); if (lpfnEnum == 0) error (SWT.ERROR_NO_MORE_CALLBACKS); OS.EnumDisplayMonitors (0, null, lpfnEnum, 0); callback.dispose (); Monitor result = null; MONITORINFO lpmi = new MONITORINFO (); lpmi.cbSize = MONITORINFO.sizeof; for (int i = 0; i < monitorCount; i++) { Monitor monitor = monitors [i]; OS.GetMonitorInfo (monitors [i].handle, lpmi); if ((lpmi.dwFlags & OS.MONITORINFOF_PRIMARY) != 0) { result = monitor; break; } } monitors = null; monitorCount = 0; return result; }

Target:
public Monitor getPrimaryMonitor () { checkDevice (); if (OS.IsWinCE || OS.WIN32_VERSION < OS.VERSION (4, 10)) { Monitor monitor = new Monitor(); int width = OS.GetSystemMetrics (OS.SM_CXSCREEN); int height = OS.GetSystemMetrics (OS.SM_CYSCREEN); monitor.width = width; monitor.height = height; RECT rect = new RECT (); OS.SystemParametersInfo (OS.SPI_GETWORKAREA, 0, rect, 0); monitor.clientX = rect.left; monitor.clientY = rect.top; monitor.clientWidth = rect.right - rect.left; monitor.clientHeight = rect.bottom - rect.top; long hDC = internal_new_GC (null); monitor.dpi = (OS.GetDeviceCaps (hDC, OS.LOGPIXELSX)); monitor.imageSelectorIndex = DPIUtil.mapDPIToImageSelectorIndex (monitor.dpi); internal_dispose_GC (hDC, null); return monitor; } monitors = new Monitor [4]; Callback callback = new Callback (this, "monitorEnumProc", 4); long lpfnEnum = callback.getAddress (); if (lpfnEnum == 0) error (SWT.ERROR_NO_MORE_CALLBACKS); OS.EnumDisplayMonitors (0, null, lpfnEnum, 0); callback.dispose (); Monitor result = null; MONITORINFO lpmi = new MONITORINFO (); lpmi.cbSize = MONITORINFO.sizeof; for (int i = 0; i < monitorCount; i++) { Monitor monitor = monitors [i]; OS.GetMonitorInfo (monitors [i].handle, lpmi); if ((lpmi.dwFlags & OS.MONITORINFOF_PRIMARY) != 0) { result = monitor; break; } } monitors = null; monitorCount = 0; return result; }
Source:
public void introspect() throws IOException { JsonObject msgBodyJson = new JsonObject(); msgBodyJson.addProperty("query", IntrospectionQuery.INTROSPECTION_QUERY); HttpRequestBody msgBody = new HttpRequestBody(msgBodyJson.toString()); HttpRequestHeader msgHeader = new HttpRequestHeader(HttpRequestHeader.POST, endpointUrl, "HTTP/1.1"); msgHeader.setHeader("Accept", "application/json"); msgHeader.setHeader("Content-Type", "application/json"); msgHeader.setContentLength(msgBody.length()); importMessage = new HttpMessage(msgHeader, msgBody); requestHandler.makeRequest(importMessage); try { Map<String, Object> result = new Gson() .fromJson( importMessage.getResponseBody().toString(), new TypeToken<Map<String, Object>>() {}.getType()); @SuppressWarnings("unchecked") Document schema = new IntrospectionResultToSchema() .createSchemaDefinition((Map<String, Object>) result.get("data")); String schemaSDL = new SchemaPrinter().print(schema); Thread t = new Thread(() -> parse(schemaSDL)); t.start(); } catch (JsonSyntaxException e) { throw new IOException("The response was not valid JSON."); } }

Target:
public void introspect() throws IOException { JsonObject msgBodyJson = new JsonObject(); msgBodyJson.addProperty("query", IntrospectionQuery.INTROSPECTION_QUERY); HttpRequestBody msgBody = new HttpRequestBody(msgBodyJson.toString()); HttpRequestHeader msgHeader = new HttpRequestHeader(HttpRequestHeader.POST, endpointUrl, "HTTP/1.1"); msgHeader.setHeader("Accept", "application/json"); msgHeader.setHeader("Content-Type", "application/json"); msgHeader.setContentLength(msgBody.length()); HttpMessage importMessage = new HttpMessage(msgHeader, msgBody); requestor.send(importMessage); try { Map<String, Object> result = new Gson() .fromJson( importMessage.getResponseBody().toString(), new TypeToken<Map<String, Object>>() {}.getType()); @SuppressWarnings("unchecked") Document schema = new IntrospectionResultToSchema() .createSchemaDefinition((Map<String, Object>) result.get("data")); String schemaSdl = new SchemaPrinter().print(schema); parse(schemaSdl); } catch (JsonSyntaxException e) { throw new IOException("The response was not valid JSON."); } }
Source:
public void shouldFindUserSubscribingForAnyPipelineAndThatHasPermission() { User foo = new User("foo", Arrays.asList("fOO", "Foo"), "foo@cruise.com", false); foo.addNotificationFilter(new NotificationFilter(GoConstants.ANY_PIPELINE, GoConstants.ANY_STAGE, StageEvent.Passes, true)); User bar = new User("bar", Arrays.asList("bAR", "Bar"), "bar@go.com", true); bar.addNotificationFilter(new NotificationFilter(GoConstants.ANY_PIPELINE, GoConstants.ANY_STAGE, StageEvent.Passes, true)); User quux = new User("quux", Arrays.asList("qUUX", "Quux"), "quux@cruise.go", false); quux.addNotificationFilter(new NotificationFilter("p2", "s2", StageEvent.Passes, true)); when(userDao.findNotificationSubscribingUsers()).thenReturn(new Users(Arrays.asList(foo, bar))); when(securityService.hasViewPermissionForPipeline(foo.getName(), "p1")).thenReturn(true); when(securityService.hasViewPermissionForPipeline(bar.getName(), "p1")).thenReturn(false); assertThat(userService.findValidSubscribers(new StageConfigIdentifier("p1", "s1")), contains(foo)); }

Target:
public void shouldFindUserSubscribingForAnyPipelineAndThatHasPermission() { User foo = new User("foo", Arrays.asList("fOO", "Foo"), "foo@cruise.com", false); foo.addNotificationFilter(new NotificationFilter(GoConstants.ANY_PIPELINE, GoConstants.ANY_STAGE, StageEvent.Passes, true)); User bar = new User("bar", Arrays.asList("bAR", "Bar"), "bar@go.com", true); bar.addNotificationFilter(new NotificationFilter(GoConstants.ANY_PIPELINE, GoConstants.ANY_STAGE, StageEvent.Passes, true)); when(userDao.findNotificationSubscribingUsers()).thenReturn(new Users(Arrays.asList(foo, bar))); when(securityService.hasViewPermissionForPipeline(foo.getName(), "p1")).thenReturn(true); when(securityService.hasViewPermissionForPipeline(bar.getName(), "p1")).thenReturn(false); assertThat(userService.findValidSubscribers(new StageConfigIdentifier("p1", "s1")), contains(foo)); }
Source:
public void testSubstitutionEqualsAndHashCodeAreConsistent() { final List<Substitution> substitutions = new ArrayList<>(); for (int position : new int[] {0, 1}) { for (byte base : new byte[] {(byte) -1, (byte) 'A'}) { for (byte referenceBase : new byte[] {(byte) -1, (byte) 'C'}) { for (byte code : new byte[] {Substitution.NO_CODE, (byte) 2}) { Substitution substitution = new Substitution(position, base, referenceBase); substitution.setCode(code); substitutions.add(substitution); } } } } for (Substitution s1 : substitutions) { for (Substitution s2 : substitutions) { if (s1.equals(s2)) { Assert.assertEquals(s1.hashCode(), s2. hashCode(), String.format("Comparing %s (%s) and %s (%s)", s1, s1.getCode(), s2, s2.getCode())); } } } }

Target:
public void testSubstitutionEqualsAndHashCodeAreConsistent() { final List<Substitution> substitutions = new ArrayList<>(); for (int position : new int[] {0, 1}) { for (byte base : new byte[] {(byte) -1, (byte) 'A'}) { for (byte referenceBase : new byte[] {(byte) -1, (byte) 'C'}) { for (byte code : new byte[] {Substitution.NO_CODE, (byte) 1, (byte) 2}) { Substitution substitution = new Substitution(position, base, referenceBase); substitution.setCode(code); substitutions.add(substitution); } } } } for (Substitution s1 : substitutions) { for (Substitution s2 : substitutions) { if (s1.equals(s2)) { Assert.assertEquals(s1.hashCode(), s2. hashCode(), String.format("Comparing %s (%s) and %s (%s)", s1, s1.getCode(), s2, s2.getCode())); } } } }
Source:
public void onNext(final Message<AvroElasticMemoryMessage> msg) { LOG.entering(ElasticMemoryMsgHandler.class.getSimpleName(), "onNext", msg); final AvroElasticMemoryMessage innerMsg = SingleMessageExtractor.extract(msg); switch (innerMsg.getType()) { case RoutingTableInitMsg: onRoutingTableInitMsg(innerMsg); break; case RoutingTableUpdateMsg: onRoutingTableUpdateMsg(innerMsg); break; case RemoteOpMsg: case RemoteOpResultMsg: onRemoteOpResultMsg(innerMsg); break; case DataMsg: onDataMsg(innerMsg); break; case CtrlMsg: onCtrlMsg(innerMsg); break; case OwnershipMsg: onOwnershipMsg(innerMsg); break; default: throw new RuntimeException("Unexpected message: " + msg); } LOG.exiting(ElasticMemoryMsgHandler.class.getSimpleName(), "onNext", msg); }

Target:
public void onNext(final Message<AvroElasticMemoryMessage> msg) { LOG.entering(ElasticMemoryMsgHandler.class.getSimpleName(), "onNext", msg); final AvroElasticMemoryMessage innerMsg = SingleMessageExtractor.extract(msg); switch (innerMsg.getType()) { case RoutingTableInitMsg: onRoutingTableInitMsg(innerMsg); break; case RoutingTableUpdateMsg: onRoutingTableUpdateMsg(innerMsg); break; case RemoteOpReqMsg: case RemoteOpResultMsg: onRemoteOpMsg(innerMsg); break; case DataMsg: onDataMsg(innerMsg); break; case CtrlMsg: onCtrlMsg(innerMsg); break; case OwnershipMsg: onOwnershipMsg(innerMsg); break; default: throw new RuntimeException("Unexpected message: " + msg); } LOG.exiting(ElasticMemoryMsgHandler.class.getSimpleName(), "onNext", msg); }
Source:
private void loadPatterns(String directory, List<Pattern> patternList) { String dspaceHome = configurationService.getProperty("dspace.dir"); File spidersDir = new File(dspaceHome, "config/spiders"); File patternsDir = new File(spidersDir, directory); if (patternsDir.exists() && patternsDir.isDirectory()) { for (File file : patternsDir.listFiles()) { if (file.isFile() && !file.getName().matches(".+old$")) { Set<String> patterns; try { patterns = readPatterns(file); } catch (IOException ex) { log.error("Patterns not read from {}: {}", file.getPath(), ex.getMessage()); continue; } for (String pattern : patterns) { if (isUseCaseInsensitiveMatching()) { pattern = StringUtils.lowerCase(pattern); } patternList.add(Pattern.compile(pattern)); } log.info("Loaded pattern file: {}", file.getPath()); } } } else { log.info("No patterns loaded from {}", patternsDir.getPath()); } }

Target:
private void loadPatterns(String directory, List<Pattern> patternList) { String dspaceHome = configurationService.getProperty("dspace.dir"); File spidersDir = new File(dspaceHome, "config/spiders"); File patternsDir = new File(spidersDir, directory); if (patternsDir.exists() && patternsDir.isDirectory()) { for (File file : patternsDir.listFiles(new NoDotOldFilter())) { Set<String> patterns; try { patterns = readPatterns(file); } catch (IOException ex) { log.error("Patterns not read from {}: {}", file.getPath(), ex.getMessage()); continue; } for (String pattern : patterns) { if (isUseCaseInsensitiveMatching()) { pattern = StringUtils.lowerCase(pattern); } patternList.add(Pattern.compile(pattern)); } log.info("Loaded pattern file: {}", file.getPath()); } } else { log.info("No patterns loaded from {}", patternsDir.getPath()); } }
Source:
private static String get_or_attr(Map<String, String> obj, String name) { if (obj.containsKey(name)) { return obj.get(name); } else { return null; } }

Target:
private static @Nullable String get_or_attr(Map<String, String> obj, String name) { if (obj.containsKey(name)) { return obj.get(name); } else { return null; } }
Source:
public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("Version:") .append(CURRENT_VERSION) .append("\n") .append("StartTime:") .append(startTime) .append("\n") .append("StartOffsetOfLastIndexSegmentForDeleteCheck"); if (startOffsetOfLastIndexSegmentForDeleteCheck == null) { buffer.append("null"); } else { buffer.append(startOffsetOfLastIndexSegmentForDeleteCheck.toString()); } buffer.append("\n"); buffer.append("CurrentIndex:") .append(currentIdx) .append("\n") .append("CycleLogSize:") .append(cycleLogs.size()) .append("\n") .append("CycleLogs:"); for (CycleLog cycleLog : cycleLogs) { buffer.append(cycleLog.toString()).append("\n\n"); } return buffer.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Version:") .append(CURRENT_VERSION) .append("\n") .append("StartTime:") .append(startTime) .append("\n") .append("StartOffsetOfLastIndexSegmentForDeleteCheck"); if (startOffsetOfLastIndexSegmentForDeleteCheck == null) { sb.append("null"); } else { sb.append(startOffsetOfLastIndexSegmentForDeleteCheck.toString()); } sb.append("\n"); sb.append("CurrentIndex:") .append(currentIdx) .append("\n") .append("CycleLogSize:") .append(cycleLogs.size()) .append("\n") .append("CycleLogs:"); for (CycleLog cycleLog : cycleLogs) { sb.append(cycleLog.toString()).append("\n\n"); } return sb.toString(); }
Source:
public void testVSMResourceVersionMismatch() { setupFileVersionMismatch(true, false, false); Session session = null; try { clearErrors(); session = SessionUIManager.INSTANCE.openSession(sessionResourceURI, new NullProgressMonitor()); String[] args = { RuntimeException.class.getName(), "VSM" }; fail(Messages.format(THROWN_EXCEPTION, args)); } catch (RuntimeException e) { } assertTrue(SESSION_NOT_IN_SESSIONMANAGER, SessionManager.INSTANCE.getSessions().isEmpty()); }

Target:
public void testVSMResourceVersionMismatch() { setupFileVersionMismatch(true, false, false); Session session = null; try { clearErrors(); session = SessionManager.INSTANCE.openSession(sessionResourceURI, new NullProgressMonitor(), SiriusEditPlugin.getPlugin().getUiCallback()); fail(Messages.format(THROWN_EXCEPTION, new String[] { RuntimeException.class.getName(), "VSM" })); } catch (RuntimeException e) { } assertTrue(SESSION_NOT_IN_SESSIONMANAGER, SessionManager.INSTANCE.getSessions().isEmpty()); }
Source:
public void testGetClustersByServiceAndCompatibilityVersion() { List<VDSGroup> vdsGroups = ((VdsGroupDAODbFacadeImpl)dao).getClustersByServiceAndCompatibilityVersion(true, false, new Version("2.3")); assertNotNull(vdsGroups); assertEquals(1, vdsGroups.size()); assertEquals(new Guid("ae956031-6be2-43d6-bb8f-5191c9253314"), vdsGroups.get(0).getId()); }

Target:
public void testGetClustersByServiceAndCompatibilityVersion() { List<VDSGroup> vdsGroups = ((VdsGroupDAODbFacadeImpl)dao).getClustersByServiceAndCompatibilityVersion(true, false, new Version("2.3")); assertNotNull(vdsGroups); assertEquals(1, vdsGroups.size()); assertEquals(FixturesTool.GLUSTER_CLUSTER_ID, vdsGroups.get(0).getId()); }
Source:
public Expression convert(String input) throws OptionsParsingException { if (input.isEmpty()) { return null; } if (isLegacySyntax(input)) { input = convertLegacySyntaxToBooleanFormula(input); GoogleLogger.forEnclosingClass().at(Level.WARNING).log( "Specifying a list of tags separated by comma is legacy syntax and will not be supported after" + " Jan 1, 2021. Consider changing to: " + input); } try { Expression result = Expression.parse(ParserInput.fromLines(input)); validate(result); return result; } catch (SyntaxError.Exception e) { throw new OptionsParsingException("Failed to parse expression: " + e.getMessage() + " input: " + input, e); } }

Target:
@Nullable public Expression convert(String input) throws OptionsParsingException { if (input.isEmpty()) { return null; } if (isLegacySyntax(input)) { input = convertLegacySyntaxToBooleanFormula(input); } try { Expression result = Expression.parse(ParserInput.fromLines(input)); validate(result); return result; } catch (SyntaxError.Exception e) { throw new OptionsParsingException("Failed to parse expression: " + e.getMessage() + " input: " + input, e); } }
Source:
public CompletionStage<Result> queryMetrics() { try { final MetricsQuery metricsQuery = _mapper.treeToValue(request().body().asJson(), MetricsQuery.class); if (!metricsQuery.getMetrics().stream().allMatch(metric -> metric.getAggregators().size() >= 1)) { return CompletableFuture.completedFuture( Results.badRequest("All queried metrics must have at least one aggregator")); } return _kairosService.queryMetrics(metricsQuery) .<JsonNode>thenApply(_mapper::valueToTree) .thenApply(Results::ok); } catch (final IOException e) { return CompletableFuture.completedFuture(Results.internalServerError(e.getMessage())); } }

Target:
public CompletionStage<Result> queryMetrics() { try { final MetricsQuery metricsQuery = _mapper.treeToValue(request().body().asJson(), MetricsQuery.class); if (_requireAggregators && metricsQuery.getMetrics().stream().anyMatch(metric -> metric.getAggregators().isEmpty())) { return CompletableFuture.completedFuture( Results.badRequest("All queried metrics must have at least one aggregator")); } return _kairosService.queryMetrics(metricsQuery) .<JsonNode>thenApply(_mapper::valueToTree) .thenApply(Results::ok); } catch (final IOException e) { return CompletableFuture.completedFuture(Results.internalServerError(e.getMessage())); } }
Source:
T select( IndexSlot slot ) { if ( !instances.containsKey( slot ) ) { assertOpen(); instances.put( slot, factory.apply( slot ) ); } return super.select( slot ); }

Target:
T select( IndexSlot slot ) { return instances.computeIfAbsent( slot, s -> { assertOpen(); return factory.apply( s ); } ); }
Source:
private Properties getCoordinatorStreamProperties(KafkaConfig config) { Properties coordinatorStreamProperties = new Properties(); coordinatorStreamProperties.put("cleanup.policy", "compact"); coordinatorStreamProperties.put("segment.bytes", config.getCoordinatorSegmentBytes()); return coordinatorStreamProperties; }

Target:
private Properties getCoordinatorStreamProperties(KafkaConfig config) { Properties coordinatorStreamProperties = new Properties(); coordinatorStreamProperties.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT); coordinatorStreamProperties.put(TopicConfig.SEGMENT_BYTES_CONFIG, config.getCoordinatorSegmentBytes()); return coordinatorStreamProperties; }
Source:
private void changeValue(float delta) { float newValue = TeraMath.clamp(getValue() + delta, 0, getRange() + getMinimum()); setValue(newValue); }

Target:
private void changeValue(float delta) { float newValue = TeraMath.clamp(getValue() + delta, getMinimum(), getRange() + getMinimum()); setValue(newValue); }