/// <summary>
        /// Initialize a new instance of the ViewDrawMenuMonthCalendar class.
        /// </summary>
        /// <param name="provider">Reference to provider.</param>
        /// <param name="monthCalendar">Reference to owning month calendar entry.</param>
        public ViewDrawMenuMonthCalendar(IContextMenuProvider provider,
                                         KryptonContextMenuMonthCalendar monthCalendar)
        {
            _provider = provider;
            _monthCalendar = monthCalendar;
            _firstDayOfWeek = _monthCalendar.FirstDayOfWeek;
            _minDate = _monthCalendar.MinDate;
            _maxDate = _monthCalendar.MaxDate;
            _todayDate = _monthCalendar.TodayDate;
            _maxSelectionCount = _monthCalendar.MaxSelectionCount;
            _scrollChange = _monthCalendar.ScrollChange;
            _todayText = _monthCalendar.TodayText;
            _todayFormat = _monthCalendar.TodayFormat;
            _dimensions = _monthCalendar.CalendarDimensions;

            // Decide on the enabled state of the display
            _itemEnabled = provider.ProviderEnabled && _monthCalendar.Enabled;

            // Give the item object the redirector to use when inheriting values
            _monthCalendar.SetPaletteRedirect(provider.ProviderRedirector);

            // Create view that is used by standalone control as well as this context menu element
            _layoutMonths = new ViewLayoutMonths(provider, monthCalendar, provider.ProviderViewManager, this, provider.ProviderRedirector, provider.ProviderNeedPaintDelegate);
            _layoutMonths.CloseOnTodayClick = _monthCalendar.CloseOnTodayClick;
            _layoutMonths.ShowWeekNumbers = _monthCalendar.ShowWeekNumbers;
            _layoutMonths.ShowTodayCircle = _monthCalendar.ShowTodayCircle;
            _layoutMonths.ShowToday = _monthCalendar.ShowToday;
            _layoutMonths.Enabled = _itemEnabled;

            Add(_layoutMonths);
        }
示例#2
0
 public static void LoadDaysEvents(Day _day)
 {
     _day.events = new List<Event>();
     string line;
     string[] data;
     System.IO.StreamReader file = new System.IO.StreamReader(@"Assets\Data\Events\"+_day.dayName+".txt");
     while((line = file.ReadLine())!=null){
         data = line.Split('|');
         GameObject clone = GameObject.Instantiate(TimeManager.master.eventPrefab) as GameObject;
         clone.transform.parent = _day.transform;
         Event newEvent = clone.GetComponent<Event>();
         newEvent.eventName = data[0];
         newEvent.id = data[0];
         newEvent.dayName = _day.dayName;
         newEvent.startTime = float.Parse(data[1]);
         newEvent.secretEvent = bool.Parse(data[2]);
         newEvent.schedulable = bool.Parse(data[3]);
         Location location = Map.master.locationDictionary[data[4]];
         newEvent.location = location;
         if(data[5]!= ""){
             string[] people = data[5].Split('/');
             foreach(string person in people){
                 string[] personData = person.Split('~');
                 Person personScript = Population.master.peopleDictionary[personData[0]];
                 if(personData[1] == "true"){
                     newEvent.participants.Add(personScript);
                 } else {
                     newEvent.unwelcomed.Add(personScript);
                 }
             }
         }
         if(data[6]!= ""){
             string[] properties = data[6].Split('/');
             foreach(string property in properties){
                 string[] propertyData = property.Split('~');
                 if(propertyData[1] == "true"){
                     newEvent.requiredItemProperties.Add(propertyData[0]);
                 } else {
                     newEvent.unwantedItemProperties.Add(propertyData[0]);
                 }
             }
         }
         if(data[7]!= ""){
             string[] curEvents = data[7].Split('/');
             foreach(string curEvent in curEvents){
                 string[] eventData = curEvent.Split('~');
                 if(eventData[1] == "true"){
                     newEvent.precedingEvents.Add(eventData[0]);
                 } else {
                     newEvent.deterringEvents.Add(eventData[0]);
                 }
             }
         }
         if(data.Length>8) newEvent.eventHappened = bool.Parse(data[8]);
         if(data.Length>9) newEvent.conversation = data[9];
         if(data.Length>10) newEvent.outcome = data[10];
         _day.events.Add(newEvent);
     }
     file.Close();
 }
示例#3
0
        public void SaveDate(Day day)
        {
            //first check that the notes is not already in repo

            var t = CheckDayForNotes(day.Date);
            if (t == day.Notes)
            {}
            else
            {
                //if new post, then remove old one
                var el = Repo.XPathSelectElement(string.Format("Appointment/Date[text()='{0}']/..", day.Date.ToString("yyyy-MM-dd")));
                if (el != null)
                {
                    el.Remove();
                    Repo.Save(repoPath);
                }
                if (!string.IsNullOrEmpty(day.Notes))
                {
                    var appointement = new XElement("Appointment");
                    appointement.Add(new XElement("Date", day.Date.ToString("yyyy-MM-dd")));
                    appointement.Add(new XElement("Content", day.Notes));
                    Repo.Add(appointement);
                    Repo.Save(repoPath);

                }
            }
        }
        /// <summary>
        /// Adds time to specific day of the week
        /// </summary>
        /// <param name="hour">Hours worked</param>
        /// <param name="min">Minites worked</param>
        /// <param name="d">The day of the week </param>
        public void AddTime(string inHour, string inMin, Day d)
        {
            int hour;
            int min;
            hour = CheckHour(inHour);
            min = CheckMin(inMin);

            switch (d)
            {
                case Day.Monday:
                    monTime = new TimeSpan(hour, min, 0);
                    break;
                case Day.Tuesday:
                    tueTime = new TimeSpan(hour, min, 0);
                    break;
                case Day.Wendsday:
                    wedTime = new TimeSpan(hour, min, 0);
                    break;
                case Day.Thursday:
                    thurTime = new TimeSpan(hour, min, 0);
                    break;
                case Day.Friday:
                    friTime = new TimeSpan(hour, min, 0);
                    break;
                case Day.Saturday:
                    satTime = new TimeSpan(hour, min, 0);
                    break;
                case Day.Sunday:
                    sunTime = new TimeSpan(hour, min, 0);
                    break;
            }
            TotalTime();
        }
示例#5
0
 public WeeksBuilder OnDay(DayOfWeek day)
 {
     switch(day)
     {
         case DayOfWeek.Sunday:
             _days = Day.SUNDAY;
             break;
         case DayOfWeek.Monday:
             _days = Day.MONDAY;
             break;
         case DayOfWeek.Tuesday:
             _days = Day.TUESDAY;
             break;
         case DayOfWeek.Wednesday:
             _days = Day.WEDNESDAY;
             break;
         case DayOfWeek.Thursday:
             _days = Day.THURSDAY;
             break;
         case DayOfWeek.Friday:
             _days = Day.FRIDAY;
             break;
         case DayOfWeek.Saturday:
             _days = Day.SATURDAY;
             break;
     }
     return this;
 }
示例#6
0
 public DayManager(DataContext db, Day day, Week week, DateTime date)
 {
     this.db = db;
     this.week = week;
     this.day = day;
     this.date = date;
 }
示例#7
0
        public void CreateGroupForNewDay(GroupBaseDto group, bool isMorning)
        {
            var newDay = new Day() { Date = date, IsMorning = isMorning };

            var entity = db.Groups.Find(group.Id);
            newDay.Group = entity;
        }
示例#8
0
 public NextDayResult(Day day)
 {
     Number = day.Number;
     Weather = day.Weather;
     ForecastMessage = day.Event.ForecastMessage;
     LemonadeCost = day.LemonadeCost;
 }
示例#9
0
    public void buildCity(Day currentDay)
    {
        if(loadedDay != null){
            for (int i = 0; i < loadedDay.TspCase.Nodes.Length; i++)
            {
                Vector2 node = loadedDay.TspCase.Nodes[i];
                GameObject b = buildings[(int)node.x, (int)node.y];
                DestroyImmediate(b.GetComponent<Building>());
                //Destroy(truck);
            }
        }
        for (int i = 0; i < currentDay.TspCase.Nodes.Length; i++)
        {
            Vector2 node = currentDay.TspCase.Nodes[i];
            Building b = buildings[(int)node.x, (int)node.y].AddComponent<Building>();
            b.Position = i;
            if(i==0 && !rate){
                //b.transform.position.y + distance.y/2 + streetSize/2
                vectorPosition = new Vector3(b.transform.position.x,b.transform.position.y + 9,b.transform.position.z);
                truck=Instantiate(truck,vectorPosition,truck.transform.rotation)as GameObject;
                truck.GetComponent<Vehicle>().widthBlock=distance.x;

                truck.GetComponent<Vehicle>().heigthBlock=9;
                truck.GetComponent<Vehicle>().setStretSize(streetSize);
                rate=true;

        }
        loadedDay = currentDay;

        }
    }
示例#10
0
文件: Person.cs 项目: cleverxy/csharp
 public Person()
     :this(18, "Noname")
 {
     navbatKuni = Day.Mon;
     addr = "N/A";
     phone = "N/A";
 }
示例#11
0
 /// <summary>
 /// (1) New customers arrive at your ticket booth and tell you
 /// what movie they'd like to see (so keep it in mind ;-)
 /// </summary>
 /// <param name="runtime">Movie's runtime in minutes</param>
 /// <param name="day">day of the week (enum)</param>
 /// <param name="isParquet">true if seating category is 'parquet' (and not 'loge')</param>
 /// <param name="is3D">true if the movie's shown in 3D</param>
 public void StartPurchase(int runtime, Day day, bool isParquet, bool is3D)
 {
     _tickets = new List<Ticket>();
     _runtime = runtime;
     _day = day;
     _isParquet = isParquet;
     _is3D = is3D;
 }
示例#12
0
 public void GenerateSolution()
 {
     for (int i = 0; i < days.Length; i++)
     {
         days[i] = new Day();
         days[i].GenerateRoutes(ordersCounter);
     }
 }
示例#13
0
 public CongestionRate(string description, Day day, VehicleType vehicle, decimal rate, DateTime start, DateTime end)
 {
     Description = description;
     Day = day;
     Vehicle = vehicle;
     Rate = rate;
     Start = start;
     End = end;
 }
示例#14
0
 public static DayModel MapEntityToModel(Day entity)
 {
     return new DayModel
     {
         Code = entity.Code,
         Value = entity.Value,
         Description = entity.Description
     };
 }
 public void InsertOrUpdate(Day day)
 {
     if (day.Id == default(int)) {
         // New entity
         context.Days.Add(day);
     } else {
         // Existing entity
         context.Entry(day).State = EntityState.Modified;
     }
 }
 private void D_DidEndDay( Day sender )
 {
     sender.DidEndDay -= this.D_DidEndDay;
     this._messenger.Send( new ClearOutputParagraphMessage() );
     this._messenger.Send( new PrintMessage( $"Current player stats summary:" ) );
     //_messenger.Send( new PrintMessage( $"{_psof.CreateStringFromPlayerStats( _player )}" ) );
     this._messenger.Send( new PrintMessage(this._psof.CreateTableFromPlayerStats(this._player ) ) );
     this._messenger.Send( new DecisionMessage( new Decision( "Continue...", this.StartNewDay ) ) );
     //StartNewDay();
 }
示例#17
0
        public void Exactly24Test()
        {
            Day d = new Day(_date);

            d.SetHours(HourType.WORKING, 8);
            d.SetHours(HourType.SICK, 8);
            d.SetHours(HourType.VACATION, 8);

            Assert.AreEqual(24, d.GetTotalHours());
        }
        /// <summary>
        /// Returns -1 no conflict, Return 0 ignore first Return 1 ignore 2nd
        /// </summary>
        private static int IsConflictOrOverLap(ICongestionRate cp1, ICongestionRate cp2, Day day, VehicleType type)
        {
            var cr1DateRange = new DateRange(cp1.Start, cp1.End);
            var cr2DateRange = new DateRange(cp2.Start, cp2.End);

            var intersect = DateTimeIntersect.FindIntersect(cr1DateRange, cr2DateRange);

            if (intersect == null) return -1;

            return SelectTheMoreSpecific(cp1, cp2, day, type);
        }
示例#19
0
    private void setup(SI.Controls.Button btn_, Day day_)
    {
      btn_.Click += (x, y) =>
      {
        m_d = m_d.Toggle(day_);

        BtnCheckedAppearances.SetStatus(btn_, m_d.Has(day_));

        OnSelectionChanged(EventArgs.Empty);
      };
      BtnCheckedAppearances.SetChecked(btn_);
    }
示例#20
0
        public Day AddDay(DateTime date)
        {
            var day = new Day
            {
                Date = date.Date,
                Persons = new List<Person>()
            };

            Days.Add(day.Date, day);

            return day;
        }
        public IHttpActionResult PostDay(Day day)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Days.Add(day);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = day.Id }, day);
        }
        private static int SelectTheMoreSpecific(ICongestionRate cp1, ICongestionRate cp2, Day day, VehicleType type)
        {
            //Check Vehicle
            if (cp1.Vehicle == type) return 1;
            if (cp2.Vehicle == type) return 0;

            //Check Day of the week
            if (cp1.Day == day) return 1;
            if (cp2.Day == day) return 0;

            //OtherWise ignore the 2nd
            return 1;
        }
