auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void terminatingTransactionMustEagerlyReleaseTheirLocks() throws Exception { AtomicBoolean nodeLockAcquired = new AtomicBoolean(); AtomicBoolean lockerDone = new AtomicBoolean(); BinaryLatch lockerPause = new BinaryLatch(); long nodeId; try ( Transaction tx = database.beginTx() ) { nodeId = database.createNode().getId(); tx.success(); } Future<?> locker = executor.submit( () -> { try ( Transaction tx = database.beginTx( 100, TimeUnit.MILLISECONDS ) ) { Node node = database.getNodeById( nodeId ); tx.acquireReadLock( node ); nodeLockAcquired.set( true ); lockerPause.await(); } lockerDone.set( true ); } ); boolean proceed; do { proceed = nodeLockAcquired.get(); } while ( !proceed ); Thread.sleep( 150 ); assertFalse( lockerDone.get() ); try ( Transaction tx = database.beginTx() ) { tx.acquireWriteLock( database.getNodeById( nodeId ) ); tx.success(); } lockerPause.release(); locker.get(); assertTrue( lockerDone.get() ); }

Target:
public void terminatingTransactionMustEagerlyReleaseTheirLocks() throws Exception { AtomicBoolean nodeLockAcquired = new AtomicBoolean(); AtomicBoolean lockerDone = new AtomicBoolean(); BinaryLatch lockerPause = new BinaryLatch(); long nodeId; try ( Transaction tx = database.beginTx() ) { nodeId = database.createNode().getId(); tx.success(); } Future<?> locker = executor.submit( () -> { try ( Transaction tx = database.beginTx( 100, TimeUnit.MILLISECONDS ) ) { Node node = database.getNodeById( nodeId ); tx.acquireReadLock( node ); nodeLockAcquired.set( true ); lockerPause.await(); } lockerDone.set( true ); } ); boolean proceed; do { proceed = nodeLockAcquired.get(); } while ( !proceed ); Thread.sleep( 150 ); database.resolveDependency( KernelTransactionTimeoutMonitor.class ).run(); assertFalse( lockerDone.get() ); try ( Transaction tx = database.beginTx() ) { tx.acquireWriteLock( database.getNodeById( nodeId ) ); tx.success(); } lockerPause.release(); locker.get(); assertTrue( lockerDone.get() ); }
Source:
public void startPolicyEnforcement() throws IOException { if (m_pbd.getUsageSpecificLog().isDebugEnabled()) { m_pbd.getUsageSpecificLog().debug("Starting time based retention policy enforcement with retainMillis=" + m_retainMillis + " for PBD " + m_pbd.getNonce()); } m_reader = m_pbd.openForRead(CURSOR_NAME); scheduleTaskFor(m_pbd.getNonce(), ()->deleteOldSegments(), 0); }

Target:
public void startPolicyEnforcement() throws IOException { if (m_pbd.getUsageSpecificLog().isDebugEnabled()) { m_pbd.getUsageSpecificLog().debug("Starting time based retention policy enforcement with retainMillis=" + m_retainMillis + " for PBD " + m_pbd.getNonce()); } m_reader = m_pbd.openForRead(CURSOR_NAME); scheduleTaskFor(m_pbd.getNonce(), this::deleteOldSegments, 0); }
Source:
@VisibleForTesting Call<Wikitext> request(@NonNull Service service, @NonNull final PageTitle title, final int sectionID, @NonNull final Callback cb) { Call<Wikitext> call = service.wikitext(title.getPrefixedText(), sectionID); call.enqueue(new retrofit2.Callback<Wikitext>() { @Override public void onResponse(Call<Wikitext> call, Response<Wikitext> response) { if (response.isSuccessful()) { if (response.body() == null) { cb.failure(call, new JsonParseException("Response missing required field(s)")); return; } cb.success(call, response.body().wikitext()); } else { cb.failure(call, RetrofitException.httpError(response, cachedService.retrofit())); } } @Override public void onFailure(Call<Wikitext> call, Throwable t) { cb.failure(call, t); } }); return call; }

Target:
@VisibleForTesting Call<Wikitext> request(@NonNull Service service, @NonNull final PageTitle title, final int sectionID, @NonNull final Callback cb) { Call<Wikitext> call = service.wikitext(title.getPrefixedText(), sectionID); call.enqueue(new retrofit2.Callback<Wikitext>() { @Override public void onResponse(Call<Wikitext> call, Response<Wikitext> response) { if (response.isSuccessful()) { if (response.body() == null) { Throwable t = new JsonParseException("Response missing query field"); L.logRemoteErrorIfProd(t); cb.failure(call, t); return; } cb.success(call, response.body().wikitext()); } else { cb.failure(call, RetrofitException.httpError(response, cachedService.retrofit())); } } @Override public void onFailure(Call<Wikitext> call, Throwable t) { cb.failure(call, t); } }); return call; }
Source:
public int hashCode() { int pcHashCode = 0; Collection<ProductContentDTO> productContent = this.getProductContent(); if (productContent != null) { for (ProductContentDTO dto : productContent) { pcHashCode = 31 * pcHashCode + (dto != null ? dto.hashCode() : 0); } } int ppHashCode = 0; Collection<ProductDTO> providedProducts = this.getProvidedProducts(); if (providedProducts != null) { for (ProductDTO dto : providedProducts) { ppHashCode = 31 * ppHashCode + (dto != null ? dto.hashCode() : 0); } } HashCodeBuilder builder = new HashCodeBuilder(37, 7) .append(super.hashCode()) .append(this.getUuid()) .append(this.getMultiplier()) .append(this.getId()) .append(this.getName()) .append(this.getAttributes()) .append(this.getDependentProductIds()) .append(this.getBranding()) .append(this.getProvidedProducts()) .append(pcHashCode) .append(ppHashCode); return builder.toHashCode(); }

