public BottomMargin(IWpfTextView textView, IClassifierAggregatorService classifier, ITextDocumentFactoryService documentService)
        {
            _textView = textView;
            _classifier = classifier.GetClassifier(textView.TextBuffer);
            _foregroundBrush = new SolidColorBrush((Color)FindResource(VsColors.CaptionTextKey));
            _backgroundBrush = new SolidColorBrush((Color)FindResource(VsColors.ScrollBarBackgroundKey));

            this.Background = _backgroundBrush;
            this.ClipToBounds = true;

            _lblEncoding = new TextControl("Encoding");
            this.Children.Add(_lblEncoding);

            _lblContentType = new TextControl("Content type");
            this.Children.Add(_lblContentType);

            _lblClassification = new TextControl("Classification");
            this.Children.Add(_lblClassification);

            _lblSelection = new TextControl("Selection");
            this.Children.Add(_lblSelection);

            UpdateClassificationLabel();
            UpdateContentTypeLabel();
            UpdateContentSelectionLabel();

            if (documentService.TryGetTextDocument(textView.TextDataModel.DocumentBuffer, out _doc))
            {
                _doc.FileActionOccurred += FileChangedOnDisk;
                UpdateEncodingLabel(_doc);
            }

            textView.Caret.PositionChanged += CaretPositionChanged;
        }
Exemple #2
0
        public double Validate(IClassifier classifier, Dataset csvReader)
        {
            SplitDataset(csvReader.Input, csvReader.Output);

            classifier.Learn(_trainingDataset, _trainingOutput);

            var predictedValues = new int[_testOutput.Length];

            for (int i = 0; i < _testDataSet.GetLength(0); i++)
            {
                for (int j = 0; j < _testDataSet.GetLength(1); j++)
                {
                    var prediction = classifier.Predict(GetLineOfTestDataset(i));
                    predictedValues[i] = prediction;
                }
            }

            var numberOfTrues = 0;

            for (int i = 0; i < _testOutput.Length; i++)
            {
                if (predictedValues[i] == _testOutput[i])
                {
                    numberOfTrues++;
                }
            }

            double accuracy = Convert.ToDouble(numberOfTrues) / Convert.ToDouble(_testOutput.Length);

            return(accuracy);
        }
        /// <summary>
        /// Gets the classifier for specified text buffer.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        /// <returns>Classifier for specified text buffer.</returns>
        public IClassifier GetClassifier(ITextBuffer buffer)
        {
            var dte = (DTE)ServiceProvider.GetService(typeof(DTE));
            var configuration = dte.Properties["Output Colorer", "General"];

            if (buffer.ContentType.IsOfType(BuildOutputContentType))
            {
                if (_buildOutputClassifier == null)
                {
                    var settings = (IEnumerable<ColorerFormatSetting>)configuration.Item("BuildOutputSettings").Value;
                    _buildOutputClassifier = new OutputClassifier(ClassificationRegistry, settings);
                }

                return _buildOutputClassifier;
            }

            if (buffer.ContentType.IsOfType(DebugOutputContentType))
            {
                if (_debugOutputClassifier == null)
                {
                    var settings = (IEnumerable<ColorerFormatSetting>)configuration.Item("DebugOutputSettings").Value;
                    _debugOutputClassifier = new OutputClassifier(ClassificationRegistry, settings);
                }

                return _debugOutputClassifier;
            }

            if (buffer.ContentType.IsOfType(FindResultsContentType))
            {
                return _findResultsClassifier ?? (_findResultsClassifier = new FindResultsClassifier(ClassificationRegistry));
            }

            return null;
        }
Exemple #4
0
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="textView">The text view to use</param>
        /// <param name="serviceProvider">The service provider to use</param>
        /// <param name="aggregator">The classifier tag aggregator to use</param>
        /// <param name="navigator">The text structure navigator to use</param>
        /// <param name="state">The Ctrl key state tracker to use</param>
        public GoToDefinitionMouseProcessor(IWpfTextView textView, SVsServiceProvider serviceProvider,
                                            IClassifier aggregator, ITextStructureNavigator navigator, CtrlKeyState state)
        {
            this.TextView        = textView;
            this.ServiceProvider = serviceProvider;

            this.ctrlState  = state;
            this.aggregator = aggregator;
            this.navigator  = navigator;

            this.ctrlState.CtrlKeyStateChanged += (sender, args) =>
            {
                if (this.ctrlState.Enabled)
                {
                    this.TryHighlightItemUnderMouse(this.RelativeToView(Mouse.PrimaryDevice.GetPosition(this.TextView.VisualElement)));
                }
                else
                {
                    this.SetHighlightSpan(null, null);
                }
            };

            // Some other points to clear the highlight span:
            this.TextView.LostAggregateFocus       += (sender, args) => this.SetHighlightSpan(null, null);
            this.TextView.VisualElement.MouseLeave += (sender, args) => this.SetHighlightSpan(null, null);
        }