示例#23
0
        public void NegativeTest()
        {
            Day d = new Day(_date);

            try
            {
                d.SetHours(HourType.WORKING, -8);
            }
            catch (ArgumentOutOfRangeException e)
            {
                Assert.IsInstanceOfType(e, typeof(ArgumentOutOfRangeException));
            }
        }
 public Date(int year, int month, int day)
 {
     if (year >= 0)
     {
         Year = new Year(year);
     }
     if (month >= 0)
     {
         Month = new Month(month);
     }
     if (day >= 0)
     {
         Day = new Day(day);
     }
 }
示例#25
0
        public void Over24Test()
        {
            Day d = new Day(_date);

            try
            {
                d.SetHours(HourType.WORKING, 9);
                d.SetHours(HourType.SICK, 8);
                d.SetHours(HourType.VACATION, 8);
            }
            catch (ArgumentOutOfRangeException e)
            {
                Assert.IsInstanceOfType(e, typeof(ArgumentOutOfRangeException));
            }
        }
示例#26
0
        public TimeCard(DateTime StartDate)
        {
            if(StartDate.DayOfWeek != System.DayOfWeek.Sunday)
            {
                throw new ArgumentOutOfRangeException("StartDate", "StartDate must be a Sunday");
            }

            DateTime TempDate = TrimDay(StartDate);

            for (int x = 0; x < 14; x++)
            {
                _days[x] = new Day(TempDate);
                TempDate = TempDate.AddDays(1);
            }
        }
示例#27
0
        public void UpdateDays(IEnumerable<ForumPost> posts)
        {
            foreach (var post in posts)
            {
                Regex startOfDayRegex = new Regex(@"\[start of day [0-9]+\]", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                Regex endOfDayRegex = new Regex(@"\[end of day [0-9]+\]", RegexOptions.IgnoreCase | RegexOptions.Multiline);

                var startMatched = startOfDayRegex.Match(post.Content.ToString());
                var endMatched = endOfDayRegex.Match(post.Content.ToString());

                Regex numbersRegex = new Regex("[0-9]+");

                if (startMatched.Success)
                {
                    var numbers = numbersRegex.Match(startMatched.Value);

                    int dayNumber;
                    if (int.TryParse(numbers.Value, out dayNumber))
                    {
                        var day = new Day
                        {
                            Number = dayNumber,
                            StartForumPostNumber = post.ForumPostNumber,
                            EndForumPostNumber = string.Empty,
                        };

                        _repo.UpsertDay(day);
                    }
                }
                else if (endMatched.Success)
                {
                    var numbers = numbersRegex.Match(endMatched.Value);

                    int dayNumber;
                    if (int.TryParse(numbers.Value, out dayNumber))
                    {
                        Day day = _repo.FindDay(dayNumber);

                        if (day != null)
                        {
                            day.EndForumPostNumber = post.ForumPostNumber;

                            _repo.UpsertDay(day);
                        }
                    }
                }
            }
        }
        /**
         * Saves the given Day into the given SQLite DB
         */
        public static void save(SQLiteConnection m_dbConnection, Day day, bool isNew)
        {
            using (MemoryStream stream = new MemoryStream())
              {
            Serializer.Serialize<Day>(stream, day);
            string s64 = Convert.ToBase64String(stream.ToArray());

            string sql = isNew ? "INSERT INTO saratoga (date, data) VALUES (@date, @data)" :
                             "UPDATE saratoga SET data=@data WHERE date=@date";
            SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
            command.CommandType = System.Data.CommandType.Text;
            command.Parameters.Add(new SQLiteParameter("@date", day.getSqlDate()));
            command.Parameters.Add(new SQLiteParameter("@data", s64));
            command.ExecuteNonQuery();
              }
        }
        /// <summary>
        /// Generate days and bind them to repeater.
        /// </summary>
        protected void GenerateDays()
        {
            List<Day[]> weeks = new List<Day[]>();

            DateTime today = DateTime.Now.Date;
            DateTime firstDay = today.AddDays(1 - today.Day);
            DateTime afterDay = firstDay.AddMonths(1);

            DateTime day = firstDay;
            while (day < afterDay)
            {
                Day[] week = new Day[7];
                int filled = 0;
                if (day == firstDay)
                {
                    int needToFill = GetDayOfWeekNumber(day.DayOfWeek);
                    DateTime past = firstDay.AddDays(-needToFill);
                    for (; needToFill > 0; needToFill--)
                    {
                        Day entry = new Day();
                        entry.dayOfMonth = past.Day;
                        entry.dayOfWeek = past.DayOfWeek;
                        entry.isOtherMonth = true;
                        entry.isToday = false;
                        week[filled++] = entry;
                        past = past.AddDays(1);
                    }
                }
                for (; filled < 7; filled++)
                {
                    Day entry = new Day();
                    entry.dayOfMonth = day.Day;
                    entry.dayOfWeek = day.DayOfWeek;
                    entry.isToday = day == today;
                    entry.isOtherMonth = day.Month != firstDay.Month;
                    if (DayLinks.ContainsKey(day.Day) && !entry.isOtherMonth)
                    {
                        entry.dayLink = DayLinks[day.Day];
                    }
                    week[filled] = entry;
                    day = day.AddDays(1); // May as well roll over to the next month
                }
                weeks.Add(week);
            }
            rptrWeeks.DataSource = weeks;
            rptrWeeks.DataBind();
        }
示例#30
0
        public Task<bool> CreateDay(DayModel model)
        {
            if (!model.IsValidForNew())
                return null;

            var day = new Day
            {
                Code = model.Code,
                Value = model.Value,
                Description = model.Description
            };

            _dayRepository.Create(day);

            var result = _dayRepository.SaveChanges();
            return Task.FromResult(result);
        }
示例#31
0
        string LoadInput()
        {
            string INPUT_FILEPATH = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, $"../../../Solutions/Year{Year}/Day{Day.ToString("D2")}/input"));
            string INPUT_URL      = $"https://adventofcode.com/{Year}/day/{Day}/input";
            string input          = "";

            if (File.Exists(INPUT_FILEPATH) && new FileInfo(INPUT_FILEPATH).Length > 0)
            {
                input = File.ReadAllText(INPUT_FILEPATH);
            }
            else
            {
                try
                {
                    DateTime CURRENT_EST = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Utc).AddHours(-5);
                    if (CURRENT_EST < new DateTime(Year, 12, Day))
                    {
                        throw new InvalidOperationException();
                    }

                    using (var client = new WebClient())
                    {
                        client.Headers.Add(HttpRequestHeader.Cookie, Program.Config.Cookie);
                        input = client.DownloadString(INPUT_URL).Trim();
                        File.WriteAllText(INPUT_FILEPATH, input);
                    }
                }
                catch (WebException e)
                {
                    var statusCode = ((HttpWebResponse)e.Response).StatusCode;
                    if (statusCode == HttpStatusCode.BadRequest)
                    {
                        Console.WriteLine($"Day {Day}: Error code 400 when attempting to retrieve puzzle input through the web client. Your session cookie is probably not recognized.");
                    }
                    else if (statusCode == HttpStatusCode.NotFound)
                    {
                        Console.WriteLine($"Day {Day}: Error code 404 when attempting to retrieve puzzle input through the web client. The puzzle is probably not available yet.");
                    }
                    else
                    {
                        Console.WriteLine(e.ToString());
                    }
                }
                catch (InvalidOperationException)
                {
                    Console.WriteLine($"Day {Day}: Cannot fetch puzzle input before given date (Eastern Standard Time).");
                }
            }
            return(input);
        }
示例#32
0
        //private async Task SetupCore()
        //{
        //    await PrepareDB().ConfigureAwait(false);
        //    await GenerateScriptsForCreateAndDropSequence().ConfigureAwait(false);
        //    await AddTeams().ConfigureAwait(false);
        //    await AddDays().ConfigureAwait(false);
        //    await AddResults().ConfigureAwait(false);
        //    await AddMembers().ConfigureAwait(false);
        //    await AddJobs().ConfigureAwait(false);
        //    await AddReasons().ConfigureAwait(false);
        //    await AddJobTimes().ConfigureAwait(false);
        //}

        private async Task ReplaceDuplicateKey(IAsyncDao tDao, Day newDay, string newKey)
        {
            newDay.DayId = newKey;
            await tDao.InsertEntityAsync(newDay).ConfigureAwait(false);
        }
示例#33
0
 public static void SelectDay(this Month month, Day selectedDay)
 {
     UnSelectCurrentDay(month);
     SelectNewDay(selectedDay, month);
 }
