Example #1
0
        public async Task<IEnumerable<IGameServer>> GetServersAsync(MasterServerRequest masterServerRequest)
        {
            var endPoints = new List<IPEndPoint>();

            var packet = 0;
            using (var client = SteamAgent.GetUdpClient(_endpoint))
            {
                while (!masterServerRequest.MaximumPackets.HasValue || packet < masterServerRequest.MaximumPackets.Value)
                {
                    var request = GetRequest(endPoints.LastOrDefault(), masterServerRequest.Region, masterServerRequest.Filters);
                    var response = await SteamAgent.RequestResponseAsync(client, request, IpEndPointLength);

                    packet++;

                    var packetEndPoints = ReadEndPointsFromPacket(response);
                    endPoints.AddRange(packetEndPoints);

                    if (endPoints.Last().IsEmpty())
                    {
                        break;
                    }
                }
            }

            return endPoints.Take(endPoints.Count - 1).Select(e => new GameServer(e));
        }
        public void LazyLoadOperationWillHandleIncludes()
        {
            var ids = new List<string>();
            using (var session = ShardedDocumentStore.OpenSession())
            {
                for (int i = 1; i <= 4; i++)
                {
                    var entity = new User {Name = ids.LastOrDefault()};
                    session.Store(entity);
                    ids.Add(entity.Id);
                }
                session.SaveChanges();
            }
            using (var session = ShardedDocumentStore.OpenSession())
            {
                var result1 = session.Advanced.Lazily
                    .Include("Name")
                    .Load<User>(ids[1]);
                var result2 = session.Advanced.Lazily
                    .Include("Name")
                    .Load<User>(ids[3]);

                Assert.NotNull(result1.Value);
                Assert.NotNull(result2.Value);
                Assert.True(session.Advanced.IsLoaded(result1.Value.Name));
                Assert.True(session.Advanced.IsLoaded(result2.Value.Name));
            }
        }
        /// <summary>
        /// Проверяет, будут или есть сегодня занятия
        /// Если их сегодня не было или не будет позже текущего времени
        /// то будет выводится расписание на следующий день
        /// </summary>
        public bool IsTherePeriods(List<Period> sheduleToday, DateTime selectedDate)
        {
            if (sheduleToday != null)
            {
                Period lastPeriod = sheduleToday.LastOrDefault();
                if (lastPeriod != null)
                {
                    string endLastPeriod = lastPeriod.Time;
                    int index = endLastPeriod.IndexOf('-');
                    string[] list = endLastPeriod.Substring(index + 1, endLastPeriod.Length - index - 1).Split(':');

                    DateTime endStudyTime;
                    try
                    {
                        endStudyTime = new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day,
                            Convert.ToInt32(list[0]), Convert.ToInt32(list[1]), 0);
                    }
                    catch (FormatException)
                    {
                        endStudyTime = new DateTime();
                    }

                    return (endStudyTime >= DateTime.Now);
                }
                return false;
            }
            return false;
        }
