auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() throws InterruptedException { final int numThreads = 8; final int putsPerThread = 2000; final int totalNumberOfObjects = numThreads * putsPerThread; final DataIdFactory<Long> remoteIdFactory = initDataIdFactory(nextRemoteStoreId); final Callable[] threads = new Callable[numThreads]; for (int index = 0; index < numThreads; index++) { threads[index] = new PutThread(putsPerThread, 1, remoteIdFactory); } final Future<Long>[] futures = ThreadUtils.runConcurrentlyWithResult(threads); long numTotalPutSuccess = 0; for (int index = 0; index < numThreads; index++) { try { numTotalPutSuccess += futures[index].get(); } catch (final ExecutionException e) { LOG.log(Level.SEVERE, "Test thread failed", e); } } if (numTotalPutSuccess != totalNumberOfObjects) { throw new RuntimeException(MSG_OPERATION_FAILED); } synchronize(); final int numUnits = memoryStore.getNumUnits(DATA_TYPE); if (numUnits != totalNumberOfObjects) { throw new RuntimeException(MSG_LOCAL_SIZE_ASSERTION); } }

Target:
public void run() { final int numThreads = 8; final int putsPerThread = 2000; final int totalNumberOfObjects = numThreads * putsPerThread; final DataIdFactory<Long> remoteIdFactory = initDataIdFactory(nextRemoteStoreId); final List<Callable<Long>> threads = new ArrayList<>(numThreads); for (int index = 0; index < numThreads; index++) { threads.add(index, new PutThread(putsPerThread, 1, remoteIdFactory)); } final List<Future<Long>> futures = ThreadUtils.runConcurrentlyWithResult(threads); long numTotalPutSuccess = 0; for (int index = 0; index < numThreads; index++) { try { numTotalPutSuccess += futures.get(index).get(); } catch (final ExecutionException | InterruptedException e) { throw new RuntimeException("Test thread failed", e); } } if (numTotalPutSuccess != totalNumberOfObjects) { throw new RuntimeException(MSG_OPERATION_FAILED); } synchronize(); final int numUnits = memoryStore.getNumUnits(DATA_TYPE); if (numUnits != totalNumberOfObjects) { throw new RuntimeException(MSG_LOCAL_SIZE_MISMATCH); } }
Source:
private Table getSysMutexTable() throws SQLException, IOException { String table = SYSTEM_MUTEX_NAME; TableName tableName = TableName.valueOf(table); try (Admin admin = getAdmin()) { if (!admin.tableExists(tableName)) { table = table.replace(QueryConstants.NAME_SEPARATOR, QueryConstants.NAMESPACE_SEPARATOR); tableName = TableName.valueOf(table); } return connection.getTable(tableName); } }

Target:
public Table getSysMutexTable() throws SQLException, IOException { String table = SYSTEM_MUTEX_NAME; TableName tableName = TableName.valueOf(table); try (Admin admin = getAdmin()) { if (!admin.tableExists(tableName)) { table = table.replace(QueryConstants.NAME_SEPARATOR, QueryConstants.NAMESPACE_SEPARATOR); tableName = TableName.valueOf(table); } return connection.getTable(tableName); } }
Source:
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { final int N = appWidgetIds.length; for (int i = 0; i < N; ++i) { Intent serviceIntent = new Intent(context, WidgetService.class); serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]); serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME))); RemoteViews widget = new RemoteViews(context.getPackageName(), R.layout.bookmarks_widget); Intent intent = new Intent(context, QuranDataActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); widget.setOnClickPendingIntent(R.id.WidgetIconButton, pendingIntent); intent = new Intent(context, SearchActivity.class); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); widget.setOnClickPendingIntent(R.id.WidgetBtnSearch, pendingIntent); intent = new Intent(context, PagerActivity.class); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); widget.setOnClickPendingIntent(R.id.WidgetBtnGoToQuran, pendingIntent); widget.setRemoteAdapter(appWidgetIds[i], R.id.listViewWidget, serviceIntent); Intent clickIntent = new Intent(context, PagerActivity.class); PendingIntent clickPI = PendingIntent .getActivity(context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT); widget.setPendingIntentTemplate(R.id.listViewWidget, clickPI); widget.setEmptyView(R.id.listViewWidget, R.id.empty_view); appWidgetManager.updateAppWidget(appWidgetIds[i], widget); } super.onUpdate(context, appWidgetManager, appWidgetIds); }

Target:
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { final int numWidgets = appWidgetIds.length; for (int i = 0; i < numWidgets; ++i) { Intent serviceIntent = new Intent(context, WidgetService.class); serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]); serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME))); RemoteViews widget = new RemoteViews(context.getPackageName(), R.layout.bookmarks_widget); Intent intent = new Intent(context, QuranDataActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); widget.setOnClickPendingIntent(R.id.widget_icon_button, pendingIntent); intent = new Intent(context, SearchActivity.class); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); widget.setOnClickPendingIntent(R.id.widget_btn_search, pendingIntent); intent = new Intent(context, PagerActivity.class); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); widget.setOnClickPendingIntent(R.id.widget_btn_go_to_quran, pendingIntent); widget.setRemoteAdapter(appWidgetIds[i], R.id.list_view_widget, serviceIntent); Intent clickIntent = new Intent(context, PagerActivity.class); PendingIntent clickPendingIntent = PendingIntent .getActivity(context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT); widget.setPendingIntentTemplate(R.id.list_view_widget, clickPendingIntent); widget.setEmptyView(R.id.list_view_widget, R.id.empty_view); appWidgetManager.updateAppWidget(appWidgetIds[i], widget); } super.onUpdate(context, appWidgetManager, appWidgetIds); }
Source:
public boolean applicabilityExistsOnBranchView(BranchId branch, ArtifactId viewId, String applicability) { List<GammaId> tuples = new ArrayList<>(); queryFactory.tupleQuery().getTuple2GammaFromE1E2(CoreTupleTypes.ViewApplicability, branch, viewId, applicability, tuples::add); return (!tuples.isEmpty()); }

