private static void IndexOneClassifier(Classifier aCls, string aPrefix)
 {
     if ((aCls != null) && !aCls.IsShortcut())
     {
         ArrayList list = new ArrayList();
         string code = aCls.Code;
         Classifier item = aCls;
         while (true)
         {
             if (list.Contains(item))
             {
                 break;
             }
             list.Add(item);
             PdOOM.BaseObject containerClassifier = item.ContainerClassifier;
             if (containerClassifier == null)
             {
                 break;
             }
             item = (Classifier) containerClassifier;
             code = item.Code + "+" + code;
         }
         if (aPrefix != "")
         {
             code = aPrefix + "." + code;
         }
         TypeMapping.DefineExtraType(code, aCls);
     }
 }
        public void DeleteClassifier(Classifier classifier)
        {
            var derivedClasses = _classifiers.FindAllDerivedClassifiers(classifier);

            var dependentProperties =
                _classifiers.Select(x => x.Properties.FindPropertiesThatDependOnClassifier(classifier));
            var dependentMethods =
                _classifiers.Select(x => x.Methods.FindMethodsThatDependOnClassifier(classifier));
            var dependentAssociations =
                _classifiers.Select(x => x.Associations.FindAssociationsThatDependOnClassifier(classifier));
            var dependentImplementations =
                _classifiers.Select(x => x.InterfaceImplementations.FindImplementationsOfInterface(classifier));
            var dependentParameters = 
                _classifiers.SelectMany(x => x.Methods)
                    .Select(m => m.Parameters.FindMethodsThatDependOnClassifier(classifier));

            foreach (var properties in dependentProperties)
                properties.DeleteSelection(_messageSystem);
            foreach (var methods in dependentMethods)
                methods.DeleteSelection(_messageSystem);
            foreach(var associations in dependentAssociations)
                associations.DeleteSelection(_messageSystem);
            foreach (var implementation in dependentImplementations)
                implementation.DeleteSelection(_messageSystem);
            foreach (var parameter in dependentParameters)
                parameter.DeleteSelection(_messageSystem);

            // remove the deleted class as base class
            foreach (var derivedClass in derivedClasses)
                derivedClass.ClearBaseClass(_messageSystem);

            _classifiers.RemoveClassifier(classifier);
            _messageSystem.PublishDeleted(_classifiers,classifier);
        }
 public MakeClassifierToInterfaceCommand(
     Classifier classifier,
     IRelationService relationService)
 {
     _classifier = classifier;
     _relationService = relationService;
 }
 protected override void Init()
 {
     _property = For<Property>();
     _classifiers = CreateDictionaryWithoutSystemTypes();
     _messageSystem = For<MessageSystem>();
     _oldType = new Classifier(Old);
     _newType = new Classifier(New);
     _classifiers.FindByName(Old).Returns(_oldType);
     _classifiers.FindByName(New).Returns(_newType);
 }
 public void OnNameChangedTest()
 {
     // Arrange
     var classifier3 = new Classifier(3.ToString());
     var classifier2 = new Classifier(2.ToString());
     var classifiers = new ClassifierDictionary(classifier3, classifier2);
     var classifierSelectionSource = new ClassifierSelectionItemsSource(classifiers,_ => true,_messageSystem);
     // Act
     classifierSelectionSource.OnNameChanged(new NameChangedEvent(3.ToString(), 1.ToString()));
     // Assert: after renaming, item should be at first position
     Assert.IsTrue(classifierSelectionSource.First().Name == 1.ToString());
 }
Beispiel #6
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);
            //}
        }
        protected override void Init()
        {
            _validationService = For<IValidateNameService>();
            _messageSystem = For<MessageSystem>();

            _classifierDictionary = CreateDictionaryWithoutSystemTypes();
            _classifier = new Classifier("Integer");

            _renameCommand = new RenameClassifierCommand(
                _classifier, 
                _classifierDictionary,
                _validationService,
                _messageSystem);

            _newName = RandomString();
        }
        public void ChangeFromInterfaceToClass(Classifier @interface)
        {
            @interface.IsInterface = false;
            // fire the event first, otherwise the interface item sources
            // do not contain have the new interface in their list yet
            _messageSystem.Publish(@interface, new InterfaceToClassEvent(@interface.Name));

            var implementers = _classifiers.FindAllImplementers(@interface);
            foreach (var implementer in implementers)
            {
                implementer.RemoveImplementationForInterface(@interface,_messageSystem);
                // if implementer has no base class, set class as base
                if (implementer.BaseClass == null)
                    implementer.SetBaseClass(@interface, _messageSystem);
            }

            
        }
Beispiel #9
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);
        }
Beispiel #10
0
        public void ChangeFromClassToInterface(Classifier @class)
        {
            @class.IsInterface = true;
            // the class itself cannot have a base class any more
            @class.ClearBaseClass(_messageSystem);
            // find all derived classes with this base class
            var derivedClasses = _classifiers.FindAllDerivedClassifiers(@class);
            foreach (var derivedClass in derivedClasses)
            {
                derivedClass.ClearBaseClass(_messageSystem);
                derivedClass.AddInterfaceImplementation(@class, _messageSystem);
            }

            // fire the notification at the end, because this will change all
            // existing classifier list items
            
            _messageSystem.Publish(@class, new ClassToInterfaceEvent(@class.Name));
        }
        /// <summary>
        /// finds the Schema Element for which the given element could be the subset element
        /// </summary>
        /// <param name="subsetElement">the element to search a match for</param>
        /// <returns>the corresponding SchemaElement</returns>
        internal EASchemaElement getSchemaElementForSubsetElement(Classifier subsetElement)
        {
            EASchemaElement result = null;

            if (subsetElement != null)
            {
                foreach (EASchemaElement schemaElement in this.elements)
                {
                    if (schemaElement.name == subsetElement.name)
                    {
                        //check on if there is a tagged value that references the source element
                        if (this.settings.tvInsteadOfTrace)
                        {
                            var traceTag = subsetElement.taggedValues.FirstOrDefault(x => x.name == this.settings.elementTagName);
                            if (traceTag != null &&
                                traceTag.tagValue != null &&
                                traceTag.tagValue.Equals(schemaElement.sourceElement))
                            {
                                result = schemaElement;
                            }
                        }
                        else
                        {
                            //check if the subset element has a dependency to the source element of the schema
                            string sqlCheckTrace = @"select c.Connector_ID from t_connector c
													where 
													c.Connector_Type = 'Abstraction'
													and c.Stereotype = 'trace'
													and c.Start_Object_ID = "                                                     + ((TSF_EA.ElementWrapper)subsetElement).id +
                                                   " and c.End_Object_ID = " + ((TSF_EA.ElementWrapper)schemaElement.sourceElement).id;
                            var checkTraceXML   = this.model.SQLQuery(sqlCheckTrace);
                            var connectorIDNode = checkTraceXML.SelectSingleNode(this.model.formatXPath("//Connector_ID"));
                            int connectorID;
                            if (connectorIDNode != null && int.TryParse(connectorIDNode.InnerText, out connectorID))
                            {
                                result = schemaElement;
                                break;
                            }
                        }
                    }
                }
            }
            return(result);
        }
Beispiel #12
0
        public bool Delete(Classifier entity)
        {
            Contract.Requires(entity != null);
            Contract.Requires(entity.Id >= 0);

            using (IUnitOfWork uow = this.GetUnitOfWork())
            {
                IRepository <Classifier> repo = uow.GetRepository <Classifier>();
                entity = repo.Reload(entity);

                //delete the Classifier
                repo.Delete(entity);

                // commit changes
                uow.Commit();
            }
            // if any problem was detected during the commit, an exception will be thrown!
            return(true);
        }
