Ejemplo n.º 1
0
        // Add a service to main timetable in DB
        public static void Add(int serviceId)
        {
            // Start with clearing previous entries
            Delete(serviceId);

            // Get the value of DataGrid Timetable
            IContent service = ContentService.GetById(serviceId);
            string timetable = service.GetValue<string>("timetable");

            // If there is value, deserialize it to object
            if (!string.IsNullOrWhiteSpace(timetable))
            {
                IEnumerable<ServiceTimetableModel> nodes = JsonConvert.DeserializeObject<IEnumerable<ServiceTimetableModel>>(timetable);
                if (nodes.Any())
                {
                    IContent destination = ContentService.GetById(nodes.Last().Station);

                    foreach (ServiceTimetableModel node in nodes)
                    {
                        Timetable model = new Timetable
                        {
                            ServiceId = service.Id,
                            StationId = node.Station,
                            Time = node.Time,
                            Destination = destination.Name
                        };
                        Database.Save(model);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public void FlatSqueezedFitCourses(List<Course> courses, Timetable timetable, int resolution)
        {
            ClearTables();
            bool allCoursesFitted = true;

            // We will keep squeezing the timetable as long as all the courses got fitted.
            while (allCoursesFitted)
            {
                // First we will get all the timeunits that exist in the timetable
                IEnumerable<TimeUnit> timeUnits =
                    (from day in timetable.Days
                     from room in day.Rooms
                     from time in room.Time
                     select time);
                // and find the one that has the largest duration.
                timeUnits = timeUnits.Where(unit => unit.Duration() > resolution);
                TimeUnit max = timeUnits.Aggregate((x, y) => x.Duration() > y.Duration() ? x : y);
                // If this timeunit's duration is large enough the be squeezed, then squeeze.
                if (max.Shorten(resolution))
                {
                    Timetable clone = (Timetable)timetable.Clone();
                    // We need to know if all the courses got fitted with this version of the timetable.
                    allCoursesFitted = FitCourses(courses, clone);
                }
            }
            UniquelyGeneratedTables = getUniques(GeneratedTables);
        }
Ejemplo n.º 3
0
 public void CanFit_CourseWillFitOnlyInLastDay_Yes()
 {
     course2.Students = 20;
     room2.Seats = 20;
     broom3 = new BookableRoom(end.AddMinutes(2), end.AddMinutes(7), room2);
     broomList2 = new List<BookableRoom>() { broom3 };
     day2 = new Day(broomList2);
     table1 = new Timetable(new List<Day>() { day1, day2 });
     Assert.IsTrue(table1.CanFit(course2));
 }
Ejemplo n.º 4
0
        public static List<Timetable> LoadAllTimetables()
        {
            var timetableFiles = new List<Timetable>();

            var fileList = Directory.GetFiles(Options.workingDirectory + "\\Timetables");

            foreach (string filename in fileList) {
                // Reasds the CSV using the method in this class.
                // The 'false' argument prevents readCSV from adding the directory path,
                // as it is already in the filename string.
                var splitCsv = readCSV(filename, true);

                // Split the timetable name into parts to be processed
                var timetableNameParts = Path.GetFileName(filename).Split('.');
                // Initialise a new timetable
                Timetable thisTimetable = new Timetable();
                // Set the route name and the specific sub-route to the values in the filename
                thisTimetable.routeName = timetableNameParts[0];
                thisTimetable.subRoute = timetableNameParts[1];
                // Look at the filename for which days it runs and use the sub to input these
                ProcessDaysRun(thisTimetable, timetableNameParts[2]);

                // For each line of the CSV except for the first line containing stop IDs
                for (int i = 1; i < splitCsv.Count; i++) {
                    // Initialise a journey
                    Journey journey = new Journey();
                    var row = splitCsv[i];
                    for (int j = 0; j < row.Length; j++)
                    {
                        if (Validation.ValidTime(row[j]))
                        {
                            JourneyStop stop = new JourneyStop();
                            stop.stopID = splitCsv[0][j];
                            int thisTime = int.Parse(splitCsv[i][j]);
                            stop.stopMinuteTime = Time.ConvertToMinTime(thisTime);
                            journey.stops.Add(stop);
                        }
                    }
                    thisTimetable.journeys.Add(journey);
                }
                timetableFiles.Add(thisTimetable);

            }
            return timetableFiles;
        }
Ejemplo n.º 5
0
 public static Func <PathData> DefaultPathData(int route, Timetable tt) => () => tt.GetRoute(route).ToPathData(tt);
Ejemplo n.º 6
0
 public DayView(Context context, Day day, Timetable timetable, HourView hourView) : base(context)
 {
     Day       = day;
     Timetable = timetable;
     HourView  = hourView;
 }
Ejemplo n.º 7
0
        protected override void OnDragOver(DragEventArgs drgevent)
        {
            var time = FindClickTime(PointToClient(new Point(drgevent.X, drgevent.Y)));

            // outside of table bounds?
            if (ReferenceEquals(time, null))
            {
                // clear current preview (at edge of timetable)
                EndPreviewStream();
                // cannot drag outside of the actual table
                drgevent.Effect = DragDropEffects.None;
                return;
            }

            // dragging a class
            if (drgevent.Data.GetDataPresent(typeof(Session)) || drgevent.Data.GetDataPresent(typeof(Type)))
            {
                drgevent.Effect = DragDropEffects.Move;
                Type dragType;
                if (drgevent.Data.GetDataPresent(typeof(Session)))
                {
                    dragType = ((Session)drgevent.Data.GetData(typeof(Session))).Stream.Type;
                }
                else
                {
                    dragType = (Type)drgevent.Data.GetData(typeof(Type));
                }

                var session = Timetable.From(dragType).FindClassAt(time, false);
                if (session == null)
                {
                    EndPreviewStream();
                }
                else
                {
                    PreviewEquiv(session.Stream);
                }
            }
            // dragging an unavailability
            else if (drgevent.Data.GetDataPresent(typeof(Unavailability)))
            {
                var dragUnavail = (Unavailability)drgevent.Data.GetData(typeof(Unavailability));
                var offset      = new TimeLength(dragUnavail.StartMinute);
                var start       = time - dragUnavail.Length / 2;
                start -= offset;
                start.RoundToNearestHour();
                start += offset;

                _hoverUnavail = new Timeslot(start.Day, start, (start as TimeOfDay) + dragUnavail.Length);
                if (_hoverUnavail.StartTime < new TimeOfDay(_hourStart, 0) ||
                    _hoverUnavail.EndTime > new TimeOfDay(_hourEnd, 0))
                {
                    drgevent.Effect = DragDropEffects.None;
                    _hoverUnavail   = null;
                }
                else
                {
                    drgevent.Effect = DragDropEffects.Move;
                }
                Invalidate();
            }
            else
            {
                base.OnDragOver(drgevent);
            }
        }
Ejemplo n.º 8
0
 public static Timetable CreateTimetable() {
     var timetable = new Timetable("Test", Layout());
     timetable.Add(CreateTrain1());
     timetable.Add(CreateTrain2());
     return timetable;
 }
Ejemplo n.º 9
0
        public void PushedFitCourses(List<Course> courses, Timetable timetable, int resolution)
        {
            ClearTables();
            bool allCoursesFitted = false;

            // We will traverse the timetable one timeunit at a time.
            foreach (Day day in timetable.Days)
            {
                foreach (BookableRoom room in day.Rooms)
                {
                    foreach (TimeUnit time in room.Time)
                    {
                        // And should the timeunit's duration be large enough to be squeezed, we will squeeze it.

                        while (time.Shorten(resolution))
                        {
                            Timetable clone = (Timetable)timetable.Clone();
                            // And try to fit the courses again.
                            clone = (Timetable)timetable.Clone();
                            allCoursesFitted = FitCourses(courses, clone);
                            // In the event that not all courses got fitted, we will backtrack this last squeeze and move on
                            // to the next timeunit.
                            if (!allCoursesFitted)
                            {
                                time.Lengthen(resolution);
                                break;
                            }
                        }

                    }
                }
            }
            UniquelyGeneratedTables = getUniques(GeneratedTables);
        }
Ejemplo n.º 10
0
 public string GetTimetableDay(Timetable item)
 {
     //switch(item.Dayname)
     //{
     //    case "Thursday": return item.Dayname.ToUpper().Substring(0,4);
     //    default: return item.Dayname.ToUpper().Substring(0, 3);
     //}
     return item.Dayname.ToUpper().Substring(0, 3);
 }
Ejemplo n.º 11
0
 public HomeController(MyRUZDbContext context, Timetable timetable)
 {
     _context   = context;
     _timetable = timetable;
 }
Ejemplo n.º 12
0
 public void Update(Timetable timetable)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 13
0
        public void Start()
        {
            mqClient.DeclareQueues(
                queues.ToArray()
                );

            mqClient.PurgeQueues(
                queues.ToArray()
                );

            var cancellationSource = new CancellationTokenSource();
            var cancellationToken  = cancellationSource.Token;
            var playDelaySource    = new PlayDelaySource(timeFactor);

            Task.Run(() =>
            {
                try
                {
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        var num = 4;
                        // generate passengers
                        if (random.NextDouble() < 1.0 / num)
                        {
                            var passenger = generator.GeneratePassenger();
                            Console.WriteLine($"{passenger.PassengerId}: new passenger");
                            idlePassengers.TryAdd(
                                passenger.PassengerId,
                                passenger
                                );
                        }

                        playDelaySource.CreateToken().Sleep(PASSENGER_CREATION_PERIOD_MS / num);
                    }
                } catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }, cancellationToken);

            // Own run for every queue (e.g. waiting-for-response-passengers-from-cashbox)
            Task.Run(() =>
            {
                try
                {
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        // send passengers to do something
                        var copyPassengers = new List <Passenger>(idlePassengers.Values);
                        foreach (var passenger in copyPassengers)
                        {
                            TryToSendPassengerSomewhere(passenger);
                        }

                        playDelaySource.CreateToken().Sleep(PASSENGER_ACTIVITY_PERIOD_MS);
                    }
                } catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }, cancellationToken);

            mqClient.SubscribeTo <Timetable>(TimetableToPassengerQueue, (mes) =>
            {
                try
                {
                    Console.WriteLine("Timetable updated");
                    // Careful: do not change to "updating" of timetable, just replace it
                    // Otherwise it can be modified at the same time it's being traversed
                    timetable   = mes;
                    var flights = mes.Flights.Select(f => f.FlightId);
                    foreach (var passenger in passivePassengers.Values)
                    {
                        if (!flights.Contains(passenger.FlightId))
                        {
                            if (passivePassengers.TryRemove(passenger.PassengerId, out var depPassenger))
                            {
                                Console.WriteLine($"{depPassenger.PassengerId} has departed with {depPassenger.FlightId}");
                            }
                            ;
                        }
                    }
                } catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            });

            mqClient.SubscribeTo <TicketResponse>(CashboxToPassengerQueue, (mes) =>
            {
                try
                {
                    HandleCashboxResponse(mes);
                } catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            });

            mqClient.SubscribeTo <CheckInResponse>(RegistrationToPassengerQueue, (mes) =>
            {
                try {
                    HandleRegistrationResponse(mes);
                } catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            });

            mqClient.SubscribeTo <PassengerPassMessage>(BusStorageToPassengerQueue, (mes) =>
            {
                try {
                    HandleBusStorageResponse(mes);
                } catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            });

            mqClient.SubscribeTo <NewTimeSpeedFactor>(TimeServiceToPassengerQueue, (mes) =>
            {
                playDelaySource.TimeFactor = mes.Factor;
            });

            Console.ReadLine();
            cancellationSource.Cancel();
            mqClient.Dispose();
        }
Ejemplo n.º 14
0
 public Track(Timetable tt) : base("track", tt)
 {
 }
Ejemplo n.º 15
0
 /// <inheritdoc />
 public Track(XMLEntity en, Timetable tt) : base(en, tt)
 {
 }
Ejemplo n.º 16
0
        public static async Task <Timetable> getTimetable(bool forceRemote = false)
        {
            if (isDemo())
            {
                var table = new Timetable();

                var start = DateTime.Now.AddDays(-20);
                while (start.DayOfWeek != DayOfWeek.Monday)
                {
                    start = start.AddDays(-1);
                }

                for (var i = 0; i < 10; i++)
                {
                    table.Add(new Event {
                        nr   = "形式语言与自动机",
                        dd   = "六教 6A301",
                        nq   = start.AddDays(i * 7 + 2).ToString("yyyy-MM-dd"),
                        kssj = "08:00",
                        jssj = "09:35"
                    });

                    table.Add(new Event {
                        nr   = "高级数据结构",
                        dd   = "六教 6A301",
                        nq   = start.AddDays(i * 7 + 2).ToString("yyyy-MM-dd"),
                        kssj = "09:50",
                        jssj = "11:25"
                    });

                    table.Add(new Event {
                        nr   = "操作系统",
                        dd   = "六教 6A303",
                        nq   = start.AddDays(i * 7 + 3).ToString("yyyy-MM-dd"),
                        kssj = "09:50",
                        jssj = "11:25"
                    });

                    table.Add(new Event {
                        nr   = "概率论与数理统计",
                        dd   = "六教 6C102",
                        nq   = start.AddDays(i * 7 + 4).ToString("yyyy-MM-dd"),
                        kssj = "15:20",
                        jssj = "16:55"
                    });

                    table.Add(new Event {
                        nr   = "概率论与数理统计",
                        dd   = "一教 104",
                        nq   = start.AddDays(i * 7 + 1).ToString("yyyy-MM-dd"),
                        kssj = "13:30",
                        jssj = "15:05"
                    });
                }
                return(table);
            }

            //fetch from remote
            var _remoteTimetable = await Remote.getRemoteTimetable();

            Debug.WriteLine("[getTimetable] Returning remote");
            return(_remoteTimetable);
        }
Ejemplo n.º 17
0
        // exposes access to remote objects
        public static async Task <Timetable> getRemoteTimetable()
        {
            Debug.WriteLine("[getRemoteTimetable] start");
            await login();


            var ticket = await POST(
                "http://learn.cic.tsinghua.edu.cn:80/gnt",
                "appId=ALL_ZHJW");

            //await 十1s(); //cross-domain tickets needs some time to take effect

            bool outside_campus_network = false;

            try {
                var zhjw = await GET(
                    $"http://zhjw.cic.tsinghua.edu.cn/j_acegi_login.do?url=/&ticket={ticket}");
            } catch (System.Runtime.InteropServices.COMException e) {
                if (e.Message.IndexOf("403") == -1)
                {
                    throw e;
                }
                Debug.WriteLine("[getRemoteTimetable] outside campus network");
                //throw new NeedCampusNetworkException();

                outside_campus_network = true;
            }



            if (outside_campus_network)
            {
                //connect via sslvpn
                await logoutSSLVPN();
                await loginSSLVPN();

                await login();

                ticket = await POST(
                    "http://learn.cic.tsinghua.edu.cn:80/gnt",
                    "appId=ALL_ZHJW");

                await 十1s();

                var ticketPage = await GET(
                    $"https://sslvpn.tsinghua.edu.cn/,DanaInfo=zhjw.cic.tsinghua.edu.cn+j_acegi_login.do?url=/&ticket={ticket}");

                Timetable timetable = new Timetable();

                for (int i = -6; i <= 4; i += 2)
                {
                    string page;
                    try {
                        page = await get_calendar_sslvpn_page(
                            DateTime.Now.AddMonths(i).AddDays(1).ToString("yyyyMMdd"),
                            DateTime.Now.AddMonths(i + 2).ToString("yyyyMMdd")
                            );
                    } catch (Exception) {
                        page = await get_calendar_sslvpn_page(
                            DateTime.Now.AddMonths(i).AddDays(1).ToString("yyyyMMdd"),
                            DateTime.Now.AddMonths(i + 2).ToString("yyyyMMdd")
                            );
                    }
                    var set_to_be_appended = parseTimetablePage(page);
                    foreach (var _____ in set_to_be_appended)
                    {
                        timetable.Add(_____);
                    }
                }

                logoutSSLVPN();

                Debug.WriteLine("[getRemoteTimetable] returning sslvpn");
                return(timetable);
            }
            else     //TODO: duplicate code

            //connect directly

            {
                Timetable timetable = new Timetable();
                for (int i = -6; i <= 4; i += 2)
                {
                    string page;
                    try {
                        page = await get_calendar_page(
                            DateTime.Now.AddMonths(i).AddDays(1).ToString("yyyyMMdd"),
                            DateTime.Now.AddMonths(i + 2).ToString("yyyyMMdd")
                            );
                    } catch (Exception) {
                        page = await get_calendar_page(
                            DateTime.Now.AddMonths(i).AddDays(1).ToString("yyyyMMdd"),
                            DateTime.Now.AddMonths(i + 2).ToString("yyyyMMdd")
                            );
                    }
                    var set_to_be_appended = parseTimetablePage(page);
                    foreach (var _____ in set_to_be_appended)
                    {
                        timetable.Add(_____);
                    }
                }

                Debug.WriteLine("[getRemoteTimetable] returning direct");
                return(timetable);
            }
        }
Ejemplo n.º 18
0
 private Station?GetStationAfter(int route, float km, Timetable tt)
 => tt.Stations.FirstOrDefault(s =>
                               s.Routes.Contains(route) && s.Positions.GetPosition(route) > km);
Ejemplo n.º 19
0
        public SemesterServiceTest()
        {
            factory     = new ConnectionFactory();
            userContext = factory.CreateUserDbContextForInMemory();
            userContext.Database.EnsureDeleted();
            userContext.Database.EnsureCreated();
            userContext.SaveChanges();

            roomContext = factory.CreateRoomDbContextForInMemory();
            roomContext.Database.EnsureDeleted();
            roomContext.Database.EnsureCreated();
            roomContext.SaveChanges();

            attendanceDAO = new Mock <AttendanceDAO>(userContext);
            logDAO        = new Mock <LogDAO>(userContext);
            var iAttendanceDao = attendanceDAO.As <IAttendanceDAO>();
            var iLogDAO        = logDAO.As <ILogDAO>();
            //mocking user manager
            var users = new List <AppUser>
            {
                new AppUser
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                },
                new AppUser
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                },
                new AppUser
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                },
                new AppUser
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                },
                new AppUser
                {
                    UserName = "******",
                    Email    = "*****@*****.**"
                },
            }.AsQueryable();

            var fakeUserManager = new Mock <FakeUserManager>();

            fakeUserManager.Setup(x => x.Users).Returns(users.AsQueryable());

            fakeUserManager.Setup(x => x.DeleteAsync(It.IsAny <AppUser>()))
            .ReturnsAsync(IdentityResult.Success);
            fakeUserManager.Setup(x => x.CreateAsync(It.IsAny <AppUser>(), It.IsAny <string>()))
            .ReturnsAsync(IdentityResult.Success);
            fakeUserManager.Setup(x => x.UpdateAsync(It.IsAny <AppUser>()))
            .ReturnsAsync(IdentityResult.Success);

            var mockEnvironment = new Mock <IWebHostEnvironment>();

            //...Setup the mock as needed
            mockEnvironment
            .Setup(m => m.EnvironmentName)
            .Returns("Hosting:UnitTestEnvironment");
            mockEnvironment.Setup(m => m.ContentRootPath).Returns("");
            _SemetserService = new Mock <SemesterService>(fakeUserManager.Object, userContext, roomContext, mockEnvironment.Object, iAttendanceDao.Object, iLogDAO.Object);
            var semester = new Semester()
            {
                Id          = 1,
                Name        = "testSemester",
                File        = "TestFile.xsl",
                LastUpdated = DateTime.Now
            };

            SemesterDAO.Create(roomContext, semester);

            var room = new Room()
            {
                RoomId     = 1,
                Subject    = "testSubject",
                ClassName  = "testName",
                CreatorId  = "testUser",
                SemesterId = 1
            };

            RoomDAO.Create(roomContext, room);

            var links = new List <RoomUserLink>();

            links.Add(new RoomUserLink()
            {
                RoomId = 1, RoomUserId = 1, UserId = "testUser"
            });
            links.Add(new RoomUserLink()
            {
                RoomId = 1, RoomUserId = 2, UserId = "testUser2"
            });
            links.Add(new RoomUserLink()
            {
                RoomId = 1, RoomUserId = 3, UserId = "testUser1"
            });

            // Act
            RoomUserLinkDAO.Create(roomContext, links);

            var schedule = new Timetable()
            {
                Id        = 1,
                RoomId    = 1,
                Date      = DateTime.Now.Date,
                StartTime = TimeSpan.Parse("8:00"),
                EndTime   = TimeSpan.Parse("10:00"),
            };

            // Act
            TimetableDAO.Create(roomContext, schedule);
        }
