void SetUp()
 {
     target = new HashCache<POCOObject>(Guid.NewGuid().ToString());
 }
Exemple #2
0
        public void TestPersistence()
        {
            var cache = new HashCache();

            cache.Put("test_key", "test_value");
            Assert.AreEqual(cache.Get("test_key"), "test_value");
        }
Exemple #3
0
        //HashCache<string,string>

        public HashTest()
        {
            model        = new TestModel();
            HashHandler1 = model.Model1.HashTree();
            HashHandler2 = model.Model2.HashTree();
            HashHandler3 = model.Model3.HashTree();
        }
        public Task <bool> Begin()
        {
            if (1 == Interlocked.CompareExchange(ref _started, 1, 1))
            {
                throw new InvalidDataException("Can't start the processor twice");
            }

            Utils.Log("Starting Installer Task");
            return(Task.Run(async() =>
            {
                try
                {
                    Utils.Log("Installation has Started");
                    _isRunning.OnNext(true);
                    var task = await _Begin(_cancel.Token);
                    Utils.Log("Vacuuming databases");
                    HashCache.VacuumDatabase();
                    VirtualFile.VacuumDatabase();
                    Utils.Log("Vacuuming completed");
                    return task;
                }
                catch (Exception ex)
                {
                    var _ = Metrics.Error(this.GetType(), ex);
                    throw;
                }
                finally
                {
                    _isRunning.OnNext(false);
                }
            }));
        }
Exemple #5
0
 public static object Clone(object instance)
 {
     if (instance == null)
     {
         return(null);
     }
     else
     {
         var type = instance.GetType();
         if (type.IsSimpleType())
         {
             return(instance);
         }
         else if (type == typeof(object))
         {
             return(new object());
         }
         else
         {
             var func = CloneMapping.GetValue(type);
             if (func == default)
             {
                 func = ObjectCloneBuilder.Create(type);
                 _methodCache[type] = func;
                 CloneMapping       = _methodCache.HashTree();
             }
             return(func(instance));
         }
     }
 }
Exemple #6
0
        private string GetDimCappedString(string dimensionValue, HashCache <string> hashCache, int cacheSize)
        {
            hashCache.RwLock.EnterReadLock();

            if (hashCache.ValueCache.Contains(dimensionValue) == true)
            {
                hashCache.RwLock.ExitReadLock();

                return(dimensionValue);
            }

            if (hashCache.ValueCache.Count > cacheSize)
            {
                hashCache.RwLock.ExitReadLock();

                return(null);
            }

            hashCache.RwLock.ExitReadLock();
            hashCache.RwLock.EnterWriteLock();

            hashCache.ValueCache.Add(dimensionValue);

            hashCache.RwLock.ExitWriteLock();

            return(dimensionValue);
        }
Exemple #7
0
        private void ResetDimCapCaches(HashCache <string> cache1, HashCache <string> cache2, HashCache <string> cache3)
        {
            cache1.RwLock.EnterWriteLock();

            if (this.DimCapTimeout < DateTime.UtcNow.Ticks)
            {
                cache2.RwLock.EnterWriteLock();

                if (this.DimCapTimeout < DateTime.UtcNow.Ticks)
                {
                    cache3.RwLock.EnterWriteLock();

                    if (this.DimCapTimeout < DateTime.UtcNow.Ticks)
                    {
                        cache1.ValueCache.Clear();
                        cache2.ValueCache.Clear();
                        cache3.ValueCache.Clear();

                        this.DimCapTimeout = DateTime.UtcNow.Ticks + this.cacheLifetime;
                    }

                    cache3.RwLock.ExitWriteLock();
                }

                cache2.RwLock.ExitWriteLock();
            }

            cache1.RwLock.ExitWriteLock();
        }
        FactoryFactory MakeFactoryFactory()
        {
            var crypto = new Mock <ICrypto>();

            crypto.Setup(p => p.LoadRsaPublicKey(It.IsAny <string>()))
            .Returns(new RSACryptoServiceProvider());
            crypto.Setup(p => p.GeneratePublicKeyFingerprintFromPrivateKey(It.IsAny <RSA>()))
            .Returns("ff:ff");

            var httpClient = new Mock <IHttpClient>();
            var cache      = new HashCache();

            var factoryFactory = new FactoryFactory(
                crypto.Object,
                httpClient.Object,
                cache,
                "https://api.launchkey.com",
                "lka",
                5,
                3600,
                500,
                new Sdk.Transport.Domain.EntityKeyMap()
                );

            return(factoryFactory);
        }
 public BenchmarkTest()
 {
     model            = new TestModel();
     FuzzyHandler     = model.Model1.FuzzyTree();
     HashHandler      = model.Model1.HashTree();
     PrecisionHandler = model.Model1.PrecisioTree();
     DictHandler      = model.Model1;
     ConDictHandler   = new ConcurrentDictionary <string, string>(model.Model1);
 }