Beispiel #13
0
        /// <summary>
        /// Найти классификатор, у которого код начинается с заданной части кода.
        /// Если классификатор не найден функция возвращает null.
        /// </summary>
        /// <param name="code">Часть кода по маске или просто часть кода</param>
        /// <returns>Классификатор</returns>
        public static Classifier FindNearestClassifier(string code)
        {
            CheckInitialization();
            if (string.IsNullOrEmpty(code))
            {
                return(null);
            }

            var clearCode = Classifier.RemoveMaskSymbols(code);

            foreach (var c in classifiers.Values)
            {
                if (c.Code.StartsWith(clearCode))
                {
                    return(c);
                }
            }
            return(null);
        }
        /// <summary>
        ///   Compute model error for a given data set.
        /// </summary>
        ///
        /// <param name="inputs">The input points.</param>
        /// <param name="outputs">The output points.</param>
        ///
        /// <returns>The percent of misclassification errors for the data.</returns>
        ///
        public double ComputeError(int[][] inputs, int[] outputs)
        {
            // TODO: Mark as obsolete?

            int errors = 0;

            Parallel.For(0, inputs.Length, i =>
            {
                int expectedOutput = outputs[i];
                int actualOutput   = Classifier.Compute(inputs[i]);

                if (expectedOutput != actualOutput)
                {
                    Interlocked.Increment(ref errors);
                }
            });

            return(errors / (double)inputs.Length);
        }
Beispiel #15
0
    IEnumerator PredictionRoutine()
    {
        yield return(new WaitForSeconds(2f));

        while (true)
        {
            int prediction = Classifier.Predict(m_classifier);
            if (prediction == 0)
            {
                continue;
            }
            m_classCounters[prediction - 1]++;
            if (PredictionUpdateEvent != null)
            {
                PredictionUpdateEvent(m_classCounters[0], m_classCounters[1], m_classCounters[2], m_classCounters[3]);
            }
            yield return(new WaitForSeconds(1));
        }
    }
Beispiel #16
0
            private async Task <IEnumerable <SymbolDisplayPart> > GetInitializerSourcePartsAsync(EqualsValueClauseSyntax equalsValue)
            {
                if (equalsValue != null && equalsValue.Value != null)
                {
                    var semanticModel = GetSemanticModel(equalsValue.SyntaxTree);
                    if (semanticModel == null)
                    {
                        return(null);
                    }

                    var classifications = Classifier.GetClassifiedSpans(semanticModel, equalsValue.Value.Span, this.Workspace, this.CancellationToken);

                    var text = await semanticModel.SyntaxTree.GetTextAsync(this.CancellationToken).ConfigureAwait(false);

                    return(ConvertClassifications(text, classifications));
                }

                return(null);
            }
        /// <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);
        }
Beispiel #18
0
        AST.OclExpression CreateIf(IToken ifTok, AST.OclExpression condition, AST.OclExpression th, AST.OclExpression el)
        {
            if (TestNull(ifTok, condition, th, el))
            {
                return(new AST.ErrorExp(Library.Invalid));
            }

            if (condition.Type.ConformsTo(Library.Boolean) == false)
            {
                Errors.AddError(new CodeErrorItem(CompilerErrors.OCLAst_CreateIf_Condition_of_IF_must_conform_to_bool, ifTok, ifTok));
            }

            //EnvironmentStack.Pop();

            Classifier exprType = th.Type.CommonSuperType(el.Type);

            return(new AST.IfExp(exprType, condition, th, el)
                   .SetCodeSource(new CodeSource(ifTok)));;
        }
        /// <summary>
        /// Train
        /// </summary>
        /// <param name="instances"></param>
        /// <returns></returns>
        public TrainModel Train(weka.core.Instances instances, Classifier classifier)
        {
            const int percentSplit = 66;
            int       trainSize    = instances.numInstances() * percentSplit / 100;
            int       testSize     = instances.numInstances() - trainSize;

            weka.core.Instances train = new weka.core.Instances(instances, 0, trainSize);

            classifier.buildClassifier(train);

            return(this.Classifier = new TrainModel()
            {
                PercentSplit = percentSplit,
                classifier = classifier,
                TestSize = testSize,
                TrainSize = trainSize,
                Instance = instances
            });
        }
Beispiel #20
0
        VariableDeclaration ProcessAccDef(IToken name, Classifier type, AST.OclExpression initExpr, ref int pushedVar)
        {
            if (TestNull(name, initExpr))
            {
                return(new VariableDeclaration("", Library.Any, new AST.ErrorExp(Library.Invalid)));
            }

            Classifier finalType = initExpr.Type;

            if (type != null)
            {
                if (initExpr.Type.ConformsTo(type) == false)
                {
                    Errors.AddError(new ErrorItem(CompilerErrors.OCLAst_ProcessAccDef_Init_value_do_not_conform_to_variable_type));
                }
                finalType = type;
            }
            return(ProcessTypeDef(name, finalType, initExpr, ref pushedVar));
        }
Beispiel #21
0
 public override OclExpression Visit(VariableExp node)
 {
     if (!VariableTranslations.ContainsKey(node.referredVariable))
     {
         OclExpression value = null;
         if (node.referredVariable.Value != null)
         {
             value = node.referredVariable.Value.Accept(this);
         }
         PSMClass            psmClass     = VariableClassMappings[node.referredVariable].First();
         Classifier          variableType = psmBridge.Find(psmClass);
         VariableDeclaration vd           = new VariableDeclaration(node.referredVariable.Name, variableType, value);
         return(new VariableExp(vd));
     }
     else
     {
         return(new VariableExp(VariableTranslations[node.referredVariable]));
     }
 }
Beispiel #22
0
 public TrainingArgs(
     Classifier classifier,
     double[][] trainData,
     int[] targets,
     double trainRate,
     double targetError,
     int maxEpochs,
     int maxRestarts,
     Action <Classifier> callback)
 {
     Classifier  = classifier;
     TrainData   = trainData;
     Targets     = targets;
     TrainRate   = trainRate;
     TargetError = targetError;
     MaxEpochs   = maxEpochs;
     MaxRestarts = maxRestarts;
     Callback    = callback;
 }
Beispiel #23
0
        public void Initialize()
        {
            ClassifierMachineLearning  = GetClassifierMachineLearning();
            ClassifierFixtureListUpper = new FixtureListClassifier();
            ClassifierFixtureListUpper.FixtureProfiles = AnalysisUpper.FixtureProfiles;

            var classifierCompositeUpper = new CompositeClassifier();

            classifierCompositeUpper.ClassifierMachineLearning = ClassifierMachineLearning;
            classifierCompositeUpper.ClassifierFixtureList     = ClassifierFixtureListUpper;

            StyledEventsViewerUpper.EventsViewer.LinedEventsCanvas.ClassifierDisaggregation = classifierCompositeUpper;
            StyledEventsViewerUpper.Events          = AnalysisUpper.Events;
            StyledEventsViewerUpper.ViewportSeconds = EventsViewer.SecondsTwoHours;
            StyledEventsViewerUpper.ViewportVolume  = EventsViewer.VolumeTen;
            StyledEventsViewerUpper.Initialize();

            ClassifierFixtureListLower = new FixtureListClassifier();
            ClassifierFixtureListLower.FixtureProfiles = AnalysisLower.FixtureProfiles;

            var classifierCompositeLower = new CompositeClassifier();

            classifierCompositeLower.ClassifierMachineLearning = ClassifierMachineLearning;
            classifierCompositeLower.ClassifierFixtureList     = ClassifierFixtureListLower;

            StyledEventsViewerLower.EventsViewer.LinedEventsCanvas.ClassifierDisaggregation = classifierCompositeLower;
            StyledEventsViewerLower.Events          = AnalysisLower.Events;
            StyledEventsViewerLower.ViewportSeconds = EventsViewer.SecondsTwoHours;
            StyledEventsViewerLower.ViewportVolume  = EventsViewer.VolumeTen;
            StyledEventsViewerLower.Initialize();

            ButtonLinkScrollBars.IsEnabled    = CanLinkScrollBars(AnalysisUpper, AnalysisLower);
            ButtonSynchronizeGraphs.IsEnabled = CanSynchronizeGraphs(AnalysisUpper, AnalysisLower);

            ButtonSynchronizeGraphs.Click += new RoutedEventHandler(ButtonSynchronizeGraphs_Click);
            ButtonLinkScrollBars.Click    += new RoutedEventHandler(ButtonLinkScrollBars_Click);
            ButtonAppend.Click            += new RoutedEventHandler(ButtonAppend_Click);

            ButtonAppend.MouseEnter            += new MouseEventHandler(ButtonAppend_MouseEnter);
            ButtonSynchronizeGraphs.MouseEnter += new MouseEventHandler(ButtonSynchronizeGraphs_MouseEnter);

            this.Loaded += new RoutedEventHandler(CompareAnalysesPanel_Loaded);
        }
