auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testProcessWhenSharedConfigThenAddVolumeConfig() { List<SharedComponent> sharedComponents = List.of(new SharedComponent("HDFS", "JOURNALNODE")); ReflectionTestUtils.setField(underTest, "sharedComponents", sharedComponents); HostgroupView master1 = new HostgroupView("master1", 1, InstanceGroupType.GATEWAY, 1); HostgroupView master2 = new HostgroupView("master2", 1, InstanceGroupType.GATEWAY, 1); HostgroupView worker = new HostgroupView("worker", 2, InstanceGroupType.CORE, 2); HostgroupView compute = new HostgroupView("compute", 3, InstanceGroupType.CORE, 2); HostgroupView quorum = new HostgroupView("quorum", 3, InstanceGroupType.CORE, 2); setup("input/cb5660.bp", Builder.builder().withHostgroupViews(Set.of(master1, master2, worker, compute, quorum))); underTest.process(templateProcessor, templatePreparator); Map<String, List<ApiClusterTemplateConfig>> roleConfigs = mapRoleConfigs(); List<ApiClusterTemplateConfig> journalNodeBase = roleConfigs.get("hdfs-JOURNALNODE-BASE"); assertEquals(1, journalNodeBase.size()); assertEquals("dfs_journalnode_edits_dir", journalNodeBase.get(0).getName()); assertEquals("/hadoopfs/fs1/journalnode", journalNodeBase.get(0).getValue()); }

Target:
public void testProcessWhenSharedConfigThenAddVolumeConfig() { List<SharedComponent> sharedComponents = List.of(new SharedComponent("ZOOKEEPER", "SERVER"), new SharedComponent("HDFS", "JOURNALNODE")); ReflectionTestUtils.setField(underTest, "sharedComponents", sharedComponents); HostgroupView master1 = new HostgroupView("master1", 1, InstanceGroupType.GATEWAY, 1); HostgroupView master2 = new HostgroupView("master2", 1, InstanceGroupType.GATEWAY, 1); HostgroupView worker = new HostgroupView("worker", 2, InstanceGroupType.CORE, 2); HostgroupView compute = new HostgroupView("compute", 3, InstanceGroupType.CORE, 2); HostgroupView quorum = new HostgroupView("quorum", 3, InstanceGroupType.CORE, 2); setup("input/cb5660.bp", Builder.builder().withHostgroupViews(Set.of(master1, master2, worker, compute, quorum))); underTest.process(templateProcessor, templatePreparator); Map<String, List<ApiClusterTemplateConfig>> roleConfigs = mapRoleConfigs(); List<ApiClusterTemplateConfig> journalNodeBase = roleConfigs.get("hdfs-JOURNALNODE-BASE"); assertEquals(1, journalNodeBase.size()); assertEquals("dfs_journalnode_edits_dir", journalNodeBase.get(0).getName()); assertEquals("/hadoopfs/fs1/journalnode", journalNodeBase.get(0).getValue()); List<ApiClusterTemplateConfig> zkServerBase = roleConfigs.get("zookeeper-SERVER-BASE"); assertEquals("dataDir", zkServerBase.get(0).getName()); assertEquals("/hadoopfs/fs1/zookeeper", zkServerBase.get(0).getValue()); assertEquals("dataLogDir", zkServerBase.get(1).getName()); assertEquals("/hadoopfs/fs1/zookeeper", zkServerBase.get(1).getValue()); }
Source:
public boolean match(ChangeData object) throws OrmException { final PatchSet patchSet = object.currentPatchSet(db); if (patchSet == null) { return false; } final RevId revision = patchSet.getRevision(); if (revision == null) { return false; } final AnyObjectId objectId = ObjectId.fromString(revision.get()); if (objectId == null) { return false; } Change change = object.change(db); if (change == null) { return false; } final Project.NameKey projectName = change.getProject(); if (projectName == null) { return false; } Arguments args = new Arguments(patchSet, revision, objectId, change, projectName); try { RepoWalk repoWalk = repoWalksByProject.get(projectName); return match(repoWalk.repository, repoWalk.revWalk, args); } catch (RepositoryNotFoundException e) { log.error("Repository \"" + projectName.get() + "\" unknown.", e); } catch (IOException e) { log.error(projectName.get() + " cannot be read as a repository", e); } return false; }

Target:
public boolean match(ChangeData object) throws OrmException { final PatchSet patchSet = object.currentPatchSet(db); if (patchSet == null) { return false; } final RevId revision = patchSet.getRevision(); if (revision == null) { return false; } final AnyObjectId objectId = ObjectId.fromString(revision.get()); if (objectId == null) { return false; } Change change = object.change(db); if (change == null) { return false; } final Project.NameKey projectName = change.getProject(); if (projectName == null) { return false; } Arguments args = new Arguments(patchSet, revision, objectId, change, projectName); RepoWalk repoWalk = repoWalksCache.repoWalksByProject.get(projectName); return match(repoWalk.repository, repoWalk.revWalk, args); }
Source:
public PersistentModel loadModel(IProject project) { PersistentModel model = this.cache.get(project); if (model == null) { model = readModel(project); if (model != null) { this.cache.put(project, model); } } return model; }

Target:
public PersistentModel loadModel(IProject project) { return this.modelCache.getUnchecked(project); }
Source:
public void testCreatePayload() { Injector injector = Guice.createInjector(new GsonModule(), new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Supplier<URI>>() { }).annotatedWith(Provider.class).toInstance( Suppliers.ofInstance(URI.create(new ProfitBricksProviderMetadata().getEndpoint()))); } }); CreateSnapshotRequestBinder binder = injector.getInstance(CreateSnapshotRequestBinder.class); Volume.Request.CreateSnapshotPayload payload = Volume.Request.createSnapshotBuilder() .dataCenterId("datacenter-id") .volumeId("volume-id") .name("test-snapshot") .description("snapshot desc...") .build(); HttpRequest request = binder.createRequest( HttpRequest.builder().method("POST").endpoint("<LINK_0>").build(), binder.createPayload(payload) ); Multimap<String, String> expectedPayload = HashMultimap.create(); expectedPayload.put("name", "test-snapshot"); expectedPayload.put("description", "snapshot desc..."); assertEquals(request.getEndpoint().getPath(), "/rest/v2/datacenters/datacenter-id/volumes/volume-id/create-snapshot"); assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_FORM_URLENCODED); assertEquals(request.getPayload().getRawContent(), "&" + (new UrlEncodedFormPayload(expectedPayload)).getRawContent()); }

