auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean applyTemplate(INarrativeTemplate theTemplate, IBaseResource theResource) { if (templateDoesntApplyToResourceProfiles(theTemplate, theResource)) { return false; } boolean retVal = false; String resourceName = myFhirContext.getResourceDefinition(theResource).getName(); String contextPath = defaultIfEmpty(theTemplate.getContextPath(), resourceName); List<IBase> targets = findTargets(theResource, contextPath); for (IBase nextTargetContext : targets) { BaseRuntimeElementCompositeDefinition<?> targetElementDef = (BaseRuntimeElementCompositeDefinition<?>) getFhirContext().getElementDefinition(nextTargetContext.getClass()); BaseRuntimeChildDefinition targetTextChild = targetElementDef.getChildByName("text"); List<IBase> existing = targetTextChild.getAccessor().getValues(nextTargetContext); INarrative nextTargetNarrative; if (existing.isEmpty()) { nextTargetNarrative = (INarrative) getFhirContext().getElementDefinition("narrative").newInstance(); targetTextChild.getMutator().addValue(nextTargetContext, nextTargetNarrative); } else { nextTargetNarrative = (INarrative) existing.get(0); } String narrative = applyTemplate(theTemplate, nextTargetContext); narrative = cleanWhitespace(narrative); if (isNotBlank(narrative)) { try { nextTargetNarrative.setDivAsString(narrative); nextTargetNarrative.setStatusAsString("generated"); retVal = true; } catch (Exception e) { throw new InternalErrorException(e); } } } return retVal; }

Target:
private boolean applyTemplate(INarrativeTemplate theTemplate, IBaseResource theResource) { if (templateDoesntApplyToResource(theTemplate, theResource)) { return false; } boolean retVal = false; String resourceName = myFhirContext.getResourceDefinition(theResource).getName(); String contextPath = defaultIfEmpty(theTemplate.getContextPath(), resourceName); List<IBase> targets = findElementsInResourceRequiringNarratives(theResource, contextPath); for (IBase nextTargetContext : targets) { INarrative nextTargetNarrative = getOrCreateNarrativeChildElement(nextTargetContext); String narrative = applyTemplate(theTemplate, nextTargetContext); narrative = cleanWhitespace(narrative); if (isNotBlank(narrative)) { try { nextTargetNarrative.setDivAsString(narrative); nextTargetNarrative.setStatusAsString("generated"); retVal = true; } catch (Exception e) { throw new InternalErrorException(e); } } } return retVal; }
Source:
private DiscoverySubsystemDefinition() { super(new Parameters(DiscoveryExtension.SUBSYSTEM_PATH, DiscoveryExtension.getResourceDescriptionResolver()) .setAddHandler(DiscoverySubsystemAddHandler.getInstance()) ); }

Target:
private DiscoverySubsystemDefinition() { super(new Parameters(DiscoveryExtension.SUBSYSTEM_PATH, DiscoveryExtension.getResourceDescriptionResolver()) .setAddHandler(DiscoverySubsystemAddHandler.getInstance()) .setRemoveHandler(new TrivialRemoveStepHandler()) ); }
Source:
private long getExtremeLogEntry(Function<PaxosStateLog<V>, Long> extractor) { lock.readLock().lock(); try { Long result = extractor.apply(currentLog); if (firstEntry.isDone()) { Long experimentalResult = safeReadFromExperimental(extractor::apply); if (!Objects.equals(result, experimentalResult) && result != PaxosAcceptor.NO_LOG_ENTRY && result >= Futures.getUnchecked(firstEntry)) { log.error("Mismatch in getting the extreme log entry between legacy and current implementations." + " Legacy result {}, current result {}.", SafeArg.of("legacy", result), SafeArg.of("current", experimentalResult)); } } return result; } finally { lock.readLock().unlock(); } }

Target:
private long getExtremeLogEntry(Function<PaxosStateLog<V>, Long> extractor) { lock.readLock().lock(); try { Long result = extractor.apply(currentLog); Long experimentalResult = safeReadFromExperimental(extractor::apply); if (!Objects.equals(result, experimentalResult) && result != PaxosAcceptor.NO_LOG_ENTRY) { OptionalLong firstWrittenSequence = firstEntry.isDone() ? OptionalLong.of(Futures.getUnchecked(firstEntry)) : OptionalLong.empty(); log.error("Mismatch in getting the extreme log entry between legacy and current implementations." + " Legacy result {}, current result {}. First written sequence was {}.", SafeArg.of("legacy", result), SafeArg.of("current", experimentalResult), SafeArg.of("firstWrittenSequence", firstWrittenSequence)); } return result; } finally { lock.readLock().unlock(); } }
Source:
private String getSecondaryActionText() { switch (getSecondaryAction()) { case SAVE_AS_DRAFT: return getString(R.string.menu_save_as_draft); case SAVE: return getString(R.string.save); case PUBLISH_NOW: return getString(R.string.menu_publish_now); case NONE: throw new IllegalStateException("getSecondaryActionText shouldn't be called with that case"); } throw new IllegalStateException("getSecondaryActionText shouldn't be called with that case"); }

Target:
private String getSecondaryActionText() { switch (getSecondaryAction()) { case SAVE_AS_DRAFT: return getString(R.string.menu_save_as_draft); case SAVE: return getString(R.string.save); case PUBLISH_NOW: return getString(R.string.menu_publish_now); case NONE: throw new IllegalStateException("Switch in `secondaryAction` shouldn't go through the NONE case"); } throw new IllegalStateException( "Switch in getSecondaryActionText is missing a required case or the case is missing \"return\" " + "keyword "); }
Source:
public static void testDeleteSettlementAccount(SavingsAccount savingsAccount) throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println(methodName = "\nIn " + methodName); LoanAccount loanAccountToBeUpdated = newAccount; LoansService loanService = MambuAPIFactory.getLoanService(); boolean deleteResult = loanService.deleteSettlementAccount(loanAccountToBeUpdated.getEncodedKey(), savingsAccount.getEncodedKey()); System.out.println("The delete resut is: " + deleteResult); }

