示例#1
0
    static void Main(string[] args)
    {
        Dictionary <string, StopInfo> stopList = new Dictionary <string, StopInfo>();

        string startPoint = Console.ReadLine();
        string endPoint   = Console.ReadLine();

        int N = int.Parse(Console.ReadLine());

        for (int i = 0; i < N; i++)
        {
            string   stopName = Console.ReadLine();
            StopInfo newStop  = new StopInfo(stopName);
            stopList.Add(newStop.id, newStop);
        }
        int M = int.Parse(Console.ReadLine());

        for (int i = 0; i < M; i++)
        {
            string route = Console.ReadLine();
            var    path  = route.Split(' ');

            var start = stopList[path[0]];
            var end   = stopList[path[1]];

            var dist = start.Distance(end);

            start.routes.Add(end, dist);
        }

        var a = stopList[startPoint];
        var b = stopList[endPoint];

        Pathfinding.GetShortestPath(a, b, stopList);
    }
示例#2
0
        /// <summary>
        /// Defines brush to draw stop element.
        /// </summary>
        /// <param name="stop">Stop.</param>
        /// <param name="context">Drawing context.</param>
        /// <returns></returns>
        private static Brush _GetFillBrush(StopInfo stopInfo, GanttItemElementDrawingContext context)
        {
            Debug.Assert(context != null);

            // Define selected color.
            if (context.DrawSelected)
            {
                return(GanttControlHelper.GetSelectedBrush());
            }

            // Define location color.
            if (stopInfo.Stop.StopType == StopType.Location)
            {
                return(GanttControlHelper.GetLocationBrush());
            }

            // Define Break color.
            if (stopInfo.Stop.StopType == StopType.Lunch)
            {
                return(GanttControlHelper.GetBreakBrush());
            }

            // Define locked color.
            if (stopInfo.Stop.IsLocked || (stopInfo.Route != null && stopInfo.Route.IsLocked))
            {
                return(GanttControlHelper.GetLockedBrush(stopInfo.Route.Color));
            }

            // If stop is Order, not locked, not selected and not dragged over - return normal fill color.
            return(GanttControlHelper.GetFillBrush(stopInfo.Route.Color));
        }
示例#3
0
        public async Task SearchByStopCodeAsync()
        {
            IsLoading = true;

            try
            {
                StopInfo info = await new ArrivalsService().GetByStopCodeAsync(stopCode);

                IsLoading = false;

                StopInfo  = info;
                Direction = stopInfo.Lines.FirstOrDefault(l => !String.IsNullOrEmpty(l.Direction))?.Direction;

                MessengerInstance.Send(new ShowMapMessage(true, StopInfo.Lines.Count));
                await HistoryDomain.AddAsync(stopCode, stopInfo.Name);
            }
            catch (StopNotFoundException)
            {
                await ApplicationService.DisplayAlertAsync("Няма данни", $"Няма данни за спирка {stopCode}.", "OK");
            }
            catch (Exception e)
            {
                await ApplicationService.DisplayAlertAsync("Грешка", e.Message, "OK");
            }
        }
示例#4
0
    public static void GetShortestPath(StopInfo start, StopInfo end, Dictionary <string, StopInfo> stopList)
    {
        HashSet <StopInfo> closedSet = new HashSet <StopInfo>();
        HashSet <StopInfo> openSet   = new HashSet <StopInfo>();

        openSet.Add(start);

        /*foreach (var stop in stopList.Values)
         * {
         *  stop.gScore = 9999;
         *  stop.fScore = 9999;
         *  stop.parent = null;
         *  //prev.Add(stop, null);
         * }*/

        start.gScore = 0;
        start.fScore = start.Distance(end);

        while (openSet.Count > 0)
        {
            var current = openSet.OrderBy(n => n.fScore).FirstOrDefault();

            if (current == end)
            {
                PrintPath(current);
                return;
            }

            openSet.Remove(current);
            closedSet.Add(current);

            foreach (var pair in current.routes)
            {
                var neighbour = pair.Key;
                var distance  = pair.Value;

                if (closedSet.Contains(neighbour))
                {
                    continue;
                }

                var alternativeDistance = current.gScore + distance;
                if (!openSet.Contains(neighbour))
                {
                    openSet.Add(neighbour);
                }
                else if (alternativeDistance >= neighbour.gScore)
                {
                    continue;
                }

                neighbour.parent = current;
                neighbour.gScore = alternativeDistance;
                neighbour.fScore = alternativeDistance + neighbour.Distance(end);
            }
        }

        Console.WriteLine("IMPOSSIBLE");
    }
        /// <summary>
        /// This function is responsible for the series of actions that will be performed when this button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void information_Click(object sender, RoutedEventArgs e)
        {
            Button a = (Button)sender;

            tempStop = (BO.Stop)a.DataContext;
            var ab = new StopInfo(tempStop);

            ab.Height = 300;
            ab.Width  = 600;
            ab.Show();
        }