Ejemplo n.º 20
0
 public DialogResult ShowDialog(Timetable timetable, Timeslot timeslot, int earliest, int latest)
 {
     return(ShowDialog(timetable, new Unavailability("", timeslot), earliest, latest));
 }
Ejemplo n.º 21
0
 public string GetTimetableClassName(Timetable item)
 {
     return "timetable_" + item.Dayname.ToLower().Substring(0, 3);
 }
Ejemplo n.º 22
0
        public async Task <ActionResult <Timetable> > PostTimetables(Timetable timetable)
        {
            await _adminRepository.AddTimetable(timetable);

            return(Created("timetables", timetable));
        }
Ejemplo n.º 23
0
 public void NormalFitCourses(List<Course> courses, Timetable timetable)
 {
     ClearTables();
     FitCourses(courses, timetable);
     UniquelyGeneratedTables = getUniques(GeneratedTables);
 }
Ejemplo n.º 24
0
 public void Equals_DifferentDays_No()
 {
     table1 = new Timetable(new List<Day>() { day2 });
     Assert.AreNotEqual(table1, table2);
 }
Ejemplo n.º 25
0
 /// <summary>
 /// list of courses
 /// timetable
 /// 
 /// for each course in the list of courses
 ///     try to fit this course in the timetable
 ///         fit is found: 
 ///             fit course in a copy of the timetable
 ///             make a copy of the list of courses and remove the reference to this course (shallow)
 ///             call this method with the copied list and timetable
 ///         fit is not found:
 ///             try the next course in the list of courses
 /// </summary>
 private bool FitCourses(List<Course> courses, Timetable timetable)
 {
     int before = GeneratedTables.Count;
     if (courses.Any())
     {
         foreach (Course course in courses)
         {
             // TODO: optimise for speed by combining check and actually fitting
             if (timetable.CanFit(course))
             {
                 // Clone the list of courses left to fit
                 List<Course> coursesLeft = (List<Course>)courses.Clone();
                 // Remove the course that's going to be fitted from this cloned list
                 coursesLeft.Remove(course);
                 // Clone the timetable
                 Timetable newTimetable = (Timetable)timetable.Clone();
                 // Fit the course in the cloned timetable
                 newTimetable.Fit(course);
                 // Try to fit the remaining courses
                 FitCourses(coursesLeft, newTimetable);
             }
         }
     }
     else
     {
         bool added = GeneratedTables.Add(timetable);
         string output = String.Format("Item was added? {0}", added);
         Console.Out.WriteLine(output);
     }
     return before < GeneratedTables.Count;
 }
