Example #1
0
    static void Main()
    {
        var collection = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

        int first = collection.FirstOrDefault(Even);

        Console.WriteLine(first);
        Console.WriteLine(collection.FirstOrDefault(x => x > 4));

        var allEven = collection.TakeWhile(Even);
        Console.WriteLine(string.Join(" ",allEven));
        Console.WriteLine(string.Join(" ", collection.TakeWhile(x => x < 10)));

        collection.ForEach(Console.WriteLine);
    }
Example #2
0
 static void Main()
 {
     List<int> collection = new List<int>() { 1, 2, 3, 6, 11, 20 };
     Console.WriteLine(collection.FirstOrDefault(x => x > 7));
     Console.WriteLine(string.Join(", ", collection.TakeWhile(x => x < 5)));
     collection.ForEach(Console.WriteLine);
 }
        static void Main(string[] args)
        {
            var nums = new List<int>() {1, 2, 3, 4, 5, 6, 7};

            var result = nums.TakeWhile(e => e < 6);

            Console.WriteLine(string.Join(", ", result));
        }
Example #4
0
 private static List<Solution> filterByEnding(Solution end, List<Solution> solutions)
 {
     if (end != null)
     {
         solutions = solutions.TakeWhile(x => x != end).Where(end.DependsOn).ToList();
         solutions.Add(end);
     }
     return solutions;
 }
Example #5
0
        public ProductRepository()
        {
            _products = new List<Product>(new Product[]{
                new Product {Name = "Kayak", Category = "Watersports", Price = 275M},
                new Product {Name = "Lifejacket", Category = "Watersports", Price = 48.95M},
                new Product {Name = "Soccer ball", Category = "Soccer", Price = 19.50M},
                new Product {Name = "Corner flag", Category = "Soccer", Price = 34.95M}
            });

            _products.TakeWhile(p => p.Name == "Kayak");
        }
Example #6
0
        public JsonResult Lista()
        {
            var lista = new List<int> ();

            for (int i = 0; i < 50; i++) {
                lista.Add (i);
            }

            var tes = lista.TakeWhile(a => a < 15).LastOrDefault();

            return Json(tes, JsonRequestBehavior.AllowGet);
        }
 public static IEnumerable<ulong> UlongPrimes() {
     var memoized = new List<ulong>();
     var primes = PotentialUlongPrimes().Where(x => {
             double sqrt = Math.Sqrt(x);
             return memoized
                 .TakeWhile(y => y <= sqrt)
                 .All(y => x % y != 0);
         });
     foreach (var prime in primes) {
         yield return prime;
         memoized.Add(prime);
     }
 }
Example #8
0
File: Test.cs Project: krasi070/OOP
        static void Main()
        {
            List<int> list = new List<int>()
            {
                1, 12, 19, 13, 100, 1, 1000, 13, 13, 1
            };

            IEnumerable<int> smallNums = list.TakeWhile(n => n < 100);

            foreach (var num in smallNums)
            {
                Console.WriteLine(num);
            }
        }
        public int Delete(string name, string producer)
        {
            var productsWithGivenName = new List<Product>(
                productsByName[name]);
            var temp = productsWithGivenName.TakeWhile(x => x.Producer == producer);
            var count = temp.Count();

            foreach (var product in temp)
            {
                productsByName.Remove(product.Name);
                productsByPrice.Remove(product);
                productsByProducer.Remove(producer);
            }

            return count;
        }
Example #10
0
 public static IEnumerable<int> Primes4(int count)
 {
     var memoized = new List<int>();
     var primes = PotentialPrimes(count).Where(x =>
     {
         var sqrt = Math.Sqrt(x);
         return !memoized
                     .TakeWhile(y => y <= sqrt)
                     .Any(y => x % y == 0);
     });
     foreach (var prime in primes)
     {
         yield return prime;
         memoized.Add(prime);
     }
 }
