internal static void InitializeUniqueEmailAddressSource() { var recordCount = Fixture.Words(FromDictionary.PersonEmailAddress).Data.Count; var generator = new SequentialGenerator(0, recordCount, listShouldBeUnique: true); _uniquePersonEmailAddressSource = new Words(generator, new CachedFileDictionaryRepository(), FromDictionary.PersonEmailAddress); }
public override void Execute() { currentNodeIndex = this.Parameter<int>("MapReduce.MapIndex"); topItemsCount = this.Parameter<int>("MapReduce.ItemsCount"); traceMessage = string.Format("AISTek.DataFlow.Sdk.Samples.MapReduce.Map({0})", currentNodeIndex); using (Perfomance.BeginTrace(traceMessage) .BindToConsole() .Start()) { var text = ReadFile(Task.InputFiles.First()); List<Word> results; using (Perfomance.Trace(traceMessage + ": Build groups").BindToConsole()) { results = (from g in (from word in Regex.Split(text, @"\W+") where word.Length > 2 group word by word into groups let word = groups.Key let count = groups.Count() select new {Word = word, Count = count}) orderby g.Count descending select new Word(g.Word, g.Count)) .ToList(); } using (Perfomance.Trace(traceMessage + ": Write results").BindToConsole()) { var resultSet = new Words(results.Take(topItemsCount)); resultSet.Serialize().ToExistingFile(Repository, Task.OutputFiles.First()); } } }
/// <summary> /// Gets the Words in the file with the specified dictionary name. /// This method is used by <see cref="AnonymousValueFixture"/>. /// </summary> /// <param name="dictionaryName">Name of the dictionary file.</param> /// <returns></returns> internal static Words Get(string dictionaryName) { if (!_cache.ContainsKey(dictionaryName)) { _cache[dictionaryName] = new Words(dictionaryName); } return _cache[dictionaryName]; }
/// <summary> /// Set up the class with the BackgroundWorker class being used for this comptuation (to allow for callbacks), the words in the document, the total /// number of tokens, and an indication of whether the results will be displayed onscreen or saved to file. /// </summary> /// <param name="bw">the BackgroundWorker class being used for this comptuation (to allow for callbacks)</param> /// <param name="words">an array of the words in the document</param> /// <param name="start_word">the word on which this frequency calculator will start counting (including punctuation marks) from the words array. /// The lowest allowable value for this parameter is 1.</param> /// <param name="start_word">the word on which this frequency calculator will stop counting (including punctuation marks) from the words array</param> /// <param name="tosave">whether the result will be saved to CSV (true) or displayed in the taskpane (false).</param> public FrequencyCalculation(BackgroundWorker bw, Words words, int start_word, int end_word, bool tosave) { this.bgWorker = bw; this.words = words; this.start_word = start_word; this.end_word = end_word; this.tosave = tosave; punctuation = IgnoreList.getIgnoreList(); this.ignoreNumbers = IgnoreList.ignoringNumbers(); }
public static string GetWord(Words word) { switch (Game1.CurrentLanguage) { case Language.English: return English[(int)word]; case Language.German: return German[(int)word]; case Language.Russian: return Russian[(int)word]; default: return English[(int)word]; } }
public void WhenGettingUniqueEmail_ThenReturnUniqueEmailsAcrossFixtureInstances() { var source = new Words(FromDictionary.PersonEmailAddress); var generatedValues = new List<string>(); var any2 = new AnonymousValueFixture(); PersonEquivalenceExtensions.InitializeUniqueEmailAddressSource(); generatedValues.Add(any2.Person.UniqueEmailAddress()); for (var i = 0; i < source.Data.Count - 1; i++) { generatedValues.Add(Any.Person.UniqueEmailAddress()); } generatedValues.Distinct().Count() .ShouldBe(generatedValues.Count); }
public static void Main() { dynamic The = new Words(); var poem = [email protected]. Or.maybe.its.not.I.cant.even.tell. But.theres.a.warmth.on.my.face. That.isnt.the.blood. And.my.tears.are.turning. The.snow.into.mud. And.I.cant.feel.my.left.leg. But.I.think.its.still.there. Did.I.kill.anybody. Hell.I.never.fight.fair. What.state.am.I.@in. Am.I.still.on.the.run. Has.it.really.been.so.@long. Since.Ive.seen.the.sun; }
public override void Execute() { takeTop = this.Parameter<int>("TakeTop"); var traceMessage = "AISTek.DataFlow.Sdk.Samples.HashDistribute.TakeTopList()"; using (Perfomance.BeginTrace(traceMessage) .BindToConsole() .Start()) { var groups = new List<Word>(); using (Perfomance.Trace(traceMessage + ": Read data").BindToConsole()) { foreach (var words in from file in Task.InputFiles let wordsContainer = Repository.Deserialize<Words>(file) select wordsContainer) { groups.AddRange(words); } } List<Word> resultGroups; using (Perfomance.Trace(traceMessage + ": Build list").BindToConsole()) { resultGroups = (from grp in (from g in groups group g by g.Value into grp let count = grp.Sum(x => x.Count) let word = grp.Key select new Word(word, count)) orderby grp.Count descending select grp) .Take(takeTop) .ToList(); } using (Perfomance.Trace(traceMessage + ": Write result").BindToConsole()) { var result = new Words(resultGroups); result.Serialize().ToExistingFile(Repository, Task.OutputFiles.First()); } } }
public override void Execute() { nextNodesCount = this.Parameter<int>("Layer.NextSize"); var nodeId = this.Parameter<int>("Node"); traceMessage = string.Format("AISTek.DataFlow.Sdk.Samples.HashDistribute.BuildWordsList({0})", nodeId); using (Perfomance.BeginTrace(traceMessage) .BindToConsole() .Start()) { var text = ReadFile(Task.InputFiles.First()); List<Group> wordGroups; using (Perfomance.Trace(traceMessage + ": Build groups").BindToConsole()) { wordGroups = (from word in Regex.Split(text, @"\W+") where word.Length > 2 group word by word into groups let word = groups.Key let count = groups.Count() let node = NodeHash(word, nextNodesCount) select new Group {Word = word, Node = node, Count = count}) .ToList(); } using (Perfomance.Trace(traceMessage + ": Write outputs").BindToConsole()) { for (var i = 0; i < nextNodesCount; i++) { var index = i; var link = Task.OutputFiles.First(x => x.Metadata["Node"] == index.ToString()); var words = new Words(from wordGroup in wordGroups where wordGroup.Node == index select new Word(wordGroup.Word, wordGroup.Count)); words.Serialize().ToExistingFile(Repository, link); } } } }
public static int getValue(string key, string code) { int i = 0; int z = 0; List<Words> k = new List<Words>(); List<Words> c = new List<Words>(); List<string> endcode = new List<string>(); foreach (char y in key) { Words x = new Words(); x.Letter = y.ToString(); x.Position = i; k.Add(x); i++; } foreach (char y in code) { Words x = new Words(); x.Letter = y.ToString(); x.Position = z; c.Add(x); z++; } foreach (Words x in c) { if (c.Contains(x)) { endcode.Add(x.Position.ToString()); } } string concat = string.Join(" ", endcode.ToArray()); int amount = int.Parse(Convert.ToInt32(concat)); return amount; }
public ActionResult Create(string userWord, string userSentence) { Words myWords = new Words(userWord, userSentence); return(RedirectToAction("Index")); }
/// <summary> /// Init. /// </summary> /// <param name="parent">the parent box of this box</param> /// <param name="tag">the html tag data of this box</param> public CssBoxImage(CssBox parent, HtmlTag tag) : base(parent, tag) { _imageWord = new CssRectImage(this); Words.Add(_imageWord); }
/// <summary> /// Determines if the VerbPhrase implies a possession relationship. E.g. in the sentence "They certainly have a lot of ideas." the /// VerbPhrase "certainly have" asserts a possessor possessee relationship between "They" and "a lot of ideas". /// </summary> /// <returns><c>true</c> if the VerbPhrase is a possessive relationship specifier; otherwise, <c>false</c>.</returns> private bool DetermineIsPossessive() => Words.OfVerb().DefaultIfEmpty().Last()?.IsPossessive ?? false;
private Punctuator deterimineEndOfClause() => Sentence.Words .SkipWhile(w => w != Words.Last()) .First(w => w is Punctuator) as Punctuator;
internal MenuItem(Action action, Words word) { State = State.Normal; Action = action; Dst = new Rectangle(0, 0, 0, 0); Word = word; }
public String Translate(Words words) { return(TranslateCore(words)); }
static void Main(string[] args) { List <float> frequencies = new List <float>(); Console.WriteLine("Вводите частоту, пока сумма не достигнет 1"); while (true) { float FuncSum(float a, float b) => a + b; float frequency = InputFloat(0, 1, FuncSum, frequencies); frequencies.Add(frequency); float sum = SumFloat(frequencies); if (sum == 1) { Console.WriteLine("Сумма частот равна 1, ввод закончен"); break; } } Console.WriteLine("\nВведенные частоты:"); frequencies.Sort(); frequencies.Reverse(); Console.WriteLine(String.Join(" ", frequencies)); List <BinaryTree> tree = new List <BinaryTree>(); foreach (var frequency in frequencies) { tree.Add(new BinaryTree(frequency)); } if (tree.Count == 1) { BinaryTree first = tree[0]; tree[0] = new BinaryTree(first.data); tree[0].right = first; } while (tree.Count > 1) { tree.Sort(); BinaryTree first = tree[0]; BinaryTree second = tree[1]; tree[1] = new BinaryTree(first.data + second.data); tree[1].right = first; tree[1].left = second; tree.RemoveAt(0); } List <string> codesList = Words.GetWords(tree[0]); Console.WriteLine("\nРезультат: "); Console.WriteLine(String.Join(" ", codesList)); Console.WriteLine("\nСредняя длина кодового слова(Код Хаффмана): " + GetHuffmanLength(frequencies, codesList)); Console.WriteLine("Длина минимальной равномерной схемы: " + GetUniformLength(codesList.Count)); Console.ReadLine(); }
public static Words[] AddToArray(ref Words[] array, Words newValue) { array = ResizeArray(array, 1); array[array.Length - 1] = newValue; return array; }
private void SaveButton_Click(object sender, System.EventArgs e) { int result = 0; switch (position) { case 0: Words word = new Words(); word.GroupId = groupSpinner.SelectedItemPosition + 1; word.SubGroupId = subgroupSpinner.SelectedItemPosition + 1; word.Word = contentText.Text; result = repository.Save(word); break; case 1: Sentences sentence = new Sentences(); sentence.Sentence = contentText.Text; result = repository.Save(sentence); break; case 2: Poems poem = new Poems(); poem.Title = poemTitleText.Text; poem.Poem = contentText.Text; result = repository.Save(poem); break; } string message = result == 1 ? "Zapisano" : "B³¹d zapisu!"; Toast.MakeText(this, message, ToastLength.Long).Show(); OnBackPressed(); }
public static Words[] ResizeArray(Words[] oldArray, int difference) { var newArray = new Words[oldArray.Length + difference]; for (var i = 0; i < oldArray.Length; i++) newArray[i] = oldArray[i]; return newArray; }
public static Words[] SearchElementStruct(ref Words[] distinctWords, string word) { var newValue = new Words { Word = word, NoOccurences = 1 }; for (var i = 0; i <= distinctWords.Length - 1; i++) if (string.CompareOrdinal(word, distinctWords[i].Word) == 0) { distinctWords[i].NoOccurences++; return distinctWords; } AddToArray(ref distinctWords, newValue); return distinctWords; }
public Parser() { Words = new Words(); Images = new List<Image>(); }
public ActionResult Index() { List <Words> allWords = Words.GetAll(); return(View(allWords)); }
/// <summary> /// Prepares viewModel for new file selection. /// </summary> public void FileRowIsAboutToChange() { currentFile = null; Words.Clear(); }
public static void GetOrderedWordsByNumberOfOccurrencesAndAlphabetic(Words[] words) { for (var i = 0; i < words.Length; i++) for (var k = i; k > 0; k--) { if ((words[k].NoOccurences > words[k - 1].NoOccurences)|| ((words[k].NoOccurences==words[k-1].NoOccurences)&& (string.CompareOrdinal(words[k].Word, words[k - 1].Word) < 0))) { Swap(ref words[k], ref words[k - 1]); } } }
/// <summary> /// Возвращает слово грамматики /// </summary> /// <param name="word">Символьное представление слова грамматики</param> /// <returns>Возвращает слово грамматики типа <see cref="Word"/> Word</returns> public virtual Word GetWord(string word) { return(Words.FirstOrDefault(item => item.Value == word)); }
public static Words[] GetDistinctWordsAndNumberOfWords(string[] text) { var distinctWords = new Words[0]; for (var i = 0; i < text.Length; i++) { SearchElementStruct(ref distinctWords, text[i]); } return distinctWords; }
private IEnumerator Examples() { // Synthesize Log.Debug("ExampleTextToSpeech.Examples()", "Attempting synthesize."); _textToSpeech.Voice = VoiceType.en_US_Allison; _textToSpeech.ToSpeech(HandleToSpeechCallback, OnFail, _testString, true); while (!_synthesizeTested) { yield return(null); } // Get Voices Log.Debug("ExampleTextToSpeech.Examples()", "Attempting to get voices."); _textToSpeech.GetVoices(OnGetVoices, OnFail); while (!_getVoicesTested) { yield return(null); } // Get Voice Log.Debug("ExampleTextToSpeech.Examples()", "Attempting to get voice {0}.", VoiceType.en_US_Allison); _textToSpeech.GetVoice(OnGetVoice, OnFail, VoiceType.en_US_Allison); while (!_getVoiceTested) { yield return(null); } // Get Pronunciation Log.Debug("ExampleTextToSpeech.Examples()", "Attempting to get pronunciation of {0}", _testWord); _textToSpeech.GetPronunciation(OnGetPronunciation, OnFail, _testWord, VoiceType.en_US_Allison); while (!_getPronuciationTested) { yield return(null); } // Get Customizations Log.Debug("ExampleTextToSpeech.Examples()", "Attempting to get a list of customizations"); _textToSpeech.GetCustomizations(OnGetCustomizations, OnFail); while (!_getCustomizationsTested) { yield return(null); } // Create Customization Log.Debug("ExampleTextToSpeech.Examples()", "Attempting to create a customization"); _textToSpeech.CreateCustomization(OnCreateCustomization, OnFail, _customizationName, _customizationLanguage, _customizationDescription); while (!_createCustomizationTested) { yield return(null); } // Get Customization Log.Debug("ExampleTextToSpeech.Examples()", "Attempting to get a customization"); if (!_textToSpeech.GetCustomization(OnGetCustomization, OnFail, _createdCustomizationId)) { Log.Debug("ExampleTextToSpeech.Examples()", "Failed to get custom voice model!"); } while (!_getCustomizationTested) { yield return(null); } // Update Customization Log.Debug("ExampleTextToSpeech.Examples()", "Attempting to update a customization"); Word[] wordsToUpdateCustomization = { new Word() { word = "hello", translation = "hullo" }, new Word() { word = "goodbye", translation = "gbye" }, new Word() { word = "hi", translation = "ohioooo" } }; _customVoiceUpdate = new CustomVoiceUpdate() { words = wordsToUpdateCustomization, description = "My updated description", name = "My updated name" }; if (!_textToSpeech.UpdateCustomization(OnUpdateCustomization, OnFail, _createdCustomizationId, _customVoiceUpdate)) { Log.Debug("ExampleTextToSpeech.Examples()", "Failed to update customization!"); } while (!_updateCustomizationTested) { yield return(null); } // Get Customization Words Log.Debug("ExampleTextToSpeech.Examples()", "Attempting to get a customization's words"); if (!_textToSpeech.GetCustomizationWords(OnGetCustomizationWords, OnFail, _createdCustomizationId)) { Log.Debug("ExampleTextToSpeech.GetCustomizationWords()", "Failed to get {0} words!", _createdCustomizationId); } while (!_getCustomizationWordsTested) { yield return(null); } // Add Customization Words Log.Debug("ExampleTextToSpeech.Examples()", "Attempting to add words to a customization"); Word[] wordArrayToAddToCustomization = { new Word() { word = "bananna", translation = "arange" }, new Word() { word = "orange", translation = "gbye" }, new Word() { word = "tomato", translation = "tomahto" } }; Words wordsToAddToCustomization = new Words() { words = wordArrayToAddToCustomization }; if (!_textToSpeech.AddCustomizationWords(OnAddCustomizationWords, OnFail, _createdCustomizationId, wordsToAddToCustomization)) { Log.Debug("ExampleTextToSpeech.AddCustomizationWords()", "Failed to add words to {0}!", _createdCustomizationId); } while (!_addCustomizationWordsTested) { yield return(null); } // Get Customization Word Log.Debug("ExampleTextToSpeech.Examples()", "Attempting to get the translation of a custom voice model's word."); string customIdentifierWord = wordsToUpdateCustomization[0].word; if (!_textToSpeech.GetCustomizationWord(OnGetCustomizationWord, OnFail, _createdCustomizationId, customIdentifierWord)) { Log.Debug("ExampleTextToSpeech.GetCustomizationWord()", "Failed to get the translation of {0} from {1}!", customIdentifierWord, _createdCustomizationId); } while (!_getCustomizationWordTested) { yield return(null); } // Delete Customization Word Log.Debug("ExampleTextToSpeech.Examples()", "Attempting to delete customization word from custom voice model."); string wordToDelete = "goodbye"; if (!_textToSpeech.DeleteCustomizationWord(OnDeleteCustomizationWord, OnFail, _createdCustomizationId, wordToDelete)) { Log.Debug("ExampleTextToSpeech.DeleteCustomizationWord()", "Failed to delete {0} from {1}!", wordToDelete, _createdCustomizationId); } while (!_deleteCustomizationWordTested) { yield return(null); } // Delete Customization Log.Debug("ExampleTextToSpeech.Examples()", "Attempting to delete a customization"); if (!_textToSpeech.DeleteCustomization(OnDeleteCustomization, OnFail, _createdCustomizationId)) { Log.Debug("ExampleTextToSpeech.DeleteCustomization()", "Failed to delete custom voice model!"); } while (!_deleteCustomizationTested) { yield return(null); } Log.Debug("ExampleTextToSpeech.Examples()", "Text to Speech examples complete."); }
public Alternative(Words word, params string[] humanWords) { HumanWords = humanWords.ToList(); Word = word; }
private bool ParseWord(Words word) { WordStates state = WordStates.__; if (context.nodeprocs.Count != 0) { NodeProc nodeproc = context.nodeprocs[context.nodeprocs.Count - 1]; state = word_state_table[(int)(nodeproc.state), (int)word]; if (state == WordStates.__) { context.Error(); return false; } else if (state == WordStates.CLOSE) { context.nodeprocs.RemoveAt(context.nodeprocs.Count - 1); return true; } else { nodeproc.state = state; context.nodeprocs[context.nodeprocs.Count - 1] = nodeproc; } } switch (word) { case Words.ARRAY_BEGIN: { Node newnode = Node.NewArray(); if (!Value(newnode)) return false; NodeProc nodeproc; nodeproc.node = newnode; nodeproc.proc = ArrayProc; nodeproc.state = WordStates.AE; context.nodeprocs.Add(nodeproc); } break; case Words.OBJECT_BEGIN: { Node newnode = Node.NewTable(); if (!Value(newnode)) return false; NodeProc nodeproc; nodeproc.node = newnode; nodeproc.proc = TableProc; nodeproc.state = WordStates.OE; context.nodeprocs.Add(nodeproc); } break; case Words.INTEGER: { uint n = 0; double d = 0; bool minus = false; bool use_double = false; for (int i = context.outset; i < context.cursor; ++i) { byte c = context.input[i]; if (c >= (byte)'0' && c <= (byte)'9') { c -= (byte)'0'; if (use_double) { d = d * 10 + c; } else { if (minus) { if (n > int.MaxValue / 10 || (n == int.MaxValue / 10 && c > int.MaxValue % 10)) { use_double = true; d = n; d = d * 10 + c; continue; } } else { if (n > uint.MaxValue / 10 || (n == uint.MaxValue / 10 && c > uint.MaxValue % 10)) { use_double = true; d = n; d = d * 10 + c; continue; } } n = n * 10 + c; } } else if (c == '-') { minus = true; } } if (use_double) { if (!Value(Node.NewNumber(minus ? -d : d))) return false; } else { if (minus) { if (!Value(Node.NewInt(-(int)n))) return false; } else { if (!Value(Node.NewUInt(n))) return false; } } } break; case Words.FLOAT: { int n = 0; double d = 0; int dot = -1; int exp = 0; bool minus = false; bool use_double = false; for (int i = context.outset; i < context.cursor; ++i) { byte c = context.input[i]; if (c >= (byte)'0' && c <= (byte)'9') { c -= (byte)'0'; if (use_double) { d = d * 10 + c; } else { if (n > int.MaxValue / 10 || (n == int.MaxValue / 10 && c > int.MaxValue % 10)) { use_double = true; d = n; d = d * 10 + c; } else { n = n * 10 + c; } } if (dot >= 0) { ++dot; } } else if (c == '-') { minus = true; } else if (c == '.') { dot = 0; } else if (c == 'e' || c == 'E') { bool expminus = false; for (int j = i; j < context.cursor; ++j) { c = context.input[j]; if (c >= (byte)'0' && c <= (byte)'9') { exp = exp * 10 + (c - '0'); } else if (c == '-') { expminus = true; } } exp = expminus ? -exp : exp; break; } } if (use_double) { if (!Value((minus ? -d : d) * POW10((dot < 0 ? 0 : -dot) + exp))) return false; } else { if (!Value(Node.NewNumber((minus ? -n : n) * POW10((dot < 0 ? 0 : -dot) + exp)))) return false; } } break; case Words.NULL: { if (!Value(Node.NewNull())) return false; } break; case Words.TRUE: { if (!Value(Node.NewBool(true))) return false; } break; case Words.FALSE: { if (!Value(Node.NewBool(false))) return false; } break; case Words.STRING: { context.bufferused = 0; for (int i = context.outset; i < context.cursor; ++i) { byte c = context.input[i]; if (c == (byte)'\\') { switch (context.input[++i]) { case (byte)'b': context.BufferAdd((byte)'\b'); break; case (byte)'f': context.BufferAdd((byte)'\f'); break; case (byte)'n': context.BufferAdd((byte)'\n'); break; case (byte)'r': context.BufferAdd((byte)'\r'); break; case (byte)'t': context.BufferAdd((byte)'\t'); break; case (byte)'"': context.BufferAdd((byte)'"'); break; case (byte)'\\': context.BufferAdd((byte)'\\'); break; case (byte)'/': context.BufferAdd((byte)'/'); break; case (byte)'u': { int unicode = 0; for (int j = 1; j <= 4; ++j) { c = context.input[i + j]; if (c >= (byte)'a') c -= (byte)'a' - 10; else if (c >= (byte)'A') c -= (byte)'A' - 10; else c -= (byte)'0'; unicode <<= 4; unicode |= c; } i += 4; int trail; if (unicode < 0x80) { trail = 0; } else if (unicode < 0x800) { trail = 1; } else { trail = 2; } context.BufferAdd((byte)((unicode >> (trail * 6)) | utf8_lead_bits[trail])); for (int j = trail * 6 - 6; j >= 0; j -= 6) { context.BufferAdd((byte)(((unicode >> j) & 0x3F) | 0x80)); } } break; } } else { context.BufferAdd(c); } } string str = Encoding.UTF8.GetString(context.buffer, 0, context.bufferused); if (state == WordStates.CO) { context.key = str; } else { if (!Value(Node.NewString(str))) return false; } } break; } return true; }
private void OnGetCustomizationWords(Words words, Dictionary <string, object> customData) { Log.Debug("TestTextToSpeech.OnGetCustomizationWords()", "{0}", customData["json"].ToString()); Test(words != null); _getCustomizationWordsTested = true; }
public bool AddWord(String sWord) { Words.Add(sWord); return(true); }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; var vcapUrl = Environment.GetEnvironmentVariable("VCAP_URL"); var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME"); var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD"); using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword)) { while (!simpleGet.IsComplete) { yield return(null); } result = simpleGet.Result; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["text_to_speech"]; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _textToSpeech = new TextToSpeech(credentials); // Synthesize Log.Debug("TestTextToSpeech.RunTest()", "Attempting synthesize."); _textToSpeech.Voice = VoiceType.en_US_Allison; _textToSpeech.ToSpeech(HandleToSpeechCallback, OnFail, _testString, true); while (!_synthesizeTested) { yield return(null); } // Synthesize Conversation string Log.Debug("TestTextToSpeech.RunTest()", "Attempting synthesize a string as returned by Watson Conversation."); _textToSpeech.Voice = VoiceType.en_US_Allison; _textToSpeech.ToSpeech(HandleConversationToSpeechCallback, OnFail, _testConversationString, true); while (!_synthesizeConversationTested) { yield return(null); } // Get Voices Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get voices."); _textToSpeech.GetVoices(OnGetVoices, OnFail); while (!_getVoicesTested) { yield return(null); } // Get Voice Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get voice {0}.", VoiceType.en_US_Allison); _textToSpeech.GetVoice(OnGetVoice, OnFail, VoiceType.en_US_Allison); while (!_getVoiceTested) { yield return(null); } // Get Pronunciation Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get pronunciation of {0}", _testWord); _textToSpeech.GetPronunciation(OnGetPronunciation, OnFail, _testWord, VoiceType.en_US_Allison); while (!_getPronuciationTested) { yield return(null); } // Get Customizations Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get a list of customizations"); _textToSpeech.GetCustomizations(OnGetCustomizations, OnFail); while (!_getCustomizationsTested) { yield return(null); } // Create Customization Log.Debug("TestTextToSpeech.RunTest()", "Attempting to create a customization"); _textToSpeech.CreateCustomization(OnCreateCustomization, OnFail, _customizationName, _customizationLanguage, _customizationDescription); while (!_createCustomizationTested) { yield return(null); } // Get Customization Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get a customization"); if (!_textToSpeech.GetCustomization(OnGetCustomization, OnFail, _createdCustomizationId)) { Log.Debug("TestTextToSpeech.RunTest()", "Failed to get custom voice model!"); } while (!_getCustomizationTested) { yield return(null); } // Update Customization Log.Debug("TestTextToSpeech.RunTest()", "Attempting to update a customization"); Word[] wordsToUpdateCustomization = { new Word() { word = "hello", translation = "hullo" }, new Word() { word = "goodbye", translation = "gbye" }, new Word() { word = "hi", translation = "ohioooo" } }; _customVoiceUpdate = new CustomVoiceUpdate() { words = wordsToUpdateCustomization, description = "My updated description", name = "My updated name" }; if (!_textToSpeech.UpdateCustomization(OnUpdateCustomization, OnFail, _createdCustomizationId, _customVoiceUpdate)) { Log.Debug("TestTextToSpeech.UpdateCustomization()", "Failed to update customization!"); } while (!_updateCustomizationTested) { yield return(null); } // Get Customization Words Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get a customization's words"); if (!_textToSpeech.GetCustomizationWords(OnGetCustomizationWords, OnFail, _createdCustomizationId)) { Log.Debug("TestTextToSpeech.GetCustomizationWords()", "Failed to get {0} words!", _createdCustomizationId); } while (!_getCustomizationWordsTested) { yield return(null); } // Add Customization Words Log.Debug("TestTextToSpeech.RunTest()", "Attempting to add words to a customization"); Word[] wordArrayToAddToCustomization = { new Word() { word = "bananna", translation = "arange" }, new Word() { word = "orange", translation = "gbye" }, new Word() { word = "tomato", translation = "tomahto" } }; Words wordsToAddToCustomization = new Words() { words = wordArrayToAddToCustomization }; if (!_textToSpeech.AddCustomizationWords(OnAddCustomizationWords, OnFail, _createdCustomizationId, wordsToAddToCustomization)) { Log.Debug("TestTextToSpeech.AddCustomizationWords()", "Failed to add words to {0}!", _createdCustomizationId); } while (!_addCustomizationWordsTested) { yield return(null); } // Get Customization Word Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get the translation of a custom voice model's word."); string customIdentifierWord = wordsToUpdateCustomization[0].word; if (!_textToSpeech.GetCustomizationWord(OnGetCustomizationWord, OnFail, _createdCustomizationId, customIdentifierWord)) { Log.Debug("TestTextToSpeech.GetCustomizationWord()", "Failed to get the translation of {0} from {1}!", customIdentifierWord, _createdCustomizationId); } while (!_getCustomizationWordTested) { yield return(null); } // Delete Customization Word Log.Debug("TestTextToSpeech.RunTest()", "Attempting to delete customization word from custom voice model."); string wordToDelete = "goodbye"; if (!_textToSpeech.DeleteCustomizationWord(OnDeleteCustomizationWord, OnFail, _createdCustomizationId, wordToDelete)) { Log.Debug("TestTextToSpeech.DeleteCustomizationWord()", "Failed to delete {0} from {1}!", wordToDelete, _createdCustomizationId); } while (!_deleteCustomizationWordTested) { yield return(null); } // Delete Customization Log.Debug("TestTextToSpeech.RunTest()", "Attempting to delete a customization"); if (!_textToSpeech.DeleteCustomization(OnDeleteCustomization, OnFail, _createdCustomizationId)) { Log.Debug("TestTextToSpeech.DeleteCustomization()", "Failed to delete custom voice model!"); } while (!_deleteCustomizationTested) { yield return(null); } Log.Debug("TestTextToSpeech.RunTest()", "Text to Speech examples complete."); yield break; }
/// <summary> /// Determines if the VerbPhrase acts as a classifier. E.g. in the sentence "Rodents are definitely prey animals." the VerbPhrase /// "are definitely" acts as a classifier because it states that rodents are a subset of prey animals. /// </summary> /// <returns><c>true</c> if the VerbPhrase is a classifier; otherwise, <c>false</c>.</returns> private bool DetermineIsClassifier() => Words.OfVerb().DefaultIfEmpty().Last()?.IsClassifier ?? false;
public Sentence(Word word) { Words = new Words(word); Length = word.OriginWord.Length; }
public ActionResult Show(int id) { Words words = Words.Find(id); return(View(words)); }
public void SetUp() { _mplc = Substitute.For <IMPLCProvider>(); _words = new Words(_mplc, StartAddress, 2); }
public ActionResult DeleteAll() { Words.ClearAll(); return(View()); }
public void ScrabbleConstructor_CreatesInstanceOfScrabble_True() { Words newScrabble = new Words(); Assert.AreEqual(3, newScrabble.GetPoints('C')); }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; var vcapUrl = Environment.GetEnvironmentVariable("VCAP_URL"); var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME"); var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD"); using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword)) { while (!simpleGet.IsComplete) { yield return(null); } result = simpleGet.Result; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["speech_to_text"]; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _speechToText = new SpeechToText(credentials); _customCorpusFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/theJabberwocky-utf8.txt"; _customWordsFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/test-stt-words.json"; _acousticResourceMimeType = Utility.GetMimeType(Path.GetExtension(_acousticResourceUrl)); Runnable.Run(DownloadAcousticResource()); while (!_isAudioLoaded) { yield return(null); } // Recognize Log.Debug("ExampleSpeechToText.Examples()", "Attempting to recognize"); List <string> keywords = new List <string>(); keywords.Add("speech"); _speechToText.KeywordsThreshold = 0.5f; _speechToText.InactivityTimeout = 120; _speechToText.StreamMultipart = false; _speechToText.Keywords = keywords.ToArray(); _speechToText.Recognize(HandleOnRecognize, OnFail, _acousticResourceData, _acousticResourceMimeType); while (!_recognizeTested) { yield return(null); } // Get models Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get models"); _speechToText.GetModels(HandleGetModels, OnFail); while (!_getModelsTested) { yield return(null); } // Get model Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get model {0}", _modelNameToGet); _speechToText.GetModel(HandleGetModel, OnFail, _modelNameToGet); while (!_getModelTested) { yield return(null); } // Get customizations Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get customizations"); _speechToText.GetCustomizations(HandleGetCustomizations, OnFail); while (!_getCustomizationsTested) { yield return(null); } // Create customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting create customization"); _speechToText.CreateCustomization(HandleCreateCustomization, OnFail, "unity-test-customization", "en-US_BroadbandModel", "Testing customization unity"); while (!_createCustomizationsTested) { yield return(null); } // Get customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get customization {0}", _createdCustomizationID); _speechToText.GetCustomization(HandleGetCustomization, OnFail, _createdCustomizationID); while (!_getCustomizationTested) { yield return(null); } // Get custom corpora Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom corpora for {0}", _createdCustomizationID); _speechToText.GetCustomCorpora(HandleGetCustomCorpora, OnFail, _createdCustomizationID); while (!_getCustomCorporaTested) { yield return(null); } // Add custom corpus Log.Debug("ExampleSpeechToText.Examples()", "Attempting to add custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); string corpusData = File.ReadAllText(_customCorpusFilePath); _speechToText.AddCustomCorpus(HandleAddCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName, true, corpusData); while (!_addCustomCorpusTested) { yield return(null); } // Get custom corpus Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); _speechToText.GetCustomCorpus(HandleGetCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName); while (!_getCustomCorpusTested) { yield return(null); } // Wait for customization Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Get custom words Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom words."); _speechToText.GetCustomWords(HandleGetCustomWords, OnFail, _createdCustomizationID); while (!_getCustomWordsTested) { yield return(null); } // Add custom words from path Log.Debug("ExampleSpeechToText.Examples()", "Attempting to add custom words in customization {0} using Words json path {1}", _createdCustomizationID, _customWordsFilePath); string customWords = File.ReadAllText(_customWordsFilePath); _speechToText.AddCustomWords(HandleAddCustomWordsFromPath, OnFail, _createdCustomizationID, customWords); while (!_addCustomWordsFromPathTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Add custom words from object Words words = new Words(); Word w0 = new Word(); List <Word> wordList = new List <Word>(); w0.word = "mikey"; w0.sounds_like = new string[1]; w0.sounds_like[0] = "my key"; w0.display_as = "Mikey"; wordList.Add(w0); Word w1 = new Word(); w1.word = "charlie"; w1.sounds_like = new string[1]; w1.sounds_like[0] = "char lee"; w1.display_as = "Charlie"; wordList.Add(w1); Word w2 = new Word(); w2.word = "bijou"; w2.sounds_like = new string[1]; w2.sounds_like[0] = "be joo"; w2.display_as = "Bijou"; wordList.Add(w2); words.words = wordList.ToArray(); Log.Debug("ExampleSpeechToText.Examples()", "Attempting to add custom words in customization {0} using Words object", _createdCustomizationID); _speechToText.AddCustomWords(HandleAddCustomWordsFromObject, OnFail, _createdCustomizationID, words); while (!_addCustomWordsFromObjectTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Get custom word Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom word {1} in customization {0}", _createdCustomizationID, words.words[0].word); _speechToText.GetCustomWord(HandleGetCustomWord, OnFail, _createdCustomizationID, words.words[0].word); while (!_getCustomWordTested) { yield return(null); } // Train customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to train customization {0}", _createdCustomizationID); _speechToText.TrainCustomization(HandleTrainCustomization, OnFail, _createdCustomizationID); while (!_trainCustomizationTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Upgrade customization - not currently implemented in service //Log.Debug("ExampleSpeechToText.Examples()", "Attempting to upgrade customization {0}", _createdCustomizationID); //_speechToText.UpgradeCustomization(HandleUpgradeCustomization, _createdCustomizationID); //while (!_upgradeCustomizationTested) // yield return null; // Delete custom word Log.Debug("ExampleSpeechToText.Examples()", "Attempting to delete custom word {1} in customization {0}", _createdCustomizationID, words.words[2].word); _speechToText.DeleteCustomWord(HandleDeleteCustomWord, OnFail, _createdCustomizationID, words.words[2].word); while (!_deleteCustomWordTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete custom corpus Log.Debug("ExampleSpeechToText.Examples()", "Attempting to delete custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); _speechToText.DeleteCustomCorpus(HandleDeleteCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName); while (!_deleteCustomCorpusTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Reset customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to reset customization {0}", _createdCustomizationID); _speechToText.ResetCustomization(HandleResetCustomization, OnFail, _createdCustomizationID); while (!_resetCustomizationTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to delete customization {0}", _createdCustomizationID); _speechToText.DeleteCustomization(HandleDeleteCustomization, OnFail, _createdCustomizationID); while (!_deleteCustomizationsTested) { yield return(null); } // List acoustic customizations Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get acoustic customizations"); _speechToText.GetCustomAcousticModels(HandleGetCustomAcousticModels, OnFail); while (!_getAcousticCustomizationsTested) { yield return(null); } // Create acoustic customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to create acoustic customization"); _speechToText.CreateAcousticCustomization(HandleCreateAcousticCustomization, OnFail, _createdAcousticModelName); while (!_createAcousticCustomizationsTested) { yield return(null); } // Get acoustic customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get acoustic customization {0}", _createdAcousticModelId); _speechToText.GetCustomAcousticModel(HandleGetCustomAcousticModel, OnFail, _createdAcousticModelId); while (!_getAcousticCustomizationTested) { yield return(null); } while (!_isAudioLoaded) { yield return(null); } // Create acoustic resource Log.Debug("ExampleSpeechToText.Examples()", "Attempting to create audio resource {1} on {0}", _createdAcousticModelId, _acousticResourceName); string mimeType = Utility.GetMimeType(Path.GetExtension(_acousticResourceUrl)); _speechToText.AddAcousticResource(HandleAddAcousticResource, OnFail, _createdAcousticModelId, _acousticResourceName, mimeType, mimeType, true, _acousticResourceData); while (!_addAcousticResourcesTested) { yield return(null); } // Wait for customization _isAcousticCustomizationReady = false; Runnable.Run(CheckAcousticCustomizationStatus(_createdAcousticModelId)); while (!_isAcousticCustomizationReady) { yield return(null); } // List acoustic resources Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get audio resources {0}", _createdAcousticModelId); _speechToText.GetCustomAcousticResources(HandleGetCustomAcousticResources, OnFail, _createdAcousticModelId); while (!_getAcousticResourcesTested) { yield return(null); } // Train acoustic customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to train acoustic customization {0}", _createdAcousticModelId); _speechToText.TrainAcousticCustomization(HandleTrainAcousticCustomization, OnFail, _createdAcousticModelId, null, true); while (!_trainAcousticCustomizationsTested) { yield return(null); } // Get acoustic resource Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get audio resource {1} from {0}", _createdAcousticModelId, _acousticResourceName); _speechToText.GetCustomAcousticResource(HandleGetCustomAcousticResource, OnFail, _createdAcousticModelId, _acousticResourceName); while (!_getAcousticResourceTested) { yield return(null); } // Wait for customization _isAcousticCustomizationReady = false; Runnable.Run(CheckAcousticCustomizationStatus(_createdAcousticModelId)); while (!_isAcousticCustomizationReady) { yield return(null); } // Delete acoustic resource DeleteAcousticResource(); while (!_deleteAcousticResource) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete acoustic resource for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } // Reset acoustic customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to reset acoustic customization {0}", _createdAcousticModelId); _speechToText.ResetAcousticCustomization(HandleResetAcousticCustomization, OnFail, _createdAcousticModelId); while (!_resetAcousticCustomizationsTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete acoustic customization for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } // Delete acoustic customization DeleteAcousticCustomization(); while (!_deleteAcousticCustomizationsTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying complete for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } Log.Debug("TestSpeechToText.RunTest()", "Speech to Text examples complete."); yield break; }
public static string WordString(Words Word) { return(Text[CurrentLanguage.MyLanguage][Word]); }
public bool LoadFromXmlResource(string langFolder) { try { if (!Directory.Exists(langFolder)) { return(false); } if (int.TryParse(SerializerHelper.LoadText(Path.Combine(langFolder, CurrentLangFile)), out int landId)) { Langs.Clear(); Words.Clear(); foreach (string lang in Directory.GetDirectories(langFolder)) { string name = new DirectoryInfo(lang).Name; if (int.TryParse(name.Substring(0, name.IndexOf('.')), out int id)) { name = name.Substring(name.IndexOf('.') + 1); Langs.Add(new Lang { Id = id, Name = name }); string text = SerializerHelper.LoadText(Path.Combine(lang, WordsFile)); while (!string.IsNullOrEmpty(text)) { if (text[0] == '<') { string key = text.Substring(1, text.IndexOf('>') - 1); string value = text.Substring(text.IndexOf('>') + 1, text.IndexOf($"</{key}>") - $"</{key}>".Length + 1); Word word = Words.FirstOrDefault(w => w.Key == key); if (word == null) { word = new Word { Key = key, Values = new Dictionary <int, string>() }; Words.Add(word); } if (word.Values.ContainsKey(id)) { word.Values[id] = value; } else { word.Values.Add(id, value); } text = text.Substring(key.Length * 2 + value.Length + 5).TrimStart('\r', '\n'); } } } } CurrentLang = Langs.FirstOrDefault(l => l.Id == landId) ?? Langs.FirstOrDefault(); return(true); } } catch (Exception ex) { Logger.Log(ex); } return(false); }
public ActionResult CreateAnswer(vm_AnswerEventQuestion Answer) { List<string> words = Answer.Words.Split(',').ToList(); foreach (var singleword in words) { var lowerword = singleword.ToLower().Trim(); var word = _wordRepository.FindAll(w => w.Word == lowerword).FirstOrDefault(); if (word != null) { word.WordCount = word.WordCount + 1; _wordRepository.Save(word); } else { var newword = new Words(); newword.WordCount = 1; newword.ID = Guid.NewGuid(); newword.Word = lowerword; _wordRepository.Save(newword); } } var eventQuestionIDs = Answer.EventQuestionIDs.Split(';').Select(e => new Guid(e)).ToList(); List<int> ar = new List<int>(); for(int n =0; n < Answer.StringAnswers.Length; n++) { ar.Add(int.Parse(Answer.StringAnswers[n].ToString())); } int i = 0; foreach (var id in eventQuestionIDs) { var qAnswer = new Answer { Age = Answer.Age, Username = Answer.Username, Email = Answer.Email, ID = Guid.NewGuid(), Gender = Answer.Gender, EventQuestionID = id, Score = ar[i] }; i++; try { _answerRepository.Save(qAnswer); } catch (DbEntityValidationException ex) { StringBuilder sb = new StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } throw new DbEntityValidationException("Entity Validation Failed - errors follow:\n" + sb.ToString(), ex); } } if (!string.IsNullOrEmpty(Answer.Email)) { Subscriber subscriber = _subScriberRepository.FindAll(s => s.Email == Answer.Email).FirstOrDefault(); if(subscriber == null){ subscriber = new Subscriber(); subscriber.Email = Answer.Email; subscriber.City = Answer.City; subscriber.Name = Answer.Username; subscriber.ID = Guid.NewGuid(); _subScriberRepository.Save(subscriber); } } return RedirectToAction("CreateAnswer", "Event"); }
internal void SelectWord(Word w) { var toSelect = Words.FirstOrDefault(vm => vm.word == w); SelectedWord = toSelect; }
public static string WordMarkup(Words Word) { int Size = 80; return(string.Format("{{p{1},?,{0}}}", Size, WordToTextureName(Word))); }
/// <summary> /// Проверка слов. Начало тренировки /// </summary> public void CheckWords() { //Мод изучения слов включён _User.LearningMode = true; //Сообщенаем пользователю о начале тренировки if (FirstWord) { StringBuilder sb = new StringBuilder(); for (int i = 0; i <= 10; i++) { sb.Append(".\n"); } Sender.SendTextMessage(_User.ChatId, sb.ToString()); Sender.SendTextMessage(_User.ChatId, "Start!"); } Random r = new Random(); try { //Формируем список слов, которые будут проверятся if (FirstWord) { int index; var selectedWords = from word in _User.Words where word.LearningProgress < Word.NeededProgress select word; List <Word> temp = selectedWords.ToList(); if (temp.Count == 0) { Sender.SendTextMessage(_User.ChatId, "Вы уже выучили все слова!"); _User.LearningMode = false; return; } for (int i = 0; i < AmountOfQuestions; i++) { if (temp.Count <= 10) { if (temp.Count < AmountOfQuestions) { AmountOfQuestions = temp.Count; Counter = AmountOfQuestions; } for (int j = 0; j < AmountOfQuestions; j++) { Words.Add(temp[j]); } AmountOfQuestions = 5; break; } index = r.Next(temp.Count - 1); Word w = temp[index]; Words.Add(w); temp.RemoveAt(index); } FirstWord = false; } } catch { } try { WordIndex = r.Next(Words.Count - 1); WordObject = Words[WordIndex]; CurrentWord = WordObject._Word; CorrectAnswer = WordObject.Translation; Sender.SendTextMessage(_User.ChatId, $"Translate: {CurrentWord}"); } catch { return; } }
public static string WordMarkup(Words Word, int Size) { return(string.Format("{{p{1},{0},?}}", Size, WordToTextureName(Word))); }
private void OnGetCustomizationWords(Words words, Dictionary <string, object> customData = null) { Log.Debug("ExampleTextToSpeech.OnGetCustomizationWords()", "Text to Speech - Get customization words response: {0}", customData["json"].ToString()); _getCustomizationWordsTested = true; }
private void AddTo(Words words) { words.Add(this.verb, this.synonyms); }
private IEnumerator Examples() { Runnable.Run(DownloadAcousticResource()); while (!_isAudioLoaded) { yield return(null); } Runnable.Run(DownloadOggResource()); while (!_isOggLoaded) { yield return(null); } // Recognize Log.Debug("ExampleSpeechToText.Examples()", "Attempting to recognize"); List <string> keywords = new List <string>(); keywords.Add("speech"); _service.KeywordsThreshold = 0.5f; _service.InactivityTimeout = 120; _service.StreamMultipart = false; _service.Keywords = keywords.ToArray(); _service.Recognize(HandleOnRecognize, OnFail, _acousticResourceData, _acousticResourceMimeType); while (!_recognizeTested) { yield return(null); } // Recognize ogg Log.Debug("ExampleSpeechToText", "Attempting to recognize ogg: mimeType: {0} | _speechTText.StreamMultipart: {1}", _oggResourceMimeType, _service.StreamMultipart); _service.Recognize(HandleOnRecognizeOgg, OnFail, _oggResourceData, _oggResourceMimeType + ";codecs=vorbis"); while (!_recognizeOggTested) { yield return(null); } // Get models Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get models"); _service.GetModels(HandleGetModels, OnFail); while (!_getModelsTested) { yield return(null); } // Get model Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get model {0}", _modelNameToGet); _service.GetModel(HandleGetModel, OnFail, _modelNameToGet); while (!_getModelTested) { yield return(null); } // Get customizations Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get customizations"); _service.GetCustomizations(HandleGetCustomizations, OnFail); while (!_getCustomizationsTested) { yield return(null); } // Create customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting create customization"); _service.CreateCustomization(HandleCreateCustomization, OnFail, "unity-test-customization", "en-US_BroadbandModel", "Testing customization unity"); while (!_createCustomizationsTested) { yield return(null); } // Get customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get customization {0}", _createdCustomizationID); _service.GetCustomization(HandleGetCustomization, OnFail, _createdCustomizationID); while (!_getCustomizationTested) { yield return(null); } // Get custom corpora Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom corpora for {0}", _createdCustomizationID); _service.GetCustomCorpora(HandleGetCustomCorpora, OnFail, _createdCustomizationID); while (!_getCustomCorporaTested) { yield return(null); } // Add custom corpus Log.Debug("ExampleSpeechToText.Examples()", "Attempting to add custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); string corpusData = File.ReadAllText(_customCorpusFilePath); _service.AddCustomCorpus(HandleAddCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName, true, corpusData); while (!_addCustomCorpusTested) { yield return(null); } // Get custom corpus Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); _service.GetCustomCorpus(HandleGetCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName); while (!_getCustomCorpusTested) { yield return(null); } // Wait for customization Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Get custom words Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom words."); _service.GetCustomWords(HandleGetCustomWords, OnFail, _createdCustomizationID); while (!_getCustomWordsTested) { yield return(null); } // Add custom words from path Log.Debug("ExampleSpeechToText.Examples()", "Attempting to add custom words in customization {0} using Words json path {1}", _createdCustomizationID, _customWordsFilePath); string customWords = File.ReadAllText(_customWordsFilePath); _service.AddCustomWords(HandleAddCustomWordsFromPath, OnFail, _createdCustomizationID, customWords); while (!_addCustomWordsFromPathTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Add custom words from object Words words = new Words(); Word w0 = new Word(); List <Word> wordList = new List <Word>(); w0.word = "mikey"; w0.sounds_like = new string[1]; w0.sounds_like[0] = "my key"; w0.display_as = "Mikey"; wordList.Add(w0); Word w1 = new Word(); w1.word = "charlie"; w1.sounds_like = new string[1]; w1.sounds_like[0] = "char lee"; w1.display_as = "Charlie"; wordList.Add(w1); Word w2 = new Word(); w2.word = "bijou"; w2.sounds_like = new string[1]; w2.sounds_like[0] = "be joo"; w2.display_as = "Bijou"; wordList.Add(w2); words.words = wordList.ToArray(); Log.Debug("ExampleSpeechToText.Examples()", "Attempting to add custom words in customization {0} using Words object", _createdCustomizationID); _service.AddCustomWords(HandleAddCustomWordsFromObject, OnFail, _createdCustomizationID, words); while (!_addCustomWordsFromObjectTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Get custom word Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom word {1} in customization {0}", _createdCustomizationID, words.words[0].word); _service.GetCustomWord(HandleGetCustomWord, OnFail, _createdCustomizationID, words.words[0].word); while (!_getCustomWordTested) { yield return(null); } // Train customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to train customization {0}", _createdCustomizationID); _service.TrainCustomization(HandleTrainCustomization, OnFail, _createdCustomizationID); while (!_trainCustomizationTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Upgrade customization - not currently implemented in service //Log.Debug("ExampleSpeechToText.Examples()", "Attempting to upgrade customization {0}", _createdCustomizationID); //_speechToText.UpgradeCustomization(HandleUpgradeCustomization, _createdCustomizationID); //while (!_upgradeCustomizationTested) // yield return null; // Delete custom word Log.Debug("ExampleSpeechToText.Examples()", "Attempting to delete custom word {1} in customization {0}", _createdCustomizationID, words.words[2].word); _service.DeleteCustomWord(HandleDeleteCustomWord, OnFail, _createdCustomizationID, words.words[2].word); while (!_deleteCustomWordTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete custom corpus Log.Debug("ExampleSpeechToText.Examples()", "Attempting to delete custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); _service.DeleteCustomCorpus(HandleDeleteCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName); while (!_deleteCustomCorpusTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Reset customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to reset customization {0}", _createdCustomizationID); _service.ResetCustomization(HandleResetCustomization, OnFail, _createdCustomizationID); while (!_resetCustomizationTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to delete customization {0}", _createdCustomizationID); _service.DeleteCustomization(HandleDeleteCustomization, OnFail, _createdCustomizationID); while (!_deleteCustomizationsTested) { yield return(null); } // List acoustic customizations Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get acoustic customizations"); _service.GetCustomAcousticModels(HandleGetCustomAcousticModels, OnFail); while (!_getAcousticCustomizationsTested) { yield return(null); } // Create acoustic customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to create acoustic customization"); _service.CreateAcousticCustomization(HandleCreateAcousticCustomization, OnFail, _createdAcousticModelName); while (!_createAcousticCustomizationsTested) { yield return(null); } // Get acoustic customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get acoustic customization {0}", _createdAcousticModelId); _service.GetCustomAcousticModel(HandleGetCustomAcousticModel, OnFail, _createdAcousticModelId); while (!_getAcousticCustomizationTested) { yield return(null); } while (!_isAudioLoaded) { yield return(null); } // Create acoustic resource Log.Debug("ExampleSpeechToText.Examples()", "Attempting to create audio resource {1} on {0}", _createdAcousticModelId, _acousticResourceName); string mimeType = Utility.GetMimeType(Path.GetExtension(_acousticResourceUrl)); _service.AddAcousticResource(HandleAddAcousticResource, OnFail, _createdAcousticModelId, _acousticResourceName, mimeType, mimeType, true, _acousticResourceData); while (!_addAcousticResourcesTested) { yield return(null); } // Wait for customization _isAcousticCustomizationReady = false; Runnable.Run(CheckAcousticCustomizationStatus(_createdAcousticModelId)); while (!_isAcousticCustomizationReady) { yield return(null); } // List acoustic resources Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get audio resources {0}", _createdAcousticModelId); _service.GetCustomAcousticResources(HandleGetCustomAcousticResources, OnFail, _createdAcousticModelId); while (!_getAcousticResourcesTested) { yield return(null); } // Train acoustic customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to train acoustic customization {0}", _createdAcousticModelId); _service.TrainAcousticCustomization(HandleTrainAcousticCustomization, OnFail, _createdAcousticModelId, null, true); while (!_trainAcousticCustomizationsTested) { yield return(null); } // Get acoustic resource Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get audio resource {1} from {0}", _createdAcousticModelId, _acousticResourceName); _service.GetCustomAcousticResource(HandleGetCustomAcousticResource, OnFail, _createdAcousticModelId, _acousticResourceName); while (!_getAcousticResourceTested) { yield return(null); } // Wait for customization _isAcousticCustomizationReady = false; Runnable.Run(CheckAcousticCustomizationStatus(_createdAcousticModelId)); while (!_isAcousticCustomizationReady) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete acoustic resource for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } // Delete acoustic resource DeleteAcousticResource(); while (!_deleteAcousticResource) { yield return(null); } // Reset acoustic customization Log.Debug("ExampleSpeechToText.Examples()", "Attempting to reset acoustic customization {0}", _createdAcousticModelId); _service.ResetAcousticCustomization(HandleResetAcousticCustomization, OnFail, _createdAcousticModelId); while (!_resetAcousticCustomizationsTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete acoustic customization for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } // Delete acoustic customization DeleteAcousticCustomization(); while (!_deleteAcousticCustomizationsTested) { yield return(null); } // Delay Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying complete for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } Log.Debug("ExampleSpeechToText.Examples()", "Speech to Text examples complete."); }
private void myAutocompleteBox_TextChanged(object sender, RoutedEventArgs e) { try { if (myAutocompleteBox.SelectedItem == null || string.IsNullOrEmpty(((Word)myAutocompleteBox.SelectedItem).Name)) { if (!String.IsNullOrEmpty(myAutocompleteBox.Text) && !String.IsNullOrEmpty(myAutocompleteBox.Text.Trim())) { List<Word> list = tccvm.FindAllWords(myAutocompleteBox.Text.TrimStart(), 8); if (list != null && list.Count > 0) { Words wordlist = new Words(); for (int ix = 0; ix < list.Count; ix++) { wordlist.ListOfWords.Add(list[ix]); } myAutocompleteBox.ItemsSource = wordlist.ListOfWords; } } } } catch (Exception ex) { App.ShowMessageBox(ex); } }
public static string WordToTextureName(Words Word) { return("white"); }
public static void Swap(ref Words x, ref Words y) { var temp = y; y = x; x = temp; }