Target:
public static void testDeleteSettlementAccount(SavingsAccount savingsAccount) throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println(methodName = "\nIn " + methodName); LoanAccount loanAccountToBeUpdated = newAccount; LoansService loanService = MambuAPIFactory.getLoanService(); boolean deleteResult = loanService.deleteSettlementAccount(loanAccountToBeUpdated.getEncodedKey(), savingsAccount.getEncodedKey()); System.out.println("The delete result is: " + deleteResult); }
Source:
synchronized void tryToProvidePreviewSurface() { if (mResolution == null || mSurfaceTexture == null || mSurfaceCompleter == null) { return; } mSurfaceTexture.setDefaultBufferSize(mResolution.getWidth(), mResolution.getHeight()); final Surface surface = new Surface(mSurfaceTexture); mSurfaceCount.register(); final ListenableFuture<Void> surfaceReleaseFuture = mSurfaceReleaseFuture; mSurfaceReleaseFuture.addListener( () -> onSurfaceReleaseFutureComplete(surface, surfaceReleaseFuture), ContextCompat.getMainExecutor(mTextureView.getContext())); mSurfaceCompleter.set(surface); mCompleterMap.remove(mSurfaceCompleter); mSurfaceCompleter = null; correctPreviewForCenterCrop(mParent, mTextureView, mResolution); }

Target:
void tryToProvidePreviewSurface() { Threads.checkMainThread(); if (mResolution == null || mSurfaceTexture == null || mSurfaceCompleter == null) { return; } mSurfaceTexture.setDefaultBufferSize(mResolution.getWidth(), mResolution.getHeight()); final Surface surface = new Surface(mSurfaceTexture); incrementSurfaceCount(); final ListenableFuture<Void> surfaceReleaseFuture = mSurfaceReleaseFuture; mSurfaceReleaseFuture.addListener( () -> onSurfaceReleaseFutureComplete(surface, surfaceReleaseFuture), ContextCompat.getMainExecutor(mTextureView.getContext())); mSurfaceCompleter.set(surface); mCompleterMap.remove(mSurfaceCompleter); mSurfaceCompleter = null; correctPreviewForCenterCrop(mParent, mTextureView, mResolution); }
Source:
protected void executeQueryCommand() { final List<VdsNetworkInterface> vdsInterfaces = interfaceDao.getAllInterfacesForVds(getParameters().getId(), getUserID(), getParameters().isFiltered()); List<VdsNetworkInterface> interfaces = new ArrayList<>(vdsInterfaces.size()); if (!vdsInterfaces.isEmpty()) { VdsStatic vdsStatic = vdsStaticDao.get(getParameters().getId()); Map<String, Network> networks = Entities.entitiesByName(networkDao.getAllForCluster(vdsStatic.getClusterId())); for (final VdsNetworkInterface nic : vdsInterfaces) { if (!nic.isBond() || nicDoesHaveSlaves(vdsInterfaces, nic)) { interfaces.add(nic); Network network = networks.get(nic.getNetworkName()); NetworkImplementationDetails networkImplementationDetails = networkImplementationDetailsUtils.calculateNetworkImplementationDetails(nic, network); nic.setNetworkImplementationDetails(networkImplementationDetails); } if (nic.isBond()) { boolean isAdPartnerInvalid = StringUtils.isEmpty(nic.getAdPartnerMac()) && InterfaceStatus.UP.equals(nic.getStatistics().getStatus()) && BondMode.BOND4.equals(BondMode.parseBondMode(nic.getBondOptions())); boolean isAdPartnerSupportedForCluster = FeatureSupported.adPartenerMacSupported(clusterDao.get(vdsStatic.getClusterId()).getCompatibilityVersion()); Bond bond = (Bond) nic; bond.setAdPartnerMacValid(!isAdPartnerSupportedForCluster || !isAdPartnerInvalid); } } } getQueryReturnValue().setReturnValue(interfaces); }

Target:
protected void executeQueryCommand() { final List<VdsNetworkInterface> vdsInterfaces = interfaceDao.getAllInterfacesForVds(getParameters().getId(), getUserID(), getParameters().isFiltered()); List<VdsNetworkInterface> interfaces = new ArrayList<>(vdsInterfaces.size()); if (!vdsInterfaces.isEmpty()) { VdsStatic vdsStatic = vdsStaticDao.get(getParameters().getId()); Map<String, Network> networks = Entities.entitiesByName(networkDao.getAllForCluster(vdsStatic.getClusterId())); for (final VdsNetworkInterface nic : vdsInterfaces) { if (!nic.isBond() || nicDoesHaveSlaves(vdsInterfaces, nic)) { interfaces.add(nic); Network network = networks.get(nic.getNetworkName()); NetworkImplementationDetails networkImplementationDetails = networkImplementationDetailsUtils.calculateNetworkImplementationDetails(nic, network); nic.setNetworkImplementationDetails(networkImplementationDetails); } if (nic.isBond()) { Bond bond = (Bond) nic; bond.setAdPartnerMacValid(isAdPartnerMacValid(bond, vdsStatic)); } } } getQueryReturnValue().setReturnValue(interfaces); }
Source:
public void renameWhileComputing() throws Exception { CoordinatedComputedFolder d = r.jenkins.createProject(CoordinatedComputedFolder.class, "d"); d.kids.addAll(Arrays.asList("A", "B")); QueueTaskFuture<Queue.Executable> future = d.scheduleBuild2(0).getFuture(); FolderComputation<FreeStyleProject> computation; while (Executor.of((computation = d.getComputation())) == null) { Thread.sleep(50); } try { d.checkRename("d2"); fail("Should be blocked while computation is in progress"); } catch (Failure f) { assertThat(f.getMessage(), is(Messages.ComputedFolder_ComputationInProgress())); } }

Target:
public void renameWhileComputing() throws Exception { CoordinatedComputedFolder d = r.jenkins.createProject(CoordinatedComputedFolder.class, "d"); d.kids.addAll(Arrays.asList("A", "B")); QueueTaskFuture<Queue.Executable> future = d.scheduleBuild2(0).getFuture(); future.waitForStart(); try { d.checkRename("d2"); fail("Should be blocked while computation is in progress"); } catch (Failure f) { assertThat(f.getMessage(), is(Messages.ComputedFolder_ComputationInProgress())); } d.onKid("B"); future.get(); waitUntilNoActivityIgnoringThreadDeathUpTo(10000); d.checkRename("d2"); }
Source:
private Map<String, Entity> createUserEntites(List<String> userLines) { Map<String, Entity> users = new HashMap<String, Entity>(); for (String line : userLines) { String[] userParts = line.split(",", 3); if (userParts.length < 3 || userParts[0].trim().length() == 0) { System.out.println("Skipping user: " + line); } Entity user = new Entity(USER_KIND); user.setProperty(USER_EMAIL_FIELD, userParts[0].trim()); user.setProperty(USER_PERMISSION_FIELD, userParts[1].trim()); user.setProperty(USER_ROLE_FIELD, Boolean.valueOf(userParts[2].trim())); users.put(userParts[0].trim(), user); } return users; }

