/// <summary> /// Performs initialization when the adapter's node is set. /// This method is called each time the adapter is connected to its underlying node. /// Typically overridden by creators of DOM adapters.</summary> protected override void OnNodeSet() { base.OnNodeSet(); Box boxValue = DomNodeUtil.GetBox(DomNode, Schema.meshType.boundingBoxAttribute); if (boxValue.IsEmpty) m_boundingBox = new Cached<Box>(CalculateBoundingBox); // don't set value and force to compute else m_boundingBox = new Cached<Box>(CalculateBoundingBox, boxValue); // non-default value found, use it }
public void Value_RefreshesTheValueOnFirstRead() { var called = false; var temp = new Cached <int>(() => { called = true; return(-1); }, 1); var x = temp.Value; Assert.IsTrue(called); }
public WebV2RequestRepo(IWebProxy proxy, IBasicCredentials creds, AuthCodeRequiredDelegate onAuthCodeRequired) :base(creds) { HttpSettings.Proxy = proxy; Authent = new WebAuth(HttpSettings, creds, onAuthCodeRequired); _bannedShards = new Cached<List<ShardInfo>>(old => new List<ShardInfo>(), value => TimeSpan.FromMinutes(2)); _cachedShards = new Cached<Dictionary<ShardType, ShardInfo>>(old => new ShardInfoRequest(HttpSettings, Authent).MakeRequestAsync().Result.ToShardInfo(), value => TimeSpan.FromSeconds(ShardsExpiresInSec)); }
public CombinedFeedSource(IAmACommunityMember[] bloggers) { Bloggers = bloggers; var cached = new Cached <ISyndicationFeedSource>(TimeSpan.FromHours(1), new SystemClock(), LoadFeeds); _combinedFeedSource = new Lazy <Cached <ISyndicationFeedSource> >(() => cached, LazyThreadSafetyMode.PublicationOnly); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; HttpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("PlanetXamarin", $"{GetType().Assembly.GetName().Version}")); HttpClient.Timeout = TimeSpan.FromMinutes(1); }
public AttributeCollection(ReadOnlyArray <AttributeMetadata> tags) { _attributes = tags; if (tags.Length == 0) { _data = Cached.Array <OpenXmlSimpleType>(); } else { _data = new OpenXmlSimpleType[tags.Length]; } }
public IEnumerable <UserLockouts> GetPage(int page) { if (!IsInnitalized) { throw new InvalidOperationException("call RefreshData() first!"); } if (page > LastPage && !IsInnitalized) { throw new InvalidOperationException("invalid page"); } if (Cached.ContainsKey(page)) { var collection = Cached[page]; return(collection); } else { var list = new List <UserLockouts>(); _adapter.BeginDBAccess(); if (IsDataFiltered) { if (string.IsNullOrEmpty(FilterString) || FilterParam == null) { throw new InvalidOperationException("filter is not set"); } var collection = _adapter.GetData(FilterString, FilterParam, (page - 1) * _adapter.RecordPerPage, _adapter.RecordPerPage, out int total); //bc of lazy or smt if we dont clone the UserLockouts when endDB is called our UserLockouts will be lost foreach (var item in collection) { list.Add(item.Clone()); } Cached.Add(page, list); RecordCount = total; LastPage = Helper.HelperClass.CalculatePage(RecordCount, _adapter.RecordPerPage); } else { var collection = _adapter.GetData((page - 1) * _adapter.RecordPerPage, _adapter.RecordPerPage, out int total); foreach (var item in collection) { list.Add(item.Clone()); } Cached.Add(page, list); RecordCount = total; LastPage = Helper.HelperClass.CalculatePage(RecordCount, _adapter.RecordPerPage); } _adapter.EndDBAccess(); return(list); } }
private bool MaybeReadAllFromCache(JsonOperationContext ctx, AggressiveCacheOptions options) { DisposeCache(); bool readAllFromCache = options != null; var trackChanges = readAllFromCache && options.Mode == AggressiveCacheMode.TrackChanges; for (int i = 0; i < _commands.Count; i++) { var command = _commands[i]; var cacheKey = GetCacheKey(command, out _); var cachedItem = _httpCache.Get(ctx, cacheKey, out var changeVector, out var cached); if (cachedItem.Item == null) { using (cachedItem) { readAllFromCache = false; continue; } } if (readAllFromCache && (trackChanges && cachedItem.MightHaveBeenModified || cachedItem.Age > options.Duration || command.CanCacheAggressively == false)) { readAllFromCache = false; } command.Headers[Constants.Headers.IfNoneMatch] = $"\"{changeVector}\""; _cached ??= new Cached(_commands.Count); _cached.Values[i] = (cachedItem, cached); } if (readAllFromCache) { using (_cached) { Result = new List <GetResponse>(_commands.Count); for (int i = 0; i < _commands.Count; i++) { // ReSharper disable once PossibleNullReferenceException var(_, cached) = _cached.Values[i]; Result.Add(new GetResponse { Result = cached?.Clone(ctx), StatusCode = HttpStatusCode.NotModified }); } } _cached = null; } return(readAllFromCache); }
public void Expire_MarksTheValueAsExpired() { var called = 0; var temp = new Cached <int>(() => { called++; return(-1); }, 1000); var x = temp.Value; temp.Expire(); Assert.IsTrue(called == 1); }
public YadWebRequestRepo(IWebProxy proxy, IBasicCredentials creds) { ServicePointManager.DefaultConnectionLimit = int.MaxValue; HttpSettings.Proxy = proxy; Authent = new YadWebAuth(HttpSettings, creds); CachedSharedList = new Cached <Dictionary <string, IEnumerable <PublicLinkInfo> > >(old => { var res = GetShareListInner().Result; return(res); }, value => TimeSpan.FromSeconds(30)); }
public void SetRetry(TResource resource, long retry) { lock (_sharedResourceTimes) { if (!_sharedResourceTimes.TryGetValue(resource, out Cached <long> sharedRetry)) { _sharedResourceTimes.Add(resource, new Cached <long>(retry, DateTimeOffset.UtcNow)); } else if (sharedRetry <= retry) { _sharedResourceTimes[resource] = new Cached <long>(retry, DateTimeOffset.UtcNow); } } }
public SessionKeys( ISymbols mrzInfo, IReader reader ) { _selectedMrtdApplication = new Cached( new ExecutedCommandApdu( new SelectMRTDApplicationCommandApdu(), reader ) ); var kIfd = new Cached(new Kifd()); var rndIc = new Cached(new RNDic(reader)); var rndIfd = new Cached(new RNDifd()); var externalAuthRespData = new ResponseApduData( new Cached( new ExecutedCommandApdu( new ExternalAuthenticateCommandApdu( new ExternalAuthenticateCommandData( mrzInfo, rndIc, rndIfd, kIfd ) ), reader ) ) ); var kSeedIc = new KseedIc( kIfd, new Kic( new R( externalAuthRespData, mrzInfo ) ) ); _cachedKSenc = new Cached(new KSenc(kSeedIc)); _cachedKSmac = new Cached(new KSmac(kSeedIc)); _ssc = new Cached( new SSC( rndIc, rndIfd ) ); }
public void SetRetry(TResource resource, string bucket, long retry) { lock (_userResourceTimes) { var resourceBucket = new ResourceBucket(resource, bucket); if (!_userResourceTimes.TryGetValue(resourceBucket, out Cached <long> sharedRetryAfter)) { _userResourceTimes.Add(resourceBucket, new Cached <long>(retry, DateTimeOffset.UtcNow)); } else if (sharedRetryAfter <= retry) { _userResourceTimes[resourceBucket] = new Cached <long>(retry, DateTimeOffset.UtcNow); } } }
/// <summary> /// Binds the compiled expression with the specified binding context and options. /// </summary> /// <param name="binder">The binding context used to bind the expression.</param> /// <param name="options">The options used to bind the expression.</param> /// <returns>The bound expression.</returns> public IBoundExpression Bind(IBindingContext binder, BoundExpressionOptions options) { if (binder == null) { binder = new ExpressionContext(); } if (options == null) { options = new BoundExpressionOptions(); } options.Freeze(); return(Cached.GetOrCreateBoundExpression(binder, options)); }
/// <summary> /// Performs initialization when the adapter's node is set. /// This method is called each time the adapter is connected to its underlying node. /// Typically overridden by creators of DOM adapters.</summary> protected override void OnNodeSet() { base.OnNodeSet(); Box boxValue = DomNodeUtil.GetBox(DomNode, Schema.meshType.boundingBoxAttribute); if (boxValue.IsEmpty) { m_boundingBox = new Cached <Box>(CalculateBoundingBox); // don't set value and force to compute } else { m_boundingBox = new Cached <Box>(CalculateBoundingBox, boxValue); // non-default value found, use it } }
public void ValidateExpectedParticles() { var exclude = new HashSet <Type> { typeof(OpenXmlUnknownElement), typeof(OpenXmlMiscNode), }; var elements = typeof(OpenXmlElement).GetTypeInfo().Assembly.GetTypes() .Where(t => !t.GetTypeInfo().IsAbstract&& typeof(OpenXmlElement).IsAssignableFrom(t)) .Where(t => !exclude.Contains(t)); var constraints = new Dictionary <Type, VersionCollection <ParticleConstraint> >(); foreach (var version in FileFormatVersionExtensions.AllVersions) { foreach (var type in elements) { var constructor = type.GetConstructor(Cached.Array <Type>()); if (constructor is not null) { var element = (OpenXmlElement)Activator.CreateInstance(type); if (version.AtLeast(element.InitialVersion)) { var constraint = element.Metadata.Particle.Particle?.Build(version); if (constraint is not null) { if (constraints.TryGetValue(type, out var current)) { current.Add(version, constraint); } else { constraints.Add(type, new VersionCollection <ParticleConstraint> { { version, constraint } }); } } } } } } AssertEqual(constraints); }
private void LoadRecord(FileInfo file) { if (Cached.ContainsKey(Path.GetFileNameWithoutExtension(file.Name))) { return; } var record = InvertJsonExtensions.DeserializeObject(For, JSON.Parse(File.ReadAllText(file.FullName))) as IDataRecord; if (record != null) { record.Repository = this.Repository; Cached.Add(record.Identifier, record); record.Changed = false; } }
public static IEnumerable <OpenXmlElement> Descendants(this OpenXmlElement element, FileFormatVersions version = FileFormatVersions.Office2007, TraversalOptions options = TraversalOptions.None) { if (element is null) { return(Cached.Array <OpenXmlElement>()); } if ((options & TraversalOptions.SelectAlternateContent) == TraversalOptions.SelectAlternateContent) { return(ValidatingTraverse(element, new MCContext(false), version)); } else { return(element.Descendants()); } }
public void Value_RefreshesTheValueIfExpired() { var called = 0; var temp = new Cached <int>(() => { called++; return(-1); }, 1); var x = temp.Value; Thread.Sleep(10); x = temp.Value; Assert.IsTrue(called > 1); }
public async Task CachedResourceScript() { var tcs = new TaskCompletionSource <object> (); var src = "http://this.url.cant.possibly.actually.exist/dummy/script.js"; WebView.Cache.Add(src, Cached.Resource("window.dummyScriptLoaded = true", "application/javascript")); WebView.Loaded += async delegate { await WebView.RunScriptAsync(window => { Assert.IsTrue(((bool?)window.dummyScriptLoaded).GetValueOrDefault(), "#2"); }); tcs.TrySetResult(null); }; LoadHtml("<html><head><script src=\"" + src + "\"></script></head><body></body></html>"); await tcs.Task; }
/// <inheritdoc /> public override int GetHashCode() { unchecked { int hashCode = ChatId is not null?ChatId.GetHashCode() : 0; hashCode = (hashCode * 397) ^ (Phone is not null ? Phone.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (QuotedMessageId is not null ? QuotedMessageId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Body is not null ? Body.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (FileName is not null ? FileName.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Caption is not null ? Caption.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (MentionedPhones is not null ? MentionedPhones.GetHashCode() : 0); hashCode = (hashCode * 397) ^ Cached.GetHashCode(); return(hashCode); } }
public void Expire_WillForceTheValueToBeRefreshed() { var called = 0; var temp = new Cached <int>(() => { called++; return(-1); }, 1000); var x = temp.Value; temp.Expire(); x = temp.Value; Assert.IsTrue(called == 2); }
public void TestCache <T>(int min, int max) where T : IFunction, new() { var function = new T(); var cachedFunction = new Cached <T>(); var random = new Random(); for (var i = 0; i < 4000; ++i) { var input = Enumerable.Range(0, 100).Select(_ => random.Next(min, max)).ToArray(); var expected = function.Compute(input); var result = cachedFunction.Compute(input); var cachedResult = cachedFunction.Compute(input); Assert.AreEqual(expected, cachedResult); Assert.AreEqual(result, cachedResult); } }
/// <summary> /// Performs custom actions on NodeSet events. /// Called after successfully attaching to internal DOM object.</summary> protected override void OnNodeSet() { base.OnNodeSet(); // Initialize scale to (1, 1, 1) if missing DomNode.SetAttributeIfDefault(Schema.nodeType.scaleAttribute, new Vec3F(1, 1, 1)); m_rotation = DomNode.GetChild(Schema.nodeType.rotEulChild); m_rotationAxis = DomNode.GetChild(Schema.nodeType.rotAxisEulChild); Transform = TransformUtils.CalcTransform(this); Box boxValue = DomNodeUtil.GetBox(DomNode, Schema.nodeType.boundingBoxAttribute); if (boxValue.IsEmpty) m_boundingBox = new Cached<Box>(CalculateBoundingBox); // don't set value and force to compute else m_boundingBox = new Cached<Box>(CalculateBoundingBox, boxValue); // non-default value found, use it }
public void Import(ExportedRecord record) { LoadRecordsIntoCache(); if (Cached.ContainsKey(record.Identifier)) { InvertJsonExtensions.DeserializeExistingObject(Cached[record.Identifier], JSON.Parse(record.Data).AsObject); } else { var dataRecord = InvertJsonExtensions.DeserializeObject(For, JSON.Parse(record.Data)) as IDataRecord; if (dataRecord != null) { Add(dataRecord); } } }
internal Actor(World world, string name, TypeDictionary initDict) { var init = new ActorInitializer(this, initDict); World = world; ActorID = world.NextAID(); if (initDict.Contains <OwnerInit>()) { Owner = init.Get <OwnerInit, Player>(); } occupySpace = Lazy.New(() => TraitOrDefault <IOccupySpace>()); if (name != null) { if (!Rules.Info.ContainsKey(name.ToLowerInvariant())) { throw new NotImplementedException("No rules definition for unit {0}".F(name.ToLowerInvariant())); } Info = Rules.Info[name.ToLowerInvariant()]; foreach (var trait in Info.TraitsInConstructOrder()) { AddTrait(trait.Create(init)); } } facing = Lazy.New(() => TraitOrDefault <IFacing>()); size = Lazy.New(() => { var si = Info.Traits.GetOrDefault <SelectableInfo>(); if (si != null && si.Bounds != null) { return(new int2(si.Bounds[0], si.Bounds[1])); } return(TraitsImplementing <IAutoSelectionSize>().Select(x => x.SelectionSize(this)).FirstOrDefault()); }); applyIRender = (x, wr) => x.Render(this, wr); applyRenderModifier = (m, p, wr) => p.ModifyRender(this, wr, m); Bounds = Cached.New(() => CalculateBounds(false)); ExtendedBounds = Cached.New(() => CalculateBounds(true)); }
public void Get_UsesTheSuppliedFunctionInsteadOfTheDefaultOne() { var called = 0; var temp = new Cached <int>(() => { called += 10; return(-1); }, 1); var x = temp.Get(() => { called++; return(-1); }); Assert.IsTrue(called == 1); }
public void should_honor_ttl() { int hitCount = 0; _cachedString = new Cached<string>(); for (int i = 0; i < 10; i++) { _cachedString.Get("key", () => { hitCount++; return null; }, TimeSpan.FromMilliseconds(300)); Thread.Sleep(100); } hitCount.Should().BeInRange(3, 6); }
public virtual async Task <Cached <T> > GetFromCacheAsync <T>(Func <Task <T> > serviceCall, Func <Cached <T>, Exception, Task> onUpdate) where T : Cacheable { var cachedResponse = await cacheManager.GetAsync <T>(); Cached <T> data; if (cachedResponse != null) { data = new Cached <T>(cachedResponse.Object, cachedResponse.Updated.Value); } else { data = new Cached <T>(); } GetFromService(serviceCall, onUpdate, data); return(await Task.FromResult(data)); }
public void SameCacheKey_DoesNotRefresh() { // arrange int timesFetched = 0; var cached = new Cached <int>( getCacheKey: () => "static", fetchNew: () => ++ timesFetched ); // act _ = cached.Value; _ = cached.Value; int lastValue = cached.Value; // assert Assert.AreEqual(1, timesFetched, "The value was fetched more than once."); Assert.AreEqual(lastValue, timesFetched, "The cached value doesn't match the expected value."); }
public void Value_RefreshesTheValueAtEveryOneMsReadIfTtlWasSuppliedAsZero() { var called = 0; var temp = new Cached <int>(() => { called++; return(-1); }, 0); var x = temp.Value; Thread.Sleep(1); x = temp.Value; Thread.Sleep(1); x = temp.Value; Assert.AreEqual(3, called); }
/********* ** Public methods *********/ /// <summary>Get the cached mod data.</summary> /// <param name="site">The mod site to search.</param> /// <param name="id">The mod's unique ID within the <paramref name="site"/>.</param> /// <param name="mod">The fetched mod.</param> /// <param name="markRequested">Whether to update the mod's 'last requested' date.</param> public bool TryGetMod(ModSiteKey site, string id, out Cached <IModPage> mod, bool markRequested = true) { // get mod if (!this.Mods.TryGetValue(this.GetKey(site, id), out var cachedMod)) { mod = null; return(false); } // bump 'last requested' if (markRequested) { cachedMod.LastRequested = DateTimeOffset.UtcNow; } mod = cachedMod; return(true); }
public void Add(IDataRecord o) { if (Removed.Contains(o.Identifier)) { Removed.Remove(o.Identifier); } o.Changed = true; if (string.IsNullOrEmpty(o.Identifier)) { o.Identifier = Guid.NewGuid().ToString(); } o.Repository = this.Repository; if (!Cached.ContainsKey(o.Identifier)) { Cached.Add(o.Identifier, o); Repository.Signal <IDataRecordInserted>(_ => _.RecordInserted(o)); } }
public void should_honor_ttl() { int hitCount = 0; _cachedString = new Cached <string>(); for (int i = 0; i < 100; i++) { _cachedString.Get("key", () => { hitCount++; return(null); }, TimeSpan.FromMilliseconds(300)); Thread.Sleep(10); } hitCount.Should().BeInRange(3, 6); }
/// <summary> /// Performs initialization when the adapter's node is set. /// This method is called each time the adapter is connected to its underlying node. /// Typically overridden by creators of DOM adapters.</summary> protected override void OnNodeSet() { base.OnNodeSet(); m_boundingBox = new Cached<Box>(CalculateBoundingBox); }
public ShowCreatePoolWindow(Cached<IList<NodeAgentSku>> nodeAgentSkus) { this.NodeAgentSkus = nodeAgentSkus; }
public UserService() { Cached = new Cached(); }
public void SetUp() { _cachedString = new Cached<string>(); _worker = new Worker(); }
protected InvoicesBaseController() { _cachedInvoice = new Cached<Invoice>(() => Cache, () => new Invoice()); _cachedProducts = new Cached<IEnumerable<Product>>(() => Cache, () => Repository.GetAllProducts()) {Name = "Products"}; }
public Model() { Cache = Cached.New(() => new ModelCache(this)); }
/// <summary> /// Performs initialization when the adapter's node is set. /// This method is called each time the adapter is connected to its underlying node. /// Typically overridden by creators of DOM adapters.</summary> protected override void OnNodeSet() { base.OnNodeSet(); // get trans, scale, and rot. foreach (DomNode domNode in this.DomNode.GetChildList(Schema.node.scaleChild)) { m_scale = Tools.GetVector3(domNode, Schema.TargetableFloat3.Attribute); break; } foreach (DomNode domNode in this.DomNode.GetChildList(Schema.node.translateChild)) { m_translation = Tools.GetVector3(domNode, Schema.TargetableFloat3.Attribute); break; } const float PiOver180 = (float)(Math.PI / 180.0f); foreach (DomNode node in DomNode.GetChildList(Schema.node.rotateChild)) { double[] arr = (double[])node.GetAttribute(Schema.rotate.Attribute); float angle = (float)arr[3] * PiOver180; string sid = node.GetAttribute(Schema.rotate.sidAttribute) as string; if (string.IsNullOrEmpty(sid)) continue; if (sid == "rotateX") m_rotation.X = angle; else if (sid == "rotateY") m_rotation.Y = angle; else if (sid == "rotateZ") m_rotation.Z = angle; } Matrix4F M = new Matrix4F(); Matrix4F temp = new Matrix4F(); temp.Scale(Scale); M.Mul(M, temp); if (m_rotation.X != 0) { temp.RotX(m_rotation.X); M.Mul(M, temp); } if (m_rotation.Y != 0) { temp.RotY(m_rotation.Y); M.Mul(M, temp); } if (m_rotation.Z != 0) { temp.RotZ(m_rotation.Z); M.Mul(M, temp); } temp.Set(Translation); M.Mul(M, temp); Transform = M; m_boundingBox = new Cached<Box>(CalculateBoundingBox); Visible = true; }
public CreatePoolViewModel(IDataProvider batchService, Cached<IList<NodeAgentSku>> nodeAgentSkus) { this.batchService = batchService; // pre-populate the available VM sizes this.AvailableVirtualMachineSizes = Common.SupportedVirtualMachineSizesList; this.AvailableNodeAgentSkus = new List<NodeAgentSku>(); //Initially empty Task task = nodeAgentSkus.GetDataAsync().ContinueWith( (t) => this.AvailableNodeAgentSkus = new ReadOnlyCollection<NodeAgentSku>(t.Result)); AsyncOperationTracker.Instance.AddTrackedInternalOperation(task); this.Version = "latest"; //Default to latest this.AvailableOSVersions = new List<string> { "*" }; this.TargetDedicated = 1; this.MaxTasksPerComputeNode = 1; this.IsBusy = false; this.HasVirtualMachineConfiguration = false; this.AvailableOSFamilies = new List<string>(Common.SupportedOSFamilyDictionary.Keys); }