public static string GetSegmentList(CoordinatesModel coordinates) { try { HttpClient httpClient = GetClient(); if (httpClient == null) { return(null); } var task = httpClient.SendAsync(GetHttpRequestMessage(coordinates)); task.Wait(); if (task.Result.IsSuccessStatusCode) { var jsontask = task.Result.Content.ReadAsStringAsync(); jsontask.Wait(); PulseSegmentListModel segmentList = JsonConvert.DeserializeObject <PulseSegmentListModel>(jsontask.Result); return(string.Join(", ", segmentList.data)); } return("Error while getting segment list. Check API key!"); } catch (Exception ex) { Debug.WriteLine("HttpHelper.QueryPulse(): Error: " + ex.Message); return("Error while getting segment list. Check API key!"); } }
public async Task <double> GetAverageEnergyAsync(CoordinatesModel firstCoordinate, CoordinatesModel secondCoordinate) { var rectTopLeft = _mapper.Map <Coordinates>(firstCoordinate); var rectBottomRight = _mapper.Map <Coordinates>(secondCoordinate); return(await Task.Run(() => _analizer.GetAverageEnergy(rectTopLeft, rectBottomRight))); }
public async Task <CoordinatesModel> ApproximatePointAsync(CoordinatesModel coords) { var url = $"{DockerBaseUrl}/examples/astar/closestNode?lat={coords.Latitude.ToString(CultureInfo.InvariantCulture)}&long={coords.Longitude.ToString(CultureInfo.InvariantCulture)}"; Console.WriteLine($"URL is {url}"); var msg = new HttpRequestMessage(HttpMethod.Get, url); var httpClient = this._httpClientFactory.CreateClient(); { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"neo4j:Qwerty123"))); var response = await httpClient.SendAsync(msg).ConfigureAwait(false); var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); // todo: if not successful - throw a meaningful error. var resp = JsonConvert.DeserializeObject <ClosestNodeResponse>(responseContent); Debug.WriteLine($"Node.NodeId = {resp.Id}"); return(new CoordinatesModel { NodeId = long.Parse(resp.Id), Latitude = resp.Lat, Longitude = resp.Lon }); } }
public static CoordinatesModel GetCoordinates(string input) { CoordinatesModel result = new CoordinatesModel(); try { string[] _ = input.Split(','); if (_.Length >= 4) { result.X = int.Parse(_[0]); result.Y = int.Parse(_[1]); result.DeltaX = int.Parse(_[2]); result.DeltaY = int.Parse(_[3]); } else { Console.WriteLine("something wrong with the bounding box coordinates format"); } } catch (Exception e) { Console.WriteLine("Exception " + e.ToString()); throw; } return(result); }
public IActionResult Index(CoordinatesModel model) { // sets result for current rover var currentRover = model.Results[model.Results.Count - 1]; try { // sets end coordinates _coordinatesService.SetEnd(model.MaxCoordinates); // sets start position of rover _coordinatesService.SetCurrentPosition(currentRover.CurrentPosition); // calculates coordinates depending on route currentRover.Result = _coordinatesService.Calculate(currentRover.Movement); // adds result to model model.Results.Add(new RoverResultModel()); ModelState.Clear(); } catch (Exception ex) { ModelState.AddModelError("CustomError", ex.Message); } return(View(model)); }
private double HaversineFormulae(CoordinatesModel coordinates1, CoordinatesModel coordinates2) { var deltaLambda = Math.Abs(coordinates1.Longitude.ToRadians() - coordinates2.Longitude.ToRadians()); var deltaPhi = Math.Abs(coordinates1.Latitude.ToRadians() - coordinates2.Latitude.ToRadians()); var deltaSigma = Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(deltaPhi / 2), 2) + Math.Cos(coordinates1.Latitude.ToRadians()) * Math.Cos(coordinates2.Latitude.ToRadians()) * Math.Pow(Math.Sin(deltaLambda / 2), 2))); return(Math.Round(2 * _earthRadius * deltaSigma, 2)); }
public IActionResult Index() { // Loads empty model var model = new CoordinatesModel(); model.Results = new List <RoverResultModel>(); model.Results.Add(new RoverResultModel()); return(View(model)); }
public HttpResponseMessage DataByCoordinates(CoordinatesModel coOrdinates) { IRequestModel tmp = coOrdinates; GenerateURL urlobj = new GenerateURL(Endpoints.ByCoordinates, tmp.Get()); return(new HttpResponseMessage() { Content = new StringContent(Test.CreateObject(urlobj.GeneratedURL)) }); }
public static void SplitPoints_ShouldThrowException_WhenArrayCountIsNotEvenHelper <T>() { var random = new Random(); var readOnlyList = (IReadOnlyList <T>)Enumerable .Range(0, 1 + 2 * random.Next(5)) .Select(r => random.Next(10)) .ToList(); Assert.ThrowsException <ArgumentException>(() => CoordinatesModel.SplitCoordinates(readOnlyList), "The array must contain an even number of elements"); }
public void FlightService_CalculateDistance(double latitude1, double longitude1, double latitude2, double longitude2, double distanceBetween) { var coordinate1 = new CoordinatesModel(latitude1, longitude1); var coordinate2 = new CoordinatesModel(latitude2, longitude2); var flightService = new FlightService(); var resultingDistance = flightService.CalculateDistanceWithHaversineFormulae(coordinate1, coordinate2); Assert.AreEqual(distanceBetween, resultingDistance); }
public static IEnumerable <TweetModel> SearchTweets(CoordinatesModel coordinates, double radius) { using (var db = new LiteDatabase(@"TweetsDB.db")) { // Get tweet collection var tweets = db.GetCollection <TweetModel>("tweets"); var Result = tweets.Find(tweetToCheck => isLocInRadOfTweet(coordinates, radius, tweetToCheck)); return(Result); } }
public void UpdateCoordinates(CoordinatesModel coordinates) { var entity = _driverRepository.Get().FirstOrDefault(x => x.Device.HardwareId == coordinates.DeviceId); if (entity == null) { return; } entity.Latitude = coordinates.Latitude; entity.Longitude = coordinates.Longitude; _driverRepository.Put(entity); }
private double VicentyFormulae(CoordinatesModel coordinates1, CoordinatesModel coordinates2) { var deltaLambda = Math.Abs(coordinates1.Longitude.ToRadians() - coordinates2.Longitude.ToRadians()); var numerator = Math.Sqrt(Math.Pow(Math.Cos(coordinates2.Latitude.ToRadians()) * Math.Sin(deltaLambda), 2) + Math.Pow(Math.Cos(coordinates1.Latitude.ToRadians()) * Math.Sin(coordinates2.Latitude.ToRadians() - Math.Sin(coordinates1.Latitude.ToRadians() * Math.Cos(coordinates2.Latitude.ToRadians()) * Math.Cos(deltaLambda))), 2)); var denominator = Math.Sin(coordinates1.Latitude.ToRadians()) * Math.Sin(coordinates2.Latitude.ToRadians()) + Math.Cos(coordinates1.Latitude.ToRadians()) * Math.Cos(coordinates2.Latitude.ToRadians()) * Math.Cos(deltaLambda); var deltaSigma = Math.Atan(numerator / denominator); return(Math.Round(2 * _earthRadius * deltaSigma, 2)); }
/// <summary> /// Function to determine if a location of tweet matches the location and radius /// </summary> private static bool isLocInRadOfTweet(CoordinatesModel coords, double rad, TweetModel TweetToCheck) { if (!(TweetToCheck.Coordinates is null)) { // Get Distance double Distance = GetDistance(coords.Latitude, coords.Longitude, TweetToCheck.Coordinates.Latitude, TweetToCheck.Coordinates.Longitude); // If the distance is less than the rad then its within return(Distance < rad); }
public async Task<ActionResult> Index() { string nextUrl = ""; logger.LogInfo(Enums.LogType.Logging, "Entering HomeController.Index"); Stopwatch timer = Stopwatch.StartNew(); CoordinatesModel model = new CoordinatesModel(); IList<Status> savedStatuses = await statusRepository.GetStatuses(); if (savedStatuses.Any()) { foreach (var status in savedStatuses) { if (status.geo != null && status.geo.coordinates != null && status.geo.coordinates.Any()) model.Coordinates.Add(status.geo.coordinates); } } else { for (int i = 0; i < 100; i++) { string query = i == 0 ? "?q=%23surfsup" : nextUrl; if (string.IsNullOrEmpty(query)) break; StatusSearchResponse searchResponse = await TwitterApi.SearchStatus(query); if (searchResponse != null && searchResponse.statuses != null && searchResponse.statuses.Any()) { foreach (var status in searchResponse.statuses) { if (status.geo != null && status.geo.coordinates != null && status.geo.coordinates.Any()) model.Coordinates.Add(status.geo.coordinates); } await statusRepository.SaveStatuses(searchResponse.statuses); } nextUrl = searchResponse.search_metadata.next_results; } } timer.Stop(); logger.LogInfo(Enums.LogType.Logging, string.Format("Exiting HomeController.Index in {0}", timer.ElapsedMilliseconds)); return View(model); }
public HttpResponseMessage Post([FromBody] CoordinatesModel parameter) { try { GxRjxxBusiness gxRjxxBusiness = new GxRjxxBusiness(); var entity = gxRjxxBusiness.Find(parameter.Id); if (entity == null) { var loginResult = new DataResult <string>(); loginResult.ErrorCode = "404"; loginResult.Result = false; loginResult.Message = "未找到人井信息"; return(Request.CreateResponse(HttpStatusCode.OK, loginResult)); } entity.LONGITUDE = parameter.Longitude; entity.LATITUDE = parameter.Latitude; entity.MODIFYBY = "接口数修改"; entity.MODIFYTIME = DateTime.Now; gxRjxxBusiness.Update(entity); var dataResult = new DataResult <string>(); if (gxRjxxBusiness.SaveChange() > 0) { dataResult.ErrorCode = "200"; dataResult.Result = true; dataResult.Message = "人井坐标信息修改成功"; dataResult.Data = ""; return(Request.CreateResponse(HttpStatusCode.OK, dataResult)); } else { dataResult.ErrorCode = "500"; dataResult.Result = false; dataResult.Message = "人井坐标信息修改失败"; dataResult.Data = ""; return(Request.CreateResponse(HttpStatusCode.OK, dataResult)); } } catch (Exception ex) { DataResult <string> dataResult = new DataResult <string>(); dataResult.ErrorCode = "100101"; dataResult.Result = false; dataResult.Message = "获取数据异常:" + (ex.InnerException == null ? ex.Message : ex.InnerException.Message); return(Request.CreateResponse(HttpStatusCode.OK, dataResult)); } }
public static HttpRequestMessage GetHttpRequestMessage(CoordinatesModel coordinates) { var payload = new Dictionary <string, double> { { "latitude", coordinates.Latitude }, { "longitude", coordinates.Longitude } }; var json = JsonConvert.SerializeObject(payload, Formatting.Indented); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Global.SegmentMembershipUrl) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; return(request); }
private void PulseSessionStartHandler(object sender, CriterionEventArgs e) { var locker = LockingSingleton.GetInstance(); if (Monitor.TryEnter(locker.lockObj)) { try { if (!locker.isLocked) { locker.isLocked = true; Debug.WriteLine("PulseSessionStartHandler(): START"); string ip = IpHelper.GetIPAddress(new HttpRequestWrapper(HttpContext.Current.Request)); Debug.WriteLine("PulseSessionStartHandler(): IP:" + ip); CoordinatesModel coordinates = GeoLocationHelper.GetCoordinatesFromIp(IPAddress.Parse(ip)); if (coordinates == null) { e.HttpContext.Session["pulse_segments"] = new string[0]; locker.isLocked = false; return; } QueryPulse(coordinates, e.HttpContext.Session, locker); Debug.WriteLine("PulseSessionStartHandler(): END"); } else { Debug.WriteLine("PulseSessionStartHandler(): Another thread already started"); } } finally { // Ensure that the lock is released. Monitor.Exit(locker.lockObj); Debug.WriteLine("PulseSessionStartHandler(): Lock released"); } } }
private static void Move(CoordinatesModel selectedRover, int upperRightX, int upperRightY, List <CoordinatesModel> rovers) { if (selectedRover.Orientation.Value == OrientationType.North.Value) { if (selectedRover.Y < upperRightY) { if (!rovers.Any(r => r.X == selectedRover.X && r.Y == (selectedRover.Y + 1))) { selectedRover.Y++; } } } else if (selectedRover.Orientation.Value == OrientationType.West.Value) { if (selectedRover.X > 0) { if (!rovers.Any(r => r.X == (selectedRover.X - 1) && r.Y == selectedRover.Y)) { selectedRover.X--; } } } else if (selectedRover.Orientation.Value == OrientationType.South.Value) { if (selectedRover.Y > 0) { if (!rovers.Any(r => r.X == selectedRover.X && r.Y == (selectedRover.Y - 1))) { selectedRover.Y--; } } } else if (selectedRover.Orientation.Value == OrientationType.East.Value) { if (selectedRover.X < upperRightX) { if (!rovers.Any(r => r.X == (selectedRover.X + 1) && r.Y == selectedRover.Y)) { selectedRover.X++; } } } }
private static void Turn(CoordinatesModel selectedRover, char instruction) { if (instruction.ToString() == InstructionType.TurnLeft.Value) { if (selectedRover.Orientation.Value == OrientationType.North.Value) { selectedRover.Orientation.Value = OrientationType.West.Value; } else if (selectedRover.Orientation.Value == OrientationType.West.Value) { selectedRover.Orientation.Value = OrientationType.South.Value; } else if (selectedRover.Orientation.Value == OrientationType.South.Value) { selectedRover.Orientation.Value = OrientationType.East.Value; } else if (selectedRover.Orientation.Value == OrientationType.East.Value) { selectedRover.Orientation.Value = OrientationType.North.Value; } } else { if (selectedRover.Orientation.Value == OrientationType.North.Value) { selectedRover.Orientation.Value = OrientationType.East.Value; } else if (selectedRover.Orientation.Value == OrientationType.East.Value) { selectedRover.Orientation.Value = OrientationType.South.Value; } else if (selectedRover.Orientation.Value == OrientationType.South.Value) { selectedRover.Orientation.Value = OrientationType.West.Value; } else if (selectedRover.Orientation.Value == OrientationType.West.Value) { selectedRover.Orientation.Value = OrientationType.North.Value; } } }
public static CoordinatesModel ConvertLatToDMS(double?latitud, double?longitud, double?altitud = null) { if (latitud.HasValue && longitud.HasValue) { //https://stackoverflow.com/a/27996566 string latitudDir = (latitud.Value >= 0 ? "N" : "S"); latitud = Math.Abs(latitud.Value); double latMinPart = ((latitud.Value - Math.Truncate(latitud.Value) / 1) * 60); double latSecPart = ((latMinPart - Math.Truncate(latMinPart) / 1) * 60); string lonDir = (longitud.Value >= 0 ? "E" : "W"); longitud = Math.Abs(longitud.Value); double lonMinPart = ((longitud.Value - Math.Truncate(longitud.Value) / 1) * 60); double lonSecPart = ((lonMinPart - Math.Truncate(lonMinPart) / 1) * 60); var latitudDeg = (int)Math.Truncate(latitud.Value); var latitudMin = (int)Math.Truncate(latMinPart); var latitudSec = Math.Round(latSecPart, 4); var longitudDeg = (int)Math.Truncate(longitud.Value); var longitudMin = (int)Math.Truncate(lonMinPart); var longitudSec = Math.Round(lonSecPart, 3); var coordinates = new CoordinatesModel() { LatitudDirection = latitudDir, LatitudDegrees = latitudDeg, LatitudMinutes = latitudMin, LatitudSeconds = latitudSec, LongitudDirection = lonDir, LongitudDegrees = longitudDeg, LongitudMinutes = longitudMin, LongitudSeconds = longitudSec, Altitud = altitud ?? 0 }; return(coordinates); } return(null); }
public static CoordinatesModel FindTotalCoordinates(ReceiptModel receipt) { CoordinatesModel coord = new CoordinatesModel(); foreach (var region in receipt.Regions) { var coordinates = region.Lines.SelectMany(l => l.Words) .Select(w => w) .Where(t => t.Text == "TOTAL") .Select(s => s.BoundingCoordinates) .FirstOrDefault(); if (coordinates != null) { coord = coordinates; } else { continue; } } return(coord); }
public static void QueryPulse(CoordinatesModel coordinates, HttpSessionStateBase sessionBase, LockingSingleton locker) { Debug.WriteLine("QueryPulse(): START"); HttpClient httpClient = HttpHelper.GetClient(); HttpSessionStateBase session = sessionBase; if (httpClient == null) { locker.isLocked = false; return; } httpClient.SendAsync(HttpHelper.GetHttpRequestMessage(coordinates)).ContinueWith((task) => { var response = task.Result; if (response.StatusCode == HttpStatusCode.OK) { Debug.WriteLine("QueryPulse(): Status: " + response.StatusCode); var jsonTask = response.Content.ReadAsStringAsync(); jsonTask.Wait(); PulseSegmentListModel ps = JsonConvert.DeserializeObject <PulseSegmentListModel>(jsonTask.Result); session["pulse_segments"] = ps.data; Debug.WriteLine("QueryPulse(): Data: " + string.Join(", ", ps.data)); } else { Debug.WriteLine("QueryPulse(): Error: {0}", response); } locker.isLocked = false; }); Debug.WriteLine("QueryPulse(): END"); return; }
public void FindTotalSum() { var allLines = ExtractAllLines(); CoordinatesModel totalCoord = Helpers.Helpers.FindTotalCoordinates(Receipt); int avgLineHeight = (int)Helpers.Helpers.DisplayAvgLineHeight(Receipt).Average(); var res = allLines.Select(l => l) .Where(line => (line.BoundingCoordinates.Y < totalCoord.Y + avgLineHeight) && (line.BoundingCoordinates.Y >= totalCoord.Y - avgLineHeight)); foreach (var line in res) { var txt = line.Words.SelectMany(w => w.Text) .Select(t => t); foreach (var item in txt) { Console.Write(item + " "); } Console.WriteLine(); } }
private void ChatMessageControl_Loaded(object sender, RoutedEventArgs e) { this.MessageWrapPanel.Children.Clear(); this.MessageWrapPanel.Children.Add(this.messageHeader); foreach (ChatMessageDataModel messageData in this.Message.MessageComponents) { if (messageData.type.Equals("emoticon") && ChatMessageViewModel.EmoticonImages.ContainsKey(messageData.text)) { if (!ChatMessageControl.emoticonBitmapImages.ContainsKey(messageData.text)) { ChatMessageControl.emoticonBitmapImages[messageData.text] = new BitmapImage(new Uri(ChatMessageViewModel.EmoticonImages[messageData.text].FilePath)); } CoordinatesModel coords = ChatMessageViewModel.EmoticonImages[messageData.text].Coordinates; CroppedBitmap bitmap = new CroppedBitmap(ChatMessageControl.emoticonBitmapImages[messageData.text], new Int32Rect((int)coords.x, (int)coords.y, (int)coords.width, (int)coords.height)); Image image = new Image(); image.Source = bitmap; image.Height = image.Width = 15; image.VerticalAlignment = VerticalAlignment.Center; this.MessageWrapPanel.Children.Add(image); } else { foreach (string word in messageData.text.Split(new string[] { " " }, StringSplitOptions.None)) { TextBlock textBlock = new TextBlock(); textBlock.Text = word + " "; textBlock.VerticalAlignment = VerticalAlignment.Center; this.textBlocks.Add(textBlock); this.MessageWrapPanel.Children.Add(textBlock); } } } }
public async Task <double> GetMinEnergyAsync(CoordinatesModel coordinate) => await Task.Run(() => _analizer.GetMinEnergy(_mapper.Map <Coordinates>(coordinate)));
public Task <CoordinatesModel> ApproximatePointAsync([FromBody] CoordinatesModel coordsRcvd) { return(this.mapService.ApproximatePointAsync(coordsRcvd)); }
public Robot(PositionModel position, CoordinatesModel upperRight) { _position = position; _upperRight = upperRight; }
public async Task <IActionResult> GetMaxEnergy([FromBody] CoordinatesModel coordinate) { return(Ok(await _researcherService.GetMaxEnergyAsync(coordinate))); }
internal static Coordinates ToCoordinates(this CoordinatesModel coordinatesDto) { return(new Coordinates(coordinatesDto.X, coordinatesDto.Y)); }
/// <summary> /// This Method is used to calculate distance between two points at the surface of a ellipsoide earth /// </summary> /// <param name="coordinates1"></param> /// <param name="coordinates2"></param> /// <returns>decimal</returns> public double CalculateDistanceWithVicentyFormulae(CoordinatesModel coordinates1, CoordinatesModel coordinates2) { var distance = VicentyFormulae(coordinates1, coordinates2); return(distance); }
/// <summary> /// This Method is used to calculate distance between two points at the surface of a sperical earth /// </summary> /// <param name="coordinates1"></param> /// <param name="coordinates2"></param> /// <returns>decimal</returns> public double CalculateDistanceWithHaversineFormulae(CoordinatesModel coordinates1, CoordinatesModel coordinates2) { var distance = HaversineFormulae(coordinates1, coordinates2); return(distance); }