Esempio n. 1
0
        public void CompareReviews()
        {
            const string evidenceRepo = @"C:\Dragon\Evidence\";
            var positiveReviews = new Evidence("Positive", evidenceRepo, loadEvidence: true);
            var negativeReviews = new Evidence("Negative", evidenceRepo, loadEvidence: true);
            var classifier = new Classifier(positiveReviews, negativeReviews);
            var reviewUrls = new List<string>();

            using (var file = new StreamReader(@"C:\Dragon\RawData\ReviewUrls.txt"))
            {
                string line;
                while ((line = file.ReadLine()) != null)
                {
                    if (string.IsNullOrWhiteSpace(line.Trim())) continue;
                    reviewUrls.Add(line.Trim());
                }
            }

            var boilerPipeContents = Helper.GetUrlContentsViaBoilerPipe(reviewUrls);
            var readabilityContents = Helper.GetUrlContentsViaReadability(reviewUrls);
            var uClassifyResults = Helper.GetUClassifyReviewScores(reviewUrls);
            var dragonResultsViaReadability = new Dictionary<string, double>();
            var dragonResultsViaBoilerPipe = new Dictionary<string, double>();

            foreach (var content in boilerPipeContents)
            {
                var scores = classifier.Classify(content.Value, DragonHelper.DragonHelper.TokenCharMappings, DragonHelper.DragonHelper.ExcludeList);
                var positive = scores["Positive"];
                dragonResultsViaBoilerPipe.Add(content.Key, positive);
            }

            foreach (var content in readabilityContents)
            {
                var scores = classifier.Classify(content.Value, DragonHelper.DragonHelper.TokenCharMappings, DragonHelper.DragonHelper.ExcludeList);
                var positive = scores["Positive"];
                dragonResultsViaReadability.Add(content.Key, positive);
            }

            Console.Out.WriteLine("Url,Dragon_Readability,Dragon_BoilerPipe,uClassify");
            foreach (var url in reviewUrls)
            {
                var output = string.Format("{0}, {1}, {2}, {3}", url, dragonResultsViaReadability[url], dragonResultsViaBoilerPipe[url], uClassifyResults[url]);
                Console.Out.WriteLine(output);
            }

            //foreach (var dragonResult in dragonResultsViaReadability)
            //{
            //    var output = string.Format("{0}, {1}, {2}", dragonResult.Key, dragonResult.Value, uClassifyResults[dragonResult.Key]);
            //    Console.Out.WriteLine(output);
            //}
        }
        private static string[] GetDetails(Classifier classifier, List <FeatureVector> vectors, TextIdMapper classToClassId, TextIdMapper featureToFeatureId)
        {
            var detailsAsText = new string[vectors.Count];

            for (int v_i = 0; v_i < vectors.Count; v_i++)
            {
                double[] details;
                //int sysClass =
                classifier.Classify(vectors[v_i], out details);
                Debug.Assert(details.Length == 1);
                detailsAsText[v_i] = string.Format($"{details[0]:0.00000}");
            }
            return(detailsAsText);
        }
Esempio n. 3
0
        //[TestMethod]
        public void ExtractContentsAndClassify()
        {
            const string evidenceRepo     = @"C:\Dragon\Evidence\";
            var          positiveReviews  = new Evidence("Positive", evidenceRepo, loadEvidence: true);
            var          negativeReviews  = new Evidence("Negative", evidenceRepo, loadEvidence: true);
            var          classifier       = new Classifier(positiveReviews, negativeReviews);
            const string reviewUrl        = "http://www.theverge.com/2012/9/30/3433110/amazon-kindle-paperwhite-review";
            var          extractedContent = Helper.GetUrlContentsViaReadability(reviewUrl);
            var          scores           = classifier.Classify(extractedContent, DragonHelper.DragonHelper.TokenCharMappings, DragonHelper.DragonHelper.ExcludeList);
            var          positiveFromUrl  = scores["Positive"];

            Assert.IsNotNull(positiveFromUrl);

            string testData;

            using (var sr = new StreamReader(@"C:\Users\Amrish\Desktop\Review.txt", Encoding.UTF7))
            {
                testData = sr.ReadToEnd();
            }
            scores = classifier.Classify(testData, DragonHelper.DragonHelper.TokenCharMappings, DragonHelper.DragonHelper.ExcludeList);
            var positiveFromContents = scores["Positive"];

            Assert.IsNotNull(positiveFromContents);
        }
Esempio n. 4
0
    public void ClassifierSupportsWhitespace()
    {
        var text     = "       ";
        var tree     = SyntaxTree.Parse(text);
        var fullSpan = tree.Root.FullSpan;

        Assert.Collection(
            Classifier.Classify(tree, fullSpan),
            span =>
        {
            Assert.Equal(Classification.Text, span.Classification);
            Assert.Equal(TextSpan.FromBounds(0, 7), span.Span);
            Assert.Equal("       ", tree.File.ToString(span.Span));
        }
            );
    }