Exemple #10
0
    public void Refresh()
    {
        List <ToggleInfo> list = new List <ToggleInfo>();

        if (tagCategoryMap == null)
        {
            int building_index = 0;
            tagCategoryMap = new Dictionary <Tag, HashedString>();
            tagOrderMap    = new Dictionary <Tag, int>();
            if (TUNING.BUILDINGS.PLANORDER.Count > 12)
            {
                DebugUtil.LogWarningArgs("Insufficient keys to cover root plan menu", "Max of 12 keys supported but TUNING.BUILDINGS.PLANORDER has " + TUNING.BUILDINGS.PLANORDER.Count);
            }
            toggleEntries.Clear();
            for (int i = 0; i < TUNING.BUILDINGS.PLANORDER.Count; i++)
            {
                PlanInfo   planInfo   = TUNING.BUILDINGS.PLANORDER[i];
                Action     hotkey     = (Action)((i >= 12) ? 247 : (36 + i));
                string     icon       = iconNameMap[planInfo.category];
                string     str        = HashCache.Get().Get(planInfo.category).ToUpper();
                ToggleInfo toggleInfo = new ToggleInfo(UI.StripLinkFormatting(Strings.Get("STRINGS.UI.BUILDCATEGORIES." + str + ".NAME")), icon, planInfo.category, hotkey, Strings.Get("STRINGS.UI.BUILDCATEGORIES." + str + ".TOOLTIP"), string.Empty);
                list.Add(toggleInfo);
                PopulateOrderInfo(planInfo.category, planInfo.data, tagCategoryMap, tagOrderMap, ref building_index);
                List <BuildingDef> list2 = new List <BuildingDef>();
                foreach (BuildingDef buildingDef in Assets.BuildingDefs)
                {
                    HashedString value;
                    if (!buildingDef.Deprecated && tagCategoryMap.TryGetValue(buildingDef.Tag, out value) && !(value != planInfo.category))
                    {
                        list2.Add(buildingDef);
                    }
                }
                toggleEntries.Add(new ToggleEntry(toggleInfo, planInfo.category, list2, planInfo.hideIfNotResearched));
            }
            Setup(list);
            toggles.ForEach(delegate(KToggle to)
            {
                ImageToggleState[] components = to.GetComponents <ImageToggleState>();
                ImageToggleState[] array      = components;
                foreach (ImageToggleState imageToggleState in array)
                {
                    if ((UnityEngine.Object)imageToggleState.TargetImage.sprite != (UnityEngine.Object)null && imageToggleState.TargetImage.name == "FG" && !imageToggleState.useSprites)
                    {
                        imageToggleState.SetSprites(Assets.GetSprite(imageToggleState.TargetImage.sprite.name + "_disabled"), imageToggleState.TargetImage.sprite, imageToggleState.TargetImage.sprite, Assets.GetSprite(imageToggleState.TargetImage.sprite.name + "_disabled"));
                    }
                }
                to.GetComponent <KToggle>().soundPlayer.Enabled = false;
            });
            for (int j = 0; j < toggleEntries.Count; j++)
            {
                ToggleEntry value2 = toggleEntries[j];
                value2.CollectToggleImages();
                toggleEntries[j] = value2;
            }
        }
    }
    private void ApplyShape(KAnim.Build.Symbol variation_symbol, KBatchedAnimController controller, KAnimFile shapes_file, HashedString symbol_name_in_shape_file, bool should_use_sideways_symbol)
    {
        HashedString hashedString = HASH_NEUTRAL;

        if (currentExpression != null)
        {
            hashedString = currentExpression.face.hash;
        }
        KAnim.Anim anim = null;
        KAnim.Anim.FrameElement frameElement = default(KAnim.Anim.FrameElement);
        bool flag  = false;
        bool flag2 = false;

        for (int i = 0; i < shapes_file.GetData().animCount; i++)
        {
            if (flag)
            {
                break;
            }
            KAnim.Anim anim2 = shapes_file.GetData().GetAnim(i);
            if (anim2.hash == hashedString)
            {
                anim = anim2;
                KAnim.Anim.Frame frame = anim.GetFrame(shapes_file.GetData().build.batchTag, 0);
                for (int j = 0; j < frame.numElements; j++)
                {
                    KBatchGroupData batchGroupData = KAnimBatchManager.Instance().GetBatchGroupData(shapes_file.GetData().animBatchTag);
                    frameElement = batchGroupData.GetFrameElement(frame.firstElementIdx + j);
                    if (!(frameElement.symbol != symbol_name_in_shape_file))
                    {
                        if (flag2 || !should_use_sideways_symbol)
                        {
                            flag = true;
                        }
                        flag2 = true;
                        break;
                    }
                }
            }
        }
        if (anim == null)
        {
            DebugUtil.Assert(false, "Could not find shape for expression: " + HashCache.Get().Get(hashedString));
        }
        if (!flag2)
        {
            DebugUtil.Assert(false, "Could not find shape element for shape:" + HashCache.Get().Get(variation_symbol.hash));
        }
        KAnim.Build.Symbol symbol          = KAnimBatchManager.Instance().GetBatchGroupData(controller.batchGroupID).GetSymbol(symbol_name_in_shape_file);
        KBatchGroupData    batchGroupData2 = KAnimBatchManager.Instance().GetBatchGroupData(variation_symbol.build.batchTag);

        KAnim.Build.SymbolFrameInstance symbol_frame_instance = batchGroupData2.symbolFrameInstances[variation_symbol.firstFrameIdx + frameElement.frame];
        symbol_frame_instance.buildImageIdx = GetComponent <SymbolOverrideController>().GetAtlasIdx(variation_symbol.build.GetTexture(0));
        controller.SetSymbolOverride(symbol.firstFrameIdx, symbol_frame_instance);
    }