Ejemplo n.º 26
0
        public void Equals_InHashSet()
        {
            HashSet<Timetable> set = new HashSet<Timetable>();
            Assert.IsTrue(set.Add(table1));
            Assert.IsFalse(set.Add(table1));
            Assert.IsFalse(set.Add((Timetable)table1.Clone()));

            Assert.IsTrue(set.Add(table2));
            Timetable table3 = new Timetable(new List<Day>() { day1, day2 });
            Assert.IsFalse(set.Add(table3));

            Timetable table4 = new Timetable(new List<Day>() { (Day) day1.Clone(), (Day) day2.Clone() });
            Assert.IsFalse(set.Add(table4));

            Timetable table5 = (Timetable) table4.Clone();
            Timetable table6 = (Timetable) table4.Clone();
            table5.Fit(course1);
            table6.Fit(course1);
            Assert.IsTrue(set.Add(table5));
            Assert.IsFalse(set.Add(table6));
        }
Ejemplo n.º 27
0
        public void Equals_SameDays_Yes()
        {
            day1 = new Day(broomList);
            day2 = new Day(broomList);

            table1 = new Timetable(new List<Day>() { day1 });
            table2 = new Timetable(new List<Day>() { day2 });

            Assert.AreEqual(table1, table2);
        }
Ejemplo n.º 28
0
        public void Fit_OnlyOnce()
        {
            broomList = new List<BookableRoom>() { broom1 };
            broomList2 = new List<BookableRoom>() { (BookableRoom) broom1.Clone() };
            day1 = new Day(broomList);
            day2 = new Day(broomList2);

            table1 = new Timetable(new List<Day>() { day1, day2 });
            Assert.IsTrue(table1.Fit(course1));

            var fits = table1.Days.Where(day => day.IsCourseBooked(course1)).ToList();
            Assert.AreEqual(1, fits.Count);
        }
 public FormularzSzczegolyFilmy(Timetable element, deleteCallbakck callbakck)
 {
     this.element  = element;
     this.callback = callbakck;
     InitializeComponent();
 }