Example #11
0
		public static IEnumerable <long> Get ()
		{
			var temp = new List <long> ();
			var current = 1L;
			while (true)
			{
				current++;
				var sqrt = Math.Sqrt (current);
				if (temp
					.TakeWhile (x => x <= sqrt)
					.Any (x => current % x == 0))
					continue;

				temp.Add (current);
				yield return current;
			}
		}
        static void Main()
        {
            Action<int> printNumberAction = Console.WriteLine;
            printNumberAction(10);

            var students = new List<Student>()
            {
                new Student("Pesho", 23),
                new Student("Sasho", 18),
                new Student("Ivan", 34)
            };
            Student ivan = students.FirstOrDef(Hasname);
            Console.WriteLine(ivan.Name + " " + ivan.Age);

            var nums = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            nums.ForEachH();
            var smallNums = nums.TakeWhile(IsSmallerThan);
            Console.WriteLine(String.Join(", ", smallNums));
        }
Example #13
0
 public void Append(TableDataDesc table)
 {
     var rows = new List<RowDesc>();
       foreach(var scriptedRow in table.ScriptedData)
       {
     var row = DataDescFactory.CreateRowDescriptor(scriptedRow, table.PrimaryColumns);
     rows.Add(row);
       }
       var gen = new RowScriptGen();
       //Header
       var header = rows.TakeWhile(r => false == r is InsertRowDesc);
       //_sb.Append(gen.GenerateScript(header));
       _sb.AppendFormat("{0}{1}", gen.GenerateScript(header), Environment.NewLine);
       //Data
       var data = rows.Where(r => r is InsertRowDesc).Select(r => r as InsertRowDesc);
       _sb.AppendFormat("{0}{1}", gen.GenerateMergeScript(data, true), Environment.NewLine);
       //Footer
       var footer = rows.Skip(header.Count() + data.Count());
       _sb.AppendFormat("{0}{1}", gen.GenerateScript(footer), Environment.NewLine);
 }
Example #14
0
        private IList<Rectangle> ProbeScreenBounds()
        {
            var screenBoundsList = new List<Rectangle>();

            foreach (Screen screen in Screen.AllScreens)
            {
                Rectangle currentBounds = DpiHelper.ConvertPixelsToDIPixels(screen.Bounds);

                if (screenBoundsList.Count == 0)
                {
                    screenBoundsList.Add(currentBounds);
                    continue;
                }

                int index = screenBoundsList.TakeWhile(bounds => (currentBounds.Top >= bounds.Top) && (currentBounds.Left >= bounds.Left)).Count();
                screenBoundsList.Insert(index, currentBounds);
            }

            return screenBoundsList;
        }