示例#6
0
    public List <StopInfo> stopInfos;    // indexed by stopId

    public void LoadStopsData(System.Action dataLoadedCallback)
    {
        this.stopInfos = new List <StopInfo>(7030);        // highest stopId is 7027, but there are tons of gaps within that

        StopInfo nullStop = new StopInfo();

        nullStop.stopId = -1;

        System.Action <CSVLineDataHandler> lineProcessor = delegate(CSVLineDataHandler lineComponents) {
            int stopId = int.Parse(lineComponents["stop_id"]);

            StopInfo newStopInfo = new StopInfo();
            newStopInfo.latlong  = new LatitudeLongitude(double.Parse(lineComponents["stop_lat"]), double.Parse(lineComponents["stop_lon"]));
            newStopInfo.stopId   = stopId;
            newStopInfo.stopName = lineComponents["stop_name"];

            while (this.stopInfos.Count <= (stopId))
            {
                this.stopInfos.Add(nullStop);
            }

            if (this.stopInfos[stopId].stopId >= 0)
            {
                Debug.LogError("Stop id collision, two stops found for stop id: " + stopId);
            }

            this.stopInfos[stopId] = newStopInfo;

//			if (this.stopInfos.Count > stopId) {
//				Debug.LogWarning("Out of order stop detected at count: " + this.stopInfos.Count + " stopId: " + stopId);
//			}
//			else {
//				while (this.stopInfos.Count < (stopId))
//					this.stopInfos.Add(nullStop);
//
//				this.stopInfos.Add(newStopInfo);
//			}
        };

        this.ProcessCSVData(this.stopsTextData.text, lineProcessor, 5, dataLoadedCallback);

                #if UNITY_EDITOR
        for (int i = 0; i < this.stopInfos.Count; i++)
        {
            StopInfo stopInfo = this.stopInfos[i];

            if (stopInfo.stopName != null && stopInfo.stopId != i)
            {
                Debug.LogWarning("Stop Id doesn't match index at index: " + i + " stopId: " + stopInfo.stopId);
            }
        }
                #endif
    }
示例#7
0
    public static void PrintPath(StopInfo current)
    {
        List <string> pathNames = new List <string>();

        while (current != null)
        {
            pathNames.Add(current.name);
            current = current.parent;
        }

        pathNames.Reverse();
        pathNames.ForEach(n => Console.WriteLine(n));
    }
示例#8
0
    IEnumerator GetRequest(string uri)
    {
        //store l'url de requête dans une unitywebrequest
        UnityWebRequest request = UnityWebRequest.Get(uri);

        //ajoute les headers d'application + token à la requete
        request.SetRequestHeader("Accept", "application/json");
        request.SetRequestHeader("Authorization", "Bearer 01dc5ca7d2c53c40771fcce562bb0377");

        //envoi la requête et attend la réponse
        yield return(request.Send());

        GameObject status = GameObject.Find("Status");

        status.GetComponent <SceneStatus>().readyToOpen = true;
        // Show results as text
        Debug.Log(request.downloadHandler.text);
        StopInfo stibData = new StopInfo();

        stibData = JsonUtility.FromJson <StopInfo>(request.downloadHandler.text);
        for (int i = 0; i < stibData.points[0].passingTimes.Length; i++)
        {
            waitingLines.Add(new WaitingLine(int.Parse(stibData.points[0].passingTimes[i].lineId), (transformDate(stibData.points[0].passingTimes[i].expectedArrivalTime) - DateTime.Now).TotalMinutes));
        }
        waitingLines.Sort();
        for (int i = 0; i < waitingLines.Count; i++)
        {
            GameObject lineUI = GameObject.Find("Line" + i);
            if (waitingLines[i].lineNumber == 92)
            {
                lineUI.GetComponent <Image>().sprite = line92;
            }
            if (waitingLines[i].lineNumber == 93)
            {
                lineUI.GetComponent <Image>().sprite = line93;
            }
            GameObject timeToWaitUI = GameObject.Find("TimeToWait" + i);
            if (Math.Round(waitingLines[i].waitingTime) <= 0)
            {
                timeToWaitUI.GetComponent <Text>().text = char.ConvertFromUtf32(0x2193) + char.ConvertFromUtf32(0x2193);
            }
            else
            {
                timeToWaitUI.GetComponent <Text>().text = Math.Round(waitingLines[i].waitingTime).ToString().PadLeft(2, '0') + "'";
            }
        }
        Debug.Log((transformDate(stibData.points[0].passingTimes[0].expectedArrivalTime) - DateTime.Now).Minutes);
        Debug.Log(stibData.points[0].passingTimes[0].lineId);
    }