Exemple #12
0
    public void WriteAnimData(int start_index, float[] data)
    {
        List <KAnim.Anim.Frame>        animFrames        = GetAnimFrames();
        List <KAnim.Anim.FrameElement> animFrameElements = GetAnimFrameElements();
        int num = 1 + ((animFrames.Count != 0) ? animFrames.Count : symbolFrameInstances.Count);

        if (animFrames.Count == 0 && symbolFrameInstances.Count == 0 && animFrameElements.Count == 0)
        {
            Debug.LogError("Eh, no data " + animFrames.Count + " " + symbolFrameInstances.Count + " " + animFrameElements.Count);
        }
        data[start_index++] = (float)num;
        data[start_index++] = (float)animFrames.Count;
        data[start_index++] = (float)animFrameElements.Count;
        data[start_index++] = (float)symbolFrameInstances.Count;
        if (animFrames.Count == 0)
        {
            for (int i = 0; i < symbolFrameInstances.Count; i++)
            {
                WriteAnimFrame(data, start_index, i, i, 1, i);
                start_index += 4;
            }
            for (int j = 0; j < symbolFrameInstances.Count; j++)
            {
                WriteAnimFrameElement(data, start_index, j, j, Matrix2x3.identity, Color.white, 0);
                start_index += 16;
            }
        }
        else
        {
            for (int k = 0; k < animFrames.Count; k++)
            {
                Write(data, start_index, k, animFrames[k]);
                start_index += 4;
            }
            for (int l = 0; l < animFrameElements.Count; l++)
            {
                KAnim.Anim.FrameElement element = animFrameElements[l];
                if (element.symbol == KGlobalAnimParser.MISSING_SYMBOL)
                {
                    WriteAnimFrameElement(data, start_index, -1, l, Matrix2x3.identity, Color.white, 0);
                }
                else
                {
                    KAnim.Build.Symbol buildSymbol = GetBuildSymbol(element.symbolIdx);
                    if (buildSymbol == null)
                    {
                        Debug.LogError("Missing symbol for Anim Frame Element: [" + HashCache.Get().Get(element.symbol) + ": " + element.symbol + "]");
                    }
                    int frameIdx = buildSymbol.GetFrameIdx(element.frame);
                    Write(data, start_index, frameIdx, l, element);
                }
                start_index += 16;
            }
        }
    }
    private static void ParseHashTable(FastReader reader)
    {
        int num = reader.ReadInt32();

        for (int i = 0; i < num; i++)
        {
            int    hash = reader.ReadInt32();
            string text = reader.ReadKleiString();
            HashCache.Get().Add(hash, text);
        }
    }
        /// <summary>
        /// Creates a <see cref="SettingsKeyCodeReference"/> instance.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="keySettingName">Name of the key setting.</param>
        /// <returns>The <see cref="SettingsKeyCodeReference"/> instance.</returns>
        public static SettingsKeyCodeReference Create(ApplicationSettingsBase settings, string keySettingName)
        {
            HashCache<string, SettingsKeyCodeReference> c;
            if (!_settingsCache.TryGetValue(settings, out c))
            {
                c = new HashCache<string, SettingsKeyCodeReference>(x => new SettingsKeyCodeReference(settings, x),
                    StringComparer.Ordinal);
                _settingsCache.Add(settings, c);
            }

            return c[keySettingName];
        }
Exemple #15
0
        private void InitRowTransformationManually()
        {
            var hashCache = new HashCache <TInput>();

            hashCache.HashSumFunc = HashSumCalculation;
            CachedRowTransformation.CacheManager       = hashCache;
            CachedRowTransformation.TransformationFunc = MakeRowDistinct;
            CachedRowTransformation.CopyLogTaskProperties(this);
            CachedRowTransformation.MaxBufferSize = this.MaxBufferSize;
            CachedRowTransformation.FillCacheAfterTranformation = true;
            CachedRowTransformation.InitBufferObjects();
        }
        /// <summary>
        /// Creates a <see cref="SettingsKeyCodeReference"/> instance.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="keySettingName">Name of the key setting.</param>
        /// <returns>The <see cref="SettingsKeyCodeReference"/> instance.</returns>
        public static SettingsKeyCodeReference Create(ApplicationSettingsBase settings, string keySettingName)
        {
            HashCache <string, SettingsKeyCodeReference> c;

            if (!_settingsCache.TryGetValue(settings, out c))
            {
                c = new HashCache <string, SettingsKeyCodeReference>(x => new SettingsKeyCodeReference(settings, x),
                                                                     StringComparer.Ordinal);
                _settingsCache.Add(settings, c);
            }

            return(c[keySettingName]);
        }
 public static KCompBuilder.BodyData CreateBodyData(Personality p)
 {
     KCompBuilder.BodyData result = default(KCompBuilder.BodyData);
     result.eyes      = HashCache.Get().Add($"eyes_{p.eyes:000}");
     result.hair      = HashCache.Get().Add($"hair_{p.hair:000}");
     result.headShape = HashCache.Get().Add($"headshape_{p.headShape:000}");
     result.mouth     = HashCache.Get().Add($"mouth_{p.mouth:000}");
     result.neck      = HashCache.Get().Add($"neck_{p.neck:000}");
     result.arms      = HashCache.Get().Add($"arm_{p.body:000}");
     result.body      = HashCache.Get().Add($"body_{p.body:000}");
     result.hat       = HashedString.Invalid;
     return(result);
 }
Exemple #18
0
 public override void BeginTransition(Navigator navigator, Navigator.ActiveTransition transition)
 {
     base.BeginTransition(navigator, transition);
     CreatureCalorieMonitor.Instance sMI = navigator.GetSMI <CreatureCalorieMonitor.Instance>();
     if (sMI != null && sMI.stomach.IsReadyToPoop())
     {
         KBatchedAnimController component = navigator.GetComponent <KBatchedAnimController>();
         string s = HashCache.Get().Get(transition.anim.HashValue) + "_full";
         if (component.HasAnimation(s))
         {
             transition.anim = s;
         }
     }
 }
