示例#1
0
        /// <summary>
        /// Alter the lex entirely including all of its sublex
        /// </summary>
        /// <param name="context">Contextual nature of the request.</param>
        /// <param name="obfuscationLevel">-100 to 100 range.</param>
        /// <returns>the new lex</returns>
        private ILexica Mutate(MessagingType sensoryType, short obfuscationLevel = 0)
        {
            IDictata dict   = GetDictata();
            ILexica  newLex = Clone();

            if (dict != null)
            {
                IDictata newDict = null;
                if (obfuscationLevel != 0)
                {
                    newDict = Thesaurus.ObscureWord(dict, obfuscationLevel);
                }
                else if (Type != LexicalType.ProperNoun &&
                         (Context.Severity + Context.Elegance + Context.Quality > 0 ||
                          Context.Language != dict.Language ||
                          Context.Plural != dict.Plural ||
                          Context.Possessive != dict.Possessive ||
                          Context.Tense != dict.Tense ||
                          Context.Perspective != dict.Perspective ||
                          Context.Determinant != dict.Determinant ||
                          Context.GenderForm.Feminine != dict.Feminine))
                {
                    newDict = Thesaurus.GetSynonym(dict, Context);
                }

                if (newDict != null)
                {
                    newLex.Phrase = newDict.Name;
                }
            }

            return(newLex);
        }
示例#2
0
        public IActionResult GetThesaurus(
            [FromRoute] string database,
            [FromRoute] string id,
            [FromQuery] bool emptyIfNotFound)
        {
            ICadmusRepository repository =
                _repositoryProvider.CreateRepository(database);
            Thesaurus thesaurus = repository.GetThesaurus(id);

            if (thesaurus == null)
            {
                return(emptyIfNotFound
                    ? Ok(new ThesaurusModel
                {
                    Id = id,
                    Language = "en",
                    Entries = Array.Empty <ThesaurusEntry>()
                })
                    : (IActionResult)NotFound());
            }

            ThesaurusModel model = new ThesaurusModel
            {
                Id       = thesaurus.Id,
                Language = thesaurus.GetLanguage(),
                Entries  = thesaurus.GetEntries().ToArray()
            };

            return(Ok(model));
        }
示例#3
0
        public ActionResult <Dictionary <string, ThesaurusModel> > GetThesauri(
            [FromRoute] string database,
            [FromRoute] string ids,
            [FromQuery] bool purgeIds)
        {
            ICadmusRepository repository =
                _repositoryProvider.CreateRepository(database);
            Dictionary <string, ThesaurusModel> dct =
                new Dictionary <string, ThesaurusModel>();

            foreach (string id in (ids ?? "")
                     .Split(',', StringSplitOptions.RemoveEmptyEntries)
                     .Distinct())
            {
                Thesaurus thesaurus = repository.GetThesaurus(id);
                if (thesaurus == null)
                {
                    continue;
                }
                dct[purgeIds ? PurgeThesaurusId(id) : id] = new ThesaurusModel
                {
                    Id       = thesaurus.Id,
                    Language = thesaurus.GetLanguage(),
                    Entries  = thesaurus.GetEntries().ToArray()
                };
            }
            return(Ok(dct));
        }
示例#4
0
        public void HandleSpan(MessageSink messageSink, MessageActionSpan actionSpan)
        {
            if (DateTime.Now.Subtract(lastdoge).Seconds <= 10)
            {
                var prefix = actionSpan.Match.Groups[1].ToString();
                var word   = actionSpan.Match.Groups[2].ToString();

                var thesaurus = new Thesaurus(word);

                if (thesaurus.Success)
                {
                    var message = "";

                    foreach (var p in DogeRegEx)
                    {
                        if (thesaurus.Synonyms.Count == 0)
                        {
                            break;
                        }
                        if (p != prefix)
                        {
                            var pos = rnd.Next(thesaurus.Synonyms.Count - 1);
                            message += p + " " + thesaurus.Synonyms[pos] + "\n";
                            thesaurus.Synonyms.RemoveAt(pos);
                        }
                    }

                    messageSink(message);
                }
            }

            lastdoge = DateTime.Now;
        }
示例#5
0
        private Thesaurus ParseSource(XElement sourceElem, string id,
                                      bool authors)
        {
            if (sourceElem == null)
            {
                return(null);
            }

            Thesaurus thesaurus = new Thesaurus(
                $"apparatus-{(authors? "authors":"witnesses")}.{id}@en");

            foreach (XElement child in sourceElem
                     .Elements(XmlHelper.TEI + (authors? "bibl" : "witness")))
            {
                string value = _wsRegex.Replace(child.Value, " ").Trim();

                // prepend @n if @ref
                if (child.Attribute("ref") != null)
                {
                    value = child.Attribute("n").Value + value;
                }

                var entry = new ThesaurusEntry(
                    child.Attribute(XmlHelper.XML + "id").Value,
                    ReduceLabel(value));

                thesaurus.AddEntry(entry);
            }

            return(thesaurus);
        }