Beispiel #24
0
        /// <summary>
        /// Get information about a classifier.
        ///
        /// Returns status and other information about a classifier.
        /// </summary>
        /// <param name="classifierId">Classifier ID to query.</param>
        /// <param name="customData">Custom data object to pass data including custom request headers.</param>
        /// <returns><see cref="Classifier" />Classifier</returns>
        public Classifier GetClassifier(string classifierId, Dictionary <string, object> customData = null)
        {
            if (string.IsNullOrEmpty(classifierId))
            {
                throw new ArgumentNullException(nameof(classifierId));
            }
            Classifier result = null;

            try
            {
                IClient client = this.Client;
                if (_tokenManager != null)
                {
                    client = this.Client.WithAuthentication(_tokenManager.GetToken());
                }
                if (_tokenManager == null)
                {
                    client = this.Client.WithAuthentication(this.UserName, this.Password);
                }

                var restRequest = client.GetAsync($"{this.Endpoint}/v1/classifiers/{classifierId}");

                if (customData != null)
                {
                    restRequest.WithCustomData(customData);
                }

                restRequest.WithHeader("X-IBMCloud-SDK-Analytics", "service_name=natural_language_classifier;service_version=v1;operation_id=GetClassifier");
                result = restRequest.As <Classifier>().Result;
                if (result == null)
                {
                    result = new Classifier();
                }
                result.CustomData = restRequest.CustomData;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Beispiel #25
0
        public bool ConformsTo(Classifier left, Classifier right, bool skipComposit)
        {
            if (skipComposit == false && (left is ICompositeType || right is IConformsToComposite))
            {
                return(ResolveComposite(left, right));
            }

            //realokace makingTemp na velikost matrix.count
            PrepareMarkingTemp();

            int leftIndex  = table[left].MatrixIndex;
            int rightIndex = table[right].MatrixIndex;

            Queue <int> toFind = new Queue <int>();

            toFind.Enqueue(leftIndex);

            while (toFind.Count > 0)
            {
                int actIndex = toFind.Dequeue();
                if (markingTemp[actIndex])
                {
                    continue;
                }
                markingTemp[actIndex] = true;

                if (actIndex == rightIndex)
                {
                    return(true);
                }

                foreach (int newIndex in matrix[actIndex].EdgesIndex)
                {
                    if (markingTemp[newIndex] == false)
                    {
                        toFind.Enqueue(newIndex);
                    }
                }
            }

            return(false);
        }
        public async Task <CodeAnalysisResults> RunCodeAnalysisAsync(IEditor editor, List <UnsavedFile> unsavedFiles, Func <bool> interruptRequested)
        {
            var result = new CodeAnalysisResults();

            var textLength = 0;

            await Dispatcher.UIThread.InvokeAsync(() => { textLength = editor.Document.TextLength; });

            var dataAssociation = GetAssociatedData(editor);

            var document = GetDocument(dataAssociation, editor.SourceFile);

            if (document == null)
            {
                return(result);
            }

            // Example how to get file specific diagnostics.

            /*var model = await document.GetSemanticModelAsync();
             *
             * var diagnostics = model.GetDiagnostics();*/

            try
            {
                var highlightData = await Classifier.GetClassifiedSpansAsync(document, new Microsoft.CodeAnalysis.Text.TextSpan(0, textLength));

                foreach (var span in highlightData)
                {
                    result.SyntaxHighlightingData.Add(new OffsetSyntaxHighlightingData {
                        Start = span.TextSpan.Start, Length = span.TextSpan.Length, Type = FromRoslynType(span.ClassificationType)
                    });
                }
            }
            catch (NullReferenceException)
            {
            }

            result.IndexItems = await IndexBuilder.Compute(document);

            return(result);
        }
Beispiel #27
0
        /// <summary>
        /// Create a Recognition Manager for the given sketch panel with default settings.
        /// Settings are loaded from file settings.txt
        /// </summary>
        /// <param name="p">a sketch panel to manage</param>
        public RecognitionManager(SketchPanelLib.SketchPanel p)
        {
            // Load settings from text file
            string directory        = AppDomain.CurrentDomain.BaseDirectory;
            string SettingsFilename = directory + "//settings.txt";

            _filenames = Files.SettingsReader.readSettings(SettingsFilename);

            // Initialize the recognition machines
            _domain           = ContextDomain.CircuitDomain.GetInstance();
            _strokeClassifier = RecognitionPipeline.createDefaultClassifier();
            _strokeGrouper    = RecognitionPipeline.createDefaultGrouper();
            _sketchRecognizer = RecognitionPipeline.createDefaultRecognizer();
            _connector        = RecognitionPipeline.createDefaultConnector();
            _refinement       = RecognitionPipeline.createDefaultRefiner(_connector, _sketchRecognizer);

            // Add events
            _panel         = p;
            _featuresketch = p.InkSketch.FeatureSketch;
        }
Beispiel #28
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 bool Load(Bitmap bitmap)
        {
            Bitmap = bitmap;

            try
            {
                Image = new Image <Gray, byte>(bitmap);

                Locations = Classifier.DetectMultiScale(
                    Image, Configuration.ScaleFactor, Configuration.MinimumNeighbors, Configuration.MinimumSize, Configuration.MaximumSize).ToList();
            }
            catch (Exception e)
            {
                return(false);
            }

            IsLoaded = true;

            return(true);
        }
        /// <summary>
        /// updates the subset model linked to given messageElement
        /// </summary>
        /// <param name="messageElement">The message element that is the root for the message subset model</param>
        public void updateSubsetModel(Classifier messageElement)
        {
            //match the subset existing subset elements
            //Logger.log("starting EASchema::updateSubsetModel");
            matchSubsetElements(messageElement);
            //Logger.log("after EASchema::matchSubsetElements");

            foreach (EASchemaElement schemaElement in this.schemaElements)
            {
                //match the attributes
                schemaElement.matchSubsetAttributes();
                //Logger.log("after EASchema::matchSubsetAttributes");
                schemaElement.matchSubsetLiterals();
                //match the associations
                schemaElement.matchSubsetAssociations();
                //Logger.log("after EASchema::matchSubsetAssociations");
            }
            this.createSubsetModel(messageElement.owningPackage);
            //Logger.log("after EASchema::createSubsetModel");
        }
Beispiel #31
0
        public Classifier Create(string name, string description, Classifier parent)
        {
            Contract.Requires(!string.IsNullOrWhiteSpace(name));
            Contract.Ensures(Contract.Result <Classifier>() != null && Contract.Result <Classifier>().Id >= 0);

            Classifier u = new Classifier()
            {
                Name        = name,
                Description = description,
                Parent      = parent, // if parent is null, current node will be a root
            };

            using (IUnitOfWork uow = this.GetUnitOfWork())
            {
                IRepository <Classifier> repo = uow.GetRepository <Classifier>();
                repo.Put(u);
                uow.Commit();
            }
            return(u);
        }
Beispiel #32
0
        public Bitmap GetBitmapWithLocations(Bitmap bitmap)
        {
            var returnBitmap = (Bitmap)bitmap.Clone();

            var image = returnBitmap.ToImage<Gray, byte>(); // var mat = image.ToUMat();

            var locations = Classifier.DetectMultiScale(image, ClassifierConfiguration.ScaleFactor, ClassifierConfiguration.MinimumNeighbors, ClassifierConfiguration.MinimumSize, ClassifierConfiguration.MaximumSize);

            var g = Graphics.FromImage(returnBitmap);

            foreach (var location in locations)
            {
                using (var p = new Pen(Color.Red, returnBitmap.Width / 200f))
                {
                    g.DrawRectangle(p, location);
                }
            }

            return returnBitmap;
        }
Beispiel #33
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);
        }