Target:
public int hashCode() { int pcHashCode = 0; Collection<ProductContentDTO> productContent = this.getProductContent(); if (productContent != null) { for (ProductContentDTO dto : productContent) { pcHashCode = 31 * pcHashCode + (dto != null ? dto.hashCode() : 0); } } HashCodeBuilder builder = new HashCodeBuilder(37, 7) .append(super.hashCode()) .append(this.getUuid()) .append(this.getMultiplier()) .append(this.getId()) .append(this.getName()) .append(this.getAttributes()) .append(this.getDependentProductIds()) .append(this.getBranding()) .append(this.getProvidedProducts()) .append(pcHashCode); return builder.toHashCode(); }
Source:
private ArrayList<MediaOption> initOtherMediaImageOptions() { ArrayList<MediaOption> otherMediaOptions = new ArrayList<>(); FragmentActivity activity = getActivity(); Bundle arguments = getArguments(); GutenbergWebViewAuthorizationData gutenbergWebViewAuthorizationData = arguments.getParcelable(ARG_GUTENBERG_WEB_VIEW_AUTH_DATA); boolean supportStockPhotos = arguments != null && gutenbergWebViewAuthorizationData.isSiteUsingWPComRestAPI(); boolean supportGifs = arguments != null && arguments.getBoolean(ARG_TENOR_ENABLED); if (activity != null) { String packageName = activity.getApplication().getPackageName(); if (supportStockPhotos) { int stockMediaResourceId = getResources().getIdentifier("photo_picker_stock_media", "string", packageName); otherMediaOptions.add(new MediaOption(MEDIA_SOURCE_STOCK_MEDIA, getString(stockMediaResourceId))); } if (supportGifs) { int gifMediaResourceId = getResources().getIdentifier("photo_picker_gif", "string", packageName); otherMediaOptions.add(new MediaOption(GIF_MEDIA, getString(gifMediaResourceId))); } } else { AppLog.e(T.EDITOR, "Failed to initialize other media options because the activity is null"); } return otherMediaOptions; }

Target:
private ArrayList<MediaOption> initOtherMediaImageOptions() { ArrayList<MediaOption> otherMediaOptions = new ArrayList<>(); Bundle arguments = getArguments(); FragmentActivity activity = getActivity(); if (activity == null || arguments == null) { AppLog.e(T.EDITOR, "Failed to initialize other media options because the activity or getArguments() is null"); return otherMediaOptions; } GutenbergWebViewAuthorizationData gutenbergWebViewAuthorizationData = arguments.getParcelable(ARG_GUTENBERG_WEB_VIEW_AUTH_DATA); boolean supportStockPhotos = gutenbergWebViewAuthorizationData.isSiteUsingWPComRestAPI(); boolean supportGifs = arguments.getBoolean(ARG_TENOR_ENABLED, false); String packageName = activity.getApplication().getPackageName(); if (supportStockPhotos) { int stockMediaResourceId = getResources().getIdentifier("photo_picker_stock_media", "string", packageName); otherMediaOptions.add(new MediaOption(MEDIA_SOURCE_STOCK_MEDIA, getString(stockMediaResourceId))); } if (supportGifs) { int gifMediaResourceId = getResources().getIdentifier("photo_picker_gif", "string", packageName); otherMediaOptions.add(new MediaOption(GIF_MEDIA, getString(gifMediaResourceId))); } return otherMediaOptions; }
Source:
private static MultiBucketContentRepoEndpoint parseCorpusStorage(MultibucketContentRepoEndpointInput corpus) { URI address = corpus.address; if (address == null) { throw new RuntimeException("contentRepo.corpus.address must be configured"); } String defaultBucket = corpus.bucket; if (defaultBucket == null) { throw new RuntimeException("contentRepo.corpus.bucket must be configured"); } ImmutableSet<String> allBuckets = ImmutableSet.<String>builder() .add(defaultBucket) .addAll(MoreObjects.firstNonNull(corpus.secondaryBuckets, ImmutableSet.of())) .build(); ImmutableSet<String> secondaryBuckets = ImmutableSet.<String>builder() .addAll(MoreObjects.firstNonNull(corpus.secondaryBuckets, ImmutableSet.of())) .build(); return new MultiBucketContentRepoEndpoint() { @Override public URI getAddress() { return address; } @Override public String getDefaultBucket() { return defaultBucket; } @Override public ImmutableSet<String> getAllBuckets() { return allBuckets; } @Override public ImmutableSet<String> getSecondaryBuckets() { return secondaryBuckets; } }; }

Target:
private static MultiBucketContentRepoEndpoint parseCorpusStorage(MultibucketContentRepoEndpointInput corpus) { URI address = corpus.address; if (address == null) { throw new RuntimeException("contentRepo.corpus.address must be configured"); } String defaultBucket = corpus.bucket; if (defaultBucket == null) { throw new RuntimeException("contentRepo.corpus.bucket must be configured"); } ImmutableSet<String> allBuckets = ImmutableSet.<String>builder() .add(defaultBucket) .addAll(MoreObjects.firstNonNull(corpus.secondaryBuckets, ImmutableSet.of())) .build(); ImmutableSet<String> secondaryBuckets = ImmutableSet.copyOf(MoreObjects.firstNonNull(corpus.secondaryBuckets, ImmutableSet.of())); return new MultiBucketContentRepoEndpoint() { @Override public URI getAddress() { return address; } @Override public String getDefaultBucket() { return defaultBucket; } @Override public ImmutableSet<String> getAllBuckets() { return allBuckets; } @Override public ImmutableSet<String> getSecondaryBuckets() { return secondaryBuckets; } }; }
Source:
public IAtsVersion getTargetedVersionByTeamWf(IAtsTeamWorkflow team) throws OseeCoreException { Collection<ArtifactId> versions = services.getRelationResolver().getRelated((team.getStoreObject()), AtsRelationTypes.TeamWorkflowTargetedForVersion_Version); IAtsVersion version = null; if (!versions.isEmpty()) { if (versions.size() > 1) { OseeLog.log(Activator.class, Level.SEVERE, "Multiple targeted versions for artifact " + team.toStringWithId()); } else { version = services.getConfigItemFactory().getVersion(versions.iterator().next()); } } return version; }

Target:
public IAtsVersion getTargetedVersionByTeamWf(IAtsTeamWorkflow team) throws OseeCoreException { if (team == null) { throw new OseeArgumentException("Team Workflow can not be null %s", team); } Collection<ArtifactId> versions = services.getRelationResolver().getRelated((team.getStoreObject()), AtsRelationTypes.TeamWorkflowTargetedForVersion_Version); IAtsVersion version = null; if (!versions.isEmpty()) { if (versions.size() > 1) { OseeLog.log(Activator.class, Level.SEVERE, "Multiple targeted versions for artifact " + team.toStringWithId()); } else { version = services.getConfigItemFactory().getVersion(versions.iterator().next()); } } return version; }
Source:
public void afterRegionClearIsInvokedOnAccessorAndDataMembers() { CacheListener<String, Integer> listener = new ClearCountingCacheListener(); Region<String, Integer> region = createAccessorRegion(regionName, listener); for (int i = 0; i < getVMCount(); i++) { getVM(i).invoke(() -> { withData(createRegion(regionName, listener)); }); } region.clear(); assertThat(sharedCountersRule.getTotal(CLEAR)).isEqualTo(expectedRegionDestroys()); }

