Exemplo n.º 1
0
        /// <summary>
        /// Поиск существительного по точному совпадению с автоматическим определением рода, падежа и числа.
        /// Возвращает null если слово не было найдено.
        /// </summary>
        /// <param name="word">Существительное в любом роде, числе и падеже.</param>
        /// <param name="number">Число найденного существительного.</param>
        /// <param name="case">Падеж найденного существительного.</param>
        /// <returns></returns>
        public CyrNoun GetOrDefault(string word, out CasesEnum @case, out NumbersEnum number)
        {
            DictionaryKey key;
            CyrNoun       noun;

            // Существительные, без формы единственного числа, не имеют рода. К примеру "ворота" или "шахматы".
            GendersEnum[] gendersWithZero = new GendersEnum[] { GendersEnum.Masculine, GendersEnum.Feminine, GendersEnum.Neuter, GendersEnum.Undefined };

            foreach (CasesEnum c in this.cases)
            {
                foreach (NumbersEnum n in this.numbers)
                {
                    foreach (GendersEnum g in gendersWithZero)
                    {
                        key = new DictionaryKey(word, g, c, n);

                        if (this.words.TryGetValue(key, out noun))
                        {
                            @case  = key.Case;
                            number = key.Number;

                            return(noun);
                        }
                    }
                }
            }

            @case  = 0;
            number = 0;

            return(null);
        }
Exemplo n.º 2
0
 private object serializeDictKey(DictionaryKey k)
 {
     return(new {
         text = k.text,
         misc = k.misc
     });
 }