Beispiel #35
0
        private static void Main(string[] args)
        {
            List <Node> nodes = new List <Node> {
                new Node {
                    Key = "income", Value = "2245"
                },
                new Node {
                    Key = "income", Value = "2529"
                },
                new Node {
                    Key = "income", Value = "2206"
                },
                new Node {
                    Key = "tax", Value = "2210"
                },
                new Node {
                    Key = "tax", Value = "2169"
                },
                new Node {
                    Key = "income", Value = "2202"
                },
                new Node {
                    Key = "tax", Value = "2202"
                },
                new Node {
                    Key = "tax", Value = "2201"
                },
                new Node {
                    Key = "tax", Value = "2200"
                },
                new Node {
                    Key = "tax", Value = "2199"
                }
            };

            var classifier = new Classifier();

            classifier.Run(nodes);

            Console.WriteLine("Hello World!");
        }
        public Bitmap GetBitmapWithLocations(Bitmap bitmap)
        {
            var returnBitmap = (Bitmap)bitmap.Clone();

            var mat = returnBitmap.ToMat().CvtColor(ColorConversionCodes.BGR2GRAY);

            var locations = Classifier.DetectMultiScale(
                mat, ClassifierConfiguration.ScaleFactor, ClassifierConfiguration.MinimumNeighbors, ClassifierConfiguration.HaarDetectionType, ClassifierConfiguration.MinimumSize, ClassifierConfiguration.MaximumSize);

            var g = Graphics.FromImage(returnBitmap);

            foreach (var rectangle in locations)
            {
                using (var p = new Pen(Color.Purple, returnBitmap.Width / 200f))
                {
                    g.DrawRectangle(p, rectangle.Left, rectangle.Top, rectangle.Right - rectangle.Left, rectangle.Bottom - rectangle.Top);
                }
            }

            return(returnBitmap);
        }
Beispiel #37
0
        private static void saveModel(Classifier c, String name, java.io.File fileName)
        {
            ObjectOutputStream oos = null;

            try
            {
                oos = new ObjectOutputStream(
                    new FileOutputStream("..\\..\\..\\..\\libs\\models\\" + "models" + name + ".model"));
            }
            catch (java.io.FileNotFoundException e1)
            {
                e1.printStackTrace();
            }
            catch (java.io.IOException e1)
            {
                e1.printStackTrace();
            }
            oos.writeObject(c);
            oos.flush();
            oos.close();
        }
Beispiel #38
0
        public static ClassificationModel ParseHtmlToNewModel(HtmlDocument htmlDoc, ClassificationModel model)
        {
            var infoDetails = htmlDoc.DocumentNode
                              .SelectNodes("//div[@class='h3_notice']")
                              ?.Select(x => x.InnerText).ToList() ?? new List <string>();
            var artistName = htmlDoc.DocumentNode
                             .SelectNodes("//h2")
                             ?.Select(x => x.InnerText).ToList().FirstOrDefault() ?? string.Empty;

            model.OriginalArtist = artistName.Trim();
            model.Artist         = Classifier.NormalizeArtist(artistName.Trim());
            if (infoDetails.Count > 0)
            {
                model.Name = infoDetails[0].Trim();
            }
            if (infoDetails.Count > 1)
            {
                model.Date = infoDetails[1].Trim();
            }
            return(model);
        }
Beispiel #39
0
        public MainPage()
        {
            InitializeComponent();

            ApplicationView.PreferredLaunchViewSize      = new Size(640, 400);
            ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
            ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(640, 400));

            DrawingArea.InkPresenter.InputDeviceTypes =
                Windows.UI.Core.CoreInputDeviceTypes.Mouse
                | Windows.UI.Core.CoreInputDeviceTypes.Touch
                | Windows.UI.Core.CoreInputDeviceTypes.Pen;
            DrawingArea.InkPresenter.StrokesCollected += DrawingCanvas_StrokesCollected;

            classifier = new Classifier();

            foreach (Symbol symbol in Symbol.All())
            {
                ResultsList.Items.Add(new SymbolListItem(symbol));
            }
        }
Beispiel #40
0
        public bool IsXPathAtomic(Classifier obj)
        {
            // HACK - WFJT : this should be known from obj.Tag

            if (obj is VoidType)
            {
                return(true);
            }

            if (obj is InvalidType)
            {
                return(true);
            }

            if (FindCorrespondingAtomicType(obj) != null)
            {
                return(true);
            }

            return(false);
        }
Beispiel #41
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);
 }
Beispiel #42
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        int layerid = getTopLayer();
        if (Session["LayersSymbolized"] != null)
        {
            removeJoins(layerid);
        }
        QueryTable qt = QueryCube(layerid);

        this.Label2.Text = "";
        if (this.CheckBox1.Checked)
        {
            String query2 = qt.getQuery();
            this.Label2.Text = this.Label2.Text + query2;
        }

        ITable table = qt.getTable();
        MapFunctionality mf = (MapFunctionality)Map1.GetFunctionality(0);
        MapResourceLocal mrb = (MapResourceLocal)mf.MapResource;
        IServerContext mapContext = mrb.ServerContextInfo.ServerContext;
        IMapServerObjects mapServerObjects = (IMapServerObjects)mrb.MapServer;

        IMap map = mapServerObjects.get_Map(mrb.DataFrame);

        ILayer layer = map.get_Layer(layerid);
        IFeatureLayer featureLayer = (IFeatureLayer)layer;
        String region = table.Fields.get_Field(1).AliasName;

        bool success = joinTabletoFeatureLayer(mapContext, table, featureLayer, region,
                                               featureLayer.DisplayField,
                                               esriJoinType.esriLeftOuterJoin);

        IDisplayTable dt = (IDisplayTable)featureLayer;
        ITable joinTable = dt.DisplayTable;

        int breaks = Convert.ToInt32(this.DropDownList2.SelectedValue);
        //qt.calcFrequencies();
        qt.calcFrequencies(joinTable);
        double[] values = qt.getValues();
        int[] counts = qt.getCounts();

        String classifierType = this.DropDownList3.SelectedValue;
        Classifier classifier = new Classifier(mapContext, values,counts, classifierType, breaks);
        applyRenderer((IGeoFeatureLayer)featureLayer, mapContext, "joinedTable.Measure", classifier);
        IGeoFeatureLayer geof = (IGeoFeatureLayer)featureLayer;

        if (Session["LayersSymbolized"] == null)
        {

            Dictionary<int, bool> layersDict = new Dictionary<int, bool>();
            layersDict[layerid] = true;
            Session.Add("LayersSymbolized", layersDict);
        }

        updateMap();
        //exportImage();
    }
