Example usage for java.util Comparator comparing

List of usage examples for java.util Comparator comparing

Introduction

In this page you can find the example usage for java.util Comparator comparing.

Prototype

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor) 

Source Link

Document

Accepts a function that extracts a java.lang.Comparable Comparable sort key from a type T , and returns a Comparator that compares by that sort key.

Usage

From source file:org.onosproject.imr.IntentMonitorAndRerouteManager.java

@Override
public boolean applyPath(Route route) {
    checkNotNull(route, "Route to apply must be not null");
    checkNotNull(route.appId(), "Application id must be not null");
    checkNotNull(route.key(), "Intent key to apply must be not null");
    checkNotNull(route.paths(), "New path must be not null");
    checkArgument(route.paths().size() >= 1);

    ApplicationId appId = route.appId();
    Key key = route.key();//from  w  w w . j  a  va  2s .  c o  m

    // check if the app and the intent key are monitored
    if (!monitoredIntents.containsKey(appId)) {
        return false;
    }
    if (!monitoredIntents.get(appId).containsKey(key)) {
        return false;
    }

    // TODO: now we manage only the unsplittable routing
    Path currentPath = route.paths().stream().max(Comparator.comparing(Path::weight)).get();

    // Check if the last and first element of the path are HostId
    // in this case remove them from the list
    if (currentPath.path().get(0) instanceof HostId) {
        currentPath.path().remove(0);
    }
    if (currentPath.path().get(currentPath.path().size() - 1) instanceof HostId) {
        currentPath.path().remove(currentPath.path().size() - 1);
    }

    List<Link> links = createPathFromDeviceList(currentPath.path());

    // Generate the new Link collection intent, if not possible it will return the old intent
    ConnectivityIntent intent = generateLinkCollectionIntent(links, key, appId);
    storeMonitoredIntent(intent);
    intentService.submit(intent);
    return true;
}

From source file:org.cgiar.ccafs.marlo.action.powb.CRPStaffingAction.java

@Override
public void prepare() throws Exception {
    // Get current CRP
    loggedCrp = (GlobalUnit) this.getSession().get(APConstants.SESSION_CRP);
    loggedCrp = crpManager.getGlobalUnitById(loggedCrp.getId());
    // Check history version
    if (this.getRequest().getParameter(APConstants.TRANSACTION_ID) != null) {
        this.setPowbSynthesisIdHistory();
    } else {// w w  w  .ja v  a  2  s.  com
        this.setPowbSynthesisParameters();
    }
    // Validate draft version
    if (powbSynthesis != null) {

        Path path = this.getAutoSaveFilePath();
        if (path.toFile().exists() && this.getCurrentUser().isAutoSave()) {
            this.readJsonAndLoadPowbSynthesis(path);
        } else {
            this.setDraft(false);
            this.createEmptyCrpStaffing();
            powbSynthesis
                    .setPowbSynthesisCrpStaffingCategoryList(powbSynthesis.getPowbSynthesisCrpStaffingCategory()
                            .stream().filter(c -> c.isActive()).collect(Collectors.toList()));
        }
    }
    // Get the list of liaison institutions Flagships and PMU.
    liaisonInstitutions = loggedCrp.getLiaisonInstitutions().stream()
            .filter(c -> c.getCrpProgram() != null
                    && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()
                    && c.isActive())
            .collect(Collectors.toList());
    liaisonInstitutions.addAll(loggedCrp.getLiaisonInstitutions().stream()
            .filter(c -> c.getCrpProgram() == null && c.getAcronym().equals("PMU") && c.isActive())
            .collect(Collectors.toList()));
    liaisonInstitutions.sort(Comparator.comparing(LiaisonInstitution::getAcronym));
    powbCrpStaffingCategories = new ArrayList<>();
    powbCrpStaffingCategories = powbCrpStaffingCategoriesManager.findAll().stream().filter(c -> c.isActive())
            .collect(Collectors.toList());

    if (this.isFlagship()) {
        PowbSynthesis powbSynthesisDB = powbSynthesisManager.findSynthesis(this.getActualPhase().getId(),
                liaisonInstitution.getId());
        powbSynthesisID = powbSynthesisDB.getId();
    }

    // Base Permission
    String params[] = { loggedCrp.getAcronym(), powbSynthesis.getId() + "" };
    this.setBasePermission(this.getText(Permission.POWB_SYNTHESIS_CRPSTAFFING_BASE_PERMISSION, params));

    if (this.isHttpPost()) {
        if (powbSynthesis.getPowbSynthesisCrpStaffingCategoryList() != null) {
            powbSynthesis.getPowbSynthesisCrpStaffingCategoryList().clear();
        }
    }
}