示例#6
0
        public bool RequiresStop(string arg)
        {
            thes = DialogueManager.thes;
            string funcName = arg.Substring(0, arg.IndexOf("("));

            return(thes.IsSynonym("random", funcName) || thes.IsSynonym("comparevar", funcName) || thes.IsSynonym("goto", funcName) || thes.IsSynonym("loadfile", funcName) || thes.IsSynonym("wait", funcName));
        }
示例#7
0
        public void DeduplicateYieldsListOfDistinctCanonicalForms(string text, string expectedDeduplicated)
        {
            var expectedTerms = expectedDeduplicated.Split(' ').OrderBy(term => term);
            var deduped       = new Thesaurus(_synonyms).Dedupe(text.Split(' ')).OrderBy(term => term);

            Assert.IsTrue(expectedTerms.SequenceEqual(deduped), $"Expected [{ string.Join(", ", expectedTerms) }] but was [{ string.Join(", ", deduped) }].");
        }
        public ActionResult DeleteConfirmed(int id)
        {
            Thesaurus thesaurus = db.Thesauruss.Find(id);

            db.Thesauruss.Remove(thesaurus);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 public void Setup()
 {
     request   = new ThesaurusRequest();
     response  = new ThesaurusResponse();
     thesaurus = new Thesaurus();
     testData  = new LinkedList <string[]>();
     testData.AddLast(new string[] { "good", "alright", "alright", "alright", "alright" });
     testData.AddLast(new string[] { "bad", "crummy", "crummy", "crummy", "crummy" });
 }
示例#10
0
 public void GetPhrasePermutationsTest()
 {
     Thesaurus target = new Thesaurus("..\\..\\..\\watch_assistant\\thesaurus.dic"); // TODO: инициализация подходящего значения
     string phrase = "красивый       <!#5>автомобиль. {15} ,ехал, \nпо         дороге, автомобильбудус"; // TODO: инициализация подходящего значения тестовая фраза, предназначенная для определения ошибок в алгоритме поиска интервалов подразделения.
     string[] expected = null; // TODO: инициализация подходящего значения
     string[] actual;
     actual = target.GetPhrasePermutations(phrase);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Проверьте правильность этого метода теста.");
 }
 public ActionResult Edit([Bind(Include = "Id,Senten")] Thesaurus thesaurus)
 {
     if (ModelState.IsValid)
     {
         db.Entry(thesaurus).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(thesaurus));
 }
示例#12
0
 public void ThesaurusConstructorThrowsForDuplicateLemmas()
 {
     Assert.ThrowsException <InvalidDataException>(() => {
         _ = new Thesaurus(new[]
         {
             new[] { "foo", "bar" },
             new[] { "baz", "bar" }
         });
     });
 }
        public ActionResult Create([Bind(Include = "Id,Senten")] Thesaurus thesaurus)
        {
            if (ModelState.IsValid)
            {
                db.Thesauruss.Add(thesaurus);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(thesaurus));
        }
示例#14
0
文件: Class1.cs 项目: Tilps/Stash
 static void Main(string[] args)
 {
     Thesaurus a = new Thesaurus();
     string[] results = a.edit(new string[] {"a b c", "d e f", "g h i", "b g c e f"});
     for (int i=0; i< results.Length;i++) {
         Console.Out.WriteLine("{0}",
             results[i]
             );
     }
     Console.In.ReadLine();
 }
示例#15
0
        public ApplicationData()
        {
            var folder        = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            var thesaurusPath = Path.Combine(folder, "Synonyms");

            if (!Directory.Exists(thesaurusPath))
            {
                Directory.CreateDirectory(thesaurusPath);
            }
            Thesaurus = new Thesaurus(thesaurusPath);
        }
        /// <summary>
        /// This will be be run several times during execution i.e. before every test function
        /// </summary>
        public ThesaurusTest()
        {
            mockObject = new Thesaurus();
            result     = new Result();
            DbContextOptionsBuilder <ThesaurusContext> dbContextBuilder = new DbContextOptionsBuilder <ThesaurusContext>();

            dbContextBuilder.UseSqlServer($"server={ServerConfig.Server};uid={ServerConfig.User};pwd={ServerConfig.Password};database={ServerConfig.Database}");
            this.context = new ThesaurusContext(dbContextBuilder.Options);
            // Delete all rows before execution
            context.Database.ExecuteSqlCommand("TRUNCATE TABLE Word");
            context.Database.ExecuteSqlCommand("TRUNCATE TABLE MeaningGroup");
        }
示例#17
0
        /// <summary>
        /// Gets a thesaurus from this object.
        /// </summary>
        /// <returns>Thesaurus.</returns>
        public Thesaurus ToThesaurus()
        {
            Thesaurus thesaurus = new Thesaurus(Id)
            {
                TargetId = TargetId
            };

            foreach (MongoThesaurusEntry entry in Entries)
            {
                thesaurus.AddEntry(entry.ToThesaurusEntry());
            }
            return(thesaurus);
        }
        // GET: Thesaurus/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Thesaurus thesaurus = db.Thesauruss.Find(id);

            if (thesaurus == null)
            {
                return(HttpNotFound());
            }
            return(View(thesaurus));
        }
        public void Handle(MessageSink messageSink, Command command)
        {
            var thesaurus = new Thesaurus(command.FullArguments);
            var message   = "Synonyms for '" + command.FullArguments + "': ";

            if (thesaurus.Success)
            {
                foreach (var synonym in thesaurus.Synonyms)
                {
                    message += synonym + ", ";
                }
                messageSink(message);
            }
        }