示例#9
0
        public void Process([NotNull] QaErrorEventArgs args)
        {
            Assert.ArgumentNotNull(args, nameof(args));

            QaError qaError = args.QaError;

            QualitySpecificationElement element = _elementsByTest[qaError.Test];

            QualityCondition qualityCondition = element.QualityCondition;

            if (element.StopOnError)
            {
                foreach (InvolvedRow involvedRow in qaError.InvolvedRows)
                {
                    var stopInfo = new StopInfo(qualityCondition, qaError.Description);
                    _rowsWithStopConditions.Add(involvedRow.TableName, involvedRow.OID,
                                                stopInfo);
                }
            }

            if (IsIssueGeometryOutsideTestPerimeter(qaError, qualityCondition))
            {
                args.Cancel = true;
                return;
            }

            IssueStats issueStats = GetIssueStats(qualityCondition);

            if (ExistsExceptionFor(qaError, element))
            {
                issueStats.AddException();
                return;
            }

            issueStats.AddIssue();

            if (element.AllowErrors)
            {
                WarningCount++;
            }
            else
            {
                ErrorCount++;
                Fulfilled = false;
            }

            _issueWriter.WriteIssue(qaError, element);
        }
示例#10
0
        public async Task <Passages> GetPassagesByStopId(int id, StopPassagesType type = StopPassagesType.Departure, StopType stopType = StopType.Tram | StopType.Bus)
        {
            StopInfo tramInfo;
            StopInfo busInfo;

            if ((stopType & StopType.Tram) == StopType.Tram)
            {
                var response = await Request.StopPassages(id, type, false).ConfigureAwait(false);

                tramInfo = JsonConvert.DeserializeObject <StopInfo>(response.Data);
            }
            else
            {
                tramInfo = new StopInfo {
                    ActualPassages = new List <StopPassage>(), OldPassages = new List <StopPassage>()
                }
            };
            if ((stopType & StopType.Bus) == StopType.Bus)
            {
                var response = await Request.StopPassages(id, type, true).ConfigureAwait(false);

                busInfo = JsonConvert.DeserializeObject <StopInfo>(response.Data);
            }
            else
            {
                busInfo = new StopInfo {
                    ActualPassages = new List <StopPassage>(), OldPassages = new List <StopPassage>()
                }
            };
            var result = new Passages();

            result.ActualPassages = tramInfo.ActualPassages
                                    .Select(ap => PassageConverter.Convert(ap))
                                    .Concat(busInfo.ActualPassages
                                            .Select(ap => PassageConverter.Convert(ap, true)))
                                    .OrderBy(p => p.ActualRelative)
                                    .ToList();
            result.OldPassages = tramInfo.OldPassages
                                 .Select(ap => PassageConverter.Convert(ap))
                                 .Concat(busInfo.OldPassages
                                         .Select(ap => PassageConverter.Convert(ap, true)))
                                 .OrderBy(p => p.ActualRelative)
                                 .ToList();
            return(result);
        }
示例#11
0
        public StopInfo ParseStopInfo(string json)
        {
            JObject  jObject = JObject.Parse(json);
            StopInfo result  = new StopInfo();

            foreach (var bus in jObject["delay"])
            {
                result.BusInfos.Add(new BusInfo
                {
                    EstimatedTime   = bus["estimatedTime"].ToString(),
                    Headsign        = bus["headsign"].ToString(),
                    RouteID         = bus["routeId"].ToString(),
                    TheoreticalTime = bus["theoreticalTime"].ToString()
                });
            }

            return(result);
        }