Target:
public boolean applicabilityExistsOnBranchView(BranchId branch, ArtifactId viewId, String applicability) { List<GammaId> tuples = new ArrayList<>(); queryFactory.tupleQuery().getTuple2GammaFromE1E2(CoreTupleTypes.ViewApplicability, branch, viewId, applicability, tuples::add); return !tuples.isEmpty(); }
Source:
public CheckNotificationsSupportedTask(ServerConnection connection) { super(null, "Check if smart notifications is available in the SonarQube edition", true); this.connection = connection; }

Target:
public CheckNotificationsSupportedTask(ServerConnection connection) { super(null, "Check if smart notifications are available in the SonarQube edition", true); this.connection = connection; }
Source:
public static void updateMoveAndCopyCommandAvailability(List<DiskImage> disks, UICommand moveCommand, UICommand copyCommand) { boolean isCopyAllowed = true; boolean isMoveAllowed = true; if (moveCommand == null || copyCommand == null) { return; } if (disks == null || disks.isEmpty() || disks.get(0).getDiskStorageType() != DiskStorageType.IMAGE) { disableMoveAndCopyCommands(copyCommand, moveCommand); return; } Guid dataCenterId = disks.get(0).getStoragePoolId(); boolean foundTemplateDisk = false; boolean foundVmDisk = false; boolean foundUnattachedDisk = false; for (DiskImage disk : disks) { boolean isCopyOrMoveAllowed = isCopyAllowed || isMoveAllowed; boolean isImage = disk.getDiskStorageType() == DiskStorageType.IMAGE; boolean isImageStatusOK = disk.getImageStatus() == ImageStatus.OK; boolean isTheSameDataCenter = dataCenterId.equals(disk.getStoragePoolId()); boolean isOvf = disk.isOvfStore(); if (!isCopyOrMoveAllowed || !isImage || !isImageStatusOK || !isTheSameDataCenter || isOvf) { disableMoveAndCopyCommands(moveCommand, copyCommand); return; } VmEntityType vmEntityType = disk.getVmEntityType(); if (vmEntityType == null) { foundUnattachedDisk = true; } else if (vmEntityType.isTemplateType()) { foundTemplateDisk = true; } else if (vmEntityType.isVmType()) { foundVmDisk = true; } if (foundTemplateDisk && (foundUnattachedDisk || foundVmDisk)) { isCopyAllowed = false; } if (vmEntityType != null && vmEntityType.isTemplateType()) { isMoveAllowed = false; } } copyCommand.setIsExecutionAllowed(isCopyAllowed); moveCommand.setIsExecutionAllowed(isMoveAllowed); }

Target:
public static void updateMoveAndCopyCommandAvailability(List<DiskImage> disks, UICommand moveCommand, UICommand copyCommand) { boolean isCopyAllowed = true; boolean isMoveAllowed = true; if (moveCommand == null || copyCommand == null) { return; } if (disks == null || disks.isEmpty() || disks.get(0).getDiskStorageType() != DiskStorageType.IMAGE) { disableMoveAndCopyCommands(moveCommand, copyCommand); return; } Guid dataCenterId = disks.get(0).getStoragePoolId(); boolean foundTemplateDisk = false; boolean foundVmDisk = false; boolean foundUnattachedDisk = false; for (DiskImage disk : disks) { boolean isCopyOrMoveAllowed = isCopyAllowed || isMoveAllowed; boolean isImage = disk.getDiskStorageType() == DiskStorageType.IMAGE; boolean isImageStatusOK = disk.getImageStatus() == ImageStatus.OK; boolean isTheSameDataCenter = dataCenterId.equals(disk.getStoragePoolId()); boolean isOvf = disk.isOvfStore(); if (!isCopyOrMoveAllowed || !isImage || !isImageStatusOK || !isTheSameDataCenter || isOvf) { disableMoveAndCopyCommands(moveCommand, copyCommand); return; } VmEntityType vmEntityType = disk.getVmEntityType(); if (vmEntityType == null) { foundUnattachedDisk = true; } else if (vmEntityType.isTemplateType()) { foundTemplateDisk = true; } else if (vmEntityType.isVmType()) { foundVmDisk = true; } if (foundTemplateDisk && (foundUnattachedDisk || foundVmDisk)) { isCopyAllowed = false; } if (vmEntityType != null && vmEntityType.isTemplateType()) { isMoveAllowed = false; } } copyCommand.setIsExecutionAllowed(isCopyAllowed); moveCommand.setIsExecutionAllowed(isMoveAllowed); }
Source:
public static UserSession createMockUserSession(Person person) { UserSession userSession = mock(UserSession.class); String principleId = person.getPrincipalId(); when(userSession.getPrincipalId()).thenReturn(principleId); String principleName = person.getPrincipalName(); when(userSession.getPrincipalName()).thenReturn(principleName); when(userSession.getLoggedInUserPrincipalName()).thenReturn(principleName); when(userSession.getPerson()).thenReturn(person); when(userSession.getActualPerson()).thenReturn(person); return userSession; }

Target:
public static UserSession createMockUserSession(Person person) { UserSession userSession = mock(UserSession.class); String principalId = person.getPrincipalId(); when(userSession.getPrincipalId()).thenReturn(principalId); String principalName = person.getPrincipalName(); when(userSession.getPrincipalName()).thenReturn(principalName); when(userSession.getLoggedInUserPrincipalName()).thenReturn(principalName); when(userSession.getPerson()).thenReturn(person); when(userSession.getActualPerson()).thenReturn(person); return userSession; }
Source:
public Result authenticate(Request request, ContentResponse response, HeaderInfo headerInfo, Attributes attributes) { URI requestUri = request.getURI(); String servicePrincipal = makeServicePrincipal(remoteServiceName, requestUri.getHost()); GSSContext context = doAs(loginContext.getSubject(), () -> { GSSContext result = GSS_MANAGER.createContext( GSS_MANAGER.createName(servicePrincipal, null), SPNEGO_OID, clientCredential, GSSContext.INDEFINITE_LIFETIME); result.requestMutualAuth(true); result.requestConf(true); result.requestInteg(true); result.requestCredDeleg(false); return result; }); try { byte[] token = context.initSecContext(new byte[0], 0, 0); if (token != null) { return new SpnegoResult( headerInfo.getHeader(), UriUtil.normalizedUri(requestUri), format("%s %s", NEGOTIATE, Base64.getEncoder().encodeToString(token))); } } catch (GSSException e) { } finally { try { context.dispose(); } catch (GSSException e) { } } throw new AuthenticationException(format("Failed to establish GSSContext for request %s", requestUri)); }

