当前位置: 首页>>代码示例>>C#>>正文


C# SortedSet.Count方法代码示例

本文整理汇总了C#中SortedSet.Count方法的典型用法代码示例。如果您正苦于以下问题:C# SortedSet.Count方法的具体用法?C# SortedSet.Count怎么用?C# SortedSet.Count使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在SortedSet的用法示例。


在下文中一共展示了SortedSet.Count方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: textBox1_TextChanged

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

            //Unsorted 
            HashSet<int> set = new HashSet<int>();
            List<int> list = new List<int>();
            SortedSet<int> sortset = new SortedSet<int>();
            StringBuilder s = new StringBuilder();
            Random rand = new Random();

            //Add random numbers to a list (not ordered)
            for (int i = 0; i < 10000; i++) { list.Add(rand.Next(1, 20000)); }

            //Place unique numbers from the list previously generated into a hashset
            for (int i = 0; i < 10000; i++) { set.Add(list[i]); }

            //Sorts the list of random numbers through the use of a Sortedset
            for (int i = 0; i < 10000; i++) { sortset.Add(list[i]); }

            //count distinct characters in the list 
            int unique = (from i in list select i).Distinct().Count();

            //String formatting
            s.Append("1. Hashset method: " + set.Count().ToString() + " unique numbers." +
            "The time complexity of this code is O(nlog(n) + 2n), because the intialization of variables " +
            "is O(1) and the add function for the hashset and list is O(1). Therefore the algorithm executes" +
            "10000 times twice and we'll mark this up to be (2n)." +
            "This gives us a time complexity for the aglorithm to be O(2n). Then the add time complexity for the sortedset is nlogn which consequatnly"+
            "gives us O(nlog(n) + 2n)");
            s.Append("\r\n2. " + unique.ToString() + " unique numbers.");
            s.Append("\r\n3. " + sortset.Count().ToString() + " unique numbers");
            textBox1.Text = s.ToString();                  
        }
开发者ID:russvick,项目名称:CS322,代码行数:33,代码来源:Form1.cs

示例2: buttonGerar_Click

        private void buttonGerar_Click(object sender, EventArgs e)
        {
            Task.Run(() => {
                ClearText();
                Random random = new Random((int) DateTime.Now.Ticks);
                SortedSet<string> numerosCertidao = new SortedSet<string>();

                int quantidade;
                if (!Int32.TryParse(textBoxQtd.Text, out quantidade)) {
                    InsertText(String.Format("Erro: \"{0}\" não é uma quantidade válida.", textBoxQtd.Text));
                    return;
                }

                while (numerosCertidao.Count() < quantidade) {
                    string numeroCertidao = CertidaoNascimentoHelper.GerarNumeroCertidao(random);
                    numeroCertidao =
                        numeroCertidao.Substring(0, 6) + " " +
                        numeroCertidao.Substring(6, 2) + " " +
                        numeroCertidao.Substring(8, 2) + " " +
                        numeroCertidao.Substring(10, 4) + " " +
                        numeroCertidao.Substring(14, 1) + " " +
                        numeroCertidao.Substring(15, 5) + " " +
                        numeroCertidao.Substring(20, 3) + " " +
                        numeroCertidao.Substring(23, 7) + " " +
                        numeroCertidao.Substring(30, 2);
                    numerosCertidao.Add(numeroCertidao);
                }

                foreach (var numero in numerosCertidao) {
                    InsertText(numero);
                }
            });
        }
开发者ID:arfurlaneto,项目名称:CertidaoNascimento,代码行数:33,代码来源:FormPrincipal.cs

