Beispiel #1
1
        public bool NextWord(bool isRemember)
        {
            IsHiddenAnswer = true;
            if (CurrentWordPosition != -1)
            {
                CurrentWord.IsRemember = isRemember;
                if (isRemember)
                {
                    CurrentWord.RememberCount++;
                }
                else
                {
                    CurrentWord.NoRememberCount++;
                }
            }
            CurrentWordPosition++;
            if (CurrentWordPosition >= WordList.Count)
            {
                CurrentFileName = string.Empty;
                TopNoRememberList.Clear();
                var list = WordList.OrderBy(q => q.RememberRate).Take(5).ToList();
                foreach (var item in list)
                {
                    TopNoRememberList.Add(item);
                    UpdateLiveTileForText(item.Word, item.Mean, "正答率 = " + ((int)(item.RememberRate * 100)) + "%");
                }

                if (RecentlyFileList.Count > 5)
                {
                    RecentlyFileList.RemoveAt(RecentlyFileList.Count - 1);
                }
                RecentlyFileList.Insert(0, this.CurrentWordFile);

                var temp = new List <WordFile>(RecentlyFileList.OrderByDescending(q => q.LastLearnDate));
                RecentlyFileList.Clear();
                foreach (var item in temp)
                {
                    RecentlyFileList.Add(item);
                }


                IsStudying = false;
                return(false);
            }
            else
            {
                CurrentWord = WordList.ElementAt(CurrentWordPosition);

                return(true);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Write the specified list of words to a compressed file.
        /// </summary>
        /// <param name="wordList"></param>
        private static void WriteCompressedFile(WordList wordList)
        {
            string filePath = Path.Combine(Path.GetDirectoryName(_sourceFile), string.Format("words{0}.gz", wordList.WordLength));

            using (FileStream compressedFile = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (GZipStream compressionStream = new GZipStream(compressedFile, CompressionMode.Compress))
                {
                    try
                    {
                        // Output new file
                        string data = String.Join(" ", wordList.ToArray());
                        byte[] bytes = new byte[data.Length * sizeof(char)];
                        Buffer.BlockCopy(data.ToCharArray(), 0, bytes, 0, bytes.Length);

                        using (MemoryStream stream = new MemoryStream(bytes))
                        {
                            stream.CopyTo(compressionStream);

                            Console.WriteLine("{0} created.", Path.GetFileName(filePath));
                            Console.WriteLine();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.StackTrace);
                        Console.WriteLine();
                    }
                }
            }
        }
    /// <summary>
    /// Attempt to score how well this WordList matches the actual input
    /// </summary>
    /// <param name="input">The users words</param>
    /// <returns>A score representing how well it matches</returns>
    internal double score(WordList input)
    {
        var score = 1.0;
          // for each word
          int L = words.Length;
          if (L > input.words.Length)
         return 0.0;
          for (var I = 0; I <L; I++)
          {
         var item = words[I];
         var inWord=input.words[I];
         // Check for exact, but caseless match
         if (item.Equals(inWord, StringComparison.CurrentCultureIgnoreCase))
         {
            score += 1.0;
            continue;
         }

         // Check for a partial match
         if ((inWord. Length < item.Length)
             && item.Substring(0, inWord.Length).Equals(inWord, StringComparison.CurrentCultureIgnoreCase))
         {
            // Calculate a score for this match
            score += ((double)item.Length)/(double)item.Length;
         }
          }

          // return the result
          return score;
    }
Beispiel #4
0
        // Constructor is protected in order to make sure no other word lists are open for this list.
        protected ListBuilder(WordList wordList)
        {
            InitializeComponent();

            list = wordList;
            grid.DataSource = wordList;

            UpdateTitle();
            name.Text = list.Name;
            author.Text = list.Author;
            url.Text = list.Url;
            UpdateEntryCount();

            grid.ColumnRatio = GuiConfiguration.ListBuilderColumnRatio;
            meta.Height = GuiConfiguration.ListBuilderMetadataSectionHeight;

            Layout += ListBuilderLayout;
            Closing += ListBuilderClosing;
            editMetadata.Click += EditMetadataClick;
            copyAsCsv.Click += CopyAsCsvClick;
            sort.Click += SortItems;
            swapAll.Click += SwapAll;
            shadow.MouseDown += ShadowMouseDown;
            shadow.MouseMove += ShadowMouseMove;
            name.TextChanged += NameTextChanged;
            author.TextChanged += AuthorTextChanged;
            url.TextChanged += UrlTextChanged;
            showStartPage.Click += showStartPage_Click;
            close.Click += CloseClick;
            deleteList.Click += DeleteListClick;
            grid.ColumnRatioChanged += GridColumnRatioChanged;

            undo.Click += delegate { list.Undo(); };
            redo.Click += delegate { list.Redo(); };
            editMenu.DropDownOpening += EditMenuDropDownOpening;
            itemContextMenu.Opening += ItemContextMenuOpening;
            mainMenu.Items.Add(new TagMenu { WordList = list });

            grid.ColumnHeaderMouseClick += ColumnHeaderClicked;

            cutMI.Click += delegate { grid.Cut(); };
            copyMI.Click += delegate { grid.Copy(); };
            pasteMI.Click += delegate { grid.Paste(); };
            cutCM.Click += delegate { grid.Cut(); };
            copyCM.Click += delegate { grid.Copy(); };
            pasteCM.Click += delegate { grid.Paste(); };

            swap.Click += SwapItems;

            deleteMI.Click += RemoveItems;
            deleteCM.Click += RemoveItems;

            WireListEvents();
            MakeRecent();

            queuedUpdateTimer = new Timer { Interval = 150, Enabled = false };
            components.Add(queuedUpdateTimer);
            queuedUpdateTimer.Tick += QueuedUpdateTimerTick;
        }
 public static SearchEngine Get(IEngineData searchEngineData)
 {
     var wordSearchBox = new WordSearchBox(searchEngineData.Letters, searchEngineData.Width);
     var expectedWords = searchEngineData.ExpectedWords;
     var wordList = new WordList();
     wordList.AddWordsToList(expectedWords);
     return new SearchEngine(wordSearchBox, wordList);
 }
Beispiel #6
0
	    private void ImportCompleted(WordList result) {
			Debug.Assert(!InvokeRequired, "ImportCompleted called on a secondary thread");
			importedWordList = result;
			CurrentUI = null;
			if(importedWordList.ID.HasValue)
				ListBuilder.Open(importedWordList.ID.Value);
			Close();
		}
        public List<QuizWord> GetWords(WordList wordList)
        {
            List<WordInfo> wordsToLearn = wordList.GetAllWords().Where(w => w.IsStudied && !w.IsLearned).OrderBy(w => w.Word.Name).ToList();

            DateTime cutOffDate = DateTime.UtcNow - WordInfo.TimeToMarkVerified;
            List<WordInfo> wordsToVerify = wordList.GetAllWords().Where(w => w.IsLearned && !w.IsVerified && w.LastEvent.LastStateChange <= cutOffDate).OrderBy(w => w.Word.Name).ToList();

            List<WordInfo> words = wordsToLearn.Concat(wordsToVerify).ToList();
            
            return words.Select(w => new QuizWord(w)).ToList();
        }
        public void TestWhenWordsAddedTheMiddleWordIsFound()
        {
            // arrange
            var newWords = new List<string> { "firstword", "middleword", "lastword" };
            var wordList = new WordList();

            // act
            wordList.AddWordsToList(newWords);

            // assert
            Assert.IsTrue(wordList.IsInWordList("middleword"));
        }
Beispiel #9
0
            public void can_check_words_when_constructed_from_list()
            {
                var words = "The quick brown fox jumps over the lazy dog".Split(' ');

                var wordList = WordList.CreateFromWords(words);

                foreach (var word in words)
                {
                    wordList.Check(word).Should().BeTrue();
                }
                wordList.Check("missing").Should().BeFalse();
                wordList.Check("Wot?").Should().BeFalse();
            }
        // GET: SimpleBoard
        public ActionResult Index()
        {
            WordList list  = WordListConfig.Lists[WordListConfig.ENGLISH_AS_A_SECOND_LANGUAGE];
            var      board = Board.InitiliseBoard(list);

            var suggestionRequest = new SuggestionRequestModel();

            suggestionRequest.Board       = new BoardModel(board, list);
            suggestionRequest.Hand        = new HandModel();
            suggestionRequest.Suggestions = new SuggestionsModel();

            return(View(suggestionRequest));
        }
        static void Suggestions()
        {
            var hunspell = WordList.CreateFromFiles("files/English (American).dic");
            var words    = ReadWords()
                           .Take(500)
                           .ToList();

            foreach (var word in words)
            {
                var isFound     = hunspell.Check(word);
                var suggestions = hunspell.Suggest(word);
            }
        }
        static void Checks()
        {
            var hunspell = WordList.CreateFromFiles("files/English (American).dic");
            var words    = ReadWords().ToList();

            for (var i = 0; i < 1000; i++)
            {
                foreach (var word in words)
                {
                    hunspell.Check(word);
                }
            }
        }
        private void drag_area_tracker_OnDragStarted(bool button_left_pressed, bool button_right_pressed, Point mouse_down_point)
        {
            PDFRendererControl pdf_renderer_control = GetPDFRendererControl();
            PDFDocument        pdf_document         = pdf_renderer_control?.GetPDFDocument();

            ASSERT.Test(pdf_document != null);

            if (pdf_document != null)
            {
                WordList words = pdf_document.GetOCRText(page);
                text_selection_manager.OnDragStarted(text_layer_selection_mode, words, ActualWidth, ActualHeight, button_left_pressed, button_right_pressed, mouse_down_point);
            }
        }
Beispiel #14
0
        private static void PracticeMenu(string[] args)
        {
            var name     = args[1].ToLower();
            var wordList = WordList.LoadList(name);

            if (wordList == null)
            {
                Console.WriteLine($"This list name {name} does not exit on your  computer");
                return;
            }

            PracticeMenu1(wordList);
        }
Beispiel #15
0
        private void WordPadTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            WordPad targetPad;

            if (!m_wordPads.TryGetValue(e.Node.Text, out targetPad))
            {
                return;
            }

            WordList.Show();
            searchResultList.Hide();
            UpdateWordListFromWordPad(targetPad);
        }
        /// <summary>
        /// Listar namnen på alla ordlistor från mappen i appdata/local/Labb4
        /// </summary>
        /// <returns>Förutsätter att kommandot "-lists" skrevs in. Returnerar alltid true.</returns>
        static bool ExecuteListsCommand()
        {
            var lists = WordList.GetLists();

            Console.WriteLine("Word List .dat files found in {0}:", WordList.DestinationFolderPath);

            for (int i = 0; i < lists.Length; i++)
            {
                Console.WriteLine($"{i + 1}: {lists[i]}");
            }

            return(true);
        }
Beispiel #17
0
        private void LoadLists()
        {
            if (listBox.Items.Count > 0)
            {
                listBox.Items.Clear();
            }
            var listOfFiles = WordList.GetLists();

            foreach (var list in listOfFiles)
            {
                listBox.Items.Add(list);
            }
        }
Beispiel #18
0
        public void Clear()
        {
            _wL = new WordList();
            var wList = _context.wordLists.ToList();

            foreach (WordList Wl in wList)
            {
                _msg = new MsgEnginner();
                _context.wordLists.RemoveRange(Wl);
                Console.WriteLine(_msg.ClearWordLis());
                _context.SaveChanges();
            }
        }
Beispiel #19
0
        private void ViewListSelection_Load(object sender, EventArgs e)
        {
            cmbLists.Items.Clear();
            var list = WordList.GetLists();

            if (list != null && list.Count() > 0)
            {
                foreach (var item in list)
                {
                    cmbLists.Items.Add(item);
                }
            }
        }
        private void ButtonReadOutLoud_Click(object sender, RoutedEventArgs e)
        {
            FeatureTrackingManager.Instance.UseFeature(Features.Document_ReadOutLoud);

            AugmentedToggleButton button = (AugmentedToggleButton)sender;

            if (null != button.IsChecked && button.IsChecked.Value)
            {
                if (null != pdf_renderer_control.SelectedPage)
                {
                    PDFDocument pdf_document = GetPDFDocument();
                    ASSERT.Test(pdf_document != null);

                    if (pdf_document != null)
                    {
                        int      page  = pdf_renderer_control.SelectedPage.PageNumber;
                        WordList words = pdf_document.GetOCRText(page);
                        if (null != words)
                        {
                            StringBuilder sb = new StringBuilder();
                            foreach (var word in words)
                            {
                                sb.Append(word.Text);
                                sb.Append(' ');
                            }

                            ReadOutLoudManager.Instance.Read(sb.ToString());
                        }
                        else
                        {
                            Logging.Info("No OCR to read");
                            ReadOutLoudManager.Instance.Read("Please run OCR on this page before it can be read.");
                        }
                    }
                    else
                    {
                        Logging.Info("No document to read");
                        ReadOutLoudManager.Instance.Read("INTERNAL ERROR: no document to read.");
                    }
                }
                else
                {
                    Logging.Info("No page selected to read");
                    ReadOutLoudManager.Instance.Read("Please select the page that you wish to have read to you.");
                }
            }
            else
            {
                ReadOutLoudManager.Instance.Pause();
            }
        }
Beispiel #21
0
        public void HandleWord(string OriginalWord, string Response)
        {
            if (Response == DefaultErrorString)
            {
                byte[] wordbyte = Encoding.Default.GetBytes(OriginalWord);
                Console.WriteLine("No matches were found for this word: " + BitConverter.ToString(wordbyte) + "! See Log file!");

                using (StreamWriter log = File.AppendText(LogFile))
                {
                    string Error = ": No matches were found for the word: " + OriginalWord;
                    log.WriteLine(DateTime.Now.ToString() + Error);
                }

                return;
            }

            string SingleResponse = HandleMultipleResponses(OriginalWord, Response);

            WordClass NewWord = new WordClass();

            NewWord.Kanji     = GetKanjiFromLine(SingleResponse);
            NewWord.Hiragana  = GetHiraganaFromLine(SingleResponse);
            NewWord.Meanings  = GetMeaningsFromLine(SingleResponse);
            NewWord.HaveAudio = false;

            if (EnableAudioDownload == "true")
            {
                string FileName  = GetFileName(NewWord.Hiragana.Split(";")[0]);
                string Audiofile = FileName + ".mp3";
                FileName = MediaFolder + "/" + FileName + ".mp3";
                DownloadAudio(NewWord.Kanji, NewWord.Hiragana, FileName);

                if (VerifyDownload(FileName))
                {
                    Console.WriteLine("The download was succesfull!");
                    NewWord.HaveAudio = true;
                    NewWord.AudioFile = Audiofile;
                }
                else
                {
                    Console.Write("This word does not have an audio file!");
                    using (StreamWriter log = File.AppendText(LogFile))
                    {
                        string Error = ": No audio file was found for the word: " + NewWord.Kanji;
                        log.WriteLine(DateTime.Now.ToString() + Error);
                    }
                }
            }

            WordList.Add(NewWord);
        }
Beispiel #22
0
    // This method formats a sequence of words (Strings obtained from
    // an enumerator) into lines of text, padding the inter-word
    // gaps with extra spaces to obtain lines of length lineWidth, and
    // thus a straight right margin.
    //
    // There are the following exceptions:
    //  * if a word is longer than lineWidth, it is put on a line by
    //    itself (producing a line longer than lineWidth)
    //  * a single word may appear on a line by itself (producing a line
    //     shorter than lineWidth) if adding the next word to the line
    //     would make the line longer than lineWidth
    //  * the last line of the output is not padded with extra spaces.
    //
    // The algorithm for padding with extra spaces ensures that the
    // spaces are evenly distributed over inter-word gaps, using modulo
    // arithmetics.  An Assert method call asserts that the resulting
    // output line has the correct length unless the line contains only
    // a single word or is the last line of the output.

    public static void Format(IEnumerator <String> words, int lineWidth,
                              TextWriter tw)
    {
        lineWidth = Math.Max(0, lineWidth);
        WordList curLine   = new WordList();
        bool     moreWords = words.MoveNext();

        while (moreWords)
        {
            while (moreWords && curLine.Length < lineWidth)
            {
                String word = words.Current;
                if (word != null && word != "")
                {
                    curLine.AddLast(word);
                }
                moreWords = words.MoveNext();
            }
            int wordCount = curLine.Count;
            if (wordCount > 0)
            {
                int extraSpaces = lineWidth - curLine.Length;
                if (wordCount > 1 && extraSpaces < 0) // last word goes on next line
                {
                    int lastWordLength = curLine.GetLast.Length;
                    extraSpaces += 1 + lastWordLength;
                    wordCount   -= 1;
                }
                else if (!moreWords)            // last line, do not pad
                {
                    extraSpaces = 0;
                }
                // Pad inter-word space with evenly distributed extra blanks
                int           holes  = wordCount - 1;
                int           spaces = holes / 2;
                StringBuilder sb     = new StringBuilder();
                sb.Append(curLine.RemoveFirst());
                for (int i = 1; i < wordCount; i++)
                {
                    spaces += extraSpaces;
                    appendBlanks(sb, 1 + spaces / holes);
                    spaces %= holes;
                    sb.Append(curLine.RemoveFirst());
                }
                String res = sb.ToString();
                Debug.Assert(res.Length == lineWidth || wordCount == 1 || !moreWords);
                tw.WriteLine(res);
            }
        }
        tw.Flush();
    }
        public void TestWhenWordsAddedTheFirstWordIsFound()
        {
            // arrange
            var newWords = new List <string> {
                "firstword", "middleword", "lastword"
            };
            var wordList = new WordList();

            // act
            wordList.AddWordsToList(newWords);

            // assert
            Assert.IsTrue(wordList.IsInWordList("firstword"));
        }
Beispiel #24
0
        private void TryHands(WordList list)
        {
            string input;

            do
            {
                Console.Write("Please enter a hand:");
                input = Console.ReadLine();
                if (input != null && input.Length > 0)
                {
                    Console.WriteLine(string.Format("found the following: [{0}]", FindMoves(input, list).Take(10).ToExpandedString()));
                }
            } while (input.Length > 0);
        }
Beispiel #25
0
        // GET: WordLists/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            WordList wordList = _wordListService.GetById((int)id);

            if (wordList == null)
            {
                return(HttpNotFound());
            }
            return(View(wordList));
        }