Target:
public Result authenticate(Request request, ContentResponse response, HeaderInfo headerInfo, Attributes attributes) { URI requestUri = request.getURI(); String servicePrincipal = makeServicePrincipal(remoteServiceName, requestUri.getHost()); GSSContext context = doAs(loginContext.getSubject(), () -> { GSSContext result = GSS_MANAGER.createContext( GSS_MANAGER.createName(servicePrincipal, null), SPNEGO_OID, clientCredential, INDEFINITE_LIFETIME); result.requestMutualAuth(true); result.requestConf(true); result.requestInteg(true); result.requestCredDeleg(false); return result; }); try { byte[] token = context.initSecContext(new byte[0], 0, 0); if (token != null) { return new SpnegoResult( UriUtil.normalizedUri(requestUri), headerInfo.getHeader(), format("%s %s", NEGOTIATE, Base64.getEncoder().encodeToString(token))); } } catch (GSSException e) { } finally { try { context.dispose(); } catch (GSSException e) { } } throw new AuthenticationException(format("Failed to establish GSSContext for request %s", requestUri)); }
Source:
public void addItem(String itemName, String property) { logger.debug("Mapping: itemname=" + itemName + " & property = " + property); if (!watches.containsKey(itemName)) { watches.put(itemName, property); } }

Target:
public void addItem(String itemName, String property) { logger.debug("Mapping: itemname = & property = {}", itemName, property); if (!watches.containsKey(itemName)) { watches.put(itemName, property); } }
Source:
public void onPlayerActive(CallbackInfo ci) { ((IMixinNetHandlerPlayServer) this.connection).resendLatestResourcePackRequest(); }

Target:
private void onPlayerActive(CallbackInfo ci) { ((IMixinNetHandlerPlayServer) this.connection).resendLatestResourcePackRequest(); }
Source:
public FileFavoritesCtrl(ProjectState projectState, FileNavigationState navState){ this.navState = navState; projectState.configProperty().addListener((p, o, n) -> { if (n == null) return; Path path = Paths.get(n.getProjectPath()); this.navState.getFavoriteFolders().add(new LocalFile(path)); this.navState.getFavoriteFolders().add(new LocalFile(path.resolve(Paths.get("schemas")))); this.navState.setSelectedParent(this.navState.getFavoriteFolders().get(0)); }); this.navState.selectedParentProperty().addListener((p, o, n) -> { if (n == null || n.equals(fileFavorites.getSelectionModel().getSelectedItem())) return; fileFavorites.getSelectionModel().clearSelection(); }); }

Target:
public FileFavoritesCtrl(ProjectState projectState, FileNavigationState navState){ this.navState = navState; projectState.configProperty().addListener((p, o, n) -> { if (n == null) return; Path path = Paths.get(n.getProjectPath()); this.navState.getFavoriteFolders().add(new LocalFile(path)); this.navState.getFavoriteFolders().add(new LocalFile(path.resolve(Paths.get("schemas")))); this.navState.setSelectedParent(this.navState.getFavoriteFolders().get(0)); }); }
Source:
public void testGetAllForHost() { List<NetworkAttachment> result = dao.getAllForHost(FixturesTool.NETWORK_ATTACHMENT_HOST); assertNotNull(result); assertEquals(2, result.size()); result.forEach(r -> assertNull(r.getHostNetworkQos())); result.forEach(r-> { HostNetworkQos hostNetworkQos = new HostNetworkQos(); hostNetworkQos.setId(r.getId()); hostNetworkQosDao.save(hostNetworkQos); }); result = dao.getAllForHost(FixturesTool.NETWORK_ATTACHMENT_HOST); assertNotNull(result); assertEquals(2, result.size()); result.forEach(r -> { assertNotNull(r.getHostNetworkQos()); assertEquals(r.getId(), r.getHostNetworkQos().getId()); assertNull(r.getHostNetworkQos().getOutAverageLinkshare()); assertNull(r.getHostNetworkQos().getOutAverageRealtime()); assertNull(r.getHostNetworkQos().getOutAverageUpperlimit()); }); }

Target:
public void testGetAllForHost() { List<NetworkAttachment> result = dao.getAllForHost(FixturesTool.NETWORK_ATTACHMENT_HOST); assertNotNull(result); assertEquals(2, result.size()); result.forEach(r -> assertNull(r.getHostNetworkQos())); result.forEach(r-> { HostNetworkQos hostNetworkQos = new HostNetworkQos(); hostNetworkQos.setId(r.getId()); hostNetworkQos.setOutAverageLinkshare(31); hostNetworkQos.setOutAverageUpperlimit(32); hostNetworkQos.setOutAverageRealtime(33); hostNetworkQosDao.save(hostNetworkQos); }); result = dao.getAllForHost(FixturesTool.NETWORK_ATTACHMENT_HOST); assertNotNull(result); assertEquals(2, result.size()); result.forEach(r -> { assertNotNull(r.getHostNetworkQos()); assertEquals(r.getId(), r.getHostNetworkQos().getId()); assertEquals(31, r.getHostNetworkQos().getOutAverageLinkshare().intValue()); assertEquals(32, r.getHostNetworkQos().getOutAverageUpperlimit().intValue()); assertEquals(33, r.getHostNetworkQos().getOutAverageRealtime().intValue()); }); }
Source:
public List<RichMember> getSponsoredMembers(PerunSession sess, Vo vo, User user, List<String> attrNames) throws InternalErrorException, AttributeNotExistsException, PrivilegeException, VoNotExistsException, UserNotExistsException { Utils.checkPerunSession(sess); perunBl.getVosManagerBl().checkVoExists(sess, vo); perunBl.getUsersManagerBl().checkUserExists(sess, user); if (!(AuthzResolver.isAuthorized(sess, Role.REGISTRAR)||AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo))) { throw new PrivilegeException(sess, "getSponsoredRichMembers"); } List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); for (String attrName : attrNames) { attributeDefinitions.add(getPerunBl().getAttributesManagerBl().getAttributeDefinition(sess, attrName)); } List<RichMember> richMembers = membersManagerBl.convertMembersToRichMembers(sess, membersManagerBl.getSponsoredMembers(sess, vo, user)); richMembers = membersManagerBl.convertMembersToRichMembersWithAttributes(sess, richMembers, attributeDefinitions); richMembers = membersManagerBl.filterOnlyAllowedAttributes(sess, richMembers); return richMembers; }