Example #15
0
        public IEnumerable<long> Generate()
        {
            var primes = new List<long>();

            yield return 2;
            yield return 3;

            var value = 5L;
            var add4 = false;
            while(true)
            {
                var maxFactor = (int)Math.Sqrt(value) + 1;
                if (!primes.TakeWhile(prime => prime <= maxFactor).Any(prime => value % prime == 0))
                {
                    primes.Add(value);
                    yield return value;
                }

                value += (add4 ? 4 : 2);
                add4 = !add4;
            }
        }
        public IViewComponentResult Invoke(string linqQueryType)
        {
            var modelList = new List<SampleModel>()
            {
                new SampleModel { Prop1 = "Hello", Prop2 = "World" },
                new SampleModel { Prop1 = linqQueryType, Prop2 = "Test" },
            };

            switch (linqQueryType) {
                case "Where":
                    return View(modelList.Where(e => e != null));

                case "Take":
                    return View(modelList.Take(2));

                case "TakeWhile":
                    return View(modelList.TakeWhile(a => a != null));

                case "Union":
                    return View(modelList.Union(modelList));

                case "SelectMany":
                    var selectManySampleModelList = new List<SelectManySampleModel>
                    {
                        new SelectManySampleModel {
                            TestModel =
                                new List<SampleModel> { new SampleModel { Prop1 = "Hello", Prop2 = "World" } } },
                        new SelectManySampleModel {
                            TestModel = 
                                new List<SampleModel> { new SampleModel{ Prop1 = linqQueryType, Prop2 = "Test" } } }
                    };

                    return View(selectManySampleModelList.SelectMany(a => a.TestModel));
            };

            return View(modelList.Select(e => e));
        }
        public static void Main()
        {
            List<int> collection = new List<int> {1, 2, 3, 4, 6, 11, 3};

            Console.WriteLine(string.Join(", ", collection.TakeWhile(x => x < 10)));
        }
        //
        // Pull off messages from the Queue, batch them up and send them all across
        //
        private void ElasticsearchSender()
        {
            // Force an inital flush
            DateTime lastFlushTime = DateTime.MinValue;

            LogManager.GetCurrentClassLogger()
                            .Info("{0}: Elasticsarch Output To {1} Ready", Thread.CurrentThread.ManagedThreadId, string.Join(",", _hosts));

            using (var syncHandle = new ManualResetEventSlim())
            {
                // Execute the query
                while (!Stop)
                {
                    if (!CancelToken.IsCancellationRequested)
                    {
                        try
                        {
                            int messageCount = 0;
                            List<JObject> messages = new List<JObject>();

                            // Lets get whats in the queue
                            lock (_locker)
                            {
                                messageCount = _jsonQueue.Count;

                                // Time to flush?
                                if (messageCount >= _flushSize || (DateTime.UtcNow - lastFlushTime).Seconds >= _idleFlushTimeSeconds)
                                {
                                    messages = _jsonQueue.Take(messageCount).ToList();
                                    _jsonQueue.RemoveRange(0, messageCount);
                                    if (messages.Count > 0)
                                        _manager.IncrementMessageCount(messages.Count);
                                }
                            }

                            // We have some messages to work with
                            if (messages.Count > 0)
                            {
                                var client = getClient();

                                LogManager.GetCurrentClassLogger()
                                    .Debug("Sending {0} Messages to {1}", messages.Count, string.Join(",", _hosts));
                                // This loop will process all messages we've taken from the queue
                                // that have the same index and type (an elasticsearch requirement)
                                do
                                {
                                    try
                                    {
                                        // Grab all messages with same index and type (this is the whole point, group the same ones)
                                        var bulkTypeName = this._parameters.GetTypeName(messages[0]);
                                        var bulkIndexName = this._parameters.GetIndexName(messages[0]);

                                        IEnumerable<JObject> bulkItems =
                                            messages.TakeWhile(
                                                message =>
                                                    String.Compare(bulkTypeName, _parameters.GetTypeName(message), false) == 0 &&
                                                    String.Compare(bulkIndexName, _parameters.GetIndexName(message), false) == 0);

                                        // Send the message(s), if the are successfully sent, they
                                        // are removed from the queue
                                        lastFlushTime = transmitBulkData(bulkItems, bulkIndexName, bulkTypeName, client, lastFlushTime, messages);

                                        GC.Collect();
                                    }
                                    catch (Exception ex)
                                    {
                                        LogManager.GetCurrentClassLogger().Error(ex);
                                        break;
                                    }
                                } while (messages.Count > 0);
                            }
                            GC.Collect();
                            if (!Stop)
                            {
                                syncHandle.Wait(TimeSpan.FromMilliseconds(_interval), CancelToken);
                            }
                        }
                        catch (OperationCanceledException)
                        {
                            break;
                        }
                        catch (Exception ex)
                        {
                            LogManager.GetCurrentClassLogger().Error(ex);
                        }
                    }
                }
            }

            LogManager.GetCurrentClassLogger()
                          .Info("{0}: Elasticsarch Output To {1} Terminated", Thread.CurrentThread.ManagedThreadId, string.Join(",", _hosts));
        }
        private bool posh()
        {
            List<Tuple<int, int>> degree = new List<Tuple<int, int>>();
            for(int i = 0; i < v; ++i)
            {
                Tuple<int, int> pair = new Tuple<int, int>(i, graph.AdjacentDegree(i));
                degree.Add(pair);
            }
            degree.Sort((x, y) => x.Item2.CompareTo(y.Item2));

            int mid = (v - 1) / 2;
            for (int k = 0; k < mid; ++k)
            {
                if (!(degree.TakeWhile(item => item.Item2 < k).Count()<k))
                {
                    return false;
                }
            }
            if (v % 2 == 1 && degree.TakeWhile(item => item.Item2 == mid).Count() > mid)
            {
                return false;
            }
            return true;
        }