Example #4
0
        /// <summary>
        /// Brute force approach that checks every odd number.
        /// By dividing the number to every prime number before that, we can check whether the number is prime or not.
        /// </summary>
        /// <returns>Returns the 10001th prime number</returns>
        public static int Solition1()
        {
            int counter = 0, number = 2;

            var primes = new List<int>();

            while (counter != PRIME_NO)
            {
                bool isPrime = true;

                // If remainder is 0, it is not a prime
                foreach (var p in primes)
                {
                    if (number % p == 0)
                        isPrime = false;
                }

                if (isPrime)
                {
                    primes.Add(number);
                    counter++;
                }

                // For any number different than 2, increment by 2, since other primes are all odd
                if (number == 2)
                    number += 1;
                else
                    number += 2;
            }

            return primes.LastOrDefault();
        }
        internal static EnumDeclarationSyntax AddEnumMemberTo(EnumDeclarationSyntax destination, IFieldSymbol enumMember, CodeGenerationOptions options)
        {
            var members = new List<SyntaxNodeOrToken>();
            members.AddRange(destination.Members.GetWithSeparators());

            var member = GenerateEnumMemberDeclaration(enumMember, destination, options);

            if (members.Count == 0)
            {
                members.Add(member);
            }
            else if (members.LastOrDefault().CSharpKind() == SyntaxKind.CommaToken)
            {
                members.Add(member);
                members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
            }
            else
            {
                var lastMember = members.Last();
                var trailingTrivia = lastMember.GetTrailingTrivia();
                members[members.Count - 1] = lastMember.WithTrailingTrivia();
                members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(trailingTrivia));
                members.Add(member);
            }

            return destination.EnsureOpenAndCloseBraceTokens()
                .WithMembers(SyntaxFactory.SeparatedList<EnumMemberDeclarationSyntax>(members));
        }
        public List<Station> Process(StationDirection direction)
        {
            var stationDirectionList = new List<List<Station>>();
            var stationsHtmlDocument = GetHtmlDocument();
            var stationsTable = GetStationTables(stationsHtmlDocument);

            if (stationsTable != null && stationsTable.Count > 0)
            {
                foreach (var tbl in stationsTable)
                {
                    var stationsForward = new List<Station>();
                    var rows = GetRows(tbl);
                    if (rows != null && rows.Count > 0)
                    {
                        stationDirectionList.Add(GetStations(rows));
                    }
                }
            }

            switch (direction)
            {
                case StationDirection.Backward:
                    return stationDirectionList.LastOrDefault();

                case StationDirection.Forward:
                default:
                    return stationDirectionList.FirstOrDefault();
            }
        }
Example #7
0
        public static void CalculateStatistics(this StatisticsItem item, List<LocationTrack> dayTrackList, LocationTrack lastTrack)
        {
            dayTrackList.Sort((t1, t2) => t1.TimeStamp.CompareTo(t2.TimeStamp));
            LocationTrack lastSaved = dayTrackList.LastOrDefault();
            if (lastSaved == null)
            {
                return;
            }

            if (lastSaved.TimeStamp.AddMinutes(10) < lastTrack.TimeStamp)
            {
                //Difference too much
                return;
            }

            double? distance = lastTrack.Location.Distance(lastSaved.Location);
            if (!distance.HasValue)
            {
                return;
            }

            decimal co2Index = GetCo2Index(lastTrack.Speed);
            decimal distanceValue = Convert.ToDecimal(distance.Value);
            decimal co2InKilograms = 0.15m * co2Index * distanceValue / (1000.0m);
            const decimal co2RecycleInOneDay = 44.0m / 365.0m;

            decimal result = co2InKilograms/co2RecycleInOneDay;
            item.Day = lastTrack.TimeStamp.Date;
            item.UserProfile = lastTrack.UserProfile;
            item.Value += result;
            item.Consumer = "Car";
        }
        public BlogsByUserViewModel(string username)
        {
            // Get back to the original name before url conversion
            BlogUsername = username.Replace(ContentGlobals.BLOGDELIMMETER, " ");

            using (var context = new DataContext())
            {

                // Get User based on authorid
                TheBlogUser = context.BlogUsers.FirstOrDefault(x => x.Username == BlogUsername);

                MaxBlogCount = BlogListModel.GetBlogSettings().MaxBlogsOnHomepageBeforeLoad;
                BlogTitle = BlogListModel.GetBlogSettings().BlogTitle;

                BlogsByUser = context.Blogs.Where(x => x.Author == BlogUsername && x.IsActive)
                            .OrderByDescending(blog => blog.Date)
                            .Take(MaxBlogCount)
                            .ToList();

                // Try permalink first
                TheBlog = BlogsByUser.FirstOrDefault(x => x.Author == BlogUsername);

                if (BlogsByUser.Count > 0)
                {
                    LastBlogId = BlogsByUser.LastOrDefault().BlogId;
                }
            }
        }
        /// <summary>
        /// Adds the original instructions to a given method body.
        /// </summary>
        /// <param name="IL">The <see cref="CilWorker"/> responsible for the target method body.</param>
        public void Emit(CilWorker IL)
        {
            var originalInstructions = new List<Instruction>(_oldInstructions);
            Instruction lastInstruction = originalInstructions.LastOrDefault();

            if (lastInstruction != null && lastInstruction.OpCode == OpCodes.Ret)
            {
                // HACK: Convert the Ret instruction into a Nop
                // instruction so that the code will
                // fall through to the epilog
                lastInstruction.OpCode = OpCodes.Br;
                lastInstruction.Operand = _endLabel;
            }

            foreach (Instruction instruction in (IEnumerable<Instruction>) originalInstructions)
            {
                if (instruction.OpCode != OpCodes.Ret || instruction == lastInstruction)
                    continue;

                if (lastInstruction == null)
                    continue;

                // HACK: Modify all ret instructions to call
                // the epilog after execution
                instruction.OpCode = OpCodes.Br;
                instruction.Operand = lastInstruction;
            }

            // Emit the original instructions
            foreach (Instruction instruction in originalInstructions)
            {
                IL.Append(instruction);
            }
        }