Beispiel #26
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Removebutton.Enabled   = false;
            Savebutton.Enabled     = false;
            Practicebutton.Enabled = false;
            AddWordbutton.Enabled  = false;

            var list = WordList.GetLists();

            foreach (var i in list)
            {
                listBox.Items.Add(Path.GetFileName(i).Split('.')[0]);
            }
        }
Beispiel #27
0
        private void Form1_Activated(object sender, EventArgs e)
        {
            var addnewlist = new AddNewList();

            listBox1.Show();
            ListLabel.Show();
            listBox1.Items.Clear();
            var vs = WordList.GetLists();

            foreach (var v in vs)
            {
                listBox1.Items.Add(v);
            }
        }
Beispiel #28
0
    public static WordList GetList(int _count)
    {
        WordList TempList = new WordList();

        for (int i = 0; i < m_WordList.Count; i++)
        {
            if (m_WordList.Count <= i)
            {
                break;
            }
            TempList.Add(m_WordList.GetInfo(i), m_WordList.GetAnswer(i), m_WordList.GetMeaning(i));
        }
        return(TempList);
    }
Beispiel #29
0
        //Adds the lists from filepath to the listbox - DONE!
        private void Form1_Load(object sender, EventArgs e)
        {
            string empty = "No Lists to display...";

            foreach (var item in WordList.GetList())
            {
                listBox1_ShowLists.Items.Add(Path.GetFileNameWithoutExtension(item));
            }

            if (listBox1_ShowLists.Items.Count == 0)
            {
                listBox1_ShowLists.Items.Add(empty);
            }
        }
        private string encodeKeywords(string script)
        {
            if (Encoding == PackerEncoding.HighAscii)
            {
                script = escape95(script);                                                                                                  // escape high-ascii values already in the script (i.e. in strings)
            }
            ParseMaster  parser = new ParseMaster();                                                                                        // create the parser
            EncodeMethod encode = getEncoder(Encoding);
            Regex        regex  = new Regex((Encoding == PackerEncoding.HighAscii) ? "\\w\\w+" : "\\w+");                                   // for high-ascii, don't encode single character low-ascii

            encodingLookup = analyze(script, regex, encode);                                                                                // build the word list
            parser.Add((Encoding == PackerEncoding.HighAscii) ? "\\w\\w+" : "\\w+", new ParseMaster.MatchGroupEvaluator(encodeWithLookup)); // encode
            return((script == string.Empty) ? "" : bootStrap(parser.Exec(script), encodingLookup));                                         // if encoded, wrap the script in a decoding function
        }