Target:
private Map<String, Entity> createUserEntites(List<String> userLines) { Map<String, Entity> users = new HashMap<String, Entity>(); for (String line : userLines) { String[] userParts = line.split(",", 3); if (userParts.length < 3 || userParts[0].trim().length() == 0) { System.out.println("Skipping user: " + line); continue; } Entity user = new Entity(USER_KIND); user.setProperty(USER_EMAIL_FIELD, userParts[0].trim()); user.setProperty(USER_PERMISSION_FIELD, userParts[1].trim()); user.setProperty(USER_ROLE_FIELD, Boolean.valueOf(userParts[2].trim())); users.put(userParts[0].trim(), user); } return users; }
Source:
private void getAllSections(final int expectedNumberOfSections, final String title) throws Throwable { final CountDownLatch completionLatch = new CountDownLatch(1); startActivity(new Intent(), null, null); runTestOnUiThread(new Runnable() { @Override public void run() { final WikipediaApp app = (WikipediaApp) getInstrumentation().getTargetContext().getApplicationContext(); new SectionsFetchTask(app, new PageTitle(null, title, new Site("test.wikipedia.org")), "all") { @Override public void onFinish(List<Section> result) { assertNotNull(result); assertEquals(expectedNumberOfSections, result.size()); completionLatch.countDown(); } }.execute(); } }); assertTrue(completionLatch.await(TASK_COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS)); }

Target:
private void getAllSections(final int expectedNumberOfSections, final String title) throws Throwable { final CountDownLatch completionLatch = new CountDownLatch(1); startActivity(new Intent(), null, null); runTestOnUiThread(new Runnable() { @Override public void run() { final WikipediaApp app = WikipediaApp.getInstance(); new SectionsFetchTask(app, new PageTitle(null, title, new Site("test.wikipedia.org")), "all") { @Override public void onFinish(List<Section> result) { assertNotNull(result); assertEquals(expectedNumberOfSections, result.size()); completionLatch.countDown(); } }.execute(); } }); assertTrue(completionLatch.await(TASK_COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS)); }
Source:
public void respondOk_whenSearchMandatesRequest(Map<String, StringValuePattern> searchParams, SearchMandateConnectorResponse response, String gatewayAccountId) { try { String responseAsJson = new ObjectMapper().writeValueAsString(response); wireMockClassRule.stubFor(get(urlPathEqualTo(format(CONNECTOR_MOCK_MANDATES_PATH, gatewayAccountId))) .withHeader(ACCEPT, matching(APPLICATION_JSON)) .withQueryParams(searchParams) .willReturn(aResponse() .withStatus(200) .withHeader(CONTENT_TYPE, APPLICATION_JSON) .withBody(responseAsJson))); } catch (JsonProcessingException e) { e.printStackTrace(); } }

Target:
public void respondOk_whenSearchMandatesRequest(Map<String, StringValuePattern> searchParams, SearchMandateConnectorResponse response, String gatewayAccountId) throws JsonProcessingException { String responseAsJson = new ObjectMapper().writeValueAsString(response); wireMockClassRule.stubFor(get(urlPathEqualTo(format(CONNECTOR_MOCK_MANDATES_PATH, gatewayAccountId))) .withHeader(ACCEPT, matching(APPLICATION_JSON)) .withQueryParams(searchParams) .willReturn(aResponse() .withStatus(200) .withHeader(CONTENT_TYPE, APPLICATION_JSON) .withBody(responseAsJson))); }
Source:
private MavenExecutionResult readProjectWithDependencies(IProjectRegistry state, final IFile pomFile, ResolverConfiguration resolverConfiguration, final IProgressMonitor monitor) { try { return execute(state, pomFile, resolverConfiguration, new ICallable<MavenExecutionResult>() { public MavenExecutionResult call(IMavenExecutionContext context, IProgressMonitor monitor) throws CoreException { ProjectBuildingRequest configuration = context.newProjectBuildingRequest(); configuration.setResolveDependencies(true); MavenExecutionResult res = getMaven().readMavenProjects(Collections.singleton(pomFile.getLocation().toFile()), configuration); return res; } }, monitor); } catch(CoreException ex) { DefaultMavenExecutionResult result = new DefaultMavenExecutionResult(); result.addException(ex); return result; } }

Target:
private MavenExecutionResult readProjectWithDependencies(IProjectRegistry state, final IFile pomFile, ResolverConfiguration resolverConfiguration, final IProgressMonitor monitor) { try { return execute(state, pomFile, resolverConfiguration, (context, pm) -> { ProjectBuildingRequest configuration = context.newProjectBuildingRequest(); configuration.setResolveDependencies(true); return getMaven().readMavenProject(pomFile.getLocation().toFile(), configuration); }, monitor); } catch(CoreException ex) { DefaultMavenExecutionResult result = new DefaultMavenExecutionResult(); result.addException(ex); return result; } }
Source:
public void testMVResolution() throws IOException, ProcCallException { final Client client = withViews( "CREATE VIEW v5_1 AS SELECT DISTINCT a1 distinct_a1, COUNT(b1) count_b1, SUM(a) sum_a, " + "COUNT(*) counts FROM t1 WHERE b >= 2 OR b1 IN (3,30,300) GROUP BY a1;", "CREATE VIEW v5_2 AS SELECT a a, COUNT(b1) count_b1, SUM(a) sum_a, " + "COUNT(*) counts FROM t1 WHERE b >= 2 AND b1 IN (3,30,300) GROUP BY a;", "CREATE VIEW v5_3 AS SELECT a1 a1, COUNT(b1) count_b1, SUM(a) sum_a, " + "COUNT(*) counts FROM t1 WHERE b >= 2 OR b1 IN (3,30,300) GROUP BY a1;", "CREATE VIEW v5_4 AS SELECT a1 a1, COUNT(b1) count_b1, SUM(a) sum_a, " + "COUNT(*) counts FROM t1 WHERE a >= 2 OR b1 IN (3,30,300) GROUP BY a1;"); String adHocQuery = "SELECT COUNT(b1) cb FROM t1 WHERE b >= 2 OR b1 in (3, 30, 300) GROUP BY a1"; String matchedQuery = "SELECT COUNT(b1) cb FROM t1 WHERE b >= 2 OR b1 in (3, 30, 300) GROUP BY a1"; assertTablesAreEqual("Exact match with view", client.callProcedure("@AdHoc", adHocQuery + " order by cb").getResults()[0], client.callProcedure("@AdHoc", matchedQuery + " order by cb").getResults()[0]); assertTrue(getQueryPlan('\n', client, adHocQuery).toLowerCase().contains("sequential scan of \"v5_3\"".toLowerCase())); cleanTableAndViews(client, "V5_1", "V5_2", "V5_3", "V5_4"); }