Ejemplo n.º 30
0
        public void GetHashCode_Clone_SameHashCode()
        {
            table2 = (Timetable) table1.Clone();

            Assert.AreEqual(table1, table2);
            Assert.AreEqual(table1.GetHashCode(), table2.GetHashCode());
        }
Ejemplo n.º 31
0
 public Renderer(Timetable timetable, Func <PathData> getPathData)
 {
     tt = timetable;
     this.getPathData = getPathData;
     attrs            = new TimetableStyle(tt);
 }
Ejemplo n.º 32
0
        public void init()
        {
            resource1 = new Resource("TV");
            resource2 = new Resource("Projector");
            resource3 = new Resource("PC");

            resources1 = new List<Resource>() { resource1, resource2 };
            resources2 = new List<Resource>() { resource3 };

            room1 = new Room(10, resources1);
            room2 = new Room(10, resources2);

            start = DateTime.Now;
            end = start.AddMinutes(5);

            broom1 = new BookableRoom(start, end, room1);
            broom2 = new BookableRoom(end.AddMinutes(1), end.AddMinutes(6), room2);
            broom3 = new BookableRoom(end.AddMinutes(2), end.AddMinutes(7), room2);

            course1 = new Course(1, 10, resources1);
            course2 = new Course(1, 10, resources2);
            course3 = new Course(1, 20, new List<Resource>() { new Resource("CoffeeMachine")});

            broomList = new List<BookableRoom>() { broom1, broom2 };
            broomList2 = new List<BookableRoom>() { broom3 };
            day1 = new Day(broomList);
            day2 = new Day(broomList2);

            table1 = new Timetable(new List<Day>() { day1, day2 });
            table2 = new Timetable(new List<Day>() { day1 });
        }