Beispiel #31
0
        public Mainform()
        {
            InitializeComponent();
            deleteList.Enabled = false;
            deleteWord.Enabled = false;
            addWord.Enabled    = false;
            label3.Visible     = false;


            foreach (string str in WordList.GetLists())
            {
                listViewer.Items.Add(Path.GetFileNameWithoutExtension(str));
            }
        }
Beispiel #32
0
        private void btnConvert_Click(object sender, EventArgs e)
        {
            WordList   wl;
            Serializer serializer;

            wl         = new WordList();
            serializer = new SerializerFactory().getSerializer("WordList.txt");

            serializer.loadWordList(wl);

            serializer = new SerializerFactory().getSerializer("WordList.xml");
            serializer.setChanged(true);
            serializer.saveWordList(wl);
        }
Beispiel #33
0
        public static string AutoCorrect(string word, string dicFilePath, string affFilePath)
        {
            var dictionary  = WordList.CreateFromFiles(dicFilePath, affFilePath);
            var suggestions = dictionary.Suggest(word).ToArray <string>();

            foreach (var suggestion in suggestions)
            {
                if (suggestion.Length > word.Length)
                {
                    return(suggestion);
                }
            }
            return(word);
        }
            public async Task can_find_correct_best_suggestion(string dictionaryFilePath, string givenWord, string[] expectedSuggestions)
            {
                var dictionary = await WordList.CreateFromFilesAsync(dictionaryFilePath);

                var actual = dictionary.Suggest(givenWord);

                actual.Should().NotBeNull();

                // ',' can either be a delimiter in the test data or part of the data
                var actualText   = string.Join(", ", actual);
                var expectedText = string.Join(", ", expectedSuggestions);

                actualText.Should().Be(expectedText);
            }