From source file:org.tightblog.ui.restapi.WeblogController.java

@GetMapping(value = "/tb-ui/authoring/rest/weblogconfig/metadata")
public WeblogConfigMetadata getWeblogConfigMetadata(Locale locale, Principal p) {
    User user = userRepository.findEnabledByUserName(p.getName());

    WeblogConfigMetadata metadata = new WeblogConfigMetadata();

    metadata.absoluteSiteURL = dp.getAbsoluteUrl();

    metadata.usersOverrideAnalyticsCode = webloggerPropertiesRepository.findOrNull()
            .isUsersOverrideAnalyticsCode();

    metadata.usersCommentNotifications = webloggerPropertiesRepository.findOrNull()
            .isUsersCommentNotifications();

    metadata.sharedThemeMap = themeManager.getEnabledSharedThemesList().stream()
            // Remove sitewide theme options for non-admins, if desired admin can create a sitewide blog
            // and assign a non-admin user ownership of it on the members page.
            .filter(theme -> !theme.isSiteWide() || user.hasEffectiveGlobalRole(GlobalRole.ADMIN))
            .collect(Utilities.toLinkedHashMap(SharedTheme::getId, st -> st));

    metadata.editFormats = Arrays.stream(Weblog.EditFormat.values()).collect(Utilities.toLinkedHashMap(
            Weblog.EditFormat::name, eF -> messages.getMessage(eF.getDescriptionKey(), null, locale)));

    metadata.locales = Arrays.stream(Locale.getAvailableLocales())
            .sorted(Comparator.comparing(Locale::getDisplayName))
            .collect(Utilities.toLinkedHashMap(Locale::toString, Locale::getDisplayName));

    metadata.timezones = Arrays.stream(TimeZone.getAvailableIDs()).sorted(Comparator.comparing(tz -> tz))
            .collect(Utilities.toLinkedHashMap(tz -> tz, tz -> tz));

    WebloggerProperties.CommentPolicy globalCommentPolicy = webloggerPropertiesRepository.findOrNull()
            .getCommentPolicy();//from  w ww  .  j a v a  2 s. c  o  m

    metadata.commentOptions = Arrays.stream(WebloggerProperties.CommentPolicy.values())
            .filter(co -> co.getLevel() <= globalCommentPolicy.getLevel())
            .collect(Utilities.toLinkedHashMap(WebloggerProperties.CommentPolicy::name,
                    co -> messages.getMessage(co.getWeblogDescription(), null, locale)));

    metadata.commentDayOptions = Arrays.stream(WeblogEntry.CommentDayOption.values())
            .collect(Utilities.toLinkedHashMap(cdo -> Integer.toString(cdo.getDays()),
                    cdo -> messages.getMessage(cdo.getDescriptionKey(), null, locale)));

    return metadata;
}

From source file:org.apache.sysml.hops.codegen.template.CPlanMemoTable.java

public MemoTableEntry getBest(long hopID, TemplateType pref) {
    List<MemoTableEntry> tmp = get(hopID);
    if (tmp == null || tmp.isEmpty())
        return null;

    //single plan per type, get plan w/ best rank in preferred order
    return Collections.min(tmp,
            Comparator.comparing(p -> (p.type == pref) ? -p.countPlanRefs() : p.type.getRank() + 1));
}

From source file:org.obiba.mica.search.JoinQueryExecutor.java

