/// <summary> /// Writes the current live world content (entities, positions, etc) to the Current backup; archives whatever was already considered current /// </summary> /// <returns>Success state</returns> public bool WriteLiveBackup(string backupName) { LiveData liveDataAccessor = new LiveData(); try { LoggingUtility.Log("World backup to current INITIATED.", LogChannels.Backup, true); liveDataAccessor.ArchiveFull(backupName); LoggingUtility.Log("Current live world written to archive.", LogChannels.Backup, true); return(WritePlayers()); } catch (Exception ex) { LoggingUtility.LogError(ex); } return(false); }
public LiveData GetData() { var result = new LiveData { Handles = 0, Threads = 0 }; var processes = Process.GetProcesses(); result.Processes = processes.Length; foreach (var process in processes) { result.Handles += process.HandleCount; result.Threads += process.Threads.Count; } result.ClockSpeed = GetCpuSpeedInGHz(); result.InUse = (byte)Math.Round(_cpuPerformanceCounter.NextValue(), 0); result.UpTimeSeconds = CoreHelper.RunningOnVistaOrGreater ? (uint)(NativeMethods.GetTickCount64() / 1000) : NativeMethods.GetTickCount() / 1000; var memStatus = new MEMORYSTATUSEX(); if (NativeMethods.GlobalMemoryStatusEx(memStatus)) { result.UsedMemory = memStatus.ullTotalPhys - memStatus.ullAvailPhys; } result.EthernetAdapterData = new List <EthernetAdapterData>(); foreach (var keyValue in _receiveCounters) { result.EthernetAdapterData.Add(new EthernetAdapterData { Name = keyValue.Key, BytesReceive = keyValue.Value.NextValue(), BytesSend = _sendCounters[keyValue.Key].NextValue() }); } return(result); }
public SelectGameEnvironmentViewModel(IAvailableGameEnvironmentGetRepository availableGameEnvironmentRepository, IGameEnvironmentRepository selectedGameEnvironmentRepository) { _selectedGameEnvironmentRepository = selectedGameEnvironmentRepository; CurrentlyInspectingGameEnvironmentLiveData = new LiveData <GameEnvironment>(); AvailableGameEnvironmentLiveData = new LiveData <IEnumerable <GameEnvironment> >(); _disposable = new CompositeDisposable { availableGameEnvironmentRepository .GetObservableStream() .SubscribeOn(Scheduler.ThreadPool) .ObserveOn(Scheduler.MainThread) .Subscribe(AvailableGameEnvironmentLiveData.PostValue), _selectedGameEnvironmentRepository .GetObservableStream() .SubscribeOn(Scheduler.ThreadPool) .ObserveOn(Scheduler.MainThread) .Subscribe(CurrentlyInspectingGameEnvironmentLiveData.PostValue) }; }
private void DelegateUpdateProcess(ScheduledTask task, LiveData data, bool hasCalendar) { if (hasCalendar && (bool)SettingHelper.Get(Constants.CALENDAR_SHOW_APPOINTMENT)) { //일정이 몇개 있는지를 백타일에 표시 Appointments ap = new Appointments(); ap.SearchCompleted += (so, se) => { VsCalendar.MergeCalendar(data.DayList, se.Results); if (data is LockscreenData) { SetLockscreenImage(task, (LockscreenData)data); } else { SetLivetileImage(task, (LivetileData)data); } //완료됨을 OS에 알림 NotifyComplete(); }; ap.SearchAsync(data.DayList[7].DateTime, data.DayList[data.DayList.Count - 1].DateTime.AddDays(1), null); } else { //백타일에 일정 표시하지 않음 if (data is LockscreenData) { SetLockscreenImage(task, (LockscreenData)data); } else { SetLivetileImage(task, (LivetileData)data); } //완료됨을 OS에 알림 NotifyComplete(); } }
public void Calculate20() { File_Z_BLL zbll = new File_Z_BLL(); LiveData_BLL lbll = new LiveData_BLL(); DateTime lastDay = DateTime.Now.AddDays(-5); List <File_Z> zlist = zbll.GetList(a => a.Date >= lastDay).OrderBy(a => a.Date).ToList(); foreach (File_Z fileZ in zlist) { LiveData liveData = lbll.Get(a => a.FDate == fileZ.Date && a.CountryCode == fileZ.CountryCode && a.Category == "20时"); if (liveData != null) { if (liveData.Rain == null) { liveData.Rain = fileZ.Twenty_Eight + fileZ.Eight_Twenty; lbll.Update(liveData); } } else { liveData = new LiveData() { LDID = Guid.NewGuid(), Category = "20时", CountryCode = fileZ.CountryCode, CountryName = fileZ.CountryName, CreateTime = DateTime.Now, FDate = fileZ.Date, Rain = fileZ.Twenty_Eight + fileZ.Eight_Twenty }; lbll.Add(liveData); } Console.WriteLine("成功计算20时:" + fileZ.CountryName + fileZ.Date.ToString()); } }
public Form1() { InitializeComponent(); textBox1.Text = "initial text"; textBox6.Text = "switchmap inti"; textLiveData1.Value = textBox1.Text; textLiveData2 = textLiveData1.Map <string, string>((text) => { return(string.Concat("Mapped: ", text)); }); textLiveData3 = textLiveData1.SwitchMap <string, string>((text) => { switchMapLive.Value += text; return(switchMapLive); }); textLiveData1.Observe(t => textBox2.Text = t); textLiveData1.Observe(t => textBox4.Text = t); textLiveData2.Observe(t => textBox3.Text = t); textLiveData3.Observe(t => textBox5.Text = t); }
private void BSEvents_energyDidChange(float health) { LiveData.PlayerHealth = health * 100; LiveData.Send(); }
private void ScoreController_scoreDidChangeEvent(int arg1, int arg2) { LiveData.Score = arg1; LiveData.Accuracy = arg1 / scoreController.immediateMaxPossibleRawScore * 100f; LiveData.Send(); }
/// <summary> /// Restores live entity backup from Current /// </summary> /// <returns>Success state</returns> public bool RestoreLiveBackup() { LiveData liveDataAccessor = new LiveData(); string currentBackupDirectory = liveDataAccessor.BaseDirectory + liveDataAccessor.CurrentDirectoryName; //No backup directory? No live data. if (!Directory.Exists(currentBackupDirectory)) { return(false); } LoggingUtility.Log("World restored from current live INITIATED.", LogChannels.Backup, false); try { //dont load players here List <IEntity> entitiesToLoad = new List <IEntity>(); IEnumerable <Type> implimentedTypes = typeof(EntityPartial).Assembly.GetTypes().Where(ty => ty.GetInterfaces().Contains(typeof(IEntity)) && ty.IsClass && !ty.IsAbstract && !ty.GetCustomAttributes <IgnoreAutomatedBackupAttribute>().Any()); foreach (Type type in implimentedTypes.OrderByDescending(type => type == typeof(Gaia) ? 6 : type == typeof(Zone) ? 5 : type == typeof(Locale) ? 3 : type == typeof(Room) ? 3 : type == typeof(Pathway) ? 2 : 0)) { if (!Directory.Exists(currentBackupDirectory + type.Name)) { continue; } DirectoryInfo entityFilesDirectory = new DirectoryInfo(currentBackupDirectory + type.Name); foreach (FileInfo file in entityFilesDirectory.EnumerateFiles()) { entitiesToLoad.Add(liveDataAccessor.ReadEntity(file, type)); } } //Check we found actual data if (!entitiesToLoad.Any(ent => ent.GetType() == typeof(Gaia))) { throw new Exception("No Worlds found, failover."); } if (!entitiesToLoad.Any(ent => ent.GetType() == typeof(Zone))) { throw new Exception("No zones found, failover."); } //Shove them all into the live system first foreach (IEntity entity in entitiesToLoad.OrderBy(ent => ent.Birthdate)) { entity.UpsertToLiveWorldCache(); entity.KickoffProcesses(); } //We need to pick up any places that aren't already live from the file system incase someone added them during the last session\ foreach (IGaiaTemplate thing in TemplateCache.GetAll <IGaiaTemplate>().Where(dt => !entitiesToLoad.Any(ent => ent.TemplateId.Equals(dt.Id) && ent.Birthdate >= dt.LastRevised))) { IGaia entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IGaia; entityThing.SpawnNewInWorld(); } foreach (IZoneTemplate thing in TemplateCache.GetAll <IZoneTemplate>().Where(dt => !entitiesToLoad.Any(ent => ent.TemplateId.Equals(dt.Id) && ent.Birthdate >= dt.LastRevised))) { IZone entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IZone; entityThing.SpawnNewInWorld(); } foreach (ILocaleTemplate thing in TemplateCache.GetAll <ILocaleTemplate>().Where(dt => !entitiesToLoad.Any(ent => ent.TemplateId.Equals(dt.Id) && ent.Birthdate >= dt.LastRevised))) { ILocale entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as ILocale; entityThing.ParentLocation = entityThing.ParentLocation.GetLiveInstance(); entityThing.SpawnNewInWorld(); } foreach (IRoomTemplate thing in TemplateCache.GetAll <IRoomTemplate>().Where(dt => !entitiesToLoad.Any(ent => ent.TemplateId.Equals(dt.Id) && ent.Birthdate >= dt.LastRevised))) { IRoom entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IRoom; entityThing.ParentLocation = entityThing.Template <IRoomTemplate>().ParentLocation.GetLiveInstance(); entityThing.SpawnNewInWorld(); } foreach (IPathwayTemplate thing in TemplateCache.GetAll <IPathwayTemplate>().Where(dt => !entitiesToLoad.Any(ent => ent.TemplateId.Equals(dt.Id) && ent.Birthdate >= dt.LastRevised))) { IPathway entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IPathway; entityThing.SpawnNewInWorld(); } //We have the containers contents and the birthmarks from the deserial //I don't know how we can even begin to do this type agnostically since the collections are held on type specific objects without some super ugly reflection foreach (Room entity in entitiesToLoad.Where(ent => ent.GetType() == typeof(Room))) { foreach (IInanimate obj in entity.Contents.EntitiesContained()) { IInanimate fullObj = LiveCache.Get <IInanimate>(new LiveCacheKey(obj)); entity.MoveFrom(obj); entity.MoveInto(fullObj); } foreach (INonPlayerCharacter obj in entity.MobilesInside.EntitiesContained()) { INonPlayerCharacter fullObj = LiveCache.Get <INonPlayerCharacter>(new LiveCacheKey(obj)); entity.MoveFrom(obj); entity.MoveInto(fullObj); } } foreach (NonPlayerCharacter entity in entitiesToLoad.Where(ent => ent.GetType() == typeof(NonPlayerCharacter))) { foreach (IInanimate obj in entity.Inventory.EntitiesContained()) { IInanimate fullObj = LiveCache.Get <IInanimate>(new LiveCacheKey(obj)); entity.MoveFrom(obj); entity.MoveInto(fullObj); } } foreach (Inanimate entity in entitiesToLoad.Where(ent => ent.GetType() == typeof(Inanimate))) { foreach (Tuple <string, IInanimate> obj in entity.Contents.EntitiesContainedByName()) { IInanimate fullObj = LiveCache.Get <IInanimate>(new LiveCacheKey(obj.Item2)); entity.MoveFrom(obj.Item2); entity.MoveInto(fullObj, obj.Item1); } foreach (Tuple <string, IInanimate> obj in entity.Contents.EntitiesContainedByName()) { INonPlayerCharacter fullObj = LiveCache.Get <INonPlayerCharacter>(new LiveCacheKey(obj.Item2)); entity.MoveFrom((INonPlayerCharacter)obj.Item2); entity.MoveInto(fullObj, obj.Item1); } } //We need to poll the WorldMaps here and give all the rooms their coordinates as well as the zones their sub-maps ParseDimension(); LoggingUtility.Log("World restored from current live.", LogChannels.Backup, false); return(true); } catch (Exception ex) { LoggingUtility.LogError(ex); } return(false); }
public void DataImport() { LiveData_BLL bll = new LiveData_BLL(); List <FileInfo> allFileList = FileHelper.GetShareFileInfos(@"\\172.18.226.109\市县一体化平台文档\检验\A", "A*", "administrator", "yubk0501!"); foreach (FileInfo fileInfo in allFileList) { List <LiveData> sklist = new List <LiveData>(); //string contents = File.ReadAllText(@"\\172.18.226.10\nt40\zdzh\" + item.Value); string countrycode = fileInfo.Name.Substring(1, 5); //string apath = @"P:\zdzh\" + item.Value; string contents = FileHelper.GetShareTextContent(@"\\172.18.226.109\市县一体化平台文档\检验\A\" + fileInfo.Name, "Administrator", "yubk0501!", Encoding.Default); string tbcontents = contents.Substring(contents.IndexOf("TB") + 4, (contents.IndexOf("IB") - contents.IndexOf("TB") - 7)).Replace("\r\n", ""); string[] tb = tbcontents.Split('.'); for (int i = 0; i < tb.Length; i++) { LiveData shikuang = new LiveData(); shikuang.LDID = Guid.NewGuid(); shikuang.FDate = DateTime.ParseExact(fileInfo.Name.Substring(7, 6) + (i + 1).ToString("00"), "yyyyMMdd", CultureInfo.InvariantCulture); shikuang.CountryCode = countrycode; shikuang.CreateTime = DateTime.Now; shikuang.CountryName = CityUtility.GetName(countrycode); shikuang.Category = "20时"; shikuang.MaxTemp = decimal.Parse(tb[i].Substring(119, 4)) / 10; shikuang.MinTemp = decimal.Parse(tb[i].Substring(129, 4)) / 10; sklist.Add(shikuang); } string raincontents = contents.Substring(contents.IndexOf("R6") + 4, tb.Length * 16 - 2).Replace("\r\n", "."); string raincontents2 = contents.Substring(contents.IndexOf("R6") + 4, tb.Length * 18 - 3).Replace("\r\n", "."); string[] rains = raincontents.Split('.'); for (int i = 0; i < rains.Length; i++) { string rainstr = rains[i].Substring(10, 4); if (rainstr != ",,,,") { sklist.ElementAt(i).Rain = decimal.Parse(rainstr) / 10; } else { sklist.ElementAt(i).Rain = (decimal)0.01; } } foreach (var item in sklist) { int count = bll.GetCount(a => a.CountryCode == item.CountryCode && a.FDate == item.FDate && a.Category == "20时"); if (count <= 0) { bll.Add(item); } } Response.Write(countrycode + " " + fileInfo.Name.Substring(7, 6) + sklist.Count().ToString()); } Response.Write(allFileList.Count().ToString()); }
protected void Btn_DataCheck_Click(object sender, EventArgs e) { DateTime startTime = DateTime.Parse(DropDownList_Year.SelectedItem.Value + "-" + DropDownList_Month.SelectedItem.Value + "-01"); DateTime endTime = startTime.AddMonths(1); LiveData_BLL bll = new LiveData_BLL(); List <LiveData> list = bll.GetList( a => a.FDate >= startTime & a.FDate < endTime && a.Category == DropDownList_YBTime.SelectedItem.Value) .OrderBy(a => a.FDate).ThenBy(a => a.CountryCode) .ToList(); //GridView1.DataSource = list; //GridView1.DataBind(); TimeSpan timeSpan = endTime - startTime; List <LiveData_Check> ldcList = new List <LiveData_Check>(); List <string> citys = CityUtility.AllNameList(); for (int i = 0; i < timeSpan.Days; i++) { DateTime currentDate = startTime.AddDays(i); List <LiveData> daylist = list.Where(a => a.FDate == currentDate).ToList(); LiveData_Check ldc = new LiveData_Check(); ldc.Date = currentDate; StringBuilder dataMissStr = new StringBuilder(); foreach (string city in citys) { LiveData dayCity = daylist.Where(a => a.CountryName == city).FirstOrDefault(); if (dayCity != null) { if (dayCity.MaxTemp == null || dayCity.MinTemp == null || dayCity.Rain == null) { dataMissStr.Append("<li style='color:#ff6a00;'>" + city + " 缺少 "); string missElement = string.Empty; if (dayCity.MaxTemp == null) { missElement += "最高温度 "; } if (dayCity.MinTemp == null) { missElement += "最低温度 "; } if (dayCity.Rain == null) { missElement += "降水 "; } dataMissStr.Append(missElement); dataMissStr.Append("数据<br/></li>"); } } else { dataMissStr.Append("<li style='color:#ff0000;'>" + city + " 缺少 最高温度 最低温度 降水 数据<br/></li>"); } } ldc.DataMiss = dataMissStr.ToString(); if (!String.IsNullOrWhiteSpace(ldc.DataMiss)) { ldcList.Add(ldc); } } Repeater_DataCheck.DataSource = ldcList; Repeater_DataCheck.DataBind(); if (ldcList.Count() > 0) { Label_DataMiss.Text = startTime.ToString("yyyy年MM月") + DropDownList_YBTime.SelectedItem.Value + "实况数据有缺失,请及时补充!"; Panel_DataMiss.Visible = true; } else { Label_DataMiss.Text = startTime.ToString("yyyy年MM月") + DropDownList_YBTime.SelectedItem.Value + "实况数据齐全!"; Panel_DataMiss.Visible = false; } }
/// <summary> /// /// </summary> /// <remarks> /// Yes, this function requires a full UserView to listen. We need to know what groups and such the user /// is in for listening; other functions might look this up automatically but because this is a high traffic /// endpoint, we can't keep looking up the user for the caller. /// </remarks /// <param name="listener"></param> /// <param name="lastId"></param> /// <param name="token"></param> /// <returns></returns> public async Task <LiveData> ListenAsync(UserView listener, int lastId = -1, CancellationToken?token = null) { var result = new LiveData() { lastId = lastId }; //No tail recursion optimization, don't do recursive call to self! Easier to just do loop anyway! while (true) { var checkpoint = await ListenEventsAsync(result.lastId, token); //Always keep our "lastId" up to date! result.lastId = checkpoint.LastId; //Data.Max(x => x.id); //Thanks to us caching permissions with the events, we can filter out the events we're not allowed to see immediately, saving us from //weird situations where we get a data cache miss simply due to too many events going through the system that we're not even allowed to see. var events = checkpoint.Data.Where(x => permissionService.CanUserStatic(listener, UserAction.read, x.permissions)); if (events.Count() == 0) { continue; //There is NOTHING to do for this run, because the event(s) in question don't pertain to us } else if (events.Count() > config.MaxEventListen) { events = events.OrderBy(x => x.id).Take(config.MaxEventListen); //Don't let the user get too many events all at once! } else if (events.Count(x => x.id == 0) > 0) //this adds to the computation but shouldn't take too long to compute... { throw new InvalidOperationException("SAFETY CHECK FAILED: events with zero ID discovered after listen!"); } var optimalRoute = false; //Go ahead and set up the return events, we know we'll return SOMETHING this loop, since there's a non-zero amount result.events = events.Select(x => mapper.Map <LiveEventView>(x)).OrderBy(x => x.id).ToList(); //The "fast optimized" route. Hopefully, MOST live updates go through this. if (events.Count() == 1) { var optimalEvent = events.First(); lock (dataCacheLock) { var matching = dataCache.FirstOrDefault(x => x.evnt.id == optimalEvent.id); if (matching != null) { result.objects.Add(optimalEvent.type, matching.data ?? throw new InvalidOperationException($"No data set for event cache item {optimalEvent.id}")); result.optimized = true; optimalRoute = true; } else { throw new InvalidOperationException($"OPTIMAL EVENT BUT NO MATCHING: {optimalEvent.id} VS: {string.Join(",", dataCache.Select(x => x.evnt.id))}"); } } } //Oh, we weren't able to be cool and optimal. Go look up stuff manually! if (!optimalRoute) { //Use only ONE searcher for each listen call! Hopefully this isn't a problem! //NOTE: moved down after the listen so we don't have dangling sqlite connections while waiting for data using var search = dbFactory.CreateSearch(); foreach (var type in events.Select(x => x.type).Distinct()) { var requests = GetSearchRequestsForEvents(events.Where(x => x.type == type)); var searchData = await search.Search(requests, listener.id); result.objects.Add(type, searchData.objects); } } return(result); } }
public void LiveDataValueTypeDefaultSettingsIntegrationTest() { var randomGen = new Random(); var val0 = randomGen.Next(); var val1 = randomGen.Next(); var val2 = randomGen.Next(); var testSequence = new List <int>(new[] { val1, val2, val2, val1, val2, val1, val1 }); _liveDataValueType = new LiveData <int>(val0, _testRxSchedulerFacade.Object); _liveDataValueType.Observe(_lifecycleManager, i => _emittedVerificationListValue.Add(i), e => Assert.Fail("onError called")); Assert.AreEqual(0, _emittedVerificationListValue.Count); _lifecycleManager.OnResume(); Assert.AreEqual(1, _emittedVerificationListValue.Count); Assert.AreEqual(val0, _emittedVerificationListValue[0]); testSequence.ForEach(i => _liveDataValueType.PostValue(i)); Assert.AreEqual(6, _emittedVerificationListValue.Count); Assert.AreEqual(val0, _emittedVerificationListValue[0]); Assert.AreEqual(val1, _emittedVerificationListValue[1]); Assert.AreEqual(val2, _emittedVerificationListValue[2]); Assert.AreEqual(val1, _emittedVerificationListValue[3]); Assert.AreEqual(val2, _emittedVerificationListValue[4]); Assert.AreEqual(val1, _emittedVerificationListValue[5]); _lifecycleManager.OnPause(); testSequence.ForEach(i => _liveDataValueType.PostValue(i)); Assert.AreEqual(6, _emittedVerificationListValue.Count); _lifecycleManager.OnResume(); Assert.AreEqual(6, _emittedVerificationListValue.Count); _lifecycleManager.OnPause(); testSequence.ForEach(i => _liveDataValueType.PostValue(i)); _liveDataValueType.PostValue(val0); _liveDataValueType.PostValue(val1); _liveDataValueType.PostValue(val2); _lifecycleManager.OnResume(); Assert.AreEqual(7, _emittedVerificationListValue.Count); Assert.AreEqual(val2, _emittedVerificationListValue[6]); _lifecycleManager.OnDestroyView(); Assert.AreEqual(7, _emittedVerificationListValue.Count); _liveDataValueType.Observe(_lifecycleManager, i => _emittedVerificationListValue.Add(i), e => Assert.Fail("onError called")); Assert.AreEqual(7, _emittedVerificationListValue.Count); _lifecycleManager.OnResume(); Assert.AreEqual(8, _emittedVerificationListValue.Count); Assert.AreEqual(val2, _emittedVerificationListValue[7]); _lifecycleManager.OnPause(); Assert.AreEqual(8, _emittedVerificationListValue.Count); _lifecycleManager.OnDestroyView(); testSequence.ForEach(i => _liveDataValueType.PostValue(i)); _liveDataValueType.PostValue(val0); _liveDataValueType.PostValue(val1); _liveDataValueType.Observe(_lifecycleManager, i => _emittedVerificationListValue.Add(i), e => Assert.Fail("onError called")); Assert.AreEqual(8, _emittedVerificationListValue.Count); _lifecycleManager.OnResume(); Assert.AreEqual(9, _emittedVerificationListValue.Count); Assert.AreEqual(val1, _emittedVerificationListValue[8]); }
public void LiveDataReferenceTypeAllowDuplicatesIntegrationTest() { var val0 = TestUtils.RandomString(32); var val1 = TestUtils.RandomString(32); var val2 = TestUtils.RandomString(32); var testSequence = new List <string>(new[] { val1, val2, val2, val1, val2, val1, val1 }); _liveDataReferenceType = new LiveData <string>(val0, _testRxSchedulerFacade.Object, true); _liveDataReferenceType.Observe(_lifecycleManager, s => _emittedVerificationListReference.Add(s), e => Assert.Fail("onError called")); Assert.AreEqual(0, _emittedVerificationListReference.Count); _lifecycleManager.OnResume(); Assert.AreEqual(1, _emittedVerificationListReference.Count); Assert.AreEqual(val0, _emittedVerificationListReference[0]); testSequence.ForEach(i => _liveDataReferenceType.PostValue(i)); Assert.AreEqual(8, _emittedVerificationListReference.Count); for (var i = 1; i < _emittedVerificationListReference.Count; ++i) { Assert.AreEqual(testSequence[i - 1], _emittedVerificationListReference[i]); } _lifecycleManager.OnPause(); testSequence.ForEach(s => _liveDataReferenceType.PostValue(s)); Assert.AreEqual(8, _emittedVerificationListReference.Count); _lifecycleManager.OnResume(); Assert.AreEqual(9, _emittedVerificationListReference.Count); Assert.AreEqual(val1, _emittedVerificationListReference[8]); _lifecycleManager.OnPause(); testSequence.ForEach(s => _liveDataReferenceType.PostValue(s)); _liveDataReferenceType.PostValue(val0); _liveDataReferenceType.PostValue(val1); _liveDataReferenceType.PostValue(val2); _lifecycleManager.OnResume(); Assert.AreEqual(10, _emittedVerificationListReference.Count); Assert.AreEqual(val2, _emittedVerificationListReference[9]); _lifecycleManager.OnDestroyView(); Assert.AreEqual(10, _emittedVerificationListReference.Count); _liveDataReferenceType.Observe(_lifecycleManager, s => _emittedVerificationListReference.Add(s), e => Assert.Fail("onError called")); Assert.AreEqual(10, _emittedVerificationListReference.Count); _lifecycleManager.OnResume(); Assert.AreEqual(11, _emittedVerificationListReference.Count); Assert.AreEqual(val2, _emittedVerificationListReference[10]); _lifecycleManager.OnPause(); Assert.AreEqual(11, _emittedVerificationListReference.Count); _lifecycleManager.OnDestroyView(); testSequence.ForEach(i => _liveDataReferenceType.PostValue(i)); _liveDataReferenceType.PostValue(val0); _liveDataReferenceType.PostValue(val1); _liveDataReferenceType.Observe(_lifecycleManager, s => _emittedVerificationListReference.Add(s), e => Assert.Fail("onError called")); Assert.AreEqual(11, _emittedVerificationListReference.Count); _lifecycleManager.OnResume(); Assert.AreEqual(12, _emittedVerificationListReference.Count); Assert.AreEqual(val1, _emittedVerificationListReference[11]); }
public bool DataCheck(DateTime yearMonth, string category) { DateTime startTime = yearMonth; DateTime endTime = startTime.AddMonths(1); LiveData_BLL bll = new LiveData_BLL(); List <LiveData> list = bll.GetList( a => a.FDate >= startTime & a.FDate < endTime && a.Category == category) .OrderBy(a => a.FDate).ThenBy(a => a.CountryCode) .ToList(); //GridView1.DataSource = list; //GridView1.DataBind(); TimeSpan timeSpan = endTime - startTime; List <LiveData_Check> ldcList = new List <LiveData_Check>(); List <string> citys = CityUtility.AllNameList(); for (int i = 0; i < timeSpan.Days; i++) { DateTime currentDate = startTime.AddDays(i); List <LiveData> daylist = list.Where(a => a.FDate == currentDate).ToList(); LiveData_Check ldc = new LiveData_Check(); ldc.Date = currentDate; StringBuilder dataMissStr = new StringBuilder(); foreach (string city in citys) { LiveData dayCity = daylist.Where(a => a.CountryName == city).FirstOrDefault(); if (dayCity != null) { if (dayCity.MaxTemp == null || dayCity.MinTemp == null || dayCity.Rain == null) { dataMissStr.Append("<li style='color:#ff6a00;'>" + city + " 缺少 "); string missElement = string.Empty; if (dayCity.MaxTemp == null) { missElement += "最高温度 "; } if (dayCity.MinTemp == null) { missElement += "最低温度 "; } if (dayCity.Rain == null) { missElement += "降水 "; } dataMissStr.Append(missElement); dataMissStr.Append("数据<br/></li>"); } } else { dataMissStr.Append("<li style='color:#ff0000;'>" + city + " 缺少 最高温度 最低温度 降水 数据<br/></li>"); } } ldc.DataMiss = dataMissStr.ToString(); if (!String.IsNullOrWhiteSpace(ldc.DataMiss)) { ldcList.Add(ldc); } } if (ldcList.Count() > 0) { return(false); } else { return(true); } }
public string DataImportTemp08(DateTime yearMonth) { StringBuilder message = new StringBuilder(); string yearMonthString = yearMonth.ToString("yyyyMM"); DATAHOUR_BLL hbll = new DATAHOUR_BLL(); LiveData_BLL lbll = new LiveData_BLL(); DateTime startTime = DateTime.ParseExact(yearMonthString + "01" + "08", "yyyyMMddHH", CultureInfo.InvariantCulture); DateTime endTime = startTime.AddMonths(1); TimeSpan ts = endTime - startTime; for (int i = 0; i < ts.Days; i++) { DateTime stime = startTime.AddDays(i); DateTime etime = stime.AddDays(1); List <string> citynames = CityUtility.AllNameList(); foreach (string cityname in citynames) { string selectname = cityname; if (cityname == "黄岛") { selectname = "胶南"; } List <DATAHOUR> dlist = hbll.GetList(a => a.STANAME == selectname && a.MINTEMP != 9999 && a.MAXTEMP != 9999 && a.FDATE >= stime && a.FDATE < etime).ToList(); if (dlist.Count > 0) { DateTime seletime = DateTime.Parse(stime.ToShortDateString()); LiveData liveData = lbll.Get(a => a.CountryName == cityname && a.FDate == seletime && a.Category == "08时"); if (liveData != null) { liveData.MaxTemp = dlist.Max(a => a.MAXTEMP); liveData.MinTemp = dlist.Min(a => a.MINTEMP); lbll.Update(liveData); } else { LiveData newModel = new LiveData(); newModel.LDID = Guid.NewGuid(); newModel.FDate = stime; newModel.Category = "08时"; newModel.CountryCode = CityUtility.GetCode(cityname); newModel.CountryName = cityname; newModel.CreateTime = DateTime.Now; newModel.MaxTemp = dlist.Max(a => a.MAXTEMP); newModel.MinTemp = dlist.Min(a => a.MINTEMP); lbll.Add(newModel); } //message.Append(cityname + "<br/>"); } } //message.Append("导入08时温度成功,"stime.ToString("yyyy-MM-dd HH:mm") + "~" + etime.ToString("yyyy-MM-dd HH:mm") + "<br/>"); } message.Append("导入08时温度成功,共计" + ts.Days + "天数据。<br/>"); return(message.ToString()); }
/// <summary> /// Adds data to the cache or replaces the old data with the provided <paramref name="data"/> /// </summary> /// <param name="key"></param> /// <param name="data"></param> public static void AddOrReplace(string key, object data) { var cachedData = new LiveData(data); cache.AddOrUpdate(key, cachedData, (k, v) => cachedData); }
// GET: Liveupdate public ActionResult Liveupdate() { ViewBag.datasource = LiveData.GetData(); return(View()); }
private void BSEvents_gameSceneLoaded() { ResetData(); LiveData.InLevel = true; scoreController = Resources.FindObjectsOfTypeAll <ScoreController>().FirstOrDefault(); scoreController.scoreDidChangeEvent += ScoreController_scoreDidChangeEvent; AudioTimeSyncController audioController = Resources.FindObjectsOfTypeAll <AudioTimeSyncController>().FirstOrDefault(); PlayerData playerData = Resources.FindObjectsOfTypeAll <PlayerDataModel>().FirstOrDefault().playerData; GameplayCoreSceneSetupData currentMap = BS_Utils.Plugin.LevelData.GameplayCoreSceneSetupData; IBeatmapLevel levelData = currentMap.difficultyBeatmap.level; StaticData.SongName = levelData.songName; StaticData.SongSubName = levelData.songSubName; StaticData.SongAuthor = levelData.songAuthorName; StaticData.Mapper = levelData.levelAuthorName; StaticData.BPM = Convert.ToInt32(Math.Round(levelData.beatsPerMinute)); StaticData.Length = Convert.ToInt32(Math.Round(audioController.songLength)); PlayerLevelStatsData playerLevelStats = playerData.GetPlayerLevelStatsData(levelData.levelID, currentMap.difficultyBeatmap.difficulty, currentMap.difficultyBeatmap.parentDifficultyBeatmapSet.beatmapCharacteristic); StaticData.PreviousRecord = playerLevelStats.highScore; if (previousMap == null || previousBeatmap == null || (levelData.levelID != previousMap.difficultyBeatmap.level.levelID)) { Task.Run(async() => { if (previousBeatmap != null) { StaticData.PreviousBSR = previousBeatmap.Key; } Beatmap bm = await beatSaver.Hash(levelData.levelID.Replace("custom_level_", "")); if (bm != null) { StaticData.BSRKey = bm.Key; StaticData.coverImage = BeatSaver.BaseURL + bm.CoverURL; previousBeatmap = bm; } else { StaticData.BSRKey = null; StaticData.coverImage = null; previousBeatmap = null; } StaticData.Send(); }); } else { StaticData.BSRKey = previousBeatmap.Key; StaticData.coverImage = BeatSaver.BaseURL + previousBeatmap.CoverURL; } StaticData.Difficulty = currentMap.difficultyBeatmap.difficultyRank; StaticData.NJS = currentMap.difficultyBeatmap.noteJumpMovementSpeed; StaticData.Modifiers.Add("instaFail", currentMap.gameplayModifiers.instaFail); StaticData.Modifiers.Add("batteryEnergy", currentMap.gameplayModifiers.energyType == GameplayModifiers.EnergyType.Battery); StaticData.Modifiers.Add("disappearingArrows", currentMap.gameplayModifiers.disappearingArrows); StaticData.Modifiers.Add("ghostNotes", currentMap.gameplayModifiers.ghostNotes); StaticData.Modifiers.Add("fasterSong", currentMap.gameplayModifiers.songSpeedMul == 1.2f ? true : false); StaticData.Modifiers.Add("noFail", currentMap.gameplayModifiers.noFail); LiveData.PlayerHealth = StaticData.Modifiers["noFail"] ? 100 : 50; StaticData.Modifiers.Add("noObstacles", currentMap.gameplayModifiers.enabledObstacleType == GameplayModifiers.EnabledObstacleType.NoObstacles); StaticData.Modifiers.Add("noBombs", currentMap.gameplayModifiers.noBombs); StaticData.Modifiers.Add("slowerSong", currentMap.gameplayModifiers.songSpeedMul == 0.85f ? true : false); StaticData.Modifiers.Add("noArrows", currentMap.gameplayModifiers.noArrows); if (currentMap.practiceSettings != null) //In Practice mode { StaticData.PracticeMode = true; startSongTime = new TimeSpan(0, 0, (int)Math.Round(currentMap.practiceSettings.startSongTime) - 1); //1s time desync StaticData.PracticeModeModifiers.Add("songSpeedMul", currentMap.practiceSettings.songSpeedMul); } previousMap = currentMap; TimeElapsed.Start(); TimeElapsedLogger.Start(); StaticData.Send(); LiveData.Send(); }
/// <summary> /// Something went wrong with restoring the live backup, this loads all persistence singeltons from the database (rooms, paths, spawns) /// </summary> /// <returns>success state</returns> public bool NewWorldFallback() { LiveData liveDataAccessor = new LiveData(); //This means we delete the entire Current livedata dir since we're falling back. string currentLiveDirectory = liveDataAccessor.BaseDirectory + liveDataAccessor.CurrentDirectoryName; //No backup directory? No live data. if (Directory.Exists(currentLiveDirectory)) { DirectoryInfo currentDir = new DirectoryInfo(currentLiveDirectory); LoggingUtility.Log("Current Live directory deleted during New World Fallback Procedures.", LogChannels.Backup, true); try { currentDir.Delete(true); } catch { //occasionally will be pissy in an async situation } } //Only load in stuff that is static and spawns as singleton //We need to pick up any places that aren't already live from the file system incase someone added them during the last session\ foreach (IGaiaTemplate thing in TemplateCache.GetAll <IGaiaTemplate>()) { IGaia entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IGaia; } foreach (IZoneTemplate thing in TemplateCache.GetAll <IZoneTemplate>()) { IZone entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IZone; } foreach (ILocaleTemplate thing in TemplateCache.GetAll <ILocaleTemplate>()) { ILocale entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as ILocale; entityThing.ParentLocation = entityThing.Template <ILocaleTemplate>().ParentLocation.GetLiveInstance(); entityThing.GetFromWorldOrSpawn(); } foreach (IRoomTemplate thing in TemplateCache.GetAll <IRoomTemplate>()) { IRoom entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IRoom; entityThing.ParentLocation = entityThing.Template <IRoomTemplate>().ParentLocation.GetLiveInstance(); entityThing.GetFromWorldOrSpawn(); } foreach (IPathwayTemplate thing in TemplateCache.GetAll <IPathwayTemplate>()) { IPathway entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IPathway; } ParseDimension(); LoggingUtility.Log("World restored from data fallback.", LogChannels.Backup, true); return(true); }
public void Temp20() { DATAHOUR_BLL hbll = new DATAHOUR_BLL(); LiveData_BLL lbll = new LiveData_BLL(); DateTime.Now.AddDays(-1).ToString("yyyyMMdd"); DateTime startTime = DateTime.ParseExact(DateTime.Now.AddDays(-5).ToString("yyyyMMdd") + "20", "yyyyMMddHH", CultureInfo.InvariantCulture); DateTime endTime = startTime.AddDays(4); TimeSpan ts = endTime - startTime; for (int i = 0; i < ts.Days; i++) { DateTime stime = startTime.AddDays(i); DateTime etime = stime.AddDays(1); List <string> citynames = CityUtility.AllNameList(); foreach (string cityname in citynames) { string selectname = cityname; if (cityname == "黄岛") { selectname = "胶南"; } List <DATAHOUR> dlist = hbll.GetList(a => a.STANAME == selectname && a.MINTEMP != 9999 && a.MAXTEMP != 9999 && a.FDATE >= stime && a.FDATE < etime).ToList(); if (dlist.Count > 0) { DateTime seletime = DateTime.Parse(etime.ToShortDateString()); LiveData liveData = lbll.Get(a => a.CountryName == cityname && a.FDate == seletime && a.Category == "20时"); if (liveData != null) { liveData.MaxTemp = dlist.Max(a => a.MAXTEMP); liveData.MinTemp = dlist.Min(a => a.MINTEMP); lbll.Update(liveData); } else { LiveData newModel = new LiveData(); newModel.LDID = Guid.NewGuid(); newModel.FDate = etime; newModel.Category = "20时"; newModel.CountryCode = CityUtility.GetCode(cityname); newModel.CountryName = cityname; newModel.CreateTime = DateTime.Now; newModel.MaxTemp = dlist.Max(a => a.MAXTEMP); newModel.MinTemp = dlist.Min(a => a.MINTEMP); lbll.Add(newModel); } Console.WriteLine(cityname); } } Console.WriteLine(stime.ToString("yyyy-MM-dd HH:mm") + "~" + etime.ToString("yyyy-MM-dd HH:mm")); } }