Beispiel #35
0
        private void CreateRecognizer(InkOverlay overlay)
        {
            Recognizers recognizers = new Recognizers();
            Recognizer english = recognizers.GetDefaultRecognizer();
            context = english.CreateRecognizerContext();

            WordList wordList = new WordList();
            for (int i = 0; i < 100; ++i)
                wordList.Add(i.ToString());

            context.WordList = wordList;
            context.Factoid = Factoid.WordList;
            context.RecognitionFlags = RecognitionModes.Coerce;
        }
Beispiel #36
0
    public void AddWordList(WordList wl)
    {
        if (wordSetLists.Contains(wl))
        {
            return;
        }
        KeywordRecognizer newKey = new KeywordRecognizer(wl.wordslist, ConfidenceLevel.Rejected);

        wordSetLists.Add(wl);
        Debug.Log(wl.wordslist);
        recogizerList.Add(newKey);
        newKey.OnPhraseRecognized += RecogSpeech;
        newKey.Start();
    }
        public Session(Account account)
        {
            this.account = account;

            knownWords = WordListFromText.get(new TextLoader(account.filenameKnown));
            trashWords = WordListFromText.get(new TextLoader(account.filenameTrash));

            appendKnown = new FileAppendWord(account.filenameKnown);
            appendTrash = new FileAppendWord(account.filenameTrash);

            filters.Add(new WordFilterNoWord());
            filters.Add(new WordFilterExistsInList(knownWords));
            filters.Add(new WordFilterExistsInList(trashWords));
        }
            public async Task can_find_good_words_in_dictionary(string dictionaryFilePath, string word)
            {
                if (dictionaryFilePath.EndsWith("base_utf.dic") && word.Contains("İ"))
                {
                    // NOTE: These tests are bypassed because capitalization only works when the language is turkish and the UTF8 dic has no language applied
                    return;
                }

                var dictionary = await WordList.CreateFromFilesAsync(dictionaryFilePath);

                var checkResult = dictionary.Check(word);

                checkResult.Should().BeTrue();
            }