protected Function<List<MicaSearch.AggregationResultDto>, List<MicaSearch.AggregationResultDto>> aggregationPostProcessor() {
    return (aggregationResultDtos) -> {
        Map<String, AggregationResultDto.Builder> buildres = taxonomyService.getOpalTaxonomies().stream()
                .collect(Collectors.toMap(Taxonomy::getName, t -> {
                    MicaSearch.AggregationResultDto.Builder builder = MicaSearch.AggregationResultDto
                            .newBuilder().setAggregation(t.getName());
                    t.getTitle().forEach((k, v) -> builder
                            .addTitle(Mica.LocalizedStringDto.newBuilder().setLang(k).setValue(v).build()));
                    return builder;
                }));/*from ww  w. j a v  a2 s.  c  om*/

        Pattern pattern = Pattern.compile("attributes-(\\w+)__(\\w+)-\\w+$");
        List<MicaSearch.AggregationResultDto> newList = Lists.newArrayList();
        // report only aggregations for which we have results
        List<String> aggregationNames = Lists.newArrayList();
        aggregationResultDtos.forEach(dto -> {
            Matcher matcher = pattern.matcher(dto.getAggregation());
            if (matcher.find()) {
                String taxonomy = matcher.group(1);
                MicaSearch.AggregationResultDto.Builder builder = buildres.get(taxonomy);
                builder.addChildren(dto);
                aggregationNames.add(builder.getAggregation());
            } else {
                newList.add(dto);
            }
        });

        newList.addAll(buildres.values().stream() //
                .filter(b -> aggregationNames.contains(b.getAggregation())) //
                .sorted(Comparator.comparing(AggregationResultDto.Builder::getAggregation)) //
                .map(MicaSearch.AggregationResultDto.Builder::build) //
                .collect(Collectors.toList())); //

        return newList;
    };
}

From source file:diffhunter.Indexer.java