Target:
public void testCreatePayload() { CreateSnapshotRequestBinder binder = injector.getInstance(CreateSnapshotRequestBinder.class); Volume.Request.CreateSnapshotPayload payload = Volume.Request.createSnapshotBuilder() .dataCenterId("datacenter-id") .volumeId("volume-id") .name("test-snapshot") .description("snapshot desc...") .build(); HttpRequest request = binder.createRequest( HttpRequest.builder().method("POST").endpoint("<LINK_0>").build(), binder.createPayload(payload) ); Multimap<String, String> expectedPayload = HashMultimap.create(); expectedPayload.put("name", "test-snapshot"); expectedPayload.put("description", "snapshot desc..."); assertEquals(request.getEndpoint().getPath(), "/rest/v2/datacenters/datacenter-id/volumes/volume-id/create-snapshot"); assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_FORM_URLENCODED); assertEquals(request.getPayload().getRawContent(), "&" + (new UrlEncodedFormPayload(expectedPayload)).getRawContent()); }
Source:
public String getContactName() { if (this.contact == null) return null; StringBuilder sb = new StringBuilder(32); if (this.contact.getFirstName() != null) { sb.append(this.contact.getFirstName()); } if (this.contact.getLastName() != null) { sb.append(" "); sb.append(this.contact.getLastName()); } if (this.contact.getOrganization() != null) { if (sb.length() > 0) sb.append(","); sb.append(" "); sb.append(this.contact.getOrganization()); } return sb.toString().trim(); }

Target:
public String getContactName() { if (this.contact == null) return null; StringBuilder sb = new StringBuilder(32); if (this.contact.getFirstName() != null) { sb.append(this.contact.getFirstName()); } if (this.contact.getLastName() != null) { sb.append(" "); sb.append(this.contact.getLastName()); } if (this.contact.getOrganization() != null) { if (sb.length() > 0) sb.append(", "); sb.append(this.contact.getOrganization()); } return sb.toString().trim(); }
Source:
private void initializeLocationProviders() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mockLocationProviders.addAll(createMockProviders(locationManager)); if (PlayServicesHelpers.isAvailable(this)) { Log.d(TAG, "Adding FusedLocationProvider"); mockLocationProviders.add(createFusedLocationProvider()); } Log.d(TAG, String.format("Created mock providers: %s", mockLocationProviders.toString())); }

Target:
private void initializeLocationProviders() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mockLocationProviders.clear(); mockLocationProviders.addAll(createMockProviders(locationManager)); if (PlayServicesHelpers.isAvailable(this)) { Log.d(TAG, "Adding FusedLocationProvider"); mockLocationProviders.add(createFusedLocationProvider()); } Log.d(TAG, String.format("Created mock providers: %s", mockLocationProviders.toString())); }
Source:
private List<ICommitMessageProvider> getCommitMessageProviders() throws CoreException { List<ICommitMessageProvider> providers = new ArrayList<>(); IExtensionRegistry registry = Platform.getExtensionRegistry(); IConfigurationElement[] configs = registry .getConfigurationElementsFor(COMMIT_MESSAGE_PROVIDER_ID); for (IConfigurationElement config : configs) { Object provider; try { provider = config.createExecutableExtension("class"); if (provider instanceof ICommitMessageProvider) { providers.add((ICommitMessageProvider) provider); } else { Activator.logError( UIText.CommitDialog_WrongTypeOfCommitMessageProvider, null); } } catch (CoreException | InvalidRegistryObjectException e) { String contributorName; try { contributorName = config.getDeclaringExtension() .getContributor().getName(); } catch (InvalidRegistryObjectException e1) { contributorName = ""; } Activator.logError( NLS.bind( UIText.CommitDialog_ErrorCreatingCommitMessageProvider, contributorName), e); } } return providers; }

Target:
private List<ICommitMessageProvider> getCommitMessageProviders() throws CoreException { List<ICommitMessageProvider> providers = new ArrayList<>(); IExtensionRegistry registry = Platform.getExtensionRegistry(); IConfigurationElement[] configs = registry .getConfigurationElementsFor(COMMIT_MESSAGE_PROVIDER_ID); for (IConfigurationElement config : configs) { Object provider; String contributorName = "<unknown"; try { contributorName = config.getDeclaringExtension() .getContributor().getName(); provider = config.createExecutableExtension("class"); if (provider instanceof ICommitMessageProvider) { providers.add((ICommitMessageProvider) provider); } else { Activator.logError( UIText.CommitDialog_WrongTypeOfCommitMessageProvider, null); } } catch (CoreException | InvalidRegistryObjectException e) { Activator.logError( MessageFormat.format( UIText.CommitDialog_ErrorCreatingCommitMessageProvider, contributorName), e); } } return providers; }
Source:
public void removeFieldFile (String fieldInode, String contentInode, PageMode mode) { String velocityRootPath = VelocityUtil.getVelocityRootPath(); velocityRootPath += java.io.File.separator; String folderPath = mode.name() + java.io.File.separator; String filePath=folderPath + contentInode + "_" + fieldInode + "." + VelocityType.FIELD.fileExtension; java.io.File f = new java.io.File(velocityRootPath + filePath); f.delete(); DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); vc.remove(ResourceManager.RESOURCE_TEMPLATE + filePath ); }

Target:
public void removeFieldFile (String fieldInode, String contentInode, PageMode mode) { }
Source:
public void touch() throws Exception { final String foo1 = "foo1"; long reply = jedis.touch(foo1, "foo2", "foo3"); assertEquals(0, reply); jedis.set(foo1, "bar1"); await().atMost(2, TimeUnit.SECONDS).until(jedisTargetIsIdle(foo1)); assertTrue(jedis.objectIdletime("foo1") > 0); reply = jedis.touch("foo1"); assertEquals(1, reply); assertTrue(jedis.objectIdletime("foo1") == 0); reply = jedis.touch("foo1", "foo2", "foo3"); assertEquals(1, reply); jedis.set("foo2", "bar2"); jedis.set("foo3", "bar3"); reply = jedis.touch("foo1", "foo2", "foo3"); assertEquals(3, reply); reply = jedis.touch(bfoo1, bfoo2, bfoo3); assertEquals(0, reply); jedis.set(bfoo1, bbar1); await().atMost(2, TimeUnit.SECONDS).until(jedisTargetIsIdle(bfoo1)); assertTrue(jedis.objectIdletime(bfoo1) > 0); reply = jedis.touch(bfoo1); assertEquals(1, reply); assertTrue(jedis.objectIdletime(bfoo1) == 0); reply = jedis.touch(bfoo1, bfoo2, bfoo3); assertEquals(1, reply); jedis.set(bfoo2, bbar2); jedis.set(bfoo3, bbar3); reply = jedis.touch(bfoo1, bfoo2, bfoo3); assertEquals(3, reply); }