Beispiel #39
0
		private static SetModel GetSetModel(WordList list) {
			Debug.Assert(list.ID != null, "list.ID != null");

			Uri uri;
			Uri.TryCreate(list.Url, UriKind.Absolute, out uri);

			return new SetModel {
				Author = list.Author,
				SetID = list.ID.Value,
				Title = list.Name,
				Uri = uri,
				Terms = (from e in list
				         select new TermModel { Term = e.Phrase, Definition = e.Translation }).ToList()
			};
		}
Beispiel #40
0
		// TODO Sync tags
		private async Task SyncSet(IQuizletService api, WordList list, CancellationToken cancel) {
			Debug.Assert(list.SyncID != null, "list.SyncID != null");
			Debug.Assert(list.ID != null, "list.ID != null");

			if (list.SyncNeeded) {
				try {
					var info = await api.FetchSetInfo(list.SyncID.Value, cancel);
					
					// Find updates from Quizlet
					var missingLocally = (from qTerm in info.Terms
										  where list.All(e => !SameTerm(e.Phrase, e.Translation, qTerm.Term, qTerm.Definition))
										  select new TranslationPair(qTerm.Term, qTerm.Definition)).ToList();

					var missingRemotely = (from lTerm in list
										   where info.Terms.All(t => !SameTerm(lTerm.Phrase, lTerm.Translation, t.Term, t.Definition))
										   select new TranslationPair(lTerm.Phrase, lTerm.Translation)).ToList();

					var modifiedLocally = list.SyncNeeded;
					var modifiedRemotely = info.Modified > list.SyncDate || !list.SyncDate.HasValue;
						
					if (modifiedLocally && modifiedRemotely) {
						// Merge conflict!
					} else if (modifiedRemotely) {
						// Apply deletions from Quizlet
						for (int i = 0; i < missingRemotely.Count; i++) {
							var qd = missingRemotely[i];
							list.Remove(e => SameTerm(e.Phrase, e.Translation, qd.Phrase, qd.Translation));
						}

						// Apply insertions from Quizlet
						foreach (var qi in missingLocally)
							list.Add(new WordListEntry(list, qi.Phrase, qi.Translation));
					} else {
						// Just push a full update of the entries to Quizlet
						var set = GetSetModel(list);
						
						// Update properties that aren't stored locally
						await api.UpdateSet(set, cancel);
					}
				} catch (Exception e) {
					OnItemError(list, e);
					return;
				}
			}

			OnItemFinished(list);
		}
Beispiel #41
0
        public static void AddNotificationsSource(WordList list)
        {
            // REDO: for multiple sources of notifications
            wordList = list;

            if (notificationsTimer == null)
            {
                notificationsTimer = new System.Timers.Timer();
                notificationsTimer.Interval = 6000; //1000*60;
                notificationsTimer.AutoReset = false;
                notificationsTimer.Elapsed += notificationsTimer_Elapsed;
                notificationsTimer.Start();

                uiContext = SynchronizationContext.Current;

                uiContext.Send(ShowNotification, "test");
            }
        }