Target:
public void afterRegionClearIsInvokedOnAccessorAndDataMembers() { CacheListener<String, Integer> listener = new ClearCountingCacheListener(); Region<String, Integer> region = createAccessorRegion(regionName, listener); for (int i = 0; i < getVMCount(); i++) { getVM(i).invoke(() -> { withData(createRegion(regionName, listener)); }); } region.clear(); assertThat(sharedCountersRule.getTotal(CLEAR)).isEqualTo(expectedClears()); }
Source:
public void onChatMessage(ChatMessageEvent event) { Platform.runLater(() -> { ChatMessage message = event.getMessage(); if (message.getSource().equals(String.format("#%s'sParty", teamMatchmakingService.getParty().getOwner().getUsername()))) { matchmakingChatController.onChatMessage(message); } }); }

Target:
public void onChatMessage(ChatMessageEvent event) { ChatMessage message = event.getMessage(); if (message.getSource().equals(matchmakingChatController.getReceiver())) { Platform.runLater(() -> matchmakingChatController.onChatMessage(message)); } }
Source:
static void setup() { WebDriverManager.firefoxdriver().setup(); System.setProperty( SeleniumOptions.FIREFOX_DRIVER_SYSTEM_PROPERTY, System.getProperty("webdriver.gecko.driver")); }

Target:
static void setup() { WebDriverManager.firefoxdriver().setup(); WebDriverManager.chromedriver().setup(); }
Source:
public void clickSourceButton(){ waitForElementByElement(sourceButton); sourceButton.click(); driver.switchTo().defaultContent(); }

Target:
public void clickSourceButton(){ waitForElementByElement(sourceButton); sourceButton.click(); driver.switchTo().defaultContent(); PageObjectLogging.log("clickSourceButton", "Source button was clicked", true, driver); }
Source:
private void normalizeIntensities() { normalizedXIntensities = new float[numberOfSnps]; normalizedYIntensities = new float[numberOfSnps]; int[] normIds = normalizationManifest.getNormIds(); for (int i = 0; i < rawXIntensities.length; i++) { int rawX = rawXIntensities[i]; int rawY = rawYIntensities[i]; int normId; int normIndex = -1; if ((normIds != null) && (normIds.length > i)) { normId = normIds[i]; normIndex = getAllNormIndex(normId); } if (normIndex != -1) { InfiniumTransformation xform = normalizationTransformations[normIndex]; float tempX = rawX - xform.getOffsetX(); float tempY = rawY - xform.getOffsetY(); float theta = xform.getTheta(); double tempX2 = Math.cos(theta) * tempX + Math.sin(theta) * tempY; double tempY2 = -Math.sin(theta) * tempX + Math.cos(theta) * tempY; double tempX3 = tempX2 - xform.getShear() * tempY2; if (tempX3 < 0) { tempX3 = 0; } if (tempY2 < 0) { tempY2 = 0; } normalizedXIntensities[i] = (float) (tempX3 / xform.getScaleX()); normalizedYIntensities[i] = (float) (tempY2 / xform.getScaleY()); } else { normalizedXIntensities[i] = rawXIntensities[i]; normalizedYIntensities[i] = rawYIntensities[i]; } } }

Target:
private void normalizeIntensities() { normalizedXIntensities = new float[numberOfSnps]; normalizedYIntensities = new float[numberOfSnps]; final int[] normIds = normalizationManifest.getNormIds(); for (int i = 0; i < rawXIntensities.length; i++) { final int rawX = rawXIntensities[i]; final int rawY = rawYIntensities[i]; final int normId; int normIndex = -1; if ((normIds != null) && (normIds.length > i)) { normId = normIds[i]; normIndex = getAllNormIndex(normId); } if (normIndex != -1) { final InfiniumTransformation xform = normalizationTransformations[normIndex]; final float tempX = rawX - xform.getOffsetX(); final float tempY = rawY - xform.getOffsetY(); final float theta = xform.getTheta(); double tempX2 = Math.cos(theta) * tempX + Math.sin(theta) * tempY; double tempY2 = -Math.sin(theta) * tempX + Math.cos(theta) * tempY; double tempX3 = tempX2 - xform.getShear() * tempY2; if (tempX3 < 0) { tempX3 = 0; } if (tempY2 < 0) { tempY2 = 0; } normalizedXIntensities[i] = (float) (tempX3 / xform.getScaleX()); normalizedYIntensities[i] = (float) (tempY2 / xform.getScaleY()); } else { normalizedXIntensities[i] = rawXIntensities[i]; normalizedYIntensities[i] = rawYIntensities[i]; } } }
Source:
public void tearDown() throws Exception { if (app != null) Entities.destroy(app); }

Target:
public void tearDown() throws Exception { if (app != null) Entities.destroyAll(app.getManagementContext()); }
Source:
public HSBType(String value) { if (value != null) { String[] constituents = value.split(","); if (constituents.length == 3) { String constituent0 = constituents[0].trim(); String constituent1 = constituents[1].trim(); String constituent2 = constituents[2].trim(); this.hue = new BigDecimal(constituent0); this.saturation = new BigDecimal(constituent1); this.value = new BigDecimal(constituent2); } else { throw new IllegalArgumentException(value + " is not a valid HSBType syntax"); } } else { throw new IllegalArgumentException("Constructor argument must not be null"); } }

Target:
public HSBType(String value) { if (value != null) { List<String> constituents = Arrays.stream(value.split(",")).map(in -> in.trim()) .collect(Collectors.toList()); if (constituents.size() == 3) { this.hue = new BigDecimal(constituents.get(0)); this.saturation = new BigDecimal(constituents.get(1)); this.value = new BigDecimal(constituents.get(2)); } else { throw new IllegalArgumentException(value + " is not a valid HSBType syntax"); } } else { throw new IllegalArgumentException("Constructor argument must not be null"); } }
Source:
public void answerWhenMentioned() throws Exception { final Repo repo = new MkGithub().randomRepo(); final Issue issue = repo.issues().create("", ""); issue.comments().post("hello @xx deploy"); MatcherAssert.assertThat( new QnReferredTo("xx", new QnDeploy()).understand( new Comment.Smart(issue.comments().get(1)), new URI("#") ), Matchers.is(Req.DONE) ); MatcherAssert.assertThat( new Comment.Smart(issue.comments().get(2)).body(), Matchers.containsString( StringUtils.join( "I see you're talking about me, but I don't", " understand it. If you want to say something to me", " directly, start a message with @xx" ) ) ); }