Target:
public void touch() throws Exception { final String foo1 = "foo1"; long reply = jedis.touch(foo1, "foo2", "foo3"); assertEquals(0, reply); jedis.set(foo1, "bar1"); AwaitilityUtils.waitFor(2000); assertTrue(jedis.objectIdletime("foo1") > 0); reply = jedis.touch("foo1"); assertEquals(1, reply); assertTrue(jedis.objectIdletime("foo1") == 0); reply = jedis.touch("foo1", "foo2", "foo3"); assertEquals(1, reply); jedis.set("foo2", "bar2"); jedis.set("foo3", "bar3"); reply = jedis.touch("foo1", "foo2", "foo3"); assertEquals(3, reply); reply = jedis.touch(bfoo1, bfoo2, bfoo3); assertEquals(0, reply); jedis.set(bfoo1, bbar1); AwaitilityUtils.waitFor(2000); assertTrue(jedis.objectIdletime(bfoo1) > 0); reply = jedis.touch(bfoo1); assertEquals(1, reply); assertTrue(jedis.objectIdletime(bfoo1) == 0); reply = jedis.touch(bfoo1, bfoo2, bfoo3); assertEquals(1, reply); jedis.set(bfoo2, bbar2); jedis.set(bfoo3, bbar3); reply = jedis.touch(bfoo1, bfoo2, bfoo3); assertEquals(3, reply); }
Source:
protected void buildVmDrives() { Map<String, String>[] drives = new Map[vm.getDiskMap().size()]; int ideCount = 0, pciCount = 0; int i = 0; List<DiskImage> diskImages = getSortedDiskImages(); for (DiskImage disk : diskImages) { VmDevice vmDevice = DbFacade.getInstance().getVmDeviceDAO().get(new VmDeviceId(disk.getId(), vm.getId())); Map<String, String> drive = new HashMap<String, String>(); drive.put("domainID", disk.getstorage_ids().get(0).toString()); drive.put("poolID", disk.getstorage_pool_id().toString()); drive.put("volumeID", disk.getId().toString()); drive.put("imageID", disk.getimage_group_id().toString()); drive.put("format", disk.getvolume_format().toString() .toLowerCase()); drive.put("propagateErrors", disk.getpropagate_errors().toString() .toLowerCase()); switch (disk.getdisk_interface()) { case IDE: try { drive.put("if", "ide"); drive.put("index", String.valueOf(ideIndexSlots[ideCount])); ideCount++; } catch (IndexOutOfBoundsException e) { log.errorFormat("buildVmDrives throws IndexOutOfBoundsException for index {0}, IDE slots are limited to 4.", ideCount); throw e; } break; case VirtIO: drive.put("if", "virtio"); drive.put("index", String.valueOf(pciCount)); drive.put("boot", String.valueOf(disk.getboot()).toLowerCase()); pciCount++; break; default: logUnsupportedInterfaceType(); break; } drives[i] = drive; i++; } createInfo.add("drives", drives); }

Target:
protected void buildVmDrives() { Map<String, String>[] drives = new Map[vm.getDiskMap().size()]; int ideCount = 0, pciCount = 0; int i = 0; List<DiskImage> diskImages = getSortedDiskImages(); for (DiskImage disk : diskImages) { Map<String, String> drive = new HashMap<String, String>(); drive.put("domainID", disk.getstorage_ids().get(0).toString()); drive.put("poolID", disk.getstorage_pool_id().toString()); drive.put("volumeID", disk.getId().toString()); drive.put("imageID", disk.getimage_group_id().toString()); drive.put("format", disk.getvolume_format().toString() .toLowerCase()); drive.put("propagateErrors", disk.getpropagate_errors().toString() .toLowerCase()); switch (disk.getdisk_interface()) { case IDE: try { drive.put("if", "ide"); drive.put("index", String.valueOf(ideIndexSlots[ideCount])); ideCount++; } catch (IndexOutOfBoundsException e) { log.errorFormat("buildVmDrives throws IndexOutOfBoundsException for index {0}, IDE slots are limited to 4.", ideCount); throw e; } break; case VirtIO: drive.put("if", "virtio"); drive.put("index", String.valueOf(pciCount)); drive.put("boot", String.valueOf(disk.getboot()).toLowerCase()); pciCount++; break; default: logUnsupportedInterfaceType(); break; } drives[i] = drive; i++; } createInfo.add("drives", drives); }
Source:
public Scene getCurrentScene() { if (currentScene == null && project != null) { currentScene = project.getDefaultScene(); } return currentScene; }

Target:
public Scene getCurrentScene() { if (currentScene == null) { currentScene = project.getDefaultScene(); } return currentScene; }
Source:
public static int getItemIcon(Context appContext, String itemName) { itemName = itemName.replaceFirst("itemdex_", ""); return appContext.getResources() .getIdentifier("item_" + MyApplication.toId(itemName), "drawable", appContext.getPackageName()); }

Target:
public static int getItemIcon(Context appContext, String itemName) { if (appContext != null && itemName != null) { return appContext.getResources() .getIdentifier("item_" + MyApplication.toId(itemName), "drawable", appContext.getPackageName()); } else { return R.drawable.sprites_0; } }
Source:
protected void markImagesIllegalIfNotInDb(VM vm) { List<DiskImage> imagesInDb = getDiskImageDao().getAllSnapshotsForVmSnapshot(getParameters().getSnapshotSourceId()); for (DiskImage fromConfigImg : vm.getImages()) { if (!imagesInDb.contains(fromConfigImg)) { fromConfigImg.setimageStatus(ImageStatus.ILLEGAL); } } }

Target:
protected void markImagesIllegalIfNotInDb(VM vm) { List<DiskImage> imagesInDb = getDiskImageDao().getAllSnapshotsForVmSnapshot(getParameters().getSnapshotSourceId()); Map<Guid, DiskImage> imagesInDbMap = ImagesHandler.getDiskImagesByIdMap(imagesInDb); for (DiskImage fromConfigImg : vm.getImages()) { if (!imagesInDbMap.containsKey(fromConfigImg.getId())) { fromConfigImg.setimageStatus(ImageStatus.ILLEGAL); } } }
Source:
public <T> List<T> queryList(String sql) throws Exception { List<T> resultList = Lists.newArrayList(); ResultSet rs = executeQuery(sql); while (rs.next()) { resultList.add((T) rs.getObject(1)); } rs.close(); return resultList; }