Example #10
0
 /// <summary>
 /// Beginning at the end, of the set, return all elements until the element after the element which satifies the condition [stopAt]
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="orderedSet"></param>
 /// <param name="stopAt"></param>
 /// <returns></returns>
 static IEnumerable<TestBuilder> Filter(List<TestBuilder> orderedSet, Func<TestBuilder, bool> stopAt)
 {
     var first = orderedSet.LastOrDefault(stopAt);
     return first == null ?
         orderedSet :
         orderedSet.Skip(orderedSet.LastIndexOf(first));
 }
Example #11
0
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            var tcs = new TaskCompletionSource<object>();

            context.ApplicationInstance.CompleteRequest();
            var clientId = new Guid(context.Request["clientId"]);

            var jsons = new List<CommandMessage>();

            var bus = SheepJaxComet.PollingCommandBus;
            var obs = bus.GetObservable(clientId).Replay();
            var subscription = obs.Connect();
            obs.TakeUntil(Observable.Interval(LongPollTimeout))
                .TakeUntil(obs.Take(1).Delay(BatchInterval))
                .Subscribe(jsons.Add, context.AddError, ()=>
                    {
                        try
                        {
                            subscription.Dispose();
                            context.Response.Write("[" + string.Join(",", jsons.Select(x => x.Message)) + "]");
                            bus.Consumed(jsons.LastOrDefault());
                        }
                        catch (Exception ex)
                        {
                            _logger.Error("SheepJax exception thrown while writing to long-polling connection", ex);
                        }
                        finally
                        {
                            tcs.SetResult(null);
                            cb(tcs.Task);
                        }
                    });

            return tcs.Task;
        }
Example #12
0
        private void ShowMissingFields()
        {
            var missingFields = new List<string>(3);

            if (string.IsNullOrEmpty(_userRegisterModel.Email))
                missingFields.Add("email");

            if (string.IsNullOrEmpty(_userRegisterModel.Password))
                missingFields.Add("password");

            if (string.IsNullOrEmpty(_userRegisterModel.ConfirmPassword))
                missingFields.Add("password confirmation");

            string joinedFields = string.Join(", ", missingFields.Take(missingFields.Count - 1)) + (missingFields.Count <= 1 ? "" : " and ") + missingFields.LastOrDefault();

            var messageBuilder = new StringBuilder("Field");

            if (missingFields.Count > 1)
                messageBuilder.Append("s");

            messageBuilder.Append($" {joinedFields} ");

            messageBuilder.Append(missingFields.Count > 1 ? "are" : "is");

            messageBuilder.Append(" missing.");
            
            _notifyPage.DisplayAlert(missingFields.Count > 1 ? "Missing fields" : "Mising field", messageBuilder.ToString());
        }
        public BlogArchiveViewModel()
        {
            using (var context = new DataContext())
            {
                Blogs = context.Blogs.Where(x => x.IsActive)
                            .OrderByDescending(blog => blog.Date)
                            .ToList();

                Grouped = (from p in Blogs
                    group p by
                        new {month = p.Date.ToString("MMM"), year = p.Date.ToString("yyyy"), dateString = p.Date.ToString("MM/yyyy")}
                        into d
                    select
                        String.Format(
                            "<a href=\"/blog?date={3}\" class=\"archive\">" +
                            "<span class=\"dateRef\" data-date=\"{3}\">{0} {1}</span>  ({2}) </a>",
                            d.Key.month, d.Key.year, d.Count(), d.Key.dateString)
                ).Take(MaxArchiveCount);

                if (Grouped.Any())
                {
                    LastMonth = Blogs.LastOrDefault().Date.ToString("MM/yyyy");
                }

            }
        }