Target:
public void answerWhenMentioned() throws Exception { final Repo repo = new MkGithub().randomRepo(); final Issue issue = repo.issues().create("", ""); final String login = "xx"; issue.comments().post(String.format("hello @%s deploy", login)); MatcherAssert.assertThat( new QnReferredTo(login, new QnDeploy()).understand( new Comment.Smart(issue.comments().get(1)), new URI("#") ), Matchers.is(Req.DONE) ); MatcherAssert.assertThat( new Comment.Smart(issue.comments().get(2)).body(), Matchers.containsString( StringUtils.join( "I see you're talking about me, but I don't", " understand it. If you want to say something to me", " directly, start a message with @", login ) ) ); }
Source:
private boolean argumentInheritsFromBaseException(Argument argument) { if (!argument.is(Tree.Kind.REGULAR_ARGUMENT)) { return true; } Expression expression = ((RegularArgument) argument).expression(); if (expression.is(Tree.Kind.NAME) || expression.is(Tree.Kind.QUALIFIED_EXPR)) { return inheritsFromBaseException(((HasSymbol) expression).symbol()); } return true; }

Target:
private boolean argumentInheritsFromBaseException(Argument argument) { if (!argument.is(Tree.Kind.REGULAR_ARGUMENT)) { return true; } Expression expression = ((RegularArgument) argument).expression(); if (expression instanceof HasSymbol) { return inheritsFromBaseException(((HasSymbol) expression).symbol()); } return true; }
Source:
private synchronized boolean hasLockWatch(LockDescriptor lockDescriptor) { return ranges.contains(lockDescriptor); }

Target:
private boolean hasLockWatch(LockDescriptor lockDescriptor) { return ranges.get().contains(lockDescriptor); }
Source:
public org.eclipse.jface.util.IPropertyChangeListener getPreferenceChangeListener() { if (listener == null) { listener = new org.eclipse.jface.util.IPropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent event) { if (event.getProperty().equals(PreferenceConstants.P_EVENT_CONNECTOR_COLOR) || event.getProperty().equals(PreferenceConstants.P_DATA_CONNECTOR_COLOR) || event.getProperty().equals(PreferenceConstants.P_ADAPTER_CONNECTOR_COLOR)) { getFigure().repaint(); } } }; } return listener; }

Target:
public org.eclipse.jface.util.IPropertyChangeListener getPreferenceChangeListener() { if (null == listener) { listener = new org.eclipse.jface.util.IPropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent event) { if (event.getProperty().equals(PreferenceConstants.P_EVENT_CONNECTOR_COLOR) || event.getProperty().equals(PreferenceConstants.P_DATA_CONNECTOR_COLOR) || event.getProperty().equals(PreferenceConstants.P_ADAPTER_CONNECTOR_COLOR)) { getFigure().repaint(); } } }; } return listener; }
Source:
public GoogleProvider(Activity activity, IDPProviderParcel parcel, @Nullable String email) { mActivity = activity; String mClientId = parcel.getProviderExtra().getString(CLIENT_ID_KEY); GoogleSignInOptions googleSignInOptions; GoogleSignInOptions.Builder builder = new GoogleSignInOptions.Builder(GoogleSignInOptions .DEFAULT_SIGN_IN) .requestEmail() .requestIdToken(mClientId); if (email != null) { builder.setAccountName(email); } googleSignInOptions = builder.build(); mGoogleApiClient = new GoogleApiClient.Builder(activity) .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions) .build(); mGoogleApiClient.connect(); }

Target:
public GoogleProvider(Activity activity, IDPProviderParcel parcel, @Nullable String email) { mActivity = activity; String mClientId = parcel.getProviderExtra().getString(CLIENT_ID_KEY); GoogleSignInOptions googleSignInOptions; GoogleSignInOptions.Builder builder = new GoogleSignInOptions.Builder(GoogleSignInOptions .DEFAULT_SIGN_IN) .requestEmail() .requestIdToken(mClientId); if (!TextUtils.isEmpty(email)) { builder.setAccountName(email); } googleSignInOptions = builder.build(); mGoogleApiClient = new GoogleApiClient.Builder(activity) .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions) .build(); mGoogleApiClient.connect(); }
Source:
public void countTest() throws Exception { sendManagementCallOnClientToCollectStats(); Cache<String, String> cache = cacheManager.getCache("dedicated-cache-1", String.class, String.class); cache.put("one", "val1"); cache.put("two", "val2"); cache.get("one"); cache.get("two"); cache.get("three"); cache.get("four"); long cacheHitCount = 0; long clusteredHitCount = 0; long cacheMissCount = 0; long clusteredMissCount = 0; do { List<ContextualStatistics> stats = waitForNextStats(); for (ContextualStatistics stat : stats) { if (stat.getContext().contains("cacheName") && stat.getContext().get("cacheName").equals("dedicated-cache-1")) { System.out.println("stats:"); Set<Map.Entry<String, Statistic<?>>> entries = stat.getStatistics().entrySet(); for (Map.Entry<String, Statistic<?>> entry : entries) { System.out.println(" - " + entry.getKey() + " : " + entry.getValue()); } cacheHitCount = stat.<Long>getLatestSampleValue("Cache:HitCount").get(); clusteredHitCount = stat.<Long>getLatestSampleValue("Clustered:HitCount").get(); clusteredMissCount = stat.<Long>getLatestSampleValue("Clustered:MissCount").get(); cacheMissCount = stat.<Long>getLatestSampleValue("Cache:MissCount").get(); } } } while(!Thread.currentThread().isInterrupted() && (cacheHitCount != CACHE_HIT_COUNT) && (clusteredHitCount != CLUSTERED_HIT_COUNT) && (cacheMissCount != CACHE_MISS_COUNT) && (clusteredMissCount != CLUSTERED_MISS_COUNT)); Assert.assertThat(cacheHitCount,is(CACHE_HIT_COUNT)); Assert.assertThat(clusteredHitCount,is(CLUSTERED_HIT_COUNT)); Assert.assertThat(cacheMissCount,is(CACHE_MISS_COUNT)); Assert.assertThat(clusteredMissCount,is(CLUSTERED_MISS_COUNT)); }