Beispiel #43
0
    private void applyRenderer(IGeoFeatureLayer geoLayer, IServerContext mapContext, string fieldName, Classifier classifier)
    {
        IClassBreaksRenderer cbRenderer = (IClassBreaksRenderer)mapContext.CreateObject("esriCarto.ClassBreaksRenderer");
        cbRenderer.Field = fieldName;

        ILegendInfo legendInfo = (ILegendInfo)cbRenderer;
        ILegendGroup legendGroup = legendInfo.get_LegendGroup(0);
        legendGroup.Heading = "Counts";

        int breaks = classifier.getBreaks();
        IColor [] pColors = new IColor[breaks];
        ISimpleFillSymbol [] symbols = new ISimpleFillSymbol[breaks];

        double breakValue;
        cbRenderer.BreakCount = breaks;
        IAlgorithmicColorRamp colorRamp = (IAlgorithmicColorRamp)mapContext.CreateObject("esriDisplay.AlgorithmicColorRamp");
        IColor startColor, endColor;

        startColor = createRGBColor(mapContext, 255, 255, 0);
        endColor = createRGBColor(mapContext, 255, 0, 0);
        colorRamp.FromColor = startColor;
        colorRamp.ToColor = endColor;
        colorRamp.Algorithm = esriColorRampAlgorithm.esriCIELabAlgorithm;
        colorRamp.Size = breaks;
        bool created;
        try
        {
            colorRamp.CreateRamp(out created);
        }
        catch
        {
            this.Label2.Text = "There is not enough data associated with the current extents and attributes selected. A map was not generated. Please try selecting other attributes.";
            return;
        }
        IEnumColors iterColors = colorRamp.Colors;

        double[] classBreaksArray = (double[])classifier.getClassBreaksArray();

        for (int i = 0; i < breaks; i++)
        {
            pColors[i] = iterColors.Next();
            symbols[i] = (ISimpleFillSymbol)mapContext.CreateObject("esriDisplay.SimpleFillSymbol");
            symbols[i].Color = pColors[i];
            cbRenderer.set_Symbol(i, (ISymbol)symbols[i]);

            breakValue = classBreaksArray[i + 1];
            cbRenderer.set_Break(i, breakValue);
            string breakValueString = String.Format("{0:0.00}", breakValue);

            if (i == 0)
            {
                cbRenderer.set_Label(i, "<" + breakValueString);
            }
            else
            {
                string prevValueString = String.Format("{0:0.00}", classBreaksArray[i]);
                string label = prevValueString + " < " + breakValueString;
                cbRenderer.set_Label(i, label);
            }

        }

        geoLayer.Renderer = (IFeatureRenderer)cbRenderer;
        this.Toc1.ExpandDepth = 1;
        this.Toc1.Refresh();
    }
Beispiel #44
0
 private void CreateAttribute(TypeInfo ti, Classifier aCls, AttributeInfo aField, PdOOM.BasePackage aPckg)
 {
     CustomHandlerField field = new CustomHandlerField(aField, null);
     if (!field.ThroughProperty)
     {
         PdOOM.Attribute attribute = (PdOOM.Attribute)aCls.CreateObject(0x18112065, "", -1, true);
         if (aField.IsStatic)
         {
             attribute.Static = true;
         }
         try
         {
             attribute.Name = attribute.Code = aField.Name;
         }
         catch (COMException)
         {
             if (LZ.Reverse.Info._bDebug)
             {
                 LZ.Reverse.Info.Write(new string[] { "*** exception while naming the attribute \"{1}\" on the type \"{0}\"", aField.Code, aField.Name });
             }
         }
         attribute.Visibility = GetTypeVisibility(aField.Modifier);
         //attribute.Persistent = !aField.IsNotSerialized;
         field.PdObj = attribute;
         field.Convert();
         ////Type fieldType = aField.FieldType;
         ////if (fieldType.IsArray)
         ////{
         ////    attribute.Multiplicity = "*";
         ////    fieldType = fieldType.GetElementType();
         ////}
         ////if (fieldType.IsGenericType && !fieldType.IsGenericTypeDefinition)
         ////{
         ////    fieldType = fieldType.GetGenericTypeDefinition();
         ////}
         ////this.ProcessType(fieldType, false);
         ////TypeMapping mapping = TypeMapping.Retrieve(fieldType);
         ////if (mapping.HasClassifier())
         ////{
         ////    PdOOM.BaseObject obj2 = ProperRef.Link(NamespaceMapping.Retrieve(aPckg), mapping);
         ////    attribute.UseQualifiedDataType = false;
         ////    attribute.DataTypeObject = obj2;
         ////}
         ////else
         {
             attribute.DataType = ti.Code;   // mapping.Name;
         }
     }
 }
 /// <summary>
 /// add the subset association to the list if it does not exist
 /// </summary>
 /// <param name="associationTarget">the target for the association</param>
 private void addSubsetAssociation(Classifier associationTarget)
 {
     Association existingAssociation = this.subsetAssociations.FirstOrDefault(x => ((UTF_EA.Association)x).target.Equals(associationTarget));
     Association subsetAssociation = CreateSubSetAssociation(associationTarget,existingAssociation);
     if (existingAssociation == null
         && subsetAssociation != null)
     {
         this.subsetAssociations.Add(subsetAssociation);
     }
     //if the association is part of an associationclass then create the link
     this.setAssociationClassProperties();
 }
 private bool shouldElementExistAsDatatype(Classifier subsetElement)
 {
     if (subsetElement is Class || subsetElement is Enumeration)
     {
         return true;
     }
     else
     {
         var datatype = subsetElement as DataType;
         if (datatype != null && this.settings.copyDataTypes)
         {
             if (!this.settings.limitDataTypes
                 || this.settings.dataTypesToCopy.Contains(datatype.name))
             {
                 return true;
             }
             else
             {
                 return false;
             }
         }
         else
         {
             return false;
         }
     }
 }
        /// <summary>
        /// updates the subset model linked to given messageElement
        /// </summary>
        /// <param name="messageElement">The message element that is the root for the message subset model</param>
        public void updateSubsetModel(Classifier messageElement)
        {
            //match the subset existing subset elements
            //Logger.log("starting EASchema::updateSubsetModel");
            matchSubsetElements(messageElement);
            //Logger.log("after EASchema::matchSubsetElements");

            foreach (EASchemaElement schemaElement in this.schemaElements)
            {
                //match the attributes
                schemaElement.matchSubsetAttributes();
                //Logger.log("after EASchema::matchSubsetAttributes");
                schemaElement.matchSubsetLiterals();
                //match the associations
                schemaElement.matchSubsetAssociations();
                //Logger.log("after EASchema::matchSubsetAssociations");
            }
            this.createSubsetModel(messageElement.owningPackage);
            //Logger.log("after EASchema::createSubsetModel");
        }
Beispiel #48
0
 public StartNode(Classifier classifier, string name = "", bool isNavigable = false) : 
     base(classifier, name, isNavigable)
 {
 }
Beispiel #49
0
        internal static async Task<Classifier<ImageSample>> LoadData(StreamReader reader)
        {
            var retVal = new Classifier<ImageSample>();

            var line = await reader.ReadLineAsync();

            if (line.StartsWith(LBPImageLearner.UniqueIdString))
            {
                retVal.AddLayer<LBPImageLearner>(line);
            }

            return retVal;
        }