Ejemplo n.º 33
0
 private Station?GetStationBefore(int route, float km, Timetable tt)
 => tt.Stations.LastOrDefault(s =>
                              s.Routes.Contains(route) && s.Positions.GetPosition(route) < km);
Ejemplo n.º 34
0
 public List <FilterRule> LoadStationRules(Timetable tt)
 {
     Init(tt);
     return(stationRules);
 }
Ejemplo n.º 35
0
 public void Update(Timetable obj)
 {
     db.Entry(obj).State = EntityState.Modified;
     db.SaveChanges();
 }
        public ActionResult Edit(int id)
        {
            Timetable existing = service.SelectByID(id);

            return(View(existing));
        }
Ejemplo n.º 37
0
        public ActionResult Delete(int?id)
        {
            Timetable timetable = manager.GetTimetableByID(id);

            return(View(timetable));
        }
Ejemplo n.º 38
0
        public bool Export(Timetable tt, Stream stream, IReducedPluginInterface pluginInterface, string[] flags = null)
        {
            if (tt.Type == TimetableType.Linear)
            {
                throw new TimetableTypeNotSupportedException(TimetableType.Linear, "convert to linear");
            }
            if (tt.GetRoutes().Length != 1)
            {
                throw new NotSupportedException(T._("Der Fahrplan hat mehr als eine oder keine Strecke"));
            }

            if (tt.Version.CompareTo(TimetableVersion.Extended_FPL2) >= 0 && Timetable.DefaultLinearVersion.CompareTo(TimetableVersion.JTG3_3) < 0)
            {
                throw new NotSupportedException(T._("Eine Fahrplandatei der Version >= 101 kann nicht als lineare Datei <= 012 exportiert werden!"));
            }

            var clone = tt.Clone();

            var trainPaths = new Dictionary <ITrain, TrainPathData>();

            foreach (var orig in clone.Trains)
            {
                trainPaths[orig] = new TrainPathData(clone, orig);
            }

            var route = clone.GetRoutes().Single().Index;

            foreach (var sta in clone.Stations)
            {
                ConvertStationNetToLin(sta, route);

                sta.RemoveAttribute("fpl-rt");
                sta.RemoveAttribute("fpl-pos");
                sta.RemoveAttribute("fpl-id");
            }

            var actions = pluginInterface.GetRegistered <ITimetableTypeChangeAction>();

            foreach (var action in actions)
            {
                action.ToLinear(clone);
            }

            clone.SetVersion(Timetable.DefaultLinearVersion);

            var sortedStations = clone.GetRoutes()[Timetable.LINEAR_ROUTE_ID].Stations;

            foreach (var t in clone.Trains)
            {
                var data = trainPaths[t];

                var sta1 = data.PathEntries.FirstOrDefault()?.Station;
                var sta2 = data.PathEntries.LastOrDefault()?.Station;

                var dir = TrainDirection.ti;
                if (sta1 != sta2)
                {
                    if (sortedStations.IndexOf(sta1) > sortedStations.IndexOf(sta2))
                    {
                        dir = TrainDirection.ta;
                    }
                }
                else if (sortedStations.IndexOf(sta1) == sortedStations.Count - 1)
                {
                    dir = TrainDirection.ta;
                }

                t.XMLEntity.XName = dir.ToString();

                if (!(t is IWritableTrain wt))
                {
                    continue;
                }

                wt.Children.Clear();   // Clear all existing arrdeps...
                wt.AddLinearArrDeps(); // ...and re-add all linear ones.

                foreach (var sta in data.PathEntries)
                {
                    if (sta.ArrDep != null)
                    {
                        t.GetArrDep(sta.Station).ApplyCopy(sta.ArrDep);
                    }
                }
            }

            return(new XMLExport().Export(clone, stream, pluginInterface));
        }