Esempio n. 5
0
        public void ClassificationTest_Classify_Quantity()
        {
            const Classifier.ColumnType testColumn = Classifier.ColumnType.Quantity;
            Classifier clf = Classifier.GetInstance();

            Assert.IsNotNull(clf);

            LoadFrequencyValues(clf);

            var result = clf.Classify(new List <string>()
            {
                "1", "2", "3", "4", "5", "6"
            });

            Assert.AreEqual(testColumn, result.Min().columnType);
            Assert.IsTrue(result.Count > 1);
        }
Esempio n. 6
0
        public void ClassificationTest_Classify_MPN()
        {
            const Classifier.ColumnType testColumn = Classifier.ColumnType.PartNumber;
            Classifier clf = Classifier.GetInstance();

            Assert.IsNotNull(clf);

            LoadFrequencyValues(clf);

            var result = clf.Classify(new List <string>()
            {
                "C1608X7R1E105K080AB", "MC0805N100J201CT", "GRM2165C2A471JA01D", "VS-15MQ040NPBF", "EMVA250ADA101MF80G", "251R15S221JV4E"
            });

            Assert.AreEqual(testColumn, result.Min().columnType);
            Assert.IsTrue(result.Count > 1);
        }
        public void Train()
        {
            // Example binary data
            double[][] inputs = { new double[] { -1, -1 }, new double[] { -1, 1 }, new double[] { 1, -1 }, new double[] { 1, 1 } };

            int[] xor = // xor labels
            {
                -1, 1, 1, -1
            };
            instance.Train(xor, inputs, CancellationToken.None);
            var result = instance.Classify(inputs);

            Assert.AreEqual(4, result.Length);
            instance.Save(fileName);
            Assert.IsTrue(File.Exists(fileName));
            instance.Load(fileName);
        }
Esempio n. 8
0
        public void ClassifyHappyPath()
        {
            Logger.Debug("Hello");

            const string evidenceRepo = @"C:\Dragon\Evidence\";
            var positiveReviews = new Evidence("Positive", evidenceRepo, loadEvidence: true);
            var negativeReviews = new Evidence("Negative", evidenceRepo, loadEvidence: true);
            string testData;
            using (var sr = new StreamReader(@"C:\Users\Amrish\Desktop\Review.txt", Encoding.UTF7))
            {
                testData = sr.ReadToEnd();
            }

            var classifier = new Classifier(positiveReviews, negativeReviews);
            var scores = classifier.Classify(testData, DragonHelper.DragonHelper.TokenCharMappings, DragonHelper.DragonHelper.ExcludeList);
            var positive = scores["Positive"];
            Assert.IsNotNull(positive);
        }
        public JsonResult classify_extra_stuff(string address, int month)
        {
            Apartment apartment = _context.Apartment.Include(m => m.malfunctions).FirstOrDefault(x => x.Address.Contains(address));

            InitiallizeTrainData(month);
            Classifier classifier = new Classifier();

            classifier.TrainClassifier(table);
            var name = classifier.Classify(new double[] { apartment.RoomsNumber, month, apartment.Longitude + apartment.Latitude });

            string message;

            message = name.ToLower() == "above" ?
                      "Consider putting more stuff at this area and this month, there should be a lot of malfunctions" :
                      "Your Stuff is quiet enough! :) No need to get extra.";

            return(Json($"{{\"message\":\"{message}\"}}"));
        }
 private void button1_Click(object sender, EventArgs e)
 {
     if ((textBox1.Text.Length > 0) && (textBox2.Text.Length > 0) && (textBox3.Text.Length > 0) && (textBox4.Text.Length > 0))
     {
         double t1, t2, t3, t4;
         using (SqlCommand cmd = new SqlCommand("truncate table temp_z", cn))
         {
             cn.Open();
             cmd.ExecuteNonQuery();
             cn.Close();
         }
         t1 = Convert.ToDouble(textBox1.Text);
         t2 = Convert.ToDouble(textBox2.Text);
         t3 = Convert.ToDouble(textBox3.Text);
         t4 = Convert.ToDouble(textBox4.Text);
         DataTable table = new DataTable();
         using (SqlCommand cmd = new SqlCommand("select *  from dataset", cn))
         {
             using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
             {
                 adp.Fill(table);
             }
         }
         Classifier classifier = new Classifier();
         classifier.TrainClassifier(table);
         string val = classifier.Classify(new double[] { t1, t2, t3, t4 });
         if (val == "Good")
         {
             label2.Text = "Good";
         }
         else if (val == "Fair")
         {
             label2.Text = "Fair";
         }
         else if (val == "Poor")
         {
             label2.Text = "Poor";
         }
     }
     else
     {
         MessageBox.Show("ENTER values!");
     }
 }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override IModel Convert()
        {
            var mapping    = GetOrCreateMappings <MappingIfcBuildingToFacility>();
            var classifier = new Classifier(this);
            var buildings  = SourceRepository.Instances.OfType <IIfcBuilding>().ToList();
            var facilities = new List <CobieFacility>(buildings.Count);

            foreach (var building in buildings)
            {
                var facility = TargetRepository.Instances.New <CobieFacility>();
                facility = mapping.AddMapping(building, facility);
                if (_classify)
                {
                    classifier.Classify(facility);
                }
                facilities.Add(facility);
            }
            return(TargetRepository);
        }