Beispiel #42
0
        public void Run()
        {
            WordList wordList = new WordList();
            WordObserver wordObserver = new WordObserver();

            wordList.Attatch(wordObserver);
            {
                wordList.Messages.Add("Hello");
                wordList.NotifyAll();

                wordList.Messages.Add("Message");

                wordList.Messages.Add("Tester");
                foreach(IObserver ob in wordList.GetObservers())
                {
                    wordList.Notify(ob);
                }
            }
            wordList.Detach(wordObserver);
        }
Beispiel #43
0
        private WordList GetHash(string text)
        {
            WordList wordList = new WordList();
            text = Util.CleanText(text);
            string[] words = text.Split(' ');
            StartProgressBar(words.Length);
            foreach (string word in words)
            {
                wordList.SaveWord(word);
                ChangeProgressBar();
            }

            return wordList;
        }
Beispiel #44
0
        /* private void ListByWord(SortedList wordList)
        {
            foreach (string word in wordList.Keys)
            {
                Console.WriteLine(string.Format("{0}: {1}", word, wordList[word]));
            }
        }*/
        private void ListByWordCount(WordList wordList)
        {
            wordList.Sort();

            foreach (Occurency occurency in wordList)
            {
                AddInResultList(string.Format("{0}: {1}", occurency.Word.ToLower(), occurency.Count));
            }
        }
Beispiel #45
0
		protected void OnMergeConflict(WordList set, MergeConflict conflict) {
			var h = MergeConflict;
			if (h != null)
				SynchronizationContext.Current.Post(x => h(this, set, conflict), null);
		}
Beispiel #46
0
		protected void OnItemError(WordList set, Exception exception) {
			var h = ItemError;
			if (h != null)
				SynchronizationContext.Current.Post(x => h(this, set, exception), null);
		}
Beispiel #47
0
		protected void OnItemFinished(WordList set) {
			var h = ItemFinished;
			if (h != null)
				SynchronizationContext.Current.Post(x => h(this, set), null);
		}
Beispiel #48
0
        /// <summary>
        /// Adds the specified word to the appropriate word list.
        /// </summary>
        /// <param name="word">The word to add.</param>
        private static void PutWord(string word)
        {
            if (string.IsNullOrEmpty(word))
                return;

            if (_wordLists == null)
                _wordLists = new List<WordList>();

            WordList wordList = _wordLists.SingleOrDefault(e => e.WordLength == word.Length);

            if (wordList == null)
            {
                wordList = new WordList { WordLength = word.Length };
                _wordLists.Add(wordList);
            }

            wordList.Add(word);
        }
        private string encodeSpecialChars(string script)
        {
            ParseMaster parser = new ParseMaster();
            // replace: $name -> n, $$name -> na
            parser.Add("((\\$+)([a-zA-Z\\$_]+))(\\d*)",
                new ParseMaster.MatchGroupEvaluator(encodeLocalVars));

            // replace: _name -> _0, double-underscore (__name) is ignored
            Regex regex = new Regex("\\b_[A-Za-z\\d]\\w*");

            // build the word list
            encodingLookup = analyze(script, regex, new EncodeMethod(encodePrivate));

            parser.Add("\\b_[A-Za-z\\d]\\w*", new ParseMaster.MatchGroupEvaluator(encodeWithLookup));

            script = parser.Exec(script);
            return script;
        }
 /// <summary>
 /// Adds the pair to the relation
 /// </summary>
 /// <param name="relationName"></param>
 /// <param name="a"></param>
 /// <param name="b"></param>
 void add(WordList relationName, ZObject a, ZObject b)
 {
     relation2Add[relationName](a,b);
 }
    void define(WordList relationName)
    {
        // Get the relation for the name; if none exists, add the structure
          Dictionary<ZObject,ZEdge> relation;
          if (!relation2.TryGetValue(relationName, out relation))
          {
         // Define a structure to hold the relation
         relation2[relationName] = relation = new Dictionary<ZObject,ZEdge>();
          }

          // Create a delegate to add the items in directed
          relation2Add[relationName] =  delegate(ZObject source, ZObject sink)
          {
         ZEdge edge;
         // Add the entry to the table.. if none exists.
         if (!relation.TryGetValue(source, out edge))
         {
            // Doesn't exist, create the relation
            relation[source] = new ZEdge(newName(), sink, null);
            return;
         }
         // Check that the relation is sensible
         if (edge.sink == sink)
            return;
         // Oh-oh, there is a problem.
          };
    }
 /// <summary>
 /// A direction
 /// </summary>
 /// <returns>The new object</returns>
 ZObject Direction(WordList nouns)
 {
     var ret= Kind((ZObject) Object(), dirKind);
       ret.shortDescription=nouns.words[0];
       ret.nouns = nouns;
       return ret;
 }