Target:
public void countTest() throws Exception { sendManagementCallOnClientToCollectStats(); Cache<String, String> cache = cacheManager.getCache("dedicated-cache-1", String.class, String.class); cache.put("one", "val1"); cache.put("two", "val2"); cache.get("one"); cache.get("two"); cache.get("three"); cache.get("four"); long cacheHitCount = 0; long clusteredHitCount = 0; long cacheMissCount = 0; long clusteredMissCount = 0; do { List<ContextualStatistics> stats = waitForNextStats(); for (ContextualStatistics stat : stats) { if (stat.getContext().contains("cacheName") && stat.getContext().get("cacheName").equals("dedicated-cache-1")) { cacheHitCount = stat.<Long>getLatestSampleValue("Cache:HitCount").get(); clusteredHitCount = stat.<Long>getLatestSampleValue("Clustered:HitCount").get(); clusteredMissCount = stat.<Long>getLatestSampleValue("Clustered:MissCount").get(); cacheMissCount = stat.<Long>getLatestSampleValue("Cache:MissCount").get(); } } } while(!Thread.currentThread().isInterrupted() && (cacheHitCount != CACHE_HIT_COUNT) && (clusteredHitCount != CLUSTERED_HIT_COUNT) && (cacheMissCount != CACHE_MISS_COUNT) && (clusteredMissCount != CLUSTERED_MISS_COUNT)); Assert.assertThat(cacheHitCount,is(CACHE_HIT_COUNT)); Assert.assertThat(clusteredHitCount,is(CLUSTERED_HIT_COUNT)); Assert.assertThat(cacheMissCount,is(CACHE_MISS_COUNT)); Assert.assertThat(clusteredMissCount,is(CLUSTERED_MISS_COUNT)); }
Source:
public static Object[][] storageFormats() { return new StorageFormat[][] { {storageFormat("ORC")}, {storageFormat("ORC", ImmutableMap.of("hive.orc_optimized_writer_enabled", "true", "hive.orc_optimized_writer_validate", "true"))}, {storageFormat("DWRF")}, {storageFormat("PARQUET")}, {storageFormat("PARQUET", ImmutableMap.of("hive.parquet_optimized_reader_enabled", "true"))}, {storageFormat("RCBINARY")}, {storageFormat("RCTEXT")}, {storageFormat("SEQUENCEFILE")}, {storageFormat("TEXTFILE")} }; }

Target:
public static Object[][] storageFormats() { return new StorageFormat[][] { {storageFormat("ORC")}, {storageFormat("ORC", ImmutableMap.of("hive.orc_optimized_writer_enabled", "true", "hive.orc_optimized_writer_validate", "true"))}, {storageFormat("DWRF")}, {storageFormat("PARQUET")}, {storageFormat("PARQUET", ImmutableMap.of("hive.parquet_optimized_reader_enabled", "true"))}, {storageFormat("RCBINARY", ImmutableMap.of("hive.rcfile_optimized_writer_enabled", "false", "hive.rcfile_optimized_writer_validate", "false"))}, {storageFormat("RCBINARY", ImmutableMap.of("hive.rcfile_optimized_writer_enabled", "true", "hive.rcfile_optimized_writer_validate", "true"))}, {storageFormat("RCTEXT", ImmutableMap.of("hive.rcfile_optimized_writer_enabled", "false", "hive.rcfile_optimized_writer_validate", "false"))}, {storageFormat("RCTEXT", ImmutableMap.of("hive.rcfile_optimized_writer_enabled", "true", "hive.rcfile_optimized_writer_validate", "true"))}, {storageFormat("SEQUENCEFILE")}, {storageFormat("TEXTFILE")}, {storageFormat("AVRO")} }; }
Source:
public void testOpenLedgerWithRecovery() throws Exception { long lId; byte[] data = "foo".getBytes(StandardCharsets.UTF_8); final byte[] password = "password".getBytes(StandardCharsets.UTF_8); Map<String, byte[]> customMetadata = new HashMap<>(); customMetadata.put("test", "test".getBytes(StandardCharsets.UTF_8)); try (WriteHandle writer = result(newCreateLedgerOp() .withAckQuorumSize(1) .withWriteQuorumSize(2) .withEnsembleSize(3) .withDigestType(DigestType.MAC) .withCustomMetadata(customMetadata) .withPassword(password) .execute());) { lId = writer.getId(); writer.append(ByteBuffer.wrap(data)).get(); writer.append(ByteBuffer.wrap(data)).get(); registerMockEntryForRead(lId, BookieProtocol.LAST_ADD_CONFIRMED, password, data, -1); registerMockEntryForRead(lId, 0, password, data, -1); registerMockEntryForRead(lId, 1, password, data, 0); try (ReadHandle reader = result(newOpenLedgerOp() .withDigestType(DigestType.MAC) .withPassword(password) .withRecovery(true) .withLedgerId(lId) .execute())) { } try { result(writer.append(ByteBuffer.wrap(data))); fail("should not be able to write"); } catch (BKLedgerFencedException ok) { } } try (ReadHandle reader = result(newOpenLedgerOp() .withDigestType(DigestType.MAC) .withPassword(password) .withRecovery(false) .withLedgerId(lId) .execute())) { assertEquals(1, reader.getLastAddConfirmed()); assertEquals(1, reader.readLastAddConfirmed().get().intValue()); checkEntries(reader.read(0, reader.getLastAddConfirmed()).get(), data); } }

Target:
public void testOpenLedgerWithRecovery() throws Exception { long lId; try (WriteHandle writer = result(newCreateLedgerOp() .withAckQuorumSize(1) .withWriteQuorumSize(2) .withEnsembleSize(3) .withPassword(password) .execute());) { lId = writer.getId(); result(writer.append(ByteBuffer.wrap(data))); result(writer.append(ByteBuffer.wrap(data))); registerMockEntryForRead(lId, BookieProtocol.LAST_ADD_CONFIRMED, password, data, -1); registerMockEntryForRead(lId, 0, password, data, -1); registerMockEntryForRead(lId, 1, password, data, 0); try (ReadHandle reader = result(newOpenLedgerOp() .withPassword(password) .withRecovery(true) .withLedgerId(lId) .execute())) { } result(writer.append(ByteBuffer.wrap(data))); } }
Source:
protected TenantUserManager(ScopeInfo scope, Extension config) { super(scope, config); this.systemTenant = config.get("system-tenant").asString(); this.acceptApiTokens = config.get("accept-api-tokens").asBoolean(true); this.availableLanguages = config.getStringList("availableLanguages").isEmpty() ? Collections.singletonList(NLS.getDefaultLanguage()) : config.getStringList("availableLanguages"); }