Target:
public void testMVResolution() throws IOException, ProcCallException { final Client client = withViews( "CREATE VIEW v5_1 AS SELECT DISTINCT a1 distinct_a1, COUNT(b1) count_b1, SUM(a) sum_a, " + "COUNT(*) counts FROM t1 WHERE b >= 2 OR b1 IN (3,30,300) GROUP BY a1;", "CREATE VIEW v5_2 AS SELECT a a, COUNT(b1) count_b1, SUM(a) sum_a, " + "COUNT(*) counts FROM t1 WHERE b >= 2 AND b1 IN (3,30,300) GROUP BY a;", "CREATE VIEW v5_3 AS SELECT a1 a1, COUNT(b1) count_b1, SUM(a) sum_a, " + "COUNT(*) counts FROM t1 WHERE b >= 2 OR b1 IN (3,30,300) GROUP BY a1;", "CREATE VIEW v5_4 AS SELECT a1 a1, COUNT(b1) count_b1, SUM(a) sum_a, " + "COUNT(*) counts FROM t1 WHERE a >= 2 OR b1 IN (3,30,300) GROUP BY a1;"); assertTablesAreEqual("Exact match with view", client.callProcedure("@AdHoc", "SELECT COUNT(b1) cb FROM t1 WHERE b >= 2 OR b1 in (3, 30, 300) GROUP BY a1 order by cb").getResults()[0], client.callProcedure("@AdHoc", "SELECT count_b1 cb FROM v5_1 order by cb").getResults()[0]); assertTrue(getQueryPlan('\n', client, "SELECT COUNT(b1) cb FROM t1 WHERE b >= 2 OR b1 in (3, 30, 300) GROUP BY a1").toLowerCase().contains("sequential scan of \"v5_3\"".toLowerCase())); cleanTableAndViews(client, "V5_1", "V5_2", "V5_3", "V5_4"); }
Source:
public void testGetMediaInformation() throws IOException { FFmpegProbeResult probeResult = ffprobe.probe(Samples.big_buck_bunny_720p_1mb); FFmpegFormat format = probeResult.getFormat(); String line1 = String.format(Locale.US, "File: '%s' ; Format: '%s' ; Duration: %.3fs", format.filename, format.format_long_name, format.duration); FFmpegStream stream = probeResult.getStreams().get(0); String line2 = String.format(Locale.US, "Codec: '%s' ; Width: %dpx ; Height: %dpx", stream.codec_long_name, stream.width, stream.height); assertThat( line1, is("File: 'src/test/resources/net/bramp/ffmpeg/samples/big_buck_bunny_720p_1mb.mp4' ; Format: 'QuickTime / MOV' ; Duration: 5.312s")); assertThat(line2, is("Codec: 'H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10' ; Width: 1280px ; Height: 720px")); }

Target:
public void testGetMediaInformation() throws IOException { FFmpegProbeResult probeResult = ffprobe.probe(Samples.big_buck_bunny_720p_1mb); FFmpegFormat format = probeResult.getFormat(); String line1 = String.format(locale, "File: '%s' ; Format: '%s' ; Duration: %.3fs", format.filename, format.format_long_name, format.duration); FFmpegStream stream = probeResult.getStreams().get(0); String line2 = String.format(locale, "Codec: '%s' ; Width: %dpx ; Height: %dpx", stream.codec_long_name, stream.width, stream.height); assertThat( line1, is("File: 'src/test/resources/net/bramp/ffmpeg/samples/big_buck_bunny_720p_1mb.mp4' ; Format: 'QuickTime / MOV' ; Duration: 5.312s")); assertThat(line2, is("Codec: 'H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10' ; Width: 1280px ; Height: 720px")); }
Source:
public int getFolderUnreadCount(Context context, String folderName) throws MessagingException { if (!isAvailable(context)) { return 0; } int unreadMessageCount = 0; ContentResolver cr = context.getContentResolver(); Uri uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI, "account/" + getUuid() + "/stats"); String[] projection = { StatsColumns.UNREAD_COUNT, }; LocalSearch search = new LocalSearch(); search.addAllowedFolder(folderName); StringBuilder query = new StringBuilder(); List<String> queryArgs = new ArrayList<>(); ConditionsTreeNode conditions = search.getConditions(); SqlQueryBuilder.buildWhereClause(this, conditions, query, queryArgs); String selection = query.toString(); String[] selectionArgs = queryArgs.toArray(new String[0]); Cursor cursor = cr.query(uri, projection, selection, selectionArgs, null); try { if (cursor != null && cursor.moveToFirst()) { unreadMessageCount = cursor.getInt(0); } } finally { Utility.closeQuietly(cursor); } return unreadMessageCount; }

Target:
public int getFolderUnreadCount(Context context, String folderName) throws MessagingException { if (!isAvailable(context)) { return 0; } int unreadMessageCount = 0; Cursor cursor = loadUnreadCountForFolder(context, folderName); try { if (cursor != null && cursor.moveToFirst()) { unreadMessageCount = cursor.getInt(0); } } finally { Utility.closeQuietly(cursor); } return unreadMessageCount; }
Source:
public DataTransactionResult remove(DataHolder dataHolder) { IMixinTileEntityShulkerBox box = (IMixinTileEntityShulkerBox) dataHolder; DyeColor color = (DyeColor) (Object) box.getColor(); box.setColor(null); return DataTransactionResult.successRemove(new ImmutableSpongeValue<>(Keys.DYE_COLOR, DyeColors.PURPLE, color)); }

Target:
public DataTransactionResult remove(DataHolder dataHolder) { IMixinTileEntityShulkerBox box = (IMixinTileEntityShulkerBox) dataHolder; DyeColor color = (DyeColor) (Object) box.getColor(); box.setColor(null); if (color == null) { return DataTransactionResult.failNoData(); } return DataTransactionResult.successRemove(ImmutableSpongeValue.cachedOf(Keys.DYE_COLOR, DyeColors.PURPLE, color)); }
Source:
public void delete(APIContext apiContext) throws PayPalRESTException { if (this.getId() == null) { throw new IllegalArgumentException("Id cannot be null"); } apiContext.setRequestId(null); Object[] parameters = new Object[] {this.getId()}; String pattern = "v1/payment-experience/web-profiles/{0}"; String resourcePath = RESTUtil.formatURIPath(pattern, parameters); String payLoad = ""; configureAndExecute(apiContext, HttpMethod.DELETE, resourcePath, payLoad, null); apiContext.setRequestId(null); }