Example #20
0
        public static IEnumerable<long> Primes(long count)
        {
            var memoized = new List<long>();
            long sqrt = 1;
            var primes = PotentialPrimes().Where(x =>
            {
                sqrt = GetSqrtCeiling(x, sqrt);
                return !memoized
                            .TakeWhile(y => y <= sqrt)
                            .Any(y => x % y == 0);
            });

            var current = 1;
            foreach (long prime in primes)
            {
                //Get x number prime
                if (current == count)
                {
                    Debug.WriteLine(prime);
                    yield return prime;
                    break;
                }
                current++;
                //end get x number prime
                yield return prime;
                memoized.Add(prime);
            }
        }
Example #21
0
 float ComputePosY(ref List<Txt> txts)
 {
     // Considering a vertical margin of 15% of the height
     float Y = 0;
     var heightMargin = (float)MetroSlideshow.WindowHeight * 0.15;
     var stackHeightTextOnTopItThis = txts.TakeWhile(x => x.Id < Id).Sum(x => x.RowHeight);
     Y = (float)heightMargin + stackHeightTextOnTopItThis;
     return Y;
 }
Example #22
0
 List<IMessage> TruncateMessages(List<IMessage> msgs)
 {
     // we remove msg to recents because their is no time synchronisation between azure VMs
     DateTime dateLimit = DateTime.Now - limitDateDiff;
     return msgs.TakeWhile(m => m.Date < dateLimit).ToList();    // TODO : improve performance
 }
        /// <summary> Constructor for a new instance of the Thematic_Headings_AdminViewer class </summary>
        /// <param name="User"> Authenticated user information </param>
        /// <param name="Current_Mode"> Mode / navigation information for the current request </param>
        /// <param name="Thematic_Headings"> Headings under which all the highlighted collections on the home page are organized </param>
        /// <param name="Code_Manager"> List of valid collection codes, including mapping from the Sobek collections to Greenstone collections</param>
        /// <param name="Tracer">Trace object keeps a list of each method executed and important milestones in rendering</param>
        /// <remarks> Postback from handling an edit or new thematic heading is handled here in the constructor </remarks>
        public Thematic_Headings_AdminViewer(User_Object User,
            SobekCM_Navigation_Object Current_Mode,
            List<Thematic_Heading> Thematic_Headings,
			Aggregation_Code_Manager Code_Manager,
            Custom_Tracer Tracer)
            : base(User)
        {
            Tracer.Add_Trace("Thematic_Headings_AdminViewer.Constructor", String.Empty);

            // Get the current list of thematic headings
            thematicHeadings = Thematic_Headings;

            // Save the mode
            currentMode = Current_Mode;

            // Set action message to nothing to start
            actionMessage = String.Empty;

            // If the user cannot edit this, go back
            if ((!user.Is_System_Admin) && ( !user.Is_Portal_Admin ))
            {
                currentMode.Mode = Display_Mode_Enum.My_Sobek;
                currentMode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                currentMode.Redirect();
                return;
            }

            // Handle any post backs
            if (currentMode.isPostBack)
            {
                try
                {
                    // Pull the standard values from the form
                    NameValueCollection form = HttpContext.Current.Request.Form;
                    string save_value = form["admin_heading_tosave"];
                    string action_value = form["admin_heading_action"];

                    // Switch, depending on the request
                    if (action_value != null)
                    {
                        switch (action_value.Trim().ToLower())
                        {
                            case "edit":
                                string new_name = form["form_heading_name"];
                                if (new_name != null)
                                {
                                    int id = Convert.ToInt32(save_value);
                                    int order = 1 + Thematic_Headings.TakeWhile(ThisHeading => ThisHeading.ThematicHeadingID != id).Count();
                                    if (SobekCM_Database.Edit_Thematic_Heading(id, order, new_name, Tracer) < 1)
                                    {
                                        actionMessage = "Unable to edit existing thematic heading";
                                    }
                                    else
                                    {
                                        // For thread safety, lock the thematic headings list
                                        lock (Thematic_Headings)
                                        {
                                            // Repopulate the thematic headings list
                                            SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer);
                                        }

                                        actionMessage = "Thematic heading edits saved";
                                    }
                                }
                                break;

                            case "delete":
                                int thematicDeleteId = Convert.ToInt32(save_value);
                                if (!SobekCM_Database.Delete_Thematic_Heading(thematicDeleteId, Tracer))
                                {
                                    // Set action message
                                    actionMessage = "Unable to delete existing thematic heading";
                                }
                                else
                                {
                                    // For thread safety, lock the thematic headings list
                                    lock (Thematic_Headings)
                                    {
                                        // Remove this thematic heading from the list
                                        int i = 0;
                                        while (i < Thematic_Headings.Count)
                                        {
                                            if (Thematic_Headings[i].ThematicHeadingID == thematicDeleteId)
                                                Thematic_Headings.RemoveAt(i);
                                            else
                                                i++;
                                        }
                                    }

                                    // Set action message
                                    actionMessage = "Thematic heading deleted";
                                }
                                break;

                            case "new":
                                int new_order = Thematic_Headings.Count + 1;
                                int newid = SobekCM_Database.Edit_Thematic_Heading(-1, new_order, save_value, Tracer);
                                if ( newid  < 1)
                                    actionMessage = "Unable to save new thematic heading";
                                else
                                {
                                    // For thread safety, lock the thematic headings list
                                    lock (Thematic_Headings)
                                    {
                                        // Repopulate the thematic headings list
                                        SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer);
                                    }

                                    // Add this blank thematic heading to the code manager
                                    Code_Manager.Add_Blank_Thematic_Heading(newid);

                                    actionMessage = "New thematic heading saved";
                                }
                                break;

                            case "moveup":
                                string[] moveup_split = save_value.Split(",".ToCharArray());
                                int moveup_id = Convert.ToInt32(moveup_split[0]);
                                int moveup_order = Convert.ToInt32(moveup_split[1]);
                                if (moveup_order > 1)
                                {
                                    Thematic_Heading themeHeading = Thematic_Headings[moveup_order - 1];
                                    if (themeHeading.ThematicHeadingID == moveup_id)
                                    {
                                        // For thread safety, lock the thematic headings list
                                        lock (Thematic_Headings)
                                        {
                                            // Move this thematic heading up
                                            Thematic_Headings.Remove(themeHeading);
                                            Thematic_Headings.Insert(moveup_order - 2, themeHeading);
                                            int current_order = 1;
                                            foreach (Thematic_Heading thisTheme in Thematic_Headings)
                                            {
                                                SobekCM_Database.Edit_Thematic_Heading(thisTheme.ThematicHeadingID, current_order, thisTheme.ThemeName, Tracer);
                                                current_order++;
                                            }

                                            // Repopulate the thematic headings list
                                            SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer);
                                        }
                                    }
                                }
                                break;

                            case "movedown":
                                string[] movedown_split = save_value.Split(",".ToCharArray());
                                int movedown_id = Convert.ToInt32(movedown_split[0]);
                                int movedown_order = Convert.ToInt32(movedown_split[1]);
                                if (movedown_order < Thematic_Headings.Count)
                                {
                                    Thematic_Heading themeHeading = Thematic_Headings[movedown_order - 1];
                                    if (themeHeading.ThematicHeadingID == movedown_id)
                                    {
                                        // For thread safety, lock the thematic headings list
                                        lock (Thematic_Headings)
                                        {
                                            // Move this thematic heading down
                                            Thematic_Headings.Remove(themeHeading);
                                            Thematic_Headings.Insert(movedown_order, themeHeading);
                                            int current_order = 1;
                                            foreach (Thematic_Heading thisTheme in Thematic_Headings)
                                            {
                                                SobekCM_Database.Edit_Thematic_Heading(thisTheme.ThematicHeadingID, current_order, thisTheme.ThemeName, Tracer);
                                                current_order++;
                                            }

                                            // Repopulate the thematic headings list
                                            SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer);
                                        }
                                    }
                                }
                                break;

                        }
                    }
                }
                catch (Exception)
                {
                    actionMessage = "Unknown error caught while handling your reqeust";
                }
            }
        }