示例3: FillCache

 public void FillCache(IPTV2Entities context, TimeSpan cacheDuration, int offeringId, int serviceId)
 {
     DateTime registDt = DateTime.Now;
     try
     {
         var countries = context.Countries;
         var listOfProductPackages = context.ProductPackages.Where(p => p.Product.IsForSale && p.Product.StatusId == Visible).Select(p => p.Package).Distinct();
         var offering = context.Offerings.Find(offeringId);
         var service = offering.Services.FirstOrDefault(o => o.PackageId == serviceId);
         foreach (var package in listOfProductPackages)
         {
             foreach (var c in countries)
             {
                 string cacheKey = "GPKGFEAT:P:" + package.PackageId + ";C:" + c.Code;
                 List<string> list = new List<string>();
                 SortedSet<int> listOfShowIds = new SortedSet<int>();
                 try
                 {
                     foreach (var category in package.Categories)
                     {
                         listOfShowIds.UnionWith(service.GetAllOnlineShowIds(c.Code, category.Category));
                         if (category.Category is Category)
                         {
                             var item = (Category)category.Category;
                             var CategoryShowIds = service.GetAllOnlineShowIds(c.Code, item);
                             if (CategoryShowIds.Count() > 1000)
                                 list.Add(String.Format("{0}+ in {1}", Floor(CategoryShowIds.Count(), 100), item.Description));
                             else if (CategoryShowIds.Count() > 100)
                                 list.Add(String.Format("{0}+ in {1}", Floor(CategoryShowIds.Count(), 10), item.Description));
                             else if (CategoryShowIds.Count() > 10)
                                 list.Add(String.Format("{0}+ in {1}", Floor(CategoryShowIds.Count(), 10), item.Description));
                             else
                                 list.Add(String.Format("{0} in {1}", CategoryShowIds.Count(), item.Description));
                         }
                     }
                     int showCount = listOfShowIds.Count();
                     if (showCount < 10)
                         list.Add(String.Format("{0} {1}", showCount, showCount == 1 ? "Title" : "Titles"));
                     else
                         list.Add(String.Format("{0}+ Titles", Floor(showCount, 10)));
                     string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(list);
                     IPTV2_Model.DataCache.Cache.Put(cacheKey, jsonString, cacheDuration);
                 }
                 catch (Exception) { }
             }
         }
     }
     catch (Exception e) { Trace.TraceError("PackageFeatureCacheRefresher Cache - Error! " + e.Message); }
 }
开发者ID:agentvnod,项目名称:tfctvoldcode,代码行数:49,代码来源:PackageFeatureCacheRefresher.cs

示例4: Main

 static void Main()
 {
     string text = Console.ReadLine();
     SortedSet<char> characters = new SortedSet<char>();
     for (int i = 0; i < text.Length; i++)
     {
         characters.Add(text[i]);
     }
     int[] counter = new int[characters.Count()];
     for (int i = 0; i < characters.Count; i++)
     {
         for (int j = 0; j < text.Length; j++)
         {
             if (text[j] == characters.ElementAt(i))
             {
                 counter[i]++;
             }
         }
     }
     for (int i = 0; i < characters.Count(); i++)
     {
         Console.WriteLine("{0}: {1} time/s", characters.ElementAt(i), counter[i]);
     }
 }
开发者ID:hristodobrev,项目名称:Software-University,代码行数:24,代码来源:CountSymbols.cs