Target:
public void delete(APIContext apiContext) throws PayPalRESTException { if (this.getId() == null) { throw new IllegalArgumentException("Id cannot be null"); } Object[] parameters = new Object[] {this.getId()}; String pattern = "v1/payment-experience/web-profiles/{0}"; String resourcePath = RESTUtil.formatURIPath(pattern, parameters); String payLoad = ""; configureAndExecute(apiContext, HttpMethod.DELETE, resourcePath, payLoad, null); }
Source:
public void testUncompress_withSymbolicLinks() throws IOException { File inputFile = null; try { inputFile = new File(inputUrl.toURI().getPath(), "tarLink.tar.gz"); } catch (URISyntaxException e) { e.printStackTrace(); } final File temporaryDirectory = Files.createTempDir(); temporaryDirectory.deleteOnExit(); final List<File> extractedFiles = extractor.uncompress(inputFile, temporaryDirectory, e -> {}); final File file1 = new File(temporaryDirectory, "file1.txt"); final File file2 = new File(temporaryDirectory, "file1_link.txt"); assertTrue(file1.exists()); assertTrue(file2.exists()); assertEquals("file1content", new String(FileUtils.readFileToByteArray(file1))); assertEquals("file1content", new String(FileUtils.readFileToByteArray(file2))); assertTrue(java.nio.file.Files.isSymbolicLink(Paths.get(file2.getPath()))); }

Target:
public void testUncompress_withSymbolicLinks() throws IOException, URISyntaxException { File inputFile = new File(inputUrl.toURI().getPath(), "tarLink.tar.gz"); final File temporaryDirectory = Files.createTempDir(); temporaryDirectory.deleteOnExit(); final List<File> extractedFiles = extractor.uncompress(inputFile, temporaryDirectory, e -> {}); final File file1 = new File(temporaryDirectory, "file1.txt"); final File file2 = new File(temporaryDirectory, "file1_link.txt"); assertTrue(file1.exists()); assertTrue(file2.exists()); assertEquals("file1content", new String(FileUtils.readFileToByteArray(file1))); assertEquals("file1content", new String(FileUtils.readFileToByteArray(file2))); assertTrue(java.nio.file.Files.isSymbolicLink(Paths.get(file2.getPath()))); }
Source:
public static void output(@AggregationState PrecisionRecallState state, BlockBuilder out) { Iterator<PrecisionRecallAggregation.BucketResult> resultsIterator = getResultsIterator(state); BlockBuilder entryBuilder = out.beginBlockEntry(); while (resultsIterator.hasNext()) { final BucketResult result = resultsIterator.next(); final Double remainingTrueWeight = result.totalTrueWeight - result.runningTrueWeight; final Double remainingFalseWeight = result.totalFalseWeight - result.runningFalseWeight; DoubleType.DOUBLE.writeDouble( entryBuilder, remainingTrueWeight / (remainingTrueWeight + remainingFalseWeight)); } out.closeEntry(); }

Target:
public static void output(@AggregationState PrecisionRecallState state, BlockBuilder out) { Iterator<PrecisionRecallAggregation.BucketResult> resultsIterator = getResultsIterator(state); BlockBuilder entryBuilder = out.beginBlockEntry(); while (resultsIterator.hasNext()) { final BucketResult result = resultsIterator.next(); final double remainingTrueWeight = result.totalTrueWeight - result.runningTrueWeight; final double remainingFalseWeight = result.totalFalseWeight - result.runningFalseWeight; DoubleType.DOUBLE.writeDouble( entryBuilder, remainingTrueWeight / (remainingTrueWeight + remainingFalseWeight)); } out.closeEntry(); }
Source:
public boolean apply(Game game, Ability source) { AtTheBeginOfNextEndStepDelayedTriggeredAbility delayedLifeLost = new AtTheBeginOfNextEndStepDelayedTriggeredAbility(new LoseLifeSourceControllerEffect(1)); game.addDelayedTriggeredAbility(delayedLifeLost, source); Effect effect = new ReturnToHandTargetEffect(); effect.setText("return Brood of Cockroaches to your hand."); effect.setTargetPointer(new FixedTarget(source.getSourceId(), source.getSourceObjectZoneChangeCounter())); DelayedTriggeredAbility delayedAbility = new AtTheBeginOfNextEndStepDelayedTriggeredAbility(effect); game.addDelayedTriggeredAbility(delayedAbility, source); return true; }

Target:
public boolean apply(Game game, Ability source) { AtTheBeginOfNextEndStepDelayedTriggeredAbility delayedLifeLost = new AtTheBeginOfNextEndStepDelayedTriggeredAbility(new LoseLifeSourceControllerEffect(1)); game.addDelayedTriggeredAbility(delayedLifeLost, source); Effect effect = new ReturnToHandTargetEffect(); effect.setText("return {this} to your hand."); effect.setTargetPointer(new FixedTarget(source.getSourceId(), source.getSourceObjectZoneChangeCounter())); DelayedTriggeredAbility delayedAbility = new AtTheBeginOfNextEndStepDelayedTriggeredAbility(effect); game.addDelayedTriggeredAbility(delayedAbility, source); return true; }
Source:
public ServiceResponse delete(String url, String data) throws JAXBException, IOException, URISyntaxException, AuthenticationException { return Util.sendRequest(url, "delete"); }

Target:
public ServiceResponse delete(String url, String data) throws JAXBException, IOException, URISyntaxException, AuthenticationException { return Util.sendRequest(url + "/feed/" + Util.readDatasetName(data) + colo, "delete"); }
Source:
public static ByteBuf encodeMetadata( ByteBufAllocator allocator, WellKnownAuthType authType, ByteBuf metadata) { if (authType == WellKnownAuthType.UNPARSEABLE_AUTH_TYPE || authType == WellKnownAuthType.UNKNOWN_RESERVED_AUTH_TYPE) { metadata.release(); throw new IllegalArgumentException("only allowed AuthType should be used"); } int capacity = AUTH_TYPE_ID_LENGTH; ByteBuf headerBuffer = allocator .buffer(capacity, capacity) .writeByte(authType.getIdentifier() | STREAM_METADATA_KNOWN_MASK); return TupleByteBuf.of(allocator, headerBuffer, metadata); }

Target:
public static ByteBuf encodeMetadata( ByteBufAllocator allocator, WellKnownAuthType authType, ByteBuf metadata) { if (authType == WellKnownAuthType.UNPARSEABLE_AUTH_TYPE || authType == WellKnownAuthType.UNKNOWN_RESERVED_AUTH_TYPE) { throw new IllegalArgumentException("only allowed AuthType should be used"); } int capacity = AUTH_TYPE_ID_LENGTH; ByteBuf headerBuffer = allocator .buffer(capacity, capacity) .writeByte(authType.getIdentifier() | STREAM_METADATA_KNOWN_MASK); return TupleByteBuf.of(allocator, headerBuffer, metadata); }
Source:
public String getProvidedExtensionAsServer() { return EXTENSION_REGISTERED_NAME; }