示例#34
0
 public Weekly(int weeks, DateTime starting, DateTime?ending, Day days, DayOfWeek firstDayOfWeek) : base(weeks, starting, ending)
 {
     Days           = days;
     FirstDayOfWeek = firstDayOfWeek;
 }
        public ActionResult Create(RoomAllocation roomallocation)
        {
            Room   room   = db.Rooms.Find(roomallocation.RoomId);
            Course course = db.Courses.Find(roomallocation.CourseId);
            Day    day    = db.Days.Find(roomallocation.DayId);


            if (ModelState.IsValid)
            {
                int givenForm, givenEnd;

                try
                {
                    givenForm = ConvertTimeIntoInt(roomallocation.StartTime);
                }
                catch (Exception exception)
                {
                    if (TempData["ErroeMessage3"] == null)
                    {
                        TempData["ErroeMessage1"] = exception.Message;
                    }
                    TempData["ErrorMessage4"] = TempData["ErrorMessage3"];
                    ViewBag.DepartmentId      = new SelectList(db.Departments, "DepartmentId", "DepartmentCode", course.DepartmentId);
                    ViewBag.CourseId          = new SelectList(db.Courses.Where(c => c.DepartmentId == course.DepartmentId), "CourseId", "CourseCode", roomallocation.CourseId);
                    ViewBag.RoomId            = new SelectList(db.Rooms, "RoomId", "RoomName", roomallocation.RoomId);
                    ViewBag.DayId             = new SelectList(db.Days, "DayId", "DayName", roomallocation.DayId);
                    return(View(roomallocation));
                }

                try
                {
                    givenEnd = ConvertTimeIntoInt(roomallocation.EndTime);
                }
                catch (Exception anException)
                {
                    if (TempData["ErrorMessage3"] == null)
                    {
                        TempData["ErrorMessage2"] = anException.Message;
                    }
                    TempData["ErrorMessage5"] = TempData["ErrorMessage3"];
                    ViewBag.DepartmentId      = new SelectList(db.Departments, "DepartmentId", "DepartmentCode", course.DepartmentId);
                    ViewBag.CourseId          = new SelectList(db.Courses.Where(c => c.DepartmentId == course.DepartmentId), "CourseId", "CourseCode", roomallocation.CourseId);
                    ViewBag.RoomId            = new SelectList(db.Rooms, "RoomId", "RoomName", roomallocation.RoomId);
                    ViewBag.DayId             = new SelectList(db.Days, "DayId", "DayName", roomallocation.DayId);
                    return(View(roomallocation));
                }


                if (givenEnd < givenForm)
                {
                    TempData["Message"]  = "Class Should Start Before End (24 hours)";
                    ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentCode", course.DepartmentId);
                    ViewBag.CourseId     = new SelectList(db.Courses.Where(c => c.DepartmentId == course.DepartmentId), "CourseId", "CourseCode", roomallocation.CourseId);
                    ViewBag.RoomId       = new SelectList(db.Rooms, "RoomId", "RoomName", roomallocation.RoomId);
                    ViewBag.DayId        = new SelectList(db.Days, "DayId", "DayName", roomallocation.DayId);
                    return(View(roomallocation));
                }
                if (givenEnd == givenForm)
                {
                    TempData["Message"]  = "Class Should Start Before End (24 hours)";
                    ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentCode", course.DepartmentId);
                    ViewBag.CourseId     = new SelectList(db.Courses.Where(c => c.DepartmentId == course.DepartmentId), "CourseId", "CourseCode", roomallocation.CourseId);
                    ViewBag.RoomId       = new SelectList(db.Rooms, "RoomId", "RoomName", roomallocation.RoomId);
                    ViewBag.DayId        = new SelectList(db.Days, "DayId", "DayName", roomallocation.DayId);
                    return(View(roomallocation));
                }

                if ((givenForm < 0) || (givenEnd >= (24 * 60)))
                {
                    TempData["Message"]  = " 24 hours--format HH:MM";
                    ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentCode", course.DepartmentId);
                    ViewBag.CourseId     = new SelectList(db.Courses.Where(c => c.DepartmentId == course.DepartmentId), "CourseId", "CourseCode", roomallocation.CourseId);
                    ViewBag.RoomId       = new SelectList(db.Rooms, "RoomId", "RoomName", roomallocation.RoomId);
                    ViewBag.DayId        = new SelectList(db.Days, "DayId", "DayName", roomallocation.DayId);
                    return(View(roomallocation));
                }

                List <RoomAllocation> overLapList = new List <RoomAllocation>();

                var DayRoomAlocationList =
                    db.RoomAllocations.Include(c => c.Course)
                    .Include(d => d.Day)
                    .Include(r => r.Room)
                    .Where(r => r.RoomId == roomallocation.RoomId && r.DayId == roomallocation.DayId).ToList();

                foreach (var aDayRoomAllocatin in DayRoomAlocationList)
                {
                    int DbForm = ConvertTimeIntoInt(aDayRoomAllocatin.StartTime);
                    int DbEnd  = ConvertTimeIntoInt(aDayRoomAllocatin.EndTime);

                    if (
                        ((DbForm <= givenForm) && (givenForm < DbEnd)) ||
                        ((DbForm < givenEnd) && (givenEnd <= DbEnd)) ||
                        ((givenForm <= DbForm) && (DbEnd <= givenEnd))
                        )
                    {
                        overLapList.Add(aDayRoomAllocatin);
                    }
                }

                if (overLapList.Count == 0)
                {
                    roomallocation.RoomStatus = "Allocated";
                    db.RoomAllocations.Add(roomallocation);
                    db.SaveChanges();
                    TempData["Message"] = "Room : " + room.RoomName + " Allocated "
                                          + " for course : " + course.CourseCode + " From " + roomallocation.StartTime
                                          + " to " + roomallocation.EndTime + " on " + day.DayName;
                }
                else
                {
                    string message = "Room : " + room.RoomName + " Overlapped ";

                    foreach (var anOverlappedRoom in overLapList)
                    {
                        int dbForm = ConvertTimeIntoInt(anOverlappedRoom.StartTime);
                        int dbEnd  = ConvertTimeIntoInt(anOverlappedRoom.EndTime);

                        string overlapStart, overlapEnd;

                        if ((dbForm <= givenForm) && (givenForm < dbEnd))
                        {
                            overlapStart = roomallocation.StartTime;
                        }

                        else
                        {
                            overlapStart = anOverlappedRoom.StartTime;
                        }

                        if ((dbForm < givenEnd) && (givenEnd <= dbEnd))
                        {
                            overlapEnd = anOverlappedRoom.EndTime;
                        }

                        else
                        {
                            overlapEnd = anOverlappedRoom.EndTime;
                        }
                        message += " Course : " + anOverlappedRoom.Course.CourseCode + " Start Time : "
                                   + anOverlappedRoom.StartTime + " End Time : "
                                   + anOverlappedRoom.EndTime + " Overlapped from : ";
                        message += overlapStart + " To " + overlapEnd;
                    }
                    TempData["Message"] = message + " on " + day.DayName;

                    ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentCode");
                    ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentCode", course.DepartmentId);
                    ViewBag.CourseId     = new SelectList(db.Courses.Where(c => c.DepartmentId == course.DepartmentId), "CourseId", "CourseCode", roomallocation.CourseId);
                    ViewBag.RoomId       = new SelectList(db.Rooms, "RoomId", "RoomName", roomallocation.RoomId);
                    ViewBag.DayId        = new SelectList(db.Days, "DayId", "DayName", roomallocation.DayId);
                    return(View(roomallocation));
                }
                return(RedirectToAction("Create"));
            }

            ViewBag.CourseId     = new SelectList(db.Courses, "CourseId", "CourseCode", roomallocation.CourseId);
            ViewBag.DayId        = new SelectList(db.Days, "DayId", "DayName", roomallocation.DayId);
            ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentCode", roomallocation.DepartmentId);
            ViewBag.RoomId       = new SelectList(db.Rooms, "RoomId", "RoomName", roomallocation.RoomId);
            return(View(roomallocation));
        }
    public override void ExecuteBuild()
    {
        string   DayParam = ParseParamValue("Day");
        DateTime Day;
        string   FileName = ParseParamValue("FileName");

        // delete anything older than two weeks
        DateTime TwoWeeksAgo = DateTime.UtcNow.Subtract(new TimeSpan(14, 0, 0, 0));

        // The day we're passing in is running at midnight+ for the daily, so we actually want to label this as yesterday's report as far as the graph
        // since the utilization capture is actually getting from 12am the previous day to 12am today.
        // All builds run in that timeframe will be technically yesterday's builds.
        if (string.IsNullOrEmpty(DayParam))
        {
            Day = DateTime.Today.Add(new TimeSpan(1, 0, 0, 0));
            LogInformation("Day parameter not specified, defaulting to today's report: " + Day.Date.ToString("MM-dd-yyyy"));
        }
        else
        {
            if (!DateTime.TryParse(DayParam, out Day))
            {
                throw new AutomationException("Day was passed in an incorrect format. Format <mm/dd/yy>");
            }
            if (Day < TwoWeeksAgo)
            {
                throw new AutomationException("The day passed is more than two weeks in the past. The report would be deleted tomorrow. Not running.");
            }
        }
        if (string.IsNullOrEmpty(FileName))
        {
            throw new AutomationException("FileName not Specified!");
        }

        if (!File.Exists(FileName))
        {
            throw new AutomationException("Could not find file at path: " + FileName);
        }



        CommandUtils.ERunOptions Opts = CommandUtils.ERunOptions.Default | CommandUtils.ERunOptions.SpewIsVerbose;
        XmlDocument Reader            = new XmlDocument();

        // get all of the existing properties
        Reader.LoadXml(CommandUtils.RunAndLog("ectool", "--timeout 900 getProperties --path \"/projects/GUBP_V5/Generated/Utilization2\"", Options: Opts));
        // grab just the prop names
        XmlNodeList ExistingProps = Reader.GetElementsByTagName("propertyName");

        foreach (XmlNode prop in ExistingProps)
        {
            string   date = prop.InnerText.Replace("Report_", string.Empty);
            DateTime ExistingDate;
            if (!DateTime.TryParse(date, out ExistingDate))
            {
                LogWarning("Found property in Utilization properties that had a malformed name: " + prop.InnerText + ", remove this manually ASAP.");
                continue;
            }
            // delete anything older than two weeks
            if (ExistingDate < TwoWeeksAgo)
            {
                LogInformation("Deleting out-of-date property: " + prop.InnerText);
                CommandUtils.RunAndLog("ectool", string.Format("--timeout 900 deleteProperty --propertyName \"/projects/GUBP_V5/Generated/Utilization2/{0}\"", prop.InnerText), Options: Opts);
            }
        }
        // add today's
        LogInformation("Adding report: " + Day.Subtract(new TimeSpan(1, 0, 0, 0)).ToString("yyyy-MM-dd") + "->" + Day.ToString("yyyy-MM-dd"));
        CommandUtils.RunAndLog("ectool", string.Format("--timeout 900 setProperty \"/projects/GUBP_V5/Generated/Utilization2/Report_{0}\" --valueFile {1}", Day.Subtract(new TimeSpan(1, 0, 0, 0)).ToString("yyyy-MM-dd"), FileName), Options: Opts);
    }