Example #14
0
        public static IEnumerable<Page> Breadcrumb()
        {
            List<Page> breadcrumbPages = new List<Page>();
            var defaultPage = ServiceFactory.PageManager.GetDefaultPage(Page_Context.Current.PageRequestContext.Page.Site);
            if (defaultPage == Page_Context.Current.PageRequestContext.Page)
            {
                return breadcrumbPages;
            }
            var currentPage = Page_Context.Current.PageRequestContext.Page.Parent;
            while (currentPage != null)
            {
                currentPage = currentPage.LastVersion(Page_Context.Current.PageRequestContext.Site).AsActual();

                if (currentPage.Navigation != null
                    && currentPage.Navigation.ShowInCrumb.Value == true && currentPage.Published.HasValue && currentPage.Published.Value == true)
                {
                    breadcrumbPages.Add(currentPage);
                }

                currentPage = currentPage.Parent;
            }
            if (breadcrumbPages.LastOrDefault() != defaultPage)
            {
                defaultPage = defaultPage.AsActual();

                if (defaultPage.Navigation != null
                && defaultPage.Navigation.ShowInCrumb.Value == true && defaultPage.Published.HasValue && defaultPage.Published.Value == true)
                {
                    breadcrumbPages.Add(defaultPage);
                }
            }

            breadcrumbPages.Reverse();
            return breadcrumbPages;
        }
        public BlogRelatedViewModel(string title)
        {
            using (var context = new DataContext())
            {
                // Try permalink first
                TheBlog = context.Blogs.FirstOrDefault(x => x.PermaLink == title);

                MaxBlogCount = BlogListModel.GetBlogSettings().MaxBlogsOnHomepageBeforeLoad;

                // If no go then try title as a final back up
                if (TheBlog == null)
                {
                    title = title.Replace(Utils.ContentGlobals.BLOGDELIMMETER, " ");
                    TheBlog = context.Blogs.FirstOrDefault(x => x.Title == title);
                }

                if (TheBlog != null && TheBlog.Tags != null)
                {
                    List<string> tags = TheBlog.Tags.Split(',').ToList();
                    RelatedPosts = context.Blogs.Where(x => x.BlogId != TheBlog.BlogId && tags.Contains(x.Tags) && x.MainCategory == TheBlog.MainCategory)
                                    .OrderByDescending(blog => blog.Date)
                                    .Take(MaxBlogCount)
                                    .ToList();

                    if (RelatedPosts.Count > 0)
                    {
                        LastBlogId = RelatedPosts.LastOrDefault().BlogId;
                    }
                }
            }
        }
        private static System.Windows.Window GetActiveWindowForApplication(this System.Windows.Application application)
        {
            System.Windows.Window activeWindow = null;

            // CTL-687: Only allow windows that have an actual size (been shown at least once)
            Func<System.Windows.Window, bool> predicate = x => x.ActualWidth > 0d && x.ActualHeight > 0d;

            if (application != null && application.Windows.Count > 0)
            {
                var windowList = new List<System.Windows.Window>(application.Windows.Cast<System.Windows.Window>());

                activeWindow = windowList.FirstOrDefault(x => x.IsActive && predicate(x));
                if (activeWindow == null && windowList.Count == 1 && windowList[0].Topmost)
                {
                    activeWindow = windowList[0];
                }

                if (activeWindow == null)
                {
                    activeWindow = windowList.LastOrDefault(predicate);
                }
            }

            return activeWindow;
        }