Target:
public List<RichMember> getSponsoredMembers(PerunSession sess, Vo vo, User user, List<String> attrNames) throws InternalErrorException, AttributeNotExistsException, PrivilegeException, VoNotExistsException, UserNotExistsException { Utils.checkPerunSession(sess); perunBl.getVosManagerBl().checkVoExists(sess, vo); perunBl.getUsersManagerBl().checkUserExists(sess, user); if (!(AuthzResolver.isAuthorized(sess, Role.REGISTRAR)||AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo))) { throw new PrivilegeException(sess, "getSponsoredMembers"); } List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); for (String attrName : attrNames) { attributeDefinitions.add(getPerunBl().getAttributesManagerBl().getAttributeDefinition(sess, attrName)); } List<RichMember> richMembers = membersManagerBl.convertMembersToRichMembers(sess, membersManagerBl.getSponsoredMembers(sess, vo, user)); richMembers = membersManagerBl.convertMembersToRichMembersWithAttributes(sess, richMembers, attributeDefinitions); richMembers = membersManagerBl.filterOnlyAllowedAttributes(sess, richMembers, null, true); return richMembers; }
Source:
private void createNotificationChannel() { NotificationChannel serviceChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID, "Telescope Service Channel", NotificationManager.IMPORTANCE_DEFAULT ); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(serviceChannel); }

Target:
private void createNotificationChannel() { NotificationChannel serviceChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID, "Telescope", NotificationManager.IMPORTANCE_MIN ); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(serviceChannel); }
Source:
public static NamedVector of(Map<String, Double> values) { SparseVector vector = new SparseVector(values.size(), StorageConstants.RANDOM_ACCESS_MODE); for (int i = 0; i < values.size(); i++) vector.set(i, Double.NaN); Map<String, Integer> dict = new HashMap<>(); int idx = 0; for (Map.Entry<String, Double> e : values.entrySet()) { dict.put(e.getKey(), idx); vector.set(idx, e.getValue()); idx++; } return new DelegatingNamedVector(vector, dict); }

Target:
public static SimpleNamedVector of(Map<String, Double> values) { Map<String, Integer> dict = new HashMap<>(); int idx = 0; for (Map.Entry<String, Double> e : values.entrySet()) { dict.put(e.getKey(), idx); idx++; } SimpleNamedVector vector = new SimpleNamedVector(dict); for (Map.Entry<String, Double> e : values.entrySet()) vector.set(e.getKey(), e.getValue()); return vector; }
Source:
public void addFileToPackage(TarArchiveOutputStream tarArchiveOutputStream, File file, String path) throws IOException { CompressionUtils.addFileToTar(tarArchiveOutputStream, file, getLibPath() + path); }

Target:
public void addFileToPackage(TarArchiveOutputStream tarArchiveOutputStream, File file, String path) throws IOException { addFileToTar(tarArchiveOutputStream, file, getLibPath() + path); }
Source:
void setupToC(@NonNull Page page, @NonNull WikiSite wiki, boolean firstPage) { adapter.setPage(page); rtl = L10nUtil.isLangRTL(wiki.languageCode()); showOnboading = Prefs.isTocTutorialEnabled() && !page.isMainPage() && !firstPage && !Prefs.showActionFeedIndicator(); tocList.setRtl(rtl); setConditionalLayoutDirection(tocContainer, wiki.languageCode()); FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)tocContainer.getLayoutParams(); params.gravity = rtl ? Gravity.START : Gravity.END; tocContainer.setLayoutParams(params); funnel = new ToCInteractionFunnel(WikipediaApp.getInstance(), wiki, page.getPageProperties().getPageId(), adapter.getCount()); }

Target:
void setupToC(@NonNull Page page, @NonNull WikiSite wiki, boolean firstPage) { adapter.setPage(page); rtl = L10nUtil.isLangRTL(wiki.languageCode()); showOnboading = Prefs.isTocTutorialEnabled() && !page.isMainPage() && !firstPage && !Prefs.showActionFeedIndicator(); tocList.setRtl(rtl); setConditionalLayoutDirection(tocContainer, wiki.languageCode()); FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)tocContainer.getLayoutParams(); params.gravity = rtl ? Gravity.LEFT : Gravity.RIGHT; tocContainer.setLayoutParams(params); funnel = new ToCInteractionFunnel(WikipediaApp.getInstance(), wiki, page.getPageProperties().getPageId(), adapter.getCount()); }
Source:
public void testGetBuildsSummary() throws Exception { TestBuildsView view = Mockito.spy(new TestBuildsView()); when(view.getContentProvider()).thenReturn(new BuildContentProvider()); when(view.getModel()).thenReturn(BuildsUiInternal.getModel()); assertTrue(view.getBuildsSummary().isEmpty()); assertBuildSummary(view.getBuildsSummary(), false, false, false); view.getModel().getPlans().add(createBuildPlan(BuildStatus.SUCCESS)); view.getModel().getPlans().add(createBuildPlan(BuildStatus.SUCCESS)); view.getModel().getPlans().add(createBuildPlan(BuildStatus.SUCCESS)); assertBuildSummary(view.getBuildsSummary(), true, false, false); view.getModel().getPlans().add(createBuildPlan(BuildStatus.UNSTABLE)); view.getModel().getPlans().add(createBuildPlan(BuildStatus.UNSTABLE)); assertBuildSummary(view.getBuildsSummary(), false, true, false); view.getModel().getPlans().add(createBuildPlan(BuildStatus.FAILED)); assertBuildSummary(view.getBuildsSummary(), false, false, true); assertFalse(view.getBuildsSummary().isEmpty()); assertEquals("3 Succeeded, 2 Unstable, 1 Failed", view.getBuildsSummary().toString()); }