示例5: GetRelatedSpecials

        public PartialViewResult GetRelatedSpecials(int? id, int? episodeId, int? NextEpisodeId, int? PreviousEpisodeId, int? EpisodeNumber, int? EpisodeCount, int? pageSize, string partialViewName = "")
        {
            List<EpisodeObject> list = null;
            try
            {
                ViewBag.PageSize = pageSize;
                if (id != null)
                {
                    var registDt = DateTime.Now;
                    var context = new IPTV2Entities();
                    var category = context.CategoryClasses.FirstOrDefault(c => c.CategoryId == id);
                    if (category != null)
                    {
                        if (category.StartDate < registDt && category.EndDate > registDt && category is Show)
                        {
                            string CountryCode = MyUtility.GetCountryCodeViaIpAddressWithoutProxy();
                            var offering = context.Offerings.Find(GlobalConfig.offeringId);
                            var service = offering.Services.FirstOrDefault(s => s.PackageId == GlobalConfig.serviceId);

                            var specialCurrentCategory = context.CategoryClasses.FirstOrDefault(c => c.CategoryId == GlobalConfig.SpecialsCurrentCategoryId);
                            if (specialCurrentCategory != null)
                            {
                                if (specialCurrentCategory is Category)
                                {
                                    SortedSet<int> showIds = new SortedSet<int>();
                                    showIds.UnionWith(service.GetAllOnlineShowIds(CountryCode, (Category)specialCurrentCategory));
                                    if (showIds.Count() > 0)
                                    {
                                        showIds.Remove(category.CategoryId); // remove the current id from list;                                        
                                        var shows = context.CategoryClasses.Where(c => showIds.Contains(c.CategoryId)).OrderByDescending(c => c.StartDate);
                                        if (shows != null)
                                        {
                                            list = new List<EpisodeObject>();
                                            foreach (var show in shows)
                                            {
                                                if (show is SpecialShow)
                                                {
                                                    string img = GlobalConfig.AssetsBaseUrl + GlobalConfig.BlankGif;
                                                    if (!String.IsNullOrEmpty(show.ImagePoster))
                                                        img = String.Format("{0}{1}/{2}", GlobalConfig.ShowImgPath, show.CategoryId, show.ImageMobileLandscape);
                                                    list.Add(new EpisodeObject()
                                                    {
                                                        EpisodeId = show.CategoryId,
                                                        Name = show.Description,
                                                        DateAiredStr = show.StartDate.Value.ToString("MMMM d, yyyy"),
                                                        Synopsis = show.Blurb,
                                                        ImgUrl = img,
                                                        Show = show.Description,
                                                        slug = MyUtility.GetSlug(show.Description)
                                                    });

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e) { MyUtility.LogException(e); }
            if (!String.IsNullOrEmpty(partialViewName))
                return PartialView(partialViewName, list);
            return PartialView(list);
        }
开发者ID:agentvnod,项目名称:tfctvoldcode,代码行数:66,代码来源:ShowController.cs

示例6: GetRelatedContent

        public PartialViewResult GetRelatedContent(int? id, int? episodeId, int? NextEpisodeId, int? PreviousEpisodeId, int? EpisodeNumber, int? EpisodeCount, int? pageSize, string partialViewName = "")
        {
            List<EpisodeObject> list = null;
            try
            {
                ViewBag.PageSize = pageSize;
                if (id != null)
                {
                    var registDt = DateTime.Now;
                    var context = new IPTV2Entities();
                    var category = context.CategoryClasses.FirstOrDefault(c => c.CategoryId == id);
                    if (category != null)
                    {
                        if (category.StartDate < registDt && category.EndDate > registDt && category is Show)
                        {
                            string CountryCode = MyUtility.GetCountryCodeViaIpAddressWithoutProxy();
                            var offering = context.Offerings.Find(GlobalConfig.offeringId);
                            var service = offering.Services.FirstOrDefault(s => s.PackageId == GlobalConfig.serviceId);

                            //get subcategories of movie category
                            List<int> subCategoryIds = null;
                            try
                            {
                                var movieCategory = context.CategoryClasses.FirstOrDefault(c => c.CategoryId == GlobalConfig.Movies);
                                if (movieCategory != null)
                                {
                                    if (movieCategory is Category)
                                    {
                                        var movieSubCategories = ((Category)movieCategory).CategoryClassSubCategories.Select(c => c.SubCategory.CategoryId);
                                        if (movieSubCategories != null)
                                        {
                                            subCategoryIds = movieSubCategories.ToList();
                                        }
                                    }
                                }
                            }
                            catch (Exception) { }
                            var parents = ((Show)category).GetAllParentCategories();
                            if (parents != null)
                            {
                                if (parents.Count() > 0)
                                {
                                    var intersect = subCategoryIds == null ? parents : parents.Intersect(subCategoryIds);
                                    SortedSet<int> showIds = new SortedSet<int>();
                                    foreach (var item in intersect)
                                    {
                                        var parentCategory = context.CategoryClasses.FirstOrDefault(c => c.CategoryId == item);
                                        if (parentCategory is Category)
                                            showIds.UnionWith(service.GetAllOnlineShowIds(CountryCode, (Category)parentCategory));
                                    }

                                    if (showIds.Count() > 0)
                                    {
                                        List<int> eIds = null;
                                        using (var ec = new EngagementsModel.EngagementsEntities())
                                        {
                                            var eShowIds = ec.ShowReactions.Where(s => s.ReactionTypeId == GlobalConfig.SOCIAL_LOVE).GroupBy(s => s.CategoryId)
                                                .Select(s => new { count = s.Count(), id = s.Key }).OrderByDescending(s => s.count).Select(s => s.id);
                                            if (eShowIds != null)
                                                eIds = eShowIds.ToList();

                                        }
                                        if (eIds != null)
                                        {
                                            var shows = context.CategoryClasses.Where(c => showIds.Contains(c.CategoryId));
                                            if (shows != null)
                                            {
                                                Dictionary<int, CategoryClass> d = shows.ToDictionary(x => x.CategoryId);
                                                List<CategoryClass> ordered = new List<CategoryClass>();
                                                foreach (var i in eIds)
                                                {
                                                    if (d.ContainsKey(i))
                                                        ordered.Add(d[i]);
                                                }

                                                list = new List<EpisodeObject>();
                                                foreach (var show in ordered)
                                                {
                                                    if (show is Movie)
                                                    {
                                                        string img = GlobalConfig.AssetsBaseUrl + GlobalConfig.BlankGif;
                                                        if (!String.IsNullOrEmpty(show.ImagePoster))
                                                            img = String.Format("{0}{1}/{2}", GlobalConfig.ShowImgPath, show.CategoryId, show.ImageMobileLandscape);
                                                        list.Add(new EpisodeObject()
                                                        {
                                                            EpisodeId = show.CategoryId,
                                                            Name = show.Description,
                                                            DateAiredStr = show.StartDate.Value.ToString("MMMM d, yyyy"),
                                                            Synopsis = show.Blurb,
                                                            ImgUrl = img,
                                                            Show = show.Description,
                                                            slug = MyUtility.GetSlug(show.Description)
                                                        });

                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
//.........这里部分代码省略.........
开发者ID:agentvnod,项目名称:tfctvoldcode,代码行数:101,代码来源:ShowController.cs

示例7: FeatureSummary

        public static string FeatureSummary(Task feature)
        {
            IEnumerable<Task> allTasks;
            try
            {
                allTasks = LinkedTasks(feature);
            }
            catch (UnlinkedException)
            {
                if (feature.GetCustomColumnValue("Planned sprint").ToString() != string.Empty)
                    feature.SetCustomColumnValue("Planned sprint", string.Empty);
                return string.Empty;
            }
            var projects = allTasks.Select(t => t.Project.Name).Distinct();
            var allPlannedSprints = new SortedSet<string>();
            var plannedIPSprint = false;

            var summary_builder = new StringBuilder();
            summary_builder.Append(string.Format(FEATURE_SUMMARY_LINE_FORMAT, FEATURE_SUMMARY_HEADINGS));
            summary_builder.Append(FEATURE_SUMMARY_HEADER_SEPARATOR);

            foreach (var project in projects)
            {
                var team = project.Substring(TEAM_PROJECT_PREFIX.Length);
                var teamShort = team.Substring(0, (team.Length > 14) ? 13 : team.Length) + ((team.Length > 14) ? "…" : "");
                var tasks = allTasks.Where(t => t.Project.Name == project);
                var status = CalcAggregatedStatus(tasks);
                var completedPoints = tasks.Where(t => LeafCompleted(t)).Sum(t => t.Points);
                var totalPoints = tasks.Sum(t => t.Points);
                var completedStories = tasks.Where(t => LeafCompleted(t)).Count();
                var totalStories = tasks.Count();
                var plannedSprints = tasks
                    .Where(t => !LeafCompleted(t))
                    .Select(t => t.GetCustomColumnValue("Planned sprint"))
                    .Where(sprintColumn => sprintColumn != null)
                    .Select(sprintColumn => sprintColumn.ToString())
                    .Where(sprint => sprint.Length != 0)
                    .Distinct()
                    .OrderBy(sprint => sprint);
                var plannedSprintsString = plannedSprints.Aggregate(
                        new StringBuilder(),
                        (sb, sprint) => sb.Append(sprint).Append(", "),
                        sb => sb.Length > 0 ? sb.ToString(0, sb.Length-2) : "");
                var productOwner = ProductOwnerConfig.GetProductOwner(team, "unknown");
                var productOwnerShort = productOwner.Substring(0, (productOwner.Length > 14) ? 13 : productOwner.Length) + ((productOwner.Length > 14) ? "…" : "");

                summary_builder.AppendFormat(FEATURE_SUMMARY_LINE_FORMAT,
                    teamShort, status, completedPoints + "/" + totalPoints, completedStories + "/" + totalStories, productOwnerShort, plannedSprintsString);

                if (plannedSprintsString.Length > 0)
                {
                    if (!plannedIPSprint && plannedSprints.Where(t => t == "IP").Any())
                        plannedIPSprint = true;
                    var maxPlannedSprint = plannedSprints.Where(t => t.StartsWith("S")).Max();
                    allPlannedSprints.Add(maxPlannedSprint);
                }
            }

            if (plannedIPSprint)
                feature.SetCustomColumnValue("Planned sprint", "IP");
            else if (allPlannedSprints.Count() > 0)
                feature.SetCustomColumnValue("Planned sprint", allPlannedSprints.Max());

            return summary_builder.ToString();
        }
开发者ID:patrikha,项目名称:HansoftSAFeExtension,代码行数:65,代码来源:TeamStories2ProgramFeatureAggregation.cs

示例8: Cluster

        /**
         * Now the Agglomerative Clustering. May want to pass in additional parameters, like the termination
         * criteria and parameters.
         * Assumes list of colors are in row-order
         **/
        public void Cluster(List<CIELAB> colors, int width, int height)
        {
            double maxDist = 50*10;
            SortedSet<int> activeClusterIds = new SortedSet<int>();
            String logFile = "log.txt";
            StreamWriter log = File.AppendText(logFile);
            log.WriteLine("\n\tCluster Spatial Run " + DateTime.Now.ToString());
            log.Flush();

            //the smaller id comes first in the dictionary for pairwise distances
            PriorityQueue<Tuple<int, int>, double> pq = new PriorityQueue<Tuple<int, int>, double>();

            clusters = new Dictionary<int, PixelCluster>();

            int counter = 0;

            //Initialize the clusters in row-order
            for (int j = 0; j < height; j++)
            {
                for (int i = 0; i < width; i++)
                {
                    activeClusterIds.Add(counter);
                    PixelCluster p = new PixelCluster(counter, colors[width * j + i]);
                    counter++;

                    //Initialize the 4-neighbors
                    if (i > 0)
                        p.neighbors.Add(ToIndex(i - 1, j, width));
                    if (j > 0)
                        p.neighbors.Add(ToIndex(i, j - 1, width));
                    if (i < width - 1)
                        p.neighbors.Add(ToIndex(i + 1, j, width));
                    if (j < height - 1)
                        p.neighbors.Add(ToIndex(i, j + 1, width));

                    clusters.Add(p.id, p);
                }
            }

            foreach (int i in activeClusterIds)
            {
                //calculate distances to neighbors larger than current id
                SortedSet<int> neighbors = Simplify(clusters[i].neighbors);
                foreach (int j in neighbors)
                {
                    if (i < j)
                    {
                        pq.Enqueue(new Tuple<int, int>(i, j), -1*clusters[i].lab.SqDist(clusters[j].lab));
                    }
                }

            }

            Stopwatch timer = new Stopwatch();
            timer.Start();

            while (activeClusterIds.Count > 1)
            {

                //Find the pair with the smallest distance
                KeyValuePair<Tuple<int, int>, double> result = BestPair(pq, activeClusterIds);
                Tuple<int, int> pair = result.Key;
                double bestDist = -1*result.Value;

                Console.WriteLine("num clusters: " + activeClusterIds.Count());

                if (bestDist > maxDist)
                    break;

                PixelCluster a = clusters[pair.Item1];
                PixelCluster b = clusters[pair.Item2];

                //Create a new cluster with unique id
                PixelCluster merged = new PixelCluster();
                merged.id = counter++;
                merged.lab = (a.lab * a.count + b.lab * b.count) / (a.count + b.count);
                merged.count = a.count + b.count;
                merged.children = new int[] { a.id, b.id };
                merged.neighbors = MergeNeighbors(a.id, b.id);
                merged.parentId = merged.id;
                a.parentId = merged.id;
                b.parentId = merged.id;
                clusters.Add(merged.id, merged);

                //Update the active cluster set
                activeClusterIds.Remove(a.id);
                activeClusterIds.Remove(b.id);
                activeClusterIds.Add(merged.id);

                double totalCount = a.count + b.count;

                //Update the distances, based on old distances
                foreach (int i in merged.neighbors)
                {
                    //Debug.Assert(i != merged.id && activeClusterIds.Contains(i));
//.........这里部分代码省略.........
开发者ID:dritchie,项目名称:SceneColorMaterial,代码行数:101,代码来源:Clustering.cs

示例9: ClusterColorSpace

        //Cluster the final clusters into color space
        public void ClusterColorSpace()
        {
            double maxDist = 20*20;
            int minRegions = 5;

            SortedSet<int> activeClusterIds = new SortedSet<int>(rootIds);
            String logFile = "colorlog.txt";
            StreamWriter log = File.AppendText(logFile);
            log.WriteLine("\n\tCluster ColorSpace Run " + DateTime.Now.ToString());
            log.Flush();

            //the smaller id comes first in the dictionary for pairwise distances
            PriorityQueue<Tuple<int, int>, double> pq = new PriorityQueue<Tuple<int, int>, double>();

            int counter = activeClusterIds.Last()+1;

            int[] ids = activeClusterIds.ToArray<int>();

            //Calculate the initial distances
            for (int i = 0; i < ids.Count(); i++)
            {
                for (int j = i+1; j < ids.Count(); j++)
                {
                    //log.WriteLine(ids[i] + ", " + ids[j] + " dist " + -1 * clusters[ids[i]].lab.SqDist(clusters[ids[j]].lab));
                    //log.Flush();

                    //pq.Enqueue(new Tuple<int, int>(ids[i], ids[j]), -1 * clusters[ids[i]].lab.SqDist(clusters[ids[j]].lab));
                    PixelCluster a = clusters[ids[i]];
                    PixelCluster b = clusters[ids[j]];

                    double newDist = a.lab.SqDist(b.lab);

                    //Add in Ward's variance  (variation in Color Segmentation using Region Merging)
                    //http://www.mathworks.com/help/toolbox/stats/linkage.html
                    //newDist = newDist * Math.Sqrt(2 * a.count * b.count / (a.count + b.count));

                    pq.Enqueue(new Tuple<int, int>(ids[i], ids[j]), -1 * newDist);
                }
            }

            Stopwatch timer = new Stopwatch();
            timer.Start();

            while (activeClusterIds.Count > minRegions)
            {

                //Find the pair with the smallest distance
                KeyValuePair<Tuple<int, int>, double> result = BestPair(pq, activeClusterIds);
                Tuple<int, int> pair = result.Key;
                double bestDist = -1 * result.Value;

                Console.WriteLine("num clusters: " + activeClusterIds.Count());

                if (bestDist > maxDist)
                    break;

                PixelCluster a = clusters[pair.Item1];
                PixelCluster b = clusters[pair.Item2];

                //Create a new cluster with unique id, we don't care about the neighbors
                PixelCluster merged = new PixelCluster();
                merged.id = counter++;
                merged.lab = (a.lab * a.count + b.lab * b.count) / (a.count + b.count);
                merged.count = a.count + b.count;
                merged.children = new int[] { a.id, b.id };
                merged.parentId = merged.id;
                a.parentId = merged.id;
                b.parentId = merged.id;
                clusters.Add(merged.id, merged);

                //Update the active cluster set
                activeClusterIds.Remove(a.id);
                activeClusterIds.Remove(b.id);
                activeClusterIds.Add(merged.id);

                double totalCount = a.count + b.count;

                //Update the distances, based on old distances
                foreach (int i in activeClusterIds)
                {
                    if (i == merged.id)
                        continue;

                    //TODO: Ward's method with minimum variance
                    //For now, just use the dist between the centroids
                    PixelCluster c = clusters[i];
                    double newDist = merged.lab.SqDist(c.lab);

                    //Add in Ward's variance  (variation in Color Segmentation using Region Merging)
                    //http://www.mathworks.com/help/toolbox/stats/linkage.html
                    //newDist = newDist * Math.Sqrt(2*a.count * b.count / (a.count + b.count));

                    if (c.id < merged.id)
                        pq.Enqueue(new Tuple<int, int>(c.id, merged.id), -1 * newDist);
                    else
                        pq.Enqueue(new Tuple<int, int>(merged.id, c.id), -1 * newDist);

                }

//.........这里部分代码省略.........
开发者ID:dritchie,项目名称:SceneColorMaterial,代码行数:101,代码来源:Clustering.cs

示例10: ClusterColors

        public void ClusterColors(List<CIELAB> colors, int width, int height)
        {
            //Bin the colors
            int minRegions = 5;
            double maxDist = 10*10;
            SortedSet<int> activeClusterIds = new SortedSet<int>();
            String logFile = "log-colorspace.txt";
            StreamWriter log = File.AppendText(logFile);
            log.WriteLine("\n\tCluster Color Space " + DateTime.Now.ToString());
            log.Flush();

            //the smaller id comes first in the dictionary for pairwise distances
            PriorityQueue<Tuple<int, int>, double> pq = new PriorityQueue<Tuple<int, int>, double>();

            clusters = new Dictionary<int, PixelCluster>();
            int counter = 0;

            foreach (CIELAB color in colors)
            {
                //bin it into one of the clusters
                //index is a first, then b, then L
                int id = GetBinId(color);

                if (id > counter)
                    counter = id;

                if (!clusters.ContainsKey(id))
                {
                    clusters.Add(id, new PixelCluster(id, color));
                }
                else
                {
                    clusters[id].lab = (clusters[id].lab * clusters[id].count + color) / (clusters[id].count + 1);
                    clusters[id].count++;
                }
            }
            counter++;

            activeClusterIds = new SortedSet<int>(clusters.Keys);

            List<int> ids = activeClusterIds.ToList<int>();
            for (int i=0; i<ids.Count(); i++)
            {
                PixelCluster a = clusters[ids[i]];

                //calculate distances to neighbors larger than current id
                for (int j=i+1; j<ids.Count(); j++)
                {
                    PixelCluster b = clusters[ids[j]];

                    double newDist = a.lab.SqDist(b.lab);
                    //newDist = newDist * Math.Sqrt(2 * a.count * b.count / (a.count + b.count));
                    pq.Enqueue(new Tuple<int, int>(a.id, b.id), -1*newDist);
                }

            }

            Stopwatch timer = new Stopwatch();
            timer.Start();

            while (activeClusterIds.Count > minRegions)
            {
                //Find the pair with the smallest distance
                KeyValuePair<Tuple<int, int>, double> result = BestPair(pq, activeClusterIds);
                Tuple<int, int> pair = result.Key;
                double bestDist = -1 * result.Value;

                Console.WriteLine("num clusters: " + activeClusterIds.Count());

                if (bestDist > maxDist)
                    break;

                PixelCluster a = clusters[pair.Item1];
                PixelCluster b = clusters[pair.Item2];

                //Create a new cluster with unique id, don't care about neighbors
                PixelCluster merged = new PixelCluster();
                merged.id = counter++;
                merged.lab = (a.lab * a.count + b.lab * b.count) / (a.count + b.count);
                merged.count = a.count + b.count;
                merged.children = new int[] { a.id, b.id };
                merged.parentId = merged.id;
                a.parentId = merged.id;
                b.parentId = merged.id;
                clusters.Add(merged.id, merged);

                //Update the active cluster set
                activeClusterIds.Remove(a.id);
                activeClusterIds.Remove(b.id);
                activeClusterIds.Add(merged.id);

                double totalCount = a.count + b.count;

                //Update the distances, based on old distances
                foreach (int i in activeClusterIds)
                {
                    //Debug.Assert(i != merged.id && activeClusterIds.Contains(i));

                    //TODO: Ward's method with minimum variance
                    //For now, just use the dist between the centroids
//.........这里部分代码省略.........
开发者ID:dritchie,项目名称:SceneColorMaterial,代码行数:101,代码来源:Clustering.cs

示例11: AddFixedDerefBytesField

        private void AddFixedDerefBytesField(FieldInfo field, IndexOutput data, IndexOutput index, IEnumerable<BytesRef> values, int length)
        {
            field.PutAttribute(LegacyKey, LegacyDocValuesType.BYTES_FIXED_DEREF.Name);

            CodecUtil.WriteHeader(data, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_CODEC_NAME_DAT, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_VERSION_CURRENT);

            CodecUtil.WriteHeader(index, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_CODEC_NAME_IDX, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_VERSION_CURRENT);

            // deduplicate
            SortedSet<BytesRef> dictionary = new SortedSet<BytesRef>();
            foreach (BytesRef v in values)
            {
                dictionary.Add(v == null ? new BytesRef() : BytesRef.DeepCopyOf(v));
            }

            /* values */
            data.WriteInt(length);
            foreach (BytesRef v in dictionary)
            {
                data.WriteBytes(v.Bytes, v.Offset, v.Length);
            }

            /* ordinals */
            int valueCount = dictionary.Count;
            Debug.Assert(valueCount > 0);
            index.WriteInt(valueCount);
            int maxDoc = State.SegmentInfo.DocCount;
            PackedInts.Writer w = PackedInts.GetWriter(index, maxDoc, PackedInts.BitsRequired(valueCount - 1), PackedInts.DEFAULT);

            BytesRef brefDummy;
            foreach (BytesRef v in values)
            {
                brefDummy = v;

                if (v == null)
                {
                    brefDummy = new BytesRef();
                }
                //int ord = dictionary.HeadSet(brefDummy).Size();
                int ord = dictionary.Count(@ref => @ref.CompareTo(brefDummy) < 0);
                w.Add(ord);
            }
            w.Finish();
        }
开发者ID:Cefa68000,项目名称:lucenenet,代码行数:44,代码来源:Lucene40DocValuesWriter.cs

示例12: InitializeAsyncAcquireMissingInfos

		private static BingImageInfo[] InitializeAsyncAcquireMissingInfos(ref DateTime anchorDate, ref DateTime minDate, int retry = 0)
		{
			if (retry > 3) return new BingImageInfo[0];

			var set = new SortedSet<BingImageInfo>(new BingImageInfo.Comparer());
			var startOffset = 0;
			var countOffset = 8;
			var startOffsetMax = (anchorDate - minDate).Days;
			bool isDateShifted = false;
			while (startOffset <= startOffsetMax)
			{
				var count = (startOffsetMax - startOffset) + 1;
				if (count > countOffset) count = countOffset;
				var infos = BingDailyImage.RequestImages(startOffset, count);

				// bing image request has 3 behaviors
				// 1. request fail (infos.count=0)
				// 2. request success and count(infos)=count => valid i and c
				// 3. request success and count(infos)<>count => when count > count(infos), bing returns all valid date.  
				//   otherwise,  count(infos) is the max bing is happy to offer.

				if (infos.Length == 0) break;

				if (infos.Length != count)
				{
					// condition 3
					if (infos.Length > count)
					{
						// bing returned all valid.
						foreach (var info in infos) if (!set.Contains(info)) set.Add(info);
						break; // nothing more to do.
					}

					countOffset = count = infos.Length;
					// this essentially makes count(infos)<count into condition 2.
				}

				// condition 2. 
				foreach (var info in infos)
				{
					if (!set.Contains(info)) set.Add(info);
					else isDateShifted = true; // repeat date.  should not occure unless the firstDate is shifted.
				}
				startOffset += count;
			}

			if (isDateShifted && !InitializeAsyncAcquireMissingInfosTryShiftDate(ref anchorDate, set))
			{
				// something weird happened. let's requery bing image and hope for best.
				return InitializeAsyncAcquireMissingInfos(ref anchorDate, ref minDate, retry + 1);
			}

			if (set.Count() != 0)
			{
				BingDataHelper.TryConvertStartdate(set.Max.StartDate, out anchorDate);
				BingDataHelper.TryConvertStartdate(set.Min.StartDate, out minDate);
			}

			return set.ToArray();
		}
开发者ID:Siggans,项目名称:bgview,代码行数:60,代码来源:ModelManager.cs

示例13: GetPackageFeaturesViaPackage

        public static List<string> GetPackageFeaturesViaPackage(string CountryCode, Package package)
        {
            List<string> list = null;
            string jsonString = String.Empty;
            try
            {
                var cache = DataCache.Cache;
                //modify cache duration
                var CacheDuration = new TimeSpan(0, GlobalConfig.PackageAndProductCacheDuration, 0);
                string cacheKey = "GPKGFEAT:P:" + package.PackageId + ";C:" + CountryCode;
                try { jsonString = (string)cache[cacheKey]; }
                catch (Exception) { }
                if (String.IsNullOrEmpty(jsonString))
                {
                    list = new List<string>();
                    var context = new IPTV2Entities();
                    var offering = context.Offerings.Find(GlobalConfig.offeringId);
                    var service = offering.Services.FirstOrDefault(o => o.PackageId == GlobalConfig.serviceId);
                    SortedSet<int> listOfShowIds = new SortedSet<int>();

                    foreach (var category in package.Categories)
                    {
                        listOfShowIds.UnionWith(service.GetAllOnlineShowIds(CountryCode, category.Category));
                        if (category.Category is Category)
                        {
                            var item = (Category)category.Category;
                            var CategoryShowIds = service.GetAllOnlineShowIds(CountryCode, item);
                            if (CategoryShowIds.Count() > 1000)
                                list.Add(String.Format("{0}+ in {1}", CategoryShowIds.Count().Floor(100), item.Description));
                            else if (CategoryShowIds.Count() > 100)
                                list.Add(String.Format("{0}+ in {1}", CategoryShowIds.Count().Floor(10), item.Description));
                            else if (CategoryShowIds.Count() > 10)
                                list.Add(String.Format("{0}+ in {1}", CategoryShowIds.Count().Floor(10), item.Description));
                            else
                                list.Add(String.Format("{0} in {1}", CategoryShowIds.Count(), item.Description));
                        }
                    }
                    list.Add(String.Format("{0}+ Titles", listOfShowIds.Count().Floor(10)));
                    jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(list);
                    cache.Put(cacheKey, jsonString, CacheDuration);
                }
                else
                    list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(jsonString);
            }
            catch (Exception e) { MyUtility.LogException(e); }
            return list;
        }
开发者ID:agentvnod,项目名称:tfctvoldcode,代码行数:47,代码来源:ContextHelper.cs


注:本文中的SortedSet.Count方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。