public void Make_Index(Database hashdb, String file_name, String read_gene_location)
        throws FileNotFoundException, IOException {
    Set_Parameters();/* w  w w.ja  v  a2  s  .co m*/
    //System.out.print("Sasa");
    ConcurrentHashMap<String, Map<Integer, Integer>> dic_gene_loc_count = new ConcurrentHashMap<>();
    ArrayList<String> lines_from_bed_file = new ArrayList<>();
    BufferedReader br = new BufferedReader(new FileReader(file_name));

    String line = br.readLine();
    List<String> toks = Arrays.asList(line.split("\t"));
    lines_from_bed_file.add(line);
    String last_Seen_chromosome = toks.get(0).replace("chr", "");
    line = br.readLine();
    lines_from_bed_file.add(line);
    toks = Arrays.asList(line.split("\t"));
    String new_chromosome = toks.get(0).replace("chr", "");

    while (((line = br.readLine()) != null) || lines_from_bed_file.size() > 0) {
        if (line != null) {
            toks = Arrays.asList(line.split("\t"));
            new_chromosome = toks.get(0).replace("chr", "");
        }
        // process the line.
        if (line == null || !new_chromosome.equals(last_Seen_chromosome)) {
            System.out.println("Processing chromosome" + "\t" + last_Seen_chromosome);
            last_Seen_chromosome = new_chromosome;
            lines_from_bed_file.parallelStream().forEach(content -> {

                List<String> inner_toks = Arrays.asList(content.split("\t"));
                //WARNINNG WARNING WARNING WARNINNG WARNING WARNING WARNINNG WARNING WARNING WARNINNG WARNING WARNING WARNINNG WARNING WARNING WARNINNG WARNING WARNING WARNINNG WARNING WARNING WARNINNG WARNING WARNING 
                //STRAND column count should be changed. 
                String strand = inner_toks.get(5);
                String chromosome_ = inner_toks.get(0).replace("chr", "");
                if (!dic_Loc_gene.get(strand).containsKey(chromosome_)) {
                    return;
                }
                Integer start_loc = Integer.parseInt(inner_toks.get(1));
                Integer end_loc = Integer.parseInt(inner_toks.get(2));
                List<Interval<String>> res__ = dic_Loc_gene.get(strand).get(chromosome_).getIntervals(start_loc,
                        end_loc);
                //IntervalTree<String> pot_gene_name=new IntervalTree<>(res__);
                //                        for (int z = 0; z < pot_gene_name.Intervals.Count; z++)
                //{
                for (int z = 0; z < res__.size(); z++) {

                    dic_gene_loc_count.putIfAbsent(res__.get(z).getData(), new HashMap<>());
                    String gene_symbol = res__.get(z).getData();
                    Integer temp_gene_start_loc = dic_genes.get(gene_symbol).start_loc;
                    Integer temp_gene_end_loc = dic_genes.get(gene_symbol).end_loc;
                    if (start_loc < temp_gene_start_loc) {
                        start_loc = temp_gene_start_loc;
                    }
                    if (end_loc > temp_gene_end_loc) {
                        end_loc = temp_gene_end_loc;
                    }
                    synchronized (dic_synchrinzer_genes.get(gene_symbol)) {
                        for (int k = start_loc; k <= end_loc; k++) {
                            Integer value_inside = 0;
                            value_inside = dic_gene_loc_count.get(gene_symbol).get(k);
                            dic_gene_loc_count.get(gene_symbol).put(k,
                                    value_inside == null ? 1 : (value_inside + 1));
                        }
                    }
                }
            });
            /*                    List<string> keys_ = dic_gene_loc_count.Keys.ToList();
             List<string> alt_keys = new List<string>();// dic_gene_loc_count.Keys.ToList();
             for (int i = 0; i < keys_.Count; i++)
             {
             Dictionary<int, int> dicccc_ = new Dictionary<int, int>();
             dic_gene_loc_count[keys_[i]] = new Dictionary<int, int>(dic_gene_loc_count[keys_[i]].Where(x => x.Value >= 2).ToDictionary(x => x.Key, x => x.Value));
             if (dic_gene_loc_count[keys_[i]].Count == 0)
             {
                    
             dic_gene_loc_count.TryRemove(keys_[i], out dicccc_);
             continue;
             }
             hashdb.Put(Get_BDB(keys_[i]), Get_BDB_Dictionary(dic_gene_loc_count[keys_[i]]));
             alt_keys.Add(keys_[i]);
             dic_gene_loc_count.TryRemove(keys_[i], out dicccc_);
             }*/
            ArrayList<String> keys_ = new ArrayList<>(dic_gene_loc_count.keySet());
            ArrayList<String> alt_keys = new ArrayList<>();
            for (int i = 0; i < keys_.size(); i++) {

                //LinkedHashMap<Integer, Integer> tmep_map = new LinkedHashMap<>(dic_gene_loc_count.get(keys_.get(i)));
                LinkedHashMap<Integer, Integer> tmep_map = new LinkedHashMap<>();
                /*tmep_map = */
                dic_gene_loc_count.get(keys_.get(i)).entrySet().stream().filter(p -> p.getValue() >= 2)
                        .sorted(Comparator.comparing(E -> E.getKey()))
                        .forEach((entry) -> tmep_map.put(entry.getKey(), entry.getValue()));//.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
                if (tmep_map.isEmpty()) {
                    dic_gene_loc_count.remove(keys_.get(i));
                    continue;
                }

                //Map<Integer, Integer> tmep_map1 = new LinkedHashMap<>();
                //tmep_map1=sortByKey(tmep_map);
                //tmep_map.entrySet().stream().sorted(Comparator.comparing(E -> E.getKey())).forEach((entry) -> tmep_map1.put(entry.getKey(), entry.getValue()));
                //BerkeleyDB_Box box=new BerkeleyDB_Box();
                hashdb.put(null, BerkeleyDB_Box.Get_BDB(keys_.get(i)),
                        BerkeleyDB_Box.Get_BDB_Dictionary(tmep_map));
                alt_keys.add(keys_.get(i));
                dic_gene_loc_count.remove(keys_.get(i));
                //dic_gene_loc_count.put(keys_.get(i),tmep_map);
            }

            hashdb.sync();
            int a = 1111;
            /*                    hashdb.Sync();
             File.AppendAllLines("InputDB\\" + Path.GetFileNameWithoutExtension(file_name) + "_genes.txt", alt_keys);
             //total_lines_processed_till_now += lines_from_bed_file.Count;
             //worker.ReportProgress(total_lines_processed_till_now / count_);
             lines_from_bed_file.Clear();
             if (!reader.EndOfStream)
             {
             lines_from_bed_file.Add(_line_);
             }
             last_Seen_chromosome = new_choromosome;*/
            lines_from_bed_file.clear();
            if (line != null) {
                lines_from_bed_file.add(line);
            }
            Path p = Paths.get(file_name);
            file_name = p.getFileName().toString();

            BufferedWriter output = new BufferedWriter(new FileWriter((Paths
                    .get(read_gene_location, FilenameUtils.removeExtension(file_name) + ".txt").toString()),
                    true));
            for (String alt_key : alt_keys) {
                output.append(alt_key);
                output.newLine();
            }
            output.close();
            /*if (((line = br.readLine()) != null))
            {
            lines_from_bed_file.add(line);
            toks=Arrays.asList(line.split("\t"));
            new_chromosome=toks.get(0).replace("chr", "");
            }*/
            //last_Seen_chromosome=new_chromosome;
        } else if (new_chromosome.equals(last_Seen_chromosome)) {
            lines_from_bed_file.add(line);
        }

    }
    br.close();
    hashdb.sync();
    hashdb.close();

}