Target:
public String getProvidedExtensionAsServer() { return EXTENSION_REGISTERED_NAME + "; " + SERVER_NO_CONTEXT_TAKEOVER + (clientNoContextTakeover ? "; " + CLIENT_NO_CONTEXT_TAKEOVER : ""); }
Source:
public void accept(CsvFileSource annotation) { resources = annotation.resources(); charset = Charset.forName(annotation.encoding()); skipHeaderLines = annotation.skipHeaderLines(); settings = new CsvParserSettings(); settings.getFormat().setDelimiter(annotation.delimiter()); settings.getFormat().setLineSeparator(annotation.lineSeparator()); settings.getFormat().setQuote('"'); settings.getFormat().setQuoteEscape('"'); settings.setEmptyValue(""); settings.setAutoConfigurationEnabled(false); }

Target:
public void accept(CsvFileSource annotation) { resources = annotation.resources(); charset = Charset.forName(annotation.encoding()); numLinesToSkip = annotation.numLinesToSkip(); settings = new CsvParserSettings(); settings.getFormat().setDelimiter(annotation.delimiter()); settings.getFormat().setLineSeparator(annotation.lineSeparator()); settings.getFormat().setQuote('"'); settings.getFormat().setQuoteEscape('"'); settings.setEmptyValue(""); settings.setAutoConfigurationEnabled(false); }
Source:
private void setQcowCompat() { if (getDiskImage().getDiskStorageType() == DiskStorageType.IMAGE) { final DiskImage newDiskImage = getDiskImage(); if (newDiskImage.getVolumeFormat().equals(VolumeFormat.COW)) { try { setQcowCompat(newDiskImage.getImage(), newDiskImage.getStoragePoolId(), newDiskImage.getId(), newDiskImage.getImageId(), getParameters().getStorageDomainId(), null); imageDao.update(newDiskImage.getImage()); } catch (EngineException e) { log.error("Unable to update the image info for image '{}' (image group: '{}') on domain '{}'", newDiskImage.getImageId(), newDiskImage.getId(), getParameters().getStorageDomainId()); } } } }

Target:
private void setQcowCompat() { if (getDiskImage().getDiskStorageType() == DiskStorageType.IMAGE && getDiskImage().getVolumeFormat().equals(VolumeFormat.COW)) { DiskImage newDiskImage = getDiskImage(); try { setQcowCompat(newDiskImage.getImage(), newDiskImage.getStoragePoolId(), newDiskImage.getId(), newDiskImage.getImageId(), getParameters().getStorageDomainId(), null); imageDao.update(newDiskImage.getImage()); } catch (EngineException e) { log.error("Unable to update the image info for image '{}' (image group: '{}') on domain '{}'", newDiskImage.getImageId(), newDiskImage.getId(), getParameters().getStorageDomainId()); } } }
Source:
public void setPayloadFilter(String stringPattern, boolean isRegex, boolean isIgnoreCase,boolean isInverted) throws PatternSyntaxException { if(stringPattern == null || stringPattern.length() == 0){ this.payloadFilter = null; }else{ payloadFilter = new WebSocketMessagesPayloadFilter(stringPattern, isRegex, isIgnoreCase, isInverted); } }

Target:
public void setPayloadFilter(String stringPattern, boolean isRegex, boolean isIgnoreCase,boolean isInverted) throws PatternSyntaxException { if(stringPattern == null || stringPattern.isEmpty()){ payloadFilter = null; }else{ payloadFilter = new WebSocketMessagesPayloadFilter(stringPattern, isRegex, isIgnoreCase, isInverted); } }
Source:
private void setFilters(final Map<ProgramFilters, Object> filters, final String crop, final String programName) { List<CropType> croptypeList; croptypeList = this.workbenchDataManager.getInstalledCropDatabses(); for (CropType cropType : croptypeList) { if (cropType.getCropName().equalsIgnoreCase(crop)) { filters.put(ProgramFilters.CROP_TYPE, cropType); } } if (!StringUtils.isBlank(programName)) { filters.put(ProgramFilters.PROGRAM_NAME, programName); } }

Target:
private void setFilters(final Map<ProgramFilters, Object> filters, final String crop, final String programName) { List<CropType> cropTypeList; cropTypeList = this.workbenchDataManager.getInstalledCropDatabses(); for (final CropType cropType : cropTypeList) { if (cropType.getCropName().equalsIgnoreCase(crop)) { filters.put(ProgramFilters.CROP_TYPE, cropType); } } if (!StringUtils.isBlank(programName)) { filters.put(ProgramFilters.PROGRAM_NAME, programName); } }
Source:
public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { try { IStatus status = Central.bndCall(() -> { BndEditModel model = new BndEditModel(project); model.load(); switch (pathtype) { case Constants.TESTPATH : model.addPath(bundle, Constants.TESTPATH); break; case Constants.BUILDPATH : default : model.addPath(bundle, Constants.BUILDPATH); break; } model.saveChanges(); Central.refreshFile(project.getPropertiesFile()); return Status.OK_STATUS; }); String[] determine = Descriptors.determine(fqn) .unwrap(); assert determine[0] != null : "We must have found a package"; if (determine[1] == null) { context.getCompilationUnit() .createImport(fqn + ".*", null, monitor); } else { context.getCompilationUnit() .createImport(fqn, null, monitor); } return status; } catch (Exception e) { throw new CoreException( new Status(IStatus.ERROR, Plugin.PLUGIN_ID, "Failed to add bundle to -buildpath", e)); } }

Target:
public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { try { IStatus status = Central.bndCall(() -> { BndEditModel model = new BndEditModel(project); model.load(); switch (pathtype) { case Constants.TESTPATH : model.addPath(bundle, Constants.TESTPATH); break; case Constants.BUILDPATH : default : model.addPath(bundle, Constants.BUILDPATH); break; } model.saveChanges(); Central.refreshFile(project.getPropertiesFile()); return Status.OK_STATUS; }, monitor); String[] determine = Descriptors.determine(fqn) .unwrap(); assert determine[0] != null : "We must have found a package"; if (doImport) { if (determine[1] == null) { context.getCompilationUnit() .createImport(fqn + ".*", null, monitor); } else { context.getCompilationUnit() .createImport(fqn, null, monitor); } } return status; } catch (Exception e) { return new Status(IStatus.ERROR, Plugin.PLUGIN_ID, "Failed to add bundle " + bundle + " to " + pathtype, e); } }
Source:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, ctx -> this.ignoreList = new LinkedList<>()); context.registerSyntaxNodeConsumer(Tree.Kind.IF_STMT, ctx -> { PyIfStatementTree ifStatement = (PyIfStatementTree) ctx.syntaxNode(); if (ignoreList.contains(ifStatement)) { return; } List<PyExpressionTree> conditions = getConditionsToCompare(ifStatement); findSameConditions(conditions, ctx); }); }

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, ctx -> this.ignoreList = new ArrayList<>()); context.registerSyntaxNodeConsumer(Tree.Kind.IF_STMT, ctx -> { PyIfStatementTree ifStatement = (PyIfStatementTree) ctx.syntaxNode(); if (ignoreList.contains(ifStatement)) { return; } List<PyExpressionTree> conditions = getConditionsToCompare(ifStatement); findSameConditions(conditions, ctx); }); }
Source:
public void run() { try { startDiscovery(); while (shouldRun) { try { DiscoveryServiceEvent event = eventQueue.take(); processEvent(event); } catch (Exception e) { log.error("Caught an exception. Stop discovery service.", e); shouldRun = false; stopLogReplication(); if (e instanceof InterruptedException) { Thread.interrupted(); } } } } catch (LogReplicationDiscoveryServiceException e) { log.error("Exceptionally terminate Log Replication Discovery Service", e); discoveryCallback.completeExceptionally(e); } catch (Exception e) { log.error("Unhandled exception caught during log replication service discovery", e); } finally { if (runtime != null) { runtime.shutdown(); } } }