Example #24
0
		public static int GetRepetitionIndex(this ParseParsedIndex i, List<ParsedElement> allParsedElements)
		{
			//incidentally, this method computes exactly the same as ParseParsedIndex.GetRepetitionIndex(NotationMatch<TDomain>, RepetitionParseForm) but in a completely different manner
			return allParsedElements.TakeWhile(parsedElement => parsedElement.ParseIndex < i).Count(parsedElement => parsedElement.ParseIndex.Element == i.Element);
		}
 static void Main()
 {
     List<int> list = new List<int>() { 1, 2, 3, 4, 6, 11, 3 };
     Console.WriteLine(string.Join(", ", list.TakeWhile(x => x < 10)));
 }
Example #26
0
 /// <summary>
 /// Crops data if id found
 /// </summary>
 /// <param name="data">List of media data</param>
 /// <param name="stopatMediaId">The media id without the _user suffix</param>
 /// <returns>true if id found, false otherwise</returns>
 private static bool CropDataIfIdFound(List<Models.Media> data, string stopatMediaId)
 {
     if (stopatMediaId == null)
     {
         return false;
     }
     int count = data.Count;
     data = data.TakeWhile(x => x.Id != stopatMediaId).ToList();
     return count != data.Count;
 }
Example #27
0
        /// <summary>
        /// Sends message (from template in parameter)
        /// </summary>
        /// <param name="package">Package with initial data</param>
        public void SendPackage(Package package)
        {
            // Divide to packages
            var packages = new List<Package>();
            _messages.Add(new Package
            {
                Id = FreeId,
                MessageCreatedOn = TickNumber
            });

            if (package.SizeTotal() <= SizeMaxPackage)  // If message is in size like one package
            {
                package.FromNow = package.From;
                package.Id = FreeId;
                package.MyBufIdx = Nodes[package.From].Buffer.Count;
                package.Sent = 0;
                package.PartIdx = 0;
                package.TickGeneratedOn = TickNumber;  // For statistics
                package.CreatedOn = TickNumber;        // For statistics
                packages.Add(package);
                SendedMessagePart = 1;    // For external world

                if (package.IsDatagram) DatagramsSent++;
                else VirtualSent++;
            }
            else   // If bigger
            {
                // Divide message to packages
                var sizeMaxInf = SizeMaxPackage - Package.SizeHeader;
                var packagesNumber = Convert.ToInt32(Math.Ceiling(package.SizeInformation / (double)sizeMaxInf));

                if (package.IsDatagram) DatagramsSent += packagesNumber;
                else VirtualSent += packagesNumber;

                SendedMessagePart = packagesNumber;    // For external world
                var firstBufIdx = Nodes[package.From].Buffer.Count;
                for (var i = 0; i < packagesNumber - 1; i++)    // Several the same packages
                    packages.Add(new Package
                    {
                        To = package.To,
                        FromNow = package.From,
                        From = package.From,
                        IsDatagram = package.IsDatagram,
                        Id = FreeId,
                        PartIdx = i,
                        SizeInformation = sizeMaxInf,
                        MyBufIdx = firstBufIdx + i,
                        Sent = 0,
                        Parts = packagesNumber,
                        TickGeneratedOn = TickNumber,  // For statistics
                        CreatedOn = TickNumber         // For statistics
                    });

                // Last package can be lesser in size
                var sizeLastInf = package.SizeInformation % sizeMaxInf;
                packages.Add(new Package
                {
                    To = package.To,
                    FromNow = package.From,
                    From = package.From,
                    IsDatagram = package.IsDatagram,
                    Id = FreeId,
                    PartIdx = packagesNumber - 1,
                    SizeInformation = sizeLastInf,
                    MyBufIdx = firstBufIdx + packagesNumber - 1,
                    Sent = 0,
                    Parts = packagesNumber,
                    TickGeneratedOn = TickNumber,  // For statistics
                    CreatedOn = TickNumber         // For statistics
                });
            }

            // Add packages while it isn't filled
            foreach (var pack in packages.TakeWhile(pack => BufferSize > Nodes[package.From].Buffer.Count))
                Nodes[package.From].Buffer.Add(pack);

            // Add new packages to buffer
            //Nodes[package.From].Buffer.AddRange(packages);

            FreeId++;
        }
        private static List<EventListModel> SortAndLimitTo20(List<EventListModel> upcomingEvents)
        {
            upcomingEvents.Sort((e1, e2) => e1.Date.CompareTo(e2.Date));

            var upcomingEventsLimited = new List<EventListModel>();
            int[] counter = { 0 };
            foreach (var upcomingEvent in upcomingEvents.TakeWhile(upcomingEvent => counter[0] < 20))
            {
                upcomingEventsLimited.Add(upcomingEvent);
                counter[0]++;
            }
            return upcomingEventsLimited;
        }