From source file:org.apache.sysml.hops.codegen.template.CPlanMemoTable.java

public MemoTableEntry getBest(long hopID, TemplateType pref1, TemplateType pref2) {
    List<MemoTableEntry> tmp = get(hopID);
    if (tmp == null || tmp.isEmpty())
        return null;

    //single plan per type, get plan w/ best rank in preferred order
    return Collections.min(tmp, Comparator.comparing(p -> (p.type == pref1) ? -p.countPlanRefs() - 4
            : (p.type == pref2) ? -p.countPlanRefs() : p.type.getRank() + 1));
}

From source file:org.ballerinalang.docgen.docs.BallerinaDocGenerator.java

private static void sortPackageConstructs(BLangPackage bLangPackage) {
    bLangPackage.getFunctions().sort(Comparator.comparing(
            f -> (f.getReceiver() == null ? "" : f.getReceiver().getName()) + f.getName().getValue()));
    bLangPackage.getAnnotations().sort(Comparator.comparing(a -> a.getName().getValue()));
    bLangPackage.getTypeDefinitions().sort(Comparator.comparing(a -> a.getName().getValue()));
    bLangPackage.getGlobalVariables().sort(Comparator.comparing(a -> a.getName().getValue()));
}

From source file:org.languagetool.rules.spelling.suggestions.XGBoostSuggestionsOrderer.java

