public void Set(int key, int value) { //Console.WriteLine("Adding " + key + ":" + value + " -- " + (head == null ? "NULL" : head.Key.ToString()) +" : " + (tail == null ? "NULL" : tail.Key.ToString())+" : " + (tail == null || tail.Prev == null ? "NULL" : tail.Prev.Key.ToString())+" : " + (head == null || head.Next == null ? "NULL" : head.Next.Key.ToString())); if (dict.ContainsKey(key)) { var r = dict[key]; r.Val = value; BringToHead(r); } else { var nv = new CachedValue() { Val = value, Key = key }; if (count == capacity) { DiscardLRU(); } else { count++; } AddNew(nv); dict.Add(key, nv); } //Console.WriteLine("Added " + key + ":" + value + " -- " + (head == null ? "NULL" : head.Key.ToString()) +" : " + (tail == null ? "NULL" : tail.Key.ToString())+" : " + (tail == null || tail.Prev == null ? "NULL" : tail.Prev.Key.ToString())+" : " + (head == null || head.Next == null ? "NULL" : head.Next.Key.ToString())); }
public void LambdaLifting(ITreeNode node, CachedValue <string> cachedValue) { var str0 = cachedValue.GetOrCreate(node, 4222, (_, __) => _.ToString()); var str1 = cachedValue.GetOrCreate(node, _ => _.ToString()); var str2 = cachedValue.GetOrCreate(node, _ => node.ToString()); var str3 = cachedValue.GetOrCreate(() => node.ToString()); }
public override void Initialize() { if (!IsInNovember(DateTime.Now)) { throw new NotNovemberException("I can only nut during november, the one month where one must not nut."); } _chanceStartDay = GetConfigCache("ChanceStartDay", x => 10); _chanceStartPercent = GetConfigCache("ChanceStartPercent", x => 10f); _chancePerDayPercent = GetConfigCache("ChancePerDayPercent", x => 5f); _refractoryPeriod = GetConfigCache("RefractoryPeriod", x => 60 * 60 * 2); // two hours. _nutters = GetDataCache("Nutters", x => new List <ulong>()); AddConfigInfo <int>("setchancestartday", "", (x) => _chanceStartDay.SetValue(x), (success, x) => $"Start day set to day {x}.", "day"); AddConfigInfo <float>("setchancestartpercent", "", (x) => _chanceStartPercent.SetValue(x), (success, x) => $"Starting chance after starting day set to {x}%", "chance"); AddConfigInfo <float>("setchanceperday", "", (x) => _chancePerDayPercent.SetValue(x), (success, x) => $"Chance per day after starting day set to {x}%", "chance per day"); AddConfigInfo <int>("setrefractoryperiod", "", (x) => _refractoryPeriod.SetValue(x), (success, x) => $"Refractory period set to {x} seconds.", "seconds"); GuildHandler.Clock.OnDayPassed += CheckDate; _nutCommand = new NutCommand() { ParentPlugin = this }; SendMessage("Moduthulhu-Command Root", "AddCommand", _nutCommand); }
public Precursor(SkylineDataSchema dataSchema, IdentityPath identityPath) : base(dataSchema, identityPath) { _peptide = new Lazy <Peptide>(() => new Peptide(DataSchema, IdentityPath.Parent)); _transitions = CachedValue.Create(dataSchema, () => DocNode.Children .Select(child => new Transition(DataSchema, new IdentityPath(IdentityPath, child.Id))).ToArray()); _results = CachedValue.Create(dataSchema, MakeResults); }
public ProcessedProperty(PropertyInfo property, Processor processor, ProcessedType declaringType) : base(processor, declaringType) { Property = property; getMethod = new CachedValue <ProcessedMethod> (() => { var getter = Property.GetGetMethod(); if (getter != null) { return(new ProcessedMethod(getter, Processor, declaringType) { NameOverride = GetterName, IsPropertyImplementation = true }); } return(null); }); setMethod = new CachedValue <ProcessedMethod> (() => { var setter = Property.GetSetMethod(); if (setter != null) { return(new ProcessedMethod(setter, Processor, declaringType) { NameOverride = SetterName, IsPropertyImplementation = true }); } return(null); }); }
public TheGame(IMemory m, Cache cache) { pM = m; pCache = cache; pTheGame = this; Instance = this; Address = m.Read <long>(m.BaseOffsets[OffsetsName.GameStateOffset] + m.AddressOfProcess); _AreaChangeCount = new TimeCache <int>(() => M.Read <int>(M.AddressOfProcess + M.BaseOffsets[OffsetsName.AreaChangeCount]), 50); AllGameStates = ReadList(Address); PreGameStatePtr = AllGameStates[GameStateE.PreGameState].Address; LoginStatePtr = AllGameStates[GameStateE.LoginState].Address; SelectCharacterStatePtr = AllGameStates[GameStateE.SelectCharacterState].Address; WaitingStatePtr = AllGameStates[GameStateE.WaitingState].Address; InGameStatePtr = AllGameStates[GameStateE.InGameState].Address; LoadingStatePtr = AllGameStates[GameStateE.LoadingState].Address; EscapeStatePtr = AllGameStates[GameStateE.EscapeState].Address; LoadingState = new AreaLoadingState(AllGameStates[GameStateE.AreaLoadingState]); IngameState = new IngameState(AllGameStates[GameStateE.InGameState]); _inGame = new FrameCache <bool>( () => IngameState.Address != 0 && IngameState.Data.Address != 0 && IngameState.Data.ServerData.Address != 0 && !IsLoading /*&& * IngameState.ServerData.IsInGame*/); Files = new FilesContainer(m); }
public Stats() { _cachedValue = new FrameCache <StatsComponentOffsets>(() => M.Read <StatsComponentOffsets>(Address)); _statDictionary = new FrameCache <Dictionary <GameStat, int> >(ParseStats); // _humanDictionary = new FrameCache<Dictionary<string,int>>(HumanStats); }
private void IfNotNull(CachedValue <string> value, Action <string> ifNot) { if (!string.IsNullOrEmpty(value.GetValue())) { ifNot(value.GetValue()); } }
protected DynamicProperty() { m_CachedBooleanValue = new DelegateCachedValue <bool>(this, rep => { if ( m_TrueValues.Any( v => string.Equals(rep, v, StringComparison.OrdinalIgnoreCase))) { return(true); } if ( m_FalseValues.Any( v => string.Equals(rep, v, StringComparison.OrdinalIgnoreCase))) { return(false); } throw new ArgumentException(); }); m_CachedStringValue = new DelegateCachedValue <string>(this, rep => rep); m_CachedIntegerValue = new DelegateCachedValue <int>(this, int.Parse); m_CachedLongValue = new DelegateCachedValue <long>(this, long.Parse); m_CachedFloatValue = new DelegateCachedValue <float>(this, float.Parse); m_CachedDoubleValue = new DelegateCachedValue <double>(this, double.Parse); m_CachedTypeValue = new DelegateCachedValue <Type>(this, Type.GetType); }
public TheGame(IMemory m, Cache cache) { pM = m; pCache = cache; pTheGame = this; Instance = this; Address = m.Read <long>(m.BaseOffsets[OffsetsName.GameStateOffset] + m.AddressOfProcess); _AreaChangeCount = new TimeCache <int>(() => M.Read <int>(M.AddressOfProcess + M.BaseOffsets[OffsetsName.AreaChangeCount]), 50); AllGameStates = ReadHashMap(Address + 0x48); PreGameStatePtr = AllGameStates["PreGameState"].Address; LoginStatePtr = AllGameStates["LoginState"].Address; SelectCharacterStatePtr = AllGameStates["SelectCharacterState"].Address; WaitingStatePtr = AllGameStates["WaitingState"].Address; InGameStatePtr = AllGameStates["InGameState"].Address; LoadingStatePtr = AllGameStates["LoadingState"].Address; EscapeStatePtr = AllGameStates["EscapeState"].Address; LoadingState = AllGameStates["AreaLoadingState"].AsObject <AreaLoadingState>(); IngameState = AllGameStates["InGameState"].AsObject <IngameState>(); _inGame = new FrameCache <bool>( () => IngameState.Address != 0 && IngameState.Data.Address != 0 && IngameState.ServerData.Address != 0 && !IsLoading /*&& * IngameState.ServerData.IsInGame*/); Files = new FilesContainer(m); DataOff = Extensions.GetOffset <IngameStateOffsets>(nameof(IngameStateOffsets.Data)); CurrentAreaHashOff = Extensions.GetOffset <IngameDataOffsets>(nameof(IngameDataOffsets.CurrentAreaHash)); }
public async Task Redis_ExpireAfter() { var cache = CreateCache(); var cacheStrategy = cache.Method(c => c.DoSomeWork()) .ExpireAfter(TimeSpan.FromSeconds(3)); var start = DateTime.UtcNow; CachedValue <double> firstResult = cacheStrategy.Get(); Assert.AreEqual(0L, firstResult.Version); await Task.Delay(TimeSpan.FromSeconds(2)); //we should still get the same cached version of data CachedValue <double> secondResult = cacheStrategy.Get(); Assert.AreEqual(firstResult.CachedDate, secondResult.CachedDate); await Task.Delay(TimeSpan.FromSeconds(4)); //we should have a new version of data because the sliding expiration has expired CachedValue <double> thirdResult = cacheStrategy.Get(); Assert.AreNotEqual(firstResult.CachedDate, thirdResult.CachedDate); }
/// <summary> /// Asynchronously executes the plan /// </summary> public virtual async Task <CachedValue <T> > ExecuteAsync() { CachedValue <T> cachedValue = null; try { cachedValue = Cache.Get <T>(Key, Region); CacheValidationResult validationResult = await ValidateCachedValueAsync(cachedValue); if (validationResult != CacheValidationResult.Valid && (validationResult == CacheValidationResult.Invalid || cachedValue == null)) { cachedValue = await RetrieveCachedValueAsync(previousCachedValue : cachedValue); } return(cachedValue); } catch (FluentCache.FluentCacheException cacheException) { if (!ExceptionHandler.TryHandleCachingFailure(cacheException)) { throw; } else { return(null); } } }
public override bool Initialise() { Player = GameController.Player; ingameUI = GameController.IngameState.IngameUi; PlayerBar = new HealthBar(Player, Settings); GameController.EntityListWrapper.PlayerUpdate += (sender, args) => { Player = GameController.Player; PlayerBar = new HealthBar(Player, Settings); }; ingameUICheckVisible = new TimeCache <bool>(() => { windowRectangle = GameController.Window.GetWindowRectangleReal(); windowSize = new Size2F(windowRectangle.Width / 2560, windowRectangle.Height / 1600); camera = GameController.Game.IngameState.Camera; return(ingameUI.BetrayalWindow.IsVisibleLocal || ingameUI.SellWindow.IsVisibleLocal || ingameUI.DelveWindow.IsVisibleLocal || ingameUI.IncursionWindow.IsVisibleLocal || ingameUI.UnveilWindow.IsVisibleLocal || ingameUI.TreePanel.IsVisibleLocal || ingameUI.AtlasPanel.IsVisibleLocal || ingameUI.CraftBench.IsVisibleLocal); }, 250); ReadIgnoreFile(); return(true); }
public void Method_Get_Invalidation(Cache <Example> cache) { bool isInvalid = false; Func <CachedValue <double>, CacheValidationResult> validate = existing => { if (isInvalid) { return(CacheValidationResult.Invalid); } else { return(CacheValidationResult.Unknown); } }; CacheStrategy <double> strategy = cache.Method(c => c.CalculateSomeWork()) .Validate(validate); CachedValue <double> result0 = strategy.Get(); Assert.AreEqual(0L, result0.Version); isInvalid = true; CachedValue <double> result1 = strategy.Get(); CachedValue <double> result2 = strategy.Get(); Assert.AreEqual(1L, result1.Version); Assert.AreEqual(2L, result2.Version); }
public void Value_WhenFirstAccessed_IsHydrated() { const string value = "a value"; var cache = new CachedValue<string>(() => value); Assert.That(cache.Value, Is.SameAs(value)); }
public IngameState(GameState parent) { Address = parent.Address; StateName = parent.StateName; _ingameState = new FrameCache <IngameStateOffsets>(() => M.Read <IngameStateOffsets>(Address)); _worldData = new AreaCache <WorldData>(() => GetObject <WorldData>(_ingameState.Value.WorldData)); _ingameData = new AreaCache <IngameData>(() => GetObject <IngameData>(_ingameState.Value.Data)); _ingameUi = new AreaCache <IngameUIElements>(() => GetObject <IngameUIElements>(_ingameState.Value.IngameUi)); _UIRoot = new AreaCache <Element>(() => GetObject <Element>(_ingameState.Value.UIRoot)); _UIHover = new FrameCache <Element>(() => GetObject <Element>(_ingameState.Value.UIHover)); _UIHoverPosX = new FrameCache <float>(() => _ingameState.Value.UIHoverPos.X); _UIHoverPosY = new FrameCache <float>(() => _ingameState.Value.UIHoverPos.Y); _UIHoverTooltip = new FrameCache <Element>(() => GetObject <Element>(_ingameState.Value.UIHoverTooltip)); _MousePosX = new FrameCache <float>(() => _ingameState.Value.MousePos.X); _MousePosY = new FrameCache <float>(() => _ingameState.Value.MousePos.Y); _DiagnosticInfoType = new FrameCache <DiagnosticInfoType>(() => (DiagnosticInfoType)_ingameState.Value.DiagnosticInfoType); _LatencyRectangle = new AreaCache <DiagnosticElement>(() => GetObject <DiagnosticElement>(Address + LatencyRectangleOffset)); _FrameTimeRectangle = new AreaCache <DiagnosticElement>(() => GetObject <DiagnosticElement>(Address + FrameTimeRectangleOffset)); _FPSRectangle = new AreaCache <DiagnosticElement>(() => GetObject <DiagnosticElement>(Address + FPSRectangleOffset)); _TimeInGameF = new FrameCache <float>(() => _ingameState.Value.TimeInGameF); _EntityLabelMap = new AreaCache <EntityLabelMapOffsets>(() => M.Read <EntityLabelMapOffsets>(_ingameState.Value.EntityLabelMap)); }
public Chest() { _cachedValue = new FramesCache <ChestComponentOffsets>(() => M.Read <ChestComponentOffsets>(Address), 3); _cachedValueStrongboxData = new FramesCache <StrongboxChestComponentData>(() => M.Read <StrongboxChestComponentData>(_cachedValue.Value.StrongboxData), 3); }
public void Method_Get(Cache <Example> cache) { CachedValue <double> result = cache.Method(c => c.CalculateSomeWork()) .Get(); Assert.IsNotNull(result, "Should not return null since we specified a retrieval mechanism"); }
public WorldData() { _worldData = new FrameCache <WorldDataOffsets>(() => M.Read <WorldDataOffsets>(Address)); _CurrentArea = new AreaCache <AreaTemplate>(() => GetObject <AreaTemplate>(M.Read <WorldAreaDetailsOffsets>(_worldData.Value.WorldAreaDetails).AreaTemplate)); _CurrentWorldArea = new AreaCache <WorldArea>(() => TheGame.Files.WorldAreas.GetByAddress(CurrentArea.Address)); _camera = new AreaCache <Camera>(() => GetObject <Camera>(Address + CameraOffset)); }
public RepositoryService( GitRepositoryChangedEvent repositoryChangedEvent, GitWorkingTreeChangedEvent workingTreeChangedEvent ) { _repositoryChangedEvent = repositoryChangedEvent; _workingTreeChangedEvent = workingTreeChangedEvent; _status = new CachedValue<StatusCollection>( () => { if (!IsGitRepository) return new StatusCollection(Enumerable.Empty<Status>()); var clean = new Clean { Target = Clean.CleanTarget.Ignored, IncludeDirectories = false }; var statusResult = Git.Execute(new Git.Commands.Status()); var cleanResult = Git.Execute(clean); return new StatusCollection( statusResult.Concat(cleanResult.Select(name => new Status(System.IO.Path.Combine(BaseDirectory, name), FileStatus.Ignored))) ); } ); }
public CachedRepositoryService(TimeSpan cacheDelay, IRepositoryService repository) { _repository = repository; _existsCache = new CachedValue<string, bool>(id => _repository.Exists(id), cacheDelay); _queryCache = new CachedValue<CIQueryParameters, ConfigurationItemId[]>(p => _repository.Query(p), cacheDelay); _getCache = new CachedValue<string, XElement>(id => _repository.Get(id), cacheDelay); }
public Cached <TValue> Get(TKey key) { var textKey = _keyFormatter(key); var result = _cache.Get(textKey) as Cached <TValue>; if (result != null) { return(result); } var cacheItemValue = new CachedValue(_valueFactory, key, () => Touch(textKey)); var cacheItem = new CacheItem(textKey, cacheItemValue); var cacheItemPolicy = _policyProvider(new CacheExpirationSelector(key)).Policy; cacheItemPolicy.RemovedCallback = OnCacheItemRemoved; var existingItem = _cache.AddOrGetExisting(cacheItem, cacheItemPolicy); if (existingItem != cacheItem) { result = existingItem.Value as CachedValue; if (result != null) { return(result); } _cache.Set(cacheItem, cacheItemPolicy); } return(cacheItemValue); }
public ResultFile(Replicate replicate, ChromFileInfoId chromFileInfoId, int optStep) : base(replicate.DataSchema) { Replicate = replicate; ChromFileInfoId = chromFileInfoId; _chromFileInfo = CachedValue.Create(DataSchema, () => Replicate.ChromatogramSet.GetFileInfo(ChromFileInfoId)); OptimizationStep = optStep; }
public static async Task <ValueLock> EnterAsync(CachedValue value) { var semaphore = Semaphores.GetOrAdd(value, _ => new SemaphoreSlim(1)); await semaphore.WaitAsync().ConfigureAwait(false); return(new ValueLock(value, semaphore)); }
public async Task Method_ExpireAfter_Callback(Cache <Example> cache) { TimeSpan wait1 = TimeSpan.FromSeconds(1.25); TimeSpan wait2 = TimeSpan.FromSeconds(0.75); Func <double, TimeSpan> waitCallback = d => d < 1.0 ? wait1 : wait2; CacheStrategy <double> strategy = cache.Method(c => c.CalculateSomeWork()) .ExpireAfter(waitCallback); DateTime firstCacheDate = default(DateTime); strategy.Get(); for (int i = 1; i < 10; i++) { CachedValue <double> result = strategy.Get(); Assert.AreEqual(0L, result.Version, "These calls should be cached"); var wait = waitCallback(result.Value); await Task.Delay(TimeSpan.FromSeconds(wait.TotalSeconds / 5.0)); firstCacheDate = result.CachedDate; } await Task.Delay(wait1 + wait2); CachedValue <double> expiredResult = strategy.Get(); Assert.AreNotEqual(firstCacheDate, expiredResult.CachedDate, "This call should have expired after waiting"); }
public override void Initialize() { AssertPermission(GuildPermission.ManageChannels); _commandSet = new VoiceNameSet { ParentPlugin = this }; GuildHandler.ChannelCreated += OnChannelCreated; GuildHandler.ChannelDestroyed += OnChannelDestroyed; GuildHandler.UserVoiceStateUpdated += OnVoiceStateUpdated; GuildHandler.GuildMemberUpdated += OnGuildMemberUpdated; GuildHandler.ChannelUpdated += OnChannelUpdated; InitDefaultTags(); _channelNames = GetConfigCache("ChannelNames", x => x.GetGuild().VoiceChannels.ToDictionary(y => y.Id, z => z.Name)); _channelNames.Store(); _toIgnore = GetConfigCache("ToIgnore", x => new List <ulong> { (x.GetGuild().AFKChannel?.Id).GetValueOrDefault() }); _musicBotId = GetConfigCache("MusicBotId", x => (ulong)0); _internationalRoleId = GetConfigCache("MusicBotId", x => (ulong)0); _nameFormat = GetConfigCache("NameFormat", x => $"{_formatStart}{_formatNameStr}{_formatEnd} - {_formatStart}{_formatGameStr}{_formatEnd} {_formatStart}({_formatAmountPlayersStr}){_formatEnd}"); // lol _shortenedGameNames = GetConfigCache("ShortenedGameNames", x => new Dictionary <string, string>()); AddConfigInfo("Set Channel Name", "Display channel names", () => "Current channel names:\n" + string.Join('\n', _channelNames.GetValue().Select(x => x.Value).ToArray())); AddConfigInfo <SocketVoiceChannel, string>("Set Channel Name", "Set channel name", (x, y) => _channelNames.MutateValue(z => z[x.Id] = y), (success, x, y) => $"Succesfully set channel '{x.Name}' to '{y}'", "Channel", "New name"); AddConfigInfo <string, string>("Set Channel Name", "Set channel name", (x, y) => _channelNames.MutateValue(z => z[GuildHandler.GetVoiceChannel(x).Id] = y), (success, x, y) => "Succesfully set channel names.", "Channel", "New name"); AddConfigInfo <SocketVoiceChannel>("Dont Name Channel", "Ignore channel", x => _toIgnore.MutateValue(y => y.Add(x.Id)), (success, x) => $"Added channel '{x.Name}' to list of ignored channels.", "Channel"); AddConfigInfo <ulong>("Dont Name Channel", "Ignore channel", x => _toIgnore.MutateValue(y => y.Add(GuildHandler.GetVoiceChannel(x).Id)), (success, x) => $"Added channel '{GuildHandler.GetVoiceChannel (x).Name}' to list of ignored channels.", "ignored"); AddConfigInfo <string>("Dont Name Channel", "Ignore channel", x => _toIgnore.MutateValue(y => y.Add(GuildHandler.GetVoiceChannel(x).Id)), (success, x) => $"Added channel '{GuildHandler.GetVoiceChannel(x).Name}' to list of ignored channels.", "Channel"); AddConfigInfo <SocketVoiceChannel>("Do Name Channel", "Unignore channel", x => _toIgnore.MutateValue(y => y.Remove(x.Id)), (success, x) => $"Removed channel '{x.Name}' from list of ignored.", "Channel"); AddConfigInfo <ulong>("Do Name Channel", "Unignore channel", x => _toIgnore.MutateValue(y => y.Remove(GuildHandler.GetVoiceChannel(x).Id)), (success, x) => $"Removed channel '{GuildHandler.GetChannel(x)}' from list of ignored.", "Channel"); AddConfigInfo <string>("Do Name Channel", "Unignore channel", x => _toIgnore.MutateValue(y => y.Remove(GuildHandler.GetVoiceChannel(x).Id)), (success, x) => $"Removed channel '{GuildHandler.GetChannel(x)}' from list of ignored.", "Channel"); AddConfigInfo <SocketGuildUser>("Set Music Bot", "Set music bot.", x => _musicBotId.SetValue(x.Id), (success, x) => $"Set music bot to be {x.Id}.", "Music Bot"); AddConfigInfo <string>("Set Music Bot", "Set music bot.", x => _musicBotId.SetValue(GuildHandler.GetUser(x).Id), (success, x) => $"Set music bot to be {GuildHandler.GetUser(x).GetShownName()}.", "Music Bot"); AddConfigInfo("Set Music Bot", "Show music bot.", () => GuildHandler.FindUser(_musicBotId.GetValue()) == null ? "Current music bot doesn't exist :(" : "Current music bot is " + GuildHandler.GetUser(_musicBotId.GetValue()).GetShownName()); AddConfigInfo <SocketRole>("Set International Role", "Set role.", x => _internationalRoleId.SetValue(x.Id), (success, x) => $"Set international role to be {x}.", "Role"); AddConfigInfo <string>("Set International Role", "Set role.", x => _internationalRoleId.SetValue(GuildHandler.GetRole(x).Id), (success, x) => $"Set international role to be {GuildHandler.GetRole(x).Name}.", "Role Name"); AddConfigInfo("Set International Role", "Show role.", () => GuildHandler.FindRole(_internationalRoleId.GetValue()) == null ? "Current international role doesn't exist :(" : "Current international role is " + GuildHandler.GetRole(_internationalRoleId.GetValue()).Name); AddConfigInfo("Set Name Format", "Set format", () => $"Current format is '{_nameFormat.GetValue()}' which might look like this in practice: '{FormatName(_nameFormat.GetValue(), _formatStart, _formatEnd, "General 1", "Cool Game 3: The Coolest", 5)}'."); AddConfigInfo <string>("Set Name Format", "Set format", x => _nameFormat.SetValue(x), (success, x) => $"Set format to '{x}' which might look like this in practice: '{FormatName(x, _formatStart, _formatEnd, "General 1", "Cool Game 3: The Coolest", 5)}'.", "Format"); AddConfigInfo <string, string>("Shorten Game Name", "Shorten a games name", (x, y) => SetShortenedGameName(x, y), (success, x, y) => $"'{x}' will now be shortened to '{y}'.", "Game", "Name"); SendMessage("Moduthulhu-Command Root", "AddCommand", _commandSet); AddGeneralFeaturesStateAttribute("AutomatedVoiceNames", "Automatically changing voice channel names to reflect games played within."); RegisterMessageAction("AddTag", x => AddTag(new Tag((string)x[0], (string)x[1], (Func <SocketVoiceChannel, bool>)x[2]))); RegisterMessageAction("RemoveTag", x => RemoveTag((string)x[0])); SetStateChangeHeaders("Tags", "The following voice channel tags has been added", "The following voice channel tags has been removed", "The following voice channel tags has been modified"); RegisterMessageAction("UpdateChannel", x => UpdateChannel(GuildHandler.GetVoiceChannel((ulong)x[0])).ConfigureAwait(false)); }
public IngameData() { _IngameData = new AreaCache <IngameDataOffsets>(() => M.Read <IngameDataOffsets>(Address)); _LocalPlayer = new AreaCache <Entity>(() => GetObject <Entity>(_IngameData.Value.LocalPlayer)); _EntitiesCount = new FrameCache <long>(() => M.Read <long>(Address + EntityCountOffset)); _ServerData = new AreaCache <ServerData>(() => GetObject <ServerData>(_IngameData.Value.ServerData)); }
public Mods() { _cachedData = new FrameCache <ModsComponentOffsets>(() => M.Read <ModsComponentOffsets>(Address)); _cachedDetails = new FrameCache <ModsComponentDetailsOffsets>(() => M.Read <ModsComponentDetailsOffsets>(_cachedData.Value.ModsComponentDetailsKey)); }
/************************************************************************************************************************/ /// <summary> /// If a value has already been cached for the specified `key`, return it. Otherwise create a new one using /// the delegate provided in the constructor and cache it. /// <para></para> /// This method also periodically removes values that have not been used recently. /// </summary> public TValue Convert(TKey key) { CachedValue cached; // The next time a value is retrieved after at least 100 frames, clear out any old ones. var frame = Time.frameCount; if (_LastCleanupFrame + 100 < frame) { for (int i = Keys.Count - 1; i >= 0; i--) { var checkKey = Keys[i]; if (!Cache.TryGetValue(checkKey, out cached) || cached.lastFrameAccessed <= _LastCleanupFrame) { Cache.Remove(checkKey); Keys.RemoveAt(i); } } _LastCleanupFrame = frame; } if (!Cache.TryGetValue(key, out cached)) { Cache.Add(key, cached = new CachedValue { value = ConvertToValue(key) }); Keys.Add(key); } cached.lastFrameAccessed = frame; return(cached.value); }
public IngameState() { _ingameState = new FrameCache <IngameStateOffsets>(() => M.Read <IngameStateOffsets>(Address /*+M.offsets.IgsOffsetDelta*/)); _camera = new AreaCache <Camera>( () => GetObject <Camera>(Address + /*0x1258*/ Extensions.GetOffset <IngameStateOffsets>(nameof(IngameStateOffsets.Camera)))); _ingameData = new AreaCache <IngameData>(() => GetObject <IngameData>(_ingameState.Value.Data)); _serverData = new AreaCache <ServerData>(() => GetObject <ServerData>(_ingameState.Value.ServerData)); _ingameUi = new AreaCache <IngameUIElements>(() => GetObject <IngameUIElements>(_ingameState.Value.IngameUi)); _UIRoot = new AreaCache <Element>(() => GetObject <Element>(_ingameState.Value.UIRoot)); _UIHover = new FrameCache <Element>(() => GetObject <Element>(_ingameState.Value.UIHover)); _UIHoverX = new FrameCache <float>(() => _ingameState.Value.UIHoverX); _UIHoverY = new FrameCache <float>(() => _ingameState.Value.UIHoverY); _UIHoverTooltip = new FrameCache <Element>(() => GetObject <Element>(_ingameState.Value.UIHoverTooltip)); _CurrentUElementPosX = new FrameCache <float>(() => _ingameState.Value.CurentUElementPosX); _CurrentUElementPosY = new FrameCache <float>(() => _ingameState.Value.CurentUElementPosY); _DiagnosticInfoType = new FrameCache <DiagnosticInfoType>(() => (DiagnosticInfoType)_ingameState.Value.DiagnosticInfoType); _LatencyRectangle = new AreaCache <DiagnosticElement>( () => GetObject <DiagnosticElement>( Address + Extensions.GetOffset <IngameStateOffsets>(nameof(IngameStateOffsets.LatencyRectangle)))); _FrameTimeRectangle = new AreaCache <DiagnosticElement>( () => GetObject <DiagnosticElement>(Address + /*0x1628*/ +Extensions.GetOffset <IngameStateOffsets>( nameof(IngameStateOffsets.FrameTimeRectangle)))); _FPSRectangle = new AreaCache <DiagnosticElement>( () => GetObject <DiagnosticElement>(Address /*0x1870*/ + Extensions.GetOffset <IngameStateOffsets>(nameof(IngameStateOffsets.FPSRectangle)))); _TimeInGameF = new FrameCache <float>(() => _ingameState.Value.TimeInGameF); _EntityLabelMap = new AreaCache <EntityLabelMapOffsets>(() => M.Read <EntityLabelMapOffsets>(_ingameState.Value.EntityLabelMap)); }
public void HydratingFromMultipleThreads_IsSafe() { var numberOfHydrations = 0; var cache = new CachedValue<int>(() => ++numberOfHydrations); Assert.That(cache.Value, Is.EqualTo(1)); using (var countdownEvent = new CountdownEvent(2)) { Action threadAction = () => { cache.Invalidate(); countdownEvent.Signal(); countdownEvent.Wait(); Assert.That(cache.Value, Is.EqualTo(2)); }; var t1 = threadAction.BeginInvoke(threadAction.EndInvoke, null); var t2 = threadAction.BeginInvoke(threadAction.EndInvoke, null); WaitHandle.WaitAll(new[]{t1.AsyncWaitHandle, t2.AsyncWaitHandle}); } Assert.That(numberOfHydrations, Is.EqualTo(2)); }
public async Task Method_ExpireAfter(Cache <Example> cache) { TimeSpan wait = TimeSpan.FromSeconds(1); CacheStrategy <double> strategy = cache.Method(c => c.CalculateSomeWork()) .ExpireAfter(wait); DateTime firstCacheDate = default(DateTime); strategy.Get(); for (int i = 1; i < 10; i++) { CachedValue <double> result = strategy.Get(); Assert.AreEqual(0L, result.Version, "These calls should be cached"); await Task.Delay(TimeSpan.FromSeconds(wait.TotalSeconds / 5.0)); firstCacheDate = result.CachedDate; } await Task.Delay(wait); CachedValue <double> expiredResult = strategy.Get(); Assert.AreNotEqual(firstCacheDate, expiredResult.CachedDate, "This call should have expired after waiting for {0}", wait); }
public Protein(SkylineDataSchema dataSchema, IdentityPath identityPath) : base(dataSchema, identityPath) { _peptides = CachedValue.Create(dataSchema, () => DocNode.Children .Select(node => new Peptide(DataSchema, new IdentityPath(IdentityPath, node.Id))).ToArray()); _results = CachedValue.Create(dataSchema, MakeProteinResults); _proteinAbundances = CachedValue.Create(dataSchema, CalculateProteinAbundances); }
public Task <Cached <TValue> > Get(TKey key) { return(Task.Factory.StartNew(() => { var textKey = _keyFormatter(key); var result = _cache.Get(textKey) as Cached <TValue>; if (result != null) { if (!result.Value.IsFaulted && !result.Value.IsCanceled) { return result; } _cache.Remove(textKey); } var cacheItemValue = new CachedValue(_valueFactory, key, () => Touch(textKey)); var cacheItem = new CacheItem(textKey, cacheItemValue); var cacheItemPolicy = _policyProvider(new CacheExpirationSelector(key)).Policy; cacheItemPolicy.RemovedCallback = OnCacheItemRemoved; var added = _cache.Add(cacheItem, cacheItemPolicy); if (!added) { throw new InvalidOperationException($"The item was not added to the cache: {key}"); } return cacheItemValue; }, CancellationToken.None, TaskCreationOptions.HideScheduler, _scheduler)); }
async Task <T> ICacheStrategyAsync <T> .RetrieveAsync(CachedValue <T> existingCachedValue) { if (RetrieveCallback == null) { return(default(T)); } if (RetrieveErrorHandler == null) { return(await RetrieveCallback()); } else { try { return(await RetrieveCallback()); } catch (Exception x) { RetrievalErrorHandlerResult <T> result = RetrieveErrorHandler(x, existingCachedValue); if (result.IsErrorHandled) { return(result.FallbackResult); } else { throw; } } } }
public void CachedValue_HitsIncrement_Test() { var value = new CachedValue<string>("value", Expires.Never<string>()); Assert.AreEqual("value", value.Value); Assert.AreEqual("value", value.Value); Assert.AreEqual("value", value.Value); Assert.AreEqual(3, value.Hits); }
public void CachedValue_ExpiredStrategy_Works() { var value = new CachedValue<string>("value", Expires.Always<string>()); Assert.IsTrue(value.IsExpired); value = new CachedValue<string>("value", Expires.Never<string>()); Assert.IsFalse(value.IsExpired); }
public void Expires_Never_Test() { var strategy = Expires.Never<string>(); var value = new CachedValue<string>("example", strategy); Assert.IsFalse(value.IsExpired); Assert.IsFalse(value.IsExpired); }
public void Expires_Always_Test() { var strategy = Expires.Always<string>(); var value = new CachedValue<string>("example", strategy); Assert.IsTrue(value.IsExpired); Assert.IsTrue(value.IsExpired); }
/// <summary> /// Initializes a new instance of the <see cref="GenerationControllerBase"/> class. /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="reportQueueStatusService">The report queue status service.</param> public GenerationControllerBase( IControllerConfigurationBase configuration, IReportQueueStatusService reportQueueStatusService) { this._Configuration = configuration; this._DatabaseQueuePollInterval = new CachedValue<int>(() => this._Configuration.DatabaseQueuePollInterval); this._ReportQueueStatusService = reportQueueStatusService; }
private void AddNew(CachedValue nv) { nv.Next = head; nv.Prev = null; if (head != null) { head.Prev = nv; } else { tail = nv; } head = nv; }
public void Expires_Hits_Test() { var strategy = Expires.Hits<string>(1); var value = new CachedValue<string>("example", strategy); Assert.IsFalse(value.IsExpired); var unwrapped = value.Value; // increment the hits Assert.IsTrue(value.IsExpired); }
public void CachedValue_LastTouchedIncremented_Test() { var value = new CachedValue<string>("value", Expires.Never<string>()); var current = value.LastTouched; Thread.Sleep(TimeSpan.FromMilliseconds(100)); Assert.AreEqual("value", value.Value); Assert.AreNotEqual(current, value.LastTouched); }
public void Value_WhenInvalidatedBeforeHydrating_HydratesOnce() { var numberOfHydrations = 0; var cache = new CachedValue<int>(() => ++numberOfHydrations); cache.Invalidate(); Assert.That(cache.Value, Is.EqualTo(1)); Assert.That(numberOfHydrations, Is.EqualTo(1)); }
public void Expires_NextDay_Test() { var strategy = Expires.NextDay<string>(); var value = new CachedValue<string>("example", strategy); var secret = new PrivateObject(value); Assert.IsFalse(value.IsExpired); secret.SetProperty("Created", Stopwatch.GetTimestamp() - TimeSpan.TicksPerDay); Assert.IsTrue(value.IsExpired); }
public void Expires_At_Test() { var strategy = Expires.At<string>(DateTime.Now.AddHours(-1)); var value = new CachedValue<string>("example", strategy); Assert.IsTrue(value.IsExpired); strategy = Expires.At<string>(DateTime.Now.AddHours(1)); value = new CachedValue<string>("example", strategy); Assert.IsFalse(value.IsExpired); }
public void Value_WhenAccessedMultipleTimesWithoutInvalidating_HydratesOnlyOnce() { var numberOfHydrations = 0; var cache = new CachedValue<int>(() => ++numberOfHydrations); Assert.That(cache.Value, Is.EqualTo(1)); Assert.That(cache.Value, Is.EqualTo(1)); Assert.That(cache.Value, Is.EqualTo(1)); Assert.That(numberOfHydrations, Is.EqualTo(1)); }
public EndpointHealthNotifier(IHealthMonitorClient client, ITimeCoordinator timeCoordinator, EndpointDefinition definition, IHealthChecker healthChecker) { _client = client; _timeCoordinator = timeCoordinator; _definition = definition; _healthChecker = healthChecker; _cancelationTokenSource = new CancellationTokenSource(); _healthCheckInterval = new CachedValue<TimeSpan>(HealthCheckIntervalCacheDuration, GetHealthCheckIntervalAsync); _thread = new Thread(HealthLoop) { IsBackground = true, Name = "Health Check loop" }; _thread.Start(); }
public void Expires_Introspect_Test() { var strategy = Expires.Introspect<IntrospectionType>(); var value = new CachedValue<IntrospectionType>( new IntrospectionType { Expire = true }, strategy); Assert.IsTrue(value.IsExpired); strategy = Expires.Introspect<IntrospectionType>(); value = new CachedValue<IntrospectionType>( new IntrospectionType { Expire = false }, strategy); Assert.IsFalse(value.IsExpired); }
public BranchManager() { _currentBranch = new CachedValue<Branch>( () => _repositoryService.IsGitRepository ? new Branch(_repositoryService.Git.Execute(new SymbolicRef {Name="HEAD"})) : null ); _branches = new CachedValue<IEnumerable<Branch>>( () => _repositoryService.IsGitRepository ? _repositoryService.Git.Execute(new GetBranches()).Select(name => new Branch(name)).ToArray() : Enumerable.Empty<Branch>() ); }
private void BringToHead(CachedValue r) { if (r == head) { return; } r.Prev.Next = r.Next; if (r == tail) { tail = r.Prev; } else { r.Next.Prev = r.Prev; } r.Next = head; head.Prev = r; head = r; head.Prev = null; }
public TransitionResult(Transition transition, ResultFile resultFile) : base(transition, resultFile) { _chromInfo = CachedValue.Create(DataSchema, () => GetResultFile().FindChromInfo(transition.DocNode.Results)); }
public void Expires_TimeSpan_Test() { var strategy = Expires.TimeSpan<string>(TimeSpan.FromDays(-1)); var value = new CachedValue<string>("example", strategy); Assert.IsTrue(value.IsExpired); strategy = Expires.TimeSpan<string>(TimeSpan.FromHours(1)); value = new CachedValue<string>("example", strategy); Assert.IsFalse(value.IsExpired); }
public void Expires_When_Test() { var flag = false; var strategy = Expires.When<string>(() => flag); var value = new CachedValue<string>("example", strategy); Assert.IsFalse(value.IsExpired); flag = true; Assert.IsTrue(value.IsExpired); }
public void Expires_NotUsedIn_Test() { var strategy = Expires.NotUsedIn<string>(TimeSpan.FromMilliseconds(150)); var value = new CachedValue<string>("example", strategy); Assert.IsFalse(value.IsExpired); Thread.Sleep(TimeSpan.FromSeconds(1)); Assert.IsTrue(value.IsExpired); }
public Replicate(SkylineDataSchema dataSchema, int replicateIndex) : base(dataSchema) { ReplicateIndex = replicateIndex; _chromatogramSet = CachedValue.Create(DataSchema, FindChromatogramSet); }
/// <summary> /// Adds a cache entry for the item. /// </summary> private void CreateCacheEntry(Item item) { lock (m_cache) { CachedValue cachedValue = null; if (!m_cache.TryGetValue(item.Variable.NodeId, out cachedValue)) { m_cache[item.Variable.NodeId] = cachedValue = new CachedValue(item.Variable.NodeId); } cachedValue.AddRef(); item.CachedValue = cachedValue; } }
public void CachedValue_TimeStamp_IsInitialized() { var value = new CachedValue<string>("value", Expires.Never<string>(), true); Assert.IsTrue(DateTime.Now.Ticks >= value.Created); }
public PeptideResult(Peptide peptide, ResultFile file) : base(peptide, file) { _chromInfo = CachedValue.Create(DataSchema, () => ResultFile.FindChromInfo(peptide.DocNode.Results)); _quantificationResult = CachedValue.Create(DataSchema, GetQuantification); }
public void CachedValue_AlreadyExpired_Test() { var value = new CachedValue<string>("value", Expires.Never<string>(), true); Assert.IsTrue(value.IsExpired); }