Beispiel #50
0
        private void CreateAttribute(TypeInfo ti, Classifier aCls, AttributeInfo aField, PdOOM.BasePackage aPckg)
        {
            CustomHandlerField field = new CustomHandlerField(aField, null);
            if (!field.ThroughProperty)
            {
                PdOOM.Attribute attribute = (PdOOM.Attribute)aCls.CreateObject(0x18112065, "", -1, true);
                if (aField.IsStatic)
                {
                    attribute.Static = true;
                }
                try
                {
                    attribute.Name = attribute.Code = aField.Name;
                }
                catch (COMException)
                {
                    if (LZ.Reverse.Info._bDebug)
                    {
                        LZ.Reverse.Info.Write(new string[] { "*** exception while naming the attribute \"{1}\" on the type \"{0}\"", aField.Code, aField.Name });
                    }
                }
                attribute.Visibility = GetTypeVisibility(aField.Modifier);
                //attribute.Persistent = !aField.IsNotSerialized;
                attribute.Volatile = aField.IsVolatile;
                if (aField.IsPointer)
                {
                    attribute.Multiplicity = "*";
                }
                field.PdObj = attribute;
                field.Convert();

                TypeInfo tiField = new TypeInfo();
                ////System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[a-zA-Z_][a-zA-Z_0-9]*");
                ////System.Text.RegularExpressions.Match m = reg.Match(aField.Type.Replace("unsigned",""));
                tiField.Code = tiField.Name = aField.Type;
                tiField.IsClass = true;
                tiField.Comment = aCls.Comment;
                this.AddClassifier(tiField, false);
                bool bCreate = true;
                TypeMapping mapping = TypeMapping.Retrieve(tiField, ref bCreate);
                if (mapping.HasClassifier())
                {
                    PdOOM.NamedObject objClassB = (PdOOM.NamedObject)ProperRef.Link(NamespaceMapping.Retrieve(aPckg), mapping);
                    PdOOM.NamedObject objClassA = (PdOOM.NamedObject)attribute.Parent;
                    attribute.UseQualifiedDataType = false;
                    attribute.DataTypeObject = objClassA;

                    Association ass = (Association)aPckg.CreateObject((int)PdOOM_Classes.cls_Association, "", -1, true);
                    ass.ClassA = objClassA;
                    ass.ClassB = objClassB;
                    try
                    {
                        ass.Name = ass.Code = string.Format("ass_{0}_2_{1}_{2}", objClassA.Code, objClassB.Code, attribute.Code);
                        if (tiField.Code == aField.FullType)
                        {
                            ass.RoleBMultiplicity = "1..1";
                            ass.RoleAIndicator = aField.IsPointer ? "A" : "C";
                        }
                        ass.RoleAMultiplicity = "";
                        ass.RoleBName = aField.Name;
                        ass.RoleANavigability = false;
                        ass.RoleBNavigability = false;
                    }
                    catch (COMException)
                    {
                        if (LZ.Reverse.Info._bDebug)
                        {
                            LZ.Reverse.Info.Write(new string[] { "*** exception while naming the attribute \"{1}\" on the type \"{0}\"", aField.Code, aField.Name });
                        }
                    }

                }
                ////else
                {
                    attribute.DataType = aField.FullType;   // mapping.Name;
                }
            }
        }
Beispiel #51
0
        private void CreateMethod(TypeInfo aType, Classifier aCls, MethordInfo aMethod, PdOOM.BasePackage aPckg, Operation anOper, InfluenceTable anInfTable)
        {
            Operation operation;
            if (anOper != null)
            {
                operation = anOper;
            }
            else
            {
                operation = (Operation)aCls.CreateObject(0x18112066, "", -1, true);
            }
            operation.Static = aMethod.IsStatic;
            operation.Visibility = GetTypeVisibility(aMethod.Modifier);
            operation.ReturnType = aMethod.Type;
            //operation.Final = aMethod.IsFinal;
            if (aMethod.IsGenericMethod)
            {
                operation.Generic = true;
                foreach (TypeParameter parameter in operation.TypeParameters)
                {
                    parameter.delete();
                }
                ////foreach (Type type in aMethod.GetGenericArguments())
                ////{
                ////    TypeParameter parameter2 = (TypeParameter)operation.CreateObject(0x1811207d, "", -1, true);
                ////    this.ProcessType(type, false);
                ////    TypeMapping mapping = TypeMapping.Retrieve(type);
                ////    parameter2.Name = parameter2.Code = mapping.Name;
                ////    operation.TypeParameters.Add(parameter2);
                ////}
            }
            if (aMethod.IsVirtual)
            {
                operation.SetExtendedAttribute("C++.virtual", "true");
            }
            if (aMethod.IsAbstract)
            {
                operation.Abstract = true;
            }
            try
            {
                operation.Code = aMethod.Code;
                operation.Name = aMethod.Name;
            }
            catch (COMException)
            {
                if (LZ.Reverse.Info._bDebug)
                {
                    LZ.Reverse.Info.Write(new string[] { "*** exception while naming the operation \"{1}\" on the type \"{0}\"", aType.Code, aMethod.Name });
                }
            }

            new CustomHandlerMethod(aMethod, operation).Convert();
            // 添加参数
            foreach (ObjectInfo type in aMethod.Parameters)
            {
                AddParameter(operation, type, aPckg);
            }

            // 防止有重载方法前面改名失败
            if (aMethod.Parameters.Count > 0 && operation.Code != aMethod.Code)
            {
                try
                {
                    operation.Code = aMethod.Code;
                    operation.Name = aMethod.Name;
                }
                catch (COMException)
                {
                    if (LZ.Reverse.Info._bDebug)
                    {
                        LZ.Reverse.Info.Write(new string[] { "*** exception while naming the operation \"{1}\" on the type \"{0}\"", aType.Code, aMethod.Name });
                    }
                }
            }
        }