Target:
public void testGetBuildsSummary() throws Exception { TestBuildsView view = Mockito.spy(new TestBuildsView()); when(view.getContentProvider()).thenReturn(new BuildContentProvider()); when(view.getModel()).thenReturn(BuildsUiInternal.getModel()); assertBuildSummary(view.getBuildsSummary(), false, false, false); assertTrue(view.getBuildsSummary().isEmpty()); view.getModel().getPlans().add(createBuildPlan(BuildStatus.SUCCESS)); view.getModel().getPlans().add(createBuildPlan(BuildStatus.SUCCESS)); view.getModel().getPlans().add(createBuildPlan(BuildStatus.SUCCESS)); assertBuildSummary(view.getBuildsSummary(), true, false, false); view.getModel().getPlans().add(createBuildPlan(BuildStatus.UNSTABLE)); view.getModel().getPlans().add(createBuildPlan(BuildStatus.UNSTABLE)); assertBuildSummary(view.getBuildsSummary(), false, true, false); view.getModel().getPlans().add(createBuildPlan(BuildStatus.FAILED)); assertBuildSummary(view.getBuildsSummary(), false, false, true); assertFalse(view.getBuildsSummary().isEmpty()); assertEquals("3 Succeeded, 2 Unstable, 1 Failed", view.getBuildsSummary().toString()); }
Source:
public Text toText() { Text.Builder builder = null; for (Object element : this.elements) { if (element instanceof TextElement) { if (builder == null) { builder = Text.builder(); } ((TextElement) element).applyTo(builder); } else { String str = element.toString(); if (builder == null) { builder = Text.builder(str); } else { builder.append(Text.of(str)); } } } return Optional.ofNullable(builder).orElse(Text.builder()).build(); }

Target:
public Text toText() { return this.text; }
Source:
public Set<GPUInfo> retrieveResourceInfo(long gpuAmount) throws Exception { if (gpuAmount <= 0) { throw new FlinkException("The amount of GPU should be positive."); } final Set<GPUInfo> gpuResources = new HashSet<>(); String output = executeDiscoveryScript(discoveryScript, gpuAmount, args); if (output != null && !output.isEmpty()) { String[] indexes = output.split(","); for (String index : indexes) { gpuResources.add(new GPUInfo(index)); } } LOG.info("Discover the GPU resource {}.", gpuResources); return Collections.unmodifiableSet(gpuResources); }

Target:
public Set<GPUInfo> retrieveResourceInfo(long gpuAmount) throws Exception { Preconditions.checkArgument(gpuAmount > 0, "The gpuAmount should be positive when retrieving the GPU resource information."); final Set<GPUInfo> gpuResources = new HashSet<>(); String output = executeDiscoveryScript(discoveryScriptFile, gpuAmount, args); if (!output.isEmpty()) { String[] indexes = output.split(","); for (String index : indexes) { if (!StringUtils.isNullOrWhitespaceOnly(index)) { gpuResources.add(new GPUInfo(index.trim())); } } } LOG.info("Discover GPU resources: {}.", gpuResources); return Collections.unmodifiableSet(gpuResources); }
Source:
public void emptyRefreshResponse() { setTimeDynamic(NanoTime::now); LockToken t1 = LockToken.of(UUID.randomUUID()); LockToken t2 = LockToken.of(UUID.randomUUID()); Leased<Set<LockToken>> refreshResult = heldLocksCollection.refresh(ImmutableSet.of(t1, t2)); assertThat(refreshResult.value()).isEmpty(); assertThat(refreshResult.lease().leaderTime().currentTime()).isLessThan(NanoTime.now()); }

Target:
public void emptyRefreshResponse() { LockToken t1 = LockToken.of(UUID.randomUUID()); LockToken t2 = LockToken.of(UUID.randomUUID()); Leased<Set<LockToken>> refreshResult = heldLocksCollection.refresh(ImmutableSet.of(t1, t2)); assertThat(refreshResult.value()).isEmpty(); assertThat(refreshResult.lease().leaderTime().currentTime()).isLessThanOrEqualTo(time.get()); }
Source:
String handleResponse(final HttpRequestBase requestBase, final CloseableHttpResponse response) throws IOException { String result = StringUtils.EMPTY; final HttpEntity entity = response.getEntity(); if (null != entity) { result = EntityUtils.toString(entity); if (response.getStatusLine().getStatusCode() >= 400) { PageObjectLogging.logInfo("Error response:", response.toString()); throw new RemoteException("Error while invoking request. " + " Method: " + requestBase.getMethod() + " Url: " + requestBase.getURI().toString() + " Response: " + result); } } return result; }

Target:
String handleResponse(final HttpRequestBase requestBase, final CloseableHttpResponse response) throws IOException { String result = StringUtils.EMPTY; final HttpEntity entity = response.getEntity(); if (null != entity) { result = EntityUtils.toString(entity); if (response.getStatusLine().getStatusCode() >= 400) { PageObjectLogging.logInfo("Error response:", result); throw new RemoteException("Error while invoking request. " + " Method: " + requestBase.getMethod() + " Url: " + requestBase.getURI().toString() + " Response: " + result); } } return result; }
Source:
public static Cipher getCipher(String cipherSuite, String securityProvider) { Cipher cipher = null; if (cipherSuite.equals("NullCipher")) { cipher = new NullCipher(); } else { try { cipher = Cipher.getInstance(cipherSuite, securityProvider); } catch (NoSuchAlgorithmException e) { log.error(String.format("Accumulo configuration file contained a cipher suite \"%s\" that was not recognized by any providers", cipherSuite)); throw new RuntimeException(e); } catch (NoSuchPaddingException e) { log.error(String.format("Accumulo configuration file contained a cipher, \"%s\" with a padding that was not recognized by any providers", cipherSuite)); throw new RuntimeException(e); } catch (NoSuchProviderException e) { log.error(String.format("Accumulo configuration file contained a provider, \"%s\" an unrecognized provider", securityProvider)); throw new RuntimeException(e); } } return cipher; }

