public void matching_texts_and_whitespaces() { string s = " AB \t\r C"; var m = new StringMatcher( s ); Assert.That( m.MatchText( "A" ), Is.False ); Assert.That( m.StartIndex, Is.EqualTo( 0 ) ); Assert.That( m.MatchWhiteSpaces(), Is.True ); Assert.That( m.StartIndex, Is.EqualTo( 1 ) ); Assert.That( m.MatchText( "A" ), Is.True ); Assert.That( m.MatchText( "B" ), Is.True ); Assert.That( m.StartIndex, Is.EqualTo( 3 ) ); Assert.That( m.MatchWhiteSpaces( 6 ), Is.False ); Assert.That( m.MatchWhiteSpaces( 5 ), Is.True ); Assert.That( m.StartIndex, Is.EqualTo( 8 ) ); Assert.That( m.MatchWhiteSpaces(), Is.False ); Assert.That( m.StartIndex, Is.EqualTo( 8 ) ); Assert.That( m.MatchText( "c" ), Is.True ); Assert.That( m.StartIndex, Is.EqualTo( s.Length ) ); Assert.That( m.IsEnd, Is.True ); Assert.DoesNotThrow( () => m.MatchText( "c" ) ); Assert.DoesNotThrow( () => m.MatchWhiteSpaces() ); Assert.That( m.MatchText( "A" ), Is.False ); Assert.That( m.MatchWhiteSpaces(), Is.False ); }
public void matching_integers() { var m = new StringMatcher( "X3712Y" ); Assert.That( m.MatchChar( 'X' ) ); int i; Assert.That( m.MatchInt32( out i ) && i == 3712 ); Assert.That( m.MatchChar( 'Y' ) ); }
public void match_methods_must_set_an_error() { var m = new StringMatcher( "A" ); CheckMatchError( m, () => m.MatchChar( 'B' ) ); int i; CheckMatchError( m, () => m.MatchInt32( out i ) ); CheckMatchError( m, () => m.MatchText( "PP" ) ); CheckMatchError( m, () => m.MatchText( "B" ) ); CheckMatchError( m, () => m.MatchWhiteSpaces() ); }
public void matching_integers_with_min_max_values() { var m = new StringMatcher( "3712 -435 56" ); int i; Assert.That( m.MatchInt32( out i, -500, -400 ), Is.False ); Assert.That( m.MatchInt32( out i, 0, 3712 ) && i == 3712 ); Assert.That( m.MatchWhiteSpaces() ); Assert.That( m.MatchInt32( out i, 0 ), Is.False ); Assert.That( m.MatchInt32( out i, -500, -400 ) && i == -435 ); Assert.That( m.MatchWhiteSpaces() ); Assert.That( m.MatchInt32( out i, 1000, 2000 ), Is.False ); Assert.That( m.MatchInt32( out i, 56, 56 ) && i == 56 ); Assert.That( m.IsEnd ); }
public void simple_char_matching() { string s = "ABCD"; var m = new StringMatcher( s ); Assert.That( m.MatchChar( 'a' ), Is.False ); Assert.That( m.MatchChar( 'A' ), Is.True ); Assert.That( m.StartIndex, Is.EqualTo( 1 ) ); Assert.That( m.MatchChar( 'A' ), Is.False ); Assert.That( m.MatchChar( 'B' ), Is.True ); Assert.That( m.MatchChar( 'C' ), Is.True ); Assert.That( m.IsEnd, Is.False ); Assert.That( m.MatchChar( 'D' ), Is.True ); Assert.That( m.MatchChar( 'D' ), Is.False ); Assert.That( m.IsEnd, Is.True ); }
public static StringMatcher BuildMatcherFromLists(params List <string>[] collections) { StringMatcher matcher = new StringMatcher(MatchStrategy.TrieTree, new NumberWithUnitTokenizer()); List <string> matcherList = new List <string>(); foreach (List <string> collection in collections) { collection.ForEach(o => matcherList.Add(o.Trim().ToLowerInvariant())); } matcherList = matcherList.Distinct().ToList(); matcher.Init(matcherList); return(matcher); }
public ThaiMergedParserConfiguration(DateTimeOptions options) : base(options | DateTimeOptions.Format24) { BeforeRegex = ThaiMergedExtractorConfiguration.BeforeRegex; AfterRegex = ThaiMergedExtractorConfiguration.AfterRegex; SinceRegex = ThaiMergedExtractorConfiguration.SinceRegex; YearAfterRegex = ThaiMergedExtractorConfiguration.YearAfterRegex; YearRegex = ThaiDatePeriodExtractorConfiguration.YearRegex; SuperfluousWordMatcher = null; DatePeriodParser = new BaseDatePeriodParser(new ThaiDatePeriodParserConfiguration(this)); TimePeriodParser = new BaseTimePeriodParser(new ThaiTimePeriodParserConfiguration(this)); DateTimePeriodParser = new BaseDateTimePeriodParser(new ThaiDateTimePeriodParserConfiguration(this)); GetParser = null; HolidayParser = null; TimeZoneParser = new BaseTimeZoneParser(); }
public static bool TryParse(IActivityMonitor m, string text, out BaseNode b) { if (text == null) { throw new ArgumentNullException(nameof(text)); } var matcher = new StringMatcher(text); b = Parse(matcher); if (matcher.IsError) { m.Error($"Error while parsing condition @{matcher.StartIndex} '{text}': {matcher.ErrorMessage}."); return(false); } return(true); }
public IStringMatcher CreateStringMatcher(string NameSpace, IEnumerable <string> Patterns) { StringMatcher matcher; Regex regex; matcher = new StringMatcher(); foreach (string pattern in Patterns) { if (!Try(() => regexBuilder.Build(NameSpace, pattern, false)).OrAlert(out regex, $"Failed to build regex: {pattern}")) { continue; } matcher.Add(regex); } return(matcher); }
public ModuleMatcher(ConfigNode identifierNode) { this.identifierNode = identifierNode ?? throw new ArgumentNullException(nameof(identifierNode)); string moduleNameStr = identifierNode.GetValue("name"); if (moduleNameStr == null) { throw new ArgumentException("node has no name", nameof(identifierNode)); } if (moduleNameStr == "") { throw new ArgumentException("node has empty name", nameof(identifierNode)); } moduleName = StringMatcher.Parse(moduleNameStr); }
public Result Create(IPublicAPI contextApi) { return(new Result(StringMatcher.FuzzySearch(Search, Title).MatchData) { Title = Title, IcoPath = Path, // Using CurrentCulture since this is user facing SubTitle = string.Format(CultureInfo.CurrentCulture, Properties.Resources.wox_plugin_folder_select_folder_result_subtitle, Subtitle), QueryTextDisplay = Path, ContextData = new SearchResult { Type = ResultType.Folder, FullPath = Path }, Action = c => _shellAction.Execute(Path, contextApi), }); }
public Wox.Plugin.Result Create(IPublicAPI contextApi) { var result = new Wox.Plugin.Result { Title = Title, SubTitle = string.Format(CultureInfo.CurrentCulture, Properties.Resources.wox_plugin_folder_select_file_result_subtitle, FilePath), IcoPath = FilePath, TitleHighlightData = StringMatcher.FuzzySearch(Search, Path.GetFileName(FilePath)).MatchData, Action = c => ShellAction.Execute(FilePath, contextApi), ContextData = new SearchResult { Type = ResultType.File, FullPath = FilePath }, }; return(result); }
public void simple_char_matching() { string s = "ABCD"; var m = new StringMatcher(s); m.MatchChar('a').Should().BeFalse(); m.MatchChar('A').Should().BeTrue(); m.StartIndex.Should().Be(1); m.MatchChar('A').Should().BeFalse(); m.MatchChar('B').Should().BeTrue(); m.MatchChar('C').Should().BeTrue(); m.IsEnd.Should().BeFalse(); m.MatchChar('D').Should().BeTrue(); m.MatchChar('D').Should().BeFalse(); m.IsEnd.Should().BeTrue(); }
public EnglishMergedParserConfiguration(DateTimeOptions options) : base(options) { BeforeRegex = EnglishMergedExtractorConfiguration.BeforeRegex; AfterRegex = EnglishMergedExtractorConfiguration.AfterRegex; SinceRegex = EnglishMergedExtractorConfiguration.SinceRegex; YearAfterRegex = EnglishMergedExtractorConfiguration.YearAfterRegex; YearRegex = EnglishDatePeriodExtractorConfiguration.YearRegex; SuperfluousWordMatcher = EnglishMergedExtractorConfiguration.SuperfluousWordMatcher; DatePeriodParser = new BaseDatePeriodParser(new EnglishDatePeriodParserConfiguration(this)); TimePeriodParser = new BaseTimePeriodParser(new EnglishTimePeriodParserConfiguration(this)); DateTimePeriodParser = new BaseDateTimePeriodParser(new EnglishDateTimePeriodParserConfiguration(this)); GetParser = new BaseSetParser(new EnglishSetParserConfiguration(this)); HolidayParser = new BaseHolidayParser(new EnglishHolidayParserConfiguration()); TimeZoneParser = new BaseTimeZoneParser(); }
public GermanMergedParserConfiguration(IOptionsConfiguration config) : base(config) { BeforeRegex = GermanMergedExtractorConfiguration.BeforeRegex; AfterRegex = GermanMergedExtractorConfiguration.AfterRegex; SinceRegex = GermanMergedExtractorConfiguration.SinceRegex; AroundRegex = GermanMergedExtractorConfiguration.AroundRegex; DateAfter = GermanMergedExtractorConfiguration.DateAfterRegex; YearRegex = GermanDatePeriodExtractorConfiguration.YearRegex; SuperfluousWordMatcher = GermanMergedExtractorConfiguration.SuperfluousWordMatcher; DatePeriodParser = new BaseDatePeriodParser(new GermanDatePeriodParserConfiguration(this)); TimePeriodParser = new BaseTimePeriodParser(new GermanTimePeriodParserConfiguration(this)); DateTimePeriodParser = new BaseDateTimePeriodParser(new GermanDateTimePeriodParserConfiguration(this)); SetParser = new BaseSetParser(new GermanSetParserConfiguration(this)); HolidayParser = new BaseHolidayParser(new GermanHolidayParserConfiguration(this)); TimeZoneParser = new BaseTimeZoneParser(); }
public PortugueseMergedParserConfiguration(IOptionsConfiguration config) : base(config) { BeforeRegex = PortugueseMergedExtractorConfiguration.BeforeRegex; AfterRegex = PortugueseMergedExtractorConfiguration.AfterRegex; SinceRegex = PortugueseMergedExtractorConfiguration.SinceRegex; YearAfterRegex = PortugueseMergedExtractorConfiguration.YearAfterRegex; YearRegex = PortugueseDatePeriodExtractorConfiguration.YearRegex; SuperfluousWordMatcher = PortugueseMergedExtractorConfiguration.SuperfluousWordMatcher; DatePeriodParser = new BaseDatePeriodParser(new PortugueseDatePeriodParserConfiguration(this)); TimePeriodParser = new BaseTimePeriodParser(new PortugueseTimePeriodParserConfiguration(this)); DateTimePeriodParser = new DateTimePeriodParser(new PortugueseDateTimePeriodParserConfiguration(this)); SetParser = new BaseSetParser(new PortugueseSetParserConfiguration(this)); HolidayParser = new BaseHolidayParser(new PortugueseHolidayParserConfiguration(this)); TimeZoneParser = new BaseTimeZoneParser(); }
public List <Result> Query(Query query) { List <Result> results = new List <Result>(); foreach (Result availableResult in availableResults) { int titleScore = StringMatcher.Match(availableResult.Title, query.Search); int subTitleScore = StringMatcher.Match(availableResult.SubTitle, query.Search); if (titleScore > 0 || subTitleScore > 0) { availableResult.Score = titleScore > 0 ? titleScore : subTitleScore; results.Add(availableResult); } } return(results); }
private Result CreateResult(string keyword, SearchResult searchResult, int index) { var path = searchResult.FullPath; string workingDir = null; if (_settings.UseLocationAsWorkingDir) { workingDir = Path.GetDirectoryName(path); } var r = new Result { Title = Path.GetFileName(path), Score = _settings.MaxSearchCount - index, SubTitle = path, IcoPath = path, TitleHighlightData = StringMatcher.FuzzySearch(keyword, Path.GetFileName(path)).MatchData, Action = c => { bool hide; try { Process.Start(new ProcessStartInfo { FileName = path, UseShellExecute = true, WorkingDirectory = workingDir }); hide = true; } catch (Win32Exception) { var name = $"Plugin: {_context.CurrentPluginMetadata.Name}"; var message = "Can't open this file"; _context.API.ShowMsg(name, message, string.Empty); hide = false; } return(hide); }, ContextData = searchResult, SubTitleHighlightData = StringMatcher.FuzzySearch(keyword, path).MatchData }; return(r); }
public List <Result> Query(Query query) { var results = new List <Result>(); if (query == null) { return(results); } CultureInfo culture = _localizeSystemCommands ? CultureInfo.CurrentUICulture : new CultureInfo("en-US"); var systemCommands = Commands.GetSystemCommands(IsBootedInUefiMode, IconTheme, culture, _confirmSystemCommands); var networkConnectionResults = Commands.GetNetworkConnectionResults(IconTheme, culture); foreach (var c in systemCommands) { var resultMatch = StringMatcher.FuzzySearch(query.Search, c.Title); if (resultMatch.Score > 0) { c.Score = resultMatch.Score; c.TitleHighlightData = resultMatch.MatchData; results.Add(c); } } foreach (var r in networkConnectionResults) { // On global queries the first word/part has to be 'ip', 'mac' or 'address' if (string.IsNullOrEmpty(query.ActionKeyword)) { string[] keywordList = Resources.ResourceManager.GetString("Microsoft_plugin_sys_Search_NetworkKeywordList", culture).Split("; "); if (!keywordList.Any(x => query.Search.StartsWith(x, StringComparison.CurrentCultureIgnoreCase))) { continue; } } var resultMatch = StringMatcher.FuzzySearch(query.Search, r.SubTitle); if (resultMatch.Score > 0) { r.Score = _reduceNetworkResultScore ? (int)(resultMatch.Score * 65 / 100) : resultMatch.Score; // Adjust score to improve user experience and priority order r.SubTitleHighlightData = resultMatch.MatchData; results.Add(r); } } return(results); }
/// <summary> /// Selects the folder quickset with the specified name. /// </summary> /// <param name="quicksetName">The quickset name.</param> public void SelectQuickset(string quicksetName) { WidgetCollection quicksetWidgets = _controlPanel.GetWidgets().OfType(WidgetType.HelpListItem); string bestMatch = StringMatcher.FindBestMatch(quicksetName, quicksetWidgets.Select(n => n.Text), StringMatch.StartsWith, ignoreCase: true, ignoreWhiteSpace: true, allowPartialMatch: true); if (bestMatch != null) { Widget quickset = _controlPanel.ScrollToItem("StringContent1", bestMatch); _controlPanel.Press(quickset); Pacekeeper.Sync(); } else { throw new DeviceWorkflowException($"Could not find the quickset '{quicksetName}'."); } }
public List <Result> Query(Query query) { var results = new List <Result>(); foreach (var item in controlPanelItems) { var titleMatch = StringMatcher.FuzzySearch(query.Search, item.LocalizedString); item.Score = titleMatch.Score; if (item.Score > 0) { var result = new Result { Title = item.LocalizedString, TitleHighlightData = titleMatch.MatchData, SubTitle = item.InfoTip, Score = item.Score, IcoPath = item.IconPath, Action = e => { try { Process.Start(item.ExecutablePath); } catch (Exception ex) { ex.Data.Add(nameof(item.LocalizedString), item.LocalizedString); ex.Data.Add(nameof(item.ExecutablePath), item.ExecutablePath); ex.Data.Add(nameof(item.IconPath), item.IconPath); ex.Data.Add(nameof(item.GUID), item.GUID); Logger.WoxError($"cannot start control panel item {item.ExecutablePath}", ex); } return(true); } }; results.Add(result); } } var panelItems = results.OrderByDescending(o => o.Score).Take(5).ToList(); return(panelItems); }
internal static bool MatchProgram(Bookmark bookmark, string queryString) { if (StringMatcher.FuzzySearch(queryString, bookmark.Name).IsSearchPrecisionScoreMet()) { return(true); } if (StringMatcher.FuzzySearch(queryString, bookmark.PinyinName).IsSearchPrecisionScoreMet()) { return(true); } if (StringMatcher.FuzzySearch(queryString, bookmark.Url).IsSearchPrecisionScoreMet()) { return(true); } return(false); }
public void matching_the_5_forms_of_guid(string form) { var id = Guid.NewGuid(); string sId = id.ToString(form); { string s = sId; var m = new StringMatcher(s); Guid readId; m.TryMatchGuid(out readId).Should().BeTrue(); readId.Should().Be(id); } { string s = "S" + sId; var m = new StringMatcher(s); Guid readId; m.TryMatchChar('S').Should().BeTrue(); m.TryMatchGuid(out readId).Should().BeTrue(); readId.Should().Be(id); } { string s = "S" + sId + "T"; var m = new StringMatcher(s); Guid readId; m.MatchChar('S').Should().BeTrue(); m.TryMatchGuid(out readId).Should().BeTrue(); readId.Should().Be(id); m.MatchChar('T').Should().BeTrue(); } sId = sId.Remove(sId.Length - 1); { string s = sId; var m = new StringMatcher(s); Guid readId; m.TryMatchGuid(out readId).Should().BeFalse(); m.StartIndex.Should().Be(0); } sId = id.ToString().Insert(3, "K").Remove(4); { string s = sId; var m = new StringMatcher(s); Guid readId; m.TryMatchGuid(out readId).Should().BeFalse(); m.StartIndex.Should().Be(0); } }
public List <Result> Query(Query query) { var commands = Commands(); var results = new List <Result>(); foreach (var c in commands) { var titleMatch = StringMatcher.FuzzySearch(query.Search, c.Title); if (titleMatch.Score > 0) { c.Score = titleMatch.Score; c.TitleHighlightData = titleMatch.MatchData; results.Add(c); } } return(results); }
public void WhenGivenStringsForCalScoreMethodThenShouldReturnCurrentScoring() { // Arrange string searchTerm = "chrome"; // since this looks for specific results it will always be one case var searchStrings = new List <string> { Chrome, //SCORE: 107 LastIsChrome, //SCORE: 53 HelpCureHopeRaiseOnMindEntityChrome, //SCORE: 21 UninstallOrChangeProgramsOnYourComputer, //SCORE: 15 CandyCrushSagaFromKing //SCORE: 0 } .OrderByDescending(x => x) .ToList(); // Act var results = new List <Result>(); foreach (var str in searchStrings) { results.Add(new Result { Title = str, Score = StringMatcher.FuzzySearch(searchTerm, str).RawScore }); } // Assert VerifyResult(147, Chrome); VerifyResult(93, LastIsChrome); VerifyResult(41, HelpCureHopeRaiseOnMindEntityChrome); VerifyResult(35, UninstallOrChangeProgramsOnYourComputer); VerifyResult(0, CandyCrushSagaFromKing); void VerifyResult(int expectedScore, string expectedTitle) { var result = results.FirstOrDefault(x => x.Title == expectedTitle); if (result == null) { Assert.Fail($"Fail to find result: {expectedTitle} in result list"); } Assert.AreEqual(expectedScore, result.Score, $"Expected score for {expectedTitle}: {expectedScore}, Actual: {result.Score}"); } }
public List <Result> Query(Query query) { List <Result> results = new List <Result>(); foreach (Result availableResult in availableResults) { var titleScore = StringMatcher.Score(availableResult.Title, query.Search); var subTitleScore = StringMatcher.Score(availableResult.SubTitle, query.Search); var score = Math.Max(titleScore, subTitleScore); if (score > 0) { availableResult.Score = score; results.Add(availableResult); } } return(results); }
public SpanishMergedParserConfiguration(IOptionsConfiguration config) : base(config) { BeforeRegex = SpanishMergedExtractorConfiguration.BeforeRegex; AfterRegex = SpanishMergedExtractorConfiguration.AfterRegex; SinceRegex = SpanishMergedExtractorConfiguration.SinceRegex; AroundRegex = SpanishMergedExtractorConfiguration.AroundRegex; DateAfter = SpanishMergedExtractorConfiguration.DateAfterRegex; YearRegex = SpanishDatePeriodExtractorConfiguration.YearRegex; SuperfluousWordMatcher = SpanishMergedExtractorConfiguration.SuperfluousWordMatcher; DatePeriodParser = new BaseDatePeriodParser(new SpanishDatePeriodParserConfiguration(this)); TimePeriodParser = new BaseTimePeriodParser(new SpanishTimePeriodParserConfiguration(this)); DateTimePeriodParser = new DateTimePeriodParser(new SpanishDateTimePeriodParserConfiguration(this)); SetParser = new BaseSetParser(new SpanishSetParserConfiguration(this)); HolidayParser = new BaseHolidayParser(new SpanishHolidayParserConfiguration(this)); TimeZoneParser = new DummyTimeZoneParser(); }
public void TestStringMatcher() { var utc8Value = "UTC+08:00"; var utc8Words = new List <string>() { "beijing time", "chongqing time", "hong kong time", "urumqi time", }; var utc2Value = "UTC+02:00"; var utc2Words = new List <string>() { "cairo time", "beirut time", "gaza time", "amman time", }; var valueDictionary = new Dictionary <string, List <string> >() { { utc8Value, utc8Words }, { utc2Value, utc2Words }, }; var stringMatcher = new StringMatcher(); stringMatcher.Init(valueDictionary); foreach (var value in utc8Words) { var sentence = $"please change {value}, thanks"; var matches = stringMatcher.Find(sentence); Assert.AreEqual(value, matches.Single().Text); Assert.AreEqual(utc8Value, matches.Single().CanonicalValues.First()); Assert.AreEqual(14, matches.Single().Start); } foreach (var value in utc2Words) { var sentence = $"please change {value}, thanks"; var matches = stringMatcher.Find(sentence); Assert.AreEqual(value, matches.Single().Text); Assert.AreEqual(utc2Value, matches.Single().CanonicalValues.First()); Assert.AreEqual(14, matches.Single().Start); } }
private void QueryHistory() { const string id = "Query History ID"; #pragma warning disable CA1308 // Normalize strings to uppercase var query = QueryText.ToLower(CultureInfo.InvariantCulture).Trim(); #pragma warning restore CA1308 // Normalize strings to uppercase History.Clear(); var results = new List <Result>(); foreach (var h in _history.Items) { var title = _translator.GetTranslation("executeQuery"); var time = _translator.GetTranslation("lastExecuteTime"); var result = new Result { Title = string.Format(CultureInfo.InvariantCulture, title, h.Query), SubTitle = string.Format(CultureInfo.InvariantCulture, time, h.ExecutedDateTime), IcoPath = "Images\\history.png", OriginQuery = new Query { RawQuery = h.Query }, Action = _ => { SelectedResults = Results; ChangeQueryText(h.Query); return(false); } }; results.Add(result); } if (!string.IsNullOrEmpty(query)) { var filtered = results.Where ( r => StringMatcher.FuzzySearch(query, r.Title).IsSearchPrecisionScoreMet() || StringMatcher.FuzzySearch(query, r.SubTitle).IsSearchPrecisionScoreMet() ).ToList(); History.AddResults(filtered, id); } else { History.AddResults(results, id); } }
/// <summary> /// this were we can make suggestions /// </summary> /// <param name="e"></param> protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); if (!m_fromKeyboard || !Focused) { return; } m_suggestionList.BeginUpdate(); m_suggestionList.Items.Clear(); StringMatcher matcher = new StringMatcher(MatchingMethod, Text); foreach (object item in Items) { StringMatch sm = matcher.Match(GetItemText(item)); if (sm != null) { m_suggestionList.Items.Add(sm); } } m_suggestionList.EndUpdate(); bool visible = m_suggestionList.Items.Count != 0; if (m_suggestionList.Items.Count == 1 && ((StringMatch)m_suggestionList.Items[0]).Text.Length == Text.Trim().Length) { StringMatch sel = (StringMatch)m_suggestionList.Items[0]; Text = sel.Text; Select(0, Text.Length); visible = false; } if (visible) { showDropDown(); } else { hideDropDown(); } m_fromKeyboard = false; }
private void QueryHistory() { const string id = "Query History ID"; var query = QueryText.ToLower().Trim(); History.Clear(); var results = new List <Result>(); foreach (var h in _history.Items) { var title = _translator.GetTranslation("executeQuery"); var time = _translator.GetTranslation("lastExecuteTime"); var result = new Result { Title = string.Format(title, h.Query), SubTitle = string.Format(time, h.ExecutedDateTime), IcoPath = "Images\\history.png", OriginQuery = new Query { RawQuery = h.Query }, Action = _ => { SelectedResults = Results; ChangeQueryText(h.Query); return(false); } }; results.Add(result); } if (!string.IsNullOrEmpty(query)) { var filtered = results.Where ( r => StringMatcher.IsMatch(r.Title, query) || StringMatcher.IsMatch(r.SubTitle, query) ).ToList(); History.AddResults(filtered, id); } else { History.AddResults(results, id); } }
// Set the static properties based on the controls. private void ApplyTextSelection() { bool wasOn = TextFilterOn; MatchType matchType; _includeChecked = chkContain.Checked && !string.IsNullOrEmpty(txtContains.Text); _includeText = txtContains.Text; _excludeChecked = chkDoesNotContain.Checked && !string.IsNullOrEmpty(txtDoesNotContain.Text); _excludeText = txtDoesNotContain.Text; _caseChecked = chkCase.Checked; _wildChecked = radWildcard.Checked; _regexChecked = radRegex.Checked; // TODO: radNormal.Checked? if (_regexChecked) { matchType = MatchType.RegularExpression; } else if (_wildChecked) { matchType = MatchType.Wildcard; } else { matchType = MatchType.Simple; } if (_includeChecked) { _includeMatcher = new StringMatcher(_includeText, chkCase.Checked, matchType); } if (_excludeChecked) { _excludeMatcher = new StringMatcher(_excludeText, chkCase.Checked, matchType); } if (TextFilterOn != wasOn) { OnTextFilterOnOff(this); } }
public List <Result> Query(Query query) { var commands = Commands(); var results = new List <Result>(); foreach (var c in commands) { var titleScore = StringMatcher.Score(c.Title, query.Search); var subTitleScore = StringMatcher.Score(c.SubTitle, query.Search); var score = Math.Max(titleScore, subTitleScore); if (score > 0) { c.Score = score; results.Add(c); } } return(results); }
public void WhenMultipleResults_ExactMatchingResult_ShouldHaveGreatestScore(string queryString, string firstName, string firstDescription, string firstExecutableName, string secondName, string secondDescription, string secondExecutableName) { // Act var matcher = new StringMatcher(); var firstNameMatch = matcher.FuzzyMatch(queryString, firstName).RawScore; var firstDescriptionMatch = matcher.FuzzyMatch(queryString, firstDescription).RawScore; var firstExecutableNameMatch = matcher.FuzzyMatch(queryString, firstExecutableName).RawScore; var secondNameMatch = matcher.FuzzyMatch(queryString, secondName).RawScore; var secondDescriptionMatch = matcher.FuzzyMatch(queryString, secondDescription).RawScore; var secondExecutableNameMatch = matcher.FuzzyMatch(queryString, secondExecutableName).RawScore; var firstScore = new[] { firstNameMatch, firstDescriptionMatch, firstExecutableNameMatch }.Max(); var secondScore = new[] { secondNameMatch, secondDescriptionMatch, secondExecutableNameMatch }.Max(); // Assert Assert.IsTrue(firstScore > secondScore); }
static bool MatchName(Dictionary <string, MatchResult> savedMatches, StringMatcher matcher, string name, out int matchRank) { if (name == null) { matchRank = -1; return(false); } MatchResult savedMatch; if (!savedMatches.TryGetValue(name, out savedMatch)) { bool doesMatch = matcher.CalcMatchRank(name, out matchRank); savedMatches [name] = savedMatch = new MatchResult(doesMatch, matchRank); } matchRank = savedMatch.Rank; return(savedMatch.Match); }
public JSONProperties( StringMatcher m ) : base( m ) { Properties = new List<string>(); Paths = new List<string>(); }
public override bool GetMaxCommonFragments(HasseNode Node1, HasseNode Node2, bool dbg, HasseFragmentInsertionQueue NewFragmentList, int MinimumOverlap) { CountMCS++; string str1 = Node1.KeyString; string str2 = Node2.KeyString; bool FoundMCS = false; StringMatcher sm = new StringMatcher(); sm.Initialise(str1, str2); Match m = null; do { m = sm.nextMatch(); if (m == null) break; if (m.LastPosInA - m.FirstPosInA < MinimumOverlap-1) continue; //System.Diagnostics.Debug.WriteLine(m.StrA.Substring(m.FirstPosInA, m.LastPosInA - m.FirstPosInA + 1)); //System.Diagnostics.Debug.WriteLine(m.StrB.Substring(m.FirstPosInB, m.LastPosInB - m.FirstPosInB + 1)); string debugInfo = "MCS " + Node1.GetID().ToString() + " " + Node2.GetID().ToString(); if (true == ProcessMatch(m, MinimumOverlap, NewFragmentList, new HasseNode[2] { Node1, Node2 }, debugInfo)) { FoundMCS = true; } } while (true); return FoundMCS; }
public void matching_double_values( string s, double d ) { StringMatcher m = new StringMatcher( "P" + s + "S" ); Assert.That( m.MatchChar( 'P' ) ); int idx = m.StartIndex; Assert.That( m.TryMatchDoubleValue() ); m.UncheckedMove( idx - m.StartIndex ); double parsed; Assert.That( m.TryMatchDoubleValue( out parsed ) ); Assert.That( parsed, Is.EqualTo( d ).Within( 1 ).Ulps ); Assert.That( m.MatchChar( 'S' ) ); Assert.That( m.IsEnd ); }
/// <summary> /// Tries to parse a <see cref="LogFilter"/>: it can be a predefined filter as ("Undefined", "Debug", "Verbose", etc.) /// or as {GroupLogLevelFilter,LineLogLevelFilter} pairs like "{None,None}", "{Error,Trace}". /// </summary> /// <param name="s">Filter to parse.</param> /// <param name="f">Resulting filter.</param> /// <returns>True on success, false on error.</returns> public static bool TryParse( string s, out LogFilter f ) { var m = new StringMatcher( s ); return m.MatchLogFilter( out f ) && m.IsEnd; }
/// <summary> /// Tries to parse a <see cref="DependentToken.ToString()"/> string. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="t">The resulting dependent token.</param> /// <returns>True on success, false otherwise.</returns> static public bool TryParse( string s, out DependentToken t ) { t = null; StringMatcher m = new StringMatcher( s ); Guid id; DateTimeStamp time; if( MatchOriginatorAndTime( m, out id, out time ) && m.TryMatchText( " with" ) ) { string topic; if( ExtractTopic( s, m.StartIndex, out topic ) ) { t = new DependentToken( id, time, topic ); return true; } } return false; }
public void Setup() { actual = Factory.RandomString(20, 5); matcher = Expect.The(actual); }
private static void CheckMatchError( StringMatcher m, Func<bool> fail ) { int idx = m.StartIndex; int len = m.Length; Assert.That( fail(), Is.False ); Assert.That( m.IsError ); Assert.That( m.ErrorMessage, Is.Not.Null.Or.Empty ); Assert.That( m.StartIndex == idx, "Head must not move on error." ); Assert.That( m.Length == len, "Length must not change on error." ); m.SetSuccess(); }
public void ToString_constains_the_text_and_the_error() { var m = new StringMatcher( "The Text" ); m.SetError( "Plouf..." ); Assert.That( m.ToString(), Does.Contain( "The Text" ).And.Contain( "Plouf..." ) ); }
public void matching_JSONQuotedString( string s, string parsed, string textAfter ) { var m = new StringMatcher( s ); string result; Assert.That( m.TryMatchJSONQuotedString( out result, true ) ); Assert.That( result, Is.EqualTo( parsed ) ); Assert.That( m.TryMatchText( textAfter ), "Should be followed by: " + textAfter ); m = new StringMatcher( s ); Assert.That( m.TryMatchJSONQuotedString( true ) ); Assert.That( m.TryMatchText( textAfter ), "Should be followed by: " + textAfter ); }
public void simple_json_test() { string s = @" { ""p1"": ""n"", ""p2"" : { ""p3"": [ ""p4"": { ""p5"" : 0.989, ""p6"": [], ""p7"": {} } ] } } "; var m = new StringMatcher( s ); Assert.That( m.MatchWhiteSpaces() && m.MatchChar( '{' ) ); string pName; Assert.That( m.MatchWhiteSpaces() && m.TryMatchJSONQuotedString( out pName ) && pName == "p1" ); Assert.That( m.MatchWhiteSpaces( 0 ) && m.MatchChar( ':' ) ); Assert.That( m.MatchWhiteSpaces() && m.TryMatchJSONQuotedString( out pName ) && pName == "n" ); Assert.That( m.MatchWhiteSpaces( 0 ) && m.MatchChar( ',' ) ); Assert.That( m.MatchWhiteSpaces() && m.TryMatchJSONQuotedString( out pName ) && pName == "p2" ); Assert.That( m.MatchWhiteSpaces( 2 ) && m.MatchChar( ':' ) ); Assert.That( m.MatchWhiteSpaces() && m.MatchChar( '{' ) ); Assert.That( m.MatchWhiteSpaces() && m.TryMatchJSONQuotedString( out pName ) && pName == "p3" ); Assert.That( m.MatchWhiteSpaces( 0 ) && m.MatchChar( ':' ) ); Assert.That( m.MatchWhiteSpaces() && m.MatchChar( '[' ) ); Assert.That( m.MatchWhiteSpaces() && m.TryMatchJSONQuotedString( out pName ) && pName == "p4" ); Assert.That( m.MatchWhiteSpaces( 0 ) && m.MatchChar( ':' ) ); Assert.That( m.MatchWhiteSpaces() && m.MatchChar( '{' ) ); Assert.That( m.MatchWhiteSpaces() && m.TryMatchJSONQuotedString() ); Assert.That( m.MatchWhiteSpaces( 0 ) && m.MatchChar( ':' ) ); Assert.That( m.MatchWhiteSpaces() && m.TryMatchDoubleValue() ); Assert.That( m.MatchWhiteSpaces( 0 ) && m.MatchChar( ',' ) ); Assert.That( m.MatchWhiteSpaces() && m.TryMatchJSONQuotedString( out pName ) && pName == "p6" ); Assert.That( m.MatchWhiteSpaces( 0 ) && m.MatchChar( ':' ) ); Assert.That( m.MatchWhiteSpaces() && m.MatchChar( '[' ) ); Assert.That( m.MatchWhiteSpaces( 0 ) && m.MatchChar( ']' ) ); Assert.That( m.MatchWhiteSpaces( 0 ) && m.MatchChar( ',' ) ); Assert.That( m.MatchWhiteSpaces() && m.TryMatchJSONQuotedString() ); Assert.That( m.MatchWhiteSpaces( 0 ) && m.MatchChar( ':' ) ); Assert.That( m.MatchWhiteSpaces() && m.MatchChar( '{' ) ); Assert.That( m.MatchWhiteSpaces( 0 ) && m.MatchChar( '}' ) ); Assert.That( m.MatchWhiteSpaces() && m.MatchChar( '}' ) ); Assert.That( m.MatchWhiteSpaces() && m.MatchChar( ']' ) ); Assert.That( m.MatchWhiteSpaces() && m.MatchChar( '}' ) ); Assert.That( m.MatchWhiteSpaces() && m.MatchChar( '}' ) ); Assert.That( m.MatchWhiteSpaces( 2 ) && m.IsEnd ); }
public List<SearchResult> Search(string expression, int limit, long modifiedBefore, long modifiedAfter, double smallerThan, double largerThan) { var results = new List<SearchResult>(); var matcher = new StringMatcher(expression); foreach (RootShare share in shares.ToList()) { if ( !SearchRecursive(share.Data, matcher, string.Empty, results, limit, modifiedBefore, modifiedAfter, smallerThan, largerThan)) break; } return results; }
private bool SearchRecursive(Directory dir, StringMatcher matcher, string currentPath, List<SearchResult> results, int limit, long modifiedBefore, long modifiedAfter, double smallerThan, double largerThan) { foreach (Entities.FileSystem.File file in dir.Files) { if (matcher.IsMatch(file.Name)) { if ((modifiedBefore == 0 || file.LastModified < modifiedBefore) && (modifiedAfter == 0 || file.LastModified > modifiedAfter) && (smallerThan == 0 || file.Size < smallerThan) && (largerThan == 0 || file.Size > largerThan)) { results.Add(new SearchResult { FileName = file.Name, Modified = DateTime.FromFileTime(file.LastModified), Path = string.IsNullOrEmpty(currentPath) ? dir.Name : currentPath + "/" + dir.Name, IsFolder = false, Size = file.Size }); if (results.Count >= limit) return false; } } } foreach (Directory d in dir.SubDirectories) { if (matcher.IsMatch(d.Name)) { if ((modifiedBefore == 0 || d.LastModified < modifiedBefore) && (modifiedAfter == 0 || d.LastModified > modifiedAfter) && (smallerThan == 0 || d.Size < smallerThan) && (largerThan == 0 || d.Size > largerThan)) { results.Add(new SearchResult { FileName = d.Name, Modified = DateTime.FromFileTime(d.LastModified), Path = string.IsNullOrEmpty(currentPath) ? dir.Name : currentPath + "/" + dir.Name, IsFolder = true, Size = d.Size }); if (results.Count >= limit) return false; } } } foreach (Directory subdir in dir.SubDirectories) { if (string.IsNullOrEmpty(currentPath)) { if ( !SearchRecursive(subdir, matcher, dir.Name, results, limit, modifiedBefore, modifiedAfter, smallerThan, largerThan)) return false; } else { if ( !SearchRecursive(subdir, matcher, currentPath + "/" + dir.Name, results, limit, modifiedBefore, modifiedAfter, smallerThan, largerThan)) return false; } } return true; }
static bool MatchOriginatorAndTime( StringMatcher m, out Guid id, out DateTimeStamp time ) { time = DateTimeStamp.MinValue; if( !m.TryMatchGuid( out id ) ) return false; if( !m.TryMatchText( " at " ) ) return false; return m.MatchDateTimeStamp( out time ); }
/// <summary> /// Tries to parse a string formatted with the <see cref="FileNameUniqueTimeUtcFormat"/>. /// The string must contain only the time unless <paramref name="allowSuffix"/> is true. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="time">Result time on success.</param> /// <param name="allowSuffix">True to accept a string that starts with the time and contains more text.</param> /// <returns>True if the string has been successfully parsed.</returns> public static bool TryParseFileNameUniqueTimeUtcFormat( string s, out DateTime time, bool allowSuffix = false ) { var m = new StringMatcher( s ); return m.MatchFileNameUniqueTimeUtcFormat( out time ) && (allowSuffix || m.IsEnd); }
public void matching_the_5_forms_of_guid( string form ) { var id = Guid.NewGuid(); string sId = id.ToString( form ); { string s = sId; var m = new StringMatcher( s ); Guid readId; Assert.That( m.TryMatchGuid( out readId ) && readId == id ); } { string s = "S" + sId; var m = new StringMatcher( s ); Guid readId; Assert.That( m.MatchChar( 'S' ) ); Assert.That( m.TryMatchGuid( out readId ) && readId == id ); } { string s = "S" + sId + "T"; var m = new StringMatcher( s ); Guid readId; Assert.That( m.MatchChar( 'S' ) ); Assert.That( m.TryMatchGuid( out readId ) && readId == id ); Assert.That( m.MatchChar( 'T' ) ); } sId = sId.Remove( sId.Length - 1 ); { string s = sId; var m = new StringMatcher( s ); Guid readId; Assert.That( m.TryMatchGuid( out readId ), Is.False ); Assert.That( m.StartIndex, Is.EqualTo( 0 ) ); } sId = id.ToString().Insert( 3, "K" ).Remove( 4 ); { string s = sId; var m = new StringMatcher( s ); Guid readId; Assert.That( m.TryMatchGuid( out readId ), Is.False ); Assert.That( m.StartIndex, Is.EqualTo( 0 ) ); } }