Target:
protected TenantUserManager(ScopeInfo scope, Extension config) { super(scope, config); this.systemTenant = config.get("system-tenant").asString(); this.acceptApiTokens = config.get("accept-api-tokens").asBoolean(true); this.availableLanguages = config.getStringList("available-languages").isEmpty() ? Collections.singletonList(NLS.getDefaultLanguage()) : config.getStringList("available-languages"); }
Source:
public void testRemove() { assertEquals(dao.remove(existingAsyncTask.gettask_id()), 1); async_tasks result = dao.get(existingAsyncTask.gettask_id()); assertNull(result); assertEquals(dao.remove(existingAsyncTask.gettask_id()), 0); }

Target:
public void testRemove() { async_tasks result = dao.get(existingAsyncTask.gettask_id()); assertNotNull(result); assertEquals(dao.remove(existingAsyncTask.gettask_id()), 1); result = dao.get(existingAsyncTask.gettask_id()); assertNull(result); assertEquals(dao.remove(existingAsyncTask.gettask_id()), 0); }
Source:
private PhylogeneticNode drawInternal(TreeNode root, List<TreeNode> children, double x, double y) { List<PhylogeneticNode> drawnChildren = new ArrayList<>(); for (int i = 0; i < children.size(); i++) { PhylogeneticNode node = draw(children.get(i), x + LEVELWIDTH, y + (i * LEAFHEIGHT)); drawnChildren.add(node); PhylogeneticEdge edge = new PhylogeneticEdge(node, x); node.setOutgoingEdge(edge); getChildren().addAll(node, edge); } PhylogeneticNode first = drawnChildren.get(0); PhylogeneticNode last = drawnChildren.get(drawnChildren.size() - 1); PhylogeneticNode self = new PhylogeneticNode(x, first.getCenterY() + (last.getCenterY() - first.getCenterY()) / 2, SQUARE); for (PhylogeneticNode child : drawnChildren) { child.getOutgoingEdge().bindTo(self); } return self; }

Target:
private PhylogeneticNode drawInternal(TreeNode root, List<TreeNode> children, double x, double y) { List<PhylogeneticNode> drawnChildren = new ArrayList<>(); for (int i = 0; i < children.size(); i++) { PhylogeneticNode node = draw(children.get(i), x + LEVELWIDTH, y + (i * LEAFHEIGHT)); drawnChildren.add(node); PhylogeneticEdge edge = new PhylogeneticEdge(node, x); node.setIncomingEdge(edge); getChildren().addAll(node, edge); } PhylogeneticNode first = drawnChildren.get(0); PhylogeneticNode last = drawnChildren.get(drawnChildren.size() - 1); PhylogeneticNode self = new PhylogeneticNode(x, first.getCenterY() + (last.getCenterY() - first.getCenterY()) / 2, SQUARE); for (PhylogeneticNode child : drawnChildren) { child.getIncomingEdge().bindTo(self); } return self; }
Source:
public void loadProperties( long entityId, EntityType type, MutableIntSet propertyIds, PropertyLoadSink sink ) { PrimitiveRecord entity; if ( type == EntityType.NODE ) { entity = nodeStore.getRecord( entityId, nodeStore.newRecord(), FORCE ); } else { entity = relationshipStore.getRecord( entityId, relationshipStore.newRecord(), FORCE ); } if ( !entity.inUse() ) { return; } long firstPropertyId = entity.getNextProp(); if ( firstPropertyId == Record.NO_NEXT_PROPERTY.intValue() ) { return; } for ( PropertyRecord propertyRecord : propertyStore.getPropertyRecordChain( firstPropertyId ) ) { for ( PropertyBlock block : propertyRecord ) { int currentPropertyId = block.getKeyIndexId(); if ( propertyIds.contains( currentPropertyId ) ) { Value currentValue = block.getType().value( block, propertyStore ); sink.onProperty( currentPropertyId, currentValue ); propertyIds.remove( currentPropertyId ); } } } }

Target:
public void loadProperties( long entityId, EntityType type, MutableIntSet propertyIds, PropertyLoadSink sink ) { PrimitiveRecord entity; if ( type == EntityType.NODE ) { entity = nodeStore.getRecord( entityId, nodeStore.newRecord(), FORCE ); } else { entity = relationshipStore.getRecord( entityId, relationshipStore.newRecord(), FORCE ); } if ( !entity.inUse() ) { return; } long firstPropertyId = entity.getNextProp(); if ( firstPropertyId == Record.NO_NEXT_PROPERTY.intValue() ) { return; } for ( PropertyRecord propertyRecord : propertyStore.getPropertyRecordChain( firstPropertyId ) ) { for ( PropertyBlock block : propertyRecord ) { int currentPropertyId = block.getKeyIndexId(); if ( propertyIds.remove( currentPropertyId ) ) { Value currentValue = block.getType().value( block, propertyStore ); sink.onProperty( currentPropertyId, currentValue ); } } } }
Source:
public synchronized Api getConnection() throws UnsecuredConnectionAttemptError, ServerException, IOException { if (api == null) { String url = String.format("%s://%s:%s/ovirt-engine/api", protocol, server, port); log.debug(String.format("Logging to %s as %s", url, username)); api = new Api(url, username, password, true); } return api; }

Target:
public synchronized Api getConnection() throws UnsecuredConnectionAttemptError, ServerException, IOException { if (api == null) { String url = String.format("%s://%s:%s/ovirt-engine/api", protocol, server, port); log.debug(String.format("Logging to %s as %s", url, username)); api = new Api(url, username, password, null, null, requestTimeout, true, true, null, false); } return api; }
Source:
public Promise<Void> importProject(Path path, SourceStorageDto source) { String url = getBaseUrl() + IMPORT + encodePath(path); if (url.contains("?")) { url += "&clientId=" + appContext.getApplicationId().orElse(""); } else { url += "?clientId=" + appContext.getApplicationId().orElse(""); } return reqFactory.createPostRequest(url, source).header(CONTENT_TYPE, APPLICATION_JSON).send(); }