Exemple #19
0
 public void TestCache() {
    Cache<String, String> cache = new HashCache<String, String>();
    Map<String, String> map = new HashMap<String, String>();
    for(int i = 0; i < LOAD_COUNT; i++) {
       String key = i.ToString();
       cache.Insert(key, key);
       map.Put(key, key);
    }
    for(int i = 0; i < LOAD_COUNT; i++) {
       String key = i.ToString();
       AssertEquals(cache.Fetch(key), key);
       AssertEquals(map.Get(key), cache.Fetch(key));
    }
 }
    public void Configure(HashedString category, int depth, object data, Dictionary <HashedString, List <BuildingDef> > categorized_building_map, Dictionary <HashedString, List <HashedString> > categorized_category_map, BuildMenuBuildingsScreen buildings_screen)
    {
        this.category          = category;
        categorizedBuildingMap = categorized_building_map;
        categorizedCategoryMap = categorized_category_map;
        buildingsScreen        = buildings_screen;
        List <ToggleInfo> list = new List <ToggleInfo>();

        if (typeof(IList <BuildMenu.BuildingInfo>).IsAssignableFrom(data.GetType()))
        {
            buildingInfos = (IList <BuildMenu.BuildingInfo>)data;
        }
        else if (typeof(IList <BuildMenu.DisplayInfo>).IsAssignableFrom(data.GetType()))
        {
            subcategories = new List <HashedString>();
            IList <BuildMenu.DisplayInfo> list2 = (IList <BuildMenu.DisplayInfo>)data;
            foreach (BuildMenu.DisplayInfo item2 in list2)
            {
                BuildMenu.DisplayInfo current = item2;
                string iconName = current.iconName;
                string text     = HashCache.Get().Get(current.category).ToUpper();
                text = text.Replace(" ", string.Empty);
                ToggleInfo item = new ToggleInfo(Strings.Get("STRINGS.UI.NEWBUILDCATEGORIES." + text + ".NAME"), iconName, new UserData
                {
                    category          = current.category,
                    depth             = depth,
                    requirementsState = PlanScreen.RequirementsState.Tech
                }, current.hotkey, Strings.Get("STRINGS.UI.NEWBUILDCATEGORIES." + text + ".TOOLTIP"), string.Empty);
                list.Add(item);
                subcategories.Add(current.category);
            }
            Setup(list);
            toggles.ForEach(delegate(KToggle to)
            {
                ImageToggleState[] components = to.GetComponents <ImageToggleState>();
                ImageToggleState[] array      = components;
                foreach (ImageToggleState imageToggleState in array)
                {
                    if ((UnityEngine.Object)imageToggleState.TargetImage.sprite != (UnityEngine.Object)null && imageToggleState.TargetImage.name == "FG" && !imageToggleState.useSprites)
                    {
                        imageToggleState.SetSprites(Assets.GetSprite(imageToggleState.TargetImage.sprite.name + "_disabled"), imageToggleState.TargetImage.sprite, imageToggleState.TargetImage.sprite, Assets.GetSprite(imageToggleState.TargetImage.sprite.name + "_disabled"));
                    }
                }
                to.GetComponent <KToggle>().soundPlayer.Enabled = false;
            });
        }
        UpdateBuildableStates(true);
    }
Exemple #21
0
        private int CalculateHashCode(IEqualityComparer /*!*/ comparer)
        {
            Assert.NotNull(comparer);

            HashCache curHashCache = _hashCache;

            if (curHashCache != null && object.ReferenceEquals(comparer, curHashCache.Comparer))
            {
                return(curHashCache.HashCode);
            }

            int hash = SetStorage.GetHashCode(_items, comparer);

            _hashCache = new HashCache(hash, comparer);
            return(hash);
        }
Exemple #22
0
        /// <summary>
        /// 实时获取所有副本的在线用户总数
        /// </summary>
        /// <returns>Dict结构:key为副本id,value为副本会话总数</returns>
        public async Task <Dict> GetOnlineCount()
        {
            Dict result = null;
            int  cnt    = await Kit.GetSvcReplicaCount();

            if (cnt > 1)
            {
                // 所有副本
                string key = "msg:OnlineCount:" + Guid.NewGuid().ToString().Substring(0, 6);
                Kit.RemoteMulticast(new OnlineCountEvent {
                    CacheKey = key
                });

                // 等待收集
                int total, retry = 0;
                var sc = new StringCache(key);
                do
                {
                    await Task.Delay(_delayMilli);

                    total = await sc.Get <int>("cnt");

                    retry++;
                }while (total < cnt && retry < _maxRetry);

                // 删除统计总数
                await sc.Delete("cnt");

                var hc   = new HashCache(key);
                var hash = await hc.GetAll(null);

                if (hash != null && hash.Length > 0)
                {
                    await hc.Delete(null);

                    result = hash.ToDict();
                }
            }
            else
            {
                // 当前单副本
                result = new Dict {
                    { Kit.SvcID, Online.TotalCount }
                };
            }
            return(result);
        }
Exemple #23
0
 public void CopyBuildingOrder(Building building)
 {
     foreach (PlanInfo item in TUNING.BUILDINGS.PLANORDER)
     {
         PlanInfo current = item;
         foreach (string item2 in (List <string>)current.data)
         {
             if (building.Def.PrefabID == item2)
             {
                 OpenCategoryByName(HashCache.Get().Get(current.category));
                 OnSelectBuilding(ActiveToggles[building.Def].gameObject, building.Def);
                 productInfoScreen.materialSelectionPanel.SelectSourcesMaterials(building);
                 break;
             }
         }
     }
 }