Example #17
0
        public ProgressEstimator(IEnumerable<ProgressSampleUnit> samples)
        {
            _samples = samples.ToList();
            _lastSample = _samples.LastOrDefault();

            Calculate();
        }
Example #18
0
        internal static List<Block> CheckPostImport(List<Block> ret)
        {
            if (ret == null) return null;

            var lastImport = ret.LastOrDefault(r => r is Model.Import);
            var firstNonImport = ret.FirstOrDefault(r => !(r is Model.Import));

            if (lastImport == null || firstNonImport == null)
            {
                return ret;
            }

            var lix = ret.IndexOf(lastImport);
            var fnix = ret.IndexOf(firstNonImport);

            if (lix != -1 && fnix != -1)
            {
                if (fnix < lix)
                {
                    for (int i = fnix; i < ret.Count; i++)
                    {
                        if (ret[i] is Model.Import)
                        {
                            Current.RecordWarning(ErrorType.Parser, ret[i], "@import should appear before any other statements.  Statement will be moved.");
                        }
                    }
                }
            }

            return ret;
        }
		public void default_when_sequence_has_multiple_items()
		{
			var expectedResult = 5;
			var sequence = new List<Int32> { 1, 3, 7, 9, expectedResult }.NotNull();

			var actualResult = sequence.LastOrDefault();

			Assert.Equal(expectedResult, actualResult);
		}
Example #20
0
        static void Main(string[] args) {

            var redditApi = new RedditSharp.Reddit();
            var dailyProgrammer = redditApi.GetSubreddit("dailyprogrammer");

            var blankList = new[] { DailyProgrammerPost.Blank, DailyProgrammerPost.Blank, DailyProgrammerPost.Blank, };

            var grid = @"Easy | Intermediate | Hard | Weekly/Bonus

---- -| --------------| ------| -------------
| []() | []() | []() | **-** |
";

            var postsQuery = dailyProgrammer.Posts
                //.Take(20) // Used for development to speed things up
                //.ToList()
                //.OrderBy(p => p.Created)
                .Select(p => new DailyProgrammerPost(p.Title, p.Url.AbsoluteUri));

            List<DailyProgrammerPost> allPosts = new List<DailyProgrammerPost>();

            foreach (var post in postsQuery) {
                if (post.IsChallenge) {

                    allPosts.Add(post);
                }
                else if (post.IsWeekly || post.IsBonus) {

                    var week = allPosts.LastOrDefault()?.WeekNumber;

                    allPosts.Add(new DailyProgrammerPost(post.Title, post.Url, week));
                }
            }

            foreach (var weekOfPosts in allPosts.GroupBy(p => p.WeekNumber)) {

                var orderedPosts = weekOfPosts
                    .Where(p => p.IsChallenge)
                    .OrderBy(p => p.ChallengeDifficulty)
                    .Concat(weekOfPosts.Where(p => !p.IsChallenge))
                    .ToList();

                if (orderedPosts.Count() < 3) {

                    orderedPosts = orderedPosts.Concat(blankList).Take(3).ToList();
                }
                string extraAppend = orderedPosts.Count == 4 ? " |" : " | **-** |";

                var line = "| " + string.Join(" | ", orderedPosts) + extraAppend;

                grid += line + Environment.NewLine;
            }

            File.WriteAllText("c:\\\\temp\\DailyProgrammerReditOutput.txt", grid);
            Console.WriteLine("Done!");
            Console.ReadLine();
        }
 /// <summary>
 /// Gets the last LengthOfStay entry for the hospital. The last entry is the most recent quarter for which data is available.
 /// </summary>
 /// <param name="hospital"></param>
 /// <param name="lengthsOfStay"></param>
 /// <returns></returns>
 private double? GetLengthOfStay(myhospitals_contact_data hospital, List<emergencydept4hourlengthofstaymetadata> lengthsOfStay)
 {
     var los = lengthsOfStay.LastOrDefault(a => a.MyHospitalsId == hospital.Id);
     if (los != null && los.LessThan4HrsPct.HasValue)
     {
         return (double)los.LessThan4HrsPct.Value;
     }
     return null;
 }