示例#20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MongoThesaurus"/> class.
        /// </summary>
        /// <param name="thesaurus">The set to load data from.</param>
        /// <exception cref="ArgumentNullException">null set</exception>
        public MongoThesaurus(Thesaurus thesaurus)
        {
            if (thesaurus == null)
            {
                throw new ArgumentNullException(nameof(thesaurus));
            }

            Id       = thesaurus.Id;
            TargetId = thesaurus.TargetId;
            Entries  = new List <MongoThesaurusEntry>();
            foreach (ThesaurusEntry entry in thesaurus.GetEntries())
            {
                Entries.Add(new MongoThesaurusEntry(entry));
            }
        }
        static void Main(string[] args)
        {
            var       json       = File.ReadAllText(@"lojbantan-zei-jbovlaste.json");
            var       dictionary = OneToManyJsonSerializer.Deserialize(json);
            Thesaurus thesaurus  = JsonSerializer.Deserialize <Thesaurus>(File.ReadAllText(@"relations.json"));

            foreach (var word in dictionary.Words.Where(word => !word.Tags.Contains("ラフシ") && !word.Tags.Contains("語根《ラフシ》")))
            {
                word.Relations = new List <Relation>();
            }

            foreach (var tagFamily in thesaurus.TagFamilies)
            {
                var words = dictionary.Words.Where(word => word.Tags.Contains(tagFamily.Tag));
                foreach (var category in tagFamily.Categories)
                {
                    var relations = new List <Relation>();
                    foreach (var group in category.Groups)
                    {
                        foreach (var relationWord in group.Relations)
                        {
                            relations.Add(new Relation
                            {
                                Title = group.Title,
                                Entry = dictionary.Words.First(word => word.Entry.Form == relationWord && word.Tags.Contains(tagFamily.Tag)).Entry
                            });
                        }
                    }
                    foreach (var group in category.Groups)
                    {
                        foreach (var relationWord in group.Relations)
                        {
                            var word = dictionary.Words.First(w => w.Entry.Form == relationWord && w.Tags.Contains(tagFamily.Tag));
                            word.Relations = word.Relations.Union(relations).ToList();
                        }
                    }
                }
            }

            var options = new JsonSerializerOptions
            {
                Encoder       = JavaScriptEncoder.Create(UnicodeRanges.All),
                WriteIndented = true,
            };

            json = OneToManyJsonSerializer.Serialize(dictionary, options);
            File.WriteAllText(@"output.json", json);
        }
        public void Read_Profile_Ok()
        {
            string json = LoadProfile("SampleProfile.json");
            IDataProfileSerializer serializer = new JsonDataProfileSerializer();

            DataProfile profile = serializer.Read(json);

            // facets
            Assert.Single(profile.Facets);
            FacetDefinition facetDef = profile.Facets[0];

            Assert.Equal("facet-default", facetDef.Id);
            Assert.Equal("default", facetDef.Label);
            Assert.Equal("The default facet", facetDef.Description);
            Assert.Equal("FF0000", facetDef.ColorKey);
            Assert.Equal(7, facetDef.PartDefinitions.Count);

            // TODO: check each facet definition

            // flags
            Assert.Single(profile.Flags);
            FlagDefinition flagDef = profile.Flags[0];

            Assert.Equal(1, flagDef.Id);
            Assert.Equal("to revise", flagDef.Label);
            Assert.Equal("The item must be revised.", flagDef.Description);
            Assert.Equal("F08080", flagDef.ColorKey);

            // thesauri
            Assert.Equal(2, profile.Thesauri.Length);
            Thesaurus thesaurus = Array.Find(profile.Thesauri,
                                             t => t.Id == "categories@en");

            Assert.NotNull(thesaurus);
            Assert.Equal(16, thesaurus.GetEntries().Count);
            // TODO: check each entry

            thesaurus = Array.Find(profile.Thesauri,
                                   t => t.Id == "languages@en");
            Assert.NotNull(thesaurus);
            Assert.Equal(8, thesaurus.GetEntries().Count);
            // TODO: check each entry
        }