Esempio n. 12
0
        public void ClassifyHappyPath()
        {
            Logger.Debug("Hello");

            const string evidenceRepo    = @"C:\Dragon\Evidence\";
            var          positiveReviews = new Evidence("Positive", evidenceRepo, loadEvidence: true);
            var          negativeReviews = new Evidence("Negative", evidenceRepo, loadEvidence: true);
            string       testData;

            using (var sr = new StreamReader(@"C:\Users\Amrish\Desktop\Review.txt", Encoding.UTF7))
            {
                testData = sr.ReadToEnd();
            }

            var classifier = new Classifier(positiveReviews, negativeReviews);
            var scores     = classifier.Classify(testData, DragonHelper.DragonHelper.TokenCharMappings, DragonHelper.DragonHelper.ExcludeList);
            var positive   = scores["Positive"];

            Assert.IsNotNull(positive);
        }
Esempio n. 13
0
        /// <summary>
        /// Performs this job.
        /// </summary>
        /// <returns>The validation results.</returns>
        /// <remarks></remarks>
        public ValidationJobResult Perform()
        {
            Validator.TrainingFunction = delegate(List <Instance> train)
            {
                Classifier.Train(train);
            };

            Validator.ClassifyFunction = delegate(Instance test)
            {
                return(Classifier.Classify(test));
            };

            Stopwatch timer = new Stopwatch();

            timer.Start();
            Validator.Compute();
            timer.Stop();

            return(new ValidationJobResult(this, Validator.ConfusionMatrix, timer.Elapsed));
        }
        public static async Task <int> WriteResultsAsync(TextWriter writer, MarkdownLinksVerifierConfiguration config, string?rootDirectory = null)
        {
            if (writer is null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            if (config is null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            var returnCode = 0;

            rootDirectory ??= Directory.GetCurrentDirectory();
            await writer.WriteLineAsync($"Starting Markdown Links Verifier in '{rootDirectory}'.");

            foreach (string file in Directory.EnumerateFiles(rootDirectory, "*.md", SearchOption.AllDirectories))
            {
                string?directory = Path.GetDirectoryName(file);
                if (directory is null)
                {
                    throw new InvalidOperationException($"Cannot get directory for '{file}'.");
                }

                MarkdownDocument document = Markdown.Parse(await File.ReadAllTextAsync(file));
                foreach (LinkInline link in document.Descendants <LinkInline>())
                {
                    LinkClassification classification = Classifier.Classify(link.Url);
                    ILinkValidator     validator      = LinkValidatorCreator.Create(classification, directory);
                    if (!config.IsLinkExcluded(link.Url) && !validator.IsValid(link.Url, file))
                    {
                        await writer.WriteLineAsync($"::error::In file '{file}': Invalid link: '{link.Url}' relative to '{directory}'.");

                        returnCode = 1;
                    }
                }
            }

            return(returnCode);
        }
Esempio n. 15
0
        public static string[] GetDistributionDetails(Classifier classifier, List <FeatureVector> vectors, TextIdMapper classToClassId)
        {
            string[] details = new string[vectors.Count];
            for (int v_i = 0; v_i < vectors.Count; v_i++)
            {
                double[] distribution;
                //int sysClass =
                classifier.Classify(vectors[v_i], out distribution);
                var distribution_sorted = SearchHelper.GetMaxNItems(distribution.Length, distribution);

                // Output the results:
                StringBuilder sb = new StringBuilder();
                foreach (var classId in distribution_sorted)
                {
                    // Output the results:
                    sb.AppendFormat("\t{0}\t{1:0.00000}", classToClassId[classId], distribution[classId]);
                }
                details[v_i] = sb.ToString();
            }
            return(details);
        }
Esempio n. 16
0
    public void ClassifierSupportsABlock()
    {
        var text = AnnotatedText.Parse(
            @"
                        {
                        }"
            );

        var tree     = SyntaxTree.Parse(text.Text);
        var fullSpan = tree.Root.FullSpan;

        var newLineWidth = Environment.NewLine.Length;

        Assert.Collection(
            Classifier.Classify(tree, fullSpan),
            span =>
        {
            Assert.Equal(Classification.Text, span.Classification);
            Assert.Equal(TextSpan.FromBounds(0, 1), span.Span);
            Assert.Equal("{", tree.File.ToString(span.Span));
        },
            span =>
        {
            Assert.Equal(Classification.Text, span.Classification);
            Assert.Equal(TextSpan.FromBounds(1, 1 + newLineWidth), span.Span);
            Assert.Equal(Environment.NewLine, tree.File.ToString(span.Span));
        },
            span =>
        {
            // eof token
            Assert.Equal(Classification.Text, span.Classification);
            Assert.Equal(TextSpan.FromBounds(1 + newLineWidth, 2 + newLineWidth), span.Span);
            Assert.Equal("}", tree.File.ToString(span.Span));
        }
            );
    }
        private void Classify()
        {
            if (!IsStringCorrect(ObjViewModel.CarType, ObjViewModel.Color, ObjViewModel.Origin))
            {
                MessageBox.Show(Resources.ErrorMessage);
            }
            else
            {
                if (_classifer != null)
                {
                    var results = _classifer.Classify(new List <string>()
                    {
                        ObjViewModel.CarType, ObjViewModel.Color, ObjViewModel.Origin
                    });
                    var bestResult = results.OrderByDescending(x => x.Value).FirstOrDefault();

                    var strBuilder = new StringBuilder();
                    strBuilder.AppendLine(Resources.CategoryQuestion);
                    strBuilder.AppendLine(string.Format(Resources.ResultForma, bestResult.Key, bestResult.Value));

                    Result = strBuilder.ToString();
                }
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Returns a customized string explaining the state of a single IEQ parameter.
        /// </summary>
        /// <param name="data">Value (1-100) for given IEQ factor</param>
        /// <param name="type">The type of IEQ factor</param>
        /// <returns>Customized string explaining state of IEQ paramter</returns>
        private string GetMessage(double data, string type)
        {
            string returnString = ""; //String returned

            //Use the classifier to determine the state of the given IEQ factor
            int classification = Classifier.Classify(data, Constants.SCORE_RANGES);

            //Constructs the returnString based on the classification
            switch (classification)
            {
            case 1:
                returnString = AppResources.terrible + " " + type + "!";
                break;

            case 2:
                returnString = AppResources.bad + " " + type + "!";
                break;

            case 3:
                returnString = AppResources.acceptable + " " + type + "!";
                break;

            case 4:
                returnString = AppResources.good + " " + type + "!";
                break;

            case 5:
                returnString = AppResources.perfect + " " + type + "!";
                break;

            default:
                break;
            }

            return(returnString);
        }
Esempio n. 19
0
 static int TestTrainer(Classifier<Sample> c, IEnumerable<Sample> pointsPos, IEnumerable<Sample> pointsNeg)
 {
     //Console.WriteLine(errors / 40f + "% error rate.");
     //Console.WriteLine();
     return pointsPos.Count(s => c.Classify(s) <= 0) + pointsNeg.Count(s => c.Classify(s) >= 0);
 }
Esempio n. 20
0
        //[TestMethod]
        public void ExtractContentsAndClassify()
        {
            const string evidenceRepo = @"C:\Dragon\Evidence\";
            var positiveReviews = new Evidence("Positive", evidenceRepo, loadEvidence: true);
            var negativeReviews = new Evidence("Negative", evidenceRepo, loadEvidence: true);
            var classifier = new Classifier(positiveReviews, negativeReviews);
            const string reviewUrl = "http://www.theverge.com/2012/9/30/3433110/amazon-kindle-paperwhite-review";
            var extractedContent = Helper.GetUrlContentsViaReadability(reviewUrl);
            var scores = classifier.Classify(extractedContent, DragonHelper.DragonHelper.TokenCharMappings, DragonHelper.DragonHelper.ExcludeList);
            var positiveFromUrl = scores["Positive"];
            Assert.IsNotNull(positiveFromUrl);

            string testData;
            using (var sr = new StreamReader(@"C:\Users\Amrish\Desktop\Review.txt", Encoding.UTF7))
            {
                testData = sr.ReadToEnd();
            }
            scores = classifier.Classify(testData, DragonHelper.DragonHelper.TokenCharMappings, DragonHelper.DragonHelper.ExcludeList);
            var positiveFromContents = scores["Positive"];
            Assert.IsNotNull(positiveFromContents);
        }
        static void Main(string[] args)
        {
            //ExStart:ApplyingLicense

            /**
             *  Applying product license
             *  Please uncomment the statement if you do have license.
             */
            // const string licensePath = "../../../../GroupDocs.Classification.NET.Full.lic";
            // new License().SetLicense(licensePath);

            //ExEnd:ApplyingLicense

            Console.WriteLine("SentimentClassifier initialization is started.");

            sentimentClassifier = new SentimentClassifier();

            Console.WriteLine("SentimentClassifier was initialized.");

            var sentiments = new string[]
            {
                "Now that that is out of the way, this thing is a beast. It is fast and runs cool.",
                "When I used compressed air a cloud of dust bellowed out from the card (small scuffs and scratches)."
            };

            #region Classify raw text with Classify method of SentimentClassifier class.

            Console.WriteLine("\nClassify raw text with Classify method of SentimentClassifier class.");
            foreach (var sentiment in sentiments)
            {
                try
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    var result = sentimentClassifier.Classify(sentiment);
                    Console.WriteLine($"{sentiment}");
                    Console.WriteLine($"This sentiment is {result.BestClassName} with probability {result.BestClassProbability}. Elapsed: {sw.ElapsedMilliseconds}ms\n");
                }
                catch (ApiException e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            #endregion

            #region Classify raw text with PositiveProbability method of SentimentClassifier class.

            Console.WriteLine("\nClassify raw text with PositiveProbability method of SentimentClassifier class.");
            foreach (var sentiment in sentiments)
            {
                try
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    var positiveProbability = sentimentClassifier.PositiveProbability(sentiment);
                    Console.WriteLine($"{sentiment}");
                    Console.WriteLine($"This sentiment is {(positiveProbability > 0.5 ? "positive" : "negative")}. Elapsed: {sw.ElapsedMilliseconds}ms\n");
                }
                catch (ApiException e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            #endregion

            Console.WriteLine("Classifier initialization is started.");

            classifier = new Classifier();

            Console.WriteLine("Classifier was initialized.");

            ClassificationResponse response;

            #region Classify raw text with Classifier class.

            Console.WriteLine("\nClassify raw text with Classifier class.");

            // Simple IAB-2 text classification
            response = classifier.Classify("Medicine is an important part of our lifes");
            Console.WriteLine($"{response.BestClassName}, {response.BestClassProbability}");

            // Change taxonomy and best classes count
            response = classifier.Classify("Medicine is an important part of our lifes", 2, Taxonomy.Documents, PrecisionRecallBalance.Recall);
            Console.WriteLine($"{response.BestClassName}, {response.BestClassProbability}");

            // Classify sentiment
            response = classifier.Classify("This is a new must-have thing.", 2, Taxonomy.Sentiment);
            Console.WriteLine($"{response.BestClassName}, {response.BestClassProbability}");

            #endregion

            #region Classify documents with IAB-2 taxonomy.

            Console.WriteLine("\nClassify documents with IAB-2 taxonomy.");

            // Classify PDF document by path with IAB-2 taxonomy and return 2 best results
            ClassifyByFilePath("Annotations.pdf", Taxonomy.Iab2, 2);

            // Classify doc document by path with IAB-2 taxonomy and return the best result
            ClassifyByFilePath("four-pages.docx", Taxonomy.Iab2, 1);

            // Classify txt document by path with IAB-2 taxonomy and return 4 best results
            ClassifyByFilePath("Letter.txt", Taxonomy.Iab2, 4);

            #endregion

            #region Classify documents with Documents taxonomy.

            Console.WriteLine("\nClassify documents with Documents taxonomy.");

            // Classify PDF document from stream with Documents taxonomy and return 2 best results
            ClassifyStream("Annotations.pdf", Taxonomy.Documents, 2);

            // Classify doc document from stream with Documents taxonomy and return the best result
            ClassifyStream("four-pages.docx", Taxonomy.Documents, 1);

            // Classify txt document from stream with Documents taxonomy and return 3 best results
            ClassifyStream("Letter.txt", Taxonomy.Documents, 3);

            #endregion

            #region Classify documents with Sentiment taxonomy.

            Console.WriteLine("\nClassify documents with Sentiment taxonomy.");

            // Classify PDF document from stream with Sentiment taxonomy and return 2 best results
            ClassifyStream("Annotations.pdf", Taxonomy.Sentiment, 2);

            // Classify doc document from stream with Sentiment taxonomy and return the best result
            ClassifyStream("four-pages.docx", Taxonomy.Sentiment, 1);

            // Classify txt document from stream with Sentiment taxonomy and return 3 best results
            ClassifyStream("Letter.txt", Taxonomy.Sentiment, 2);

            #endregion

            #region Classify password-protected documents.

            Console.WriteLine("\nClassify password-protected documents.");

            try
            {
                response = classifier.Classify("password-protected.docx", dataFolderPath, password: "******");
                Console.WriteLine($"password-protected.docx: {response.BestClassName}, {response.BestClassProbability}");
            }
            catch (ApiException e)
            {
                Console.WriteLine(e.Message);
            }

            try
            {
                using (var fs = File.OpenRead(Path.Combine(dataFolderPath, "password-protected.docx")))
                {
                    response = classifier.Classify(fs, password: "******");
                    Console.WriteLine($"password-protected.docx: {response.BestClassName}, {response.BestClassProbability}");
                }
            }
            catch (ApiException e)
            {
                Console.WriteLine(e.Message);
            }

            #endregion

            #region Print taxonomy classes.

            Console.WriteLine("\nPrint taxonomy classes.");

            // Print IAB-2 taxonomy classes
            Console.WriteLine("IAB-2 taxonomy classes: ");
            Console.WriteLine(String.Join(" ", TaxonomyClasses.Iab2Classes));

            // Print Documents taxonomy classes
            Console.WriteLine("Documents taxonomy classes: ");
            Console.WriteLine(String.Join(" ", TaxonomyClasses.DocumentsClasses));

            // Print Sentiment taxonomy classes
            Console.WriteLine("Sentiment taxonomy classes: ");
            Console.WriteLine(String.Join(" ", TaxonomyClasses.SentimentClasses));

            #endregion

            Console.WriteLine("Done...");
            Console.ReadKey();
        }
Esempio n. 22
0
 public void ClassifyLocalLink_FileWithDirectory_MixedSlashes()
 {
     Assert.Equal(LinkClassification.Local, Classifier.Classify(@"path/to\myfile.txt"));
 }
Esempio n. 23
0
 public void ClassifyLocalLink_FileWithDirectory_Backslash()
 {
     Assert.Equal(LinkClassification.Local, Classifier.Classify(@"path\to\myfile.txt"));
 }
        protected override async void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            switch (requestCode)
            {
            case 100:

                if (resultCode == Result.Ok && data != null)
                {
                    Intent         mIntent = new Intent(this, typeof(ConfirmedCookingActivityViaSpeech));
                    IList <string> mResult = data.GetStringArrayListExtra(RecognizerIntent.ExtraResults);
                    System.Diagnostics.Debug.WriteLine(mResult[0]);
                    string           command     = mResult[0];
                    Classifier       mClassifier = new Classifier(command);
                    ClassifiedResult mResp       = mClassifier.Classify();
                    switch (mResp.Type)
                    {
                    case VoiceCommandType.BOOK_ME_CHEAPEST_CAB_FROM_X_TO_Y:
                        string recs = mResp.GetData("source");
                        if (!recs.Equals(""))
                        {
                            mSourceAddress = recs;
                        }
                        mDestinationAddress = mResp.GetData("destination");
                        error = "Booking Cheapest cab from " + mSourceAddress + "to" + mDestinationAddress;
                        speakUp();
                        mIntent.PutExtra("mSource", mSourceAddress);
                        mIntent.PutExtra("mDestination", mDestinationAddress);
                        StartActivity(mIntent);
                        break;

                    case VoiceCommandType.BOOK_TO_CUSTOM_LOCATION:
                        mDestinationAddress = mResp.GetData("location");
                        mIntent.PutExtra("mSource", mSourceAddress);
                        mIntent.PutExtra("mDestinationAddress", mDestinationAddress);
                        StartActivity(mIntent);
                        break;


                    case VoiceCommandType.BOOK_ME_A_CAB_FROM_X_TO_Y:
                    {
                        CabsAPI api         = new CabsAPI();
                        string  source      = mResp.GetData("source");
                        string  destination = mResp.GetData("destination");
                        mLoadingDialog.Show();
                        PlacesResponse mResposneSource = await api.GetPlaceLocation(source, token);

                        PlacesResponse mResponseDest = await api.GetPlaceLocation(destination, token);

                        if (mResposneSource.Code == ResponseCode.SUCCESS && mResponseDest.Code == ResponseCode.SUCCESS)
                        {
                            string             msource = mResposneSource.Location.Latitude + "," + mResposneSource.Location.Longitude;
                            string             mDest   = mResponseDest.Location.Latitude + "," + mResponseDest.Location.Longitude;
                            ReverseGeoResposne mResSrc = await api.GetReverseCodingResultlatlng(token, msource);

                            ReverseGeoResposne mResDest = await api.GetReverseCodingResultlatlng(token, mDest);

                            if (mResSrc.Code == ResponseCode.SUCCESS && mResDest.Code == ResponseCode.SUCCESS)
                            {
                                error = "Booking cab from " + source + "to" + destination;
                                speakUp();
                                mLoadingDialog.Dismiss();
                                mSourceAddress      = mResSrc.FormattedAddress;
                                mDestinationAddress = mResDest.FormattedAddress;
                                mIntent.PutExtra("mSource", mSourceAddress);
                                mIntent.PutExtra("mDestination", mDestinationAddress);
                                StartActivity(mIntent);
                            }
                            else
                            {
                                error = "Google maps error";
                                speakUp();
                                return;
                            }
                        }
                        else
                        {
                            error = "These places are not there in your notebook";
                            speakUp();
                            return;
                        }
                        break;
                    }

                    case VoiceCommandType.INVALID_COMMAND:
                        error = "Invalid Commmand Please try again";
                        speakUp();
                        break;
                    }
                }

                break;
            }
        }
Esempio n. 25
0
 public void ClassifyLocalLink_FromRoot()
 {
     Assert.Equal(LinkClassification.Local, Classifier.Classify(@"~/path/to/file.md"));
 }
Esempio n. 26
0
 /// <summary>
 /// Classifies an instance based on a set of feature values
 /// </summary>
 /// <param name="instance">Feature values, indexed by their name</param>
 /// <returns>Ranked results of the classification, class name to "probability"</returns>
 public Dictionary <ShapeType, double> Classify(Dictionary <string, object> instance)
 {
     return(Classifier.Classify(instance));
 }
Esempio n. 27
0
 public void ClassifyEmptyLink_ConsideredAsLocal()
 {
     Assert.Equal(LinkClassification.Local, Classifier.Classify(""));
 }
        public int Analyze(string message)
        {
            var scores = classifier.Classify(message, Dictionary.Helpers.VocabularyHelper.ExcludeList);

            return(scores["Positive"] > scores["Negative"] ? 1 : -1);
        }
Esempio n. 29
0
        public static async Task <HttpResponseMessage> AboutQueryRun(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequestMessage req,
            ILogger log,
            [EventStream(Constants.Domain_Query, "Test Case", "123")] EventStream esTest,
            [Projection(Constants.Domain_Query, "Test Case", "123", nameof(Query_Summary_Projection))] Projection prjTest,
            [Classifier(Constants.Domain_Query, "Test Case", "123", nameof(Query_InError_Classifier))] Classifier clsTest)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");


            if (null != esTest)
            {
                log.LogInformation($"Event stream created {esTest}");
                // add a test event
                await esTest.AppendEvent(new QueryCreated("Test Query",
                                                          Guid.NewGuid(),
                                                          aurhorisationTokenIn : "Duncan test 123"
                                                          ));
            }
            else
            {
                log.LogWarning($"Unable to create event stream parameter");
            }

            if (null != prjTest)
            {
                log.LogInformation($"Projection created {prjTest}");
                //
                Query_Summary_Projection projection = await prjTest.Process <Query_Summary_Projection>();

                if (null != projection)
                {
                    log.LogInformation($"Projection created {projection.CurrentSequenceNumber} status {projection.CurrentState } ");
                }
            }
            else
            {
                log.LogWarning($"Unable to create projection parameter");
            }

            if (null != clsTest)
            {
                log.LogInformation($"Classifier created {clsTest}");
                var result = await clsTest.Classify <Query_InError_Classifier>(forceExclude : true);

                log.LogInformation($"Classifier created {clsTest.ClassifierTypeName} result {result  } ");
            }
            else
            {
                log.LogWarning($"Unable to create classifier parameter");
            }

            // parse query parameter
            string name = req.GetQueryNameValuePairsExt()[@"name"];

            // Get request body
            dynamic data = await req.Content.ReadAsAsync <object>();

            // Set name to query string or body data
            name = name ?? data?.name;

            return(name == null
                ? req.CreateResponse(HttpStatusCode.OK, "The Long Run - Leagues Domain - Function App")
                : req.CreateResponse(HttpStatusCode.OK, GetFunctionAbout(name)));
        }
Esempio n. 30
0
 public void ClassifyLocalLink_FromParentDirectory()
 {
     Assert.Equal(LinkClassification.Local, Classifier.Classify(@"../path/to/file.md"));
 }
Esempio n. 31
0
        protected override object?RenderLine(IReadOnlyList <string> lines, int lineIndex, object?state)
        {
            var syntaxTree = default(SyntaxTree);

            if (state == null)
            {
                var text       = string.Join(Environment.NewLine, lines);
                var sourceText = SourceText.From(text);

                syntaxTree = SyntaxTree.Parse(sourceText);
            }
            else
            {
                syntaxTree = (SyntaxTree)state;
            }

            var lineSpan        = syntaxTree.Text.Lines[lineIndex].Span;
            var classifiedSpans = Classifier.Classify(syntaxTree, lineSpan);

            foreach (var classifiedSpan in classifiedSpans)
            {
                var tokenText = syntaxTree.Text.ToString(classifiedSpan.Span);

                switch (classifiedSpan.Classification)
                {
                case Classification.Text:
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    break;

                case Classification.Keyword:
                    Console.ForegroundColor = ConsoleColor.Magenta;
                    break;

                case Classification.Identifier:
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    break;

                case Classification.Number:
                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                    break;

                case Classification.String:
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    break;

                case Classification.Punctuation:
                    Console.ForegroundColor = ConsoleColor.White;
                    break;

                case Classification.Comment:
                    Console.ForegroundColor = ConsoleColor.DarkGreen;
                    break;

                default:
                    throw new Exception();
                }

                Console.Write(tokenText);
                Console.ResetColor();
            }

            return(syntaxTree);
        }
        public void start_testing(string path)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            DataTable table = new DataTable();

            using (SqlCommand cmd = new SqlCommand("select * from dataset", cn))
            {
                using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
                {
                    adp.Fill(table);
                }
            }
            Classifier classifier = new Classifier();

            classifier.TrainClassifier(table);
            string           pathconn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + path + "';Extended Properties=\"Excel 12.0 Xml;HDR=NO;IMEX=1;\"";
            OleDbConnection  conn     = new OleDbConnection(pathconn);
            OleDbDataAdapter dataadp  = new OleDbDataAdapter("select * from [Sheet1$]", conn);
            DataTable        ds       = new DataTable();

            dataadp.Fill(ds);
            //  ds.Rows[0].Delete();

            int t1 = 0, t2 = 0, t3 = 0, t4 = 0;

            for (int i = 1; i < ds.Rows.Count; i++)
            {
                try
                {
                    using (SqlCommand cmd = new SqlCommand("truncate table temp_z", cn))
                    {
                        cn.Open();
                        cmd.ExecuteNonQuery();
                        cn.Close();
                    }
                    t1 = Convert.ToInt32(ds.Rows[i]["f2"]);
                    t2 = Convert.ToInt32(ds.Rows[i]["f3"]);
                    t3 = Convert.ToInt32(ds.Rows[i]["f4"]);
                    t4 = Convert.ToInt32(ds.Rows[i]["f5"]);
                    string val = classifier.Classify(new double[] { t1, t2, t3, t4 });
                    if (val == "Introvert")
                    {
                        label2.Text = "Introvert";
                    }
                    else if (val == "Ambivert")
                    {
                        label2.Text = "Ambivert";
                    }
                    else if (val == "Extrovert")
                    {
                        label2.Text = "Extrovert";
                    }

                    using (SqlCommand cmdd = new SqlCommand("insert into output_master_naive(test1, test2, test3,test4,result) values(@test1, @test2, @test3,@test4,@result)", cn))
                    {
                        cmdd.Parameters.AddWithValue("test1", t1);
                        cmdd.Parameters.AddWithValue("test2", t2);
                        cmdd.Parameters.AddWithValue("test3", t3);
                        cmdd.Parameters.AddWithValue("test4", t4);
                        cmdd.Parameters.AddWithValue("result", val);
                        cn.Open();
                        cmdd.ExecuteNonQuery();
                        cn.Close();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("ERROR");
                }
            }
            MessageBox.Show("DONE EXECUTING");
            stopwatch.Stop();
            TimeSpan ts = stopwatch.Elapsed;

            string TotalTime = ts.Seconds.ToString();

            SetTime.Time = Convert.ToDouble(TotalTime);
            // SetTime.FilePath = OutPutPath;
            lblShow.Text    = TotalTime;
            button2.Visible = true;
        }
Esempio n. 33
0
        static void Main(string[] args)
        {
            Console.WriteLine("Classifier initialization is started.");

            classifier = new Classifier();
            Console.WriteLine("Classifier was initialized.");

            // Parse input and output folders.
            Parser.Default.ParseArguments <Options>(args)
            .WithParsed <Options>(o =>
            {
                //ExStart:ApplyingLicense

                /**
                 *  Applying product license
                 *  Please uncomment the statement if you do have license.
                 */
                // const string licensePath = "../../../../GroupDocs.Classification.NET.Full.lic";
                // new License().SetLicense(licensePath);

                //ExEnd:ApplyingLicense

                if (!Directory.Exists(o.Input))
                {
                    throw new Exception("Input directory doesn't exist.");
                }

                // Creates <output> directory if it doesn't exist.
                if (!Directory.Exists(o.Output))
                {
                    Directory.CreateDirectory(o.Output);
                }

                // For each file in <input> folder.
                foreach (var path in Directory.GetFiles(o.Input))
                {
                    var filename  = Path.GetFileName(path);
                    var directory = Path.GetDirectoryName(path);
                    try
                    {
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        // Classifies file with Documents taxonomy.
                        var result = classifier.Classify(filename, directory, taxonomy: Taxonomy.Documents);
                        Console.WriteLine(filename + ": " + result.BestClassName);
                        Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds}ms");

                        // Creates class directory in the <output> folder(if it doesn't exist)
                        var organizedDirectory = Path.Combine(o.Output, result.BestClassName);
                        if (!Directory.Exists(organizedDirectory))
                        {
                            Directory.CreateDirectory(organizedDirectory);
                        }

                        // Copies the document.
                        File.Copy(path, Path.Combine(organizedDirectory, filename));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            });
        }
Esempio n. 34
0
        static void Main(string[] args)
        {
            string        pathToData    = "DATA";
            string        pathToResults = "wynik.txt";
            bool          runOneTime    = true;
            DirectoryInfo di            = new DirectoryInfo(pathToData + "\\letterB");

            using (var tw = new StreamWriter(pathToResults, true))
            {
                foreach (var csv in di.GetFiles("*.csv"))
                {
                    IDataProvider       dataProvider = new MockDataProvider();
                    Classifier <string> classifier   = new Classifier <string>();

                    var sampleData = dataProvider.GetTrainingData(pathToData, csv.Name, ExcludeType.b) as List <InformationModel>;

                    classifier.Teach(sampleData);

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

                    values.AddRange(File.ReadAllLines(csv.FullName)
                                    .Skip(1)
                                    .Select(FromCsv)
                                    .ToList());

                    Dictionary <string, int> counter = new Dictionary <string, int>()
                    {
                        { "m", 0 }, { "f", 0 }, { "b", 0 }
                    };

                    foreach (var list in values)
                    {
                        IDictionary <string, double> tempDict = classifier.Classify(list);
                        double min = 0;
                        string cat = "";

                        foreach (var item in tempDict)
                        {
                            if (min == 0 || min > item.Value)
                            {
                                min = item.Value;
                                cat = item.Key;
                            }
                        }

                        counter[cat]++;
                    }

                    foreach (var item in counter)
                    {
                        tw.Write("{1}; ", item.Key, item.Value);
                    }

                    tw.WriteLine();

                    if (runOneTime)
                    {
                        break;
                    }
                }
            }
        }