Exemple #5
0
        public void Edit(IClassifier classifier)
        {
            Debug.Assert(classifier != null, "Extractor must be supplied to allow editing.");

            var window = new AddEditClassifierWindow();
            var data   = new AddEditClassifier(window, true);

            window.DataContext = data;
            window.Owner       = Application.Current.MainWindow;

            data.Name    = classifier.Name;
            data.Field   = classifier.Field;
            data.Pattern = classifier.Pattern;
            data.Mode    = classifier.Mode;
            data.Type    = classifier.Type;

            var dialogResult = window.ShowDialog();

            if (dialogResult != null && (bool)dialogResult)
            {
                classifier.Name    = data.Name;
                classifier.Pattern = data.Pattern;
                classifier.Mode    = data.Mode;
                classifier.Field   = data.Field;
                classifier.Type    = data.Type;
            }
        }
Exemple #6
0
 private static double Score(Observation obs, IClassifier classifier)
 {
     if (classifier.Predict(obs.Pixels) == obs.Label)
         return 1.0;
     else
         return 0.0;
 }
Exemple #7
0
        public void VsTextViewCreated(IVsTextView textViewAdapter)
        {
            IWpfTextView textView   = EditorAdaptersFactoryService.GetWpfTextView(textViewAdapter);
            IClassifier  classifier = ClassifierService.GetClassifier(textView.TextBuffer);

            AddCommandFilter(textViewAdapter, new ExpandCommand(textView, CompletionBroker, UndoProvider, classifier));
        }
        internal void RemoveTagger(SpellCheckerTagger tagger)
        {
            _activeTaggers.Remove(tagger);

            if (_activeTaggers.Count == 0)
            {
                // Last tagger was disposed of. This is means there are no longer any open views on the buffer so we can safely shut down
                // spell checking for that buffer.
                _buffer.ChangedLowPriority -= this.OnBufferChange;

                _provider.RemoveSpellChecker(this);

                _isDisposed = true;

                _buffer.Properties.RemoveProperty(typeof(SpellChecker));

                IDisposable classifierDispose = _classifier as IDisposable;
                if (classifierDispose != null)
                {
                    classifierDispose.Dispose();
                }

                _classifier = null;
            }
        }
Exemple #9
0
        private bool IsDocString(ITextView textWindow, SnapshotPoint point)
        {
            var         aggregator = _serviceProvider.GetComponentModel().GetService <IClassifierAggregatorService>();
            IClassifier classifier = aggregator.GetClassifier(textWindow.TextBuffer);

            var curLine = point.GetContainingLine();
            var tokens  = classifier.GetClassificationSpans(curLine.Extent);

            // TODO: Is null the right check for not having tokens?
            for (int i = curLine.LineNumber - 1; i >= 0 && tokens == null; i--)
            {
                tokens = classifier.GetClassificationSpans(curLine.Extent);
                if (tokens != null)
                {
                    break;
                }
                i = i - 1;
            }
            if (tokens == null)
            {
                return(false);
            }
            // Tokens is NOT None here.
            // If first token found on a line is only token and is string literal,
            // we're in a doc string.  Because multiline, can't be "" or ''.
            return(tokens.Count == 1 && tokens[0].ClassificationType.IsOfType(PredefinedClassificationTypeNames.String));
        }
        public CommentTextTagger(ITextBuffer buffer, IClassifier classifier)
        {
            _buffer     = buffer;
            _classifier = classifier;

            classifier.ClassificationChanged += ClassificationChanged;
        }
Exemple #11
0
        // Set the parameters for the classifier
        public void SetParameters(object sender, EventArgs e)
        {
            // Check that we have training data
            if (!HasTrainingData)
            {
                MessageBox.Show("Please load training data first");
                return;
            }

            // Show the parameters window and get the parameters
            SetTrainParamsForm paramsForm = new SetTrainParamsForm( );

            if (paramsForm.ShowDialog( ) == DialogResult.OK)
            {
                // The number of inputs equals the length of the feature vector
                int numInputs = trainData.Samples[0].FeatureVector.Count;

                // The remaining parameters are configurable
                int    numHiddenNodes = paramsForm.NumHiddenNodes;
                double learningRate   = paramsForm.LearningRate;
                int    maxRepetitions = paramsForm.MaxRepetitions;

                // Create the classifier
                classifier = new SimpleNeuralNet1(
                    numInputs, numHiddenNodes, learningRate, maxRepetitions);
            }
            else
            {
                MessageBox.Show("Please set the training parameters");
                return;
            }
        }
Exemple #12
0
 public SimpleSuggestedActions(SimpleSuggestedActionsProvider provider, ITextView textView, ITextBuffer textBuffer)
 {
     m_provider   = provider;
     m_textView   = textView;
     m_textBuffer = textBuffer;
     m_classifier = GeneralAsmClassifier.GetClassifier(textBuffer);
 }
Exemple #13
0
 public PkgdefErrorTagger(IWpfTextView view, IClassifierAggregatorService classifier, ErrorListProvider errorlist, ITextDocument document)
 {
     _view       = view;
     _classifier = classifier.GetClassifier(view.TextBuffer);
     _errorlist  = errorlist;
     _document   = document;
 }
Exemple #14
0
 public ClassifierInstance(IClassifier classifier, double[] featureScaling, double[] featureShift, string[] trainedIdentifiers)
 {
     this.classifier         = classifier;
     this.featureScaling     = featureScaling;
     this.featureShift       = featureShift;
     this.trainedIdentifiers = trainedIdentifiers;
 }