Exemplo n.º 3
0
        /// <summary>
        /// Tries to get the value based on defined key and tag.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="tag">The tag.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public static bool TryGetValue <T>(object key, int tag, out T value)
        {
            var fullKey = new DictionaryKey()
            {
                Key = key, Tag = tag
            };

            object buf;

            if (!Dict.TryGetValue(fullKey, out buf))
            {
                value = default(T);
                return(false);
            }

            if (ReferenceEquals(buf, null))
            {
                value = default(T);
                return(true);
            }

            if (typeof(T) == buf.GetType())
            {
                value = (T)buf;
                return(true);
            }

            value = default(T);
            return(false);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Добавляет слово в <see cref="words"/> словарь.
        /// </summary>
        /// <param name="line">
        /// Строка со словом в формате словаря.
        /// Смотри /Cyriller/App_Data/nouns.txt.
        /// </param>
        protected virtual void AddWordToTheCollection(string line, List <string>[] singularWordCandidates, List <string>[] pluralWordCandidates)
        {
            string[] parts = line.Split(' ');

            CyrNounCollectionRow row = CyrNounCollectionRow.Parse(parts[1]);

            CyrRule[] rules = this.rules[row.RuleID];
            CyrNoun   noun  = new CyrNoun(parts[0], (GendersEnum)row.GenderID, (AnimatesEnum)row.AnimateID, (WordTypesEnum)row.TypeID, rules);

            CyrResult singular = noun.Decline();
            CyrResult plural   = noun.DeclinePlural();

            foreach (CasesEnum @case in this.cases)
            {
                if (!string.IsNullOrEmpty(singular.Get(@case)))
                {
                    DictionaryKey key = new DictionaryKey(singular.Get(@case), noun.Gender, @case, NumbersEnum.Singular);
                    singularWordCandidates[(int)@case - 1].Add(singular.Get(@case));
                    this.words[key] = noun;
                }

                if (!string.IsNullOrEmpty(plural.Get(@case)))
                {
                    DictionaryKey key = new DictionaryKey(plural.Get(@case), noun.Gender, @case, NumbersEnum.Plural);
                    pluralWordCandidates[(int)@case - 1].Add(plural.Get(@case));
                    this.words[key] = noun;
                }
            }
        }
Exemplo n.º 5
0
 public bool Equals(Peer other)
 {
     if (other == null)
     {
         return(false);
     }
     return(DictionaryKey.Equals(other.DictionaryKey));
 }
Exemplo n.º 6
0
        /// <summary>
        /// Adds a value to cache
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="tag">The tag.</param>
        /// <param name="value">The value.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        public static void SetValue(object key, int tag, object value)
        {
            var fullKey = new DictionaryKey()
            {
                Key = key, Tag = tag
            };

            Dict[fullKey] = value;
        }
            public override bool Equals(object obj)
            {
                if (!(obj is DictionaryKey))
                {
                    return(false);
                }

                DictionaryKey that = (DictionaryKey)obj;

                return(this.Case == that.Case && this.Gender == that.Gender && this.Number == that.Number && this.Name == that.Name);
            }
Exemplo n.º 8
0
        /// <summary>
        /// Поиск прилагательного по точному совпадению с указанием рода, падежа, числа и одушевленности.
        /// Возвращает null если слово не было найдено.
        /// </summary>
        /// <param name="word">Прилагательное.</param>
        /// <param name="gender">Род, в котором указано прилагательное.</param>
        /// <param name="case">Падеж, в котором указано прилагательное.</param>
        /// <param name="number">Число, в котором указано прилагательное.</param>
        /// <param name="animate">Одушевленность прилагательного.</param>
        /// <returns></returns>
        public CyrAdjective GetOrDefault(string word, GendersEnum gender, CasesEnum @case, NumbersEnum number, AnimatesEnum animate)
        {
            DictionaryKey key = new DictionaryKey(word, gender, @case, number, animate);
            CyrAdjective  adjective;

            if (this.words.TryGetValue(key, out adjective))
            {
                return(new CyrAdjective(adjective));
            }

            return(null);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Поиск существительного по точному совпадению.
        /// Возвращает null если слово не было найдено.
        /// </summary>
        /// <param name="word">Существительное.</param>
        /// <param name="gender">Род, в котором указано существительного.</param>
        /// <param name="case">Падеж, в котором указано существительного.</param>
        /// <param name="number">Число, в котором указано существительного.</param>
        /// <returns></returns>
        public CyrNoun GetOrDefault(string word, GendersEnum gender, CasesEnum @case, NumbersEnum number)
        {
            DictionaryKey key = new DictionaryKey(word, gender, @case, number);
            CyrNoun       noun;

            if (this.words.TryGetValue(key, out noun))
            {
                return(new CyrNoun(noun));
            }

            return(null);
        }
Exemplo n.º 10
0
    /// <summary> Init key bind element </summary>
    public void Init(InputType inputType, ActionKey actionKey)
    {
        Blocker.SetActive(false);
        InputType      = inputType;
        ActionKey      = actionKey;
        KeyText.text   = actionKey.ToString();
        ValueText.text = DictionaryKey.TryGetOrDefault(actionKey).ToString();

        var btn = GetComponent <CustomButton>();

        btn.onClick.AddListener(OnClickButton);
    }
Exemplo n.º 11
0
        private static Action <IDbDataParameter> CreateSetTypeAction(DictionaryKey key)
        {
            Type enumType          = key.ParameterType.Assembly.GetType($"{key.ParameterType.Namespace}.OracleDbType");
            var  enumValue         = Enum.Parse(enumType, key.OracleTypeName);
            var  inputVariable     = Expression.Parameter(typeof(IDbDataParameter));
            var  convertExpression = Expression.Convert(inputVariable, key.ParameterType);

            var expression = Expression.Assign(
                Expression.PropertyOrField(convertExpression, "OracleDbType"),
                Expression.Constant(enumValue));

            return(Expression.Lambda <Action <IDbDataParameter> >(expression, inputVariable).Compile());
        }
Exemplo n.º 12
0
        /// <summary>
        /// Поиск существительного по неточному совпадению с указанием рода, падежа и числа.
        /// Возвращает null если слово не было найдено.
        /// </summary>
        /// <param name="word">Существительное.</param>
        /// <param name="foundWord">Существительное, найденное в словаре.</param>
        /// <param name="gender">Род, в котором указано существительного.</param>
        /// <param name="case">Падеж, в котором указано существительного.</param>
        /// <param name="number">Число, в котором указано существительного.</param>
        /// <returns></returns>
        public CyrNoun GetOrDefault(string word, out string foundWord, GendersEnum gender, CasesEnum @case, NumbersEnum number)
        {
            CyrNoun noun = this.GetOrDefault(word, gender, @case, number);

            if (noun != null)
            {
                foundWord = word;
                return(new CyrNoun(noun));
            }

            DictionaryKey key = default;

            foundWord = null;

            if (this.EnableCache)
            {
                key = new DictionaryKey(word, gender, @case, number);

                if (this.similarSearchByKeyCache.TryGetValue(key, out foundWord))
                {
                    noun = this.GetOrDefault(foundWord, gender, @case, number);
                    noun = new CyrNoun(noun);
                    noun.SetName(word, @case, number);

                    return(noun);
                }
            }

            foreach (string candidate in this.cyrData.GetSimilars(word, this.wordCandidates, this.NounMinSameLetters, this.NounMaxSameLetters))
            {
                noun = this.GetOrDefault(candidate, gender, @case, number);

                if (noun == null)
                {
                    continue;
                }

                noun = new CyrNoun(noun);
                noun.SetName(word, @case, number);
                foundWord = candidate;

                break;
            }

            if (this.EnableCache)
            {
                this.similarSearchByKeyCache.Add(key, foundWord);
            }

            return(noun);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Поиск прилагательного по точному совпадению с автоматическим определением рода, падежа, числа и одушевленности.
        /// Возвращает null если слово не было найдено.
        /// </summary>
        /// <param name="word">Прилагательное в любом роде, числе и падеже.</param>
        /// <param name="gender">Род найденного прилагательного.</param>
        /// <param name="number">Число найденного прилагательного.</param>
        /// <param name="case">Падеж найденного прилагательного.</param>
        /// <returns></returns>
        public CyrAdjective GetOrDefault(string word, out GendersEnum gender, out CasesEnum @case, out NumbersEnum number, out AnimatesEnum animate)
        {
            DictionaryKey key;
            CyrAdjective  adjective;

            foreach (AnimatesEnum a in this.animates)
            {
                foreach (GendersEnum g in this.genders)
                {
                    foreach (CasesEnum c in this.cases)
                    {
                        key = new DictionaryKey(word, g, c, NumbersEnum.Singular, a);

                        if (this.words.TryGetValue(key, out adjective))
                        {
                            gender  = key.Gender;
                            @case   = key.Case;
                            number  = key.Number;
                            animate = key.Animate;

                            return(adjective);
                        }
                    }
                }

                foreach (CasesEnum c in this.cases)
                {
                    key = new DictionaryKey(word, 0, c, NumbersEnum.Plural, a);

                    if (this.words.TryGetValue(key, out adjective))
                    {
                        gender  = key.Gender;
                        @case   = key.Case;
                        number  = key.Number;
                        animate = key.Animate;

                        return(adjective);
                    }
                }
            }

            gender  = 0;
            @case   = 0;
            number  = 0;
            animate = 0;

            return(null);
        }
Exemplo n.º 14
0
        public void CreateStaticMethodCall()
        {
            MethodInfo castMethodInfo = typeof(DictionaryKey).GetMethod("op_Implicit", new[] { typeof(string) });

            Assert.IsNotNull(castMethodInfo);

            MethodCall <object, object> call = DynamicReflectionDelegateFactory.Instance.CreateMethodCall <object>(castMethodInfo);

            object result = call(null, "First!");

            Assert.IsNotNull(result);

            DictionaryKey key = (DictionaryKey)result;

            Assert.AreEqual("First!", key.Value);
        }
        public override string ToLC(bool printDefaultParams = false)
        {
            /*
             *   KEYCHAIN SUCCESS OR
             *     STRINGKEY @myVariable Contains "abc"
             *     DICTKEY @data.COOKIES HasKey "my-cookie"
             *   KEYCHAIN FAIL AND
             *     LISTKEY @myList Contains "item"
             *     FLOATKEY 1 GreaterThan 2
             */

            using var writer = new LoliCodeWriter(base.ToLC(printDefaultParams));

            // Write all the keychains
            foreach (var keychain in Keychains)
            {
                writer
                .AppendToken("KEYCHAIN", 2)
                .AppendToken(keychain.ResultStatus)
                .AppendLine(keychain.Mode.ToString());

                foreach (var key in keychain.Keys)
                {
                    (string keyName, string comparison) = key switch
                    {
                        BoolKey x => ("BOOLKEY", x.Comparison.ToString()),
                        StringKey x => ("STRINGKEY", x.Comparison.ToString()),
                        IntKey x => ("INTKEY", x.Comparison.ToString()),
                        FloatKey x => ("FLOATKEY", x.Comparison.ToString()),
                        DictionaryKey x => ("DICTKEY", x.Comparison.ToString()),
                        ListKey x => ("LISTKEY", x.Comparison.ToString()),
                        _ => throw new Exception("Unknown key type")
                    };

                    writer
                    .AppendToken(keyName, 4)
                    .AppendToken(LoliCodeWriter.GetSettingValue(key.Left))
                    .AppendToken(comparison)
                    .AppendLine(LoliCodeWriter.GetSettingValue(key.Right));
                }
            }

            return(writer.ToString());
        }
            public override void execute3(RunTimeValueBase thisObj,FunctionDefine functionDefine,SLOT returnSlot,SourceToken token,StackFrame stackframe,out bool success)
            {
                RunTimeValueBase kv = argements[0];

                if (kv.rtType > RunTimeDataType.unknown)
                {
                    RunTimeDataType ot;
                    if (TypeConverter.Object_CanImplicit_ToPrimitive(
                            bin.getClassByRunTimeDataType(kv.rtType),out ot
                            ))
                    {
                        kv = TypeConverter.ObjectImplicit_ToPrimitive((ASBinCode.rtData.rtObjectBase)kv);
                    }
                }
                DictionaryKey key = new DictionaryKey(kv,true);

                try
                {
                    //链接结构体,不能缓存到变量,必须直接对其赋值....
                    (((LinkObj <DictionaryEntry>)
                          ((ASBinCode.rtData.rtObjectBase)thisObj).value).value).Key = key;


                    returnSlot.directSet(ASBinCode.rtData.rtUndefined.undefined);
                    //returnSlot.setValue((int)array.GetValue(index));
                    success = true;
                }
                catch (InvalidCastException ic)
                {
                    success = false;
                    stackframe.throwAneException(token,ic.Message);
                }
                catch (ArgumentException a)
                {
                    success = false;
                    stackframe.throwAneException(token,a.Message);
                }
                catch (IndexOutOfRangeException i)
                {
                    success = false;
                    stackframe.throwAneException(token,i.Message);
                }
            }
Exemplo n.º 17
0
        private bool SourceHasChanged(string sourcePath, string args)
        {
            if (!File.Exists(sourcePath))
            {
                return(true);
            }
            string hash;

            using (var stream = File.OpenRead(sourcePath))
            {
                var hasher = hasherSource.Value;
                hash = BitConverter.ToString(hasher.ComputeHash(stream));
            }

            var result    = false;
            var hashKey   = new DictionaryKey(sourcePath, args);
            var hashEntry = new DictionaryContent();

            lock (hashDb)
            {
                if (!hashDb.TryGetValue(hashKey, out hashEntry))
                {
                    result = true;
                }
                else if (hashEntry.Modified)
                {
                    return(true);
                }
                else
                {
                    result = (hashDb[hashKey].Hash != hash);
                }
                if (result)
                {
                    hashDb[hashKey] = new DictionaryContent(hash, true);
                }
#if DEBUG
                Console.WriteLine("Check of file {0} resulted in {1}, key {2}, hash {3}, in db {4}", sourcePath, result, hashKey, hash, hashDbFile);
#endif
            }
            return(result);
        }
Exemplo n.º 18
0
 public override int GetHashCode()
 {
     return(DictionaryKey.GetHashCode());
 }
Exemplo n.º 19
0
        protected virtual void AddWordToDictionary
        (
            string line,
            List <KeyValuePair <DictionaryKey, CyrAdjective> > adjectives,
            List <string>[] masculineWordCandidates,
            List <string>[] feminineWordCandidates,
            List <string>[] neuterWordCandidates,
            List <string>[] pluralWordCandidates
        )
        {
            string[] parts = line.Split(' ');

            int ruleIndex = int.Parse(parts[1]);

            CyrRule[]    rules     = this.rules[ruleIndex];
            CyrAdjective adjective = new CyrAdjective(parts[0], rules);

            // Женский и средний род склоняются одинаково для одушевленных и неодушевленных предметов.
            {
                CyrResult result = adjective.Decline(GendersEnum.Feminine, AnimatesEnum.Animated);

                foreach (CasesEnum @case in cases)
                {
                    feminineWordCandidates[(int)@case - 1].Add(result[(int)@case]);

                    foreach (AnimatesEnum animate in this.animates)
                    {
                        DictionaryKey key = new DictionaryKey(result[(int)@case], GendersEnum.Feminine, @case, NumbersEnum.Singular, animate);
                        adjectives.Add(new KeyValuePair <DictionaryKey, CyrAdjective>(key, adjective));
                    }
                }
            }
            {
                CyrResult result = adjective.Decline(GendersEnum.Neuter, AnimatesEnum.Animated);

                foreach (CasesEnum @case in cases)
                {
                    neuterWordCandidates[(int)@case - 1].Add(result[(int)@case]);

                    foreach (AnimatesEnum animate in this.animates)
                    {
                        DictionaryKey key = new DictionaryKey(result[(int)@case], GendersEnum.Neuter, @case, NumbersEnum.Singular, animate);
                        adjectives.Add(new KeyValuePair <DictionaryKey, CyrAdjective>(key, adjective));
                    }
                }
            }

            // Мужской род и множественное число склоняются по-разному для одушевленных и неодушевленных предметов.
            foreach (AnimatesEnum animate in animates)
            {
                CyrResult result = adjective.Decline(GendersEnum.Masculine, animate);

                foreach (CasesEnum @case in cases)
                {
                    DictionaryKey key = new DictionaryKey(result[(int)@case], GendersEnum.Masculine, @case, NumbersEnum.Singular, animate);
                    adjectives.Add(new KeyValuePair <DictionaryKey, CyrAdjective>(key, adjective));
                    masculineWordCandidates[(int)@case - 1].Add(key.Name);
                }

                result = adjective.DeclinePlural(animate);

                foreach (CasesEnum @case in cases)
                {
                    DictionaryKey key = new DictionaryKey(result[(int)@case], 0, @case, NumbersEnum.Plural, animate);
                    adjectives.Add(new KeyValuePair <DictionaryKey, CyrAdjective>(key, adjective));
                    pluralWordCandidates[(int)@case - 1].Add(key.Name);
                }
            }
        }
Exemplo n.º 20
0
        public void Iteration()
        {
            var axisSet = new AxisSet(new Axis []
            {
                new Axis("Axis 1", typeof(string), true),
                new Axis("Axis 2", typeof(string), true),
                new Axis("Expiry Date", typeof(DateTime), true)
            });

            var cube             = new Cube.Cube <CubeValueDouble>(axisSet);
            var simpleDictionary = new Dictionary <DictionaryKey, double>();

            var refDate = DateTime.Today;

            for (int loopIdx1 = 0; loopIdx1 < 10; loopIdx1++)
            {
                for (int loopIdx2 = 0; loopIdx2 < 10; loopIdx2++)
                {
                    for (int loopIdx3 = 0; loopIdx3 < 100; loopIdx3++)
                    {
                        object [] keys = new object [3];
                        keys [0] = string.Format("Axis 1 - {0}", loopIdx1);
                        keys [1] = string.Format("Axis 2 - {0}", loopIdx2);
                        keys [2] = refDate.AddDays(loopIdx3);

                        CubeValueDouble val = new CubeValueDouble();
                        val.Val  = loopIdx1 * 1000;
                        val.Val += loopIdx2 * 100;
                        val.Val += loopIdx3;
                        cube.AddItem(keys, val);

                        simpleDictionary [new DictionaryKey((string)keys [0], (string)keys [1], (DateTime)keys [2])] = val.Val;
                    }
                }
            }

            // Check random access
            {
                CubeValueDouble matchedValue;
                Assert.IsTrue(cube.TryGetValue(new object [] { "Axis 1 - 5", "Axis 2 - 7", refDate.AddDays(22) }, out matchedValue));
                Assert.AreEqual(5722, matchedValue.Val);
            }

            // Ensure that we can iterate over each point in a cube
            foreach (var cubePoint in cube)
            {
                string   axis1 = (string)cubePoint.GetAxisValue(0);
                string   axis2 = (string)cubePoint.GetAxisValue(1);
                DateTime date  = (DateTime)cubePoint.GetAxisValue(2);

                var    dictKey = new DictionaryKey(axis1, axis2, date);
                double expectedValue;
                if (!simpleDictionary.TryGetValue(dictKey, out expectedValue))
                {
                    Assert.Fail("No value found for key");
                }

                simpleDictionary.Remove(dictKey);

                Assert.AreEqual(expectedValue, cubePoint.CubeValue.Val);
            }

            Assert.AreEqual(0, simpleDictionary.Count);
        }
Exemplo n.º 21
0
 protected bool Equals(DictionaryKey other)
 {
     return(Key == other.Key && TypeName == other.TypeName);
 }
Exemplo n.º 22
0
 /// <summary> Update value after change any key </summary>
 public void UpdateValue()
 {
     ValueText.text = DictionaryKey.TryGetOrDefault(ActionKey).ToString();
 }