Example #22
0
 private static string ToCsv(List<string> items)
 {
     var csvBuilder = new StringBuilder();
     for (int i = 0; i < items.Count() - 1; i++)
     {
         csvBuilder.Append("'" + items[i] + "', ");
     }
     csvBuilder.Append("'" + items.LastOrDefault() + "'");
     return csvBuilder.ToString();
 }
 public string sendLastSoundCommentFromIdLocation(int idLocation, string code)
 {
     List<Comments> comments = new List<Comments>();
     Comments lastComment = new Comments();
     comments = commentServices.findCommentByIdLocation(idLocation);
     lastComment = comments.LastOrDefault();
     if (lastComment != null)
         return lastComment.sound;
     else
         return null;
 }
 public static int getSMSPoint()
 {
     s26web.Models.s26webDataContext db = new s26web.Models.s26webDataContext();
     int point = 0;
     var result = db.SMS.Where(w=>w.sms_id.Equals("000")).OrderByDescending(o => o.CreateTime).FirstOrDefault();
     List<string> sms_content = new List<string>();
     if(result != null)
         sms_content = result.content.Split('|').ToList();
     point = Convert.ToInt32(sms_content.LastOrDefault());
     return point;
 }
		public async static Task<APISyncTracking> GetServerSyncTrackingByGetServiceType(string getServiceType)
		{
			List<APISyncTracking> returnRecordList = new List<APISyncTracking>();

			var db = DependencyService.Get<ISQLite>().GetAsyncConnection();

			await db.CreateTableAsync<APISyncTracking>();

			returnRecordList = await db.Table<APISyncTracking>().Where(row => row.GetServiceType == getServiceType).ToListAsync();

			return returnRecordList.LastOrDefault();
		}
        public ProcessOutboundRulesResult(List<OutboundRuleResult> processedResults)
        {
            _processedResults = processedResults;
            var lastMatchedResult = _processedResults.LastOrDefault(r => r.RuleMatched);

            if (lastMatchedResult != null)
            {
                _rewrittenResponseString = lastMatchedResult.RewrittenResponseString;
                //_finalAction = lastMatchedResult.ResultAction;
            }

        }
Example #27
0
        public void ProcessFrames(List<Rectangle> rectangles)
        {
            // deltafying Frames ( Last - First )
            var fRect = rectangles.FirstOrDefault();
            var lRect = rectangles.LastOrDefault();

            _dh = lRect.Height - fRect.Height;
            _dw = lRect.Width - fRect.Width;

            _dx = lRect.X - fRect.X;
            _dy = lRect.Y - fRect.Y;
        }
        public ProcessInboundRulesResult(Uri originalUri, List<InboundRuleResult> processedResults)
        {
            _originalUri = originalUri;
            _processedResults = processedResults;
            var lastMatchedResult = _processedResults.LastOrDefault(r => r.RuleMatched);

            if (lastMatchedResult != null)
            {
                _rewrittenUri = lastMatchedResult.RewrittenUri;
                _finalAction = lastMatchedResult.ResultAction;
                _itemId = lastMatchedResult.ItemId;
            }
        }
        public static JSObject Closest(this JSObject self, String selector)
        {
            List<JSObject> parents = new List<JSObject>();

            // Run the selector on the whole document
            self.Document().QuerySelectorAll(selector).Each(node => {
                // Test each node and see if it contains the child
                if(node.Contains(self)) parents.Add(node);
            });

            // Return the item on the end
            return parents.LastOrDefault();
        }
Example #30
0
 private void ExtractJumpedFieldsAndEndField(List<Field> jumpedFieldsAndLastWhite)
 {
     if (jumpedFieldsAndLastWhite.Any() && jumpedFieldsAndLastWhite.Last().HasStone == false)
     {
         _endField = jumpedFieldsAndLastWhite.LastOrDefault();
         jumpedFieldsAndLastWhite.RemoveAt(jumpedFieldsAndLastWhite.Count - 1);
         _jumpedFields = jumpedFieldsAndLastWhite;
     }
     else
     {
         _jumpedFields = new List<Field>();
     }
 }