Exemple #24
0
        private int CalculateHashCode(IEqualityComparer /*!*/ comparer)
        {
            Assert.NotNull(comparer);

            HashCache curHashCache = _hashCache;

            if (curHashCache != null && object.ReferenceEquals(comparer, curHashCache.Comparer))
            {
                return(curHashCache.HashCode);
            }

            // hash code needs be stable across collections (even if keys are
            // added in different order) and needs to be fairly collision free.

            int[] hash_codes = new int[_items.Count];

            int i = 0;

            foreach (object o in _items.GetKeys())
            {
                hash_codes[i++] = comparer.GetHashCode(o);
            }

            Array.Sort(hash_codes);

            int hash1 = 6551;
            int hash2 = hash1;

            for (i = 0; i < hash_codes.Length; i += 2)
            {
                hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ hash_codes[i];

                if (i == hash_codes.Length - 1)
                {
                    break;
                }
                hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ hash_codes[i + 1];
            }

            hash1 += hash2 * 1566083941;

            _hashCache = new HashCache(hash1, comparer);
            return(hash1);
        }
Exemple #25
0
 private static void AddBindings(HashedString parent_category, BuildMenu.DisplayInfo display_info, List <BindingEntry> bindings)
 {
     if (display_info.data != null)
     {
         Type type = display_info.data.GetType();
         if (typeof(IList <BuildMenu.DisplayInfo>).IsAssignableFrom(type))
         {
             IList <BuildMenu.DisplayInfo> list = (IList <BuildMenu.DisplayInfo>)display_info.data;
             foreach (BuildMenu.DisplayInfo item2 in list)
             {
                 AddBindings(display_info.category, item2, bindings);
             }
         }
         else if (typeof(IList <BuildMenu.BuildingInfo>).IsAssignableFrom(type))
         {
             string       str      = HashCache.Get().Get(parent_category);
             TextInfo     textInfo = new CultureInfo("en-US", false).TextInfo;
             string       group    = textInfo.ToTitleCase(str) + " Menu";
             BindingEntry item     = new BindingEntry(group, GamepadButton.NumButtons, display_info.keyCode, Modifier.None, display_info.hotkey, true, true);
             bindings.Add(item);
         }
     }
 }
Exemple #26
0
 public unsafe static object Clone(object instance)
 {
     if (instance == null)
     {
         return(null);
     }
     else
     {
         var type = instance.GetType();
         if (type.IsSimpleType())
         {
             return(instance);
         }
         else if (type == typeof(object))
         {
             return(new object());
         }
         else
         {
             var func = CloneMapping.GetValue(type);
             if (func == default)
             {
                 func = ObjectCloneBuilder.Create(type);
                 _methodCache[type] = func;
                 int[] code = new int[_methodCache.Count];
                 int   i    = 0;
                 foreach (var item in _methodCache)
                 {
                     code[i] = item.Value.GetHashCode();
                     i++;
                 }
                 CloneMapping = _methodCache.HashTree(DyanamicCacheDirection.KeyToValue);
             }
             return(func(instance));
         }
     }
 }
Exemple #27
0
 /// <summary>
 /// Warms up the game hash cache. This is run every load for some reason...
 /// </summary>
 private static void LoadGameHashes()
 {
     foreach (object gh in Enum.GetValues(typeof(GameHashes)))
     {
         if (gh is GameHashes hash)
         {
             HashCache.Get().Add((int)hash, hash.ToString());
         }
     }
     foreach (object uh in Enum.GetValues(typeof(UtilHashes)))
     {
         if (uh is UtilHashes hash)
         {
             HashCache.Get().Add((int)hash, hash.ToString());
         }
     }
     foreach (object ih in Enum.GetValues(typeof(UIHashes)))
     {
         if (ih is UIHashes hash)
         {
             HashCache.Get().Add((int)hash, hash.ToString());
         }
     }
 }
    public void AddAccessories(KAnimFile default_build, ResourceSet parent)
    {
        KAnim.Build        build  = file.GetData().build;
        KAnim.Build.Symbol symbol = default_build.GetData().build.GetSymbol(targetSymbolId);
        string             text   = Id.ToLower();

        if (symbol != null)
        {
            string    id        = text + "_DEFAULT";
            Accessory accessory = new Accessory(id, parent, this, default_build.batchTag, symbol);
            accessories.Add(accessory);
            HashCache.Get().Add(accessory.IdHash.HashValue, accessory.Id);
        }
        for (int i = 0; i < build.symbols.Length; i++)
        {
            string text2 = HashCache.Get().Get(build.symbols[i].hash);
            if (text2.StartsWith(text))
            {
                Accessory accessory2 = new Accessory(text2, parent, this, file.batchTag, build.symbols[i]);
                accessories.Add(accessory2);
                HashCache.Get().Add(accessory2.IdHash.HashValue, accessory2.Id);
            }
        }
    }