Target:
public static Cipher getCipher(String cipherSuite, String securityProvider) { Cipher cipher = null; if (cipherSuite.equals("NullCipher")) { cipher = new NullCipher(); } else { try { if (securityProvider == null || securityProvider.equals("")) { cipher = Cipher.getInstance(cipherSuite); } else { cipher = Cipher.getInstance(cipherSuite, securityProvider); } } catch (NoSuchAlgorithmException e) { log.error(String.format("Accumulo configuration file contained a cipher suite \"%s\" that was not recognized by any providers", cipherSuite)); throw new RuntimeException(e); } catch (NoSuchPaddingException e) { log.error(String.format("Accumulo configuration file contained a cipher, \"%s\" with a padding that was not recognized by any providers", cipherSuite)); throw new RuntimeException(e); } catch (NoSuchProviderException e) { log.error(String.format("Accumulo configuration file contained a provider, \"%s\" an unrecognized provider", securityProvider)); throw new RuntimeException(e); } } return cipher; }
Source:
public static void setup() throws Exception { Map<String, String> serverProps = Maps.newHashMapWithExpectedSize(2); serverProps.put(QueryServices.STATS_GUIDEPOST_WIDTH_BYTES_ATTRIB, Long.toString(20)); serverProps.put(QueryServices.MAX_SERVER_METADATA_CACHE_TIME_TO_LIVE_MS_ATTRIB, Long.toString(5)); serverProps.put(QueryServices.EXTRA_JDBC_ARGUMENTS_ATTRIB, QueryServicesOptions.DEFAULT_EXTRA_JDBC_ARGUMENTS); Map<String, String> clientProps = Maps.newHashMapWithExpectedSize(2); clientProps.put(QueryServices.USE_STATS_FOR_PARALLELIZATION, Boolean.toString(true)); clientProps.put(QueryServices.STATS_UPDATE_FREQ_MS_ATTRIB, Long.toString(5)); clientProps.put(QueryServices.TRANSACTIONS_ENABLED, Boolean.TRUE.toString()); clientProps.put(QueryServices.FORCE_ROW_KEY_ORDER_ATTRIB, Boolean.TRUE.toString()); setUpTestDriver(new ReadOnlyProps(serverProps.entrySet().iterator()), new ReadOnlyProps(clientProps.entrySet().iterator())); }