示例#37
0
        public async Task <Workschedule> GenerateWS(IEnumerable <User> users, WorkScheduleNewDTO newWS)
        {
            foreach (var user in users)
            {
                var wsFromRepo = await GetUserWS(user.IdUser);

                var wsList = new List <Workschedule>();

                var userVac = await _context.Vacation
                              .Where(u => u.IdUserVac == user.IdUser)
                              .Include(a => a.IdAbsenceVacNavigation)
                              .Include(u => u.IdUserVacNavigation)
                              .ToListAsync();

                var vacList = VacationDaysToList(userVac);
                for (int i = 0; i < newWS.NumberOfWeeks; i++)
                {
                    var ws      = new Workschedule();
                    var dayList = new List <Day>();

                    foreach (var day in newWS.Day)
                    {
                        Day newDay;
                        var fromTime = day.FromTime.AddDays(i * 7);
                        var toTime   = day.ToTime.AddDays(i * 7);

                        var vacDay     = vacList.FirstOrDefault(d => d.FromTime.DayOfYear == fromTime.DayOfYear);
                        var currentDay = wsFromRepo.Day.FirstOrDefault(d => d.FromTime.DayOfYear == fromTime.DayOfYear);
                        if (vacDay != null)
                        {
                            newDay = vacDay;
                            if (newDay.Type == "Zastepstwo")
                            {
                                newDay.FromTime = fromTime;
                                newDay.ToTime   = toTime;
                            }

                            if (currentDay != null)
                            {
                                _context.Remove(currentDay);
                            }

                            dayList.Add(newDay);
                            await _context.Day.AddAsync(newDay);
                        }
                        else if (currentDay == null)
                        {
                            newDay = new Day
                            {
                                FromTime       = fromTime,
                                ToTime         = toTime,
                                IdWsNavigation = ws,
                                Type           = "Praca"
                            };

                            dayList.Add(newDay);
                            await _context.Day.AddAsync(newDay);
                        }
                        else if (currentDay.Type == "Praca")
                        {
                            newDay = new Day
                            {
                                FromTime       = fromTime,
                                ToTime         = toTime,
                                IdWsNavigation = ws,
                                Type           = "Praca"
                            };

                            _context.Remove(currentDay);
                            dayList.Add(newDay);
                            await _context.Day.AddAsync(newDay);
                        }
                    }
                    ws.IdUserNavigation = user;
                    ws.Day = dayList;

                    wsList.Add(ws);
                    await _context.Workschedule.AddAsync(ws);

                    await _context.SaveChangesAsync();
                }
            }
            return(null);
        }
示例#38
0
 public override int GetHashCode()
 {
     return(Channel.GetHashCode() ^ Day.GetHashCode());
 }
示例#39
0
 public Record(Day day, int kwh)
 {
     this.Day = day;
     this.kWh = kwh;
 }
示例#40
0
        public static Func <Day, double> CreateLinearInterpolatedInterestRateFunc(object excelValues, string excelArgumentName)
        {
            if (excelValues is ExcelMissing || excelValues is ExcelEmpty)
            {
                throw new ArgumentException(excelArgumentName + " hasn't been specified.");
            }

            if (!(excelValues is object[,] excelValuesArray))
            {
                throw new ArgumentException(excelArgumentName + " has been incorrectly entered. Argument value should be of a range with 2 columns, the first containing dates, the second containing numbers.");
            }

            if (excelValuesArray.GetLength(1) != 2)
            {
                throw new ArgumentException(excelArgumentName + " has been incorrectly entered. Argument value should be a range with 2 columns.");
            }

            var interestRatePoints = new List <(Day Date, double InterestRate)>();

            for (int i = 0; i < excelValuesArray.GetLength(0); i++)
            {
                if (excelValuesArray[i, 0] is ExcelEmpty || excelValuesArray[i, 0] is ExcelError)
                {
                    break;
                }

                if (!(excelValuesArray[i, 1] is double doubleValue))
                {
                    throw new ArgumentException($"Value in the second column of row {i} for argument {excelArgumentName} is not a number.");
                }

                DateTime curvePointDateTime = ObjectToDateTime(excelValuesArray[i, 0], $"Cannot create DateTime from value in first row of argument {excelArgumentName}.");

                interestRatePoints.Add((Date: Day.FromDateTime(curvePointDateTime), InterestRate: doubleValue));
            }

            if (interestRatePoints.Count < 2)
            {
                throw new ArgumentException(excelArgumentName + " must contain at least two points.");
            }

            Day firstDate = interestRatePoints.Min(curvePoint => curvePoint.Date);
            IEnumerable <double> maturitiesToInterpolate =
                interestRatePoints.Select(curvePoint => curvePoint.Date.OffsetFrom(firstDate) / 365.0);

            LinearSpline linearSpline = LinearSpline.Interpolate(maturitiesToInterpolate, interestRatePoints.Select(curvePoint => curvePoint.InterestRate));

            Day lastDate = interestRatePoints.Max(curvePoint => curvePoint.Date);

            double InterpolatedCurve(Day cashFlowDate)
            {
                if (cashFlowDate < firstDate || cashFlowDate > lastDate)
                {
                    throw new ArgumentException($"Interest rate for future cash flow {cashFlowDate} cannot be interpolated, as this date is outside of the bounds of the input rates curve.");
                }
                double maturity = (cashFlowDate - firstDate) / 365.0;

                return(linearSpline.Interpolate(maturity));
            }

            return(InterpolatedCurve);
        }
示例#41
0
 private void StartDay(Day day)
 {
     textBox.PlayText(new[] { day.textMessage });
 }
示例#42
0
 private void StartNextDay()
 {
     currentDayIndex++;
     currentDay = days[currentDayIndex];
     StartDay(currentDay);
 }
示例#43
0
 private void Start()
 {
     currentDay = days[0];
     StartDay(currentDay);
 }
示例#44
0
        public static ObservableCollection <Day> DaysTestData()
        {
            var ret = new ObservableCollection <Day>();


            ResultOfTheDay result1 = new ResultOfTheDay();

            result1.CompletedTasks.Add(new Task("Finish layout"));
            result1.CompletedTasks.Add(new Task("Fix design inconsistencies"));
            result1.CompletedTasks.Add(new Task("Clean up my mess"));
            result1.CompletedGoals.Add("Make something presentable");
            result1.CompletedGoals.Add("Sleep");
            result1.CompletedGoals.Add("Eat a lot");
            result1.TimeSpentWorking = 8.0;

            Day test1 = new Day(new DateTime(2000, 10, 10), result1, "I hoped to have completed everything today, but it just didn't happen.  Oh well, I had fun!", Color.Colors["Yellow"]);

            ResultOfTheDay result2 = new ResultOfTheDay();

            result2.CompletedTasks.Add(new Task("Evaluate project"));
            result2.CompletedTasks.Add(new Task("Design GUI"));
            result2.CompletedTasks.Add(new Task("Finish basic layout"));
            result2.CompletedTasks.Add(new Task("Finish navigation"));
            result2.CompletedGoals.Add("Pick a project");
            result2.TimeSpentWorking = 10.0;

            Day test2 = new Day(new DateTime(2010, 10, 9), result2, "I had a good start", Color.Colors["Orange"]);

            ResultOfTheDay result3 = new ResultOfTheDay();

            result3.CompletedTasks.Add(new Task("Another Task1"));
            result3.CompletedTasks.Add(new Task("Another Task2"));
            result3.CompletedGoals.Add("Another Goal1");
            result3.CompletedGoals.Add("Another Goal2");
            result3.CompletedGoals.Add("Another Goal3");
            result3.TimeSpentWorking = 10.0;

            Day test3 = new Day(new DateTime(2010, 10, 8), result3, "A really awesome comment, maybe even better than the last comment!", Color.Colors["Orange"]);

            ResultOfTheDay result4 = new ResultOfTheDay();

            result4.CompletedTasks.Add(new Task("Another Task1"));
            result4.CompletedTasks.Add(new Task("Another Task2"));
            result4.CompletedGoals.Add("Another Goal1");
            result4.CompletedGoals.Add("Another Goal2");
            result4.CompletedGoals.Add("Another Goal3");
            result4.TimeSpentWorking = 10.0;

            Day test4 = new Day(new DateTime(2010, 10, 7), result4, "This comment is really good.", Color.Colors["Orange"]);

            ResultOfTheDay result5 = new ResultOfTheDay();

            result5.CompletedTasks.Add(new Task("Finish layout"));
            result5.CompletedTasks.Add(new Task("Fix design inconsistencies"));
            result5.CompletedTasks.Add(new Task("Clean up my mess"));
            result5.CompletedGoals.Add("Make something presentable");
            result5.CompletedGoals.Add("Sleep");
            result5.CompletedGoals.Add("Eat a lot");
            result5.TimeSpentWorking = 8.0;

            Day test5 = new Day(new DateTime(2010, 10, 6), result5, "I did nothing today!", Color.Colors["Orange"]);

            ret.Add(test1);
            ret.Add(test2);
            ret.Add(test3);
            ret.Add(test4);
            ret.Add(test5);

            return(ret);
        }