Exemple #29
0
        /// <summary>
        /// 查询所有副本,获取某账号的所有会话信息
        /// </summary>
        /// <param name="p_userID"></param>
        /// <returns>会话信息列表</returns>
        public async Task <List <Dict> > GetAllSessions(long p_userID)
        {
            List <Dict> result = new List <Dict>();
            int         cnt    = await Kit.GetSvcReplicaCount();

            if (cnt > 1)
            {
                // 查询所有副本
                string key = $"msg:Sessions:{p_userID}:{Guid.NewGuid().ToString().Substring(0, 6)}";
                Kit.RemoteMulticast(new UserSessionsEvent {
                    CacheKey = key, UserID = p_userID
                });

                // 等待收集
                int total, retry = 0;
                var sc = new StringCache(key);
                do
                {
                    await Task.Delay(_delayMilli);

                    total = await sc.Get <int>("cnt");

                    retry++;
                }while (total < cnt && retry < _maxRetry);

                // 删除统计总数
                await sc.Delete("cnt");

                var hc   = new HashCache(key);
                var hash = await hc.GetAll(null);

                if (hash != null && hash.Length > 0)
                {
                    await hc.Delete(null);

                    var dt = hash.ToDict();
                    foreach (var item in dt)
                    {
                        var ss = Kit.Deserialize <List <Dict> >((string)item.Value);
                        if (ss != null && ss.Count > 0)
                        {
                            result.AddRange(ss);
                        }
                    }
                }
            }
            else
            {
                // 当前单副本
                var ls = Online.GetSessions(p_userID);
                if (ls != null && ls.Count > 0)
                {
                    foreach (var ci in ls)
                    {
                        result.Add(new Dict
                        {
                            { "userid", ci.UserID },
                            { "svcid", Kit.SvcID },
                            { "starttime", ci.StartTime.ToString() },
                            { "platform", ci.Platform },
                            { "version", ci.Version },
                            { "devicename", ci.DeviceName },
                            { "devicemodel", ci.DeviceModel },
                        });
                    }
                }
            }
            return(result);
        }
Exemple #30
0
 static ObjectCloneOperator()
 {
     _methodCache = new ConcurrentDictionary <Type, Func <object, object> >();
     CloneMapping = _methodCache.HashTree();
 }
Exemple #31
0
        public bool Equals(Expression x, Expression y)
        {
            if ((object)x == (object)y) return true;
            if (x == null || y == null) return false;
            var type = x.NodeType;
            if (y.NodeType != type) return false;
            if (x.Type != y.Type) return false;
            if (HashCache != null && HashCache.TryGetValue(x, out var hashx) && HashCache.TryGetValue(x, out var hashy) && hashy.Item1 != hashx.Item1) return false;

            switch (type)
            {
                case ExpressionType.Add:
                case ExpressionType.AddChecked:
                case ExpressionType.And:
                case ExpressionType.Divide:
                case ExpressionType.Equal:
                case ExpressionType.ExclusiveOr:
                case ExpressionType.GreaterThan:
                case ExpressionType.GreaterThanOrEqual:
                case ExpressionType.AndAlso:
                case ExpressionType.Power:
                case ExpressionType.RightShift:
                case ExpressionType.Subtract:
                case ExpressionType.SubtractChecked:
                case ExpressionType.ArrayIndex:
                case ExpressionType.Modulo:
                case ExpressionType.Multiply:
                case ExpressionType.MultiplyChecked:
                case ExpressionType.LeftShift:
                case ExpressionType.OnesComplement:
                case ExpressionType.AddAssign:
                case ExpressionType.AndAssign:
                case ExpressionType.DivideAssign:
                case ExpressionType.ExclusiveOrAssign:
                case ExpressionType.LeftShiftAssign:
                case ExpressionType.ModuloAssign:
                case ExpressionType.MultiplyAssign:
                case ExpressionType.OrAssign:
                case ExpressionType.PowerAssign:
                case ExpressionType.RightShiftAssign:
                case ExpressionType.SubtractAssign:
                case ExpressionType.AddAssignChecked:
                case ExpressionType.MultiplyAssignChecked:
                case ExpressionType.SubtractAssignChecked:
                case ExpressionType.PreIncrementAssign:
                case ExpressionType.PreDecrementAssign:
                case ExpressionType.PostIncrementAssign:
                case ExpressionType.PostDecrementAssign:
                case ExpressionType.IsTrue:
                case ExpressionType.IsFalse:
                case ExpressionType.NotEqual:
                case ExpressionType.Or:
                case ExpressionType.OrElse:
                case ExpressionType.LessThan:
                case ExpressionType.LessThanOrEqual:
                case ExpressionType.Coalesce:
                    var binX = (BinaryExpression)x;
                    var binY = (BinaryExpression)y;
                    return Equals(binX.Method, binY.Method) && Equals(binX.Left, binY.Left) && Equals(binX.Right, binY.Right);
                case ExpressionType.Call:
                    var callX = (MethodCallExpression)x;
                    var callY = (MethodCallExpression)y;
                    return Equals(callX.Method, callY.Method) && Equals(callX.Object, callY.Object) && callX.Arguments.Zip(callY.Arguments, Equals).All(f => f);
                case ExpressionType.ConvertChecked:
                case ExpressionType.Negate:
                case ExpressionType.UnaryPlus:
                case ExpressionType.Quote:
                case ExpressionType.Not:
                case ExpressionType.TypeAs:
                case ExpressionType.NegateChecked:
                case ExpressionType.Unbox:
                case ExpressionType.Convert:
                case ExpressionType.ArrayLength:
                    var unX = (UnaryExpression)x;
                    var unY = (UnaryExpression)y;
                    return Equals(unX.Method, unY.Method) && Equals(unX.Operand, unY.Operand);
                case ExpressionType.Conditional:
                    var condX = (ConditionalExpression)x;
                    var condY = (ConditionalExpression)y;
                    return Equals(condX.IfFalse, condY.IfFalse) && Equals(condX.IfTrue, condY.IfTrue) && Equals(condX.Test, condY.Test);
                case ExpressionType.Constant:
                    var constX = (ConstantExpression)x;
                    var constY = (ConstantExpression)y;
                    return constX.Value == constY.Value || constX.Value.Equals(constY.Value);
                case ExpressionType.Invoke:
                    var invX = (InvocationExpression)x;
                    var invY = (InvocationExpression)y;
                    return Equals(invX.Expression, invY.Expression) && invX.Arguments.Zip(invY.Arguments, Equals).All(f => f);
                case ExpressionType.Lambda:
                    var lamX = (LambdaExpression)x;
                    var lamY = (LambdaExpression)y;
                    return lamX.Name == lamY.Name && lamX.Parameters.Count == lamY.Parameters.Count && lamX.Parameters.Zip(lamY.Parameters, Equals).All(f => f) && Equals(lamX.Body, lamY.Body);
                case ExpressionType.ListInit:
                    var linitX = (ListInitExpression)x;
                    var linitY = (ListInitExpression)y;
                    return Equals(linitX.NewExpression, linitY.NewExpression) && linitX.Initializers.Zip(linitY.Initializers, Equals).All(f => f);
                case ExpressionType.MemberAccess:
                    var memX = (MemberExpression)x;
                    var memY = (MemberExpression)y;
                    return Equals(memX.Member, memY.Member) && Equals(memX.Expression, memY.Expression);
                case ExpressionType.MemberInit:
                    var minitX = (MemberInitExpression)x;
                    var minitY = (MemberInitExpression)y;
                    throw new NotImplementedException();
                //return Equals(minitX, minitY) && minitX.Bindings.Zip(minitY.Bindings, (a, b) => a.BindingType == b.BindingType && a.Member == b.Member).All(f => f);
                case ExpressionType.New:
                    var newX = (NewExpression)x;
                    var newY = (NewExpression)y;
                    return Equals(newX.Constructor, newY.Constructor) && newX.Arguments.Zip(newY.Arguments, Equals).All(f => f);
                case ExpressionType.NewArrayInit:
                case ExpressionType.NewArrayBounds:
                    var newArrX = (NewArrayExpression)x;
                    var newArrY = (NewArrayExpression)y;
                    return newArrX.Expressions.Zip(newArrY.Expressions, Equals).All(f => f);
                case ExpressionType.Parameter:
                    var paramX = (ParameterExpression)x;
                    var paramY = (ParameterExpression)y;
                    return paramX.Name == paramY.Name && paramX.IsByRef == paramY.IsByRef && paramX.Name != null && !paramX.Name.StartsWith("__");
                case ExpressionType.TypeEqual:
                case ExpressionType.TypeIs:
                    var typeBinX = (TypeBinaryExpression)x;
                    var typeBinY = (TypeBinaryExpression)y;
                    return typeBinX.TypeOperand == typeBinY.TypeOperand && Equals(typeBinX.Expression, typeBinY.Expression);
                case ExpressionType.Default:
                    return true;
                case ExpressionType.Block:
                    var blockX = (BlockExpression)x;
                    var blockY = (BlockExpression)y;
                    return blockX.Variables.SequenceEqual(blockY.Variables, this) &&
                        blockY.Expressions.SequenceEqual(blockY.Expressions, this);
                case ExpressionType.Index:
                    var indexX = (IndexExpression)x;
                    var indexY = (IndexExpression)y;
                    return Equals(indexX.Indexer, indexY.Indexer) && indexX.Arguments.SequenceEqual(indexY.Arguments, this) &&
                        Equals(indexX.Object, indexY.Object);
                case ExpressionType.Extension:
                    //Debug.Assert(x is MyParameterExpression);
                    return x.Equals(y);
                default:
                    throw new NotImplementedException($"Comparing expression of type { type} is not supported.");
            }
        }