Target:
public <T> List<T> queryList(String sql) throws Exception { List<T> resultList = Lists.newArrayList(); try (ResultSet rs = executeQuery(sql)) { while (rs.next()) { resultList.add((T) rs.getObject(1)); } } return resultList; }
Source:
public static void main(String... args) throws InterruptedException { System.out.println(">>> Decision tree classification trainer example started."); try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { System.out.println(">>> Ignite grid started."); IgniteThread igniteThread = new IgniteThread(ignite.configuration().getIgniteInstanceName(), DecisionTreeClassificationTrainerExample.class.getSimpleName(), () -> { CacheConfiguration<Integer, LabeledPoint> trainingSetCfg = new CacheConfiguration<>(); trainingSetCfg.setName("TRAINING_SET"); trainingSetCfg.setAffinity(new RendezvousAffinityFunction(false, 1)); IgniteCache<Integer, LabeledPoint> trainingSet = ignite.createCache(trainingSetCfg); Random rnd = new Random(0); for (int i = 0; i < 1000; i++) trainingSet.put(i, generatePoint(rnd)); DecisionTreeClassificationTrainer trainer = new DecisionTreeClassificationTrainer(4, 0, false); DecisionTreeNode mdl = trainer.fit( ignite, trainingSet, (k, v) -> VectorUtils.of(v.x, v.y), (k, v) -> v.lb ); int correctPredictions = 0; for (int i = 0; i < 1000; i++) { LabeledPoint pnt = generatePoint(rnd); double prediction = mdl.apply(VectorUtils.of(pnt.x, pnt.y)); if (prediction == pnt.lb) correctPredictions++; } System.out.println(">>> Accuracy: " + correctPredictions / 10.0 + "%"); System.out.println(">>> Decision tree classification trainer example completed."); }); igniteThread.start(); igniteThread.join(); } }

Target:
public static void main(String... args) throws InterruptedException { System.out.println(">>> Decision tree classification trainer example started."); try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { System.out.println(">>> Ignite grid started."); IgniteThread igniteThread = new IgniteThread(ignite.configuration().getIgniteInstanceName(), DecisionTreeClassificationTrainerExample.class.getSimpleName(), () -> { CacheConfiguration<Integer, LabeledPoint> trainingSetCfg = new CacheConfiguration<>(); trainingSetCfg.setName("TRAINING_SET"); trainingSetCfg.setAffinity(new RendezvousAffinityFunction(false, 10)); IgniteCache<Integer, LabeledPoint> trainingSet = ignite.createCache(trainingSetCfg); Random rnd = new Random(0); for (int i = 0; i < 1000; i++) trainingSet.put(i, generatePoint(rnd)); DecisionTreeClassificationTrainer trainer = new DecisionTreeClassificationTrainer(4, 0); DecisionTreeNode mdl = trainer.fit( ignite, trainingSet, (k, v) -> VectorUtils.of(v.x, v.y), (k, v) -> v.lb ); int correctPredictions = 0; for (int i = 0; i < 1000; i++) { LabeledPoint pnt = generatePoint(rnd); double prediction = mdl.apply(VectorUtils.of(pnt.x, pnt.y)); if (prediction == pnt.lb) correctPredictions++; } System.out.println(">>> Accuracy: " + correctPredictions / 10.0 + "%"); System.out.println(">>> Decision tree classification trainer example completed."); }); igniteThread.start(); igniteThread.join(); } }
Source:
public JSONPointer(List<String> refTokens) { this.refTokens = refTokens; }

Target:
public JSONPointer(List<String> refTokens) { this.refTokens = new ArrayList<String>(refTokens); }
Source:
public int getAggressiveHandover() { enforceAccessPermission(); return mWifiStateMachine.getAggressiveHandover(); }

Target:
public int getAggressiveHandover() { enforceAccessPermission(); mLog.trace("getAggressiveHandover uid=%").c(Binder.getCallingUid()).flush(); return mWifiStateMachine.getAggressiveHandover(); }
Source:
public void onViewCreated(View view, Bundle savedInstanceState) { GoogleMap map = mapView.getMap(); map.setMyLocationEnabled(true); map.setOnMarkerClickListener(this); setUpClusterer(); Location myLocation = map.getMyLocation(); if (myLocation != null) { currentLocation = new LatLng(myLocation.getLatitude(), myLocation.getLongitude()); map.animateCamera(CameraUpdateFactory.newLatLng(currentLocation)); loadActiveTrucks(); } }

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { GoogleMap map = mapView.getMap(); if (map != null) { map.setMyLocationEnabled(true); setUpClusterer(); } }
Source:
public GenericRecord transform(StructuredRecord structuredRecord, co.cask.cdap.api.data.schema.Schema schema) throws IOException { co.cask.cdap.api.data.schema.Schema structuredRecordSchema = structuredRecord.getSchema(); Schema avroSchema = getAvroSchema(schema); GenericRecordBuilder recordBuilder = new GenericRecordBuilder(avroSchema); for (Schema.Field field : avroSchema.getFields()) { String fieldName = field.name(); co.cask.cdap.api.data.schema.Schema.Field schemaField = structuredRecordSchema.getField(fieldName); if (schemaField == null) { throw new IllegalArgumentException("Input record does not contain the " + fieldName + " field."); } if (schemaField.getSchema().getType().equals(co.cask.cdap.api.data.schema.Schema.Type.BYTES)) { recordBuilder.set(fieldName, ByteBuffer.wrap((byte[]) structuredRecord.get(fieldName))); } else { recordBuilder.set(fieldName, convertField(structuredRecord.get(fieldName), schemaField.getSchema())); } } return recordBuilder.build(); }