Target:
public void run() { try { startDiscovery(); while (shouldRun) { try { DiscoveryServiceEvent event = eventQueue.take(); processEvent(event); } catch (Exception e) { log.error("Caught an exception. Stop discovery service.", e); shouldRun = false; stopLogReplication(); if (e instanceof InterruptedException) { Thread.interrupted(); } } } } catch (LogReplicationDiscoveryServiceException e) { log.error("Exceptionally terminate Log Replication Discovery Service", e); serverCallback.completeExceptionally(e); } catch (Exception e) { log.error("Unhandled exception caught during log replication service discovery. Retry,", e); } finally { if (runtime != null) { runtime.shutdown(); } } }
Source:
protected abstract void extractMemberMetadata(Member member, InternalCompletableFuture future, MetadataHolder metadataHolder) throws Exception; protected abstract InternalCompletableFuture fetchMetadataOf(Address address, List<String> names); private Map<Member, InternalCompletableFuture> fetchMembersMetadataFor(List<String> names) { Collection<Member> members = getDataMembers(); if (members.isEmpty()) { return Collections.emptyMap(); } Map<Member, InternalCompletableFuture> futureByMember = createHashMap(members.size()); for (Member member : members) { Address address = member.getAddress(); try { futureByMember.put(member, fetchMetadataOf(address, names)); } catch (Exception e) { if (logger.isWarningEnabled()) { logger.warning(format("Can't fetch invalidation meta-data of %s", member), e); } } } return futureByMember; }

Target:
protected abstract void extractMemberMetadata(Member member, InternalCompletableFuture future, MetadataHolder metadataHolder) throws Exception; protected abstract InternalCompletableFuture fetchMetadataOf(Address address, List<String> names); private Map<Member, InternalCompletableFuture> fetchMembersMetadataFor(List<String> names) { Collection<Member> members = getDataMembers(); if (members.isEmpty()) { return Collections.emptyMap(); } Map<Member, InternalCompletableFuture> futureByMember = createHashMap(members.size()); for (Member member : members) { Address address = member.getAddress(); try { futureByMember.put(member, fetchMetadataOf(address, names)); } catch (HazelcastInstanceNotActiveException e) { logger.finest(e); } catch (Exception e) { if (logger.isWarningEnabled()) { logger.warning(format("Can't fetch invalidation meta-data of %s", member), e); } } } return futureByMember; }
Source:
public MyNakadiRuntimeException1() { super(); }

Target:
public MyNakadiRuntimeException1() { }
Source:
protected void configure() { bind(Boolean.class).annotatedWith(Names.named("testing")).toInstance(true); bindListener(InstanceOfMatcher.createFor(WebApplication.class), new TypeListener() { @Override public <I> void hear(TypeLiteral<I> type, final TypeEncounter<I> encounter) { final Provider<Injector> injectorProvider = encounter.getProvider(Injector.class); encounter.register(new InjectionListener<Object>() { @Override public void afterInjection(Object injectee) { WebApplication app = (WebApplication)injectee; app.getComponentInstantiationListeners().add(new GuiceComponentInjector(app, injectorProvider.get())); } }); } }); bind(OrienteerTester.class).asEagerSingleton(); Provider<OrienteerTester> provider = binder().getProvider(OrienteerTester.class); bind(WicketTester.class).toProvider(provider); bind(WicketOrientDbTester.class).toProvider(provider); Multibinder<String> binder = Multibinder.newSetBinder(binder(), String.class, Names.named("orient.model.packages")); binder.addBinding().toInstance("org.orienteer.core.persist"); }

Target:
protected void configure() { bind(Boolean.class).annotatedWith(Names.named("testing")).toInstance(true); bindListener(InstanceOfMatcher.createFor(WebApplication.class), new TypeListener() { @Override public <I> void hear(TypeLiteral<I> type, final TypeEncounter<I> encounter) { final Provider<Injector> injectorProvider = encounter.getProvider(Injector.class); encounter.register((InjectionListener<Object>) injected -> { WebApplication app = (WebApplication) injected; app.getComponentInstantiationListeners().add(new GuiceComponentInjector(app, injectorProvider.get())); }); } }); bind(OrienteerTester.class).asEagerSingleton(); Provider<OrienteerTester> provider = binder().getProvider(OrienteerTester.class); bind(WicketTester.class).toProvider(provider); bind(WicketOrientDbTester.class).toProvider(provider); }
Source:
public void testAnEnabledRoomIsAvailableInTheTablet() { HomeTabletPage homeTabletPage = new HomeTabletPage(); SettingsPage settingsPage = homeTabletPage.clickSettingsBtn(); homeTabletPage = settingsPage.selectRoom(roomName); SearchPage searchPage = homeTabletPage.clickSearchBtn() .clickCollapseAdvancedBtn() .setName(roomName); Assert.assertTrue(searchPage.roomIsDiplayed(roomName)); }

Target:
public void testAnEnabledRoomIsAvailableInTheTablet() { HomeAdminPage homeAdminPage = new HomeAdminPage(); homeAdminPage.clickConferenceRoomsLink(); HomeTabletPage homeTabletPage = new HomeTabletPage(); SettingsPage settingsPage = homeTabletPage.clickSettingsBtn(); homeTabletPage = settingsPage.selectRoom(roomName); SearchPage searchPage = homeTabletPage.clickSearchBtn() .clickCollapseAdvancedBtn() .setName(roomName); Assert.assertTrue(searchPage.roomIsDiplayed(roomName)); }
Source:
public void removeAll(Guid vmId) { List<VmNetworkInterface> interfaces = getVmNetworkInterfaceDao().getAllForVm(vmId); if (interfaces != null) { for (VmNetworkInterface iface : interfaces) { getMacPoolManager().freeMac(iface); getVmNetworkInterfaceDao().remove(iface.getId()); getVmNetworkStatisticsDao().remove(iface.getId()); } } }