@Override
public List<SuggestedReplacement> orderSuggestions(List<String> suggestions, String word,
        AnalyzedSentence sentence, int startPos) {
    if (!isMlAvailable()) {
        throw new IllegalStateException("Illegal call to orderSuggestions() - isMlAvailable() returned false.");
    }/*from w w  w  . jav a2  s. c  o  m*/
    long featureStartTime = System.currentTimeMillis();

    String langCode = language.getShortCodeWithCountryAndVariant();

    Pair<List<SuggestedReplacement>, SortedMap<String, Float>> candidatesAndFeatures = computeFeatures(
            suggestions, word, sentence, startPos);
    //System.out.printf("Computing %d features took %d ms.%n", suggestions.size(), System.currentTimeMillis() - featureStartTime);
    List<SuggestedReplacement> candidates = candidatesAndFeatures.getLeft();
    SortedMap<String, Float> matchFeatures = candidatesAndFeatures.getRight();
    List<SortedMap<String, Float>> suggestionFeatures = candidates.stream()
            .map(SuggestedReplacement::getFeatures).collect(Collectors.toList());
    if (candidates.isEmpty()) {
        return Collections.emptyList();
    }
    if (candidates.size() != suggestionFeatures.size()) {
        throw new RuntimeException(
                String.format("Mismatch between candidates and corresponding feature list: length %d / %d",
                        candidates.size(), suggestionFeatures.size()));
    }

    int numFeatures = matchFeatures.size() + topN * suggestionFeatures.get(0).size(); // padding with zeros
    float[] data = new float[numFeatures];

    int featureIndex = 0;
    //System.out.printf("Features for match on '%s': %n", word);
    int expectedMatchFeatures = matchFeatureCount.getOrDefault(langCode, -1);
    int expectedCandidateFeatures = candidateFeatureCount.getOrDefault(langCode, -1);
    if (matchFeatures.size() != expectedMatchFeatures) {
        logger.warn(String.format("Match features '%s' do not have expected size %d.", matchFeatures,
                expectedMatchFeatures));
    }
    for (Map.Entry<String, Float> feature : matchFeatures.entrySet()) {
        //System.out.printf("%s = %f%n", feature.getKey(), feature.getValue());
        data[featureIndex++] = feature.getValue();
    }
    //int suggestionIndex = 0;
    for (SortedMap<String, Float> candidateFeatures : suggestionFeatures) {
        if (candidateFeatures.size() != expectedCandidateFeatures) {
            logger.warn(String.format("Candidate features '%s' do not have expected size %d.",
                    candidateFeatures, expectedCandidateFeatures));
        }
        //System.out.printf("Features for candidate '%s': %n", candidates.get(suggestionIndex++).getReplacement());
        for (Map.Entry<String, Float> feature : candidateFeatures.entrySet()) {
            //System.out.printf("%s = %f%n", feature.getKey(), feature.getValue());
            data[featureIndex++] = feature.getValue();
        }
    }
    List<Integer> labels = modelClasses.get(langCode);

    Booster model = null;
    try {
        long modelStartTime = System.currentTimeMillis();
        model = modelPool.borrowObject(language);
        //System.out.printf("Loading model took %d ms.%n", System.currentTimeMillis() - modelStartTime);
        DMatrix matrix = new DMatrix(data, 1, numFeatures);
        long predictStartTime = System.currentTimeMillis();
        float[][] output = model.predict(matrix);
        //System.out.printf("Prediction took %d ms.%n", System.currentTimeMillis() - predictStartTime);
        if (output.length != 1) {
            throw new XGBoostError(String.format(
                    "XGBoost returned array with first dimension of length %d, expected 1.", output.length));
        }
        float[] probabilities = output[0];
        if (probabilities.length != labels.size()) {
            throw new XGBoostError(
                    String.format("XGBoost returned array with second dimension of length %d, expected %d.",
                            probabilities.length, labels.size()));
        }
        // TODO: could react to label -1 (not in list) by e.g. evaluating more candidates
        //if (labels.get(0) != -1) {
        //  throw new IllegalStateException(String.format(
        //    "Expected first label of ML ranking model to be -1 (= suggestion not in list), was %d", labels.get(0)));
        //}
        //float notInListProbabilily = probabilites[0];
        for (int candidateIndex = 0; candidateIndex < candidates.size(); candidateIndex++) {
            int labelIndex = labels.indexOf(candidateIndex);
            float prob = 0.0f;
            if (labelIndex != -1) {
                prob = probabilities[labelIndex];
            }
            candidates.get(candidateIndex).setConfidence(prob);
        }
    } catch (XGBoostError xgBoostError) {
        logger.error("Error while applying XGBoost model to spelling suggestions", xgBoostError);
        return candidates;
    } catch (Exception e) {
        logger.error("Error while loading XGBoost model for spelling suggestions", e);
        return candidates;
    } finally {
        if (model != null) {
            try {
                modelPool.returnObject(language, model);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    candidates.sort(Collections.reverseOrder(Comparator.comparing(SuggestedReplacement::getConfidence)));
    return candidates;
}

From source file:org.omegat.gui.issues.IssuesPanelController.java

JMenuBar generateMenuBar() {
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = menuBar.add(new JMenu(OStrings.getString("ISSUES_WINDOW_MENU_OPTIONS")));

    {/* w w  w.j  av  a2  s . c  om*/
        // Tags item is hard-coded because it is not disableable and is implemented differently from all
        // others.
        JCheckBoxMenuItem tagsItem = new JCheckBoxMenuItem(OStrings.getString(
                "ISSUES_WINDOW_MENU_OPTIONS_TOGGLE_PROVIDER", OStrings.getString("ISSUES_TAGS_PROVIDER_NAME")));
        tagsItem.setSelected(true);
        tagsItem.setEnabled(false);
        menu.add(tagsItem);
    }

    Set<String> disabledProviders = IssueProviders.getDisabledProviderIds();
    IssueProviders.getIssueProviders().stream().sorted(Comparator.comparing(IIssueProvider::getId))
            .forEach(provider -> {
                String label = StringUtil.format(
                        OStrings.getString("ISSUES_WINDOW_MENU_OPTIONS_TOGGLE_PROVIDER"), provider.getName());
                JCheckBoxMenuItem item = new JCheckBoxMenuItem(label);
                item.addActionListener(e -> {
                    IssueProviders.setProviderEnabled(provider.getId(), item.isSelected());
                    refreshData(selectedEntry, selectedType);
                });
                item.setSelected(!disabledProviders.contains(provider.getId()));
                menu.add(item);
            });

    menu.addSeparator();

    {
        JCheckBoxMenuItem askItem = new JCheckBoxMenuItem(OStrings.getString("ISSUES_WINDOW_MENU_DONT_ASK"));
        askItem.setSelected(Preferences.isPreference(Preferences.ISSUE_PROVIDERS_DONT_ASK));
        askItem.addActionListener(
                e -> Preferences.setPreference(Preferences.ISSUE_PROVIDERS_DONT_ASK, askItem.isSelected()));
        menu.add(askItem);
    }
    return menuBar;
}