Exemple #15
0
 public GetClassesCommand(
     IClassifier <double> classifier,
     Func <Option <IFeatureCollection, Exception> > featureCollectionProvider)
 {
     this.classifier = classifier;
     this.featureCollectionProvider = featureCollectionProvider;
 }
        public VsctCompletionSource(ITextBuffer buffer, IClassifierAggregatorService classifier, ITextStructureNavigatorSelectorService navigator, string file)
        {
            _classifier = classifier.GetClassifier(buffer);
            _navigator  = navigator.GetTextStructureNavigator(buffer);

            _parser = new VsctParser(this, file);
        }
Exemple #17
0
        private static void ClassifyFile(MarkdownTestFilesFixture fixture, string fileName)
        {
            string testFile = fixture.GetDestinationPath(fileName);
            string content  = fixture.LoadDestinationFile(fileName);

            TextBufferMock textBuffer = new TextBufferMock(content, MdContentTypeDefinition.ContentType);

            MdClassifierProvider classifierProvider = new MdClassifierProvider();

            EditorShell.Current.CompositionService.SatisfyImportsOnce(classifierProvider);

            IClassifier cls = classifierProvider.GetClassifier(textBuffer);

            IList <ClassificationSpan> spans = cls.GetClassificationSpans(new SnapshotSpan(textBuffer.CurrentSnapshot, new Span(0, textBuffer.CurrentSnapshot.Length)));
            string actual = ClassificationWriter.WriteClassifications(spans);

            string baselineFile = testFile + ".colors";

            if (_regenerateBaselineFiles)
            {
                baselineFile = Path.Combine(fixture.SourcePath, @"Classification\", Path.GetFileName(testFile)) + ".colors";
                TestFiles.UpdateBaseline(baselineFile, actual);
            }
            else
            {
                TestFiles.CompareToBaseLine(baselineFile, actual);
            }
        }
Exemple #18
0
 public NavigableSymbolSource(IServiceProvider serviceProvider, ITextBuffer buffer, IClassifier classifier, ITextStructureNavigator textNavigator)
 {
     _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
     _buffer          = buffer ?? throw new ArgumentNullException(nameof(buffer));
     _classifier      = classifier ?? throw new ArgumentNullException(nameof(classifier));
     _textNavigator   = textNavigator ?? throw new ArgumentNullException(nameof(textNavigator));
 }
        public static string GetTypeScriptStringValue(this IWpfTextView textView, IClassifier classifier, IStandardClassificationService standardClassifications)
        {
            var buffers = textView.BufferGraph.GetTextBuffers(b => b.ContentType.IsOfType("TypeScript") && textView.GetSelection("TypeScript").HasValue&& textView.GetSelection("TypeScript").Value.Snapshot.TextBuffer == b);

            if (!buffers.Any())
            {
                return(null);
            }

            int position = textView.Caret.Position.BufferPosition;

            if (position == textView.TextBuffer.CurrentSnapshot.Length)
            {
                position = position - 1;
            }

            var span   = new SnapshotSpan(textView.TextBuffer.CurrentSnapshot, position, 1);
            var cspans = classifier.GetClassificationSpans(span);
            var text   = cspans
                         .Where(s => s.ClassificationType == standardClassifications.StringLiteral)
                         .Select(s => s.Span.GetText())
                         .FirstOrDefault();

            return(text != null?text.Substring(1, text.Length - 2) : null);
        }
Exemple #20
0
 internal Tagger(IClassificationTypeRegistryService typeRegistry, ITextView textView, IClassificationFormatMap formatMap, IClassifier classifier)
 {
     _classifier             = classifier;
     _colorizer              = textView.Properties.GetOrCreateSingletonProperty(() => new Colorizer(typeRegistry));
     _formatMap              = formatMap;
     textView.LayoutChanged += OnLayoutChangedEvent;
 }
Exemple #21
0
        public BottomMargin(IWpfTextView textView, IClassifierAggregatorService classifier, ITextDocumentFactoryService documentService)
        {
            _textView        = textView;
            _classifier      = classifier.GetClassifier(textView.TextBuffer);
            _foregroundBrush = new SolidColorBrush((Color)FindResource(VsColors.CaptionTextKey));
            _backgroundBrush = new SolidColorBrush((Color)FindResource(VsColors.ScrollBarBackgroundKey));

            this.Background   = _backgroundBrush;
            this.ClipToBounds = true;

            _lblEncoding = new TextControl("Encoding");
            this.Children.Add(_lblEncoding);

            _lblContentType = new TextControl("Content type");
            this.Children.Add(_lblContentType);

            _lblClassification = new TextControl("Classification");
            this.Children.Add(_lblClassification);

            _lblSelection = new TextControl("Selection");
            this.Children.Add(_lblSelection);

            UpdateClassificationLabel();
            UpdateContentTypeLabel();
            UpdateContentSelectionLabel();

            if (documentService.TryGetTextDocument(textView.TextDataModel.DocumentBuffer, out _doc))
            {
                _doc.FileActionOccurred += FileChangedOnDisk;
                UpdateEncodingLabel(_doc);
            }

            textView.Caret.PositionChanged += CaretPositionChanged;
        }
Exemple #22
0
        static IEnumerable <IClassifier> CreateCommands(Assembly assembly)
        {
            int count = 0;

            foreach (Type type in assembly.GetTypes())
            {
                if (typeof(IClassifier).IsAssignableFrom(type))
                {
                    IClassifier result = Activator.CreateInstance(type) as IClassifier;
                    if (result != null)
                    {
                        count++;
                        yield return(result);
                    }
                }
            }

            if (count == 0)
            {
                string availableTypes = string.Join(",", assembly.GetTypes().Select(t => t.FullName));
                throw new ApplicationException(
                          $"Can't find any type which implements IClassifier in {assembly} from {assembly.Location}.\n" +
                          $"Available types: {availableTypes}");
            }
        }
        public BottomMargin(IWpfTextView textView, IClassifierAggregatorService classifier, ITextDocumentFactoryService documentService)
        {
            _textView = textView;
            _classifier = classifier.GetClassifier(textView.TextBuffer);

            SetResourceReference(BackgroundProperty, EnvironmentColors.ScrollBarBackgroundBrushKey);

            ClipToBounds = true;

            _lblEncoding = new TextControl("Encoding");
            Children.Add(_lblEncoding);

            _lblContentType = new TextControl("Content type");
            Children.Add(_lblContentType);

            _lblClassification = new TextControl("Classification");
            Children.Add(_lblClassification);

            _lblSelection = new TextControl("Selection");
            Children.Add(_lblSelection);

            UpdateClassificationLabel();
            UpdateContentTypeLabel();
            UpdateContentSelectionLabel();

            if (documentService.TryGetTextDocument(textView.TextDataModel.DocumentBuffer, out _doc))
            {
                _doc.FileActionOccurred += FileChangedOnDisk;
                UpdateEncodingLabel(_doc);
            }

            textView.Caret.PositionChanged += CaretPositionChanged;
        }
Exemple #24
0
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="buffer">The text buffer</param>
        /// <param name="classifier">The classifier</param>
        public RMarkdownTextTagger(ITextBuffer buffer, IClassifier classifier)
        {
            this.buffer     = buffer;
            this.classifier = classifier;

            this.classifier.ClassificationChanged += this.ClassificationChanged;
        }
Exemple #25
0
        public BottomMargin(IWpfTextView textView, IClassifierAggregatorService classifier, ITextDocumentFactoryService documentService)
        {
            _textView   = textView;
            _classifier = classifier.GetClassifier(textView.TextBuffer);

            SetResourceReference(BackgroundProperty, EnvironmentColors.ScrollBarBackgroundBrushKey);

            ClipToBounds = true;

            _lblEncoding = new TextControl("Encoding");
            Children.Add(_lblEncoding);

            _lblContentType = new TextControl("Content type");
            Children.Add(_lblContentType);

            _lblClassification = new TextControl("Classification");
            Children.Add(_lblClassification);

            _lblSelection = new TextControl("Selection");
            Children.Add(_lblSelection);

            UpdateClassificationLabel();
            UpdateContentTypeLabel();
            UpdateContentSelectionLabel();

            if (documentService.TryGetTextDocument(textView.TextDataModel.DocumentBuffer, out _doc))
            {
                _doc.FileActionOccurred += FileChangedOnDisk;
                UpdateEncodingLabel(_doc);
            }

            textView.Caret.PositionChanged += CaretPositionChanged;
        }
Exemple #26
0
        public void Edit(IClassifier classifier)
        {
            Debug.Assert(classifier != null, "Extractor must be supplied to allow editing.");

            var window = new AddEditClassifierWindow();
            var data = new AddEditClassifier(window, true);
            window.DataContext = data;
            window.Owner = Application.Current.MainWindow;

            data.Name = classifier.Name;
            data.Field = classifier.Field;
            data.Pattern = classifier.Pattern;
            data.Mode = classifier.Mode;
            data.Type = classifier.Type;

            bool? dialogResult = window.ShowDialog();

            if (dialogResult != null && (bool)dialogResult)
            {
                classifier.Name = data.Name;
                classifier.Pattern = data.Pattern;
                classifier.Mode = data.Mode;
                classifier.Field = data.Field;
                classifier.Type = data.Type;
            }
        }
        protected void CheckOnlineClassification(IClassifier <T> classifier, String inputDoc, T expectedResult, Analyzer analyzer, String textFieldName, String classFieldName, Query query)
        {
            AtomicReader atomicReader = null;

            try
            {
                PopulateSampleIndex(analyzer);
                atomicReader = SlowCompositeReaderWrapper.Wrap(indexWriter.Reader);
                classifier.Train(atomicReader, textFieldName, classFieldName, analyzer, query);
                ClassificationResult <T> classificationResult = classifier.AssignClass(inputDoc);
                NotNull(classificationResult.AssignedClass);
                AreEqual(expectedResult, classificationResult.AssignedClass, "got an assigned class of " + classificationResult.AssignedClass);
                IsTrue(classificationResult.Score > 0, "got a not positive score " + classificationResult.Score);
                UpdateSampleIndex(analyzer);
                ClassificationResult <T> secondClassificationResult = classifier.AssignClass(inputDoc);
                Equals(classificationResult.AssignedClass, secondClassificationResult.AssignedClass);
                Equals(classificationResult.Score, secondClassificationResult.Score);
            }
            finally
            {
                if (atomicReader != null)
                {
                    atomicReader.Dispose();
                }
            }
        }
 public StringTemplateBraceMatchingTagger(ITextView textView, ITextBuffer sourceBuffer, IClassifier aggregator)
     : base(textView, sourceBuffer, aggregator, _matchingCharacters)
 {
     Contract.Requires<ArgumentNullException>(textView != null, "textView");
     Contract.Requires<ArgumentNullException>(sourceBuffer != null, "sourceBuffer");
     Contract.Requires<ArgumentNullException>(aggregator != null, "aggregator");
 }
 public FeaturesInDecisionOut(IReader reader, IClassifier classifier)
 {
     DataReader = reader;
     DataReader.OnReadFinished = OnReadFinished;
     ExecutionMethod           = DataReader.Start;
     Classifier = classifier;
 }
Exemple #30
0
 public void PutClassifier(string label, IClassifier classifier)
 {
     if (!this._modelMapping.Keys.Contains(label))
     {
         this._modelMapping.Add(label, classifier);
     }
 }
        public AsmDocMouseHandler(
            IWpfTextView view,
            IOleCommandTarget commandTarget,
            IClassifier aggregator,
            ITextStructureNavigator navigator,
            CtrlKeyState state,
            AsmDudeTools asmDudeTools)
        {
            //AsmDudeToolsStatic.Output_INFO("AsmDocMouseHandler:constructor: file=" + AsmDudeToolsStatic.GetFileName(view.TextBuffer));
            this._view          = view;
            this._commandTarget = commandTarget;
            this._state         = state;
            this._aggregator    = aggregator;
            this._navigator     = navigator;
            this._asmDudeTools  = asmDudeTools;

            this._state.CtrlKeyStateChanged += (sender, args) =>
            {
                if (Settings.Default.AsmDoc_On)
                {
                    if (this._state.Enabled)
                    {
                        this.TryHighlightItemUnderMouse(this.RelativeToView(Mouse.PrimaryDevice.GetPosition(this._view.VisualElement)));
                    }
                    else
                    {
                        this.Set_Highlight_Span(null);
                    }
                }
            };

            // Some other points to clear the highlight span:
            this._view.LostAggregateFocus       += (sender, args) => this.Set_Highlight_Span(null);
            this._view.VisualElement.MouseLeave += (sender, args) => this.Set_Highlight_Span(null);
        }
Exemple #32
0
        public GoToDefMouseHandler(IWpfTextView view, IOleCommandTarget commandTarget, IClassifier aggregator,
                                   ITextStructureNavigator navigator, CtrlKeyState state)
        {
            _view          = view;
            _commandTarget = commandTarget;
            _state         = state;
            _aggregator    = aggregator;
            _navigator     = navigator;

            _state.CtrlKeyStateChanged += (sender, args) =>
            {
                if (_state.Enabled)
                {
                    this.TryHighlightItemUnderMouse(RelativeToView(Mouse.PrimaryDevice.GetPosition(_view.VisualElement)));
                }
                else
                {
                    this.SetHighlightSpan(null);
                }
            };

            // Some other points to clear the highlight span:

            _view.LostAggregateFocus       += (sender, args) => this.SetHighlightSpan(null);
            _view.VisualElement.MouseLeave += (sender, args) => this.SetHighlightSpan(null);
        }
Exemple #33
0
        public static void IrisClassifierTest(IClassifier classifier)
        {
            var data = TestDataset.Iris();

            data.Shuffle(new Random(1));
            var split         = (int)(data.Count * 0.8);
            var trainingSet   = data.Take(split).ToList();
            var validationSet = data.Skip(split)
                                .Select(x => new Tuple <double[], double>(x.Take(x.Length - 1).ToArray(), x.Last()))
                                .ToList();

            classifier.Train(trainingSet);

            var correctlyPredicted   = 0;
            var incorrectlyPredicted = 0;

            validationSet.ForEach(x =>
            {
                if (Math.Abs(classifier.Predict(x.Item1) - x.Item2) < 0.00001)
                {
                    correctlyPredicted++;
                }
                else
                {
                    incorrectlyPredicted++;
                }
            });

            var percentCorrect = ((correctlyPredicted + 0.0) / (correctlyPredicted + incorrectlyPredicted));

            percentCorrect.ShouldBeGreaterThanOrEqualTo(0.90);
        }
Exemple #34
0
#pragma warning restore 649, 169

        #region IWpfTextViewCreationListener

        /// <summary>
        /// Called when a text view having matching roles is created over a text data model having a matching content type.
        /// Instantiates a CodeCoverageAdornment manager when the textView is created.
        /// </summary>
        /// <param name="textView">The <see cref="IWpfTextView"/> upon which the adornment should be placed</param>
        public void TextViewCreated(IWpfTextView textView)
        {
            IClassifier classifier = _classifierService.GetClassifier(textView.TextBuffer);

            // The adornment will listen to any event that changes the layout (text changes, scrolling, etc)
            new TestsAdornment(textView, classifier, _classificationRegistry, _formatMap);
        }
Exemple #35
0
        private double CalculatePooledAUC(IClassifier classifier, Dataset dataset)
        {
            double final = 0;

            int labelSize = dataset.Metadata.Target.Values.Length;

            double[][] values = new double[labelSize][];
            int        index  = 0;

            for (int exampleIndex = 0; exampleIndex < dataset.Size; exampleIndex++)
            {
                values[index] = new double[2];

                Example    example     = dataset[exampleIndex];
                bool[]     actualFlags = example.LabelFlags;
                Prediction prediction  = classifier.Classify(example);


                for (int classIndex = 1; classIndex < labelSize; classIndex++)
                {
                    values[index][0] = prediction.Probabilities[classIndex];
                    values[index][1] = actualFlags[classIndex] ? 1 : 0;
                    index++;
                }
            }

            return(final);
        }
Exemple #36
0
        private double CalculateAverageAUC(IClassifier classifier, Dataset dataset)
        {
            double final = 0;

            int labelSize = dataset.Metadata.Target.Values.Length;

            double[][] values = new double[dataset.Size][];
            double     area   = 0;
            double     weight = 1.0 / (double)labelSize - 1;

            for (int classIndex = 0; classIndex < labelSize; classIndex++)
            {
                int index = 0;


                for (int exampleIndex = 0; exampleIndex < dataset.Size; exampleIndex++)
                {
                    values[index] = new double[2];

                    Example example = dataset[exampleIndex];

                    bool[]     actualFlags = example.LabelFlags;
                    Prediction prediction  = classifier.Classify(example);

                    values[index][0] = prediction.Probabilities[classIndex];
                    values[index][1] = actualFlags[classIndex] ? 1 : 0;
                    index++;
                }

                Curve curve = this._curveBuilder.CreateCurve(values);
                area += weight * curve.CalculateArea();
            }

            return(final);
        }
 public EditorConfigCompletionSource(ITextBuffer buffer, IClassifierAggregatorService classifier, ITextStructureNavigatorSelectorService navigator, ImageSource glyph)
 {
     _buffer = buffer;
     _classifier = classifier.GetClassifier(buffer);
     _navigator = navigator;
     _glyph = glyph;
 }
 public static double Correct(IEnumerable<Observation> validationSet,
     IClassifier classifier)
 {
     return validationSet
             .Select(obs => Score(obs, classifier))
             .Average();
 }
Exemple #39
0
		internal Linguist(IClassifier aggregator, IClassificationTypeRegistryService registry)
		{
			InstallFiles.Install();
			Styles.Init();
			Languages.Init(registry);

			m_aggregator = aggregator;
		}
 public static ClassifierBuildResult Create(IClassifier classifier, double error)
 {
     return new ClassifierBuildResult
     {
         Classifier = classifier,
         Error = error
     };
 }
 public TextViewDocument(ITextDocument document, ICaret caret, IClassifier classifier, IClassificationStyler classificationStyler)
 {
     _document = document;
     _classifier = classifier;
     _classificationStyler = classificationStyler;
     Buffer.Changed += OnBufferChange;
     Caret = caret;
 }
        private static int PredictBagLabel(IClassifier<SparseBag> classifier, BagTestData[] bags, SparseBag bagToTest)
        {
            var sparseBags = BagTestData.ToSparseBags(bags);

            classifier.Train(sparseBags);

            return classifier.PredictWinner(bagToTest);
        }
 public AntlrIntellisenseCommandFilter(IVsTextView textViewAdapter, AntlrIntellisenseController controller)
     : base(textViewAdapter, controller)
 {
     var textView = Controller.Provider.EditorAdaptersFactoryService.GetWpfTextView(textViewAdapter);
     var textBuffer = textView.TextBuffer;
     _classifier = Controller.Provider.ClassifierAggregatorService.GetClassifier(textView.TextBuffer);
     _textStructureNavigator = Controller.Provider.TextStructureNavigatorSelectorService.GetTextStructureNavigator(textBuffer);
 }
		public TextViewDocument(ITextDocument document, ICaret caret, IClassifier classifier, IClassificationStyler classificationStyler)
		{
			_document = document;
			_classifier = classifier;
			_classificationStyler = classificationStyler;
			_classificationStyler.Changed += (Sender, Args) => RemoveCachedLinesFrom(0);
			Buffer.Changed += OnBufferChange;
			Caret = caret;
		}
 internal GherkinSyntaxHighlighter(
     IClassifier classifier,
     IClassificationTypeRegistryService classificationTypeRegistryService,
     ILanguagePatternMatcher languagePatternMatcher)
 {
     this.classifier = classifier;
     this.classificationTypeRegistryService = classificationTypeRegistryService;
     this.languagePatternMatcher = languagePatternMatcher;
 }
        GoToDefinitionAdorner(IWpfTextView textTextView, IComponentModel componentModel) {
            _textView = textTextView;

            _classicationFormatMapService = componentModel.GetService<IClassificationFormatMapService>();
            _classifier                   = componentModel.GetService<IViewClassifierAggregatorService>().GetClassifier(textTextView);            
            _adornmentLayer               = textTextView.GetAdornmentLayer(AdornerName);

            _textView.Closed += OnTextViewClosed;
        }
 /// <summary>
 /// Attaches events for invoking Statement completion 
 /// </summary>
 public IntellisenseController(IntellisenseControllerProvider provider, ITextView textView) {
     _textView = textView;
     _provider = provider;
     _classifier = _provider._classifierAgg.GetClassifier(_textView.TextBuffer);
     _editOps = provider._EditOperationsFactory.GetEditorOperations(textView);
     _incSearch = provider._IncrementalSearch.GetIncrementalSearch(textView);
     _textView.MouseHover += TextViewMouseHover;
     textView.Properties.AddProperty(typeof(IntellisenseController), this);  // added so our key processors can get back to us
 }
 public PkgdefCompletionSource(ITextBuffer buffer, IClassifierAggregatorService classifier, ITextStructureNavigatorSelectorService navigator, IGlyphService glyphService)
 {
     _buffer = buffer;
     _classifier = classifier.GetClassifier(buffer);
     _navigator = navigator;
     _glyphService = glyphService;
     _defaultGlyph = glyphService.GetGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPublic);
     _snippetGlyph = glyphService.GetGlyph(StandardGlyphGroup.GlyphCSharpExpansion, StandardGlyphItem.GlyphItemPublic);
 }
 public CmdCompletionSource(ITextBuffer buffer, IClassifierAggregatorService classifier, IGlyphService glyphService, ITextStructureNavigator textStructureNavigator)
 {
     _buffer = buffer;
     _classifier = classifier.GetClassifier(buffer);
     _keywordGlyph = glyphService.GetGlyph(StandardGlyphGroup.GlyphGroupVariable, StandardGlyphItem.GlyphItemPublic);
     _environmentGlyph = glyphService.GetGlyph(StandardGlyphGroup.GlyphAssembly, StandardGlyphItem.GlyphItemPublic);
     _labelGlyph = glyphService.GetGlyph(StandardGlyphGroup.GlyphArrow, StandardGlyphItem.GlyphItemPublic);
     _textStructureNavigator = textStructureNavigator;
 }
 public VsctCompletionSource(ITextBuffer buffer, IClassifierAggregatorService classifier, ITextStructureNavigatorSelectorService navigator, IGlyphService glyphService)
 {
     _buffer = buffer;
     _classifier = classifier.GetClassifier(buffer);
     _navigator = navigator;
     _glyphService = glyphService;
     _defaultGlyph = glyphService.GetGlyph(StandardGlyphGroup.GlyphGroupField, StandardGlyphItem.GlyphItemPublic);
     _builtInGlyph = glyphService.GetGlyph(StandardGlyphGroup.GlyphGroupProperty, StandardGlyphItem.TotalGlyphItems);
     _imageService = ExtensibilityToolsPackage.GetGlobalService(typeof(SVsImageService)) as IVsImageService2;
 }
        public static bool IsClassifiedAsJavaScript(IClassifier classifier, SnapshotPoint startPoint)
        {
            if (startPoint == null) return false;

            var spans = classifier.GetClassificationSpans(new SnapshotSpan(startPoint, 1));
            var span = spans.FirstOrDefault();
            if (span == null) return false;

            return span.ClassificationType.Classification.StartsWith("Script ", StringComparison.OrdinalIgnoreCase);
        }
        public static ClassifierBuildResult Create(IClassifier classifier, TextDocument[] trainingSet, string targetTag)
        {
            var errorsCount = trainingSet.Count(x => classifier.IsClassifierWrong(x, targetTag));
            var error = errorsCount * 1.0 / trainingSet.Length;

            return new ClassifierBuildResult
            {
                Classifier = classifier,
                Error = error
            };
        }
 public ScoreModel(TrainModel trainedModel, int K = 3)
 {
     if (!trainedModel.Trained)
         throw new Exception("TrainModel must be trained first");
     this.trainedModel = trainedModel;
     ConfussionMatrix = new int[trainedModel.NumberofClasses, trainedModel.NumberofClasses];
     if (trainedModel.cType == ClassifierType.Bayesian)
         classifier = new BayesianClassifier(trainedModel);
     else if (trainedModel.cType == ClassifierType.KNearestNeighbour)
         classifier = new KNearestNeighbour(trainedModel, K);
 }