示例#45
0
 public BuiltInFunctions()
 {
     // Text
     Functions["len"]         = new Len();
     Functions["lower"]       = new Lower();
     Functions["upper"]       = new Upper();
     Functions["left"]        = new Left();
     Functions["right"]       = new Right();
     Functions["mid"]         = new Mid();
     Functions["replace"]     = new Replace();
     Functions["rept"]        = new Rept();
     Functions["substitute"]  = new Substitute();
     Functions["concatenate"] = new Concatenate();
     Functions["char"]        = new CharFunction();
     Functions["exact"]       = new Exact();
     Functions["find"]        = new Find();
     Functions["fixed"]       = new Fixed();
     Functions["proper"]      = new Proper();
     Functions["search"]      = new Search();
     Functions["text"]        = new Text.Text();
     Functions["t"]           = new T();
     Functions["hyperlink"]   = new Hyperlink();
     Functions["value"]       = new Value();
     // Numbers
     Functions["int"] = new CInt();
     // Math
     Functions["abs"]         = new Abs();
     Functions["asin"]        = new Asin();
     Functions["asinh"]       = new Asinh();
     Functions["cos"]         = new Cos();
     Functions["cosh"]        = new Cosh();
     Functions["power"]       = new Power();
     Functions["sign"]        = new Sign();
     Functions["sqrt"]        = new Sqrt();
     Functions["sqrtpi"]      = new SqrtPi();
     Functions["pi"]          = new Pi();
     Functions["product"]     = new Product();
     Functions["ceiling"]     = new Ceiling();
     Functions["count"]       = new Count();
     Functions["counta"]      = new CountA();
     Functions["countblank"]  = new CountBlank();
     Functions["countif"]     = new CountIf();
     Functions["countifs"]    = new CountIfs();
     Functions["fact"]        = new Fact();
     Functions["floor"]       = new Floor();
     Functions["sin"]         = new Sin();
     Functions["sinh"]        = new Sinh();
     Functions["sum"]         = new Sum();
     Functions["sumif"]       = new SumIf();
     Functions["sumifs"]      = new SumIfs();
     Functions["sumproduct"]  = new SumProduct();
     Functions["sumsq"]       = new Sumsq();
     Functions["stdev"]       = new Stdev();
     Functions["stdevp"]      = new StdevP();
     Functions["stdev.s"]     = new Stdev();
     Functions["stdev.p"]     = new StdevP();
     Functions["subtotal"]    = new Subtotal();
     Functions["exp"]         = new Exp();
     Functions["log"]         = new Log();
     Functions["log10"]       = new Log10();
     Functions["ln"]          = new Ln();
     Functions["max"]         = new Max();
     Functions["maxa"]        = new Maxa();
     Functions["median"]      = new Median();
     Functions["min"]         = new Min();
     Functions["mina"]        = new Mina();
     Functions["mod"]         = new Mod();
     Functions["average"]     = new Average();
     Functions["averagea"]    = new AverageA();
     Functions["averageif"]   = new AverageIf();
     Functions["averageifs"]  = new AverageIfs();
     Functions["round"]       = new Round();
     Functions["rounddown"]   = new Rounddown();
     Functions["roundup"]     = new Roundup();
     Functions["rand"]        = new Rand();
     Functions["randbetween"] = new RandBetween();
     Functions["rank"]        = new Rank();
     Functions["rank.eq"]     = new Rank();
     Functions["rank.avg"]    = new Rank(true);
     Functions["quotient"]    = new Quotient();
     Functions["trunc"]       = new Trunc();
     Functions["tan"]         = new Tan();
     Functions["tanh"]        = new Tanh();
     Functions["atan"]        = new Atan();
     Functions["atan2"]       = new Atan2();
     Functions["atanh"]       = new Atanh();
     Functions["acos"]        = new Acos();
     Functions["acosh"]       = new Acosh();
     Functions["var"]         = new Var();
     Functions["varp"]        = new VarP();
     Functions["large"]       = new Large();
     Functions["small"]       = new Small();
     Functions["degrees"]     = new Degrees();
     // Information
     Functions["isblank"]    = new IsBlank();
     Functions["isnumber"]   = new IsNumber();
     Functions["istext"]     = new IsText();
     Functions["isnontext"]  = new IsNonText();
     Functions["iserror"]    = new IsError();
     Functions["iserr"]      = new IsErr();
     Functions["error.type"] = new ErrorType();
     Functions["iseven"]     = new IsEven();
     Functions["isodd"]      = new IsOdd();
     Functions["islogical"]  = new IsLogical();
     Functions["isna"]       = new IsNa();
     Functions["na"]         = new Na();
     Functions["n"]          = new N();
     // Logical
     Functions["if"]      = new If();
     Functions["iferror"] = new IfError();
     Functions["ifna"]    = new IfNa();
     Functions["not"]     = new Not();
     Functions["and"]     = new And();
     Functions["or"]      = new Or();
     Functions["true"]    = new True();
     Functions["false"]   = new False();
     // Reference and lookup
     Functions["address"] = new Address();
     Functions["hlookup"] = new HLookup();
     Functions["vlookup"] = new VLookup();
     Functions["lookup"]  = new Lookup();
     Functions["match"]   = new Match();
     Functions["row"]     = new Row()
     {
         SkipArgumentEvaluation = true
     };
     Functions["rows"] = new Rows()
     {
         SkipArgumentEvaluation = true
     };
     Functions["column"] = new Column()
     {
         SkipArgumentEvaluation = true
     };
     Functions["columns"] = new Columns()
     {
         SkipArgumentEvaluation = true
     };
     Functions["choose"]   = new Choose();
     Functions["index"]    = new Index();
     Functions["indirect"] = new Indirect();
     Functions["offset"]   = new Offset()
     {
         SkipArgumentEvaluation = true
     };
     // Date
     Functions["date"]             = new Date();
     Functions["today"]            = new Today();
     Functions["now"]              = new Now();
     Functions["day"]              = new Day();
     Functions["month"]            = new Month();
     Functions["year"]             = new Year();
     Functions["time"]             = new Time();
     Functions["hour"]             = new Hour();
     Functions["minute"]           = new Minute();
     Functions["second"]           = new Second();
     Functions["weeknum"]          = new Weeknum();
     Functions["weekday"]          = new Weekday();
     Functions["days360"]          = new Days360();
     Functions["yearfrac"]         = new Yearfrac();
     Functions["edate"]            = new Edate();
     Functions["eomonth"]          = new Eomonth();
     Functions["isoweeknum"]       = new IsoWeekNum();
     Functions["workday"]          = new Workday();
     Functions["networkdays"]      = new Networkdays();
     Functions["networkdays.intl"] = new NetworkdaysIntl();
     Functions["datevalue"]        = new DateValue();
     Functions["timevalue"]        = new TimeValue();
     // Database
     Functions["dget"]     = new Dget();
     Functions["dcount"]   = new Dcount();
     Functions["dcounta"]  = new DcountA();
     Functions["dmax"]     = new Dmax();
     Functions["dmin"]     = new Dmin();
     Functions["dsum"]     = new Dsum();
     Functions["daverage"] = new Daverage();
     Functions["dvar"]     = new Dvar();
     Functions["dvarp"]    = new Dvarp();
 }
示例#46
0
 public DayCell(Day day, Coordinate location, double size)
     : base(location, size, size)
 {
     this.day = day ?? throw new ArgumentNullException(nameof(day) + " can not be null");
 }
示例#47
0
 public static bool IsAbsence(this Day day)
 {
     return(day.DayType.Name != "Workday");
 }
示例#48
0
        void View_Drop(object sender, DragEventArgs e)
        {
            GridView[] DayViews    = { FirstDay, SecondDay, ThirdDay, AgendaList };
            GridView[] ItemSources = { FirstDay, SecondDay, ThirdDay, AddView, AgendaList };
            int        index       = -1;

            foreach (GridView Day in DayViews)
            {
                //放置的VIEW
                if (sender.Equals(Day))
                {
                    //放置的位置
                    index = Day.Items.IndexOf(rect);
                    //拖曳的ITEM
                    for (int i = DragItems.Count - 1; i >= 0; i--)
                    {
                        //拖曳的ITEM來源VIEW
                        foreach (GridView ItemSource in ItemSources)
                        {
                            int itemIndex = ItemSource.Items.IndexOf(DragItems.ElementAt(i));
                            if (itemIndex != -1)
                            {
                                object temp = ItemSource.Items.ElementAt(i);
                                ItemSource.Items.RemoveAt(itemIndex);
                                //Agendas.add()
                                NewAgenda();

                                /*
                                 * if (index != -1)
                                 * {
                                 *  Day.Items.Insert(index, CreateItem());
                                 * }
                                 * else
                                 * {
                                 *  Day.Items.Add(CreateItem());
                                 * }*/
                            }
                        }
                        if (IsAddNewItem)
                        {
                            int dayindex = -1;
                            IsAddNewItem = false;
                            //Day.Items.Add(CreateItem());
                            for (int j = 0; j < DayViews.Length; j++)
                            {
                                if (Day.Equals(DayViews[j]))
                                {
                                    dayindex = j;
                                }
                            }
                            if (dayindex == -1)
                            {
                            }
                            else if (dayindex < 3)
                            {
                                //<<<<<<< HEAD
                                DateTime leftTime  = firstDate.AddDays(dayindex);
                                DateTime rightTime = firstDate.AddDays(dayindex);

                                if (index == -1 && Day.Items.Count == 0)
                                {
                                    //新增第一筆資料
                                }
                                //else if (index==0)
                                //{
                                //    //抓右邊
                                //    rightTime = ((Agenda)((Day.Items[1] as GridView).Items[0] as StackPanel).Tag)._startDateTime.Value;
                                //    leftTime = ((Agenda)((Day.Items[1] as GridView).Items[0] as StackPanel).Tag)._startDateTime.Value;
                                //}
                                //else if (index == Day.Items.Count - 1 || index == -1 && Day.Items.Count != 0)
                                //{
                                //    //抓左邊
                                //    if (index == -1)
                                //    {
                                //        index = Day.Items.Count;
                                //    }
                                //    StackPanel a = (StackPanel)(Day.Items[index - 1] as GridView).Items[0];
                                //    Agenda Iagenda = (Agenda)((Day.Items[index - 1] as GridView).Items[0] as StackPanel).Tag;
                                //    rightTime = Iagenda.EndDateTime.Value;
                                //    leftTime = Iagenda.EndDateTime.Value;
                                //}
                                //else
                                //{
                                //    //抓兩邊
                                //    rightTime = ((Agenda)((Day.Items[index + 1] as GridView).Items[0] as StackPanel).Tag)._startDateTime.Value;
                                //    leftTime = ((Agenda)((Day.Items[index - 1] as GridView).Items[0] as StackPanel).Tag).EndDateTime.Value;
                                //}
                                //if (index == -1 && Day.Items.Count == 0)
                                //{
                                //    App.MyEditAgendaPage.SetStartDate(firstDate.AddDays(dayindex));
                                //    App.MyEditAgendaPage.SetEndDate(firstDate.AddDays(dayindex));
                                //    App.MyEditAgendaPage.SetNewState();
                                //    App.MyEditAgendaPage.SetPreviousPage(App.DailyPage);
                                //    Window.Current.Content = App.MyEditAgendaPage;
                                //}
                                App.MyEditAgendaPage.SetStartDate(firstDate.AddDays(dayindex));
                                App.MyEditAgendaPage.SetEndDate(firstDate.AddDays(dayindex));
                                App.MyEditAgendaPage.SetNewState();
                                App.MyEditAgendaPage.SetPreviousPage(App.DailyPage);
                                Window.Current.Content = App.MyEditAgendaPage;
                                //}
                                //else
                                //{
                                //    App.MyEditAgendaPage.SetStartDate(leftTime);
                                //    App.MyEditAgendaPage.SetEndDate(rightTime);
                                //    App.MyEditAgendaPage.SetNewState();
                                //    App.MyEditAgendaPage.SetPreviousPage(App.DailyPage);
                                //    Window.Current.Content = App.MyEditAgendaPage;
                                //}
                                //=======
                                //                                App.MyEditAgendaPage.SetStartDate(firstDate);
                                //                                App.MyEditAgendaPage.SetEndDate(firstDate);
                                //                                App.MyEditAgendaPage.SetNewState();
                                //                                App.MyEditAgendaPage.SetPreviousPage(App.DailyPage);
                                //                                Window.Current.Content = App.MyEditAgendaPage;
                                //                            }
                                //                            else if (dayindex == 1)
                                //                            {
                                //                                App.MyEditAgendaPage.SetStartDate(firstDate.AddDays(1));
                                //                                App.MyEditAgendaPage.SetEndDate(firstDate.AddDays(1));
                                //                                App.MyEditAgendaPage.SetNewState();
                                //                                App.MyEditAgendaPage.SetPreviousPage(App.DailyPage);
                                //                                Window.Current.Content = App.MyEditAgendaPage;
                                //                            }
                                //                            else if (dayindex == 2)
                                //                            {
                                //                                App.MyEditAgendaPage.SetStartDate(firstDate.AddDays(2));
                                //                                App.MyEditAgendaPage.SetEndDate(firstDate.AddDays(2));
                                //                                App.MyEditAgendaPage.SetNewState();
                                //                                App.MyEditAgendaPage.SetPreviousPage(App.DailyPage);
                                //                                //App.MyEditAgendaPage.
                                //                                Window.Current.Content = App.MyEditAgendaPage;
                                //>>>>>>> e6102835d3c1c886f6af430444fbd69730937cd3
                            }
                            else
                            {
                                //新增代辦事項
                            }
                        }
                    }
                }
            }
            foreach (GridView Day in DayViews)
            {
                Day.Items.Remove(rect);
            }
            rect = null;
        }