Beispiel #52
0
 private void CreateMethod(Type aType, Classifier aCls, MethodBase aMethod, PdOOM.BasePackage aPckg, Operation anOper, InfluenceTable anInfTable)
 {
     Operation operation;
     if (anOper != null)
     {
         operation = anOper;
     }
     else
     {
         operation = (Operation) aCls.CreateObject(0x18112066, "", -1, true);
     }
     operation.Static = aMethod.IsStatic;
     operation.Visibility = GetMethodVisibility(aMethod);
     operation.Final = aMethod.IsFinal;
     if (aMethod.IsGenericMethod)
     {
         operation.Generic = true;
         foreach (TypeParameter parameter in operation.TypeParameters)
         {
             parameter.delete();
         }
         foreach (Type type in aMethod.GetGenericArguments())
         {
             TypeParameter parameter2 = (TypeParameter) operation.CreateObject(0x1811207d, "", -1, true);
             this.ProcessType(type, false);
             TypeMapping mapping = TypeMapping.Retrieve(type);
             parameter2.Name = parameter2.Code = mapping.Name;
             operation.TypeParameters.Add(parameter2);
         }
     }
     if (aMethod.IsVirtual)
     {
         if (LZ.Reverse.Info._bVBNet)
         {
             operation.SetExtendedAttribute("VB.NET.Overridable", "true");
         }
         else
         {
             operation.SetExtendedAttribute("C#.virtual", "true");
         }
     }
     if (aMethod.IsAbstract)
     {
         operation.Abstract = true;
     }
     new CustomHandlerMethod(aMethod, operation).Convert();
     if (anOper == null)
     {
         foreach (ParameterInfo info in aMethod.GetParameters())
         {
             this.AddParameter(operation, info, aPckg);
         }
     }
     bool flag = aMethod.IsConstructor || aMethod.GetType().IsSubclassOf(typeof(ConstructorInfo));
     if (!flag)
     {
         MethodInfo info2 = (MethodInfo) aMethod;
         Type returnType = info2.ReturnType;
         if (returnType.IsArray)
         {
             operation.Array = true;
             returnType = returnType.GetElementType();
         }
         this.ProcessType(returnType, false);
         TypeMapping mapping2 = TypeMapping.Retrieve(returnType);
         if (mapping2.HasClassifier())
         {
             PdOOM.BaseObject obj2 = ProperRef.Link(NamespaceMapping.Retrieve(aPckg), mapping2);
             operation.UseQualifiedDataType = false;
             operation.ReturnTypeObject = obj2;
         }
         else
         {
             operation.ReturnType = mapping2.Name;
         }
         if ((anInfTable != null) && anInfTable.Contains(info2))
         {
             anInfTable.Impact(info2, operation);
         }
         if (LZ.Reverse.Info._bVBNet)
         {
             new CustomHandlerReturn(info2, anOper).Convert();
         }
         bool flag2 = false;
         if (!info2.IsHideBySig && info2.GetBaseDefinition().Equals(info2))
         {
             string name = info2.Name;
             if (!aType.BaseType.Equals(aType))
             {
                 BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
                 bool flag3 = false;
                 foreach (MethodInfo info3 in aType.GetMethods(bindingAttr))
                 {
                     if (info3.Name == name)
                     {
                         flag3 = true;
                         break;
                     }
                 }
                 if (flag3)
                 {
                     flag2 = true;
                 }
             }
         }
         if (info2.GetBaseDefinition().Equals(info2))
         {
             if (flag2)
             {
                 if (LZ.Reverse.Info._bVBNet)
                 {
                     operation.SetExtendedAttribute("VB.NET.Shadowing", "Shadows");
                 }
                 else
                 {
                     operation.SetExtendedAttribute("C#.new", "true");
                 }
             }
             else if (aMethod.IsHideBySig && LZ.Reverse.Info._bVBNet)
             {
                 operation.SetExtendedAttribute("VB.NET.Shadowing", "Overloads");
             }
         }
         else if (LZ.Reverse.Info._bVBNet)
         {
             operation.SetExtendedAttribute("VB.NET.Overrides", "true");
         }
         else
         {
             operation.SetExtendedAttribute("C#.override", "true");
         }
     }
     if (flag)
     {
         operation.Stereotype = "Constructor";
         operation.ReturnType = "";
         operation.InfluentObject = aCls;
         operation.Automatic = true;
         try
         {
             if (LZ.Reverse.Info._bVBNet)
             {
                 operation.Name = operation.Code = "New";
             }
             else
             {
                 operation.Name = operation.Code = TypeInfoHelper.GetTypeName(aType);
             }
             return;
         }
         catch (COMException)
         {
             if (LZ.Reverse.Info._bDebug)
             {
                 LZ.Reverse.Info.Write(new string[] { "*** exception while naming the operation \"{1}\" on the type \"{0}\"", aType.FullName, aMethod.Name });
             }
             return;
         }
     }
     if (anOper == null)
     {
         string aName = aMethod.Name;
         if (!LZ.Reverse.Info._bVBNet && ShortenOperator(aMethod.GetParameters().Length, ref aName))
         {
             operation.Stereotype = "Operator";
         }
         try
         {
             operation.Name = operation.Code = aName;
         }
         catch (COMException)
         {
             if (LZ.Reverse.Info._bDebug)
             {
                 LZ.Reverse.Info.Write(new string[] { "*** exception while naming the operation \"{1}\" on the type \"{0}\"", aType.FullName, aMethod.Name });
             }
         }
     }
 }
Beispiel #53
0
 private void CreateEvent(Type aType, Classifier aCls, EventInfo anEvent, PdOOM.BasePackage aPckg, ref AttributeTable aAttrTable, ref MethodTable aMthTable, ref InfluenceTable aInfTable)
 {
     if (!LZ.Reverse.Info._bVBNet)
     {
         bool flag;
         bool flag2;
         if (aType.GetField(anEvent.Name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly) != null)
         {
             flag = false;
             flag2 = false;
         }
         else
         {
             flag = true;
             flag2 = true;
         }
         if (flag)
         {
             PdOOM.Attribute anObject = (PdOOM.Attribute) aCls.CreateObject(0x18112065, "", -1, true);
             anObject.Stereotype = "Event";
             try
             {
                 anObject.Name = anObject.Code = anEvent.Name;
             }
             catch (COMException)
             {
                 if (LZ.Reverse.Info._bDebug)
                 {
                     LZ.Reverse.Info.Write(new string[] { "*** exception while naming the event \"{1}\" on the type \"{0}\"", aType.FullName, anEvent.Name });
                 }
             }
             Type eventHandlerType = anEvent.EventHandlerType;
             this.ProcessType(eventHandlerType, false);
             TypeMapping mapping = TypeMapping.Retrieve(eventHandlerType);
             anObject.DataType = mapping.Name;
             if (!mapping.Delegate && LZ.Reverse.Info._bDebug)
             {
                 LZ.Reverse.Info.Write(new string[] { "*** invalid delegate mapping for \"{0}\"", eventHandlerType.FullName });
             }
             MethodInfo addMethod = anEvent.GetAddMethod(true);
             anObject.Visibility = GetMethodVisibility(addMethod);
             if (flag2)
             {
                 aInfTable.Add(addMethod, anObject, "EventAdd");
                 addMethod = anEvent.GetRemoveMethod(true);
                 aInfTable.Add(addMethod, anObject, "EventRemove");
             }
         }
         if (!flag2)
         {
             MethodInfo aMethod = anEvent.GetAddMethod(true);
             aMthTable.Add(aMethod);
             aMethod = anEvent.GetRemoveMethod(true);
             aMthTable.Add(aMethod);
         }
     }
 }
 public void TestInitialize()
 {
     _classifier = new Classifier<FakeRecord>();
     _root = new Rule
     {
         LessOrEqualRule = new Rule
         {
             Property = "Ask",
             Value = 1.1,
             Relation = RelationType.LessOrEqual,
             Action = MarketAction.Sell
         },
         GreaterRule = new Rule
         {
             Property = "Ask",
             Value = 1.1,
             Relation = RelationType.Greater,
             LessOrEqualRule = new Rule
             {
                 Property = "Bid",
                 Value = 1.2,
                 Relation = RelationType.LessOrEqual,
                 Action = MarketAction.Buy
             },
             GreaterRule = new Rule
             {
                 Property = "Bid",
                 Value = 1.2,
                 Relation = RelationType.Greater,
                 Action = MarketAction.Hold
             }
         }
     };
 }
Beispiel #55
0
 public static void WriteFeatureStrings(
         TextWriter writer, Classifier classifier, FeatureEncoder featureEncoder,
         EncodingResult encodingResult = null) {
     var acceptingFeature = classifier.GetAllAcceptingFeatureStrings(featureEncoder);
     var rejectingFeatures = classifier.GetAllRejectingFeatureStrings(featureEncoder);
     var acceptingVectorCounts = encodingResult != null
             ? classifier.CountAcceptedVectorsOfEachGroup(encodingResult)
             : Enumerable.Repeat(-1, acceptingFeature.Count).ToList();
     var rejectingVectorCounts = encodingResult != null
             ? classifier.CountRejectedVectorsOfEachGroup(encodingResult)
             : Enumerable.Repeat(-1, rejectingFeatures.Count).ToList();
     writer.WriteLine("################ Accepting Features ################");
     for (var i = 0; i < acceptingFeature.Count; i++) {
         writer.WriteLine("######## Group: " + (i + 1) + " ("
                          + acceptingVectorCounts[i] + ") ########");
         writer.WriteLine(Beautify(classifier.GroupPaths[i]));
         if (acceptingVectorCounts[i] != 0) {
             writer.WriteLine();
             foreach (var featureString in acceptingFeature[i]) {
                 writer.WriteLine(Beautify(featureString));
             }
         }
     }
     writer.WriteLine("################ Rejecting Features ################");
     for (var i = 0; i < rejectingFeatures.Count; i++) {
         writer.WriteLine("######## Group: " + (i + 1) + " ("
                          + rejectingVectorCounts[i] + ") ########");
         writer.WriteLine(Beautify(classifier.GroupPaths[i]));
         if (rejectingVectorCounts[i] != 0) {
             writer.WriteLine();
             foreach (var featureString in rejectingFeatures[i]) {
                 writer.WriteLine(Beautify(featureString));
             }
         }
     }
     writer.Flush();
 }
 public AugmentedAffectiveInformation(AffectiveInformation affectiveInfo, Classifier classifier)
 {
     this.Name = affectiveInfo.Name;
     this.Score = affectiveInfo.Score;
     this.Classifier = classifier;
 }