Exemple #54
0
        public AutoWrapper(SVsServiceProvider serviceProvider, IClassifierAggregatorService aggregatorService, IWpfTextView textView)
        {
            var service = serviceProvider.GetService<CommentatorService>();
            this.options = service.GetOptions();

            this.view = textView;
            this.classifier = aggregatorService.GetClassifier(this.view.TextBuffer);

            this.view.TextBuffer.Changed += this.TextBuffer_Changed;
            this.view.Closed += this.View_Closed;
        }
        public SnapshotParser(ITextSnapshot snapshot, IClassifier classifier)
        {
            Snapshot = snapshot;
            Classifier = classifier;
            ClassificationSpans = Classifier.GetClassificationSpans(new SnapshotSpan(Snapshot, 0, snapshot.Length));
            foreach (ClassificationSpan s in ClassificationSpans)
                SpanIndex.Add(s.Span.Start.Position, s);

            CurrentPoint = Snapshot.GetLineFromLineNumber(0).Start;
            if (SpanIndex.ContainsKey(0))
                CurrentSpan = SpanIndex[0];
        }
        internal static bool FindMatchingBrace(ILanguageBlockManager lbm, IClassifier classifier, SnapshotPoint startPoint, bool findClosing, char open, char close, int maxLines, ref bool maxLinesReached, out SnapshotSpan pairSpan)
        {
            // Get script block we're working in
            // lbm will be null if this is not in an HTML file
            var scriptBlock = lbm != null
                ? JScriptEditorUtil.GetJavaScriptBlockSpans(lbm)
                    .Single(b => b.Start <= startPoint.Position && b.End >= startPoint.Position)
                : new BlockSpan(0, startPoint.Snapshot.TextBuffer.CurrentSnapshot.Length, true);

            return findClosing
                ? FindMatchingCloseChar(scriptBlock, classifier, startPoint, open, close, maxLines, ref maxLinesReached, out pairSpan)
                : FindMatchingOpenChar(scriptBlock, classifier, startPoint, close, open, maxLines, ref maxLinesReached, out pairSpan);
        }
        public static bool IsClassifiedAs(IClassifier classifier, SnapshotPoint startPoint, params string[] names)
        {
            if (startPoint == null) return false;

            var spans = classifier.GetClassificationSpans(new SnapshotSpan(startPoint, 1));
            var span = spans.FirstOrDefault();
            if (span == null) return false;

            if (names.Contains(span.ClassificationType.Classification))
                return true;

            return false;
        }
 public void AddClassifier(IProjectionBuffer projectionBuffer, ITextBuffer textBuffer, IClassifier classifer) {
     var elisionInfo = new ElisionInfo(textBuffer, classifer, _bufGraphFact.CreateBufferGraph(projectionBuffer));
     _elisionBuffers.Add(elisionInfo);
     
     classifer.ClassificationChanged += (sender, args) => {
         var classChanged = ClassificationChanged;
         if (classChanged != null) {
             foreach (var span in elisionInfo.BufferGraph.MapDownToBuffer(args.ChangeSpan, SpanTrackingMode.EdgeExclusive, projectionBuffer)) {
                 classChanged(this, new ClassificationChangedEventArgs(span));
             }
         }
     };
 }