示例#49
0
        public async Task <Workschedule> GenerateUserWS(int userId, WorkScheduleNewDTO newWS, List <Day> vacList)
        {
            var user = await _context.User
                       .FirstOrDefaultAsync(u => u.IdUser == userId);

            var wsList     = new List <Workschedule>();
            var wsFromRepo = await GetUserWS(userId);

            for (int i = 0; i < newWS.NumberOfWeeks; i++)
            {
                var ws      = new Workschedule();
                var dayList = new List <Day>();

                foreach (var day in newWS.Day)
                {
                    Day newDay;
                    var fromTime = day.FromTime.AddDays(i * 7);
                    var toTime   = day.ToTime.AddDays(i * 7);

                    var vacDay     = vacList.FirstOrDefault(d => d.FromTime.DayOfYear == fromTime.DayOfYear);
                    var currentDay = wsFromRepo.Day.FirstOrDefault(d => d.FromTime.DayOfYear == fromTime.DayOfYear);
                    if (vacDay != null)
                    {
                        newDay = vacDay;
                        if (newDay.Type == "Zastepstwo")
                        {
                            newDay.FromTime = fromTime;
                            newDay.ToTime   = toTime;
                        }

                        if (currentDay != null)
                        {
                            _context.Remove(currentDay);
                        }

                        dayList.Add(newDay);
                        await _context.Day.AddAsync(newDay);
                    }
                    else if (currentDay == null)
                    {
                        newDay = new Day
                        {
                            FromTime       = fromTime,
                            ToTime         = toTime,
                            IdWsNavigation = ws,
                            Type           = "Praca"
                        };

                        dayList.Add(newDay);
                        await _context.Day.AddAsync(newDay);
                    }
                    else if (currentDay.Type == "Praca")
                    {
                        newDay = new Day
                        {
                            FromTime       = fromTime,
                            ToTime         = toTime,
                            IdWsNavigation = ws,
                            Type           = "Praca"
                        };

                        _context.Remove(currentDay);
                        dayList.Add(newDay);
                        await _context.Day.AddAsync(newDay);
                    }
                }
                ws.IdUserNavigation = user;
                ws.Day = dayList;

                wsList.Add(ws);
                await _context.Workschedule.AddAsync(ws);
            }
            await _context.SaveChangesAsync();

            var wsToReturn = await GetUserWS(userId);

            return(wsToReturn);
        }
示例#50
0
 public static void SelectDay(this MonthContainer monthContainer, Day selectedDay) => monthContainer._month.SelectDay(selectedDay);
示例#51
0
        /// <summary>Returns the string representation of the value of this instance.</summary>
        /// <param name="format">Format string using the usual characters to interpret custom datetime - as per standard DateTime custom formats</param>
        /// <returns>A string that represents the value of this instance.</returns>
        public String ToString(String format, IFormatProvider provider)
        {
            //parse and replace the format stuff
            MatchCollection matches = Regex.Matches(format, "([a-zA-z])\\1{0,}");

            for (int i = matches.Count - 1; i >= 0; i--)
            {
                Match m = matches[i];
                Int32 mIndex = m.Index, mLength = m.Length;

                if (mIndex > 0 && format[m.Index - 1] == '\\')
                {
                    if (m.Length == 1)
                    {
                        continue;
                    }
                    else
                    {
                        mIndex++;
                        mLength--;
                    }
                }
                switch (m.Value[0])
                {
                case 'y':
                    format = format.Substring(0, mIndex) + Year.ToString("D" + mLength) + format.Substring(mIndex + mLength);
                    break;

                case 'M':
                    if (mLength < 3)
                    {
                        String input2 = Month.ToString("D" + mLength);
                        format = format.Substring(0, mIndex) + input2 + format.Substring(mIndex + mLength);
                    }
                    else if (mLength == 3)
                    {
                        if (KSPDateStructure.CalendarType == CalendarTypeEnum.Earth)
                        {
                            format = format.Substring(0, mIndex) + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(Month) + format.Substring(mIndex + mLength);
                        }
                        else
                        if (KSPDateStructure.MonthCount < 1)
                        {
                            String input2 = Month.ToString("D" + mLength);
                            format = format.Substring(0, mIndex) + input2 + format.Substring(mIndex + mLength);
                        }
                        else
                        {
                            format = format.Substring(0, mIndex) + KSPDateStructure.Months[Month].ToString().Substring(0, 3) + format.Substring(mIndex + mLength);
                        }
                    }
                    else
                    {
                        if (KSPDateStructure.CalendarType == CalendarTypeEnum.Earth)
                        {
                            format = format.Substring(0, mIndex) + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(Month) + format.Substring(mIndex + mLength);
                        }
                        else
                        if (KSPDateStructure.MonthCount < 1)
                        {
                            String input2 = Month.ToString("D" + mLength);
                            format = format.Substring(0, mIndex) + input2 + format.Substring(mIndex + mLength);
                        }
                        else
                        {
                            format = format.Substring(0, mIndex) + KSPDateStructure.Months[Month] + format.Substring(mIndex + mLength);
                        }
                    }
                    break;

                case 'd':
                    format = format.Substring(0, mIndex) + Day.ToString("D" + mLength) + format.Substring(mIndex + mLength);
                    break;

                case 'h':
                    //how to do this one AM/PM Hours
                    String HalfDayTime = "";
                    switch (AMPM)
                    {
                    case AMPMEnum.AM:
                        HalfDayTime = Hour.ToString("D" + mLength.Clamp(1, (KSPDateStructure.HoursPerDay / 2).ToString().Length));
                        break;

                    case AMPMEnum.PM:
                        HalfDayTime = (Hour - (KSPDateStructure.HoursPerDay / 2)).ToString("D" + mLength.Clamp(1, (KSPDateStructure.HoursPerDay / 2).ToString().Length));
                        break;

                    case AMPMEnum.OddHoursPerDay:
                    default:
                        HalfDayTime = Hour.ToString("D" + mLength.Clamp(1, KSPDateStructure.HoursPerDay.ToString().Length));
                        break;
                    }

                    format = format.Substring(0, mIndex) + HalfDayTime + format.Substring(mIndex + mLength);
                    break;

                case 't':
                    if (AMPM != AMPMEnum.OddHoursPerDay)
                    {
                        format = format.Substring(0, mIndex) + AMPM.ToString().ToLower() + format.Substring(mIndex + mLength);
                    }
                    break;

                case 'T':
                    if (AMPM != AMPMEnum.OddHoursPerDay)
                    {
                        format = format.Substring(0, mIndex) + AMPM.ToString().ToUpper() + format.Substring(mIndex + mLength);
                    }
                    break;

                case 'H':
                    format = format.Substring(0, mIndex) + Hour.ToString("D" + mLength.Clamp(1, KSPDateStructure.HoursPerDay.ToString().Length)) + format.Substring(mIndex + mLength);
                    break;

                case 'm':
                    format = format.Substring(0, mIndex) + Minute.ToString("D" + mLength.Clamp(1, KSPDateStructure.MinutesPerHour.ToString().Length)) + format.Substring(mIndex + mLength);
                    break;

                case 's':
                    format = format.Substring(0, mIndex) + Second.ToString("D" + mLength.Clamp(1, KSPDateStructure.SecondsPerMinute.ToString().Length)) + format.Substring(mIndex + mLength);
                    break;

                default:
                    break;
                }
            }

            //Now strip out the \ , but not multiple \\
            format = Regex.Replace(format, "\\\\(?=[a-z])", "");

            return(format);
            //if (KSPDateStructure.CalendarType == CalendarTypeEnum.Earth)
            //    return String.Format(format, _EarthDateTime);
            //else
            //    return String.Format(format, this); //"TEST";
        }
示例#52
0
 public EnumTest(Day day)
 {
     this.day = day;
 }