示例#12
0
        /// <summary>
        /// Draws stop.
        /// </summary>
        /// <param name="stopInfo">Information about stop. Used for optimizing performance.</param>
        /// <param name="context">DrawingContext.</param>
        /// <remarks>
        /// Getting some relation properties (like Route, AssociatedObject) from stop takes some time
        /// due to the data layer implementation specifics. To improve perofmrance on rendering of
        /// large amount of stops use this method passing cached value of stop's properties.
        /// </remarks>
        public static void DrawStop(StopInfo stopInfo, GanttItemElementDrawingContext context)
        {
            Debug.Assert(stopInfo.Stop != null);
            Debug.Assert(stopInfo.Route != null);
            Debug.Assert(context != null);

            Brush fillBrush = _GetFillBrush(stopInfo, context);

            // Draw element.
            _DrawRectangle(fillBrush, context);

            // Draw violated icon.
            if (stopInfo.Stop.IsViolated)
            {
                Rect elementRect      = _GetElementRect(context);
                Rect violatedIconRect = new Rect(elementRect.Left + GAP_SIZE, elementRect.Top + GAP_SIZE, ICON_SIZE, ICON_SIZE);

                violatedIconRect.Width = (violatedIconRect.Width > elementRect.Width) ? elementRect.Width : violatedIconRect.Width;

                ImageBrush brush = GanttControlHelper.GetViolatedBrush();
                context.DrawingContext.DrawImage(brush.ImageSource, violatedIconRect);
            }
        }
示例#13
0
        /// <summary>
        /// Draws stop.
        /// </summary>
        /// <param name="stopInfo">Information about stop. Used for optimizing performance.</param>
        /// <param name="context">DrawingContext.</param>
        /// <remarks>
        /// Getting some relation properties (like Route, AssociatedObject) from stop takes some time
        /// due to the data layer implementation specifics. To improve perofmrance on rendering of
        /// large amount of stops use this method passing cached value of stop's properties.
        /// </remarks>
        public static void DrawStop(StopInfo stopInfo, GanttItemElementDrawingContext context)
        {
            Debug.Assert(stopInfo.Stop != null);
            Debug.Assert(stopInfo.Route != null);
            Debug.Assert(context != null);

            Brush fillBrush = _GetFillBrush(stopInfo, context);

            // Draw element.
            _DrawRectangle(fillBrush, context);

            // Draw violated icon.
            if (stopInfo.Stop.IsViolated)
            {
                Rect elementRect = _GetElementRect(context);
                Rect violatedIconRect = new Rect(elementRect.Left + GAP_SIZE, elementRect.Top + GAP_SIZE, ICON_SIZE, ICON_SIZE);

                violatedIconRect.Width = (violatedIconRect.Width > elementRect.Width) ? elementRect.Width : violatedIconRect.Width;

                ImageBrush brush = GanttControlHelper.GetViolatedBrush();
                context.DrawingContext.DrawImage(brush.ImageSource, violatedIconRect);
            }
        }
示例#14
0
 public Task BusNoLongerDepartedStop(StopInfo stop, int vehicleId)
 {
     return(Task.FromResult(0));
 }
示例#15
0
 public Task BusHasDepartedStop(StopInfo stop, int vehicleId, TimeSpan delta)
 {
     return(Task.FromResult(0));
 }
示例#16
0
 public Task BusNoLongerApproachingStop(StopInfo stop, int vehicleId)
 {
     return(Task.FromResult(0));
 }
示例#17
0
 public Task BusApproachingStop(StopInfo stop, int vehicleId, TimeSpan delta)
 {
     return(Task.FromResult(0));
 }
示例#18
0
        /// <summary>
        /// Defines brush to draw stop element.
        /// </summary>
        /// <param name="stop">Stop.</param>
        /// <param name="context">Drawing context.</param>
        /// <returns></returns>
        private static Brush _GetFillBrush(StopInfo stopInfo, GanttItemElementDrawingContext context)
        {
            Debug.Assert(context != null);

            // Define selected color.
            if (context.DrawSelected)
                return GanttControlHelper.GetSelectedBrush();

            // Define location color.
            if (stopInfo.Stop.StopType == StopType.Location)
                return GanttControlHelper.GetLocationBrush();

            // Define Break color.
            if (stopInfo.Stop.StopType == StopType.Lunch)
                return GanttControlHelper.GetBreakBrush();

            // Define locked color.
            if (stopInfo.Stop.IsLocked || (stopInfo.Route != null && stopInfo.Route.IsLocked))
                return GanttControlHelper.GetLockedBrush(stopInfo.Route.Color);

            // If stop is Order, not locked, not selected and not dragged over - return normal fill color.
            return GanttControlHelper.GetFillBrush(stopInfo.Route.Color);
        }