Exemple #59
0
        public static void HandleReturn(IWpfTextView view, IClassifier classifier)
        {
            int curLine = view.Caret.Position.BufferPosition.GetContainingLine().LineNumber;
            int startLine = curLine;

            // skip blank lines as far as calculating indentation goes...
            bool hasNonWhiteSpace = false;
            string lineText;
            ITextSnapshotLine line;
            do {
                line = view.TextSnapshot.GetLineFromLineNumber(curLine);
                if (curLine == startLine) {
                    // if we're in the middle of a line only consider text to the left for white space detection
                    lineText = line.GetText().Substring(0, view.Caret.Position.BufferPosition.Position - view.Caret.Position.BufferPosition.GetContainingLine().Start);
                } else {
                    lineText = line.GetText();
                }
                foreach (char c in lineText) {
                    if (!Char.IsWhiteSpace(c)) {
                        hasNonWhiteSpace = true;
                        break;
                    }
                }
                if (!hasNonWhiteSpace) {
                    curLine--;
                }
            } while (!hasNonWhiteSpace && curLine > 0);

            int indentation = CalculateIndentation(lineText, line, view, classifier);
            if (curLine != startLine) {
                // enter on a blank line, don't re-indent instead just maintain the current indentation
                indentation = Math.Min(indentation, (view.Caret.Position.BufferPosition.Position - view.Caret.ContainingTextViewLine.Start.Position));
            }
            using (var edit = view.TextBuffer.CreateEdit()) {
                if (view.Selection.IsActive) {
                    foreach (var span in view.Selection.SelectedSpans) {
                        edit.Delete(span);
                    }
                }
                edit.Insert(view.Caret.Position.BufferPosition.Position, view.Options.GetNewLineCharacter());
                if (view.Options.IsConvertTabsToSpacesEnabled()) {
                    edit.Insert(view.Caret.Position.BufferPosition.Position, new String(' ', indentation));
                } else {
                    edit.Insert(view.Caret.Position.BufferPosition.Position, new String('\t', indentation / view.Options.GetTabSize()));
                }
                edit.Apply();
            }

            view.Caret.EnsureVisible();
        }
		public VisualsFactory(ITextView textView, IClassifier classifier, Double maxLineWidth)
		{
			_textView = textView;
			_classifier = classifier;
			_maxLineWidth = maxLineWidth;

			/* 
			 * DocumentType("text.xml") = XmlWordClassificationLookup
			 * DocumentType("C#"), DocumentType("VB"), DocumentType("text") = ClassificationFormatMap
			 * Else = DefaultClassificationFormatMap
			 */

			_classificationFormatMap = Connector.Assets.ClassificationFormatMapSelector.Invoke(_textView.TextBuffer.DocumentType);
			_paragraphProperties = new TextFormattingParagraphProperties();
		}