Target:
public Promise<Void> importProject(Path path, SourceStorageDto source) { String url = getBaseUrl() + IMPORT + encodePath(path); url += url.contains("?") ? "&" : "?"; url += "clientId=" + appContext.getApplicationId().orElse(""); return reqFactory.createPostRequest(url, source).header(CONTENT_TYPE, APPLICATION_JSON).send(); }
Source:
public void testProcessCJSWithClosureRequires() { args.add("--process_common_js_modules"); args.add("--entry_point=app"); args.add("--dependency_mode=STRICT"); setFilename(0, "base.js"); setFilename(1, "array.js"); setFilename(2, "Baz.js"); setFilename(3, "app.js"); test(new String[] { Joiner.on('\n').join(" ", " var goog = goog || {};", "var COMPILED = false;", "goog.provide = function (arg) {};", "goog.require = function (arg) {};"), "goog.provide('goog.array');", Joiner.on('\n').join("goog.require('goog.array');", "function Baz() {}", "Baz.prototype = {", " baz: function() {", " return goog.array.last(['asdf','asd','baz']);", " },", " bar: function () {", " return 4 + 4;", " }", "};", "module.exports = Baz;"), Joiner.on('\n').join("var Baz = require('./Baz');", "var baz = new Baz();", "console.log(baz.baz());", "console.log(baz.bar());") }, new String[] { "var goog=goog||{},COMPILED=!1;" + "goog.provide=function(a){};goog.require=function(a){};", "goog.array={};", "function Baz$$module$Baz(){}" + "Baz$$module$Baz.prototype={" + " baz:function(){return goog.array.last(['asdf','asd','baz'])}," + " bar:function(){return 8}" + "};" + "var module$Baz=Baz$$module$Baz;", "var module$app={}," + " Baz$$module$app=module$Baz," + " baz$$module$app=new Baz$$module$app;" + "console.log(baz$$module$app.baz());" + "console.log(baz$$module$app.bar())" }); }

Target:
public void testProcessCJSWithClosureRequires() { args.add("--process_common_js_modules"); args.add("--entry_point=app"); args.add("--dependency_mode=STRICT"); setFilename(0, "base.js"); setFilename(1, "array.js"); setFilename(2, "Baz.js"); setFilename(3, "app.js"); test(new String[] { " \n" + " var goog = goog || {};\n" + "var COMPILED = false;\n" + "goog.provide = function (arg) {};\n" + "goog.require = function (arg) {};", "goog.provide('goog.array');", "goog.require('goog.array');" + "function Baz() {}" + "Baz.prototype = {" + " baz: function() {" + " return goog.array.last(['asdf','asd','baz']);" + " }," + " bar: function () {" + " return 4 + 4;" + " }" + "};" + "module.exports = Baz;", "var Baz = require('./Baz');" + "var baz = new Baz();" + "console.log(baz.baz());" + "console.log(baz.bar());" }, new String[] { "var goog=goog||{},COMPILED=!1;" + "goog.provide=function(a){};goog.require=function(a){};", "goog.array={};", "function Baz$$module$Baz(){}" + "Baz$$module$Baz.prototype={" + " baz:function(){return goog.array.last(['asdf','asd','baz'])}," + " bar:function(){return 8}" + "};" + "var module$Baz=Baz$$module$Baz;", "var module$app={}," + " Baz$$module$app=Baz$$module$Baz," + " baz$$module$app=new Baz$$module$app;" + "console.log(baz$$module$app.baz());" + "console.log(baz$$module$app.bar())" }); }
Source:
public ScenarioSimulationEditorPresenter(final Caller<ScenarioSimulationService> service, final ScenarioSimulationResourceType type, final ImportsWidgetPresenter importsWidget, final AsyncPackageDataModelOracleFactory oracleFactory) { super(); this.baseView = newScenarioSimulationView(); this.service = service; this.type = type; this.importsWidget = importsWidget; this.oracleFactory = oracleFactory; }

Target:
public ScenarioSimulationEditorPresenter(final Caller<ScenarioSimulationService> service, final ScenarioSimulationResourceType type, final ImportsWidgetPresenter importsWidget, final AsyncPackageDataModelOracleFactory oracleFactory) { super(); this.view = newScenarioSimulationView(); this.baseView = view; this.service = service; this.type = type; this.importsWidget = importsWidget; this.oracleFactory = oracleFactory; }
Source:
public boolean isInsideStructure(World worldIn, String structureName, BlockPos pos) { if (structureMap.containsKey(structureName)) { return structureMap.get(structureName).isInsideStructure(pos); } return false; }

Target:
public boolean isInsideStructure(World worldIn, String structureName, BlockPos pos) { MapGenStructure structure = structureMap.get(structureName); return structure != null && structureMap.get(structureName).isInsideStructure(pos); }
Source:
public void setup() { super.setup(); factModelTupleLocal = new FactModelTuple(visibleFactsLocal, hiddenFactsLocal); factModelTreeHolderlocal = new BusinessCentralDMNDataManagementStrategy.ResultHolder(); factModelTreeHolderlocal.setFactModelTuple(factModelTupleLocal); try { when(dmnTypeServiceMock.retrieveFactModelTuple(any(), anyString())).thenReturn(factModelTupleLocal); } catch (Exception e) { e.printStackTrace(); } modelLocal.getSettings().setDmnFilePath(DMN_FILE_PATH); abstractDMNDataManagementStrategySpy = spy(new AbstractDMNDataManagementStrategy(mock(EventBus.class)) { @Override protected void retrieveFactModelTuple(TestToolsView.Presenter testToolsPresenter, ScenarioSimulationContext context, String dmnFilePath) { } { this.currentPath = mock(Path.class); this.model = modelLocal; this.factModelTreeHolder = factModelTreeHolderlocal; } }); }