Target:
public GenericRecord transform(StructuredRecord structuredRecord, co.cask.cdap.api.data.schema.Schema schema) throws IOException { co.cask.cdap.api.data.schema.Schema structuredRecordSchema = structuredRecord.getSchema(); Schema avroSchema = getAvroSchema(schema); GenericRecordBuilder recordBuilder = new GenericRecordBuilder(avroSchema); for (Schema.Field field : avroSchema.getFields()) { String fieldName = field.name(); co.cask.cdap.api.data.schema.Schema.Field schemaField = structuredRecordSchema.getField(fieldName); if (schemaField == null) { throw new IllegalArgumentException("Input record does not contain the " + fieldName + " field."); } co.cask.cdap.api.data.schema.Schema schemaFieldSchema = schemaField.getSchema(); co.cask.cdap.api.data.schema.Schema.Type inputFieldType = (schemaFieldSchema.isNullableSimple()) ? schemaFieldSchema.getNonNullable().getType() : schemaFieldSchema.getType(); if (inputFieldType.equals(co.cask.cdap.api.data.schema.Schema.Type.BYTES)) { recordBuilder.set(fieldName, ByteBuffer.wrap((byte[]) structuredRecord.get(fieldName))); } else { recordBuilder.set(fieldName, convertField(structuredRecord.get(fieldName), schemaField.getSchema())); } } return recordBuilder.build(); }
Source:
protected void obtainResource() throws Exception { if (embedded) { try { log.debug("Starting Zookeeper"); zookeeper = new EmbeddedZookeeper(TestZKUtils.zookeeperConnect()); log.debug("Started Zookeeper at " + zookeeper.getConnectString()); } catch (Exception e) { throw new RuntimeException("Issues creating the ZK server", e); } try { int zkConnectionTimeout = 6000; int zkSessionTimeout = 6000; zkClient = new ZkClient(getZkConnectString(), zkSessionTimeout, zkConnectionTimeout, ZKStringSerializer$.MODULE$); } catch (Exception e) { zookeeper.shutdown(); throw new RuntimeException("Issues creating the ZK client", e); } try { log.debug("Creating Kafka server"); Properties brokerConfigProperties = brokerConfig; kafkaServer = TestUtils.createServer(new KafkaConfig(brokerConfigProperties), SystemTime$.MODULE$); log.debug("Created Kafka server at " + kafkaServer.config().hostName() + ":" + kafkaServer.config().port()); } catch (Exception e) { zookeeper.shutdown(); zkClient.close(); throw new RuntimeException("Issues creating the Kafka server", e); } } else { try { this.zkClient = new ZkClient(DEFAULT_ZOOKEEPER_CONNECT, 5000, 5000, ZKStringSerializer$.MODULE$); if (ZkUtils.getAllBrokersInCluster(zkClient).size() == 0) { throw new RuntimeException("Kafka server not available on localhost"); } } catch (Exception e) { throw new RuntimeException("Issues connecting to ZK server"); } } }

Target:
protected void obtainResource() throws Exception { if (embedded) { log.debug("Starting Zookeeper"); zookeeper = new EmbeddedZookeeper(TestZKUtils.zookeeperConnect()); log.debug("Started Zookeeper at " + zookeeper.getConnectString()); try { int zkConnectionTimeout = 6000; int zkSessionTimeout = 6000; zkClient = new ZkClient(getZkConnectString(), zkSessionTimeout, zkConnectionTimeout, ZKStringSerializer$.MODULE$); } catch (Exception e) { zookeeper.shutdown(); throw e; } try { log.debug("Creating Kafka server"); Properties brokerConfigProperties = brokerConfig; kafkaServer = TestUtils.createServer(new KafkaConfig(brokerConfigProperties), SystemTime$.MODULE$); log.debug("Created Kafka server at " + kafkaServer.config().hostName() + ":" + kafkaServer.config().port()); } catch (Exception e) { zookeeper.shutdown(); zkClient.close(); throw e; } } else { this.zkClient = new ZkClient(DEFAULT_ZOOKEEPER_CONNECT, 5000, 5000, ZKStringSerializer$.MODULE$); if (ZkUtils.getAllBrokersInCluster(zkClient).size() == 0) { throw new RuntimeException("Kafka server not available"); } } }
Source:
protected void startBackgroundDiscovery() { if (usbSerialDiscovery != null) { usbSerialDiscovery.startBackgroundScanning(); } else { logger.info( "Could not start background discovery, as there is no usb serial discovery service configured."); } }

Target:
protected void startBackgroundDiscovery() { if (usbSerialDiscovery != null) { usbSerialDiscovery.startBackgroundScanning(); } else { logger.info( "Could not start background discovery, as there is no USB-Serial discovery service configured."); } }
Source:
public void shouldIgnoreBase() { WorkBenchDto workBenchDto = new WorkBenchDto(); workBenchDto.setArticleName( "MyBench" ); workBenchDto.setArticleDescription( "Beautiful" ); WorkBenchEntity benchTarget = ToolMapper.INSTANCE.mapBench( workBenchDto ); assertThat( benchTarget ).isNotNull(); assertThat( benchTarget.getArticleName() ).isEqualTo( "MyBench" ); assertThat( benchTarget.getDescription() ).isEqualTo( "Beautiful" ); assertThat( benchTarget.getKey() ).isNull(); assertThat( benchTarget.getModificationDate() ).isNull(); assertThat( benchTarget.getCreationDate() ).isNull(); }

Target:
public void shouldIgnoreBase() { WorkBenchDto workBenchDto = new WorkBenchDto(); workBenchDto.setArticleName( "MyBench" ); workBenchDto.setArticleDescription( "Beautiful" ); workBenchDto.setCreationDate( new Date() ); workBenchDto.setModificationDate( new Date() ); WorkBenchEntity benchTarget = ToolMapper.INSTANCE.mapBench( workBenchDto ); assertThat( benchTarget ).isNotNull(); assertThat( benchTarget.getArticleName() ).isEqualTo( "MyBench" ); assertThat( benchTarget.getDescription() ).isEqualTo( "Beautiful" ); assertThat( benchTarget.getKey() ).isNull(); assertThat( benchTarget.getModificationDate() ).isNull(); assertThat( benchTarget.getCreationDate() ).isNull(); }
Source:
@Override protected String run(Void arg) throws IgniteException { Set<Object> ids = ignite.context().cache().context().snapshotMgr().statusSnapshot().get().stream() .filter(Objects::nonNull) .collect(Collectors.toSet()); if (ids.isEmpty()) return "No snapshot operations."; StringBuilder sb = new StringBuilder("чSnapshot operation in progress on nodes with Consistent ID:"); ids.stream() .map(String::valueOf) .forEach(s -> sb.append(IgniteUtils.nl()).append(s)); return sb.toString(); }