Beispiel #53
0
    // Update is called once per frame
    void Update()
    {
        if (gameStart)
        {
            if (roundStart)
            {
                //Getting a new word list
                if (!isWordListLoaded)
                {
                    currentWordList = LoadWordList();
                    //sendWordList();
                    isWordListLoaded = true;
                    comboTime = 30;
                }
                comboTime -= Time.deltaTime;
                //Check if the word is loaded if not loads the word and clears old hit boxes
                if (!isWordLoaded)
                {
                    currentWord = LoadWord(currentWordList);
                    usedWords.Add(currentWord);
                    if (options.WhichInput() == "drag")
                    {
                        ClearWordHitBoxes();
                        CreateWordHitBoxes(currentWord);
                    }
                    isStreak = true;
                    isWordLoaded = true;
                }
                //Check if the word has had the vowels filled in
                if (currentWord.ToLower() == displayWord(currentWord).ToLower())
                {
                    StartCoroutine(WaitFor(0.5f));

                    if (changeWord)
                    {
                        player.attack += wordDiffculty(currentWord);
                        isWordLoaded = false;
                        //Did the player get a Combo?!?
                        if (timeSinceLastWord - comboTime < 5.0f)
                        {
                            player.currentCombo++;
                        }
                        else
                        {
                            //Player combo too good please nerf
                            if (player.currentCombo > player.bestCombo)
                            {
                                player.bestCombo = player.currentCombo;
                            }
                            player.currentCombo = 0;
                        }
                        timeSinceLastWord = comboTime;
                        if (isStreak)
                        {
                            player.defence += wordDiffculty(currentWord) / 3;
                            player.currentStreak++;
                        }
                    }
                }
                else
                {
                    changeWord = false;
                }
                //is the round over already!?
                if (comboTime < 0)
                {
                    roundStart = false;
                    isWordListLoaded = false;
                    isWordLoaded = false;
                    currentRound++;
                    EndStreak();
                    if (player.currentCombo > player.bestCombo)
                    {
                        player.bestCombo = player.currentCombo;
                    }
                    player.currentCombo = 0;

                    isRoundLoading = true;
                    roundStart = true;
                    DontDestroyOnLoad(gameObject);
                    DontDestroyOnLoad(GameObject.Find("Player"));
                    DontDestroyOnLoad(GameObject.Find("Participant"));
                    Application.LoadLevel("Timeless");
                }
            }
        }
    }
Beispiel #54
0
 // Use this for initialization
 void Start()
 {
     currentWordList = WordList.Food;
     currentWord = "peanut";
     textBox = new Rect(0,0,0,0);
     tutorialArrow = new Rect(0, 0, Screen.width / 4, Screen.width /4);
 }
        private string bootStrap(string packed, WordList keywords)
        {
            // packed: the packed script
            packed = "'" + escape(packed) + "'";

            // ascii: base for encoding
            int ascii = Math.Min(keywords.Sorted.Count, (int) Encoding);
            if (ascii == 0)
                ascii = 1;

            // count: number of words contained in the script
            int count = keywords.Sorted.Count;

            // keywords: list of words contained in the script
            foreach (object key in keywords.Protected.Keys)
            {
                keywords.Sorted[(int) key] = "";
            }
            // convert from a string to an array
            StringBuilder sbKeywords = new StringBuilder("'");
            foreach (string word in keywords.Sorted)
                sbKeywords.Append(word + "|");
            sbKeywords.Remove(sbKeywords.Length-1, 1);
            string keywordsout = sbKeywords.ToString() + "'.split('|')";

            string encode;
            string inline = "c";

            switch (Encoding)
            {
                case PackerEncoding.Mid:
                    encode = "function(c){return c.toString(36)}";
                    inline += ".toString(a)";
                    break;
                case PackerEncoding.Normal:
                    encode = "function(c){return(c<a?\"\":e(parseInt(c/a)))+" +
                        "((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))}";
                    inline += ".toString(a)";
                    break;
                case PackerEncoding.HighAscii:
                    encode = "function(c){return(c<a?\"\":e(c/a))+" +
                        "String.fromCharCode(c%a+161)}";
                    inline += ".toString(a)";
                    break;
                default:
                    encode = "function(c){return c}";
                    break;
            }

            // decode: code snippet to speed up decoding
            string decode = "";
            if (fastDecode)
            {
                decode = "if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\\\w+'};c=1;}";
                if (Encoding == PackerEncoding.HighAscii)
                    decode = decode.Replace("\\\\w", "[\\xa1-\\xff]");
                else if (Encoding == PackerEncoding.Numeric)
                    decode = decode.Replace("e(c)", inline);
                if (count == 0)
                    decode = decode.Replace("c=1", "c=0");
            }

            // boot function
            string unpack = "function(p,a,c,k,e,d){while(c--)if(k[c])p=p.replace(new RegExp('\\\\b'+e(c)+'\\\\b','g'),k[c]);return p;}";
            Regex r;
            if (fastDecode)
            {
                //insert the decoder
                r = new Regex("\\{");
                unpack = r.Replace(unpack, "{" + decode + ";", 1);
            }

            if (Encoding == PackerEncoding.HighAscii)
            {
                // get rid of the word-boundries for regexp matches
                r = new Regex("'\\\\\\\\b'\\s*\\+|\\+\\s*'\\\\\\\\b'");
                unpack = r.Replace(unpack, "");
            }
            if (Encoding == PackerEncoding.HighAscii || ascii > (int) PackerEncoding.Normal || fastDecode)
            {
                // insert the encode function
                r = new Regex("\\{");
                unpack = r.Replace(unpack, "{e=" + encode + ";", 1);
            }
            else
            {
                r = new Regex("e\\(c\\)");
                unpack = r.Replace(unpack, inline);
            }
            // no need to pack the boot function since i've already done it
            string _params = "" + packed + "," + ascii + "," + count + "," + keywordsout;
            if (fastDecode)
            {
                //insert placeholders for the decoder
                _params += ",0,{}";
            }
            // the whole thing
            return "eval(" + unpack + "(" + _params + "))\n";
        }