示例#19
0
        public StopInfoResponse GetStopData(string stop)
        {
            StopInfoResponse response = new StopInfoResponse();

            response.ResponseTime = dateTimeService.Current();

            if (dataCache.GetCachedResponse(stop) != null && dataCache.GetCachedResponse(stop).ResponseTime == response.ResponseTime)
            {
                response.StopInfos = dataCache.GetCachedResponse(stop).StopInfos;
            }
            else
            {
                var stops = GetStops().Where(x => x.Name.ToLower() == stop.ToLower());
                var buses = GetBuses();

                using (var client = new WebClient())
                {
                    foreach (var s in stops) //each stopInfo
                    {
                        var      stopInfoJson = client.DownloadString(new Uri("http://87.98.237.99:88/delays?stopId=" + s.Id));
                        StopInfo info         = dataParseService.ParseStopInfo(stopInfoJson);

                        info.Coordinates = s.Coordinates;
                        response.StopInfos.Add(info);
                    }
                }


                foreach (var s in response.StopInfos)
                {
                    foreach (var r in s.BusInfos) // assign Bus names instead of ID's
                    {
                        r.RouteID = buses.Where(x => x.Id == r.RouteID).Select(y => y.Name).FirstOrDefault();
                    }
                }

                dataCache.CacheResponse(stop, response);
            }

            foreach (var s in response.StopInfos)
            {
                if (s.BusInfos.Count > 0) //ask for a weather for active stops
                {
                    //ask Cache first
                    using (var client = new WebClient())
                    {
                        if (weatherCache.GetCachedWeather(s.Coordinates) != null &&
                            weatherCache.GetCachedWeather(s.Coordinates).Time < dateTimeService.Now.AddMinutes(15))
                        {
                            s.WeatherInfo = weatherCache.GetCachedWeather(s.Coordinates);
                        }
                        else
                        {
                            //get data and cache them
                            var         weatherInfoJson = client.DownloadString(new Uri("http://api.openweathermap.org/data/2.5/weather?lat=" + s.Coordinates.Latitude + "&lon=" + s.Coordinates.Longitude + "&appid=" + weatherApiKey));
                            WeatherInfo weatherInfo     = dataParseService.ParseWeatherInfo(weatherInfoJson);
                            s.WeatherInfo      = weatherInfo;
                            s.WeatherInfo.Time = dateTimeService.Now;
                            weatherCache.CacheWeather(s.Coordinates, weatherInfo);
                        }
                    }
                }
            }

            return(response);
        }
示例#20
0
        protected override void Seed(TransportContext context)
        {
            base.Seed(context);

            Transport transport1 = new Transport()
            {
                Name = "AutoBus"
            };
            Transport transport2 = new Transport()
            {
                Name = "TrolleyBus"
            };
            Transport transport3 = new Transport()
            {
                Name = "Tram"
            };
            Transport transport4 = new Transport()
            {
                Name = "AutoBus"
            };
            Transport transport5 = new Transport()
            {
                Name = "TrolleyBus"
            };
            Transport transport6 = new Transport()
            {
                Name = "Tram"
            };

            StopInfo stop1 = new StopInfo()
            {
                Name = "ДС Веснянка"
            };
            StopInfo stop2 = new StopInfo()
            {
                Name = "Кавальская слобода"
            };
            StopInfo stop3 = new StopInfo()
            {
                Name = "Гостиница Юбилейная"
            };
            StopInfo stop4 = new StopInfo()
            {
                Name = "Магазин Спутник"
            };
            StopInfo stop5 = new StopInfo()
            {
                Name = "Вокзал"
            };
            StopInfo stop6 = new StopInfo()
            {
                Name = "ДС Дружная"
            };
            StopInfo stop7 = new StopInfo()
            {
                Name = "Брилевичи"
            };



            RouteInfo route1 = new RouteInfo()
            {
                Name = "ДС Веснянка - Вокзал", Number = "Маршрут 1"
            };

            route1.Transports = new List <Transport> {
                transport1, transport2, transport3
            };


            RouteInfo route2 = new RouteInfo()
            {
                Name = "ДС Дружная - Брилевичи", Number = "Маршрут 2"
            };

            route2.Transports = new List <Transport> {
                transport4, transport5, transport6
            };


            RoadtoStop roadtostop1 = new RoadtoStop()
            {
                Routes = route1, Stops = stop1, VisitTime = new DateTime(2008, 5, 1, 8, 30, 52)
            };

            context.Routes.AddRange(new[] { route1, route2 });
            context.SaveChanges();
        }