Target:
public void setup() { super.setup(); factModelTupleLocal = new FactModelTuple(visibleFactsLocal, hiddenFactsLocal); factModelTreeHolderlocal = new BusinessCentralDMNDataManagementStrategy.ResultHolder(); factModelTreeHolderlocal.setFactModelTuple(factModelTupleLocal); when(dmnTypeServiceMock.retrieveFactModelTuple(any(), anyString())).thenReturn(factModelTupleLocal); modelLocal.getSettings().setDmnFilePath(DMN_FILE_PATH); abstractDMNDataManagementStrategySpy = spy(new AbstractDMNDataManagementStrategy(mock(EventBus.class)) { @Override protected void retrieveFactModelTuple(TestToolsView.Presenter testToolsPresenter, ScenarioSimulationContext context, String dmnFilePath) { } { this.currentPath = mock(Path.class); this.model = modelLocal; this.factModelTreeHolder = factModelTreeHolderlocal; } }); }
Source:
protected int mergeFileModes(int modeB, int modeO, int modeT) { if (modeO == modeT) return modeO; if (modeB == modeO) return (modeT == FileMode.MISSING.getBits()) ? modeO : modeT; if (modeB == modeT) return (modeO == FileMode.MISSING.getBits()) ? modeT : modeO; return FileMode.MISSING.getBits(); }

Target:
private int mergeFileModes(int modeB, int modeO, int modeT) { if (modeO == modeT) return modeO; if (modeB == modeO) return (modeT == FileMode.MISSING.getBits()) ? modeO : modeT; if (modeB == modeT) return (modeO == FileMode.MISSING.getBits()) ? modeT : modeO; return FileMode.MISSING.getBits(); }
Source:
Mono<Void> completeTransaction(AmqpTransaction transaction, boolean isCommit) { return Mono.fromCallable(() -> { final Message message = Proton.message(); Discharge discharge = new Discharge(); discharge.setFail(!isCommit); discharge.setTxnId(new Binary(transaction.getTransactionId().array())); message.setBody(new AmqpValue(discharge)); final int payloadSize = messageSerializer.getSize(message); final int allocationSize = payloadSize + MAX_AMQP_HEADER_SIZE_BYTES; final byte[] bytes = new byte[allocationSize]; int encodedSize = message.encode(bytes, 0, allocationSize); Tuple2<byte[], Integer> tuple = Tuples.of(bytes, encodedSize); return tuple; }) .flatMap(tuple2 -> sendLink.send(tuple2.getT1(), tuple2.getT2(), DeliveryImpl.DEFAULT_MESSAGE_FORMAT)) .handle((state, sink) -> { if (!(state instanceof Accepted)) { logger.error("Transaction could not be completed, Service Bus status [{}].", transaction, state.toString()); } sink.complete(); }); }

Target:
Mono<Void> completeTransaction(AmqpTransaction transaction, boolean isCommit) { final Message message = Proton.message(); Discharge discharge = new Discharge(); discharge.setFail(!isCommit); discharge.setTxnId(new Binary(transaction.getTransactionId().array())); message.setBody(new AmqpValue(discharge)); final int payloadSize = messageSerializer.getSize(message); final int allocationSize = payloadSize + MAX_AMQP_HEADER_SIZE_BYTES; final byte[] bytes = new byte[allocationSize]; final int encodedSize = message.encode(bytes, 0, allocationSize); return sendLink.send(bytes, encodedSize, DeliveryImpl.DEFAULT_MESSAGE_FORMAT, null) .handle((outcome, sink) -> { final DeliveryState.DeliveryStateType stateType = outcome.getType(); switch (stateType) { case Accepted: sink.complete(); break; default: sink.error(new IllegalArgumentException("Expected a Accepted, received: " + outcome)); logger.warning("Unknown DeliveryState type: {}", stateType); } }); }
Source:
protected Snapshots mapCollection(List<org.ovirt.engine.core.common.businessentities.Snapshot> entities) { Snapshots snapshots = new Snapshots(); for (org.ovirt.engine.core.common.businessentities.Snapshot entity : entities) { Snapshot snapshot = map(entity, null); snapshot = addLinks(snapshot); snapshot = addVmConfiguration(entity, snapshot); snapshot = populate(snapshot, entity); snapshots.getSnapshots().add(snapshot); } return snapshots; }

Target:
protected Snapshots mapCollection(List<org.ovirt.engine.core.common.businessentities.Snapshot> entities) { Snapshots snapshots = new Snapshots(); for (org.ovirt.engine.core.common.businessentities.Snapshot entity : entities) { Snapshot snapshot = map(entity, null); snapshot = populate(snapshot, entity); snapshot = addLinks(snapshot); snapshot = addVmConfiguration(entity, snapshot); snapshots.getSnapshots().add(snapshot); } return snapshots; }
Source:
private void addQueuedDeposits(String queueName, Map<String, Set<String>> depositMap) { Jedis jedis = jedisPool.getResource(); Set<String> queue; try { queue = jedis.zrange(queueName, 0, -1); } catch (Exception e) { LOG.warn("Redis did not return a zset for {}, trying to retrieve as a list", queueName, e); queue = new HashSet<>(jedis.lrange(queueName, 0, -1)); } ObjectMapper mapper = new ObjectMapper(); for (String entry : queue) { try { JsonNode node = mapper.readTree(entry); String depositId = node.get("args").get(1).asText(); Set<String> jobs = depositMap.get(depositId); if (jobs == null) { jobs = new HashSet<>(); depositMap.put(depositId, jobs); } jobs.add(node.get("class").asText()); } catch (IOException e) { LOG.error("Failed to parse deposit job from resque", e); } } }

Target:
private void addQueuedDeposits(String queueName, Map<String, Set<String>> depositMap) { QueueInfo info = queueDAO.getQueueInfo(queueName, 0, 0); for (Job job : info.getJobs()) { String depositId = (String) job.getArgs()[1]; Set<String> jobs = depositMap.get(depositId); if (jobs == null) { jobs = new HashSet<>(); depositMap.put(depositId, jobs); } jobs.add(job.getClassName()); } }
Source:
public void onTagDialog() { try { TagChoiceDialogFragment fragment = new TagChoiceDialogFragment(); fragment.setPreSelectedTags( Keyword.getVisibleKeywords(mMessage.getFlags())); fragment.show(getFragmentManager(), "tag_choice"); } catch (Exception e) { e.printStackTrace(); } }

Target:
public void onTagDialog() { try { TagChoiceDialogFragment fragment = new TagChoiceDialogFragment(); final FlagManager flagManager = FlagManager.getFlagManager(); fragment.setPreSelectedTags( flagManager.getVisibleKeywords(mMessage.getFlags())); fragment.show(getFragmentManager(), "tag_choice"); } catch (Exception e) { Timber.e(e, "Cannot show TagChoiceDialogFragment"); } }