示例#23
0
        public void ThesaurusBuildsNormalizedSynonymToCanonicalFormDictionaryAndIgnoresEmptyLemmas()
        {
            const string canonicalAcronym   = "acronym";
            const string canonicalMicrosoft = "Microsoft";
            var          synonyms           = new Thesaurus(new[]
            {
                new[] { canonicalAcronym, "acornym", "acronyms" },
                Array.Empty <string>(),
                new[] { canonicalMicrosoft, "Microsoft Corporation", "Microsoft corp.", "MSFT" }
            }).Synonyms;

            Assert.AreEqual(7, synonyms.Count());
            Assert.AreEqual(canonicalAcronym, synonyms["acronym"]);
            Assert.AreEqual(canonicalAcronym, synonyms["acornym"]);
            Assert.AreEqual(canonicalAcronym, synonyms["acronyms"]);
            Assert.AreEqual(canonicalMicrosoft, synonyms["microsoft"]);
            Assert.AreEqual(canonicalMicrosoft, synonyms["microsoftcorporation"]);
            Assert.AreEqual(canonicalMicrosoft, synonyms["microsoftcorp"]);
            Assert.AreEqual(canonicalMicrosoft, synonyms["msft"]);
        }
示例#24
0
    void Awake()
    {
        System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.NeutralCultures)[0];

        appPath = Application.streamingAssetsPath;

        dialogueLine = new List <int>(1)
        {
            0
        };

        parser        = new TextParser(this);
        choiceManager = new ChoiceManager();
        charManager   = new CharacterManager(startingCast);

        themeConstructor = new ThemeConstructor(this);

        uiConstructor = new UIConstructor();
        uiManager     = new UIManager(this, uiConstructor.ConstructText(Color.black), uiConstructor.ConstructGroup(1, false, Color.gray), uiConstructor.ConstructCanvas(), uiConstructor.ConstructButton(Color.black, Color.black), uiConstructor.ConstructGroup(0, false, Color.gray), uiConstructor.ConstructLayoutGroup());

        varManager      = new VariableManager();
        functionManager = new FunctionManager(this);

        //Base starting values
        if (startWithExposition)
        {
            varManager.SetVar(new string[] { "charVisible=0" });
        }
        else
        {
            varManager.SetVar(new string[] { "charVisible=1" });
        }
        varManager.SetVar(new string[] { "typeRate=" + startingTextSpeed });
        varManager.SetVar(new string[] { "buildV=" + version });
        varManager.SetVar(new string[] { "pitch=1" });

        thes      = new Thesaurus("Default");
        uiManager = themeConstructor.ConstructTheme("Default");
    }
示例#25
0
        private static Thesaurus ReadThesaurus(JsonElement thesEl)
        {
            string    id        = thesEl.GetProperty("id").GetString();
            Thesaurus thesaurus = new Thesaurus(id);

            if (thesEl.TryGetProperty("targetId", out JsonElement targetEl))
            {
                thesaurus.TargetId = targetEl.GetString();
            }
            else
            {
                foreach (JsonElement entryEl in thesEl.GetProperty("entries")
                         .EnumerateArray())
                {
                    thesaurus.AddEntry(new ThesaurusEntry
                    {
                        Id    = entryEl.GetProperty("id").GetString(),
                        Value = entryEl.GetProperty("value").GetString()
                    });
                }
            }
            return(thesaurus);
        }
示例#26
0
        public Thesaurus[] Parse(XDocument doc, string id)
        {
            if (doc == null)
            {
                throw new ArgumentNullException(nameof(doc));
            }
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }

            id = id.ToLowerInvariant();

            XElement sourceDescElem = doc.Root
                                      .Element(XmlHelper.TEI + "teiHeader")
                                      .Element(XmlHelper.TEI + "fileDesc")
                                      .Elements(XmlHelper.TEI + "sourceDesc")
                                      .FirstOrDefault(e => e.Elements()
                                                      .Any(c => c.Name == XmlHelper.TEI + "listWit"));

            Thesaurus witnesses = ParseSource(sourceDescElem
                                              .Element(XmlHelper.TEI + "listWit")
                                              .Element(XmlHelper.TEI + "listWit"),
                                              id, false);

            Thesaurus authors = ParseSource(sourceDescElem
                                            .Element(XmlHelper.TEI + "listBibl")
                                            .Element(XmlHelper.TEI + "listBibl"),
                                            id, true);

            if (witnesses == null && authors == null)
            {
                return(null);
            }

            return(new[] { witnesses, authors });
        }