Target:
@Override protected String run(Void arg) throws IgniteException { Set<Object> ids = new SnapshotMXBeanImpl(ignite.context()).statusSnapshot().entrySet() .stream() .filter(Map.Entry::getValue) .map(Map.Entry::getKey).collect(Collectors.toSet()); if (ids.isEmpty()) return "No snapshot operations."; StringBuilder sb = new StringBuilder("Snapshot operation in progress on nodes with Consistent ID:"); ids.stream() .map(String::valueOf) .forEach(s -> sb.append(IgniteUtils.nl()).append(s)); return sb.toString(); }
Source:
public List<Integer> parse() { final List<Integer> list = new LinkedList<>(); for (int i = 0; i < numTrainingDataInstance; i++) { list.add(RAND.nextInt()); } return list; }

Target:
public List<Integer> parse() { final List<Integer> list = new ArrayList<>(numTrainingDataInstance); for (int i = 0; i < numTrainingDataInstance; i++) { list.add(RAND.nextInt()); } return list; }
Source:
default DRepresentation copyRepresentation(DRepresentation representation, String name, Session session, IProgressMonitor monitor) { if (session instanceof DAnalysisSessionImpl) { DRepresentationQuery query = new DRepresentationQuery(representation); for (DAnalysis analysis: ((DAnalysisSessionImpl) session).allAnalyses()) { DRepresentationDescriptor descriptor = query.findDescriptorFromAnalysis(analysis); if (descriptor != null) { return this.copyRepresentation(descriptor, name, session, monitor); } } } return null; }

Target:
default DRepresentation copyRepresentation(DRepresentation representation, String name, Session session, IProgressMonitor monitor) { DRepresentationDescriptor descriptor = new DRepresentationQuery(representation, session).getRepresentationDescriptor(); if (descriptor != null) { return this.copyRepresentation(descriptor, name, session, monitor); } else { return null; } }
Source:
public void invokeBusinessLogic(MessageContext msgContext) throws AxisFault { try { if (log.isDebugEnabled()) { log.debug("Request received to DSS. Data Service :" + msgContext.getServiceContext().getName() + ", " + "Operation :" + msgContext.getSoapAction() + ", Request body: " + msgContext.getEnvelope().toString() + ", ThreadID:" + Thread.currentThread().getId()); } DataServiceProcessor.dispatch(msgContext); } catch(Exception e) { e.printStackTrace(); log.error("Error in in-only message receiver", e); msgContext.setProperty(Constants.FAULT_NAME, DBConstants.DS_FAULT_NAME); throw DBUtils.createAxisFault(e); } finally { if (log.isDebugEnabled()) { log.debug("Request processing completed from DSS. Data Service :" + msgContext.getServiceContext().getName() + ", Operation :" + msgContext.getSoapAction() + ", ThreadID :" + Thread.currentThread().getId()); } } }

Target:
public void invokeBusinessLogic(MessageContext msgContext) throws AxisFault { try { if (log.isDebugEnabled()) { log.debug("Request received to DSS: Data Service - " + msgContext.getServiceContext().getName() + ", Operation - " + msgContext.getSoapAction() + ", Request body - " + msgContext.getEnvelope().toString() + ", ThreadID - " + Thread.currentThread().getId()); } DataServiceProcessor.dispatch(msgContext); } catch (Exception e) { log.error("Error in in-only message receiver", e); msgContext.setProperty(Constants.FAULT_NAME, DBConstants.DS_FAULT_NAME); throw DBUtils.createAxisFault(e); } finally { if (log.isDebugEnabled()) { log.debug("Request processing completed from DSS: Data Service - " + msgContext.getServiceContext().getName() + ", Operation - " + msgContext.getSoapAction() + ", ThreadID - " + Thread.currentThread().getId()); } } }
Source:
public void partitionPage(Page page) { populatePositionsForEachPartition(page); int channelCount = page.getChannelCount(); for (int i = 0; i < channelCount; i++) { decodedBlocks[i] = decodeBlock(flattener, page.getBlock(i)); } for (int i = 0; i < partitionData.length; i++) { partitionData[i].appendRows(decodedBlocks, fixedWidthRowSize, variableWidthChannels, outputBuffer); } }

Target:
public void partitionPage(Page page) { populatePositionsForEachPartition(page); for (int i = 0; i < decodedBlocks.length; i++) { decodedBlocks[i] = decodeBlock(flattener, page.getBlock(i)); } for (int i = 0; i < partitionData.length; i++) { partitionData[i].appendRows(decodedBlocks, fixedWidthRowSize, variableWidthChannels, outputBuffer); } }
Source:
public Role populate(ModelTranslator modelTranslator, RoleDTO source, Role destination) { if (source == null) { throw new IllegalArgumentException("source is null"); } if (destination == null) { throw new IllegalArgumentException("destination is null"); } destination.setCreated(source.getCreated() != null ? new Date(source.getCreated().toInstant().toEpochMilli()) : null); destination.setUpdated(source.getUpdated() != null ? new Date(source.getUpdated().toInstant().toEpochMilli()) : null); destination.setId(source.getId()); destination.setName(source.getName()); if (modelTranslator != null) { List<UserDTO> users = source.getUsers(); if (users != null) { destination.setUsers(users.stream() .map(modelTranslator.getStreamMapper(UserDTO.class, User.class)) .collect(Collectors.toSet())); } else { destination.setUsers(Collections.<User>emptySet()); } List<PermissionBlueprintDTO> permissions = source.getPermissions(); if (permissions != null) { destination.setPermissions(permissions.stream() .map(modelTranslator.getStreamMapper(PermissionBlueprintDTO.class, PermissionBlueprint.class)) .collect(Collectors.toSet())); } else { destination.setPermissions(Collections.<PermissionBlueprint>emptySet()); } } else { destination.setUsers(Collections.<User>emptySet()); destination.setPermissions(Collections.<PermissionBlueprint>emptySet()); } return destination; }