Example #29
0
File: HUD.cs Project: nemec/4Realms
        internal void update()
        {
            tickCount = (tickCount + 1) % TicksPerScroll;
            if (onScreen.Count > 0 && tickCount == 0)
            {
                foreach (Text t in onScreen)
                {
                    t.Pos.Y -= 1;
                }

                Sprite fst = onScreen.First();
                if (fst.Pos.Y < Pos.Y)
                {
                    This.Game.CurrentLevel.RemoveSprite(fst);
                    onScreen.RemoveAt(0);
                }
            }
            if (buffer.Count != 0)
            {
                // We have room to scroll another line of text
                if (onScreen.Count == 0 ||
                    onScreen.Last().Pos.Y + onScreen.Last().GetAnimation().Height + TextSpacing <
                        Pos.Y + GetAnimation().Height - onScreen.Last().GetAnimation().Height)
                {
                    int width = GetAnimation().Width;
                    string toDisplay;

                    if (String.Join("", buffer.Take(2)) == "\n\n")
                    {
                        toDisplay = " ";
                        buffer.RemoveRange(0, 2);
                    }
                    else
                    {
                        buffer = buffer.SkipWhile(x => char.IsWhiteSpace(x)).ToList();
                        IEnumerable<char> pendingDisplay = buffer.TakeWhile((ch, ix) =>
                            theme.TextFont.MeasureString(
                                String.Join("", buffer.Take(ix + 1)).Trim()).X < width &&
                            ch != '\n');

                        if (SplitOnWhitespace &&
                            buffer.Count > pendingDisplay.Count() &&
                            buffer[pendingDisplay.Count()] != '\n')
                        {
                            // Find first instance of whitespace at end
                            pendingDisplay = pendingDisplay.Reverse().SkipWhile(x => !char.IsWhiteSpace(x)).Reverse();
                        }

                        toDisplay = String.Join("", pendingDisplay).Trim();
                        buffer.RemoveRange(0, pendingDisplay.Count());
                    }

                    Text line = new Text("text", theme.TextFont, toDisplay.ToString());
                    line.DisplayColor = theme.TextColor;
                    line.Pos = new Vector2(Pos.X, Pos.Y + GetAnimation().Height - line.GetAnimation().Height);
                    line.Static = true;
                    line.ZOrder = 101;
                    onScreen.Add(line);
                }
            }
        }