示例#27
0
        public IActionResult AddThesaurus(
            [FromRoute] string database,
            [FromBody] ThesaurusBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            ICadmusRepository repository = _repositoryProvider.CreateRepository(database);
            Thesaurus         thesaurus  = new Thesaurus(model.Id);

            foreach (ThesaurusEntryBindingModel entry in model.Entries)
            {
                thesaurus.AddEntry(new ThesaurusEntry(entry.Id, entry.Value));
            }
            repository.AddThesaurus(thesaurus);

            return(CreatedAtRoute("GetThesaurus", new
            {
                database,
                id = thesaurus.Id
            }, thesaurus));
        }
示例#28
0
        /// <summary>
        /// Add language translations for this
        /// </summary>
        public void FillLanguages()
        {
            IGlobalConfig globalConfig = ConfigDataCache.Get <IGlobalConfig>(new ConfigDataCacheKey(typeof(IGlobalConfig), "LiveSettings", ConfigDataType.GameWorld));

            //Don't do this if: we have no config, translation is turned off or lacking in the azure key, the language is not a human-ui language
            //it isn't an approved language, the word is a proper noun or the language isnt the base language at all
            if (globalConfig == null || !globalConfig.TranslationActive || string.IsNullOrWhiteSpace(globalConfig.AzureTranslationKey) ||
                !Language.UIOnly || !Language.SuitableForUse || ContainedTypes().Contains(LexicalType.ProperNoun) || Language != globalConfig.BaseLanguage)
            {
                return;
            }

            IEnumerable <ILanguage> otherLanguages = ConfigDataCache.GetAll <ILanguage>().Where(lang => lang != Language && lang.SuitableForUse && lang.UIOnly);

            foreach (ILanguage language in otherLanguages)
            {
                short  formGrouping = -1;
                string newName      = string.Empty;

                Lexeme newLexeme = new Lexeme()
                {
                    Language = language
                };

                foreach (IDictata word in WordForms)
                {
                    LexicalContext context = new LexicalContext(null)
                    {
                        Language    = language,
                        Perspective = word.Perspective,
                        Tense       = word.Tense,
                        Position    = word.Positional,
                        Determinant = word.Determinant,
                        Plural      = word.Plural,
                        Possessive  = word.Possessive,
                        Elegance    = word.Elegance,
                        Quality     = word.Quality,
                        Semantics   = word.Semantics,
                        Severity    = word.Severity,
                        GenderForm  = new Gender()
                        {
                            Feminine = word.Feminine
                        }
                    };

                    IDictata translatedWord = Thesaurus.GetSynonym(word, context);

                    //no linguistic synonym
                    if (translatedWord == this)
                    {
                        string newWord = Thesaurus.GetTranslatedWord(globalConfig.AzureTranslationKey, Name, Language, language);

                        if (!string.IsNullOrWhiteSpace(newWord))
                        {
                            newName        = newWord;
                            newLexeme.Name = newName;

                            Dictata newDictata = new Dictata(newWord, formGrouping++)
                            {
                                Elegance       = word.Elegance,
                                Severity       = word.Severity,
                                Quality        = word.Quality,
                                Determinant    = word.Determinant,
                                Plural         = word.Plural,
                                Perspective    = word.Perspective,
                                Feminine       = word.Feminine,
                                Positional     = word.Positional,
                                Possessive     = word.Possessive,
                                Semantics      = word.Semantics,
                                Antonyms       = word.Antonyms,
                                Synonyms       = word.Synonyms,
                                PhraseAntonyms = word.PhraseAntonyms,
                                PhraseSynonyms = word.PhraseSynonyms,
                                Tense          = word.Tense,
                                WordType       = word.WordType
                            };

                            newDictata.Synonyms = new HashSet <IDictata>(word.Synonyms)
                            {
                                word
                            };
                            word.Synonyms = new HashSet <IDictata>(word.Synonyms)
                            {
                                newDictata
                            };
                            newLexeme.AddNewForm(newDictata);
                        }
                    }
                }

                if (newLexeme.WordForms.Count() > 0)
                {
                    newLexeme.SystemSave();
                    newLexeme.PersistToCache();
                }
            }

            SystemSave();
            PersistToCache();
        }
示例#29
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public Thesaurus()
 {
     thesaurus = this;
 }
示例#30
0
 /// <summary>
 /// Formal constructor.
 /// </summary>
 /// <param name="word">Rumi word.</param>
 /// <param name="translate">Jawi or Arabic value.</param>
 public Thesaurus(string word, string translate)
 {
     rumi = word;
     jawi = translate;
     thesaurus = this;
 }