Target:
public static void setup() throws Exception { IndexToolIT.setup(); }
Source:
public TogglzFeature setFeatureState(@Selector String featureName, boolean enabled) { final Feature feature = featureProvider.getFeatures().stream() .filter(f -> f.name().equals(featureName)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Could not find feature with name " + featureName)); FeatureState featureState = featureManager.getFeatureState(feature); if (featureState.isEnabled() != enabled) { featureState.setEnabled(enabled); featureManager.setFeatureState(featureState); return new TogglzFeature(feature, featureState); } return null; }

Target:
public TogglzFeature setFeatureState(@Selector String featureName, boolean enabled) { final Feature feature = featureManager.getFeatures().stream() .filter(f -> f.name().equals(featureName)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Could not find feature with name " + featureName)); FeatureState featureState = featureManager.getFeatureState(feature); featureState.setEnabled(enabled); featureManager.setFeatureState(featureState); return new TogglzFeature(feature, featureState); }
Source:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((fField == null) ? 0 : fField.hashCode()); result = prime * result + (fNot ? 1231 : 1237); result = prime * result + fResult; result = prime * result + ((fType == null) ? 0 : fType.hashCode()); result = prime * result + ((fValue == null) ? 0 : fValue.hashCode()); result = prime * result + ((fValueNumber == null) ? 0 : fValueNumber.hashCode()); result = prime * result + ((fValueTimestamp == null) ? 0 : fValueTimestamp.hashCode()); return result; }

Target:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((fField == null) ? 0 : fField.hashCode()); result = prime * result + (fNot ? 1231 : 1237); result = prime * result + fResult; result = prime * result + ((fType == null) ? 0 : fType.hashCode()); result = prime * result + ((fValue == null) ? 0 : fValue.hashCode()); return result; }
Source:
public UserGroup(UserClock clock, int id, ProcessingConfig.Test.Task.User config, long time) { this(clock, id, Parser.parseInt(config.getCount(), clock.getRandom()), (int) config.getStartCount(), time + Parser.parseTime(config.getStartIn(), clock.getRandom()), Parser.parseTime(config.getStartBy(), clock.getRandom()), Parser.parseTime(config.getLife(), clock.getRandom()) ); double floor = (Double.compare(config.getStartCount(), 1.0) < 0) ? +0.0 : +Math.floor(config.getStartCount()); double slewRate = config.getStartCount() - floor; this.slewRate = slewRate; this.extraUser = slewRate; }

Target:
public UserGroup(UserClock clock, int id, ProcessingConfig.Test.Task.User config, long time) { this(clock, id, Parser.parseInt(config.getCount(), clock.getRandom()), (int) config.getStartCount(), time + Parser.parseTime(config.getStartIn(), clock.getRandom()), Parser.parseTime(config.getStartBy(), clock.getRandom()), Parser.parseTime(config.getLife(), clock.getRandom()) ); double floor = (Double.compare(config.getStartCount(), 1.0) < 0) ? +0.0 : +Math.floor(config.getStartCount()); double extraUserStep = config.getStartCount() - floor; this.extraUserStep = extraUserStep; this.extraUser = extraUserStep; }
Source:
private void clearMetadata(Entry entry) { entry.setAuthor(null); entry.setEmail(null); entry.setDescription(null); }

Target:
private void clearMetadata(Entry entry) { entry.setAuthor(null); entry.setEmail(null); entry.setDescription(WDL_SYNTAX_ERROR); }
Source:
public MemberInfo apply(GroupResource resource, Input input) throws AuthException, BadRequestException, ResourceConflictException, Exception { final GroupDescription.Basic group = resource.getGroup(); if (!(group instanceof GroupDescription.Internal)) { throw new MethodNotAllowedException(); } final Account a = findAccount(input.nameOrEmail); if (!a.isActive()) { throw new InactiveAccountException(a.getFullName()); } final AccountGroup internalGroup = ((GroupDescription.Internal) group).getAccountGroup(); final GroupControl control = groupControlFactory.controlFor(internalGroup); if (!control.canAddMember(a.getId())) { throw new AuthException("Cannot add member: " + a.getFullName()); } final AccountGroupMember.Key key = new AccountGroupMember.Key(a.getId(), internalGroup.getId()); AccountGroupMember m = db.accountGroupMembers().get(key); if (m == null) { m = new AccountGroupMember(key); db.accountGroupMembersAudit().insert( Collections.singleton(new AccountGroupMemberAudit(m, m.getAccountId()))); db.accountGroupMembers().insert(Collections.singleton(m)); accountCache.evict(m.getAccountId()); } return MembersCollection.parse(a); }

Target:
public List<MemberInfo> apply(GroupResource resource, Input input) throws AuthException, BadRequestException, ResourceConflictException, Exception { final GroupDescription.Basic group = resource.getGroup(); if (!(group instanceof GroupDescription.Internal)) { throw new MethodNotAllowedException(); } final List<AccountGroupMember> newAccountGroupMembers = Lists.newLinkedList(); final List<AccountGroupMemberAudit> newAccountGroupMemberAudits = Lists.newLinkedList(); final List<String> errors = Lists.newLinkedList(); final List<MemberInfo> newMembers = Lists.newLinkedList(); final Account.Id me = ((IdentifiedUser) self.get()).getAccountId(); for (final String nameOrEmail : input.members) { final Account a; try { a = findAccount(nameOrEmail); } catch (NoSuchAccountException e) { errors.add(e.getMessage()); continue; } if (!a.isActive()) { errors.add((new InactiveAccountException(a.getFullName())).getMessage()); continue; } final AccountGroup internalGroup = ((GroupDescription.Internal) group).getAccountGroup(); final GroupControl control = groupControlFactory.controlFor(internalGroup); if (!control.canAddMember(a.getId())) { throw new AuthException("Cannot add member: " + a.getFullName()); } final AccountGroupMember.Key key = new AccountGroupMember.Key(a.getId(), internalGroup.getId()); AccountGroupMember m = db.accountGroupMembers().get(key); if (m == null) { m = new AccountGroupMember(key); newAccountGroupMembers.add(m); newAccountGroupMemberAudits.add(new AccountGroupMemberAudit(m, me)); } newMembers.add(MembersCollection.parse(a)); } failWithBadRequestOnError(errors); db.accountGroupMembersAudit().insert(newAccountGroupMemberAudits); db.accountGroupMembers().insert(newAccountGroupMembers); for (final AccountGroupMember m : newAccountGroupMembers) { accountCache.evict(m.getAccountId()); } return newMembers; }
Source:
private void changeUserStatus( final String userId, final UserStatusEnum newUserStatus, final AsyncCallback<Void> responder ) { synchronized( currentUserLock ) { Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "changeUserStatus", new Object[] { userId, newUserStatus }, new AsyncCallback<Void>() { @Override public void handleResponse( Void response ) { if( currentUser != null && !currentUser.isEmpty() && currentUser.getObjectId().equals( userId ) ) currentUser.setProperty( USER_STATUS_COLUMN, newUserStatus.toString() ); if( responder != null ) responder.handleResponse( response ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } } ); } }

Target:
private void changeUserStatus( final String userId, final UserStatusEnum newUserStatus, final AsyncCallback<Void> responder ) { Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "changeUserStatus", new Object[] { userId, newUserStatus }, new AsyncCallback<Void>() { @Override public void handleResponse( Void response ) { if( currentUser != null && !currentUser.isEmpty() && currentUser.getObjectId().equals( userId ) ) currentUser.setProperty( USER_STATUS_COLUMN, newUserStatus.toString() ); if( responder != null ) responder.handleResponse( response ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } } ); }
Source:
static void replyError(HttpServletResponse res, int statusCode, String msg) throws IOException { res.setStatus(statusCode); CacheHeaders.setNotCacheable(res); replyText(null, res, msg); }

Target:
public static void replyError(HttpServletResponse res, int statusCode, String msg) throws IOException { res.setStatus(statusCode); CacheHeaders.setNotCacheable(res); replyText(null, res, msg); }
Source:
public void resolveArgumentSecurityContextErrorOnInvalidTypeTrue() throws Exception { String principal = "invalid_type_true"; setAuthenticationPrincipal(principal); try { resolver.resolveArgument(showSecurityContextErrorOnInvalidTypeTrue(), null, null, null); fail("should not reach here"); } catch(ClassCastException ex) }

Target:
public void resolveArgumentSecurityContextErrorOnInvalidTypeTrue() throws Exception { String principal = "invalid_type_true"; setAuthenticationPrincipal(principal); assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> resolver.resolveArgument(showSecurityContextErrorOnInvalidTypeTrue(), null, null, null)); }
Source:
private void addChildren(ITmfStateSystem ss, Builder<@NonNull TimeGraphEntryModel> builder, int quark, long parentId, List<Integer> logsQuarks) { for (Integer child : ss.getSubAttributes(quark, false)) { long childId = getId(child); String childName = ss.getAttributeName(child); if (!childName.equals(IOpenTracingConstants.LOGS)) { List<LogEvent> logs = new ArrayList<>(); int logQuark = getLogQuark(ss, childName, logsQuarks); long startTime = ss.getStartTime(); try { for (ITmfStateInterval interval : ss.query2D(Collections.singletonList(child), ss.getStartTime(), ss.getCurrentEndTime())) { if (!interval.getStateValue().isNull()) { startTime = interval.getStartTime(); break; } } for (ITmfStateInterval interval : ss.query2D(Collections.singletonList(logQuark), ss.getStartTime(), ss.getCurrentEndTime())) { if (!interval.getStateValue().isNull()) { logs.add(new LogEvent(interval.getStartTime(), String.valueOf(interval.getValue()))); } } } catch (IndexOutOfBoundsException | TimeRangeException | StateSystemDisposedException e) { } builder.add(new SpanLifeEntryModel(childId, parentId, getSpanName(childName), startTime, ss.getCurrentEndTime(), logs, getErrorTag(childName))); addChildren(ss, builder, child, childId, logsQuarks); } } }

Target:
private void addChildren(ITmfStateSystem ss, Builder<@NonNull TimeGraphEntryModel> builder, int quark, long parentId, List<Integer> logsQuarks) { for (Integer child : ss.getSubAttributes(quark, false)) { long childId = getId(child); String childName = ss.getAttributeName(child); if (!childName.equals(IOpenTracingConstants.LOGS)) { List<LogEvent> logs = new ArrayList<>(); int logQuark = getLogQuark(ss, childName, logsQuarks); try { for (ITmfStateInterval interval : ss.query2D(Collections.singletonList(logQuark), ss.getStartTime(), ss.getCurrentEndTime())) { if (!interval.getStateValue().isNull()) { logs.add(new LogEvent(interval.getStartTime(), String.valueOf(interval.getValue()))); } } } catch (IndexOutOfBoundsException | TimeRangeException | StateSystemDisposedException e) { } builder.add(new SpanLifeEntryModel(childId, parentId, getSpanName(childName), ss.getStartTime(), ss.getCurrentEndTime(), logs, getErrorTag(childName))); addChildren(ss, builder, child, childId, logsQuarks); } } }
Source:
private FTPClient createClient() throws FileSystemException { final GenericFileName rootName = getRoot(); Map<String,String>mParams = null; if(rootName instanceof URLFileName){ mParams = getQueryParams((URLFileName)rootName); } UserAuthenticationData authData = null; try { authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, FtpFileProvider.AUTHENTICATOR_TYPES); if (mParams == null) { return FtpClientFactory.createConnection(rootName.getHostName(), rootName.getPort(), UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())), UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())), rootName.getPath(), getFileSystemOptions(), defaultTimeout); } else { return FtpClientFactory.createConnection(rootName.getHostName(), rootName.getPort(), UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())), UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())), rootName.getPath(), getFileSystemOptions(), mParams.get(SftpConstants.PROXY_SERVER), mParams.get(SftpConstants.PROXY_PORT), mParams.get(SftpConstants.PROXY_USERNAME), mParams.get(SftpConstants.PROXY_PASSWORD), mParams.get(SftpConstants.TIMEOUT), mParams.get(SftpConstants.RETRY_COUNT), defaultTimeout); } } finally { UserAuthenticatorUtils.cleanup(authData); } }