Example #30
0
        private List<string> GetEvents(string channel)
        {
            Subscribe(channel);
            var headers = new WebHeaderCollection {{"method", "1"}};
            var gameDataRequest = powRequest(2, headers);
            if (string.IsNullOrWhiteSpace(gameDataRequest))
            {
                Debug.WriteLine("[Bet365] Null string");
                return null;
            }
            var gameData = gameDataRequest.Split((char) 0x01);

            var newParse = gameDataRequest.Split('|');
            var oldParse = gameData[gameData.Length - 1].Split((char) 0x7c);
            var gameDateList = new List<string>(100);
            if (newParse.Length == oldParse.Length)
                return default(List<string>);
            if (newParse.Length > oldParse.Length)
            {
                gameDateList = newParse.ToList();
                var countDeleteElems = gameDateList.TakeWhile(str => !str.Contains("CL")).Count();
                gameDateList.RemoveRange(0, countDeleteElems);
            }
            else
            {
                gameDateList = oldParse.ToList();
                var countDeleteElems = gameDateList.TakeWhile(str => !str.Contains("CL")).Count();
                gameDateList.RemoveRange(0, countDeleteElems);
            }
            if (gameDateList.Count == 0)
            {
                Debug.WriteLine("[Bet365]gameDateListNull: " + gameDataRequest);
                return null;
            }
            var initialCL = parameterizeLine(gameDateList[0]);
            var paramsDic = new Dictionary<string, string>();
            if (initialCL != null)
            {
                initialCL.TryGetValue("CL", out paramsDic);
            }
            else
            {
                Debug.WriteLine("[Bet365] InitialCl is null. Data from server: " + gameDataRequest);
            }
            /*if (paramsDic == null)
            {
                Debug.WriteLine("[Bet365] InitialCl is null. Data from server: " + gameDataRequest);
                return null;
            }*/
            Debug.WriteLine("[Bet365] InitialCl is good. Data from server: " + gameDataRequest);
            var events = new List<string>(5);
            var isTennis = false;
            var isFirst = true;
            foreach (var data in gameDateList)
            {
                if (isFirst)
                {
                    isFirst = false;
                    continue;
                }

                var lineData = parameterizeLine(data);
                if (lineData == null)
                    continue;
                if (!isTennis)
                {
                    if (!lineData.ContainsKey("CL"))
                        continue;
                    isTennis = true;
                    continue;
                }
                if (lineData.ContainsKey("CL"))
                {
                    break;
                }
                if (lineData.ContainsKey("CL"))
                {
                    break;
                }
                if (lineData.ContainsKey("EV"))
                {
                    var Id = "";
                    Dictionary<string, string> tmp;
                    lineData.TryGetValue("EV", out tmp);

                    if (tmp != null) tmp.TryGetValue("ID", out Id);
                    else Debug.WriteLine("[Bet365]No id in parseline. Continue");

                    if (Id == null) Debug.WriteLine("[Bet365] ID IS NULL");
                    if ((Id != null) && (Id.Trim().Length == 18))
                    {
                        events.Add(Id.Trim());
                    }
                }
            }
            Unsubscribe(channel);
            return events;
        }