Exemple #32
0
        private XTypeInfo(Type type, XBindingFlags flags)
        {
            this.type  = type;
            this.flags = flags;

            IEqualityComparer <string> rwKeyComparer;

            if ((flags & XBindingFlags.RWIgnoreCase) != 0)
            {
                rwKeyComparer = new IgnoreCaseEqualityComparer();
            }
            else
            {
                rwKeyComparer = EqualityComparer <string> .Default;
            }

            var fields     = new List <XFieldInfo>();
            var properties = new List <XPropertyInfo>();
            var indexers   = new List <XIndexerInfo>();
            var methods    = new List <XMethodInfo>();
            var rwFields   = new List <IXFieldRW>();

            GetItems(type, flags, fields, properties, indexers, methods);

            foreach (var item in fields)
            {
                var rwField = item as IXFieldRW;

                if (rwField == null)
                {
                    continue;
                }

                var attributes = item.FieldInfo.GetCustomAttributes(typeof(RWFieldAttribute), true);

                if (attributes != null && attributes.Length != 0)
                {
                    foreach (RWFieldAttribute attribute in attributes)
                    {
                        var attributedFieldRW = new XAttributedFieldRW(rwField, attribute);

                        if (attributedFieldRW.CanRead || attributedFieldRW.CanWrite)
                        {
                            rwFields.Add(attributedFieldRW);
                        }
                    }
                }
                else
                {
                    rwFields.Add(rwField);
                }
            }

            foreach (var item in properties)
            {
                var rwField = item as IXFieldRW;

                if (rwField == null)
                {
                    continue;
                }

                var attributes = item.PropertyInfo.GetCustomAttributes(typeof(RWFieldAttribute), true);

                if (attributes != null && attributes.Length != 0)
                {
                    foreach (RWFieldAttribute attribute in attributes)
                    {
                        var attributedFieldRW = new XAttributedFieldRW(rwField, attribute);

                        if (attributedFieldRW.CanRead || attributedFieldRW.CanWrite)
                        {
                            rwFields.Add(attributedFieldRW);
                        }
                    }
                }
                else
                {
                    rwFields.Add(rwField);
                }
            }

            rwFields.Sort((x, y) => x.Order.CompareTo(y.Order));

            this.fields     = fields.ToArray();
            this.properties = properties.ToArray();
            this.indexers   = indexers.ToArray();
            this.methods    = methods.ToArray();
            this.rwFields   = rwFields.ToArray();

            fieldsCache     = new NameCache <XFieldInfo>();
            propertiesCache = new NameCache <XPropertyInfo>();
            indexersCache   = new HashCache <RuntimeParamsSign, XIndexerInfo>();
            methodsCache    = new HashCache <RuntimeMethodSign, XMethodInfo>();
            rwFieldsCache   = new NameCache <IXFieldRW>();

            foreach (var item in fields)
            {
                fieldsCache[item.name] = item;
            }
            foreach (var item in properties)
            {
                propertiesCache[item.name] = item;
            }
            foreach (var item in indexers)
            {
                indexersCache[new RuntimeParamsSign(ParametersToTypes(item.PropertyInfo.GetIndexParameters()))] = item;
            }
            foreach (var item in methods)
            {
                methodsCache[new RuntimeMethodSign(item.MethodInfo.Name, ParametersToTypes(item.MethodInfo.GetParameters()))] = item;
            }
            foreach (var item in rwFields)
            {
                rwFieldsCache[item.Name] = item;
            }
        }
 public static void SetPortraitData(IAssignableIdentity identityObject, KBatchedAnimController controller, bool useDefaultExpression = true)
 {
     if (identityObject == null)
     {
         controller.gameObject.SetActive(false);
     }
     else
     {
         MinionIdentity minionIdentity = identityObject as MinionIdentity;
         if ((UnityEngine.Object)minionIdentity == (UnityEngine.Object)null)
         {
             MinionAssignablesProxy minionAssignablesProxy = identityObject as MinionAssignablesProxy;
             if ((UnityEngine.Object)minionAssignablesProxy != (UnityEngine.Object)null && minionAssignablesProxy.target != null)
             {
                 minionIdentity = (minionAssignablesProxy.target as MinionIdentity);
             }
         }
         controller.gameObject.SetActive(true);
         controller.Play("ui_idle", KAnim.PlayMode.Once, 1f, 0f);
         SymbolOverrideController component = controller.GetComponent <SymbolOverrideController>();
         component.RemoveAllSymbolOverrides(0);
         if ((UnityEngine.Object)minionIdentity != (UnityEngine.Object)null)
         {
             Accessorizer component2 = minionIdentity.GetComponent <Accessorizer>();
             foreach (AccessorySlot resource in Db.Get().AccessorySlots.resources)
             {
                 Accessory accessory = component2.GetAccessory(resource);
                 if (accessory != null)
                 {
                     component.AddSymbolOverride(resource.targetSymbolId, accessory.symbol, 0);
                     controller.SetSymbolVisiblity(resource.targetSymbolId, true);
                 }
             }
             component.AddSymbolOverride(Db.Get().AccessorySlots.HatHair.targetSymbolId, Db.Get().AccessorySlots.HatHair.Lookup("hat_" + HashCache.Get().Get(component2.GetAccessory(Db.Get().AccessorySlots.Hair).symbol.hash)).symbol, 1);
             RefreshHat(minionIdentity, controller);
         }
         else
         {
             StoredMinionIdentity storedMinionIdentity = identityObject as StoredMinionIdentity;
             if ((UnityEngine.Object)storedMinionIdentity == (UnityEngine.Object)null)
             {
                 MinionAssignablesProxy minionAssignablesProxy2 = identityObject as MinionAssignablesProxy;
                 if ((UnityEngine.Object)minionAssignablesProxy2 != (UnityEngine.Object)null && minionAssignablesProxy2.target != null)
                 {
                     storedMinionIdentity = (minionAssignablesProxy2.target as StoredMinionIdentity);
                 }
             }
             if (!((UnityEngine.Object)storedMinionIdentity != (UnityEngine.Object)null))
             {
                 controller.gameObject.SetActive(false);
                 return;
             }
             foreach (AccessorySlot resource2 in Db.Get().AccessorySlots.resources)
             {
                 Accessory accessory2 = storedMinionIdentity.GetAccessory(resource2);
                 if (accessory2 != null)
                 {
                     component.AddSymbolOverride(resource2.targetSymbolId, accessory2.symbol, 0);
                     controller.SetSymbolVisiblity(resource2.targetSymbolId, true);
                 }
             }
             component.AddSymbolOverride(Db.Get().AccessorySlots.HatHair.targetSymbolId, Db.Get().AccessorySlots.HatHair.Lookup("hat_" + HashCache.Get().Get(storedMinionIdentity.GetAccessory(Db.Get().AccessorySlots.Hair).symbol.hash)).symbol, 1);
             RefreshHat(storedMinionIdentity, controller);
         }
         float animScale = 1f;
         if ((UnityEngine.Object)GameScreenManager.Instance != (UnityEngine.Object)null && (UnityEngine.Object)GameScreenManager.Instance.ssOverlayCanvas != (UnityEngine.Object)null)
         {
             animScale = 0.2f * (1f / GameScreenManager.Instance.ssOverlayCanvas.GetComponent <KCanvasScaler>().GetUserScale());
         }
         controller.animScale = animScale;
         string s = "ui";
         controller.Play(s, KAnim.PlayMode.Loop, 1f, 0f);
         controller.SetSymbolVisiblity("snapTo_neck", false);
         controller.SetSymbolVisiblity("snapTo_goggles", false);
     }
 }