示例#31
0
            private static string Replace(string roman, string original, Thesaurus thes)
            {
                string old = "";
                string source = thes.Rumi;
                foreach (char c in source)
                    old += JawiTranslator.MapArabicCharacter(Arabic.CharSet, c.ToString());
                int i = roman.IndexOf(thes.Rumi, 0);
                if (i > -1) original = original.Replace(old, thes.Jawi);

                return original;
            }
示例#32
0
 public void NormalizeLowersCaseRemovesPunctuationAndSpaces(string word, string expectedNormalized)
 => Assert.AreEqual(expectedNormalized.Normalize(), Thesaurus.Normalize(word));
示例#33
0
        public void InterpretFunction(string line)
        {
            string arg = line.Substring(line.IndexOf("(")).Replace("(", "").Replace(")", "");

            line = line.ToLower();
            string funcName = line.Substring(0, line.IndexOf("("));

            thes = DialogueManager.thes;
            if (thes.IsSynonym("opentheme", funcName))
            {
                DialogueManager.uiManager = themeConstructor.ConstructTheme(arg);
            }
            else if (thes.IsSynonym("savetheme", funcName))
            {
                themeSaver.CreateTheme(arg);
                DialogueManager.uiManager.ResetUI();
                DialogueManager.uiManager = themeConstructor.ConstructTheme(arg);
            }
            else if (thes.IsSynonym("setpersistentvar", funcName))
            {
                arg = arg.Replace(" ", "");
                varManager.SetVar(parser.ParseParameters(arg), true);
            }
            else if (thes.IsSynonym("setvar", funcName))
            {
                arg = arg.Replace(" ", "");
                varManager.SetVar(parser.ParseParameters(arg));
            }
            else if (thes.IsSynonym("resetvar", funcName))
            {
                arg = arg.Replace(" ", "");
                varManager.ResetVar();
            }
            else if (thes.IsSynonym("comparevar", funcName))
            {
                string[] statements = parser.ParseParameters(arg);
                bool     hasElse    = statements[statements.Length - 1] == "else";
                DialogueManager.uiManager.choices = new string[statements.Length];
                int index = varManager.CompareVar(statements) - 1;
                if (index >= 0)
                {
                    DialogueManager.uiManager.ChooseChoice(index);
                }
                else if (hasElse)
                {
                    DialogueManager.uiManager.ChooseChoice(DialogueManager.uiManager.choices.Length - 1);
                }
                else
                {
                    dialogue.FallThrough();
                    DialogueManager.currentlyActiveChoice.choicesPassed += DialogueManager.uiManager.choices.Length;
                }
            }
            else if (thes.IsSynonym("setcast", funcName))
            {
                charManager.SetCharacterCast(parser.ParseParameters(arg));
            }
            else if (thes.IsSynonym("setchar", funcName))
            {
                charManager.SetCurrentChar(arg);
            }
            else if (thes.IsSynonym("random", funcName))
            {
                arg = arg.Replace(" ", "");
                Random(parser.ParseParameters(arg));
            }
            else if (thes.IsSynonym("goto", funcName))
            {
                arg = arg.Replace(" ", "");
                GotoKey(arg);
            }
            else if (thes.IsSynonym("setkey", funcName))
            {
                arg = arg.Replace(" ", "");
                varManager.SetKey(arg);
            }
            else if (thes.IsSynonym("loadthes", funcName))
            {
                arg = arg.Replace(" ", "");
                DialogueManager.thes = new Thesaurus(arg);
            }
            else if (thes.IsSynonym("requirechar", funcName))
            {
                string val = (arg.ToLower() == "false" ? "0" : "1");
                varManager.SetVar(new string[] { "charVisible=" + val });
            }
            else if (thes.IsSynonym("setspeed", funcName))
            {
                if (arg == "d" || arg == "default")
                {
                    arg = dialogue.startingTextSpeed + "";
                }
                varManager.SetVar(new string[] { "typeRate=" + arg });
            }
            else if (thes.IsSynonym("loadfile", funcName))
            {
                string[] args = parser.ParseParameters(arg);
                DialogueManager.parser.MakeTree(args[1].Replace(" ", ""), args[0]);
                DialogueManager.dialogueLine = new List <int>(1)
                {
                    0
                };
                dialogue.StartReading(DialogueManager.parser.dialogue);
            }
            else if (thes.IsSynonym("wait", funcName))
            {
                if (float.TryParse(arg, out float t))
                {
                    dialogue.FallThrough(t);
                }
                else
                {
                    throw new Exception("Snow# 4: Argument of the '$Wait' function must be a numerical value. Value found was: [" + arg + "]");
                }
            }
            else if (thes.IsSynonym("quit", funcName))
            {
                Application.Quit();
            }
        }