Target:
public void removeAll(Guid vmId) { List<VmNetworkInterface> interfaces = getVmNetworkInterfaceDao().getAllForVm(vmId); if (interfaces != null) { for (VmNetworkInterface iface : interfaces) { getMacPoolManager().freeMac(iface.getMacAddress()); getVmNetworkInterfaceDao().remove(iface.getId()); getVmNetworkStatisticsDao().remove(iface.getId()); } } }
Source:
private void initNativeCore() { if (!"qnx".equals(System.getProperty("os.name"))) { OsmandSettings osmandSettings = app.getSettings(); if (osmandSettings.NATIVE_RENDERING_FAILED.get()) { osmandSettings.SAFE_MODE.set(true); osmandSettings.PT_SAFE_MODE.set(true); osmandSettings.NATIVE_RENDERING_FAILED.set(false); warnings.add(app.getString(R.string.native_library_not_supported)); } else { osmandSettings.SAFE_MODE.set(false); osmandSettings.PT_SAFE_MODE.set(false); osmandSettings.NATIVE_RENDERING_FAILED.set(true); startTask(app.getString(R.string.init_native_library), -1); RenderingRulesStorage storage = app.getRendererRegistry().getCurrentSelectedRenderer(); NativeOsmandLibrary lib = NativeOsmandLibrary.getLibrary(storage, app); boolean initialized = lib != null; osmandSettings.NATIVE_RENDERING_FAILED.set(false); if (!initialized) { LOG.info("Native library could not be loaded!"); } else { File ls = app.getAppPath("fonts"); lib.loadFontData(ls); } } app.getResourceManager().initMapBoundariesCacheNative(); } }

Target:
private void initNativeCore() { if (!"qnx".equals(System.getProperty("os.name"))) { OsmandSettings osmandSettings = app.getSettings(); if (osmandSettings.NATIVE_RENDERING_FAILED.get()) { osmandSettings.SAFE_MODE.set(true); osmandSettings.NATIVE_RENDERING_FAILED.set(false); warnings.add(app.getString(R.string.native_library_not_supported)); } else { osmandSettings.SAFE_MODE.set(false); osmandSettings.NATIVE_RENDERING_FAILED.set(true); startTask(app.getString(R.string.init_native_library), -1); RenderingRulesStorage storage = app.getRendererRegistry().getCurrentSelectedRenderer(); NativeOsmandLibrary lib = NativeOsmandLibrary.getLibrary(storage, app); boolean initialized = lib != null; osmandSettings.NATIVE_RENDERING_FAILED.set(false); if (!initialized) { LOG.info("Native library could not be loaded!"); } else { File ls = app.getAppPath("fonts"); lib.loadFontData(ls); } } app.getResourceManager().initMapBoundariesCacheNative(); } }
Source:
public List<MetricFamilySamples> collect() { GaugeMetricFamily stateFamily = new GaugeMetricFamily( names.getStateMetricName(), "The state of the circuit breaker: 0 - CLOSED, 1 - OPEN, 2 - HALF_OPEN", LabelNames.NAME ); GaugeMetricFamily callsFamily = new GaugeMetricFamily( names.getCallsMetricName(), "The number of circuit breaker calls for corresponding kind", LabelNames.NAME_AND_KIND ); GaugeMetricFamily bufferedCallsFamily = new GaugeMetricFamily( names.getBufferedCallsMetricName(), "The number of circuit breaker buffered calls", LabelNames.NAME ); GaugeMetricFamily maxBufferedCallsFamily = new GaugeMetricFamily( names.getMaxBufferedCallsMetricName(), "The number of circuit breaker max buffered calls", LabelNames.NAME ); for (CircuitBreaker circuitBreaker : supplier.get()) { List<String> nameLabel = singletonList(circuitBreaker.getName()); stateFamily.addMetric(nameLabel, circuitBreaker.getState().getOrder()); Metrics metrics = circuitBreaker.getMetrics(); callsFamily.addMetric(asList(circuitBreaker.getName(), "successful"), metrics.getNumberOfSuccessfulCalls()); callsFamily.addMetric(asList(circuitBreaker.getName(), "failed"), metrics.getNumberOfFailedCalls()); callsFamily.addMetric(asList(circuitBreaker.getName(), "not_permitted"), metrics.getNumberOfNotPermittedCalls()); bufferedCallsFamily.addMetric(nameLabel, metrics.getNumberOfBufferedCalls()); maxBufferedCallsFamily.addMetric(nameLabel, metrics.getMaxNumberOfBufferedCalls()); } return asList(stateFamily, callsFamily, bufferedCallsFamily, maxBufferedCallsFamily); }

Target:
public List<MetricFamilySamples> collect() { GaugeMetricFamily stateFamily = new GaugeMetricFamily( names.getStateMetricName(), "The state of the circuit breaker: 0 - CLOSED, 1 - OPEN, 2 - HALF_OPEN", LabelNames.NAME ); GaugeMetricFamily callsFamily = new GaugeMetricFamily( names.getCallsMetricName(), "The number of calls for a corresponding kind", LabelNames.NAME_AND_KIND ); GaugeMetricFamily bufferedCallsFamily = new GaugeMetricFamily( names.getBufferedCallsMetricName(), "The number of buffered calls", LabelNames.NAME ); GaugeMetricFamily maxBufferedCallsFamily = new GaugeMetricFamily( names.getMaxBufferedCallsMetricName(), "The maximum number of buffered calls", LabelNames.NAME ); for (CircuitBreaker circuitBreaker : supplier.get()) { List<String> nameLabel = singletonList(circuitBreaker.getName()); stateFamily.addMetric(nameLabel, circuitBreaker.getState().getOrder()); Metrics metrics = circuitBreaker.getMetrics(); callsFamily.addMetric(asList(circuitBreaker.getName(), "successful"), metrics.getNumberOfSuccessfulCalls()); callsFamily.addMetric(asList(circuitBreaker.getName(), "failed"), metrics.getNumberOfFailedCalls()); callsFamily.addMetric(asList(circuitBreaker.getName(), "not_permitted"), metrics.getNumberOfNotPermittedCalls()); bufferedCallsFamily.addMetric(nameLabel, metrics.getNumberOfBufferedCalls()); maxBufferedCallsFamily.addMetric(nameLabel, metrics.getMaxNumberOfBufferedCalls()); } return asList(stateFamily, callsFamily, bufferedCallsFamily, maxBufferedCallsFamily); }