Ejemplo n.º 39
0
 public List <FilterRule> LoadTrainRules(Timetable tt)
 {
     Init(tt);
     return(trainRules);
 }
Ejemplo n.º 40
0
 public void Equals_BothEmpty_Yes()
 {
     table1 = new Timetable(null);
     table2 = new Timetable(null);
     Assert.AreEqual(table1, table2);
 }
Ejemplo n.º 41
0
 Timetable ITimetableRepository.GetTimetable(string name) {
     var result = new Timetable(name, GetLayout());
     result.Add(TestDataFactory.CreateTrain1());
     result.Add(TestDataFactory.CreateTrain2());
     return result;
 }
Ejemplo n.º 42
0
        public static void Seed(this ModelBuilder modelBuilder)
        {
            modelBuilder.Entity <Teacher>()
            .HasMany(t => t.Subjects)
            .WithMany(s => s.Teachers)
            .UsingEntity <TeachersSubjects>(
                ts => ts.HasOne(prop => prop.Subject).WithMany().HasForeignKey(prop => prop.SubjectId),
                ts => ts.HasOne(prop => prop.Teacher).WithMany().HasForeignKey(prop => prop.TeacherId),
                ts => {
                ts.HasKey(prop => new { prop.SubjectId, prop.TeacherId });
                ts.Property(prop => prop.CreatedAt).HasDefaultValueSql("GETUTCDATE()");
            }
                );

            modelBuilder.Entity <Grade>()
            .HasMany(g => g.Subjects)
            .WithMany(s => s.Grades)
            .UsingEntity <GradesSubjects>(
                gs => gs.HasOne(prop => prop.Subject).WithMany().HasForeignKey(prop => prop.SubjectId),
                gs => gs.HasOne(prop => prop.Grade).WithMany().HasForeignKey(prop => prop.GradeId),
                gs => {
                gs.HasKey(prop => new { prop.SubjectId, prop.GradeId });
                gs.Property(prop => prop.CreatedAt).HasDefaultValueSql("GETUTCDATE()");
            }
                );



            modelBuilder.Entity <Teacher>()
            .HasMany(s => s.Timetables)
            .WithOne()
            .HasForeignKey(t => t.TeacherId)
            .HasPrincipalKey(s => s.Id);



            modelBuilder.Entity <Grade>().HasData(
                new Grade
            {
                Id    = 1,
                Title = "Grade 5"
            },
                new Grade
            {
                Id    = 2,
                Title = "Grade 6"
            }
                );

            Student[] students = new Student[5];

            for (int i = 0; i < 5; i++)
            {
                students[i] = new Student
                {
                    Id      = i + 1,
                    Name    = Faker.Name.FullName(),
                    GradeId = 1
                };
            }

            modelBuilder.Entity <Student>().HasData(students);


            Teacher[] teachers = new Teacher[16];

            for (int i = 0; i < 16; i++)
            {
                teachers[i] = new Teacher
                {
                    Id   = i + 1,
                    Name = Faker.Name.FullName(),
                };
            }

            modelBuilder.Entity <Teacher>().HasData(teachers);



            modelBuilder.Entity <Subject>().HasData(
                new Subject
            {
                Id    = 1,
                Title = "Maths",
            },
                new Subject
            {
                Id    = 2,
                Title = "English",
            },
                new Subject
            {
                Id    = 3,
                Title = "Science",
            },
                new Subject
            {
                Id    = 4,
                Title = "Geometry",
            },
                new Subject
            {
                Id    = 5,
                Title = "Biology",
            },
                new Subject
            {
                Id    = 6,
                Title = "Physics",
            },
                new Subject
            {
                Id    = 7,
                Title = "Chemistry",
            },
                new Subject
            {
                Id    = 8,
                Title = "World Literature",
            }
                );

            modelBuilder.Entity <TeachersSubjects>().HasData(
                new TeachersSubjects
            {
                TeacherId = 1,
                SubjectId = 1
            },
                new TeachersSubjects
            {
                TeacherId = 2,
                SubjectId = 1
            },
                new TeachersSubjects
            {
                TeacherId = 3,
                SubjectId = 2
            },
                new TeachersSubjects
            {
                TeacherId = 4,
                SubjectId = 2
            },
                new TeachersSubjects
            {
                TeacherId = 5,
                SubjectId = 3
            },
                new TeachersSubjects
            {
                TeacherId = 6,
                SubjectId = 3
            },
                new TeachersSubjects
            {
                TeacherId = 7,
                SubjectId = 4
            },
                new TeachersSubjects
            {
                TeacherId = 8,
                SubjectId = 4
            },
                new TeachersSubjects
            {
                TeacherId = 9,
                SubjectId = 5
            },
                new TeachersSubjects
            {
                TeacherId = 10,
                SubjectId = 5
            },
                new TeachersSubjects
            {
                TeacherId = 11,
                SubjectId = 6
            },
                new TeachersSubjects
            {
                TeacherId = 12,
                SubjectId = 6
            },
                new TeachersSubjects
            {
                TeacherId = 13,
                SubjectId = 7
            },
                new TeachersSubjects
            {
                TeacherId = 14,
                SubjectId = 7
            },
                new TeachersSubjects
            {
                TeacherId = 15,
                SubjectId = 8
            },
                new TeachersSubjects
            {
                TeacherId = 16,
                SubjectId = 8
            }
                );


            modelBuilder.Entity <GradesSubjects>().HasData(
                new GradesSubjects
            {
                GradeId   = 1,
                SubjectId = 1
            },
                new GradesSubjects
            {
                GradeId   = 1,
                SubjectId = 2
            },
                new GradesSubjects
            {
                GradeId   = 1,
                SubjectId = 3
            },
                new GradesSubjects
            {
                GradeId   = 1,
                SubjectId = 4
            },
                new GradesSubjects
            {
                GradeId   = 1,
                SubjectId = 5
            },
                new GradesSubjects
            {
                GradeId   = 1,
                SubjectId = 6
            },
                new GradesSubjects
            {
                GradeId   = 1,
                SubjectId = 7
            },
                new GradesSubjects
            {
                GradeId   = 1,
                SubjectId = 8
            }
                );

            var dates = new List <DateTime>();

            Timetable[] timetables = new Timetable[40];

            int index = 0;

            for (var dt = DateTime.Parse("2021-01-11 00:00:00"); dt <= DateTime.Parse("2021-01-15 00:00:00"); dt = dt.AddDays(1))
            {
                DateTime rec = dt.ChangeTime(8, 0, 0, 0);
                for (int i = 0; i < 8; i++)
                {
                    timetables[index] = new Timetable
                    {
                        Id        = index + 1,
                        GradeId   = 1,
                        TeacherId = (i == 0 ? 1 : i + 2),
                        SubjectId = i + 1,
                        StartAt   = rec,
                        EndsAt    = rec.AddMinutes(45),
                    };
                    rec = rec.AddMinutes(45);

                    index++;
                }
            }

            modelBuilder.Entity <Timetable>().HasData(
                timetables
                );


            // modelBuilder.Entity<Student>()
            //.HasMany(s => s.Timetables)
            //.WithOne()
            //.HasForeignKey(t => t.GradeId)
            //.HasPrincipalKey(s => s.GradeId);
        }
