/// <summary> /// Get filters for Product_Groupa, OS_Type and Station_Type /// </summary> /// <param name="data"></param> /// <param name="i"></param> /// <param name="j"></param> /// <returns></returns> public override StationData eachStation(StationData data, int i, int j) { filterData.Products.Add(data.Product_Group); filterData.OS.Add(data.OS_Type); filterData.Types.Add(data.Station_Type); return data; }
/// <summary> /// Add the ping to the rig /// </summary> /// <param name="thisStation">The rig being updated</param> /// <param name="newStamp">The new ping stamp</param> /// <returns>The combined rig and ping stamp</returns> public static StationData appendPing(StationData thisStation, PingStamp newStamp) { //This creates a new day representation, which pings can be added to PingDay newDay = new PingDay(); //This adds the first stamp to the new day newDay.todayPings.Add(newStamp); //this adds the day to the station's ping list thisStation.thePings.Add(newDay); return thisStation; }
private bool _IsStationVisible(StationData station) { if (string.IsNullOrWhiteSpace(StationsFilterTextControl.Text)) { return true; } var _stationText = station.StationDisplayName.ToLowerInvariant(); var _filterText = StationsFilterTextControl.Text.Trim().ToLowerInvariant(); return _stationText.Contains(_filterText); }
public IHttpActionResult PostStationData(StationDataCollector stationDataCollector) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } int apiKeyId = db.ApiKey.Where(a => a.apiKeyValue == stationDataCollector.apiKey).First().apiKeyID; StationData stationData = stationDataCollector.ConvertToDb(apiKeyId); db.StationData.Add(stationData); db.SaveChanges(); return(CreatedAtRoute("DefaultApi", new { id = stationData.stationDataID }, stationDataCollector)); }
void InstantiateStation(StationData station) { GameObject stationGO = GameObject.CreatePrimitive(PrimitiveType.Sphere); stationGO.transform.SetParent(Map.transform); stationGO.name = station.name; stationGO.transform.localScale = Vector3.one * 5.0f; stationGO.transform.position = new Vector3(station.Position.x, station.Position.y); var stationToAdd = stationGO.AddComponent <Station>(); stationToAdd.StationData = station; _stations.Add(station.id, stationToAdd); ResizeStation(stationToAdd); }
public async Task <IActionResult> GetStationData(int id) { try { E_Station station = (E_Station)id; GetStationsInforResponse stationInfo = await _rail.GetStationsInfor(station); StationData stationData = new StationData(stationInfo.Data.FirstOrDefault(x => x.StationCode == id.ToString()), E_Language.Hebrew); return(Ok(stationData)); } catch (Exception ex) { _logger.LogCritical(ex, $"Failed GetStationData({id})"); return(StatusCode(500, ex)); } }
private StationData GetStationModel(Location location, StationData stationData) { return(new StationData { DayOfTheWeek = stationData.DayOfTheWeek, Date = stationData.Date, TrainOperator = stationData.TrainOperator, TrainOriginLocation = stationData.TrainOriginLocation, TrainDestinationLocation = stationData.TrainDestinationLocation, Station = location.Name, TimeTableDepartureTimeMins = location.TimetableDeparture, ActualDepartureTimeMins = location.ActualDeparture, TimeTableArrivalTime = location.TimetableArrival, ActualArrivalTime = location.ActualArrival }); }
public override StationData eachStation(StationData data, int i, int j) { ErrorPost thisPost = new ErrorPost(); String errorMessage = ""; bool firstPingError = true; foreach (PingDay thisDay in data.thePings) { if (thisDay.todayPings.Count > 10) { if (firstPingError) { errorMessage += "PING ERROR: "; firstPingError = false; } for(int a = 0;a< thisDay.todayPings.Count-1; a++) { if (thisDay.todayPings[a].result.Equals("Error")) { if (thisDay.todayPings[a].stackTrace.Equals("No such host is known")) { errorMessage += "\n The host is unknown"; } else { errorMessage += "unkown error: " + thisDay.todayPings[j].stackTrace; } } } } } for (int k = 0; k < data.andonData.Count - 1; k++) { String andonData = "ID : " + data.andonData[k].ID + ", Countermeasure : " + data.andonData[k].Countermeasure + ", DTID : " + data.andonData[k].DTID + ", Loadtime : " + data.andonData[k].LoadTime + ", DowntimeType : " + data.andonData[k].DowntimeType + ", Operator : " + data.andonData[k].Operator + "Concern Type : " + data.andonData[k].ConcernType + "\n"; } return data; }
/// <summary> /// This method clarifies if we need to add the new ping status to the given StationData object. /// </summary> /// <param name="thisStation">The current station</param> /// <param name="newStamp">The new ping</param> /// <returns>The updated station</returns> public static StationData processPings(StationData thisStation, PingStamp newStamp) { Boolean newDate = true; //Check if there are no pings already try{ if (thisStation.thePings.Count == 0) { thisStation = appendPing(thisStation, newStamp); //this is not a new value newDate = false; } else for (int k = 0; k < thisStation.thePings.Count; k++) { if (thisStation.thePings[k].compareDates(newStamp.theDateTime.Date)) { thisStation.thePings[k].todayPings.Add(newStamp); newDate = false; k = thisStation.thePings.Count; } } } catch(Exception) { thisStation = appendPing(thisStation, newStamp); } //ekse compare the ping dates, add the ping to the particular date if (newDate) { thisStation = appendPing(thisStation, newStamp); } for (int i = 0; i <= thisStation.thePings.Count - 1; i++) { //Iterate through ping entries to find any that are older than 30 days, and then delete them if ((thisStation.thePings[i].todayPings[0].theDateTime < DateTime.Now.AddDays(-30)) && thisStation.thePings.Count > 1) { thisStation.thePings.RemoveAt(i); i--; } } return thisStation; }
public string GetGoogleMapsUrl(StationData stationData) { StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/staticmap?"); sb.Append("size=540x320"); sb.AppendFormat("&markers=color:red%7Clabel:R%7C{0},{1}", stationData.Latitude, stationData.Longitude); if (stationData.Parking != null && stationData.Parking.Any()) { sb.Append("&markers=color:blue%7Clabel:P"); foreach (StationParking sp in stationData.Parking) { sb.AppendFormat("%7C{0},{1}", sp.Longitude, sp.Latitude); } } sb.AppendFormat("&key={0}", _config.GetValue <string>("AppSettings:GoogleApiKey")); return(sb.ToString()); }
public int Run(string stationName, DateTime startDate, DateTime endDate) { StationData station = GetStationData(stationName); IEnumerable <int> detectors = GetDetectors(station.Id); List <int> speeds = new List <int>(); foreach (int detector in detectors) { speeds.AddRange(GetSpeedsForDetector(detector, startDate, endDate)); } var averageSeconds = speeds.Where(s => s > 0).Select(speed => (station.Lenght / speed) * 3600).Average(); return((int)Math.Round(averageSeconds)); }
public IHttpActionResult Post(StationData obj) { var data = repo.GetAll(); if (data.Any(x => x.StationCode == obj.StationCode && x.Date.ToShortDateString() == obj.Date.ToShortDateString())) { var old = data.Where(x => x.StationCode == obj.StationCode && x.Date.ToShortDateString() == obj.Date.ToShortDateString()).FirstOrDefault(); obj.Id = old.Id; repo.Edit(obj); } else { repo.Create(obj); } return(Ok()); }
public void DisplayRandomStation() { if (m_stations == null) { Debug.Log("Data has not been fetched! Nothing to see here..."); return; } if (m_textUI != null) { NOAA_latest_observations m_stationData = m_stations[UnityEngine.Random.Range(0, m_stations.Count)]; DateTime m_date = DateTime.Parse(m_stationData.year + "-" + m_stationData.month + "-" + m_stationData.day + " " + m_stationData.hh + ":" + m_stationData.mm); m_textUI.text = StationData.Statistics(m_stationData, m_date); } }
/// <summary> /// 读取每日预报信息 /// </summary> /// <returns></returns> public static List <StationData> DailyFileRead(MissionInfo missionInfo) { string stateStr = ""; try { List <StationData> stationList = new List <StationData>(); string fileName = missionInfo.forecastFilesHead + DateTime.Today.ToString("yyyyMMdd") + ".txt"; string baseDirectory = AppDomain.CurrentDomain.BaseDirectory + "\\DailyData\\Meteorological\\ForecastFiles\\" + DateTime.Today.ToString("yyyyMMdd") + "\\"; stateStr = baseDirectory + fileName; StreamReader sr = new StreamReader(Path.Combine(baseDirectory, fileName)); StringBuilder sb = new StringBuilder(); while (sr.EndOfStream == false) { sb.AppendLine(sr.ReadLine()); } sr.Close(); string jsonText = sb.ToString(); JsonSerializerSettings jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DateFormatString = "yyy-MM-dd HH:mm:ss" }; var jsonObject = JsonConvert.DeserializeObject <dynamic>(jsonText, jSetting); //var jsonObject = JsonConvert.DeserializeObject<dynamic>(jsonText); for (int i = 0; i < jsonObject.Count; i++) { StationData stationData = new StationData(missionInfo); //获取父对象的栏位 stationData.stationID = int.Parse(jsonObject[i]["stationID"].Value.ToString()); stationData.stationName = jsonObject[i]["stationName"].Value; stationData.visibility = float.Parse(jsonObject[i]["visibility"].Value.ToString()); stationData.visibilityPrescription = int.Parse(jsonObject[i]["visibilityPrescription"].Value.ToString()); stationData.coordinateX = double.Parse(jsonObject[i]["coordinateX"].Value.ToString()); stationData.coordinateY = double.Parse(jsonObject[i]["coordinateY"].Value.ToString()); stationData.photoHead = jsonObject[i]["photoHead"].Value; stationList.Add(stationData); } return(stationList); } catch (Exception e) { CommonTools.WriteLog("读取气象每日预报出错:" + stateStr + "\r\n" + e.Message); return(null); } }
/// <summary> /// 任务下拉框进行选择时的操作 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { selectedID = comboBox1.SelectedIndex; NowMission = missionList[selectedID]; //加载相应stationlist stationList = FunClass.GetStationData(IP + UrlOfChartRead, NowMission); if (stationList == null) { MessageBox.Show("网络异常or站点列表数据异常or站点为空"); ReloadData(); return; } //赋予当前站点 NowStation = stationList[0]; RefreshDataGridView(); pictureForm.ChangePicture(FunClass.GetPicture(IP + UrlOfMeteoPicture, NowStation.photoHead, 1, NowMission.forecastFilesHead), NowStation); }
public void GetClosestStation() { var minDistance = Mathf.Infinity; StationData result = null; if (_stations == null) { _stations = new Dictionary <int, Station> (); } if (_stations.Count == 0) { var eligeable = Mapper.Stations.Select(i => i.Value) .Where(d => d.load < 100000000); if (eligeable.Count() < 1) { Debug.Log("do increase load acceptance for starting station"); return; } // var additionalStations = new List<StationData> (); // what was the idea here?! int rand = UnityEngine.Random.Range(0, eligeable.Count() - 1); InstantiateStation(eligeable.ElementAt(rand)); return; } foreach (var additionalStation in Mapper.Stations) { if (!_stations.ContainsKey(additionalStation.Value.id)) { foreach (var existingStation in _stations) { // ignore the input station itself var sqrDist = (additionalStation.Value.Position - existingStation.Value.StationData.Position).sqrMagnitude; if (sqrDist < minDistance) { minDistance = sqrDist; result = additionalStation.Value; } } } } InstantiateStation(result); }
public void SellItem(int itemIndex, GameObject item, StationData stationData, float favMulti, float hatedMulti) { bool soldSomething = false; // No one buys fuel if (item.name == "Fuel") { Debug.Log("Cats will not buy fuel"); } else if (stationData.isTom) { // Tom doesn't buy things } else { // Calculate the item's value float valueOfItem = item.GetComponent <ShopItemUIHandler>().shopItem.itemValue; if (item == stationData.favItem) { valueOfItem = valueOfItem * favMulti; } if (item == stationData.hatedItem) { valueOfItem = valueOfItem * hatedMulti; } // If we have the item in stock and the station can afford it then update our cargo/the station's cargo and our wallet/the station's wallet if (stock[itemIndex] > 0 && stationData.wallet > valueOfItem) { wallet += (int)valueOfItem; stationData.wallet -= (int)valueOfItem; stationData.stock[itemIndex]++; stock[itemIndex]--; soundEffects.Negative(); soldSomething = true; } } if (soldSomething) { questSystem.BuySellQuestDone(); } }
} // end of LoadSysInit() private void LoadStationTable(string _Filepath) { Debug.Log("LoadStationTable() start. _Filepath=" + _Filepath); DestroyStationsData(); TextAsset ta = (TextAsset)Resources.Load(_Filepath, typeof(TextAsset)); if (null == ta) { Debug.LogError("LoadStationTable() _Filepath load failed=" + _Filepath); return; } // m_Stations string content = ta.text; // Debug.Log( "content=" + content ) ; string[] splitor1 = { "\r\n", "\n", "\r" }; // Debug.Log( "splitor1=" + splitor1[0] ) ; StationData stationData = null; string [] lineVec = content.Split(splitor1, System.StringSplitOptions.None); // Debug.Log( "lineVec.Length=" + lineVec.Length ) ; for (int i = 0; i < lineVec.Length; ++i) { if (0 < lineVec[i].Length) { // Debug.Log( lineVec[ i ] ) ; stationData = new StationData(); stationData.ParseFromString(lineVec[i]); if (false == m_Stations.ContainsKey(stationData.ID)) { m_Stations.Add(stationData.ID, stationData); Debug.Log("m_Stations.Add=" + stationData.DisplayName); } } } Debug.Log("LoadStationTable() end."); } // end of LoadStationTable()
public IStationData LoadStationData(string stationId) { Console.Out.WriteLine($"Loading {stationId}"); var station = new StationData(stationId); var path = $"{this._configuration.FileSystemReader_BaseDirectory}/{this._configuration.FileSystemReader_DataDirectory}/{stationId}{FILE_EXTENSIONS}"; using (var fileStream = new StreamReader(path)) { string line; while ((line = fileStream.ReadLine()) != null) { this._stationParser.ParseStationLine(line, station); } fileStream.Close(); } return(station); }
public async Task <ActionResult <StationData> > PostStationData(string tableName, double[][] data) { foreach (var item in data) { try { var newData = new StationData() { WEEK = (int)item[0], T = item[1], AX = item[2], AY = item[3], AZ = item[4], Temp = item[5] }; datas.InsertAsync(tableName, newData); } catch (DuplicateException) { continue; } catch (NotFoundException) { return(NotFound()); } catch (Exception) { return(StatusCode(501)); } } try { await datas.saveAsync(); } catch (DbUpdateConcurrencyException) { return(BadRequest()); } return(NoContent()); }
public async Task<StationData> GetStationDataAsync(string uri) { StationData stationData = null; try { HttpResponseMessage response = await _client.GetAsync(uri); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); stationData = JsonConvert.DeserializeObject<StationData>(content); } } catch (Exception ex) { Debug.WriteLine("\tERROR {0}", ex.Message); } return stationData; }
void setInfoText(StationData st) { //StationData data = info_window.GetComponentInChildren<Station> ().sd; string infoText = "<b>estaçao</b>: <color=#7A7A7A>" + st.name + "</color>"; infoText += "\n<b>perfil</b>: <color=#7A7A7A>"; string perfis = ""; for (int i = 0; i < st.perfis.Count; i++) { perfis += st.perfis[i]; if (i < st.perfis.Count - 1) { perfis += ", "; } } infoText += perfis.ToLower(); infoText += "</color>"; info_window.GetComponentInChildren <TextMeshProUGUI> ().text = infoText; }
/** * Method extracting popularity for cities. * Returns a Dictionary of <didok85, StationData> entries. */ Dictionary <int, StationData> getCitiesNamesAndPopularity(Dictionary <string, Dictionary <string, string> > records) { var theDict = new Dictionary <int, StationData>(); foreach (KeyValuePair <string, Dictionary <string, string> > dict in records) { var record = dict.Value; var station = new StationData(); var lod_field = record ["lod"].Split(new char[] { '/' }); var id = int.Parse(lod_field [lod_field.Length - 1]); station.id = id; station.load = int.Parse(record ["dtv"]); station.name = record ["name"]; theDict [station.id] = station; } return(theDict); }
public async Task <IActionResult> Station(int id) { try { E_Station station = (E_Station)id; GetStationsInforResponse stationInfo = await _rail.GetStationsInfor(station); StationData stationData = new StationData(stationInfo.Data.FirstOrDefault(x => x.StationCode == id.ToString()), E_Language.Hebrew); ViewBag.GoogleMapsUrl = _google.GetGoogleMapsUrl(stationData); return(PartialView("_Station", stationData)); } catch (Exception ex) { _logger.LogCritical(ex, $"Failed Station({id})"); return(PartialView("Error", new ErrorViewModel() { Exception = ex })); } }
private StationData ToStation(Station station, List <Stop> stops) { var parentStop = stops.Where(stop => stop.LocationType == LocationType.Station).Single(); var stationData = new StationData() { Station = station, Id = parentStop.Id, Name = parentStop.Name, Coordinates = new LatLng() { Latitude = parentStop.Latitude, Longitude = parentStop.Longitude }, Timezone = parentStop.Timezone, }; stationData.Platforms.Add(stops.Where(stop => stop.LocationType == LocationType.Platform) .Select(platform => new StationData.Types.Area() { Id = platform.Id, Name = platform.Name, Coordinates = new LatLng() { Latitude = platform.Latitude, Longitude = platform.Longitude } })); stationData.Entrances.Add(stops.Where(stop => stop.LocationType == LocationType.Entrance) .Select(platform => new StationData.Types.Area() { Id = platform.Id, Name = platform.Name, Coordinates = new LatLng() { Latitude = platform.Latitude, Longitude = platform.Longitude } })); return(stationData); }
/// <summary> /// 将字符串转换成StationData格式 /// </summary> /// <param name="str"></param> /// <returns></returns> private static List <StationData> Str2StationData(string str, MissionInfo missionInfo) { List <StationData> stationList = new List <StationData>(); try { StringBuilder sb = new StringBuilder(); sb.AppendLine(str); string jsonText = sb.ToString(); JsonSerializerSettings jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DateFormatString = "yyy-MM-dd HH:mm:ss" }; var jsonObject = JsonConvert.DeserializeObject <dynamic>(jsonText, jSetting); //var jsonObject = JsonConvert.DeserializeObject<dynamic>(jsonText); for (int i = 0; i < jsonObject.Count; i++) { StationData stationData = new StationData(missionInfo); //获取父对象的栏位 stationData.stationID = int.Parse(jsonObject[i]["stationID"].Value.ToString()); stationData.stationName = jsonObject[i]["stationName"].Value; stationData.forecastValue1 = float.Parse(jsonObject[i]["forecastValue1"].Value.ToString()); stationData.forecastValue2 = float.Parse(jsonObject[i]["forecastValue2"].Value.ToString()); stationData.forecastValue3 = float.Parse(jsonObject[i]["forecastValue3"].Value.ToString()); stationData.forecastValue4 = float.Parse(jsonObject[i]["forecastValue4"].Value.ToString()); stationData.forecastValue5 = float.Parse(jsonObject[i]["forecastValue5"].Value.ToString()); stationData.coordinateX = double.Parse(jsonObject[i]["coordinateX"].Value.ToString()); stationData.coordinateY = double.Parse(jsonObject[i]["coordinateY"].Value.ToString()); stationData.forecastPrescription = int.Parse(jsonObject[i]["forecastPrescription"].Value.ToString()); stationData.photoHead = jsonObject[i]["photoHead"].Value; stationList.Add(stationData); } return(stationList); } catch (Exception e) { WriteLog(DateTime.Now.ToString() + " 将字符串转换成StationData格式异常 " + e.Message); return(null); } }
private IEnumerator RetrieveBinaryImage(StationData theStation, Action <Texture2D> callback) { if (theStation.imageUrl != "" && theStation.imageUrl != null) { var endpoint = theStation.imageUrl; UnityWebRequest www = UnityWebRequestTexture.GetTexture(endpoint); yield return(www.Send()); if (www.isNetworkError) { Debug.Log("logging error"); Debug.Log(www.error); } else { // Show results as text var downloadedBinary = ((DownloadHandlerTexture)www.downloadHandler).texture; callback(downloadedBinary); } } }
public async Task <ActionResult <StationData> > Post([FromBody] StationData data) { //verify stationId if (data.StationId <= 0) { return(BadRequest("Invalid StationID")); } //verify seqid if (data.SeqId <= 0) { return(BadRequest("Invalid SeqID")); } if (data.ReceivedAt == null) { data.ReceivedAt = DateTime.Now; } _context.StationDatas.Add(data); await _context.SaveChangesAsync(); return(data); }
/// <summary> /// 向服务器推送保存信息 /// </summary> /// <param name="url"></param> /// <param name="sd"></param> /// <returns></returns> public static string PostWaveData(string url, StationData sd, MissionInfo mi) { try { WaveDataInputModel waveData = new WaveDataInputModel(); waveData.stationID = sd.stationID; waveData.forecastValue1 = sd.forecastValue1; waveData.forecastValue2 = sd.forecastValue2; waveData.forecastValue3 = sd.forecastValue3; waveData.forecastValue4 = sd.forecastValue4; waveData.forecastValue5 = sd.forecastValue5; waveData.missionInfo = mi; string jsonStr = JsonConvert.SerializeObject(waveData); HttpWebRequest req = WebRequest.CreateHttp(url); req.Method = "POST"; req.ContentType = "application/json;charset=UTF-8"; byte[] payload = Encoding.UTF8.GetBytes(jsonStr); req.ContentLength = payload.Length; Stream writer = req.GetRequestStream(); writer.Write(payload, 0, payload.Length); writer.Close(); var response = req.GetResponse() as HttpWebResponse; Stream stm = response.GetResponseStream(); StreamReader reader = new StreamReader(stm, Encoding.UTF8); string strDate = ""; string strValue = ""; while ((strDate = reader.ReadLine()) != null) { strValue += strDate + "\r\n"; } reader.Close(); stm.Close(); return(strValue); } catch (Exception e) { WriteLog(DateTime.Now.ToString() + " 向服务器推送保存信息异常 " + e.Message); return(null); } }
/** * Extracts the urls and returns dict of the form <id, url> */ private Dictionary <int, StationData> extractCitiesImageUrls(string jsonString) { var parsed = JSON.Parse(jsonString); var theDict = new Dictionary <int, StationData>(); foreach (JSONObject record in parsed["records"].AsArray) { var station = new StationData(); var id = int.Parse(record["fields"]["nummer"]); var datasetid = record ["datasetid"]; var datasetid1 = datasetid.Value.TrimStart().TrimEnd(); var imageid = record ["fields"] ["file"] ["id"]; var imageid1 = imageid.Value.TrimStart().TrimEnd(); var url = string.Format("https://data.sbb.ch/explore/dataset/{0}/files/{1}/download", datasetid1, imageid1); station.id = id; station.imageUrl = url; station.imageWidth = record["fields"]["file"]["width"]; station.imageHeight = record["fields"]["file"]["heigth"]; theDict[id] = station; } return(theDict); }
public void ChangePicture(Image image, StationData sd) { stationData = sd; pictureBox1.Image = image; if (stationData == null) { return; } //float a = 10.20434f; //float b = -1067.09f; //float c = -10.8956f; //float d = 487.56f; //int pX = Convert.ToInt32(stationData.coordinateX * a + b) * pictureBox1.Width / 1600; ////int pX = Convert.ToInt32(stationData.coordinateX * 10 - 1100);//int.Parse((stationData.coordinateX * 10 - 1100).ToString()); //int pY = Convert.ToInt32(stationData.coordinateY * c + d) * pictureBox1.Height / 900; ////int pY = Convert.ToInt32(430 - stationData.coordinateY * 10);//int.Parse((stationData.coordinateY * 10 - 90).ToString()); //pnt1 = new Point(pX, pY); //pnt2 = new Point(pX + 320 * pictureBox1.Width / 1600, pY); //pnt3 = new Point(pX + 640 * pictureBox1.Width / 1600, pY); //pnt4 = new Point(pX + 960 * pictureBox1.Width / 1600, pY); //pnt5 = new Point(pX + 1280 * pictureBox1.Width / 1600, pY); }
// Update is called once per frame void Update() { //Updates layout if radius or number of stations is changed interval = 360 / numStations; if (interval != lastInterval || lastRadius != radius) { angle = 90; stations.Clear(); for (int i = 0; i < numStations; i++) { xPos = Mathf.Cos(Mathf.Deg2Rad * angle) * radius; yPos = Mathf.Sin(Mathf.Deg2Rad * angle) * radius; Vector2 position = new Vector2(xPos, yPos); Vector3 direction = (new Vector3(position.x, position.y, 0) - Vector3.zero).normalized; StationData s = new StationData(position, direction); stations.Add(s); angle -= interval; } } lastInterval = interval; lastRadius = radius; //Press Button to spawn missile from station 1 if (Input.GetKeyDown(KeyCode.Space)) { GameObject m = (GameObject)Instantiate(missile); m.GetComponent <TestMissile>().asteroid = this; m.transform.position = stations[0].Position; //Instantiate(missile, stations[0].Position, Quaternion.identity); } }
private void TSB_ToStation_Click(object sender, EventArgs e) { OpenFileDialog ofDlg = new OpenFileDialog(); ofDlg.Title = "Open Station Coordinate File"; if (ofDlg.ShowDialog() == DialogResult.OK) { string inFile = ofDlg.FileName; SaveFileDialog sfDlg = new SaveFileDialog(); sfDlg.Title = "Save Station Data File"; if (sfDlg.ShowDialog() == DialogResult.OK) { string outFile = sfDlg.FileName; if (ProjInfo.Transform.ProjectionName == ProjectionNames.Lon_Lat) { ((GridData)Data).ToStation(inFile, outFile); } else { if (MessageBox.Show("If project stations?", "Alarm", MessageBoxButtons.YesNo) == DialogResult.Yes) { LonLatStationDataInfo aDataInfo = new LonLatStationDataInfo(); aDataInfo.ReadDataInfo(inFile); StationData inStData = aDataInfo.GetNullStationData(); ProjectionInfo fromProj = KnownCoordinateSystems.Geographic.World.WGS1984; StationData midStData = inStData.Projection(fromProj, ProjInfo); StationData outStData = ((GridData)Data).ToStation(midStData); outStData.SaveAsCSVFile(outFile, "data"); } else { ((GridData)Data).ToStation(inFile, outFile); } } } } }
public List <StationData> FindStationData() { List <StationData> stations = new List <StationData>(); var xml = XElement.Load(@"d:\檔案\多媒體系統\OTH01728.xml"); var StationsData = xml.Descendants("Data").ToList(); StationsData .Where(x => !x.IsEmpty).ToList() .ForEach(stationData => { var Siteid = stationData.Element("Siteid").Value.Trim(); var Site = stationData.Element("Site").Value.Trim(); var Address = stationData.Element("Address").Value.Trim(); var Phonenumber = stationData.Element("Phonenumber").Value.Trim(); StationData Data = new StationData(); Data.Siteid = Siteid; Data.Site = Site; Data.Address = Address; Data.Phonenumber = Phonenumber; stations.Add(Data); }); return(stations); }
public static void createNewSave() { Debug.Log("Creating new save."); int stationCount = StationData.getStationCount(); playerData.nickname = "nick"; playerData.currentScene = "Intro_StationChoice"; //playerData.currentScene = "End"; playerData.currentQuestion = -1; //playerData.gameId = "ID"; playerData.points = new int[stationCount]; for (int i = 0; i < playerData.points.Length; i++) { playerData.points[i] = 0; } //Randomize stations playerData.stationOrder = new int[stationCount]; for (int i = 0; i < playerData.stationOrder.Length; i++) { playerData.stationOrder[i] = i; } Shuffle(playerData.stationOrder); playerData.stationStats = new StationStats[stationCount]; for (int i = 0; i < playerData.stationStats.Length; i++) { playerData.stationStats[i].active = true; playerData.stationStats[i].discovered = false; playerData.stationStats[i].opinion = Opinion.NONE; playerData.stationStats[i].points = 0; } saveToHardDrive(); }
/// <summary> /// For each station where it is enabled, send a ping. /// </summary> /// <param name="thisStation">The current rig</param> /// <param name="i">site index</param> /// <param name="j">rig index</param> /// <returns></returns> public override StationData eachStation(StationData thisStation, int i, int j) { Console.WriteLine(thisStation.Station_Name); if (!thisStation.OS_Type.Equals("DOS")) { Ping p1 = new Ping(); PingStamp newStamp = new PingStamp(); try { //Take a stamp of the time at which the ping is attempted newStamp.theDateTime = DateTime.Now; Console.WriteLine("Sending Ping"); //Send the ping PingReply PR = p1.Send(thisStation.Network_Name); //Deal with the response if ((PR.Status == IPStatus.Success)) { newStamp.result = "Online"; newStamp.roundtripTime = PR.RoundtripTime; newStamp.netStatus = PR.Status.ToString(); Console.WriteLine("Online"); } else { newStamp.result = "Offline"; newStamp.roundtripTime = PR.RoundtripTime; newStamp.netStatus = PR.Status.ToString(); Console.WriteLine("Offline"); } } catch (Exception e) { //if there was an error, log log the result Console.WriteLine("Ping Failed"); newStamp.result = "Error"; if (e.InnerException.Message.ToString().Equals("No such host is known")) { newStamp.stackTrace = "No such host is known"; } else { newStamp.stackTrace = e.ToString(); } } //If the ping data is different from the last one logged, add it to the list. try { if (!(thisStation.thePings[thisStation.thePings.Count - 1] .todayPings[thisStation.thePings[thisStation .thePings.Count - 1].todayPings.Count - 1].result == newStamp.result)) { thisStation = processPings(thisStation, newStamp); } } catch (Exception) { thisStation.thePings = new List<PingDay>(); //The exception is assumed to be a Null pointer, meaning that there is no date entered so the result to simply assign the ping. thisStation = processPings(thisStation, newStamp); } } return thisStation; }
/// <summary> /// This method is called on each station iteration /// </summary> /// <param name="data">All of the data for this station, including its site, intrastage, pings etc</param> /// <param name="i">The index of this site within the List</param> /// <param name="j">The index of this station within the site List</param> /// <returns></returns> public virtual StationData eachStation(StationData data, int i, int j) { return data; }
/// <summary> /// This method assignes the Andon data to the appropriate station. /// </summary> /// <param name="data">The data for the station being processed</param> /// <param name="i">The site index.</param> /// <param name="j">The station index</param> /// <returns>The original site data with any modifications. if you only want to read it, simply return the original</returns> public override StationData eachStation(StationData data, int i, int j) { //Clear the old list data.andonData = new List<AndonDump>(); //Find an entry which matches this station for (int k = 0; k < DumpData.Count; k++) if (data.Station_Name.Equals(DumpData[k].ID)) { data.addAndon(DumpData[k]); DumpData.RemoveAt(k); } return data; }
private void DrawDisplayEditor( int _ID ) { string [] stationDisplayModeString = { StationDisplayMode.AllStaion.ToString(), StationDisplayMode.BigStation.ToString(), StationDisplayMode.SmartDisplay.ToString(), } ; GUILayout.BeginHorizontal() ; m_StationDisplayMode = GUILayout.SelectionGrid( m_StationDisplayMode , stationDisplayModeString , stationDisplayModeString.Length ) ; pUpdateStaionPtr.m_StationDisplayMode = (StationDisplayMode) m_StationDisplayMode ; GUILayout.EndHorizontal() ; string [] selectionString = { DisplayEditorMode.NearStation.ToString(), DisplayEditorMode.SpecifiedTrain.ToString(), DisplayEditorMode.AllTrains.ToString(), DisplayEditorMode.NoTrain.ToString(), } ; string keyword = "" ; GUILayout.BeginHorizontal() ; m_SelectMode = GUILayout.SelectionGrid( m_SelectMode , selectionString , selectionString.Length ) ; GUILayout.EndHorizontal() ; GUILayout.BeginHorizontal() ; switch( (DisplayEditorMode) m_SelectMode ) { case DisplayEditorMode.NearStation : // specified station GUILayout.Label( "Station" ) ; if( 0 == m_SpecifiedStation.Length ) { StationData[] stationData = new StationData[ pLevelGeneratorPtr.m_Stations.Count ] ; pLevelGeneratorPtr.m_Stations.Values.CopyTo( stationData , 0 ) ; if( stationData.Length > 0 ) { m_SpecifiedStation = stationData[ 0 ].DisplayName; } } keyword = m_SpecifiedStation = GUILayout.TextField( m_SpecifiedStation ) ; break ; case DisplayEditorMode.SpecifiedTrain : if( 0 == m_SpecifiedTrain.Length ) { int[] trainKeys = new int[ pLevelGeneratorPtr.m_TrainData.Count ] ; pLevelGeneratorPtr.m_TrainData.Keys.CopyTo( trainKeys , 0 ) ; if( trainKeys.Length > 0 ) { m_SpecifiedTrain = trainKeys[ 0 ].ToString() ; } } GUILayout.Label( "Train" ) ; keyword = m_SpecifiedTrain = GUILayout.TextField( m_SpecifiedTrain ) ; break ; case DisplayEditorMode.AllTrains : GUILayout.Label( "Be careful!!!" ) ; break ; case DisplayEditorMode.NoTrain : GUILayout.Label( "No Train." ) ; break ; } GUILayout.EndHorizontal() ; // GUILayout.Label( "Description:" ) ; // m_StatusText = GUILayout.TextArea( m_StatusText ) ; string [] modeString = { UpdateTrainTimeMode.SystemTime.ToString(), UpdateTrainTimeMode.SpecifiedTime.ToString(), } ; int updateTrainTimeMode = (int) pUpdateTrainPtr.m_TimeMode ; GUILayout.BeginHorizontal() ; updateTrainTimeMode = GUILayout.SelectionGrid( updateTrainTimeMode , modeString , modeString.Length ) ; pUpdateTrainPtr.SetUpdateTrainTimeMode( (UpdateTrainTimeMode) updateTrainTimeMode ) ; GUILayout.EndHorizontal() ; GUILayout.BeginHorizontal() ; GUILayout.Label( modeString[ updateTrainTimeMode] ) ; GUILayout.Label( pUpdateTrainPtr.m_SpecifiedHour.ToString() + ":" + pUpdateTrainPtr.m_SpecifiedMinute.ToString() ) ; GUILayout.EndHorizontal() ; switch( pUpdateTrainPtr.m_TimeMode ) { case UpdateTrainTimeMode.SystemTime : break ; case UpdateTrainTimeMode.SpecifiedTime : int specifiedTimeValue = pUpdateTrainPtr.m_SpecifiedHour * 60 + pUpdateTrainPtr.m_SpecifiedMinute ; int maxTimeADay = 24 * 60 ; specifiedTimeValue = (int) GUILayout.HorizontalSlider( (float)specifiedTimeValue , (float)0 , (float)maxTimeADay ) ; pUpdateTrainPtr.SetSpecifiedTime( specifiedTimeValue ) ; break ; } GUILayout.BeginHorizontal() ; if( true == GUILayout.Button( "Close" ) ) { m_DisplayEditor = false ; } if( true == GUILayout.Button( "Apply" ) ) { // RecreatScene pLevelGeneratorPtr.ReCreateTrainDisplayByData( (DisplayEditorMode) m_SelectMode , keyword ) ; } GUILayout.EndHorizontal() ; GUI.DragWindow() ; }
private void InsertStationData(StationData sd) { using(var connect = new SQLiteConnection("Data Source=data/RadioStation.db")) { connect.Open(); using(SQLiteTransaction sqlt = connect.BeginTransaction()) { using(SQLiteCommand command = connect.CreateCommand()) { command.CommandText = "insert into Stations (callsign, name, address) values('" + Callsign.GetRemovedStroke(sd.Callsign) + "', '" + sd.Name + "', '" + sd.Address + "')"; command.ExecuteNonQuery(); } sqlt.Commit(); } connect.Close(); } }
private void DrawEditor_StationsData() { float tmpFloatX = 0 ; float tmpFloatY = 0 ; GUILayout.Label( "Insert" ) ; GUILayout.BeginHorizontal() ; DrawStationData( ref m_InputStationLabel , ref m_InputStationPosX , ref m_InputStationPosY ) ; if( true == GUILayout.Button( "Insert" ) && 0 != m_InputStationLabel.Length ) { StationData newSD = new StationData() ; newSD.ID = m_LevelGeneratorStaticPtr.GetANewStationID() ; newSD.DisplayName = m_InputStationLabel ; if( true == float.TryParse( m_InputStationPosX , out tmpFloatX ) && true == float.TryParse( m_InputStationPosY , out tmpFloatY ) ) { newSD.Position = new Vector3( tmpFloatX , tmpFloatY , m_LevelGeneratorStaticPtr.m_StationLayerZShift ) ; } Debug.Log( "newSD.ID" + newSD.ID ) ; m_LevelGeneratorStaticPtr.m_Stations.Add( newSD.ID , newSD ) ; m_LevelGeneratorStaticPtr.ReCreateStationDisplayByData() ; } GUILayout.EndHorizontal() ; GUILayout.BeginHorizontal() ; GUILayout.Label( "Station Table" ) ; GUILayout.Label( "Page Start Index:" + m_StationStartIndex ) ; if( true == GUILayout.Button( "Previous Page" ) ) { m_StationStartIndex -= m_StationNumInPage ; if( m_StationStartIndex < 0 ) m_StationStartIndex = 0 ; } if( true == GUILayout.Button( "Next Page" ) ) { m_StationStartIndex += m_StationNumInPage ; if( m_StationStartIndex >= m_LevelGeneratorStaticPtr.m_Stations.Count ) m_StationStartIndex -= m_StationNumInPage ; } GUILayout.EndHorizontal() ; int i = 0 ; foreach( StationData sd in m_LevelGeneratorStaticPtr.m_Stations.Values ) { if( i < m_StationStartIndex || i >= m_StationStartIndex + m_StationNumInPage ) { ++i ; continue ; } GUILayout.BeginHorizontal() ; string PreDisplayName = sd.DisplayName ; string PrePosX = string.Format( "{0:0.00}" , sd.Position.x ) ; string PrePosY = string.Format( "{0:0.00}" , sd.Position.y ) ; Vector3 tmpVec = Vector3.zero ; DrawStationData( ref PreDisplayName , ref PrePosX , ref PrePosY ) ; sd.DisplayName = PreDisplayName ; if( true == float.TryParse( PrePosX , out tmpFloatX ) && true == float.TryParse( PrePosY , out tmpFloatY ) ) { if( tmpFloatX >= 0 && tmpFloatX <= 1 && tmpFloatY >= 0 && tmpFloatY <= 1 ) { tmpVec.Set( tmpFloatX , tmpFloatY , m_LevelGeneratorStaticPtr.m_StationLayerZShift ) ; if( sd.Position != tmpVec ) { sd.Position = tmpVec ; // adjust station pos only m_LevelGeneratorStaticPtr.AdjustStationDisplayPos( sd.DisplayName , tmpVec ) ; } } } if( true == GUILayout.Button( "MoveUp" ) ) { SwapStationData( i , i-1 ) ; return ;// end this round } if( true == GUILayout.Button( "MoveDown" ) ) { SwapStationData( i , i+1 ) ; return ;// end this round } if( true == GUILayout.Button( "Remove" ) ) { m_LevelGeneratorStaticPtr.RemoveStation( sd.ID ) ; return ;// end this round } GUILayout.EndHorizontal() ; ++i ; } if( true == GUILayout.Button( "Recreate All visible stations." ) ) { m_LevelGeneratorStaticPtr.ReCreateStationDisplayByData() ; } // Save GUILayout.BeginHorizontal() ; GUILayout.Label( "Station Data Filepath" ) ; m_SaveStationDataFilepath = GUILayout.TextField( m_SaveStationDataFilepath ) ; if( true == GUILayout.Button( "Save Station Data" ) ) { m_LevelGeneratorStaticPtr.SaveStationTable() ; } GUILayout.EndHorizontal() ; }
/// <summary> /// Add each station to our sites in the plain xml list, taking away all of the ping, intrastage, andon etc data /// </summary> /// <param name="data"></param> /// <param name="i"></param> /// <param name="j"></param> /// <returns></returns> public override StationData eachStation(StationData data, int i, int j) { nullTabs[i].stations.Add(data.nullifyData()); return data; }
private void LoadStationTable( string _Filepath ) { DebugLog( "LoadStationTable() start." ) ; DestroyStationsData() ; TextAsset ta = (TextAsset) Resources.Load( _Filepath , typeof(TextAsset) ) ; if( null == ta ) { Debug.LogError( "LoadStationTable() m_StationTableFilepath load failed=" + _Filepath ) ; return ; } // m_Stations string content = ta.text ; DebugLog( "content=" + content ) ; string[] splitor1 = { "\r\n" , "\n" , "\r" } ; // Debug.Log( "splitor1=" + splitor1[0] ) ; StationData stationData = null ; string []lineVec = content.Split( splitor1 , System.StringSplitOptions.None ) ; DebugLog( "lineVec.Length=" + lineVec.Length ) ; for( int i = 0 ; i < lineVec.Length ; ++i ) { if( 0 < lineVec[ i ].Length ) { #if DEBUG Debug.Log( lineVec[ i ] ) ; #endif stationData = new StationData() ; stationData.ParseFromString( lineVec[ i ] ) ; if( false == m_Stations.ContainsKey( stationData.ID ) ) { m_Stations.Add( stationData.ID , stationData ) ; DebugLog( "m_Stations.Add=" + stationData.DisplayName ) ; } } } DebugLog( "LoadStationTable() end." ) ; }
private StationData GetTableData() { StationData sd = new StationData(); System.Net.WebClient wc = new System.Net.WebClient(); string source = wc.DownloadString("http://www.tele.soumu.go.jp/musen/SearchServlet?SC=1&pageID=3&SelectID=1&CONFIRM=0&SelectOW=01&IT=&HC=&HV=&FF=&TF=&HZ=3&NA=&MA=" + callsign + "&DFY=&DFM=&DFD=&DTY=&DTM=&DTD=&SK=2&DC=100&as_fid=2I6vX7ugLE0ekrPjPfMD#result"); HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(source); var head = doc.DocumentNode.SelectNodes(@"//div[@id=""temp1""]/table[@class=""borderstyle""]"); if(head.Count == 2) return null; var m = Regex.Matches(head[2].InnerText, @"([ \n\t]*([\S ]*))"); var l = Regex.Matches(head[2].InnerHtml, @"<a\s+[^>]*href\s*=\s*(?:(?<quot>[""'])(?<url>.*?)\k<quot>|" + @"(?<url>[^\s>]+))[^>]*>(?<text>.*?)</a>"); //04-07, 08-0b, last2 space int nameint = 4; string nm = ""; string url = ""; sd.Address = ""; while(nameint < m.Count) { if(Regex.IsMatch(m[nameint].Groups[2].Value, @"[\S ]*(" + callsign + @")")) { nm = m[nameint].Groups[2].Value; url = l[3 + nameint / 4].Value; sd.Address += m[nameint + 1].Groups[2].Value + ", "; } nameint += 4; } if(nm == "") return null; var mt = Regex.Matches(nm, @"(.*)(" + callsign + @")"); var ml = Regex.Match(url, @"<a\s+[^>]*href\s*=\s*(?:(?<quot>[""'])(?<url>.*?)\k<quot>|" + @"(?<url>[^\s>]+))[^>]*>(?<text>.*?)</a>"); sd.Url = ml.Groups["url"].Value; sd.Url = "http://www.tele.soumu.go.jp/musen/" + sd.Url.Substring(2); sd.Callsign = callsign; sd.Name = mt[0].Groups[1].Value; return sd; }
public void CopyFrom( StationData _Src ) { Setup( this.ID , _Src.DisplayName , _Src.Position ) ; }
/// <summary> /// Call an intrastage query for each station where Intrastage is enabled. /// </summary> /// <param name="thisCell"></param> /// <param name="i"></param> /// <param name="j"></param> /// <returns></returns> public override StationData eachStation(StationData thisCell, int i, int j) { //Check if intrastage is enabled (bool) if (thisCell.Intrastage) { List<String> newData = new List<String>(); //Perform the multiple queries myConnection = new SqlConnection("Data Source=BHX4SQ01;Initial Catalog=IS_Main;User ID=is_viewer;Password=is!viewer"); //Try to open the connection, otherwise log the error. try { myConnection.Open(); } catch (Exception e) { ConsolePost newPost = new ConsolePost(); newPost.type = 4; newPost.issue = "Could not connect to Intrastage"; newPost.trace = e.ToString(); Program.updates.Add(newPost); } //try to read the data and parse it appropriately. try { SqlDataReader myReader = null; String thisQuery = queryPartOne + thisCell.Station_Name + queryPartTwo; SqlCommand myCommand = new SqlCommand(thisQuery, myConnection); myReader = myCommand.ExecuteReader(); while (myReader.Read()) { Object[] thisData = new Object[myReader.FieldCount]; myReader.GetValues(thisData); switch (thisData[1].ToString()) { case "Passed": thisData[1] = "#AAD178"; break; case "Error": thisData[1] = "#F7BE64"; break; case "Aborted": thisData[1] = "#6AD2EB"; break; case "Terminated": thisData[1] = "#6AD2EB"; break; case "Failed": thisData[1] = "#EF8A80"; break; default: thisData[1] = "#808080"; break; } newData = thisData.OfType<String>().ToList(); } myReader.Close(); myConnection.Close(); } catch (Exception e) { ConsolePost newPost = new ConsolePost(); newPost.type = 4; newPost.issue = "Could not read data"; newPost.trace = e.ToString(); Program.updates.Add(newPost); } thisCell.cellData = newData; } return thisCell; }
private void SwapStationData( int _i , int _j ) { int iter = 0 ; StationData sd_i = null ; StationData sd_j = null ; StationData sd_tmp = new StationData() ; foreach( StationData sd in m_LevelGeneratorStaticPtr.m_Stations.Values ) { if( iter == _i ) { sd_i = sd ; } else if( iter == _j ) { sd_j = sd ; } ++iter ; } if( null != sd_i && null != sd_j ) { sd_tmp.CopyFrom( sd_j ) ; sd_j.CopyFrom( sd_i ); sd_i.CopyFrom( sd_tmp ) ; } }
private StationData SearchDetailFromDB() { StationData sd = new StationData(); using(var connect = new SQLiteConnection("Data Source=data/RadioStation.db")) { connect.Open(); using(SQLiteCommand command = connect.CreateCommand()) { command.CommandText = "select * from Stations where callsign = '" + callsign + "'"; using(var reader = command.ExecuteReader()) { if(!reader.HasRows) { connect.Close(); return null; } reader.Read(); sd.Callsign = reader["callsign"].ToString(); sd.Address = reader["address"].ToString(); sd.Name = reader["name"].ToString(); } } connect.Close(); } return sd; }