Target:
public Role populate(ModelTranslator modelTranslator, RoleDTO source, Role destination) { if (source == null) { throw new IllegalArgumentException("source is null"); } if (destination == null) { throw new IllegalArgumentException("destination is null"); } destination.setCreated(source.getCreated() != null ? new Date(source.getCreated().toInstant().toEpochMilli()) : null); destination.setUpdated(source.getUpdated() != null ? new Date(source.getUpdated().toInstant().toEpochMilli()) : null); destination.setId(source.getId()); destination.setName(source.getName()); if (modelTranslator != null) { Set<UserDTO> users = source.getUsers(); if (users != null) { destination.setUsers(users.stream() .map(modelTranslator.getStreamMapper(UserDTO.class, User.class)) .collect(Collectors.toSet())); } else { destination.setUsers(Collections.emptySet()); } List<PermissionBlueprintDTO> permissions = source.getPermissions(); if (permissions != null) { destination.setPermissions(permissions.stream() .map(modelTranslator.getStreamMapper(PermissionBlueprintDTO.class, PermissionBlueprint.class)) .collect(Collectors.toSet())); } else { destination.setPermissions(Collections.emptySet()); } } else { destination.setUsers(Collections.emptySet()); destination.setPermissions(Collections.emptySet()); } return destination; }
Source:
public Single<Media> fetchMediaDetails(String filename) { Single<Media> mediaSingle = getMediaFromFileName(filename); Single<Boolean> pageExistsSingle = mediaClient.doesPageExist("Commons:Deletion_requests/" + filename); Single<String> discussionSingle = getDiscussion(filename); return Single.zip(mediaSingle, pageExistsSingle, discussionSingle, (media, deletionStatus, discussion) -> { media.setDiscussion(discussion); if (deletionStatus) { media.setRequestedDeletion(); } return media; }); }

Target:
public Single<Media> fetchMediaDetails(String filename) { Single<Media> mediaSingle = getMediaFromFileName(filename); Single<Boolean> pageExistsSingle = mediaClient.checkPageExistsUsingTitle("Commons:Deletion_requests/" + filename); Single<String> discussionSingle = getDiscussion(filename); return Single.zip(mediaSingle, pageExistsSingle, discussionSingle, (media, deletionStatus, discussion) -> { media.setDiscussion(discussion); if (deletionStatus) { media.setRequestedDeletion(); } return media; }); }
Source:
public void doubleAllocate() { clf.createCANTalon(1); try { clf.createCANTalon(1); assertTrue("You shouldn't be able to double-allocate!", false); } catch (Exception e) { } }

Target:
public void doubleAllocate() { clf.createCANTalon(1); clf.createCANTalon(1); assertTrue("You shouldn't be able to double-allocate!", false); }
Source:
public void clickPropertiesTableButton() { selectFromContextMenu(propertiesItem); waitForElementByElement(tablePropertiesInputs.get(2)); }

Target:
public void clickPropertiesTableButton() { selectFromContextMenu(propertiesItem); waitForElementByElement(addTableLightbox); }
Source:
private TreeWalk createFileWalker(Repository db, List<FilterPath> paths) { final TreeWalk fileWalker = new TreeWalk(db); fileWalker.setRecursive(true); if (store.getBoolean(UIPreferences.RESOURCEHISTORY_FOLLOW_RENAMES) && paths.size() == 1 && paths.get(0).isRegularFile()) { pathFilters = paths; String selectedPath = paths.get(0).getPath(); currentWalk.setTreeFilter(FollowFilter.create(selectedPath)); fileWalker.setFilter(AndTreeFilter.create(PathFilterGroup .createFromStrings(selectedPath), TreeFilter.ANY_DIFF)); } else if (paths.size() > 0) { pathFilters = paths; List<String> stringPaths = new ArrayList<String>(paths.size()); for (FilterPath p : paths) { stringPaths.add(p.getPath()); } currentWalk.setTreeFilter(AndTreeFilter.create(PathFilterGroup .createFromStrings(stringPaths), TreeFilter.ANY_DIFF)); fileWalker.setFilter(currentWalk.getTreeFilter().clone()); } else { pathFilters = null; currentWalk.setTreeFilter(TreeFilter.ALL); fileWalker.setFilter(TreeFilter.ANY_DIFF); } return fileWalker; }

Target:
private TreeWalk createFileWalker(Repository db, List<FilterPath> paths) { final TreeWalk fileWalker = new TreeWalk(db); fileWalker.setRecursive(true); if (store.getBoolean(UIPreferences.RESOURCEHISTORY_FOLLOW_RENAMES) && !paths.isEmpty() && allRegularFiles(paths)) { pathFilters = paths; List<String> selectedPaths = new ArrayList<String>(paths.size()); for (FilterPath filterPath : paths) selectedPaths.add(filterPath.getPath()); TreeFilter followFilter = createFollowFilterFor(selectedPaths); currentWalk.setTreeFilter(followFilter); fileWalker.setFilter(AndTreeFilter.create(PathFilterGroup .createFromStrings(selectedPaths), TreeFilter.ANY_DIFF)); } else if (paths.size() > 0) { pathFilters = paths; List<String> stringPaths = new ArrayList<String>(paths.size()); for (FilterPath p : paths) stringPaths.add(p.getPath()); currentWalk.setTreeFilter(AndTreeFilter.create(PathFilterGroup .createFromStrings(stringPaths), TreeFilter.ANY_DIFF)); fileWalker.setFilter(currentWalk.getTreeFilter().clone()); } else { pathFilters = null; currentWalk.setTreeFilter(TreeFilter.ALL); fileWalker.setFilter(TreeFilter.ANY_DIFF); } return fileWalker; }
Source:
public UUID lookupUUID(String name) { for (OfflinePlayer player : getOfflinePlayers()) { if (player.getName().equalsIgnoreCase(name)) { return player.getUniqueId(); } } if (Bukkit.getServer().getOnlineMode()) { UUID id = UuidUtils.fetchUUID(name); if (id != null) { return id; } } return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8)); }

Target:
public UUID lookupUUID(String name) { for (OfflinePlayer player : getOfflinePlayers()) { if (player.getName().equalsIgnoreCase(name)) { return player.getUniqueId(); } } if (Bukkit.getServer().getOnlineMode() || ((GlowServer) Bukkit.getServer()).getProxySupport()) { UUID id = UuidUtils.fetchUUID(name); if (id != null) { return id; } } return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8)); }
Source:
private static boolean allChildrenTypeOnly(Cast node) { ImmutableList.Builder<Boolean> casts = ImmutableList.builder(); new DefaultExpressionTraversalVisitor<Void, ImmutableList.Builder<Boolean>>() { @Override protected Void visitCast(Cast node, ImmutableList.Builder<Boolean> context) { super.visitCast(node, context); context.add(node.isTypeOnly()); return null; } }.process(node, casts); return casts.build().stream().allMatch(Boolean::booleanValue); }