Ejemplo n.º 43
0
 public string GetTimetableDate(Timetable item)
 {
     return item.Date.ToString("dd");
 }
Ejemplo n.º 44
0
        public JsonResult TimetableList()
        {
            Timetable obj = new Timetable();

            return(Json(obj.TimetableList(), JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 45
0
        public Timetable generateDefaultTimeTable()
        {
            // Resources
            Resource resource1 = new Resource("Projector");
            List<Resource> resources = new List<Resource>() { resource1 };

            // Rooms
            Room room1 = new Room("001", 30, resources);
            Room room2 = new Room("112", 30, null);
            Room room3 = new Room("110", 35, resources);

            // Set Room avalability
            BookableRoom book1 = new BookableRoom(Extensions.DateTimeCreator(0, 8, 30), Extensions.DateTimeCreator(0, 16, 0), room1);
            BookableRoom book2 = new BookableRoom(Extensions.DateTimeCreator(0, 8, 30), Extensions.DateTimeCreator(0, 16, 0), room2);
            BookableRoom book3 = new BookableRoom(Extensions.DateTimeCreator(0, 8, 30), Extensions.DateTimeCreator(0, 16, 0), room3);
            List<BookableRoom> rooms1 = new List<BookableRoom>() { (BookableRoom)book1.Clone(), (BookableRoom)book2.Clone() };
            List<BookableRoom> rooms2 = new List<BookableRoom>() { (BookableRoom)book2.Clone(), (BookableRoom)book3.Clone() };
            List<BookableRoom> rooms3 = new List<BookableRoom>() { (BookableRoom)book1.Clone(), (BookableRoom)book3.Clone() };

            // Days
            Day day1 = new Day(1, rooms1);
            Day day2 = new Day(2, rooms2);
            Day day3 = new Day(3, rooms3);

            // Timetable
            Timetable timetable = new Timetable(new List<Day>() { day1, day2, day3 });

            return timetable;
        }
Ejemplo n.º 46
0
 public void AddTimetable(Timetable myTimetable)
 {
     timetableRepository.Add(myTimetable);
     unitofWork.Commit();
 }
Ejemplo n.º 47
0
 public GeneratedTables NormalFitCoursesWrapperWithReturn(List<Course> courses, Timetable timetable)
 {
     NormalFitCourses(courses, timetable);
     return new GeneratedTables(GeneratedTables.ToList(), UniquelyGeneratedTables.ToList());
 }
Ejemplo n.º 48
0
 public void EditTimetable(Timetable myTimetable)
 {
     timetableRepository.Update(myTimetable);
     unitofWork.Commit();
 }
Ejemplo n.º 49
0
 public GeneratedTables PushedFitCoursesWrapperWithReturn(List<Course> courses, Timetable timetable, int resolution)
 {
     PushedFitCourses(courses, timetable, resolution);
     return new GeneratedTables(GeneratedTables.ToList(), UniquelyGeneratedTables.ToList());
 }
Ejemplo n.º 50
0
 public TimetableStyle(Timetable tt) : base(tt)
 {
     this.tt = tt;
 }
Ejemplo n.º 51
0
        public IHttpActionResult PostTimetable(TimetablePomModel timetablePom)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            List <Timetable> listTimetableFromDb = _unitOfWork.Timetables.GetAll().ToList();

            Timetable newTimetable = new Timetable();


            int dayIdd = 0;
            //_unitOfWork.Days.GetIdDay(timetablePom.DayId).Id;
            List <Day> d = _unitOfWork.Days.GetAll().ToList();

            foreach (var item in d)
            {
                if (item.Name == timetablePom.DayId)
                {
                    dayIdd = item.Id;
                    break;
                }
            }

            int lineIdd = _unitOfWork.Lines.GetIdLine(timetablePom.LineId).Id;
            //List<Line> l = _unitOfWork.Lines.GetAll().ToList();

            bool existsTimetable = false;

            foreach (var item in listTimetableFromDb)
            {
                if (item.LineId == lineIdd && item.DayId == dayIdd)
                {
                    existsTimetable = true; //ne smije upisati vec postoji
                    break;
                }
            }



            newTimetable.LineId     = lineIdd;
            newTimetable.DayId      = dayIdd;
            newTimetable.Departures = timetablePom.Departures;

            if (!existsTimetable)
            {
                newTimetable.Departures += ":00|";
                _unitOfWork.Timetables.Add(newTimetable);
                _unitOfWork.Complete();
                return(Ok(newTimetable.Id));
            }
            else
            {
                Timetable timetable2 = new Timetable();
                foreach (var item in listTimetableFromDb)
                {
                    if (item.LineId == newTimetable.LineId && item.DayId == newTimetable.DayId)
                    {
                        timetable2 = item;
                    }
                }

                timetable2.Departures += newTimetable.Departures + "|";

                string vremena = timetable2.Departures;

                List <TimeSpan> listTimeSpan = new List <TimeSpan>();

                string[] nizVremena = vremena.Split('|');
                for (int i = 0; i < nizVremena.Length - 1; i++)
                {
                    listTimeSpan.Add(TimeSpan.Parse(nizVremena[i]));
                }

                List <TimeSpan> sortiranaVremena = listTimeSpan.OrderBy(dd => dd.Hours).ThenBy(dddd => dddd.Minutes).ToList();

                string noviString = "";
                foreach (var item in sortiranaVremena)
                {
                    noviString += item.ToString() + "|";
                }

                timetable2.Departures = noviString;
                _unitOfWork.Timetables.Update(timetable2);
                _unitOfWork.Complete();

                return(Ok());
            }
        }
Ejemplo n.º 52
0
 public NetworkHelper(Timetable tt)
 {
     this.tt = tt;
 }
Ejemplo n.º 53
0
        public void algorithm_loop()
        {
            this.output.Focus();
            this.output.AppendText("START\n");

            do
            {
                var eval_list = population.Select(x => evalSelector.Evaluate(x));
                var avg = eval_list.Average();
                var max = eval_list.Max();

                series.Points.AddXY(it, avg);
                series2.Points.AddXY(it, max);

                this.output.AppendText(String.Format(" iteracja nr {0}  avg:{1:0.000}  max:{2:0.000}\n", it++, avg, max));

                //wydzielenie podzbiorow
                var planyGrup = new Dictionary<Grupa, IList<Timetable>>();

                foreach (var osobnik in population)
                {
                    var lista_grup = osobnik.Gens.Select(x => x.Grupa).Distinct();
                    foreach (var grupa in lista_grup)
                    {
                        Application.DoEvents();

                        var planGrupy = new Timetable(mutation);

                        IList<TimetableLocus> loci =
                            (from locus in osobnik.Loci
                             where osobnik[locus].Grupa.Equals(grupa)
                             select locus).ToList();

                        foreach (var locus in loci)
                            planGrupy[locus] = osobnik[locus];

                        IList<Timetable> lista;
                        if (!planyGrup.TryGetValue(grupa, out lista))
                        {
                            lista = new List<Timetable>();
                            planyGrup.Add(grupa, lista);
                        }

                        lista.Add(planGrupy);
                    }
                }

                var listaGrup = planyGrup.Keys.ToList();

                for (int i = 0; i < listaGrup.Count; i++)
                {
                    Application.DoEvents();

                    IGeneticAlgorithmEngine<Timetable> ga_grupy;
                    ga_grupy = new GeneticAlgorithmEngine<Timetable, TimetableLocus, Zajecia>(planyGrup[listaGrup[i]], selector, reproducer, 20);
                    ga_grupy.Iterate(() =>
                    {
                        //planGrupy.Value = ga_grupy.Population;
                        return ga_grupy.Population.Select(x => evalSelector.Evaluate(x)).Average() > 0.95;
                    });
                    planyGrup[listaGrup[i]] = ga_grupy.Population;
                }

                //polaczenie podzbiorow
                var nowaPopulacja = new List<Timetable>();
                for (int i = 0; i < population.Count; i++)
                {
                    Application.DoEvents();

                    var osobnik = new Timetable(mutation);
                    foreach (var planGrupy in planyGrup)
                    {
                        osobnik.Concat(planGrupy.Value[i]);
                    }
                }
            } while ((population.Select(x => evalSelector.Evaluate(x)).Average() < 0.95) && !stop_button);

            if (!stop_button)
            {
                //wypisanie wyniku

                this.output.AppendText("ZAKOŃCZONO\n");
                stop_Click(null, null);
                stop_button = false;
            }
            else
            {
                try
                {
                    output.AppendText("STOP\n");
                }
                catch (Exception){}
            }
        }
Ejemplo n.º 54
0
        // Takes the part of the timetable name which shows when the timetable runs,
        // and adjusts the properties of the timeable which record such information.
        public static void ProcessDaysRun(Timetable timetable, string daysRunPart)
        {
            // The values to look for in the filename to see on which days the timetable runs
            string[] whatToLookFor = { "PH", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su" };
            for (int i = 0; i < 8; i++)
            {
                // Check for each value and set each part of the array accordingly
                if (daysRunPart.Contains(whatToLookFor[i])) { timetable.daysRun[i] = true; }
            }

            // Check for whether it runs specificall in termtime or holidays, and set the enum
            if (daysRunPart.Contains("Sc"))
            {
                timetable.schoolTime = SchoolDays.TermOnly;
            }
            else if (daysRunPart.Contains("NS"))
            {
                timetable.schoolTime = SchoolDays.HolidayOnly;
            }
            // No additional 'else' is required as it is set to run on all days by default.
        }