Пример #1
0
        public static double MemoizeDouble <T>(Func <T, double> function, T arg, int capacity = 100)
        {
            Dictionary <int, double> dictionary;

            if (!_values.ContainsKey(function.GetHashCode()))
            {
                _values[function.GetHashCode()] = dictionary = dictionary <int, double>(capacity);
            }
            else
            {
                dictionary = _values[function.GetHashCode()];
            }
            double integer;
            int    hashCode = arg.GetHashCode();

            if (dictionary.ContainsKey(hashCode))
            {
                return(dictionary[hashCode]);
            }
            else
            {
                dictionary[hashCode] = integer = function(arg);
            }
            return(integer);
        }
Пример #2
0
        public static void RunDelegate5()
        {
            NSucceedLog.Enabled = true;
            Func <string, string, string> action = NDelegate.RandomDomain(builder => builder.UseFileCompile()).UnsafeFunc <string, string, string>(@"
                            string result = arg1 +"" ""+ arg2;
                            Console.WriteLine(result);
                            return result;");

            Func <string, string, string> action2 = NDelegate.RandomDomain(builder => builder.UseFileCompile()).UnsafeFunc <string, string, string>(@"
                            string result = arg1 + "" "" + arg2 + ""1"";
                            Console.WriteLine(result);
                            return result;");

            Func <string, string, string> action3 = (s1, s2) => s1 + s2;


            string result = action("Hello", "World1!");

            Assert.Equal("Hello World1!", result);


            Assert.NotEqual(action3.GetHashCode(), action2.GetHashCode());
            Assert.NotEqual(action.Method.GetHashCode(), action2.Method.GetHashCode());
            Assert.Equal(action.GetHashCode(), action2.GetHashCode());
        }
 /// <summary>
 /// Получить хэш код источника.
 /// </summary>
 /// <returns>Хэш код.</returns>
 public override int GetHashCode()
 {
     unchecked
     {
         return((base.GetHashCode() * 397) ^ (_getPart != null ? _getPart.GetHashCode() : 0));
     }
 }
Пример #4
0
        public override int GetHashCode()
        {
            unchecked // Overflow is fine, just wrap
            {
                int hashCode = 41;

                if (Target != null)
                {
                    hashCode = hashCode * 59 + Target.GetHashCode();
                }

                if (Func != null)
                {
                    hashCode = hashCode * 59 + Func.GetHashCode();
                }

                if (FuncMode != null)
                {
                    hashCode = hashCode * 59 + FuncMode.GetHashCode();
                }

                if (Enabled != null)
                {
                    hashCode = hashCode * 59 + Enabled.GetHashCode();
                }

                return(hashCode);
            }
        }
Пример #5
0
        private IEnumerable <T> GetGameList <T>(Func <IBoardGameManager, string, IEnumerable <T> > listDelegate, string username, int?bestWith = null, bool hideParentlessExpansions = false) where T : IHasBoardGame
        {
            var list = new List <T>();

            if (string.IsNullOrWhiteSpace(username))
            {
                username = "******";
            }
            foreach (var singleName in username.Split(','))
            {
                var cacheKey = $"{singleName}|{listDelegate.GetHashCode()}";
                var allGames = _cache.GetOrCreate(cacheKey, entry =>
                {
                    entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
                    return(listDelegate.Invoke(_boardGameManager, singleName));
                }).ToList();
                var gamesToAdd = allGames.ToList().AsEnumerable();

                // best-with filter
                if (bestWith.HasValue)
                {
                    gamesToAdd = gamesToAdd.Where(hbg => hbg.BoardGame.IsExpansion || hbg.BoardGame.IsBestWith(bestWith.Value)).ToList();
                }

                if (hideParentlessExpansions)
                {
                    // remove parentless expansions
                    var parentfulExpansionIds = gamesToAdd.Where(bg => !bg.BoardGame.IsExpansion).SelectMany(bg => bg.BoardGame.ExpansionIds).ToList();
                    gamesToAdd = gamesToAdd.Where(bg => !bg.BoardGame.IsExpansion || parentfulExpansionIds.Contains(bg.BoardGame.Id)).ToList();
                }

                list.AddRange(gamesToAdd);
            }
            return(list);
        }
Пример #6
0
 public List <Result> GetListByPrimaryKeys <Result>(Func <T, long?> action) where Result : class, new()
 {
     {
         string key = "GetListById" + typeof(Result) + action.GetHashCode().ToString();
         return(GetListByPrimaryKeys <Result, long?>(action, key));
     }
 }
Пример #7
0
    /// <summary>
    /// 获得FieldInfo与指定Attribute映射
    /// </summary>
    /// <typeparam name="A">属性</typeparam>
    /// <param name="_type">类型</param>
    /// <param name="_condition">过渡条件</param>
    /// <returns>FieldInfo属性映射字典</returns>
    public static Dictionary <FieldInfo, A> GetFieldInfoAttribute <A>(this Type _type, Func <FieldInfo, bool> _condition)
        where A : Attribute
    {
        int tKey = _type.GetHashCode();
        int aKey = typeof(A).GetHashCode();
        int cKey = _condition == null ? 0 : _condition.GetHashCode();

        if (!msFieldInfoAttributeDictionaryMaping.ContainsKey(tKey))
        {
            msFieldInfoAttributeDictionaryMaping.Add(tKey, new Dictionary <int, Dictionary <int, object> >());
        }
        if (!msFieldInfoAttributeDictionaryMaping[tKey].ContainsKey(aKey))
        {
            msFieldInfoAttributeDictionaryMaping[tKey].Add(aKey, new Dictionary <int, object>());
        }
        if (!msFieldInfoAttributeDictionaryMaping[tKey][aKey].ContainsKey(cKey))
        {
            Dictionary <FieldInfo, A> dic = new Dictionary <FieldInfo, A>();
            foreach (FieldInfo f in _type.GetFields())
            {
                if (_condition == null || _condition(f))
                {
                    dic.Add(f, f.GetFirstAttribute <A>());
                }
            }
            msFieldInfoAttributeDictionaryMaping[tKey][aKey].Add(cKey, dic);
        }
        return((Dictionary <FieldInfo, A>)msFieldInfoAttributeDictionaryMaping[tKey][aKey][cKey]);
    }
Пример #8
0
        public override int GetHashCode()
        {
            int hash = 17;

            hash = hash * 23 + block.GetHashCode();
            return(hash + base.GetHashCode());
        }
Пример #9
0
    public static T GetFromCache <T>(Func <T> action)
    {
        long      code = action.GetHashCode();
        CacheItem item;

        if (_cachedResults.TryGetValue(code, out item))
        {
            if (item.LastUpdateTime.AddMinutes(CacheTime) >= DateTime.Now)
            {
                return((T)_cachedResults[code].Result);
            }
        }
        T         result  = action();
        CacheItem newItem = new CacheItem
        {
            LastUpdateTime = DateTime.Now,
            Result         = result
        };

        if (item == null)
        {
            _cachedResults.Add(code, newItem);
        }
        else
        {
            _cachedResults[code] = newItem;
        }
        return(result);
    }
Пример #10
0
        /// <summary>
        /// Serves as the default hash function.
        /// NOT thread safe.
        /// </summary>
        /// <returns>A hash code for the current object.</returns>
        public override int GetHashCode()
        {
            var hashCode = instance.GetHashCode() ^
                           supplier.GetHashCode();

            return(hashCode);
        }
Пример #11
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (StepMs != 0L)
            {
                hash ^= StepMs.GetHashCode();
            }
            if (Func.Length != 0)
            {
                hash ^= Func.GetHashCode();
            }
            if (StartMs != 0L)
            {
                hash ^= StartMs.GetHashCode();
            }
            if (EndMs != 0L)
            {
                hash ^= EndMs.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Пример #12
0
 public override int GetHashCode()
 {
     unchecked
     {
         return(((execute?.GetHashCode() ?? 0) * 397) ^ (canExecute?.GetHashCode() ?? 0));
     }
 }
Пример #13
0
        /// <summary>
        /// Create time series based on lambda, with lambda being executed once for
        /// every call to the indexer method. Use this for leight-weight lambdas.
        /// </summary>
        /// <param name="lambda">lambda, taking bars back as parameter and returning time series value</param>
        /// <param name="parentId">cache id used to identify functor</param>
        /// <param name="memberName">caller's member name, optional</param>
        /// <param name="lineNumber">caller line number, optional</param>
        /// <returns>lambda time series</returns>
        public static ITimeSeries <double> Lambda(Func <int, double> lambda,
                                                  CacheId parentId = null, [CallerMemberName] string memberName = "", [CallerLineNumber] int lineNumber = 0)
        {
            // NOTE:
            // this can be instantiated without parent cache id. As we don't have any data series
            // to go from, this will blow up when running multiple instances in the optimizer
            // a possible idea to fix this, would be to add the thread id... food for thought.

#if false
            // CAUTION:
            // lambda.GetHashCode() might not work w/ .Net Core
            // there are alternatives, see here:
            // https://stackoverflow.com/questions/283537/most-efficient-way-to-test-equality-of-lambda-expressions
            // however, we might not need to hash the lambda, as it is reasonably safe to assume
            // that for a different lambda, the call stack would also be different

            var cacheId = new CacheId(parentId, memberName, lineNumber,
                                      lambda.GetHashCode());
#else
            var cacheId = new CacheId(parentId, memberName, lineNumber);
#endif

            var functor = Cache <FunctorLambda> .GetData(
                cacheId,
                () => new FunctorLambda(lambda));

            return(functor);
        }
Пример #14
0
                public override int GetHashCode()
                {
                    int hash = 1;

                    if (FileIndex != 0)
                    {
                        hash ^= FileIndex.GetHashCode();
                    }
                    if (Line != 0)
                    {
                        hash ^= Line.GetHashCode();
                    }
                    if (Col != 0)
                    {
                        hash ^= Col.GetHashCode();
                    }
                    if (Func.Length != 0)
                    {
                        hash ^= Func.GetHashCode();
                    }
                    if (Code.Length != 0)
                    {
                        hash ^= Code.GetHashCode();
                    }
                    if (_unknownFields != null)
                    {
                        hash ^= _unknownFields.GetHashCode();
                    }
                    return(hash);
                }
Пример #15
0
        public static void Section(ref Vector2 position, float width, Func <Vector2, float, float> drawerFunc, string header = null, int id = 0)
        {
            bool hasHeader = !header.NullOrEmpty();

            id = id != 0 ? id : drawerFunc.GetHashCode();

            // header
            if (hasHeader)
            {
                Rect headerRect = new Rect(position.x, position.y, width, SectionHeaderHeight);
                Widgets_Labels.Label(headerRect, header, TextAnchor.LowerLeft, GameFont.Tiny, margin: 3 * Margin);
                position.y += SectionHeaderHeight;
            }

            // draw content
            Rect contentRect = new Rect(
                position.x,
                position.y,
                width,
                GetHeight(id) + 2 * Margin);

            // NOTE: we're updating height _after_ drawing, so the background is technically always one frame behind.
            GUI.DrawTexture(contentRect, Resources.SlightlyDarkBackground);
            var height = drawerFunc(position + new Vector2(Margin, Margin), width - 2 * Margin);

            position.y  += height + 3 * Margin;
            _heights[id] = height;
        }
Пример #16
0
    public static T GetFromCache <T>(Func <T> action)
    {
        long code = action.GetHashCode();

        if (!_cachedResults.ContainsKey(code))
        {
            lock (_cachedResults)
            {
                if (!_cachedResults.ContainsKey(code))
                {
                    _cachedResults.Add(code, new CacheItem {
                        LastUpdateTime = DateTime.MinValue
                    });
                }
            }
        }
        CacheItem item = _cachedResults[code];

        if (item.LastUpdateTime.AddMinutes(CacheTime) >= DateTime.Now)
        {
            return((T)item.Result);
        }
        T result = action();

        _cachedResults[code] = new CacheItem
        {
            LastUpdateTime = DateTime.Now,
            Result         = result
        };
        return(result);
    }
Пример #17
0
 public override int GetHashCode()
 {
     unchecked
     {
         return(((int)DbType * 397) ^ (Value != null ? Value.GetHashCode() : 0));
     }
 }
Пример #18
0
 /// <summary>
 /// Froms the svg stream.
 /// </summary>
 /// <returns>The svg stream.</returns>
 /// <param name="streamFunc">Stream func.</param>
 /// <param name="width">Width.</param>
 /// <param name="height">Height.</param>
 /// <param name="color">Color.</param>
 /// <param name="key">Key.</param>
 public static ImageSource FromSvgStream(Func <Stream> streamFunc, double width, double height, Color color, string key = null)
 {
     key = key ?? streamFunc.GetHashCode().ToString();
     return(new SvgImageSource {
         StreamFunc = token => Task.Run(streamFunc), Width = width, Height = height, Color = color
     });
 }
Пример #19
0
        /// <summary>
        /// Get the hash code for this key
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            int h;

            if (IsGeneric)
            {
                // And the contract for generic instances does not depend on the column spec
                h = DataItemType?.GetHashCode() ?? 0;
            }
            else
            {
                // For dynamic types the only things that can affect the mapping are the column mapping, if any,
                // and the final DatabaseTableSettings (which is included below anyway), but not the item type per se.
                h = DynamicColumnSpec?.GetHashCode() ?? 0;
            }

            h ^= DatabaseTableSettings.GetHashCode();

            // Save the time of hashing these if we know they're at their default values (0 for hash of all default is fine)
            if (HasMapperColumnsMapping)
            {
                h ^= (ColumnName?.GetHashCode() ?? 0) ^
                     (ColumnDataDirection?.GetHashCode() ?? 0) ^
                     (IgnoreColumn?.GetHashCode() ?? 0);
            }

            return(h);
        }
Пример #20
0
        public override int GetHashCode()
        {
            int prime  = 31;
            int result = 1;

            result = prime * result + ((_filter == null) ? 0 : _filter.GetHashCode());
            return(result);
        }
Пример #21
0
 public override int GetHashCode()
 {
     unchecked {
         var lt = (_listTransformation != null ? _listTransformation.GetHashCode() : 0);
         var it = (_itemTransformation != null ? _itemTransformation.GetHashCode() : 0);
         return((lt * 397) ^ (it * 17));
     }
 }
Пример #22
0
 /// <summary>
 /// HashCode
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public int GetHashCode(T obj)
 {
     if (_equailty != null)
     {
         return(_equailty.GetHashCode());
     }
     return(0);
 }
Пример #23
0
        public override int GetHashCode()
        {
            int prime  = 31;
            int result = 1;

            result = prime * result + ((_comparator == null) ? 0 : _comparator.GetHashCode());
            return(result);
        }
Пример #24
0
            public TSingleTarget Using <T>(Func <TSingleTarget, T> usingSelector, out Key <T> key)
            {
                TSingleTarget self = (TSingleTarget)(ISingleTargeter <TNode>) this;

                key = new Key <T>(usingSelector.GetHashCode());//TODO: another way to generate a key
                this.dictionary.Add(key, (target) => usingSelector(target));
                return(self);
            }
Пример #25
0
        public long GetServiceProviderHashCode()
        {
            if (!_serviceProviderHashCode.HasValue)
            {
                _serviceProviderHashCode = _bulkInsertEngineFactory?.GetHashCode() ?? 0L;
            }

            return(_serviceProviderHashCode.Value);
        }
Пример #26
0
        public long GetServiceProviderHashCode()
        {
            if (!_serviceProviderHashCode.HasValue)
            {
                _serviceProviderHashCode = _auditEntityHandlerFactory?.GetHashCode() ?? 0L;
            }

            return(_serviceProviderHashCode.Value);
        }
Пример #27
0
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = base.GetHashCode();
         hashCode = (hashCode * 397) ^ _componentType.GetHashCode();
         hashCode = (hashCode * 397) ^ _getterFunc.GetHashCode();
         return(hashCode);
     }
 }