Target:
private static boolean allChildrenTypeOnly(Cast node) { AtomicReference<Optional<Boolean>> allTrue = new AtomicReference<>(Optional.empty()); new DefaultExpressionTraversalVisitor<Void, AtomicReference<Optional<Boolean>>>() { @Override protected Void visitCast(Cast node, AtomicReference<Optional<Boolean>> context) { super.visitCast(node, context); context.set(Optional.of(node.isTypeOnly() && context.get().orElse(true))); return null; } }.process(node, allTrue); return allTrue.get().orElse(false); }
Source:
void update(RawPacket pkt, long nowMs) { rateStatistics.update(pkt.getLength(), nowMs); long ts = pkt.getTimestamp(); FrameDesc frame = frames.get(ts); boolean isNew; if (frame == null) { isNew = true; synchronized (frames) { frames.put(ts, frame = new FrameDesc(this, ts, nowMs)); } lastStableBitrateBps = getBitrateBps(nowMs); if (lastReceivedFrame == null || TimeUtils.rtpDiff(ts, lastReceivedFrame.getTimestamp()) > 0) { lastReceivedFrame = frame; } } else { isNew = false; } boolean frameChanged = frame.update(pkt); if (frameChanged) { Map.Entry<Long, FrameDesc> ceilingEntry = frames.ceilingEntry((ts + 1) & 0xFFFFFFFFL); if (ceilingEntry != null) { applyFrameBoundsHeuristics(frame, ceilingEntry.getValue()); } Map.Entry<Long, FrameDesc> floorEntry = frames.floorEntry((ts - 1) & 0xFFFFFFFFL); if (floorEntry != null) { applyFrameBoundsHeuristics(floorEntry.getValue(), frame); } } track.update(pkt, frame, isNew, nowMs); }

Target:
void update(RawPacket pkt, long nowMs) { rateStatistics.update(pkt.getLength(), nowMs); long ts = pkt.getTimestamp(); FrameDesc frame = frames.get(ts); boolean isPacketOfNewFrame; if (frame == null) { isPacketOfNewFrame = true; synchronized (frames) { frames.put(ts, frame = new FrameDesc(this, ts, nowMs)); } lastStableBitrateBps = getBitrateBps(nowMs); if (lastReceivedFrame == null || TimeUtils.rtpDiff(ts, lastReceivedFrame.getTimestamp()) > 0) { lastReceivedFrame = frame; } } else { isPacketOfNewFrame = false; } boolean frameChanged = frame.update(pkt); if (frameChanged) { Map.Entry<Long, FrameDesc> ceilingEntry = frames.ceilingEntry((ts + 1) & 0xFFFFFFFFL); if (ceilingEntry != null) { applyFrameBoundsHeuristics(frame, ceilingEntry.getValue()); } Map.Entry<Long, FrameDesc> floorEntry = frames.floorEntry((ts - 1) & 0xFFFFFFFFL); if (floorEntry != null) { applyFrameBoundsHeuristics(floorEntry.getValue(), frame); } } track.update(pkt, frame, isPacketOfNewFrame, nowMs); }
Source:
public void testVariance() { final SecureRandom random = new SecureRandom(); final int numberOfSamples = 10000; for (int run = 0; run < 100; run++) { final double[] dist = new double[8]; for (int i = 0; i < numberOfSamples; i++) { dist[random.nextInt(dist.length)]++; } final double variance = calculateVarianceOfUniformDistribution(dist); System.out.println(Arrays.toString(dist) + " = " + variance); } }

Target:
public void testVariance() { final SecureRandom random = new SecureRandom(); final int numberOfSamples = 100000; final int numberOfRuns = 1000; final double threshold = 1.5; double failProbability = 0; for (int run = 0; run < numberOfRuns; run++) { final double[] dist = new double[8]; for (int i = 0; i < numberOfSamples; i++) { dist[random.nextInt(dist.length)]++; } final double variance = calculateVarianceOfUniformDistribution(dist); if (variance > threshold) { failProbability += (1.0 / numberOfRuns); } if (((run * 100.0) / numberOfRuns) % 1 == 0) { System.out.println((int) ((run * 100.0) / numberOfRuns) + "%"); } } System.out.println("probability to fail the test: " + failProbability); }
Source:
private void initializeTabs() { final List<FragmentItemModel> fragmentItems = getFragmentItems(); final TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.appbar).findViewById(R.id.tabs); if (fragmentItems.size() <= 1) { tabLayout.setVisibility(View.GONE); } else { tabLayout.setVisibility(View.VISIBLE); for (FragmentItemModel fragmentItem : fragmentItems) { tabLayout.addTab(createTab(tabLayout, fragmentItem)); } tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { binding.viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } final TabLayout.TabLayoutOnPageChangeListener pageChangeListener = new TabLayout.TabLayoutOnPageChangeListener(tabLayout) { @Override public void onPageSelected(int position) { super.onPageSelected(position); final FragmentItemModel item = fragmentItems.get(position); getActivity().setTitle(item.getTitle()); if (item.getListener() != null) { item.getListener().onFragmentSelected(); } } }; final FragmentItemPagerAdapter adapter = new FragmentItemPagerAdapter(this.getActivity().getSupportFragmentManager(), fragmentItems); binding.viewPager.setAdapter(adapter); binding.viewPager.addOnPageChangeListener(pageChangeListener); binding.viewPager.setOffscreenPageLimit(fragmentItems.size() - 1); binding.viewPager.post(new Runnable() { @Override public void run() { pageChangeListener.onPageSelected(binding.viewPager.getCurrentItem()); } }); }

Target:
private void initializeTabs() { final List<FragmentItemModel> fragmentItems = getFragmentItems(); final TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.tabs); if (fragmentItems.size() <= 1) { tabLayout.setVisibility(View.GONE); } else { tabLayout.setVisibility(View.VISIBLE); for (FragmentItemModel fragmentItem : fragmentItems) { tabLayout.addTab(createTab(tabLayout, fragmentItem)); } tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { binding.viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } final TabLayout.TabLayoutOnPageChangeListener pageChangeListener = new TabLayout.TabLayoutOnPageChangeListener(tabLayout) { @Override public void onPageSelected(int position) { super.onPageSelected(position); final FragmentItemModel item = fragmentItems.get(position); getActivity().setTitle(item.getTitle()); if (item.getListener() != null) { item.getListener().onFragmentSelected(); } } }; final FragmentItemPagerAdapter adapter = new FragmentItemPagerAdapter(this.getActivity().getSupportFragmentManager(), fragmentItems); binding.viewPager.setAdapter(adapter); binding.viewPager.addOnPageChangeListener(pageChangeListener); binding.viewPager.setOffscreenPageLimit(fragmentItems.size() - 1); binding.viewPager.post(new Runnable() { @Override public void run() { pageChangeListener.onPageSelected(binding.viewPager.getCurrentItem()); } }); }