示例#53
0
 /// <summary>
 ///  Associates Win API day of week values with DateTime values.
 /// </summary>
 private DayOfWeek CastDayToDayOfWeek(Day day)
 => day switch
 {
        //Nadat op de index op een dag is geklikt kom die hier binnen en wordt voor die dag een festivalDay gemaakt
        public ActionResult ConcertOverview(int dayId)
        {
            Day day = dayRepository.GetDay(dayId);

            return(View(concertRepository.CreateFestivalDay(day)));
        }
示例#55
0
 public override void set(Day d)
 {
     set(d.Pressure);
 }
示例#56
0
        public ConsumptionsPage(Day day)
        {
            pageDay = day;
            SetConsumptions();

            List <Consumption> consumptions = App.GetDataBase().GetConsumptions(pageDay).ToList();
            var consumptionInfoBox          = new DataTemplate(typeof(ConsumptionCustomCell));

            // Page content
            Label plus = new Label
            {
                Text              = "+",
                FontSize          = 25,
                HorizontalOptions = LayoutOptions.CenterAndExpand
            };

            Label equal = new Label
            {
                Text              = "=",
                FontSize          = 25,
                HorizontalOptions = LayoutOptions.CenterAndExpand
            };

            StackLayout topLabels = new StackLayout
            {
                Children =
                {
                    personalDailyConsumptions,
                    plus,
                    cooperativeDailyConsumptions,
                    equal,
                    dailyConsumptions
                },
                Orientation = StackOrientation.Horizontal
            };

            ListView consumptionsList = new ListView
            {
                ItemsSource  = consumptions,
                ItemTemplate = consumptionInfoBox
            };

            Button addConsButton = new Button
            {
                Text            = "Add consumption",
                BackgroundColor = Color.White,
                FontSize        = 20
            };

            StackLayout pageStack = new StackLayout
            {
                Children =
                {
                    topLabels,
                    consumptionsList,
                    addConsButton
                }
            };

            // Modal window
            Label modalLabel = new Label
            {
                BackgroundColor         = Color.Black,
                TextColor               = Color.White,
                HorizontalOptions       = LayoutOptions.Fill,
                FontSize                = 20,
                HorizontalTextAlignment = TextAlignment.Center,
                VerticalTextAlignment   = TextAlignment.Center,
                Text = "Add consumption"
            };

            EntryCell consNameEntry = new EntryCell
            {
                Placeholder = "Name"
            };

            SwitchCell consCoop = new SwitchCell
            {
                Text = "Cooperative consumptions?"
            };

            EntryCell consPriceEntry = new EntryCell
            {
                Placeholder = "Price"
            };

            Button okButton = new Button
            {
                Text = "OK",
                HorizontalOptions = LayoutOptions.FillAndExpand
            };

            Button cancelButton = new Button
            {
                Text = "Cancel",
                HorizontalOptions = LayoutOptions.FillAndExpand
            };

            StackLayout modalButtons = new StackLayout
            {
                Children =
                {
                    okButton,
                    cancelButton
                },
                Orientation       = StackOrientation.Horizontal,
                HorizontalOptions = LayoutOptions.FillAndExpand
            };

            TableView modalTable = new TableView
            {
                Intent = TableIntent.Form,
                Root   = new TableRoot
                {
                    new TableSection
                    {
                        consNameEntry,
                        consCoop,
                        consPriceEntry
                    }
                }
            };

            ContentView modalContent = new ContentView
            {
                IsVisible       = false,
                BackgroundColor = Color.White,
                Content         = new StackLayout
                {
                    Children =
                    {
                        modalLabel,
                        modalTable,
                        modalButtons
                    }
                }
            };

            // Page content + Modal window
            Content = new AbsoluteLayout
            {
                Children =
                {
                    pageStack,
                    modalContent
                }
            };

            AbsoluteLayout.SetLayoutBounds(pageStack, new Rectangle(0, 0, 1, 1));
            AbsoluteLayout.SetLayoutFlags(pageStack, AbsoluteLayoutFlags.All);
            AbsoluteLayout.SetLayoutBounds(modalContent, new Rectangle(0.5, 0.3, 0.75, 0.45));
            AbsoluteLayout.SetLayoutFlags(modalContent, AbsoluteLayoutFlags.All);

            Title = "Потребление";

            # region Button events
示例#57
0
        //IntVar x;
        //IntVar y;//Reduntant

        public void SolveVrpProblem(Day day, ConfigParams cfg, VrpProblem vrpProblem, IDataOutput dataOutput, int[] VCMinMax)
        {
            this.day = day;
            this.cfg = cfg;
            //Google Distance Matrix API (Duration matrix)


            // Create Routing Index Manager
            manager = new RoutingIndexManager(
                day.TimeMatrix.GetLength(0),
                day.Vehicles.Count,
                day.Depot);


            // Create Routing Model.
            routing = new RoutingModel(manager);

            // Create and register a transit callback.
            int transitCallbackIndex = routing.RegisterTransitCallback(
                (long fromIndex, long toIndex) =>
            {
                // Convert from routing variable Index to distance matrix NodeIndex.
                var fromNode = manager.IndexToNode(fromIndex);
                var toNode   = manager.IndexToNode(toIndex);
                return(day.TimeMatrix[fromNode, toNode]);
            }
                );

            // Define cost of each arc.
            routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex);

            // Add Distance constraint.

            if (day.TimeWindowsActive != true)
            {
                routing.AddDimension(transitCallbackIndex, 0, 700000,
                                     true, // start cumul to zero
                                     "Distance");
                RoutingDimension distanceDimension = routing.GetMutableDimension("Distance");
                distanceDimension.SetGlobalSpanCostCoefficient(100);
            }
            else
            {
                routing.AddDimension(
                    transitCallbackIndex, // transit callback
                    1000,                 // allow waiting time
                    600,                  // vehicle maximum capacities
                    false,                // start cumul to zero
                    "Time");

                TimeWindowInit(day, routing, manager);//Set Time Window Constraints
            }
            if (day.MaxVisitsActive != 0)
            {
                int demandCallbackIndex = routing.RegisterUnaryTransitCallback(
                    (long fromIndex) => {
                    // Convert from routing variable Index to demand NodeIndex.
                    var fromNode = manager.IndexToNode(fromIndex);
                    return(day.Demands[fromNode]);
                }
                    );

                routing.AddDimensionWithVehicleCapacity(
                    demandCallbackIndex, 0,  // null capacity slack
                    day.VehicleCapacities,   // vehicle maximum capacities
                    true,                    // start cumul to zero
                    "Capacity");
            }

            // Allow to drop nodes.
            for (int i = 1; i < day.TimeMatrix.GetLength(0); ++i)
            {
                routing.AddDisjunction(
                    new long[] { manager.NodeToIndex(i) }, day.Locations.ElementAt(i).Penalty);
            }

            // Setting first solution heuristic.
            RoutingSearchParameters searchParameters =
                operations_research_constraint_solver.DefaultRoutingSearchParameters();


            searchParameters.FirstSolutionStrategy =
                FirstSolutionStrategy.Types.Value.PathMostConstrainedArc;

            //metaheuristic
            searchParameters.LocalSearchMetaheuristic = LocalSearchMetaheuristic.Types.Value.GuidedLocalSearch;
            searchParameters.TimeLimit = new Duration {
                Seconds = cfg.SolutionDuration
            };
            searchParameters.LogSearch = true;

            solver = routing.solver();

            //TODO
            //Some location must be on same route.
            //solver.Add(routing.VehicleVar(manager.NodeToIndex(2)) == routing.VehicleVar(manager.NodeToIndex(5)));
            //One node takes precedence over the another.
            //routing.AddPickupAndDelivery(manager.NodeToIndex(2), manager.NodeToIndex(5));

            //Constraint variable
            //x = solver.MakeIntVar(day.Vehicles.Count, day.Vehicles.Count, "x");

            //Number of vehicle restriction - old version
            //solver.Add(x < 7);

            //Number of vehicle restriction -new version
            //y = solver.MakeIntVar(routing.Vehicles(), routing.Vehicles(), "y");
            //solver.Add(y <= VCMinMax[1]);//Reduntant

            // Solve the problem.
            solution = routing.SolveWithParameters(searchParameters);



            day.LocationDropped = false;

            // Display dropped nodes.
            List <int> droppedNodes = new List <int>();

            for (int index = 0; index < routing.Size(); ++index)
            {
                if (routing.IsStart(index) || routing.IsEnd(index))
                {
                    continue;
                }
                if (solution.Value(routing.NextVar(index)) == index)
                {
                    droppedNodes.Add(manager.IndexToNode((int)index));
                    day.LocationDropped = true;
                }
            }
            day.DroppedLocations.Clear();
            Console.WriteLine(day.Locations.ElementAt(0).Name);
            if (droppedNodes != null)
            {
                foreach (var item in droppedNodes)
                {
                    Location location = LocationDB.Locations.Where(x => x.Position.strPos_ == day.Addresses[item]).ToList().ElementAt(0);

                    if (location != null)
                    {
                        Console.WriteLine(location.Name);
                        day.DroppedLocations.Add(location);
                    }
                }
            }
            List <int> AssignedNodes = new List <int>();

            Console.WriteLine(manager.GetNumberOfNodes());


            //Inspect Infeasable Nodes
            for (int i = 0; i < day.Vehicles.Count; i++)
            {
                var index = routing.Start(i);
                int j     = 0;
                while (routing.IsEnd(index) == false)
                {
                    j++;

                    index = solution.Value(routing.NextVar(index));
                }
                if (j == 1)
                {
                    day.InfeasibleNodes = true;
                    foreach (var item in day.DroppedLocations)
                    {
                        LocationDB.Locations.Where(x => x.ClientRef == item.ClientRef).ToList().ElementAt(0).Infeasible = true;
                    }
                    if (day.Vehicles.Count - 1 >= 1)
                    {
                        day.SetVehicleNumber(day.Vehicles.Count - 1);
                        day.ResetResults();

                        vrpProblem.SolveVrpProblem(day, cfg, vrpProblem, dataOutput, VCMinMax);
                    }
                    return;
                }
            }

            // Inspect solution.
            day.TotalDur = 0;
            day.MinDur   = 100000;
            for (int i = 0; i < day.Vehicles.Count; i++)
            {
                long routeDuration = 0;

                var index = routing.Start(i);

                while (routing.IsEnd(index) == false)
                {
                    var previousIndex = index;

                    index = solution.Value(routing.NextVar(index));

                    routeDuration += routing.GetArcCostForVehicle(previousIndex, index, 0);
                }
                day.TotalDur += routeDuration;
                day.MaxDur    = Math.Max(routeDuration, day.MaxDur);
                day.MinDur    = Math.Min(routeDuration, day.MinDur);
            }
            day.AvgDur = day.TotalDur / day.Vehicles.Count;
        }
示例#58
0
        private async Task <TrainingDay> GenerateSeparateMusclesDay(
            Goal goal, Difficulty difficulty, WorkoutPlan workoutPlan, Day day, List <ExerciseType> exercises)
        {
            var trainingDay = new TrainingDay()
            {
                Day           = day,
                WorkoutPlan   = workoutPlan,
                WorkoutPlanId = workoutPlan.Id,
            };

            var pickedExercises = new List <Exercise>();
            int exercisesCount;
            int firstSet;

            switch (difficulty)
            {
            case Difficulty.Easy:
                exercisesCount = 5;
                firstSet       = 3;
                break;

            case Difficulty.Medium:
                exercisesCount = 6;
                firstSet       = 3;
                break;

            case Difficulty.Hard:
                exercisesCount = 7;
                firstSet       = 4;
                break;

            default:
                exercisesCount = 12;
                firstSet       = 12;
                break;
            }

            if (exercises.Count == 1)
            {
                firstSet = exercisesCount;
            }

            for (int i = 0; i < firstSet; i++)
            {
                var currentExercises = await this.exercisesRepository
                                       .All()
                                       .Where(x => x.Type == exercises[0] && pickedExercises.Contains(x) == false)
                                       .ToListAsync();

                if (currentExercises.Any() == false)
                {
                    break;
                }

                var rand            = new Random();
                var currentExercise = currentExercises[rand.Next(0, currentExercises.Count)];
                pickedExercises.Add(currentExercise);

                var workoutTrainingDay = new WorkoutTrainingDay()
                {
                    ExerciseId    = currentExercise.Id,
                    Exercise      = currentExercise,
                    TrainingDay   = trainingDay,
                    TrainingDayId = trainingDay.Id,
                    MinRepsCount  = currentExercise.Difficulty == Difficulty.Hard
                    ? 6
                    : currentExercise.Difficulty == Difficulty.Medium
                    ? 8
                    : 10,
                    MaxRepsCount = currentExercise.Difficulty == Difficulty.Hard
                    ? 10
                    : currentExercise.Difficulty == Difficulty.Medium
                    ? 12
                    : 14,
                };

                await this.workoutTrainingDayRepository.AddAsync(workoutTrainingDay);

                trainingDay.Exercises.Add(workoutTrainingDay);
                currentExercise.WorkoutPlans.Add(workoutTrainingDay);
            }

            if (exercises.Count == 2)
            {
                int secondSet = exercisesCount - firstSet;
                for (int i = 0; i < secondSet; i++)
                {
                    var currentExercises = await this.exercisesRepository
                                           .All()
                                           .Where(x => x.Type == exercises[1] && pickedExercises.Contains(x) == false)
                                           .ToListAsync();

                    var rand            = new Random();
                    var currentExercise = currentExercises[rand.Next(0, currentExercises.Count)];
                    pickedExercises.Add(currentExercise);

                    var workoutTrainingDay = new WorkoutTrainingDay()
                    {
                        ExerciseId    = currentExercise.Id,
                        Exercise      = currentExercise,
                        TrainingDay   = trainingDay,
                        TrainingDayId = trainingDay.Id,
                        MinRepsCount  = currentExercise.Difficulty == Difficulty.Hard
                        ? 6
                        : currentExercise.Difficulty == Difficulty.Medium
                        ? 8
                        : 10,
                        MaxRepsCount = currentExercise.Difficulty == Difficulty.Hard
                        ? 10
                        : currentExercise.Difficulty == Difficulty.Medium
                        ? 12
                        : 14,
                    };

                    await this.workoutTrainingDayRepository.AddAsync(workoutTrainingDay);

                    trainingDay.Exercises.Add(workoutTrainingDay);
                    currentExercise.WorkoutPlans.Add(workoutTrainingDay);
                }
            }

            await this.trainingDaysRepository.AddAsync(trainingDay);

            return(trainingDay);
        }
        public void Save()
        {
            (String name, String category) Holiday(String name) => (name, "Holiday");

            var isWeekend  = ("Weekend", "Weekend").Is(Day.IsSunday.Or(Day.IsSaturday));
            var isNewYears = Holiday("New Year's Day").Is(Month.Is(1).And(Day.Is(1), Day.IsNotSunday, Day.IsNotSaturday))
                             .Or(Holiday("New Year's Day (observed)").IsEither(Month.Is(1).And(Day.Is(2), Day.IsMonday),
                                                                               Month.Is(12).And(Day.Is(31), Day.IsFriday)));

            var isThirdMonday = Month.Third(DayOfWeek.Monday);
            var isLastMonday  = Month.Last(DayOfWeek.Monday);

            var isMLK        = Holiday("Martin Luther King Day").Is(Month.Is(1).And(isThirdMonday));
            var isPresidents = Holiday("President's Day").Is(Month.Is(2).And(isThirdMonday));
            var isMemorial   = Holiday("Memorial Day").Is(Month.Is(5).And(isLastMonday));

            var isIndependence = Holiday("Independence Day").Is(Month.Is(7).And(Day.Is(4), Day.IsNotSunday, Day.IsNotSaturday))
                                 .Or(Holiday("Independence Day (observed)").Is(Month.Is(7).AndEither(Day.Is(3).And(Day.IsFriday),
                                                                                                     Day.Is(5).And(Day.IsMonday))));

            var isLabor    = Holiday("Labor Day").Is(Month.Is(9).And(Month.First(DayOfWeek.Monday)));
            var isColumbus = Holiday("Columbus Day").Is(Month.Is(10).And(Month.Second(DayOfWeek.Monday)));

            var isVeterans = Holiday("Veteran's Day").Is(Month.Is(11).And(Day.Is(11), Day.IsNotSunday, Day.IsNotSaturday))
                             .Or(Holiday("Veteran's Day (observed)").Is(Month.Is(11).AndEither(Day.Is(10).And(Day.IsFriday),
                                                                                               Day.Is(12).And(Day.IsMonday))));

            var isThanksTerm  = Month.Is(11).And(Month.Fourth(DayOfWeek.Thursday));
            var isThanks      = Holiday("Thanksgiving Day").Is(isThanksTerm);
            var isAfterThanks = Holiday("Day After Thanksgiving").Is(Month.Is(11).And(Day.PriorIs(isThanksTerm)));

            var isChristmas = Holiday("Christmas Day").Is(Month.Is(12).And(Day.Is(25).And(Day.IsNotSunday, Day.IsNotSaturday)))
                              .Or(Holiday("Christmas Day (observed)").Is(Month.Is(12).AndEither(Day.Is(26).And(Day.IsMonday),
                                                                                                Day.Is(24).And(Day.IsFriday))));

            var rules = new DateRule[] { isWeekend, isNewYears, isMLK, isPresidents, isMemorial, isIndependence, isLabor, isColumbus, isVeterans, isThanks, isAfterThanks, isChristmas };

            File.WriteAllText("HolidayRules.json", rules.ToJson());

            var rulesClone = File.ReadAllText("HolidayRules.json").ToDateRules();

            var currDate = new DateTime(2010, 1, 1);
            var endDate  = new DateTime(2020, 12, 31);

            var logic      = rules.ToLogic();
            var logicClone = rulesClone.ToLogic();

            var monthNum  = 0;
            var mondayNum = 0;

            Boolean IsWeekDay(DateTime date) => (Int32)date.DayOfWeek >= 1 && (Int32)date.DayOfWeek <= 5;

            while (currDate <= endDate)
            {
                var logicResult      = logic(currDate);
                var logicCloneResult = logicClone(currDate);

                if (mondayNum != currDate.Month)
                {
                    mondayNum = currDate.Month;
                    mondayNum = 0;
                }

                if (currDate.DayOfWeek == DayOfWeek.Monday)
                {
                    mondayNum++;
                }

                Assert.True(logicResult.Select(s => logicCloneResult.Select(sc => s.Name.Equals(sc.Name, StringComparison.OrdinalIgnoreCase), () => false),
                                               () => logicCloneResult.Select(sc => false, () => true)));

                if (currDate.Month == 1 && currDate.Day == 1 && IsWeekDay(currDate))
                {
                    Assert.True(logicResult.Select(s => s.Name.Equals("New Year's Day"), () => false));
                }
                if (currDate.Month == 1 && mondayNum == 3)
                {
                    Assert.True(logicResult.Select(s => s.Name.Equals("Martin Luther King Day"), () => false));
                }
                if (currDate.Month == 2 && mondayNum == 3)
                {
                    Assert.True(logicResult.Select(s => s.Name.Equals("President's Day"), () => false));
                }

                currDate = currDate.AddDays(1);
            }
        }
示例#60
0
        static void Main(string[] args)
        {
            var nowDay            = new DateTime(2021, 3, 19, 8, 0, 0);
            var fullTimeToRecords = new List <DayRecords>
            {
                new DayRecords
                {
                    RecordsDateTimeStart = nowDay,
                    RecordsDateTimeEnd   = nowDay.AddMinutes(30)
                },
                new DayRecords
                {
                    RecordsDateTimeStart = nowDay.AddMinutes(30),
                    RecordsDateTimeEnd   = nowDay.AddMinutes(60)
                },
                new DayRecords
                {
                    RecordsDateTimeStart = nowDay.AddMinutes(60),
                    RecordsDateTimeEnd   = nowDay.AddMinutes(90)
                },
                new DayRecords
                {
                    RecordsDateTimeStart = nowDay.AddMinutes(90),
                    RecordsDateTimeEnd   = nowDay.AddMinutes(120)
                },
                new DayRecords
                {
                    RecordsDateTimeStart = nowDay.AddMinutes(120),
                    RecordsDateTimeEnd   = nowDay.AddMinutes(150)
                },
                new DayRecords
                {
                    RecordsDateTimeStart = nowDay.AddMinutes(150),
                    RecordsDateTimeEnd   = nowDay.AddMinutes(180)
                },
                new DayRecords
                {
                    RecordsDateTimeStart = nowDay.AddMinutes(180),
                    RecordsDateTimeEnd   = nowDay.AddMinutes(210)
                },
                new DayRecords
                {
                    RecordsDateTimeStart = nowDay.AddMinutes(210),
                    RecordsDateTimeEnd   = nowDay.AddMinutes(240)
                },
                new DayRecords
                {
                    RecordsDateTimeStart = nowDay.AddMinutes(240),
                    RecordsDateTimeEnd   = nowDay.AddMinutes(270)
                },
                new DayRecords
                {
                    RecordsDateTimeStart = nowDay.AddMinutes(270),
                    RecordsDateTimeEnd   = nowDay.AddMinutes(300)
                },
                new DayRecords
                {
                    RecordsDateTimeStart = nowDay.AddMinutes(300),
                    RecordsDateTimeEnd   = nowDay.AddMinutes(330)
                },
            };

            InitConfiguration();
            var user = new User
            {
                Id       = new Guid("6b017401-fd94-4710-8bf8-f9e0b40803a2"),
                Login    = "******",
                Password = "******",
                FullName = "Человечкова Алина Кадаржановна",
                IIN      = "12345678987"
            };

            Console.WriteLine("1.понедельник\n2.вторник\n3.среда\n4.четверг\n5.пятница");
            Console.Write("Введите день недели для записи: ");
            var day   = Console.ReadLine();
            Day dayId = new Day();

            switch (day)
            {
            case "1":
                dayId.Id = new Guid("d0e91b3a-9ead-4c96-b69e-82b8420c8b4f");
                break;
            }

            var dayRecords = new List <DayRecords>();

            using (var recordDataAccess = new RecordDataAccess())
            {
                dayRecords = recordDataAccess.GetDayRecords(dayId.Id).ToList();
            }

            Console.WriteLine("Занятое время");
            foreach (var rec in dayRecords)
            {
                fullTimeToRecords.Remove(rec);
            }

            var record = new Record();

            record.Id     = Guid.NewGuid();
            record.UserId = user.Id;

            Console.WriteLine("Введите номер врача: ");
            var doctors  = new List <Doctor>();
            int chetchik = 1;

            using (var doctorDataAccess = new DoctorDataAccess())
            {
                doctors = doctorDataAccess.SelectAllDoctors().ToList();
                foreach (var doctor in doctors)
                {
                    doctor.Specialization = doctorDataAccess.GetSpecialization(doctor.SpecializationId);
                    Console.WriteLine($"{chetchik++}. {doctor.FullName} {doctor.Specialization.Specialty}");
                }
            }

            var doctorNum = int.Parse(Console.ReadLine());

            switch (doctorNum)
            {
            case 1:
                record.DoctorId = doctors[doctorNum - 1].Id;
                break;
            }



            Console.WriteLine("Введите время для записи");
            int i = 1;

            foreach (var dayrecord in fullTimeToRecords)
            {
                Console.WriteLine($"{i++}. {dayrecord.RecordsDateTimeStart.TimeOfDay} | {dayrecord.RecordsDateTimeEnd.TimeOfDay}");
            }
            var timeToRecords = int.Parse(Console.ReadLine());

            switch (timeToRecords)
            {
            case 1:
                record.RecordDateTimeStart = fullTimeToRecords[timeToRecords - 1].RecordsDateTimeStart;
                record.RecordDateTimeEnd   = fullTimeToRecords[timeToRecords - 1].RecordsDateTimeEnd;
                break;
            }

            using (var recorddata = new RecordDataAccess())
            {
                recorddata.Insert(record);
            }
        }