示例#34
0
        /// <summary>
        /// Unpacks this applying language rules to expand and add articles/verbs where needed
        /// </summary>
        /// <param name="overridingContext">The full lexical context</param>
        /// <returns>A long description</returns>
        public IEnumerable <ILexica> Unpack(MessagingType sensoryType, short strength, LexicalContext overridingContext = null)
        {
            if (overridingContext != null)
            {
                IGlobalConfig globalConfig = ConfigDataCache.Get <IGlobalConfig>(new ConfigDataCacheKey(typeof(IGlobalConfig), "LiveSettings", ConfigDataType.GameWorld));

                //Sentence must maintain the same language, tense and personage
                Context.Language    = overridingContext.Language ?? Context.Language ?? globalConfig.BaseLanguage;
                Context.Tense       = overridingContext.Tense;
                Context.Perspective = overridingContext.Perspective;
                Context.Elegance    = overridingContext.Elegance;
                Context.Severity    = overridingContext.Severity;
                Context.Quality     = overridingContext.Quality;
            }

            ILexica newLex = Mutate(sensoryType, strength);

            foreach (IWordRule wordRule in Context.Language.WordRules.Where(rul => rul.Matches(newLex))
                     .OrderByDescending(rul => rul.RuleSpecificity()))
            {
                if (wordRule.NeedsArticle && (!wordRule.WhenPositional || Context.Position != LexicalPosition.None) &&
                    !newLex.Modifiers.Any(mod => (mod.Type == LexicalType.Article && !wordRule.WhenPositional && mod.Context.Position == LexicalPosition.None) ||
                                          (mod.Type == LexicalType.Preposition && wordRule.WhenPositional && mod.Context.Position != LexicalPosition.None)))
                {
                    LexicalContext articleContext = Context.Clone();

                    //Make it determinant if the word is plural
                    articleContext.Determinant = Context.Plural || articleContext.Determinant;

                    IDictata article = null;
                    if (wordRule.SpecificAddition != null)
                    {
                        article = wordRule.SpecificAddition;
                    }
                    else
                    {
                        article = Thesaurus.GetWord(articleContext, wordRule.WhenPositional ? LexicalType.Preposition : LexicalType.Article);
                    }

                    if (article != null && !newLex.Modifiers.Any(lx => article.Name.Equals(lx.Phrase, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        ILexica newArticle = newLex.TryModify(wordRule.WhenPositional ? LexicalType.Preposition : LexicalType.Article
                                                              , GrammaticalType.Descriptive, article.Name, false);

                        if (!wordRule.WhenPositional)
                        {
                            newArticle.Context.Position = LexicalPosition.None;
                        }
                    }
                }
                else if (wordRule.SpecificAddition != null && !newLex.Modifiers.Any(lx => wordRule.SpecificAddition.Equals(lx.GetDictata())))
                {
                    newLex.TryModify(wordRule.SpecificAddition.WordType, GrammaticalType.Descriptive, wordRule.SpecificAddition.Name);
                }

                if (!string.IsNullOrWhiteSpace(wordRule.AddPrefix) && !newLex.Phrase.StartsWith(wordRule.AddPrefix))
                {
                    newLex.Phrase = string.Format("{0}{1}", wordRule.AddPrefix, newLex.Phrase.Trim());
                }

                if (!string.IsNullOrWhiteSpace(wordRule.AddSuffix) && !newLex.Phrase.EndsWith(wordRule.AddSuffix))
                {
                    newLex.Phrase = string.Format("{1}{0}", wordRule.AddSuffix, newLex.Phrase.Trim());
                }
            }

            //Placement ordering
            List <Tuple <ILexica, int> > modifierList = new List <Tuple <ILexica, int> >
            {
                new Tuple <ILexica, int>(newLex, 0)
            };

            //modification rules ordered by specificity
            List <ILexica> currentModifiers = new List <ILexica>(newLex.Modifiers);

            foreach (ILexica modifier in currentModifiers)
            {
                foreach (IWordPairRule wordRule in Context.Language.WordPairRules.Where(rul => rul.Matches(newLex, modifier))
                         .OrderByDescending(rul => rul.RuleSpecificity()))
                {
                    if (wordRule.NeedsArticle && (!wordRule.WhenPositional || Context.Position != LexicalPosition.None) &&
                        !newLex.Modifiers.Any(mod => (mod.Type == LexicalType.Article && !wordRule.WhenPositional && mod.Context.Position == LexicalPosition.None) ||
                                              (mod.Type == LexicalType.Preposition && wordRule.WhenPositional && mod.Context.Position != LexicalPosition.None)))
                    {
                        LexicalContext articleContext = Context.Clone();

                        //Make it determinant if the word is plural
                        articleContext.Determinant = Context.Plural || articleContext.Determinant;

                        IDictata article = null;
                        if (wordRule.SpecificAddition != null)
                        {
                            article = wordRule.SpecificAddition;
                        }
                        else
                        {
                            article = Thesaurus.GetWord(articleContext, wordRule.WhenPositional ? LexicalType.Preposition : LexicalType.Article);
                        }

                        if (article != null && !newLex.Modifiers.Any(lx => article.Name.Equals(lx.Phrase, StringComparison.InvariantCultureIgnoreCase)))
                        {
                            ILexica newArticle = newLex.TryModify(wordRule.WhenPositional ? LexicalType.Preposition : LexicalType.Article
                                                                  , GrammaticalType.Descriptive, article.Name, false);

                            if (!wordRule.WhenPositional)
                            {
                                newArticle.Context.Position = LexicalPosition.None;
                            }
                        }
                    }
                    else if (wordRule.SpecificAddition != null && !newLex.Modifiers.Any(lx => wordRule.SpecificAddition.Equals(lx.GetDictata())))
                    {
                        newLex.TryModify(wordRule.SpecificAddition.WordType, GrammaticalType.Descriptive, wordRule.SpecificAddition.Name);
                    }


                    if (!string.IsNullOrWhiteSpace(wordRule.AddPrefix) && !newLex.Phrase.StartsWith(wordRule.AddPrefix))
                    {
                        newLex.Phrase = string.Format("{0}{1}", wordRule.AddPrefix, newLex.Phrase.Trim());
                    }

                    if (!string.IsNullOrWhiteSpace(wordRule.AddSuffix) && !newLex.Phrase.EndsWith(wordRule.AddSuffix))
                    {
                        newLex.Phrase = string.Format("{1}{0}", wordRule.AddSuffix, newLex.Phrase.Trim());
                    }
                }
            }

            foreach (ILexica modifier in newLex.Modifiers)
            {
                IWordPairRule rule = Context.Language.WordPairRules.OrderByDescending(rul => rul.RuleSpecificity())
                                     .FirstOrDefault(rul => rul.Matches(newLex, modifier));

                if (rule != null)
                {
                    int i = 0;
                    foreach (ILexica subModifier in modifier.Unpack(sensoryType, strength, overridingContext ?? Context).Distinct())
                    {
                        modifierList.Add(new Tuple <ILexica, int>(subModifier, rule.ModificationOrder + i++));
                    }
                }
            }

            return(modifierList.OrderBy(tup => tup.Item2).Select(tup => tup.Item1));
        }
示例#35
0
        public Task Run()
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("REPLACE APPARATUS THESAURI\n");
            Console.ResetColor();
            Console.WriteLine(
                $"Input file: {_inputPath}" +
                $"Database: {_dbName}\n");

            ILoggerFactory loggerFactory = new LoggerFactory();

            loggerFactory.AddSerilog(Log.Logger);
            Log.Logger.Information("REPLACE APPARATUS THESAURI");

            using Stream input = new FileStream(_inputPath, FileMode.Open,
                                                FileAccess.Read, FileShare.Read);

            JsonDocument doc = JsonDocument.Parse(input, new JsonDocumentOptions
            {
                AllowTrailingCommas = true
            });
            ICadmusRepository repository =
                _repositoryProvider.CreateRepository(_dbName);
            string msg;

            // 1) remove all the apparatus- thesauri
            int delCount = 0;

            foreach (string id in repository.GetThesaurusIds(new ThesaurusFilter
            {
                PageSize = 0,
                Id = "apparatus-"
            }))
            {
                if (!id.StartsWith("apparatus-"))
                {
                    continue;
                }

                delCount++;
                msg = "Deleting " + id;
                Console.WriteLine(msg);
                Log.Logger.Information(msg);

                if (!_isDry)
                {
                    repository.DeleteThesaurus(id);
                }
            }

            // 2) insert new apparatus- thesauri
            // this is the thesauri JSON file generated by import thesauri,
            // having a root array with each thesaurus as an item
            int addCount = 0;

            foreach (JsonElement el in doc.RootElement.EnumerateArray())
            {
                addCount++;
                Thesaurus thesaurus = ReadThesaurus(el);
                msg = "Adding thesaurus " + thesaurus.Id;
                Console.WriteLine(msg);
                Log.Logger.Information(msg);
                if (!_isDry)
                {
                    repository.AddThesaurus(thesaurus);
                }
            }

            Console.WriteLine($"Completed: deleted {delCount}, added {addCount}");
            return(Task.CompletedTask);
        }