/// <summary>
        /// Executes Sentiment and EntitiesMentioned analysis.
        /// </summary>
        public IOutcome<AnalysisResult> Analyze(StanfordCoreNLP pipeline, string text)
        {
            //Create annotated document
            Annotation doc = new Annotation(text);
            pipeline.annotate(doc);

            //Validate
            var sentences = doc.get(typeof(CoreAnnotations.SentencesAnnotation));

            if (sentences == null)           
                return Outcomes.Outcomes
                               .Failure<AnalysisResult>()
                               .WithMessage("No sentences detected.");

            //Analyze
            var result = new AnalysisResult()
            {
                Sentiment = GetSentiment((ArrayList)sentences),
                MentionedEntities = GetMentions(doc)
            };

            return Outcomes.Outcomes
                           .Success<AnalysisResult>()
                           .WithValue(result);
        }
Exemple #2
0
 public void faceDraw(AnalysisResult analysisResult)
 {
     faceRectangle = analysisResult.Faces.Select(face => face.FaceRectangle).ToArray();
     //clear last faceRectangle
     while (ImageCanvas.Children.Count > 1)
     {
         ImageCanvas.Children.RemoveAt(ImageCanvas.Children.Count - 1);
     }
     canvasControlDraw();
 }
Exemple #3
0
        private static void Analyze(SyntaxNodeAnalysisContext context)
        {
            var            awaitNode      = (AwaitExpressionSyntax)context.Node;
            AnalysisResult analysisResult = HasConfigureAwaitFalse(awaitNode);

            if (!analysisResult.HasConfigureAwaitFalse)
            {
                context.ReportDiagnostic(Diagnostic.Create(Rule, analysisResult.Location));
            }
        }
        // GET: patients/CreateAnalysis?patientId=5
        public ActionResult CreateAnalysis(int? patientId)
        {
            if (patientId == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var analysis = new AnalysisResult { PatientId = patientId.Value };
            return View(analysis);
        }
        /// <summary>
        /// Processes the analysis result.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <returns>The caption if found, error message otherwise.</returns>
        private static string ProcessAnalysisResult(AnalysisResult result)
        {
            string message = result?.Description?.Captions.FirstOrDefault()?.Text;

            MessagesController.MakeRequest();

            return(string.IsNullOrEmpty(message) ?
                   "Couldn't find a caption for this one" :
                   "I think it's " + message);
        }
        private static void VerifyDiagnosticCount([NotNull] AnalysisResult result,
                                                  DiagnosticsCaptureMode captureMode)
        {
            if (captureMode == DiagnosticsCaptureMode.RequireInSourceTree)
            {
                result.Diagnostics.Should().HaveSameCount(result.Spans);
            }

            result.Diagnostics.Should().HaveSameCount(result.Messages);
        }
        public async Task<ActionResult> CreateAnalysis([Bind(Include = "Id,Name,Result,TakenAt,PatientId")] AnalysisResult analysisResult)
        {
            if (ModelState.IsValid)
            {
                await _service.InsertAnalysisAsync(analysisResult);
                return RedirectToAction("Index");
            }

            return View(analysisResult);
        }
Exemple #8
0
        public List <string> GenerateMetaVisionTags(AnalysisResult analysisResult)
        {
            List <string> metaTags = new List <string>();

            GetCategories(analysisResult, metaTags);

            GetTagNames(analysisResult, metaTags);

            return(metaTags);
        }
    public static void Run([ServiceBusTrigger("images", "vision-analyse")] string imageMessage, TraceWriter log)
    {
        log.Info($"Computer Vision image analysis topic trigger processed message: {imageMessage}");

        AnalysisResult imageAnalysisInfo = AnalyseImage(imageMessage, CloudConfigurationManager.GetSetting("vision-analyse-APIKey"), log).Result;

        BlobAppender.AppendToBlob("cv-imageanalysis.txt", JsonConvert.SerializeObject(new { imageAnalysis = imageAnalysisInfo, imageUrl = imageMessage }));

        log.Info($"Completed Computer Vision image analysis for processed message {imageMessage}");
    }
Exemple #10
0
        private AnalysisResult RunDiagnostics([NotNull] AnalyzerTestContext context,
                                              [NotNull][ItemNotNull] params string[] messages)
        {
            AnalysisResult result = GetAnalysisResult(context, messages);

            VerifyDiagnosticCount(result, context.DiagnosticsCaptureMode);
            VerifyDiagnostics(result, context);

            return(result);
        }
Exemple #11
0
        /// <summary>
        /// Add Columns to AnalysisResult object
        /// </summary>
        /// <param name="result">
        /// <see cref="AnalysisResult"/> object
        /// </param>
        /// <returns>
        /// <see cref="AnalysisResult"/> updated object
        /// </returns>
        private AnalysisResult AddAnalysisResultColumns(AnalysisResult result)
        {
            foreach (AnalysisProcessingResultColumn resultColumn in resultColumns)
            {
                var col = new AnalysisColumn(resultColumn.ResultColumn, xCategoryArray);
                result.AddColumn(col);
            }

            return(result);
        }
        public AnalysisResult Evaluate(List<ProjectContext> projectContexts)
        {
            var targetGroupedContexts = GroupContextsByTarget(projectContexts);

            var failureMessages = EvaluateProjectContextTargetGroups(targetGroupedContexts);
            var pass = failureMessages.Count == 0;

            var result = new AnalysisResult(failureMessages, pass);
            return result;
        }
Exemple #13
0
        static bool IsPhoto(AnalysisResult analysisResult)
        {
            if (analysisResult.Description.Tags.Contains("photo"))
            {
                return(true);
            }

            return(!analysisResult.IsClipArt() &&
                   !analysisResult.IsLineDrawing());
        }
Exemple #14
0
        /// <summary>
        /// Creates a folder containing a ProjectInfo.xml and compiled file list as
        /// specified in the supplied descriptor
        /// </summary>
        private static void CreateFilesFromDescriptor(ProjectDescriptor descriptor, string compileFiles, string fxcopReportFileName, string visualStudioCodeCoverageReportFileName)
        {
            if (!Directory.Exists(descriptor.FullDirectoryPath))
            {
                Directory.CreateDirectory(descriptor.FullDirectoryPath);
            }

            ProjectInfo projectInfo = descriptor.CreateProjectInfo();

            // Create the analysis file list if any input files have been specified
            if (descriptor.FilesToAnalyse.Any())
            {
                string fullAnalysisFileListPath = Path.Combine(descriptor.FullDirectoryPath, compileFiles);
                File.WriteAllLines(fullAnalysisFileListPath, descriptor.FilesToAnalyse);

                // Add the compile list as an analysis result
                projectInfo.AnalysisResults.Add(new AnalysisResult()
                {
                    Id = AnalysisType.FilesToAnalyze.ToString(), Location = fullAnalysisFileListPath
                });
            }

            // Create the FxCop report file
            if (fxcopReportFileName != null)
            {
                string fullFxCopName = Path.Combine(descriptor.FullDirectoryPath, fxcopReportFileName);
                File.Create(fullFxCopName);

                // Add the FxCop report as an analysis result
                var analysisResult = new AnalysisResult()
                {
                    Id = AnalysisType.FxCop.ToString(), Location = fullFxCopName
                };
                descriptor.AnalysisResults.Add(analysisResult);
                projectInfo.AnalysisResults.Add(analysisResult);
            }

            // Create the Visual Studio Code Coverage report file
            if (visualStudioCodeCoverageReportFileName != null)
            {
                string fullVisualStudioCodeCoverageName = Path.Combine(descriptor.FullDirectoryPath, visualStudioCodeCoverageReportFileName);
                File.Create(fullVisualStudioCodeCoverageName);

                // Add the Visual Studio Code Coverage report as an analysis result
                var analysisResult = new AnalysisResult()
                {
                    Id = AnalysisType.VisualStudioCodeCoverage.ToString(), Location = fullVisualStudioCodeCoverageName
                };
                descriptor.AnalysisResults.Add(analysisResult);
                projectInfo.AnalysisResults.Add(analysisResult);
            }

            // Save a project info file in the target directory
            projectInfo.Save(Path.Combine(descriptor.FullDirectoryPath, FileConstants.ProjectInfoFileName));
        }
        private void ProcessResultRows(
            AnalysisResult result,
            UPMGridPage searchPage,
            IReadOnlyList <object> xColumnArray,
            bool keyAsRawString,
            int columnCount,
            UPMResultSection section)
        {
            var i          = 0;
            var resultRows = CreateResultRows(result);
            var sumRow     = result.SumLine;

            foreach (AnalysisRow row in resultRows)
            {
                var identifier = StringIdentifier.IdentifierWithStringId($"row {i}");
                var listRow    = new UPMResultRow(identifier)
                {
                    Context = row
                };
                i++;
                var fieldArray = CreateFieldArray(row, xColumnArray, keyAsRawString, columnCount, i);

                listRow.Fields = fieldArray;
                if (searchPage.FixedSumRow && sumRow != null && i == resultRows.Count && resultRows.Count > 12)
                {
                    searchPage.SumResultRow = listRow;
                    searchPage.SumRowAtEnd  = false;
                }
                else
                {
                    section.AddResultRow(listRow);
                }

                if (row.HasDetails)
                {
                    var detailGroupCol1 = new UPMAnalysisResultRowGroup(StringIdentifier.IdentifierWithStringId("det1"))
                    {
                        Invalid = true,
                        Left    = true,
                        Row     = row
                    };
                    listRow.AddDetailGroup(detailGroupCol1);
                    var detailGroupCol2 = new UPMAnalysisResultRowGroup(StringIdentifier.IdentifierWithStringId("det2"))
                    {
                        Invalid = true,
                        Left    = false,
                        Row     = row
                    };
                    listRow.AddDetailGroup(detailGroupCol2);
                }

                this.AddDrilldownActionsFromRowToListRow(row, listRow);
                this.AddDetailsActionFromRowToListRow(row, listRow);
            }
        }
        private async void _TakePhoto()
        {
            Debug.WriteLine("Taking Photo");

            try
            {
                photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync(PHOTO_FILE_NAME, CreationCollisionOption.ReplaceExisting);

                var imageProperties = ImageEncodingProperties.CreateJpeg();

                await mediaCapture.CapturePhotoToStorageFileAsync(imageProperties, photoFile);

                var photoStream = await photoFile.OpenReadAsync();

                var bitmap = new BitmapImage();
                bitmap.SetSource(photoStream);
                captureImage.Source = bitmap;

                using (Stream imageFileStream = (await photoFile.OpenReadAsync()).AsStreamForRead())
                {
                    // Analyze the image for all visual features
                    Debug.WriteLine("Calling VisionServiceClient.AnalyzeImageAsync()...");
                    VisualFeature[] visualFeatures = new VisualFeature[]
                    {
                        VisualFeature.Adult, VisualFeature.Categories, VisualFeature.Color, VisualFeature.Description,
                        VisualFeature.Faces, VisualFeature.ImageType, VisualFeature.Tags
                    };

                    // add your API key in here
                    VisionServiceClient VisionServiceClient = new VisionServiceClient("");

                    analysisResult =
                        await VisionServiceClient.AnalyzeImageAsync(imageFileStream, visualFeatures);

                    Debug.WriteLine("photo: " + analysisResult.Description.Captions[0].Text + " , " + analysisResult.Description.Captions[0].Confidence);

                    if (analysisResult.Description.Captions[0].Confidence > 0.6d)
                    {
                        Speak("I see, " + analysisResult.Description.Captions[0].Text);
                    }
                    else
                    {
                        Speak("I'm not quite sure but it could be, " + analysisResult.Description.Captions[0].Text);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                isProcessing = false;
            }
        }
        private async Task <AnalysisResult> UploadAndAnalyzeImage(StorageFile imageFile)
        {
            var stream = await imageFile.OpenStreamForReadAsync();


            Log("Calling VisionServiceClient.AnalyzeImageAsync()...");
            VisualFeature[] visualFeatures = new VisualFeature[] { VisualFeature.Adult, VisualFeature.Categories, VisualFeature.Color, VisualFeature.Description, VisualFeature.Faces, VisualFeature.ImageType, VisualFeature.Tags };
            AnalysisResult  analysisResult = await VisionServiceClient.AnalyzeImageAsync(stream, visualFeatures);

            return(analysisResult);
        }
        public AnalysisResult Evaluate(IEnumerable<ProjectContext> projectContexts)
        {
            var filteredContexts = FilterContextList(projectContexts);
            var targetGroupedContexts = GroupContextsByTarget(filteredContexts);

            var failureMessages = EvaluateProjectContextTargetGroups(targetGroupedContexts);
            var pass = failureMessages.Count() == 0;

            var result = new AnalysisResult(failureMessages, pass);
            return result;
        }
Exemple #19
0
 private void ShowResult(AnalysisResult result)
 {
     if (result.Succeded())
     {
         this.ui.ShowSuccededResult(result);
     }
     else
     {
         this.ui.ShowErrorMessage(result);
     }
 }
        public AnalysisResult Evaluate(List <ProjectContext> projectContexts)
        {
            var targetGroupedContexts = GroupContextsByTarget(projectContexts);

            var failureMessages = EvaluateProjectContextTargetGroups(targetGroupedContexts);
            var pass            = failureMessages.Count == 0;

            var result = new AnalysisResult(failureMessages, pass);

            return(result);
        }
Exemple #21
0
    private static void WriteResult(AnalysisResult result, HttpListenerResponse response)
    {
        response.StatusCode = 200;
        Stream output = response.OutputStream;

        using (XmlWriter xml = WriteXml(output))
        {
            Pullenti_.XmlResult(result, xml);
        }
        output.Close();
    }
        /// <summary>
        /// 取非法信号干扰信息
        /// </summary>
        /// <param name="illsignal"></param>
        /// <param name="freq"></param>
        /// <returns></returns>
        private InterfereObject CreateInterfObjectFromSignal(AnalysisResult illsignal, ComparableFreq freq)
        {
            InterfereObject intosignal = new InterfereObject();

            intosignal.Guid = illsignal.Id;
            intosignal.Name = illsignal.EquimentName;
            intosignal.Type = InterfereObjectEnum.非法信号;
            intosignal.Freq = freq.Freq;
            intosignal.Band = freq.Band;
            return(intosignal);
        }
Exemple #23
0
        static bool IsBlackAndWhite(AnalysisResult analysisResult)
        {
            if (analysisResult.Description.Tags.Contains("photo") &&
                analysisResult.Description.Tags.Contains("vintage"))
            {
                // vintage photo means a black and white photo. Black and white photos are black and white.
                return(true);
            }

            return(analysisResult.IsBlackAndWhite());
        }
Exemple #24
0
        public async Task ibm(String ab)
        {
            sad  = 0.0;
            joy  = 0.0;
            fear = 0.0;
            dis  = 0.0;
            ang  = 0.0;
            String         abb  = ab;
            string         temp = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=" + abb + "&features=sentiment,keywords,emotion&keywords.sentiment=true";
            HttpWebRequest request;

            try
            {
                request = (HttpWebRequest)WebRequest.Create(temp);

                request.Credentials = new NetworkCredential("082e2d88-9164-4338-b35d-c62580b3a78d", "Eed1kE8nDr8f");
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
                request.ContentType = "application/json";
                request.MediaType   = "application/json";
                request.Accept      = "application/json";
                request.Method      = "POST";
                string text;
                var    response = await request.GetResponseAsync();

                StreamReader sr = new StreamReader(response.GetResponseStream());


                text = sr.ReadToEnd();

                HttpResponseMessage res = await CreateJsonResponse(text);

                Analysis x  = res.Content.ReadAsAsync <Analysis>().Result;
                double   sc = Convert.ToDouble(x.sentiment.document.score);
                String   lb = x.sentiment.document.label;
                try
                {
                    sad  = Convert.ToDouble(x.emotion.document.emotion.sadness);
                    joy  = Convert.ToDouble(x.emotion.document.emotion.joy);
                    fear = Convert.ToDouble(x.emotion.document.emotion.fear);
                    dis  = Convert.ToDouble(x.emotion.document.emotion.disgust);
                    ang  = Convert.ToDouble(x.emotion.document.emotion.anger);
                }
                catch (Exception o)
                {
                }

                AnalysisResult a = new AnalysisResult(sc, lb, sad, joy, fear, dis, ang);
                result_data.Add(a);
            }
            catch (WebException e)
            {
            }
        }
Exemple #25
0
        private static void AssertAnalysisResultExists(ProjectInfo actual, string expectedId, string expectedLocation)
        {
            Assert.IsNotNull(actual, "Supplied project info should not be null");
            Assert.IsNotNull(actual.AnalysisResults, "AnalysisResults should not be null");

            AnalysisResult result = actual.AnalysisResults.FirstOrDefault(ar => expectedId.Equals(ar.Id, StringComparison.InvariantCulture));

            Assert.IsNotNull(result, "AnalysisResult with the expected id does not exist. Id: {0}", expectedId);

            Assert.AreEqual(expectedLocation, result.Location, "Analysis result does not have the expected location");
        }
 public AnalysisResult ReduceRight(AnalysisResult other)
 {
     return new AnalysisResult()
     {
         Letters = (this.Letters + other.Letters) / 2,
         WhiteSpace = (this.WhiteSpace + other.WhiteSpace) / 2,
         Numbers = (this.Numbers + other.Numbers) / 2,
         Punctuation = (this.Punctuation + other.Punctuation) / 2,
         Other = (this.Other + other.Other) / 2
     };
 }
        public async Task <string> getcaption(String url)
        {
            VisionServiceClient vision = new VisionServiceClient("****************************************");


            VisualFeature[] visual   = new VisualFeature[] { VisualFeature.Description };
            AnalysisResult  analysis = await vision.AnalyzeImageAsync(url, visual);

            string message = analysis?.Description?.Captions.FirstOrDefault()?.Text;

            return(message);
        }
Exemple #28
0
        public void AnalysisResultIsNull_ArgumentNullExceptionThrown()
        {
            // Arrange

            AnalysisResult analysisResult = null;

            // Act
            Action action = () => _builderModelCreator.Create(analysisResult);

            // Assert
            Assert.Throws <ArgumentNullException>("analysisResult", action);
        }
Exemple #29
0
        public void InitializeVisitorForAccept(AnalysisResult fileAnalysisResult)
        {
            if (fileAnalysisResult == null)
            {
                throw new ArgumentNullException(nameof(fileAnalysisResult));
            }

            this.fileAnalysisResult = fileAnalysisResult;

            isAcceptedFilterMatching = false;
            isVisited = false;
        }
Exemple #30
0
        public void NoProperties_BuilderClassNameAsExpected()
        {
            // Arrange
            var analysisResult = new AnalysisResult("ClassName", Array.Empty <ClassMember>());

            // Act
            var builderModel = _builderModelCreator.Create(analysisResult);

            // Assert
            Assert.NotNull(builderModel);
            Assert.Equal("ClassNameBuilder", builderModel.BuilderClassName);
        }
Exemple #31
0
        public void NoProperties_FieldsEmpty()
        {
            // Arrange
            var analysisResult = new AnalysisResult("ClassName", Array.Empty <ClassMember>());

            // Act
            var builderModel = _builderModelCreator.Create(analysisResult);

            // Assert
            Assert.NotNull(builderModel);
            Assert.Empty(builderModel.Properties);
        }
        private static List <object> CreateResultRows(AnalysisResult result)
        {
            var resultRows = new List <object>(result.Rows);
            var sumRow     = result.SumLine;

            if (sumRow != null)
            {
                resultRows.Add(sumRow);
            }

            return(resultRows);
        }
Exemple #33
0
        public static void ShowCaptions(AnalysisResult analyzed)
        {
            //Captions is a variable that is a result of selecting the text and confidence properties for all the analyzed.Description.Captions occurencces.
            var captions = from caption in analyzed.Description.Captions select caption.Text + " - " + caption.Confidence;

            //These occurences are then joined as a single string and written to console
            if (captions.Count() > 0)
            {
                Console.WriteLine("Captions >>>>");
                Console.WriteLine(string.Join(", ", captions));
            }
        }
Exemple #34
0
        static void Main(string[] args)
        {
            IComputerVisionService   computerVisionClient    = new ComputerVisionService();
            IKeywordGeneratorService keywordGeneratorService = new KeywordGeneratorService();

            AnalysisResult analysisResult = computerVisionClient.AnalyzeImageAsync("https://www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=8389163").Result;

            List <string> keywords = keywordGeneratorService.GenerateMetaVisionTags(analysisResult);

            Console.WriteLine(analysisResult);
            Console.ReadLine();
        }
Exemple #35
0
 public void SetVariable(string name, AnalysisResult value = AnalysisResult.Null)
 {
     var current = stack.Peek();
     if (current.ContainsKey(name))
     {
         current[name] = value;
     }
     else
     {
         current.Add(name, value);
     }
 }
            private static void Analyze(SyntaxTriviaList list, ref AnalysisResult result)
            {
                if (list.Count == 0)
                {
                    return;
                }

                foreach (var trivia in list)
                {
                    if (trivia.Kind() == SyntaxKind.WhitespaceTrivia)
                    {
                        AnalyzeWhitespacesInTrivia(trivia, ref result);
                    }
                    else if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
                    {
                        AnalyzeLineBreak(trivia, ref result);
                    }
                    else if (trivia.IsRegularOrDocComment())
                    {
                        result.HasComments = true;
                    }
                    else if (trivia.Kind() == SyntaxKind.SkippedTokensTrivia)
                    {
                        result.HasSkippedTokens = true;
                    }
                    else if (trivia.Kind() == SyntaxKind.DisabledTextTrivia ||
                             trivia.Kind() == SyntaxKind.PreprocessingMessageTrivia)
                    {
                        result.HasSkippedOrDisabledText = true;
                    }
                    else
                    {
                        Contract.ThrowIfFalse(SyntaxFacts.IsPreprocessorDirective(trivia.Kind()));

                        result.HasPreprocessor = true;
                    }
                }
            }
        private static ImmutableArray<DiagnosticData> GetResult(AnalysisResult result, AnalysisKind kind, DocumentId id)
        {
            if (result.IsEmpty || !result.DocumentIds.Contains(id) || result.IsAggregatedForm)
            {
                return ImmutableArray<DiagnosticData>.Empty;
            }

            switch (kind)
            {
                case AnalysisKind.Syntax:
                    return result.GetResultOrEmpty(result.SyntaxLocals, id);
                case AnalysisKind.Semantic:
                    return result.GetResultOrEmpty(result.SemanticLocals, id);
                case AnalysisKind.NonLocal:
                    return result.GetResultOrEmpty(result.NonLocals, id);
                default:
                    return Contract.FailWithReturn<ImmutableArray<DiagnosticData>>("shouldn't reach here");
            }
        }
Exemple #38
0
        private void RaiseProjectDiagnosticsCreated(Project project, StateSet stateSet, AnalysisResult oldAnalysisResult, AnalysisResult newAnalysisResult, Action<DiagnosticsUpdatedArgs> raiseEvents)
        {
            foreach (var documentId in newAnalysisResult.DocumentIds)
            {
                var document = project.GetDocument(documentId);
                if (document == null)
                {
                    // it can happen with build synchronization since, in build case, 
                    // we don't have actual snapshot (we have no idea what sources out of proc build has picked up)
                    // so we might be out of sync.
                    // example of such cases will be changing anything about solution while building is going on.
                    // it can be user explict actions such as unloading project, deleting a file, but also it can be 
                    // something project system or roslyn workspace does such as populating workspace right after
                    // solution is loaded.
                    continue;
                }

                RaiseDocumentDiagnosticsIfNeeded(document, stateSet, AnalysisKind.NonLocal, oldAnalysisResult, newAnalysisResult, raiseEvents);

                // we don't raise events for active file. it will be taken cared by active file analysis
                if (stateSet.IsActiveFile(documentId))
                {
                    continue;
                }

                RaiseDocumentDiagnosticsIfNeeded(document, stateSet, AnalysisKind.Syntax, oldAnalysisResult, newAnalysisResult, raiseEvents);
                RaiseDocumentDiagnosticsIfNeeded(document, stateSet, AnalysisKind.Semantic, oldAnalysisResult, newAnalysisResult, raiseEvents);
            }

            RaiseDiagnosticsCreated(project, stateSet, newAnalysisResult.Others, raiseEvents);
        }
        private ImmutableDictionary<DiagnosticAnalyzer, AnalysisResult> CreateAnalysisResults(
            Project project, ImmutableArray<StateSet> stateSets, ProjectAnalysisData oldAnalysisData, ImmutableArray<DiagnosticData> diagnostics)
        {
            using (var poolObject = SharedPools.Default<HashSet<string>>().GetPooledObject())
            {
                // we can't distinguish locals and non locals from build diagnostics nor determine right snapshot version for the build.
                // so we put everything in as semantic local with default version. this lets us to replace those to live diagnostics when needed easily.
                var version = VersionStamp.Default;
                var lookup = diagnostics.ToLookup(d => d.Id);

                var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, AnalysisResult>();
                foreach (var stateSet in stateSets)
                {
                    var descriptors = HostAnalyzerManager.GetDiagnosticDescriptors(stateSet.Analyzer);
                    var liveDiagnostics = MergeDiagnostics(ConvertToLiveDiagnostics(lookup, descriptors, poolObject.Object), GetDiagnostics(oldAnalysisData.GetResult(stateSet.Analyzer)));

                    var group = liveDiagnostics.GroupBy(d => d.DocumentId);
                    var result = new AnalysisResult(
                        project.Id,
                        version,
                        documentIds: group.Where(g => g.Key != null).Select(g => g.Key).ToImmutableHashSet(),
                        syntaxLocals: ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>>.Empty,
                        semanticLocals: group.Where(g => g.Key != null).ToImmutableDictionary(g => g.Key, g => g.ToImmutableArray()),
                        nonLocals: ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>>.Empty,
                        others: group.Where(g => g.Key == null).SelectMany(g => g).ToImmutableArrayOrEmpty());

                    builder.Add(stateSet.Analyzer, result);
                }

                return builder.ToImmutable();
            }
        }
            private static void AnalyzeWhitespacesInTrivia(SyntaxTrivia trivia, ref AnalysisResult result)
            {
                // trivia already has text. getting text should be noop
                Debug.Assert(trivia.Kind() == SyntaxKind.WhitespaceTrivia);
                Debug.Assert(trivia.Width() == trivia.FullWidth());

                int space = 0;
                int tab = 0;
                int unknownWhitespace = 0;

                var text = trivia.ToString();
                for (int i = 0; i < trivia.Width(); i++)
                {
                    if (text[i] == ' ')
                    {
                        space++;
                    }
                    else if (text[i] == '\t')
                    {
                        if (result.Space > 0)
                        {
                            result.HasTabAfterSpace = true;
                        }

                        tab++;
                    }
                    else
                    {
                        unknownWhitespace++;
                    }
                }

                // set result
                result.Space += space;
                result.Tab += tab;
                result.HasUnknownWhitespace |= unknownWhitespace > 0;
                result.TreatAsElastic |= trivia.IsElastic();
            }
            private static void AnalyzeLineBreak(SyntaxTrivia trivia, ref AnalysisResult result)
            {
                // if there was any space before line break, then we have trailing spaces
                if (result.Space > 0 || result.Tab > 0)
                {
                    result.HasTrailingSpace = true;
                }

                // reset space and tab information
                result.LineBreaks++;

                result.HasTabAfterSpace = false;
                result.Space = 0;
                result.Tab = 0;
                result.TreatAsElastic |= trivia.IsElastic();
            }
        private ImmutableArray<DiagnosticData> GetDiagnostics(AnalysisResult result)
        {
            // PERF: don't allocation anything if not needed
            if (result.IsAggregatedForm || result.IsEmpty)
            {
                return ImmutableArray<DiagnosticData>.Empty;
            }

            return result.SyntaxLocals.Values.SelectMany(v => v).Concat(
                   result.SemanticLocals.Values.SelectMany(v => v)).Concat(
                   result.NonLocals.Values.SelectMany(v => v)).Concat(
                   result.Others).ToImmutableArray();
        }
        private void RaiseDocumentDiagnosticsIfNeeded(
            Document document, StateSet stateSet, AnalysisKind kind,
            AnalysisResult oldResult, AnalysisResult newResult,
            Action<DiagnosticsUpdatedArgs> raiseEvents)
        {
            var oldItems = GetResult(oldResult, kind, document.Id);
            var newItems = GetResult(newResult, kind, document.Id);

            RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, oldItems, newItems, raiseEvents);
        }
        private void RaiseProjectDiagnosticsCreated(Project project, StateSet stateSet, AnalysisResult oldAnalysisResult, AnalysisResult newAnalysisResult, Action<DiagnosticsUpdatedArgs> raiseEvents)
        {
            foreach (var documentId in newAnalysisResult.DocumentIds)
            {
                var document = project.GetDocument(documentId);
                Contract.ThrowIfNull(document);

                RaiseDocumentDiagnosticsIfNeeded(document, stateSet, AnalysisKind.NonLocal, oldAnalysisResult, newAnalysisResult, raiseEvents);

                // we don't raise events for active file. it will be taken cared by active file analysis
                if (stateSet.IsActiveFile(documentId))
                {
                    continue;
                }

                RaiseDocumentDiagnosticsIfNeeded(document, stateSet, AnalysisKind.Syntax, oldAnalysisResult, newAnalysisResult, raiseEvents);
                RaiseDocumentDiagnosticsIfNeeded(document, stateSet, AnalysisKind.Semantic, oldAnalysisResult, newAnalysisResult, raiseEvents);
            }

            RaiseDiagnosticsCreated(project, stateSet, newAnalysisResult.Others, raiseEvents);
        }