Пример #28
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (mInstanceProvider != null ? mInstanceProvider.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (mMethod != null ? mMethod.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Procedure != null ? Procedure.GetHashCode() : 0);
         return(hashCode);
     }
 }
Пример #29
0
        /// <summary>
        /// 用于 <see cref="ProductionData&lt;T&gt;"/> 类型的哈希函数。
        /// </summary>
        /// <returns>当前 <see cref="ProductionData&lt;T&gt;"/> 的哈希代码。</returns>
        public override int GetHashCode()
        {
            int hashCode = head ^ (bodySize << 5);

            if (action != null)
            {
                hashCode ^= action.GetHashCode();
            }
            return(hashCode);
        }
Пример #30
0
 public override int GetHashCode()
 {
     unchecked {
         var hashCode = (int)CType;
         hashCode = (hashCode * 397) ^ (_staticList?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (_enumParts?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (ThisPart?.GetHashCode() ?? 0);
         return(hashCode);
     }
 }
Пример #31
0
		public LazyResponses CallOnce(Func<LazyResponses> clientUsage, int? k = null)
		{
			var key = k ?? clientUsage.GetHashCode();
			LazyResponses r;
			if (_usages.TryGetValue(key, out r)) return r;
			lock (_lock)
			{
				if (_usages.TryGetValue(key, out r)) return r;
				var response = clientUsage();
				_usages.TryAdd(key, response);
				return response;
			}
		}