Beispiel #57
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);
        }
Beispiel #58
0
        static int TestTrainer(Classifier<Sample> c)
        {
            List<Sample> pointsPos, pointsNeg;

            GenerateSamples(0, out pointsPos, out pointsNeg);

            return TestTrainer(c, pointsPos, pointsNeg);
        }
        private Association CreateSubSetAssociation(Classifier associationTarget, Association existingAssociation)
        {
            Association subSetAssociation;
            if (existingAssociation == null)
            {
               		subSetAssociation = this.model.factory.createNewElement<UML.Classes.Kernel.Association>
               		 					(this.owner.subsetElement,this.sourceAssociation.name);
               		subSetAssociation.addRelatedElement(associationTarget);
            }
            else
            {
                //TODO: check and report differences
            //        		if (this._sourceAssociation.sourceEnd.multiplicity != subSetAssociation.
              		subSetAssociation = existingAssociation;
            }
               	//update name
            subSetAssociation.name = this.sourceAssociation.name;
            //notes only update them if they are empty
            if (subSetAssociation.ownedComments.Count == 0 || ! subSetAssociation.ownedComments.Any(x => x.body.Length > 0))
            {
                subSetAssociation.ownedComments = this.sourceAssociation.ownedComments;
                if (this.owner.owner.settings.prefixNotes
                    && this.owner.owner.settings.prefixNotesText.Length > 0
                    && subSetAssociation.ownedComments.Any(x => x.body.Length > 0))
                {
                    foreach (var comment in subSetAssociation.ownedComments)
                    {
                        comment.body = this.owner.owner.settings.prefixNotesText + Environment.NewLine + comment.body;
                    }
                }
            }
            //stereotype
            subSetAssociation.stereotypes = this.sourceAssociation.stereotypes;
            //save all changes
            subSetAssociation.save();
            //copy the association end properties
            //copy source end properties
            this.copyAssociationEndProperties((UTF_EA.AssociationEnd)this.thisEnd,
                ((UTF_EA.Association)subSetAssociation).sourceEnd);
            //copy target end properties
            this.copyAssociationEndProperties((UTF_EA.AssociationEnd)this.otherEnd,
                ((UTF_EA.Association)subSetAssociation).targetEnd);
            //set the target multiplicity to a possible redefined multiplicity from the schema
            ((UTF_EA.Association)subSetAssociation).targetEnd.multiplicity = this.multiplicity;
            //save all changes
            subSetAssociation.save();
            //copy tagged values
            ((EASchema) this.owner.owner).copyTaggedValues((UTF_EA.Element)this.sourceAssociation,(UTF_EA.Element)subSetAssociation);
            //((UTF_EA.Association)this.subsetAssociation).copyTaggedValues((UTF_EA.Association)this.sourceAssociation);
            //add tagged value with reference to source association
            ((UTF_EA.Association)subSetAssociation).addTaggedValue(
                this.owner.owner.settings.sourceAssociationTagName, ((UTF_EA.Association)this.sourceAssociation).guid);

            subSetAssociation.save();
            return subSetAssociation;
        }
Beispiel #60
0
 private void CreateProperty(Type aType, Classifier aCls, PropertyInfo aProperty, PdOOM.BasePackage aPckg, ref MethodTable aTable)
 {
     bool flag = aProperty.GetIndexParameters().GetLength(0) != 0;
     PdOOM.Attribute anAttr = (PdOOM.Attribute) aCls.CreateObject(0x18112065, "", -1, true);
     if (aProperty.CanRead)
     {
         if (aProperty.CanWrite)
         {
             anAttr.Frozen = "C";
         }
         else
         {
             anAttr.Frozen = "R";
         }
     }
     else
     {
         anAttr.Frozen = "A";
     }
     anAttr.Stereotype = LZ.Reverse.Info._bVBNet ? "Property" : (flag ? "Indexer" : "Property");
     Operation anOper = null;
     Operation operation2 = null;
     foreach (PdOOM.BaseObject obj2 in anAttr.DependentObjects)
     {
         if (obj2.ClassKind == 0x18112065)
         {
             obj2.delete();
         }
         else if (obj2.ClassKind == 0x18112066)
         {
             Operation operation3 = (Operation) obj2;
             if (operation3.Stereotype == "Setter")
             {
                 operation2 = operation3;
                 continue;
             }
             if (operation3.Stereotype == "Getter")
             {
                 anOper = operation3;
             }
         }
     }
     if (aProperty.CanRead)
     {
         anAttr.Visibility = GetMethodVisibility(aProperty.GetGetMethod(true));
     }
     else if (aProperty.CanWrite)
     {
         anAttr.Visibility = GetMethodVisibility(aProperty.GetSetMethod(true));
     }
     else
     {
         anAttr.Visibility = "-";
     }
     Type propertyType = aProperty.PropertyType;
     if (propertyType.IsArray)
     {
         anAttr.Multiplicity = "*";
         propertyType = propertyType.GetElementType();
     }
     this.ProcessType(propertyType, false);
     TypeMapping mapping = TypeMapping.Retrieve(propertyType);
     if (mapping.HasClassifier())
     {
         PdOOM.BaseObject obj3 = ProperRef.Link(NamespaceMapping.Retrieve(aPckg), mapping);
         anAttr.UseQualifiedDataType = false;
         anAttr.DataTypeObject = obj3;
     }
     else
     {
         anAttr.DataType = mapping.Name;
     }
     try
     {
         anAttr.Name = anAttr.Code = aProperty.Name;
     }
     catch (COMException)
     {
         if (LZ.Reverse.Info._bDebug)
         {
             LZ.Reverse.Info.Write(new string[] { "*** exception while naming the property \"{1}\" on the type \"{0}\"", aType.FullName, aProperty.Name });
         }
     }
     if (aProperty.CanRead)
     {
         if (anOper != null)
         {
             MethodInfo getMethod = aProperty.GetGetMethod(true);
             aTable.Add(getMethod);
             this.CreateMethod(aType, aCls, getMethod, aPckg, anOper, null);
         }
         else if (LZ.Reverse.Info._bDebug)
         {
             LZ.Reverse.Info.Write(new string[] { "*** exception around the setter for the property \"{1}\" on the type \"{0}\"", aType.FullName, aProperty.Name });
         }
     }
     if (aProperty.CanWrite)
     {
         if (operation2 != null)
         {
             MethodInfo setMethod = aProperty.GetSetMethod(true);
             aTable.Add(setMethod);
             this.CreateMethod(aType, aCls, setMethod, aPckg, operation2, null);
         }
         else if (LZ.Reverse.Info._bDebug)
         {
             LZ.Reverse.Info.Write(new string[] { "*** exception around the setter for the property \"{1}\" on the type \"{0}\"", aType.FullName, aProperty.Name });
         }
     }
     CustomHandlerProperty property = new CustomHandlerProperty(aProperty, anAttr);
     property.Convert();
     if (LZ.Reverse.Info._bVBNet && property.Default)
     {
         anAttr.SetExtendedAttribute("VB.NET.Default", "true");
     }
     bool flag2 = false;
     if (LZ.Reverse.Info._bVBNet)
     {
         bool flag3 = false;
         if (aProperty.CanRead && aProperty.GetGetMethod(true).IsHideBySig)
         {
             flag3 = true;
         }
         else if (aProperty.CanWrite && aProperty.GetSetMethod(true).IsHideBySig)
         {
             flag3 = true;
         }
         if (flag3 && !flag2)
         {
             anAttr.SetExtendedAttribute("VB.NET.Shadowing", "Overloads");
         }
     }
 }