Beispiel #56
0
    // Use this for initialization
    void Start()
    {
        #region LoadWords
         ArtText = (TextAsset)Resources.Load("Art");
         BathroomText = (TextAsset)Resources.Load("Bathroom") as TextAsset;
         ClothingText = (TextAsset)Resources.Load("Clothing") as TextAsset;
         ComputerText = (TextAsset)Resources.Load("Computer") as TextAsset;
         FarmText = (TextAsset)Resources.Load("Farm") as TextAsset;
         FlowersText = (TextAsset)Resources.Load("Flowers") as TextAsset;
         FoodText = (TextAsset)Resources.Load("Food") as TextAsset;
         HumanBodyText = (TextAsset)Resources.Load("Human Body") as TextAsset;
         JobsText = (TextAsset)Resources.Load("Jobs") as TextAsset;
         MoneyText = (TextAsset)Resources.Load("Money") as TextAsset;
         OfficeText = (TextAsset)Resources.Load("Office") as TextAsset;
         PublicBuildingsText = (TextAsset)Resources.Load("Public Buildings") as TextAsset;
         SchoolText = (TextAsset)Resources.Load("School") as TextAsset;
         SportsText = (TextAsset)Resources.Load("Sports") as TextAsset;
         WeatherText = (TextAsset)Resources.Load("Weather") as TextAsset;

        WordLists = new List<List<string>>();

        Art = new List<string>();
        Art = CreateWordList(ArtText.text);
        WordLists.Add(Art);

        Bathroom = new List<string>();
        Bathroom = CreateWordList(BathroomText.text);
        WordLists.Add(Bathroom);

        Clothing = new List<string>();
        Clothing = CreateWordList(ClothingText.text);
        WordLists.Add(Clothing);

        Computer = new List<string>();
        Computer = CreateWordList(ComputerText.text);
        WordLists.Add(Computer);

        Farm = new List<string>();
        Farm = CreateWordList(FarmText.text);
        WordLists.Add(Farm);

        Flowers = new List<string>();
        Flowers = CreateWordList(FlowersText.text);
        WordLists.Add(Flowers);

        Food = new List<string>();
        Food = CreateWordList(FoodText.text);
        WordLists.Add(Food);

        HumanBody = new List<string>();
        HumanBody = CreateWordList(HumanBodyText.text);
        WordLists.Add(HumanBody);

        Jobs = new List<string>();
        Jobs = CreateWordList(JobsText.text);
        WordLists.Add(Jobs);

        Money = new List<string>();
        Money = CreateWordList(MoneyText.text);
        WordLists.Add(Money);

        Office = new List<string>();
        Office = CreateWordList(OfficeText.text);
        WordLists.Add(Office);

        PublicBuildings = new List<string>();
        PublicBuildings = CreateWordList(PublicBuildingsText.text);
        WordLists.Add(PublicBuildings);

        School = new List<string>();
        School = CreateWordList(SchoolText.text);
        WordLists.Add(School);

        Sports = new List<string>();
        Sports = CreateWordList(SportsText.text);
        WordLists.Add(Sports);

        Weather = new List<string>();
        Weather = CreateWordList(WeatherText.text);
        WordLists.Add(Weather);
        #endregion

        gameStart = false;
        roundStart = false;
        isWordLoaded = false;
        isWordListLoaded = false;
        comboTime = 30.0f;
        pauseGame = false;
        currentRound = 1;
        totalRound = 3;
        currentWord = "";
        currentWordList = 0;
        hitBoxes = new List<GameObject>();
        options = GameObject.Find("Options").GetComponent<Options>();
        waitActive = false;
        changeWord = false;
        missingVowel = "_";
        usedWords = new List<string>();
        timeSinceLastWord = 0;
        isStreak = false;
        roundLoadScreen = 3;
        isRoundLoading = false;
        battleMode = true;

        if (GameObject.Find("GameLogic"))
        {
            GameObject.Find("GameLogic").GetComponent<Battle>().roundStart = true;
            GameObject.Find("GameLogic").GetComponent<Battle>().isRoundLoading = false;
            Destroy(gameObject);
        }
        else
        {
            gameObject.name = "GameLogic";
        }
        if (player == null)
        {
            player = GameObject.Find("Player").GetComponent<VowellessPlayer>();
        }
        if (participant == null)
        {
            participant = GameObject.Find("Participant").GetComponent<VowellessPlayer>();
        }
    }
        private string encodeKeywords(string script)
        {
            // escape high-ascii values already in the script (i.e. in strings)
            if (Encoding == PackerEncoding.HighAscii) script = escape95(script);
            // create the parser
            ParseMaster parser = new ParseMaster();
            EncodeMethod encode = getEncoder(Encoding);

            // for high-ascii, don't encode single character low-ascii
            Regex regex = new Regex(
                    (Encoding == PackerEncoding.HighAscii) ? "\\w\\w+" : "\\w+"
                );
            // build the word list
            encodingLookup = analyze(script, regex, encode);

            // encode
            parser.Add((Encoding == PackerEncoding.HighAscii) ? "\\w\\w+" : "\\w+",
                new ParseMaster.MatchGroupEvaluator(encodeWithLookup));

            // if encoded, wrap the script in a decoding function
            return (script == string.Empty) ? "" : bootStrap(parser.Exec(script), encodingLookup);
        }
Beispiel #58
0
 string LoadWord(WordList currentList)
 {
     string temp = WordLists[(int)currentList][(int)Random.Range(0, WordLists[(int)currentList].Count)];
     if(usedWords.Count > 0)
     {
         for (int i = 0; i < usedWords.Count; i++)
         {
             if(temp == usedWords[i])
             return LoadWord(currentList);
         }
     }
     return temp;
 }
Beispiel #59
0
 public DictionaryGrid(WordList dataSource)
     : this()
 {
     DataSource = dataSource;
 }
Beispiel #60
0
 void Awake()
 {
     S = this;
 }