Exemplo n.º 1
0
        /// <summary>Analyzes a <see cref="RegexInterpreterCode"/> to learn about the structure of the tree.</summary>
        public static AnalysisResults Analyze(RegexTree regexTree)
        {
            var results = new AnalysisResults(regexTree);

            results._complete = TryAnalyze(regexTree.Root, results, isAtomicByAncestor: true, isInLoop: false);
            return(results);
Exemplo n.º 2
0
 public MainForm()
 {
     InitializeComponent();
     _analysisResults = new AnalysisResults();
 }
Exemplo n.º 3
0
        public static AnalysisResults Analyze(string queryModelID, string _nluText)
        {
            _naturalLanguageUnderstandingService = new NaturalLanguageUnderstandingService(userNLU, pswNLU, NaturalLanguageUnderstandingService.NATURAL_LANGUAGE_UNDERSTANDING_VERSION_DATE_2017_02_27);

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

            List <string> _emotions = new List <string>()
            {
                "anger",
                "disgust",
                "fear",
                "joy",
                "sadness"
            };

            List <string> _targets = new List <string>()
            {
                "comida",
                "restaurante",
                "plato"
            };

            Parameters parameters = new Parameters()
            {
                Clean              = true,
                FallbackToRaw      = true,
                ReturnAnalyzedText = true,
                Features           = new Features()
                {
                    Relations = new RelationsOptions(),
                    Sentiment = new SentimentOptions()
                    {
                        Document = true
                                   //Targets = _targets
                    },
                    Emotion = new EmotionOptions()
                    {
                        Document = true
                                   //Targets = _emotions
                    },
                    Keywords = new KeywordsOptions()
                    {
                        Limit     = 50,
                        Sentiment = true,
                        Emotion   = true
                    },
                    Entities = new EntitiesOptions()
                    {
                        Limit     = 50,
                        Emotion   = true,
                        Sentiment = true
                    },
                    Categories = new CategoriesOptions(),
                    Concepts   = new ConceptsOptions()
                    {
                        Limit = 8
                    },
                    SemanticRoles = new SemanticRolesOptions()
                    {
                        Limit    = 50,
                        Entities = true,
                        Keywords = true
                    }
                }
            };

            if (!string.IsNullOrEmpty(queryModelID))
            {
                parameters.Features.Relations.Model = queryModelID;
                parameters.Features.Entities.Model  = queryModelID;
            }

            if (_nluText.StartsWith("http"))
            {
                parameters.Url = _nluText;
                parameters.Features.Metadata = new MetadataOptions();
            }
            else
            {
                parameters.Text = _nluText;
            }

            Console.WriteLine(string.Format("\nAnalizando()..."));

            AnalysisResults result = new AnalysisResults();

            try
            {
                result = _naturalLanguageUnderstandingService.Analyze(parameters);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                result.AnalyzedText = ex.Message;
            }

            return(result);
        }
Exemplo n.º 4
0
            static bool TryAnalyze(RegexNode node, AnalysisResults results, bool isAtomicByAncestor)
            {
                if (!StackHelper.TryEnsureSufficientExecutionStack())
                {
                    return(false);
                }

                // Track whether we've seen any node with IgnoreCase set.
                results._hasIgnoreCase |= (node.Options & RegexOptions.IgnoreCase) != 0;

                if (isAtomicByAncestor)
                {
                    // We've been told by our parent that we should be considered atomic, so add ourselves
                    // to the atomic collection.
                    results._isAtomicByAncestor.Add(node);
                }
                else
                {
                    // Certain kinds of nodes incur backtracking logic themselves: add them to the backtracking collection.
                    // We may later find that a node contains another that has backtracking; we'll add nodes based on that
                    // after examining the children.
                    switch (node.Kind)
                    {
                    case RegexNodeKind.Alternate:
                    case RegexNodeKind.Loop or RegexNodeKind.Lazyloop when node.M != node.N:
                    case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop or RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy when node.M != node.N:
                        (results._mayBacktrack ??= new()).Add(node);
                        break;
                    }
                }

                // Update state for certain node types.
                bool isAtomicBySelf = false;

                switch (node.Kind)
                {
                // Some node types add atomicity around what they wrap.  Set isAtomicBySelfOrParent to true for such nodes
                // even if it was false upon entering the method.
                case RegexNodeKind.Atomic:
                case RegexNodeKind.NegativeLookaround:
                case RegexNodeKind.PositiveLookaround:
                    isAtomicBySelf = true;
                    break;

                // Track any nodes that are themselves captures.
                case RegexNodeKind.Capture:
                    results._containsCapture.Add(node);
                    break;
                }

                // Process each child.
                int childCount = node.ChildCount();

                for (int i = 0; i < childCount; i++)
                {
                    RegexNode child = node.Child(i);

                    // Determine whether the child should be treated as atomic (whether anything
                    // can backtrack into it), which is influenced by whether this node (the child's
                    // parent) is considered atomic by itself or by its parent.
                    bool treatChildAsAtomic = (isAtomicByAncestor | isAtomicBySelf) && node.Kind switch
                    {
                        // If the parent is atomic, so is the child.  That's the whole purpose
                        // of the Atomic node, and lookarounds are also implicitly atomic.
                        RegexNodeKind.Atomic or RegexNodeKind.NegativeLookaround or RegexNodeKind.PositiveLookaround => true,

                        // Each branch is considered independently, so any atomicity applied to the alternation also applies
                        // to each individual branch.  This is true as well for conditionals.
                         RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional => true,

                        // Captures don't impact atomicity: if the parent of a capture is atomic, the capture is also atomic.
                         RegexNodeKind.Capture => true,

                        // If the parent is a concatenation and this is the last node, any atomicity
                        // applying to the concatenation applies to this node, too.
                         RegexNodeKind.Concatenate => i == childCount - 1,

                        // For loops with a max iteration count of 1, they themselves can be considered
                        // atomic as can whatever they wrap, as they won't ever iterate more than once
                        // and thus we don't need to worry about one iteration consuming input destined
                        // for a subsequent iteration.
                         RegexNodeKind.Loop or RegexNodeKind.Lazyloop when node.N == 1 => true,

                        // For any other parent type, give up on trying to prove atomicity.
                         _ => false,
                    };

                    // Now analyze the child.
                    if (!TryAnalyze(child, results, treatChildAsAtomic))
                    {
                        return(false);
                    }

                    // If the child contains captures, so too does this parent.
                    if (results._containsCapture.Contains(child))
                    {
                        results._containsCapture.Add(node);
                    }

                    // If the child might require backtracking into it, so too might the parent,
                    // unless the parent is itself considered atomic.  Here we don't consider parental
                    // atomicity, as we need to surface upwards to the parent whether any backtracking
                    // will be visible from this node to it.
                    if (!isAtomicBySelf && (results._mayBacktrack?.Contains(child) == true))
                    {
                        (results._mayBacktrack ??= new()).Add(node);
                    }
                }

                // Successfully analyzed the node.
                return(true);
            }
Exemplo n.º 5
0
        public void Analyze_Success()
        {
            IClient client = CreateClient();

            IRequest request = Substitute.For <IRequest>();

            client.PostAsync(Arg.Any <string>())
            .Returns(request);

            #region Response
            AnalysisResults response = new AnalysisResults()
            {
                Language     = "en",
                AnalyzedText = "testText",
                RetrievedUrl = "retrivedUrl",
                Usage        = new Usage()
                {
                    Features = 1
                },
                Concepts = new List <ConceptsResult>()
                {
                    new ConceptsResult()
                    {
                        Text            = "text",
                        Relevance       = 1.0f,
                        DbpediaResource = "dbpediaResouce"
                    }
                },
                Entities = new List <EntitiesResult>()
                {
                    new EntitiesResult()
                    {
                        Type      = "type",
                        Relevance = 1.0f,
                        Count     = 1,
                        Text      = "text",
                        Emotion   = new EmotionScores()
                        {
                            Anger = 1.0f, Disgust = 1.0f, Fear = 1.0f, Joy = 1.0f, Sadness = 1.0f
                        },
                        Sentiment = new FeatureSentimentResults()
                        {
                            Score = 1.0f
                        },
                        Disambiguation = new DisambiguationResult()
                        {
                            Name            = "name",
                            DbpediaResource = "dbpediaResource",
                            Subtype         = new List <string>()
                            {
                                "subtype"
                            }
                        }
                    }
                },
                Keywords = new List <KeywordsResult>()
                {
                    new KeywordsResult()
                    {
                        Relevance = 1.0f,
                        Text      = "text",
                        Emotion   = new EmotionScores()
                        {
                            Anger = 1.0f, Disgust = 1.0f, Fear = 1.0f, Joy = 1.0f, Sadness = 1.0f
                        },
                        Sentiment = new FeatureSentimentResults()
                        {
                            Score = 1.0f
                        }
                    }
                },
                Categories = new List <CategoriesResult>()
                {
                    new CategoriesResult()
                    {
                        Label = "label",
                        Score = 1.0f
                    }
                },
                Emotion = new EmotionResult()
                {
                    Document = new DocumentEmotionResults()
                    {
                        Emotion = new EmotionScores()
                        {
                            Anger = 1.0f, Disgust = 1.0f, Fear = 1.0f, Joy = 1.0f, Sadness = 1.0f
                        },
                    },
                    Targets = new List <TargetedEmotionResults>()
                    {
                        new TargetedEmotionResults()
                        {
                            Emotion = new EmotionScores()
                            {
                                Anger = 1.0f, Disgust = 1.0f, Fear = 1.0f, Joy = 1.0f, Sadness = 1.0f
                            },
                            Text = "text"
                        }
                    }
                },
                Metadata = new MetadataResult()
                {
                    Authors = new List <Author>()
                    {
                        new Author()
                        {
                            Name = "name"
                        }
                    },
                    PublicationDate = "publicationDate",
                    Title           = "title"
                },
                Relations = new List <RelationsResult>()
                {
                    new RelationsResult()
                    {
                        Score     = 1.0f,
                        Sentence  = "sentence",
                        Type      = "type",
                        Arguments = new List <RelationArgument>()
                        {
                            new RelationArgument()
                            {
                                Entities = new List <RelationEntity>()
                                {
                                    new RelationEntity()
                                    {
                                        Text = "text",
                                        Type = "type"
                                    }
                                },
                                Text = "text"
                            }
                        }
                    }
                },
                SemanticRoles = new List <SemanticRolesResult>()
                {
                    new SemanticRolesResult()
                    {
                        Sentence = "sentence",
                        Subject  = new SemanticRolesSubject()
                        {
                            Text     = "text",
                            Entities = new List <SemanticRolesEntity>()
                            {
                                new SemanticRolesEntity()
                                {
                                    Text = "text",
                                    Type = "type"
                                }
                            },
                            Keywords = new List <SemanticRolesKeyword>()
                            {
                                new SemanticRolesKeyword()
                                {
                                    Text = "text"
                                }
                            }
                        },
                        Action = new SemanticRolesAction()
                        {
                            Normalized = "normalized",
                            Text       = "text",
                            Verb       = new SemanticRolesVerb()
                            {
                                Text  = "text",
                                Tense = "tense"
                            }
                        },
                        _Object = new SemanticRolesObject()
                        {
                            Text     = "text",
                            Keywords = new List <SemanticRolesKeyword>()
                            {
                                new SemanticRolesKeyword()
                                {
                                    Text = "text"
                                }
                            }
                        }
                    }
                },
                Sentiment = new SentimentResult()
                {
                    Document = new DocumentSentimentResults()
                    {
                        Score = 1.0f
                    },
                    Targets = new List <TargetedSentimentResults>()
                    {
                        new TargetedSentimentResults()
                        {
                            Score = 1.0f,
                            Text  = "text"
                        }
                    }
                }
            };
            #endregion

            #region parameters
            Parameters parameters = new Parameters()
            {
                Text     = "text",
                Html     = "html",
                Url      = "url",
                Features = new Features()
                {
                    Concepts = new ConceptsOptions()
                    {
                        Limit = 1
                    },
                    Emotion = new EmotionOptions()
                    {
                        Document = true,
                        Targets  = new List <string>()
                        {
                            "target"
                        }
                    },
                    Entities = new EntitiesOptions()
                    {
                        Model     = "model",
                        Sentiment = true,
                        Emotion   = true,
                        Limit     = 1
                    },
                    Keywords = new KeywordsOptions()
                    {
                        Limit     = 1,
                        Sentiment = true,
                        Emotion   = true
                    },
                    Metadata = new MetadataOptions()
                    {
                    },
                    Relations = new RelationsOptions()
                    {
                        Model = "model"
                    },
                    SemanticRoles = new SemanticRolesOptions()
                    {
                        Limit    = 1,
                        Keywords = true,
                        Entities = true
                    },
                    Sentiment = new SentimentOptions()
                    {
                        Document = true,
                        Targets  = new List <string>()
                        {
                            "target"
                        }
                    },
                    Categories = new CategoriesOptions()
                    {
                    }
                },
                Clean              = true,
                Xpath              = "xpath",
                FallbackToRaw      = true,
                ReturnAnalyzedText = true,
                Language           = "en"
            };
            #endregion

            request.WithArgument(Arg.Any <string>(), Arg.Any <string>())
            .Returns(request);
            request.WithBody <Parameters>(parameters)
            .Returns(request);
            request.As <AnalysisResults>()
            .Returns(Task.FromResult(response));

            NaturalLanguageUnderstandingService service = new NaturalLanguageUnderstandingService(client);
            service.VersionDate = "versionDate";

            var result = service.Analyze(parameters);

            Assert.IsNotNull(result);
            client.Received().PostAsync(Arg.Any <string>());
            Assert.IsTrue(result.Language == "en");
            Assert.IsTrue(result.AnalyzedText == "testText");
        }
Exemplo n.º 6
0
        /// <summary>
        /// Retrieves the content to display in a <see cref="ListView"/> when a <see cref="TreeNode"/> is selected.
        /// </summary>
        /// <param name="node">The <see cref="TreeNode"/> that was selected.</param>
        /// <returns>A <see cref="ListViewContents"/> that defines the columns and items of the content.</returns>
        private ListViewContents GetListItems(TreeNode node)
        {
            ColumnHeader[]             headers = null;
            IEnumerable <ListViewItem> items   = null;

            if (node.Tag is ActiveCandidate)
            {
                // active candidate leaf node selected, show active candidate contacts/users
                headers = new[] { _nameColumnHeader, _typeColumnHeader, _usernameColumnHeader, _emailColumnHeader };
                ActiveCandidate ac      = node.Tag as ActiveCandidate;
                AnalysisResults results = AccountAnalysis.Analyze(Cfb.CandidatePortal.Cfis.GetCandidate(ac.ID), ac.ElectionCycle);

                // users for current campaign
                var current = from u in results.CurrentUsers
                              where _adminMode || u.SourceType != EntityType.Generic // hide generic accounts from non-admins
                              select new ListViewItem(new[] { u.DisplayName, string.Format("User ({0})", u.SourceType), u.UserName, u.Email }, u.Enabled ? _userImageIndex : _userDisabledImageIndex)
                {
                    Tag = u
                };
                // existing users from a different campaign
                var other = from s in results.OtherCampaignUsers
                            let u = s.MatchedUser
                                    select new ListViewItem(new[] { u.DisplayName + "*", string.Format("EC{0} User", u.SourceElectionCycle), u.UserName, u.Email }, u.Enabled ? _userImageIndex : _userDisabledImageIndex)
                {
                    Tag = s
                };
                // eligible contacts
                var eligible = from e in results.EligibleContacts
                               let v = e.Value
                                       select new ListViewItem(new[] { v.Name, AccountAnalysis.ParseEntityType(e.Key).ToString(), null, v.Email }, _userInactiveImageIndex)
                {
                    Name = e.Key,
                    Tag  = e.Value
                };
                // ineligible contacts
                var ineligible = from s in results.IneligibleContacts
                                 select new ListViewItem(new[] { s.Entity.Name, "Ineligible Contact", null, s.Entity.Email }, _blockImageIndex)
                {
                    Tag = s
                };
                items = eligible.Union(ineligible).Union(current).Union(other);
            }
            else if (node.Tag as string == GroupNodeTag)
            {
                // group leaf node selected, show groups
                headers                     = new[] { _nameColumnHeader, _usernameColumnHeader, _idColumnHeader, _emailColumnHeader };
                items                       = from u in CPSecurity.Provider.GetGroupMembers(node.Name)
                                   let user = CPSecurity.Provider.GetUser(u)
                                              where user != null && (_adminMode || user.SourceType != EntityType.Generic)
                                              select new ListViewItem(new[] { user.DisplayName, user.UserName, user.Cid, user.Email }, user.Enabled ? _userImageIndex : _userDisabledImageIndex)
                {
                    Tag = user
                };
            }
            else
            {
                // non-leaf nodes
                if (node == _candidatesNode)
                {
                    headers = new[] { _nameColumnHeader, _typeColumnHeader, _idColumnHeader }
                }
                ;
                else if (node == _electionCyclesNode || node == _groupsNode || node.Tag is Candidate || node.ImageIndex == _electionCyclesImageIndex)
                {
                    headers = new[] { _nameColumnHeader, _typeColumnHeader }
                }
                ;
                TreeNodeCollection  children      = node.Nodes;
                List <ListViewItem> treeNodeItems = new List <ListViewItem>();
                foreach (TreeNode child in children)
                {
                    ListViewItem item = null;
                    if (child.ImageIndex == _candidatesImageIndex && child.Tag is Candidate)
                    {
                        Candidate cand = child.Tag as Candidate;
                        item = new ListViewItem(new[] { cand.FormalName, "Candidate", cand.ID }, _candidatesImageIndex)
                        {
                            Name = cand.ID,
                            Tag  = child.Tag
                        };
                    }
                    else if (child.ImageIndex == _electionCyclesImageIndex)
                    {
                        item = new ListViewItem(new[] { child.Name, "Election Cycle" }, _electionCyclesImageIndex)
                        {
                            Name = child.Name,
                            Tag  = child.Tag
                        };
                    }
                    else if (node.ImageIndex == _groupsImageIndex)
                    {
                        item = new ListViewItem(new[] { child.Name, "Security Group" }, _groupsImageIndex)
                        {
                            Name = child.Name
                        };
                    }
                    if (item != null)
                    {
                        treeNodeItems.Add(item);
                    }
                }
                items = treeNodeItems;
            }
            return(new ListViewContents()
            {
                Headers = headers, Items = items.OrderBy(i => i.Text).ToArray()
            });
        }
Exemplo n.º 7
0
 private void OnAnalyze(AnalysisResults resp, Dictionary <string, object> customData)
 {
     Log.Debug("ExampleNaturalLanguageUnderstanding.OnAnalyze()", "AnalysisResults: {0}", customData["json"].ToString());
     _analyzeTested = true;
 }
Exemplo n.º 8
0
    static void LemmatizeTextFile(string dictionary_xml, string corpus_path, string result_path)
    {
        int LanguageID = SolarixGrammarEngineNET.GrammarEngineAPI.RUSSIAN_LANGUAGE;

        // int Constraints = 60000 | (30 << 22); // 1 минута и 30 альтернатив

        using (GrammarEngine2 gren = new GrammarEngine2())
        {
            gren.Load(DictionaryXmlPath: dictionary_xml, LazyLexicon: true);
            Console.WriteLine($"Словарь {dictionary_xml} успешно загружен");

            int pronoun_class = gren.FindPartOfSpeech("МЕСТОИМЕНИЕ");
            Debug.Assert(pronoun_class != -1);
            int person_coord = gren.FindCoord("ЛИЦО");
            Debug.Assert(person_coord != -1);
            int person1 = gren.FindState(person_coord, "1");
            int person2 = gren.FindState(person_coord, "2");
            int person3 = gren.FindState(person_coord, "3");

            Dictionary <int, string> id_entry2lemma = new Dictionary <int, string>();

            using (System.IO.StreamWriter wrt = new System.IO.StreamWriter(result_path))
            {
                int line_count = 0;
                using (System.IO.StreamReader rdr = new System.IO.StreamReader(corpus_path))
                {
                    while (!rdr.EndOfStream)
                    {
                        string line = rdr.ReadLine();
                        if (line == null)
                        {
                            break;
                        }

                        line_count++;
                        if ((line_count % 100) == 0)
                        {
                            Console.Write($"{line_count} lines parsed\r");
                        }

                        List <string> sentences = gren.SplitText(line, LanguageID);

                        List <string> line_lemmas = new List <string>(capacity: line.Length / 5 + 1);

                        foreach (string sentence in sentences)
                        {
                            AnalysisResults anares = gren.AnalyzeMorphology(sentence, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_MODEL_ONLY);
                            for (int itoken = 1; itoken < anares.Count - 1; ++itoken)
                            {
                                SyntaxTreeNode node     = anares[itoken];
                                string         lemma    = null;
                                int            id_entry = node.GetEntryID();
                                if (id_entry != -1)
                                {
                                    if (pronoun_class == gren.GetEntryClass(id_entry))
                                    {
                                        // В словарной базе Solarix местоимения НАС, ВАМИ etc. приводятся к базовой форме Я
                                        // Таким образом, словоизменение по лицам устраняется. Такая агрессивная лемматизация
                                        // высокочастотных слов может быть нежелательна для семантического анализа, поэтому
                                        // сделаем ручную лемматизацию.
                                        int person = node.GetCoordState(person_coord);
                                        if (person == person1)
                                        {
                                            lemma = "я";
                                        }
                                        else if (person == person2)
                                        {
                                            lemma = "ты";
                                        }
                                        else if (person == person3)
                                        {
                                            lemma = "он";
                                        }
                                        else
                                        {
                                            Debug.Fail("Unknown person tag");
                                        }
                                    }
                                    else
                                    {
                                        if (id_entry2lemma.ContainsKey(id_entry))
                                        {
                                            lemma = id_entry2lemma[id_entry];
                                        }
                                        else
                                        {
                                            lemma = gren.GetEntryName(id_entry);
                                            if (lemma.Equals("unknownentry", StringComparison.OrdinalIgnoreCase))
                                            {
                                                lemma = node.GetWord();
                                            }
                                            else if (lemma.Equals("???"))
                                            {
                                                lemma = node.GetWord();
                                            }
                                            else
                                            {
                                                lemma = lemma.Replace(' ', '_'); // для MWU типа "в конце концов"
                                            }
                                        }

                                        id_entry2lemma[id_entry] = lemma;
                                    }
                                }
                                else
                                {
                                    lemma = node.GetWord();
                                }

                                lemma = lemma.ToLower();
                                line_lemmas.Add(lemma);
                            }
                        }

                        wrt.WriteLine(string.Join(" ", line_lemmas));
                    }
                }
            }
        }

        return;
    }
Exemplo n.º 9
0
        private void PopulateGrid(AnalysisResults result)
        {
            this.dataGridMain.SuspendDrawing();
            try
            {
                this.dataGridMain.Rows.Clear();

                foreach (var dir in result.Directories)
                {
                    foreach (var file in dir.Files)
                    {
                        if (file.IsCorrect)
                            continue;

                        var row = (DataGridViewRow) dataGridMain.RowTemplate.Clone();
                        row.CreateCells(dataGridMain);
                        row.Tag = file;

                        row.Cells[colSelected.Index].Value = false; // Initialize to ensure that we don't get a nullreference exception later!
                        row.Cells[colFileName.Index].Value = Path.GetFileName(file.FilePath);
                        row.Cells[colSource.Index].Value = file.FilePath;
                        row.Cells[colDestination.Index].Value = file.CorrectedFilePath;
                        row.Cells[colDate.Index].Value = file.DateCategoryDetected;
                        row.Cells[colFileTypeText.Index].Value = Path.GetExtension(file.FilePath)?.Trim('.').ToLower();
                        //row.Cells[colFileTypeImage.Name].Value =

                        dataGridMain.Rows.Add(row);
                    }
                }

                // Store the results that are being displayed as a part of the grid
                this.dataGridMain.Tag = result;
            }
            finally
            {
                this.dataGridMain.ResumeDrawing(true);
            }
        }
Exemplo n.º 10
0
        public override IEnumerable <BaseTreeViewItem> BuildChildrenTreeViewItemsOf(BaseTreeViewItem parent)
        {
            switch (parent)
            {
            case CSharpVersionTreeViewItem csharpVersionTreeViewItem:
                return(AnalysisResults
                       .Where(result => result.Suggestion.MinimumLanguageVersion == csharpVersionTreeViewItem.CSharpVersion)
                       .Select(result => result.Suggestion.LanguageFeature)
                       .Distinct()
                       .OrderBy(feature => feature.FriendlyName)
                       .Select(feature => new CSharpFeatureTreeViewItem
                               (
                                   parent,
                                   this,
                                   AnalysisResults.Count(result => result.Suggestion.MinimumLanguageVersion == csharpVersionTreeViewItem.CSharpVersion &&
                                                         result.Suggestion.LanguageFeature == feature),
                                   feature
                               )));

            case CSharpFeatureTreeViewItem csharpFeatureTreeViewItem:
                // A certain C# feature can be introduced within several versions of C#.
                // For example, Expression-bodied members are introduced in C# 6.0 and C# 7.0.
                var parentLanguageVersion = ((CSharpVersionTreeViewItem)csharpFeatureTreeViewItem.Parent).CSharpVersion;
                return(AnalysisResults
                       .Where(result => result.Suggestion.MinimumLanguageVersion == parentLanguageVersion &&
                              result.Suggestion.LanguageFeature == csharpFeatureTreeViewItem.Feature)
                       .Select(result => result.Suggestion)
                       .Distinct()
                       .OrderBy(suggestion => suggestion.FriendlyName)
                       .Select(suggestion => new SuggestionTreeViewItem
                               (
                                   parent,
                                   this,
                                   AnalysisResults.Count(result => result.Suggestion == suggestion),
                                   suggestion
                               )));

            case SuggestionTreeViewItem suggestionTreeViewItem:
                return(AnalysisResults
                       .Where(result => result.Suggestion == suggestionTreeViewItem.Suggestion)
                       .GroupBy(suggestion => new { suggestion.AnalysisContext.ProjectName, suggestion.FilePath })
                       .OrderBy(group => group.Key.ProjectName)
                       .ThenBy(group => group.Key.FilePath)
                       .Select(group => new FilePathTreeViewItem
                               (
                                   parent,
                                   this,
                                   group.Count(),
                                   // TODO: Inefficient and ugly workaround that will work so far.
                                   //       We will soon replace all the LINQ code in this method with an access to an optimized indexing structure.
                                   AnalysisResults.First(result => result.AnalysisContext.ProjectName == group.Key.ProjectName && result.FilePath == group.Key.FilePath).AnalysisContext,
                                   group.Key.FilePath
                               )));

            case FilePathTreeViewItem filePathTreeViewItem:
                var parentSuggestion = ((SuggestionTreeViewItem)filePathTreeViewItem.Parent).Suggestion;
                return(AnalysisResults
                       .Where(result => result.Suggestion == parentSuggestion && result.AnalysisContext.ProjectName == filePathTreeViewItem.ProjectName && result.FilePath == filePathTreeViewItem.FilePath)
                       .OrderBy(suggestion => suggestion.Position.StartLinePosition.Line)
                       .ThenBy(suggestion => suggestion.Position.StartLinePosition.Character)
                       .Select(result => new SingleSuggestionTreeViewItem
                               (
                                   parent,
                                   this,
                                   result
                               )));

            default:
                throw new ArgumentOutOfRangeException
                      (
                          nameof(parent),
                          $"The parent of the type {parent.GetType().Name} is not supported as a parent in the {nameof(CSharpVersionSuggestionFilePathTreeViewBuilder)}."
                      );
            }
        }
Exemplo n.º 11
0
        public JsonResult GetPhoneNumber(string text)
        {
            Response     response     = new Response();
            ResultGoogle resultGoogle = new ResultGoogle();

            if (string.IsNullOrEmpty(text))
            {
                response.Message = "Texto vacío o nulo";
                return(Json(response));
            }

            try
            {
                //Get Entities using NLU

                string _district = "Lima";
                string _country  = "Perú";
                string _entity   = string.Empty;

                string _textModified = text.ToLower();

                if (!_textModified.Contains("lima"))
                {
                    _textModified = _textModified + " Lima";
                }

                if (!_textModified.Contains("perú") && !_textModified.Contains("peru"))
                {
                    _textModified = _textModified + " Perú";
                }

                if (!_textModified.Contains("teléfono") && !_textModified.Contains("telefono"))
                {
                    _textModified = "Teléfono " + _textModified;
                }

                if (_textModified?.Length > 14)
                {
                    _textModified = _textModified.ToTitleCase();

                    AnalysisResults _nlu = NluController.Analyze(null, _textModified);

                    if (_nlu.Entities != null)
                    {
                        foreach (var item in _nlu.Entities)
                        {
                            switch (item.Type)
                            {
                            case "Organization":
                                _entity = item.Text;
                                break;

                            case "Location":
                                if (item.Disambiguation.Subtype[0].StartsWith("City"))
                                {
                                    _district = item.Text;
                                }

                                if (item.Disambiguation.Subtype[0].StartsWith("Country"))
                                {
                                    _country = item.Text;
                                }

                                break;

                            default:
                                break;
                            }
                        }
                    }

                    //_entity = _nlu.Entities.FirstOrDefault()?.Text;



                    //if (string.IsNullOrEmpty(_entity))
                    //{
                    //    resultGoogle = GetGoogleSearch(_textModified);

                    //    //if (_nlu.Keywords != null)
                    //    //{
                    //    //    _entity = _nlu.Keywords.Where(k => k.Relevance > 0.8).Select(k => k.Text).FirstOrDefault().ToTitleCase();

                    //    //    _entity = _entity.Replace("Teléfono","").Replace("Telefono", "");
                    //    //}

                    //    //if (string.IsNullOrEmpty(_entity))
                    //    //{
                    //    //    resultGoogle = GetGoogleSearch(_textModified);
                    //    //}
                    //    //else
                    //    //{
                    //    //    resultGoogle = GetGoogleSearch($"Teléfono {_entity } {_district} {_country}");
                    //    //}
                    //}
                    //else
                    //{
                    //    string _queryParsed = $"Teléfono {_entity} {_district} {_country}";

                    //    resultGoogle = GetGoogleSearch(_queryParsed);

                    //}
                }
                //else
                //{

                //    resultGoogle = GetGoogleSearch(_textModified);

                //}

                resultGoogle = Helpers.GetGoogleSearch(_textModified);

                response.Status = resultGoogle.Status;
                response.Data   = resultGoogle.DocumentString;

                if (Regex.IsMatch(resultGoogle.Text, @"^\d+$"))
                {
                    if (string.IsNullOrEmpty(_entity))
                    {
                        response.Message = $"El número de teléfono de {resultGoogle.Title} es: {resultGoogle.Text}";
                    }
                    else
                    {
                        response.Message = $"El número de teléfono de {_entity} es: {resultGoogle.Text}";
                    }
                }
                else
                {
                    response.Message = "No se ha encontrado un número. Por favor, vuelva a intentarlo.";
                }
            }
            catch (ArgumentException e)
            {
                response.Trace   = e.StackTrace;
                response.Message = e.Message;
            }
            catch (Exception e)
            {
                response.Trace   = e.StackTrace;
                response.Message = e.Message;
            }

            return(Json(response));
        }
Exemplo n.º 12
0
 private static Dictionary <string, double> GetKeywordsFromResult(AnalysisResults result)
 {
     return(result.Keywords?
            .ToDictionary(x => x.Text, x => x.Relevance.GetValueOrDefault()));
 }
Exemplo n.º 13
0
 private static List <string> GetCategoriesFromResult(AnalysisResults result)
 {
     return(result.Categories?
            .Select(x => x.Label)
            .ToList());
 }
 /// <summary>
 /// This method will return all the events grouped by the start RRC state.
 /// </summary>
 /// <returns>A Dictionary of Analysis results</returns>
 public AnalysisResults GroupByStartRRCState()
 {
     // Group all events by the Start RRC State only.
       var query = Cluster.GetEvents()
                  .GroupBy(evt => new
                  {
                    evt.StartRRCState,
                  },
                  (key, group) => new
                  {
                    StartRRCState = key.StartRRCState,
                    Events = group
                  });
       // Setup a new results object
       AnalysisResults results = new AnalysisResults();
       // Covert each group to an EventCollection
       foreach (var row in query)
       {
     results.Add(row.StartRRCState, new EventCollection(row.Events));
       }
       return results;
 }
 /// <summary>
 /// This method will return all the events grouped by the start/end RAT 
 /// value.
 /// </summary>
 /// <returns>A Dictionary of Analysis results</returns>
 public AnalysisResults GroupByStartEndRat()
 {
     // Group all events by the Start RAT and End RAT only.
       var query = Cluster.GetEvents()
                  .GroupBy(evt => new
                  {
                    evt.StartRat,
                    evt.EndRat
                  },
                  (key, group) => new
                  {
                    StartRat = key.StartRat,
                    EndRat = key.EndRat,
                    Events = group
                  });
       // Setup a new results object
       AnalysisResults results = new AnalysisResults();
       // Covert each group to an EventCollection
       foreach (var row in query)
       {
     String key = GetKeySeperator(row.StartRat, row.EndRat);
     results.Add(key, new EventCollection(row.Events));
       }
       return results;
 }
Exemplo n.º 16
0
 public Bookmark(AnalysisResults analysisResults, List <string> tags) : this(analysisResults)
 {
     Tags.AddRange(tags);
 }