Target:
private FTPClient createClient() throws FileSystemException { final GenericFileName rootName = getRoot(); Map<String,String>mParams = null; if(rootName instanceof URLFileName){ mParams = getQueryParams((URLFileName)rootName); } UserAuthenticationData authData = null; try { authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, FtpFileProvider.AUTHENTICATOR_TYPES); char[] username = UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())); char[] password = UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())); if (mParams == null) { return FtpClientFactory.createConnection(rootName.getHostName(), rootName.getPort(), username, password, rootName.getPath(), getFileSystemOptions(), defaultTimeout); } else { return FtpClientFactory.createConnection(rootName.getHostName(), rootName.getPort(), username, password, rootName.getPath(), getFileSystemOptions(), mParams.get(SftpConstants.PROXY_SERVER), mParams.get(SftpConstants.PROXY_PORT), mParams.get(SftpConstants.PROXY_USERNAME), mParams.get(SftpConstants.PROXY_PASSWORD), mParams.get(SftpConstants.TIMEOUT), mParams.get(SftpConstants.RETRY_COUNT), defaultTimeout); } } finally { UserAuthenticatorUtils.cleanup(authData); } }
Source:
public void updateField(Pool pool, double value, String units) { throw new UnsupportedOperationException("Method not implemented for unspecified field"); }

Target:
public void updateField(Pool pool, double value, String units) { pool.setConcentration(value); pool.setConcentrationUnits(units); }
Source:
public void storeSettings() { PreviewPreferences previewPreferences = Globals.prefs.getPreviewPreferences(); if (chosenListProperty.isEmpty()) { chosenListProperty.add(previewPreferences.getTextBasedPreviewLayout()); } PreviewPreferences newPreviewPreferences = Globals.prefs.getPreviewPreferences() .getBuilder() .withPreviewCycle(chosenListProperty) .withPreviewStyle(previewTextProperty.getValue().replace("\n", "__NEWLINE__")) .build(); if (!selectedChosenItemsProperty.getValue().isEmpty()) { newPreviewPreferences = newPreviewPreferences.getBuilder().withPreviewCyclePosition(chosenListProperty.getValue().indexOf(selectedChosenItemsProperty.get(0))).build(); } Globals.prefs.storePreviewPreferences(newPreviewPreferences); for (BasePanel basePanel : JabRefGUI.getMainFrame().getBasePanelList()) { basePanel.closeBottomPane(); } }

Target:
public void storeSettings() { PreviewPreferences previewPreferences = preferences.getPreviewPreferences(); if (chosenListProperty.isEmpty()) { chosenListProperty.add(previewPreferences.getTextBasedPreviewLayout()); } PreviewLayout previewStyle = findLayoutByName("Preview"); if (previewStyle == null) { previewStyle = previewPreferences.getTextBasedPreviewLayout(); } PreviewPreferences newPreviewPreferences = preferences.getPreviewPreferences() .getBuilder() .withPreviewCycle(chosenListProperty) .withPreviewStyle(((TextBasedPreviewLayout) previewStyle).getText()) .build(); if (!chosenSelectionModelProperty.getValue().getSelectedItems().isEmpty()) { newPreviewPreferences = newPreviewPreferences.getBuilder().withPreviewCyclePosition( chosenListProperty.getValue().indexOf( chosenSelectionModelProperty.getValue().getSelectedItems().get(0))).build(); } preferences.storePreviewPreferences(newPreviewPreferences); for (BasePanel basePanel : JabRefGUI.getMainFrame().getBasePanelList()) { basePanel.closeBottomPane(); } }
Source:
double calculateDistance(final Target fromTarget, final Target toTarget) { final SimpleInterval fromInterval = fromTarget.getInterval(); final SimpleInterval toInterval = toTarget.getInterval(); if (fromInterval == null || toInterval == null) { return 0.0; } else if (!fromInterval.getContig().equals(toInterval.getContig())) { return Double.POSITIVE_INFINITY; } else { final double distance = toInterval.getStart() - fromInterval.getEnd() - 1; return distance > 0 ? distance : Math.max(0, fromInterval.getStart() - toInterval.getEnd() - 1); } }

Target:
double calculateDistance(final Target fromTarget, final Target toTarget) { final SimpleInterval fromInterval = fromTarget.getInterval(); final SimpleInterval toInterval = toTarget.getInterval(); if (fromInterval == null || toInterval == null) { return 0.0; } else if (fromInterval.overlaps(toInterval)) { return 0.0; } if (!fromInterval.getContig().equals(toInterval.getContig())) { return Double.POSITIVE_INFINITY; } else if (fromInterval.getStart() < toInterval.getStart()) { return toInterval.getStart() - fromInterval.getEnd() - 1; } else { return fromInterval.getStart() - toInterval.getEnd() - 1; } }