Пример #1
0
 public CourseController(LearningModel context)
 {
     _context = context;
 }
Пример #2
0
        public static void Initialize(LearningModel context, UserRolesContext IdContext)
        {
            //Checks to see if it has been started
            context.Database.EnsureCreated();
            IdContext.Database.EnsureCreated();

            // Look for any students.
            if (context.Courses.Any() || IdContext.Users.Any())
            {
                return;   // DB has been seeded
            }
            // ROLES
            IdContext.Roles.Add(new Microsoft.AspNetCore.Identity.IdentityRole {
                Id = "1", Name = "Admin", NormalizedName = "ADMIN", ConcurrencyStamp = null
            });
            IdContext.Roles.Add(new Microsoft.AspNetCore.Identity.IdentityRole {
                Id = "2", Name = "Instructor", NormalizedName = "INSTRUCTOR", ConcurrencyStamp = null
            });
            IdContext.Roles.Add(new Microsoft.AspNetCore.Identity.IdentityRole {
                Id = "3", Name = "Chair", NormalizedName = "CHAIR", ConcurrencyStamp = null
            });

            // ADMIN ERIN
            IdContext.Users.Add(new Microsoft.AspNetCore.Identity.IdentityUser {
                Id = "583abdab-54b2-4fbc-8024-41fd994718ba", UserName = "******", NormalizedUserName = "******", Email = "*****@*****.**", NormalizedEmail = "*****@*****.**", EmailConfirmed = true, PasswordHash = "AQAAAAEAACcQAAAAEJttv1Isvz+wfAF0X4Acz9PfSFn92uPW3vTzG/MXm3DZ/TGvsVKnzEqyjZKJbie13A==", SecurityStamp = "7LB6S2EHKBN2NB4P2YGOGJ33S5EPHPD2", ConcurrencyStamp = "e253d6e0-6f70-440d-b4bb-3102ef94b221", PhoneNumber = null, PhoneNumberConfirmed = false, TwoFactorEnabled = false, LockoutEnd = null, LockoutEnabled = true, AccessFailedCount = 0
            });
            IdContext.UserRoles.Add(new Microsoft.AspNetCore.Identity.IdentityUserRole <string> {
                UserId = "583abdab-54b2-4fbc-8024-41fd994718ba", RoleId = "1"
            });

            // INSTRUCTOR JIM
            IdContext.Users.Add(new Microsoft.AspNetCore.Identity.IdentityUser {
                Id = "e727124f-f3be-47c3-9063-398c6cc4cf16", UserName = "******", NormalizedUserName = "******", Email = "*****@*****.**", NormalizedEmail = "*****@*****.**", EmailConfirmed = true, PasswordHash = "AQAAAAEAACcQAAAAEL6m1mfC4FFQJ+VijYUJEAyhm47XX1RrAznI9dWczVOMqZkXCDJJjMVpxq9S7BDl5Q==", SecurityStamp = "BWVUXMAXTEIKTWLXFVTAV7ECRLQZR3UE", ConcurrencyStamp = "1056c7f2-9ac2-438b-baf7-e7e069e1a9b8", PhoneNumber = null, PhoneNumberConfirmed = false, TwoFactorEnabled = false, LockoutEnd = null, LockoutEnabled = true, AccessFailedCount = 0
            });
            IdContext.UserRoles.Add(new Microsoft.AspNetCore.Identity.IdentityUserRole <string> {
                UserId = "e727124f-f3be-47c3-9063-398c6cc4cf16", RoleId = "2"
            });

            // INSTRUCTOR MARY
            IdContext.Users.Add(new Microsoft.AspNetCore.Identity.IdentityUser {
                Id = "3c694a12-8727-44f5-9f53-2c4e0e63ea5f", UserName = "******", NormalizedUserName = "******", Email = "*****@*****.**", NormalizedEmail = "*****@*****.**", EmailConfirmed = true, PasswordHash = "AQAAAAEAACcQAAAAEKn9wkyyYYQsE86xfBIEEZBbl5x7QnhyABmhMAu+jRqJ3A8txusxDzBt5MR9aCLGoA==", SecurityStamp = "D2P2YGNCIN3NWWXKLVZH227CS3SPQ4ZU", ConcurrencyStamp = "a72ff5e2-24ba-4ee8-bff8-50ef20b0a619", PhoneNumber = null, PhoneNumberConfirmed = false, TwoFactorEnabled = false, LockoutEnd = null, LockoutEnabled = true, AccessFailedCount = 0
            });
            IdContext.UserRoles.Add(new Microsoft.AspNetCore.Identity.IdentityUserRole <string> {
                UserId = "3c694a12-8727-44f5-9f53-2c4e0e63ea5f", RoleId = "2"
            });


            // INSTRUCTOR DANNY
            IdContext.Users.Add(new Microsoft.AspNetCore.Identity.IdentityUser {
                Id = "3c3d6ea3-22c3-4cfb-8ae0-b1eba2663c61", UserName = "******", NormalizedUserName = "******", Email = "*****@*****.**", NormalizedEmail = "*****@*****.**", EmailConfirmed = true, PasswordHash = "AQAAAAEAACcQAAAAEHuOUe7LJo4+QRSf4SpadQ/E9eb3waJQBTVG7ZUvlsNalvChCeLeA3ir0duqvbJGUA==", SecurityStamp = "JZC5JWMEJNNN7VIOIDGAZDQNL473XQ75", ConcurrencyStamp = "97b93df4-fb80-4b65-9448-6f7231d8c683", PhoneNumber = null, PhoneNumberConfirmed = false, TwoFactorEnabled = false, LockoutEnd = null, LockoutEnabled = true, AccessFailedCount = 0
            });
            IdContext.UserRoles.Add(new Microsoft.AspNetCore.Identity.IdentityUserRole <string> {
                UserId = "3c3d6ea3-22c3-4cfb-8ae0-b1eba2663c61", RoleId = "2"
            });

            // CHAIR WHITAKER
            IdContext.Users.Add(new Microsoft.AspNetCore.Identity.IdentityUser {
                Id = "62defa0c-6d45-4d66-9c74-42e8253ad5d3", UserName = "******", NormalizedUserName = "******", Email = "*****@*****.**", NormalizedEmail = "*****@*****.**", EmailConfirmed = true, PasswordHash = "AQAAAAEAACcQAAAAEGsHbHXLLKNkmwQvA0uj/yzsRkW5bAYxpTtbAJCYewc/DFGCG1IoXrA6lxZdEk/a9w==", SecurityStamp = "PXK7EQNEUB4SIJBP3KUA4FMOKKMLI4HP", ConcurrencyStamp = "9fea99b6-7808-4b44-9d31-c6e2afd5b0b8", PhoneNumber = null, PhoneNumberConfirmed = false, TwoFactorEnabled = false, LockoutEnd = null, LockoutEnabled = true, AccessFailedCount = 0
            });
            IdContext.UserRoles.Add(new Microsoft.AspNetCore.Identity.IdentityUserRole <string> {
                UserId = "62defa0c-6d45-4d66-9c74-42e8253ad5d3", RoleId = "3"
            });

            // SAVE
            IdContext.SaveChanges();

            //2100
            List <LearningOutcome> LOs1 = new List <LearningOutcome>();

            LOs1.Add(new LearningOutcome {
                LearningId = 1, Name = "2100", Description = "use symbolic logic to model real-world situations by converting informal language statements to propositional and predicate logic expressions, as well as apply formal methods to propositions and predicates (such as computing normal forms and calculating validity)", CourseInstanceId = 1
            });
            LOs1.Add(new LearningOutcome {
                LearningId = 2, Name = "2100", Description = "analyze problems to determine underlying recurrence relations, as well as solve such relations by rephrasing as closed formulas", CourseInstanceId = 1
            });
            LOs1.Add(new LearningOutcome {
                LearningId = 3, Name = "2100", Description = "assign practical examples to the appropriate set, function, or relation model, while employing the associated terminology and operations", CourseInstanceId = 1
            });
            LOs1.Add(new LearningOutcome {
                LearningId = 4, Name = "2100", Description = "map real-world applications to appropriate counting formalisms, including permutations and combinations of sets, as well as exercise the rules of combinatorics (such as sums, products, and inclusion-exclusion)", CourseInstanceId = 1
            });
            LOs1.Add(new LearningOutcome {
                LearningId = 5, Name = "2100", Description = "calculate probabilities of independent and dependent events, in addition to expectations of random variables", CourseInstanceId = 1
            });
            LOs1.Add(new LearningOutcome {
                LearningId = 6, Name = "2100", Description = "illustrate by example the basic terminology of graph theory, as wells as properties and special cases (such as Eulerian graphs, spanning trees, isomorphism, and planarity)", CourseInstanceId = 1
            });
            LOs1.Add(new LearningOutcome {
                LearningId = 7, Name = "2100", Description = "employ formal proof techniques (such as direct proof, proof by contradiction, induction, and the pigeonhole principle) to construct sound arguments about properties of numbers, sets, functions, relations, and graphs", CourseInstanceId = 1
            });

            //2420
            List <LearningOutcome> LOs2 = new List <LearningOutcome>();

            LOs2.Add(new LearningOutcome {
                LearningId = 8, Name = "2420", Description = "implement, and analyze for efficiency, fundamental data structures (including lists, graphs, and trees) and algorithms (including searching, sorting, and hashing)", CourseInstanceId = 2
            });
            LOs2.Add(new LearningOutcome {
                LearningId = 9, Name = "2420", Description = "employ Big-O notation to describe and compare the asymptotic complexity of algorithms, as well as perform empirical studies to validate hypotheses about running time", CourseInstanceId = 2
            });
            LOs2.Add(new LearningOutcome {
                LearningId = 10, Name = "2420", Description = "recognize and describe common applications of abstract data types (including stacks, queues, priority queues, sets, and maps)", CourseInstanceId = 2
            });
            LOs2.Add(new LearningOutcome {
                LearningId = 11, Name = "2420", Description = "apply algorithmic solutions to real-world data", CourseInstanceId = 2
            });
            LOs2.Add(new LearningOutcome {
                LearningId = 12, Name = "2420", Description = "use generics to abstract over functions that differ only in their types", CourseInstanceId = 2
            });
            LOs2.Add(new LearningOutcome {
                LearningId = 13, Name = "2420", Description = "appreciate the collaborative nature of computer science by discussing the benefits of pair programming", CourseInstanceId = 2
            });

            //3500
            List <LearningOutcome> LOs3 = new List <LearningOutcome>();

            LOs3.Add(new LearningOutcome {
                LearningId = 14, Name = "3500", Description = "design and implement large and complex software systems (including concurrent software) through the use of process models (such as waterfall and agile), libraries (both standard and custom), and modern software development tools (such as debuggers, profilers, and revision control systems)", CourseInstanceId = 3
            });
            LOs3.Add(new LearningOutcome {
                LearningId = 15, Name = "3500", Description = "perform input validation and error handling, as well as employ advanced testing principles and tools to systematically evaluate software", CourseInstanceId = 3
            });
            LOs3.Add(new LearningOutcome {
                LearningId = 16, Name = "3500", Description = "apply the model-view-controller pattern and event handling fundamentals to create a graphical user interface", CourseInstanceId = 3
            });
            LOs3.Add(new LearningOutcome {
                LearningId = 17, Name = "3500", Description = "exercise the client-server model and high-level networking APIs to build a web-based software system", CourseInstanceId = 3
            });
            LOs3.Add(new LearningOutcome {
                LearningId = 18, Name = "3500", Description = "operate a modern relational database to define relations, as well as store and retrieve data", CourseInstanceId = 3
            });
            LOs3.Add(new LearningOutcome {
                LearningId = 19, Name = "3500", Description = "appreciate the collaborative nature of software development by discussing the benefits of peer code reviews", CourseInstanceId = 3
            });

            //3500 #2
            //3500
            List <LearningOutcome> LOs4 = new List <LearningOutcome>();

            LOs4.Add(new LearningOutcome {
                LearningId = 20, Name = "3500", Description = "design and implement large and complex software systems (including concurrent software) through the use of process models (such as waterfall and agile), libraries (both standard and custom), and modern software development tools (such as debuggers, profilers, and revision control systems)", CourseInstanceId = 4
            });
            LOs4.Add(new LearningOutcome {
                LearningId = 21, Name = "3500", Description = "perform input validation and error handling, as well as employ advanced testing principles and tools to systematically evaluate software", CourseInstanceId = 4
            });
            LOs4.Add(new LearningOutcome {
                LearningId = 22, Name = "3500", Description = "apply the model-view-controller pattern and event handling fundamentals to create a graphical user interface", CourseInstanceId = 4
            });
            LOs4.Add(new LearningOutcome {
                LearningId = 23, Name = "3500", Description = "exercise the client-server model and high-level networking APIs to build a web-based software system", CourseInstanceId = 4
            });
            LOs4.Add(new LearningOutcome {
                LearningId = 24, Name = "3500", Description = "operate a modern relational database to define relations, as well as store and retrieve data", CourseInstanceId = 4
            });
            LOs4.Add(new LearningOutcome {
                LearningId = 25, Name = "3500", Description = "appreciate the collaborative nature of software development by discussing the benefits of peer code reviews", CourseInstanceId = 4
            });



            //4400
            List <LearningOutcome> LOs5 = new List <LearningOutcome>();

            LOs5.Add(new LearningOutcome {
                LearningId = 26, Name = "4400", Description = "explain the objectives and functions of abstraction layers in modern computing systems, including operating systems, programming languages, compilers, and applications", CourseInstanceId = 5
            });
            LOs5.Add(new LearningOutcome {
                LearningId = 27, Name = "4400", Description = "understand cross-layer communications and how each layer of abstraction is implemented in the next layer of abstraction (such as how C programs are translated into assembly code and how C library allocators are implemented in terms of operating system memory management)", CourseInstanceId = 5
            });
            LOs5.Add(new LearningOutcome {
                LearningId = 28, Name = "4400", Description = "analyze how the performance characteristics of one layer of abstraction affect the layers above it (such as how caching and services of the operating system affect the performance of C programs)", CourseInstanceId = 5
            });
            LOs5.Add(new LearningOutcome {
                LearningId = 29, Name = "4400", Description = "construct applications using operating-system concepts (such as processes, threads, signals, virtual memory, I/O)", CourseInstanceId = 5
            });
            LOs5.Add(new LearningOutcome {
                LearningId = 30, Name = "4400", Description = "synthesize operating-system and networking facilities to build concurrent, communicating applications", CourseInstanceId = 5
            });
            LOs5.Add(new LearningOutcome {
                LearningId = 31, Name = "4400", Description = "implement reliable concurrent and parallel programs using appropriate synchronization constructs", CourseInstanceId = 5
            });

            //4540
            List <LearningOutcome> LOs6 = new List <LearningOutcome>();

            LOs6.Add(new LearningOutcome {
                LearningId = 32, Name = "4540", Description = "Construct web pages using modern HTML and CSS practices, including modern frameworks.", CourseInstanceId = 6
            });
            LOs6.Add(new LearningOutcome {
                LearningId = 33, Name = "4540", Description = "Define accessibility and utilize techniques to create accessible web pages.  ", CourseInstanceId = 6
            });
            LOs6.Add(new LearningOutcome {
                LearningId = 34, Name = "4540", Description = "Outline and utilize MVC technologies across the “full-stack” of web design (including front-end, back-end, and databases) to create interesting web applications. Deploy an application to a “Cloud” provider.", CourseInstanceId = 6
            });
            LOs6.Add(new LearningOutcome {
                LearningId = 35, Name = "4540", Description = "Describe the browser security model and HTTP; utilize techniques for data validation, secure session communication, cookies, single sign-on, and separate roles.  ", CourseInstanceId = 6
            });
            LOs6.Add(new LearningOutcome {
                LearningId = 36, Name = "4540", Description = "Utilize JavaScript for simple page manipulations and AJAX for more complex/complete “single-page” applications.", CourseInstanceId = 6
            });
            LOs6.Add(new LearningOutcome {
                LearningId = 37, Name = "4540", Description = "Demonstrate how responsive techniques can be used to construct applications that are usable at a variety of page sizes.  Define and discuss responsive, reactive, and adaptive.", CourseInstanceId = 6
            });
            LOs6.Add(new LearningOutcome {
                LearningId = 38, Name = "4540", Description = "Construct a simple web-crawler for validation of page functionality and data scraping.", CourseInstanceId = 6
            });


            var courses = new Course[]
            {
                new Course {
                    CourseId = 1, CourseNumber = 2100, Year = 2019, Name = "Discrete Structures", Description = "Introduction to propositional logic, predicate logic, formal logical arguments, finite sets, functions, relations, inductive proofs, recurrence relations, graphs, probability, and their applications to Computer Science.", Department = "CS", Semester = "Fall", LearningOutcomes = LOs1, UserId = "3c694a12-8727-44f5-9f53-2c4e0e63ea5f"
                },
                new Course {
                    CourseId = 2, CourseNumber = 2420, Year = 2019, Name = "Introduction to Algorithms & Data Structures", Description = "This course provides an introduction to the problem of engineering computational efficiency into programs. Students will learn about classical algorithms (including sorting, searching, and graph traversal), data structures (including stacks, queues, linked lists, trees, hash tables, and graphs), and analysis of program space and time requirements", Department = "CS", Semester = "Fall", LearningOutcomes = LOs2, UserId = "e727124f-f3be-47c3-9063-398c6cc4cf16"
                },
                new Course {
                    CourseId = 3, CourseNumber = 3500, Year = 2019, Name = "Software Practice I", Description = "Practical exposure to the process of creating large software systems, including requirements specifications, design, implementation, testing, and maintenance. Emphasis on software process, software tools (debuggers, profilers, source code repositories, test harnesses), software engineering techniques (time management, code, and documentation standards, source code management, object-oriented analysis and design), and team development practice. Much of the work will be in groups and will involve modifying preexisting software systems.", Department = "CS", Semester = "Fall", LearningOutcomes = LOs3, UserId = "e727124f-f3be-47c3-9063-398c6cc4cf16"
                },
                new Course {
                    CourseId = 4, CourseNumber = 3500, Year = 2019, Name = "Software Practice I", Description = "Practical exposure to the process of creating large software systems, including requirements specifications, design, implementation, testing, and maintenance. Emphasis on software process, software tools (debuggers, profilers, source code repositories, test harnesses), software engineering techniques (time management, code, and documentation standards, source code management, object-oriented analysis and design), and team development practice. Much of the work will be in groups and will involve modifying preexisting software systems.", Department = "CS", Semester = "Fall", LearningOutcomes = LOs4, UserId = "3c3d6ea3-22c3-4cfb-8ae0-b1eba2663c61"
                },
                new Course {
                    CourseId = 5, CourseNumber = 4400, Year = 2019, Name = "Computer Systems", Description = "Introduction to computer systems from a programmer's point of view.  Machine level representations of programs, optimizing program performance, memory hierarchy, linking, exceptional control flow, measuring program performance, virtual memory, concurrent programming with threads, network programming", Department = "CS", Semester = "Fall", LearningOutcomes = LOs5, UserId = "3c694a12-8727-44f5-9f53-2c4e0e63ea5f"
                },
                new Course {
                    CourseId = 6, CourseNumber = 4540, Year = 2019, Name = "Web Software Architecture", Description = "Software architectures, programming models, and programming environments pertinent to developing web applications.  Topics include client-server model, multi-tier software architecture, client-side scripting (JavaScript), server-side programming (Servlets and JavaServer Pages), component reuse (JavaBeans), database connectivity (JDBC), and web servers.", Department = "CS", Semester = "Fall", LearningOutcomes = LOs6, UserId = "e727124f-f3be-47c3-9063-398c6cc4cf16"
                }
            };

            foreach (Course s in courses)
            {
                context.Courses.Add(s);
            }
            context.SaveChanges();
        }
Пример #3
0
        /// <summary>
        /// Initialize
        /// </summary>
        /// <param name="file">The ONNX file</param>
        public async Task Init(StorageFile file)
        {
            this.model = await LearningModel.LoadFromStorageFileAsync(file);

            this.session = new LearningModelSession(this.model);
        }
Пример #4
0
 public void Init(IRandomAccessStreamReference stream)
 {
     this.model   = LearningModel.LoadFromStream(stream);
     this.session = new LearningModelSession(this.model);
 }
Пример #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Load squeezenet.onnx.");
            using (var model = LearningModel.LoadFromFilePath("squeezenet.onnx"))
            {
                Console.WriteLine("Load kitten_224.png as StorageFile.");
                var name       = AppDomain.CurrentDomain.BaseDirectory + "kitten_224.png";
                var image_task = Windows.Storage.StorageFile.GetFileFromPathAsync(name);
                image_task.AsTask().Wait();
                var image = image_task.GetResults();
                Console.WriteLine("Load StorageFile into Stream.");
                var stream_task = image.OpenReadAsync();
                System.Threading.Thread.Sleep(1000);
                // stream_task.AsTask().Wait();
                //
                // Unable to call AsTask on IAsyncOperation<IRandomAccessStreamWithContentType>...
                // System.TypeInitializationException: 'The type initializer for 'ABI.Windows.Foundation.AsyncOperationCompletedHandler`1' threw an exception.'
                // This exception was originally thrown at this call stack:
                //   System.RuntimeType.ThrowIfTypeNeverValidGenericArgument(System.RuntimeType)
                //   System.RuntimeType.SanityCheckGenericArguments(System.RuntimeType[], System.RuntimeType[])
                //   System.RuntimeType.MakeGenericType(System.Type[])
                //   System.Linq.Expressions.Compiler.DelegateHelpers.MakeNewDelegate(System.Type[])
                //   System.Linq.Expressions.Compiler.DelegateHelpers.MakeDelegateType(System.Type[])
                //   ABI.Windows.Foundation.AsyncOperationCompletedHandler<TResult>.AsyncOperationCompletedHandler()
                //
                // So sleep instead...
                using (var stream = stream_task.GetResults())
                {
                    Console.WriteLine("Create SoftwareBitmap from decoded Stream.");
                    var decoder_task = Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
                    System.Threading.Thread.Sleep(1000);
                    // decoder_task.AsTask().Wait();
                    //
                    // Unable to call AsTask on IAsyncOperation<SoftwareBitmap>...
                    // System.TypeInitializationException: 'The type initializer for 'ABI.Windows.Foundation.AsyncOperationCompletedHandler`1' threw an exception.'
                    // This exception was originally thrown at this call stack:
                    //   System.RuntimeType.ThrowIfTypeNeverValidGenericArgument(System.RuntimeType)
                    //   System.RuntimeType.SanityCheckGenericArguments(System.RuntimeType[], System.RuntimeType[])
                    //   System.RuntimeType.MakeGenericType(System.Type[])
                    //   System.Linq.Expressions.Compiler.DelegateHelpers.MakeNewDelegate(System.Type[])
                    //   System.Linq.Expressions.Compiler.DelegateHelpers.MakeDelegateType(System.Type[])
                    //   ABI.Windows.Foundation.AsyncOperationCompletedHandler<TResult>.AsyncOperationCompletedHandler()
                    //
                    // So sleep instead...
                    var decoder = decoder_task.GetResults();
                    var software_bitmap_task = decoder.GetSoftwareBitmapAsync();
                    System.Threading.Thread.Sleep(1000);
                    // software_bitmap_task.AsTask().Wait();
                    //
                    // Unable to call AsTask on IAsyncOperation<SoftwareBitmap>...
                    // System.TypeInitializationException: 'The type initializer for 'ABI.Windows.Foundation.AsyncOperationCompletedHandler`1' threw an exception.'
                    // This exception was originally thrown at this call stack:
                    //   System.RuntimeType.ThrowIfTypeNeverValidGenericArgument(System.RuntimeType)
                    //   System.RuntimeType.SanityCheckGenericArguments(System.RuntimeType[], System.RuntimeType[])
                    //   System.RuntimeType.MakeGenericType(System.Type[])
                    //   System.Linq.Expressions.Compiler.DelegateHelpers.MakeNewDelegate(System.Type[])
                    //   System.Linq.Expressions.Compiler.DelegateHelpers.MakeDelegateType(System.Type[])
                    //   ABI.Windows.Foundation.AsyncOperationCompletedHandler<TResult>.AsyncOperationCompletedHandler()
                    //
                    // So sleep instead...
                    using (var software_bitmap = software_bitmap_task.GetResults())
                    {
                        Console.WriteLine("Create VideoFrame.");
                        var frame = Windows.Media.VideoFrame.CreateWithSoftwareBitmap(software_bitmap);

                        Console.WriteLine("Create LearningModelSession.");
                        using (var session = new LearningModelSession(model))
                        {
                            Console.WriteLine("Create LearningModelBinding.");
                            var binding = new LearningModelBinding(session);
                            Console.WriteLine("Bind data_0.");
                            binding.Bind("data_0", frame);
                            Console.WriteLine("Evaluate.");
                            var results = session.Evaluate(binding, "");
                        }
                        Console.WriteLine("Success!\n");
                    }
                }
            }
        }
Пример #6
0
    public async Task LoadModelAsync(bool shouldUseGpu, bool resourceLoad)
    {
        try
        {
            // Parse labels from label file
            var labelsTextAsset = Resources.Load(LabelsFileName) as TextAsset;
            using (var streamReader = new StringReader(labelsTextAsset.text))
            {
                string line       = "";
                char[] charToTrim = { '\"', ' ' };
                while (streamReader.Peek() >= 0)
                {
                    line = streamReader.ReadLine();
                    line.Trim(charToTrim);
                    var indexAndLabel = line.Split(':');
                    if (indexAndLabel.Count() == 2)
                    {
                        _labels.Add(indexAndLabel[1]);
                    }
                }
            }

#if ENABLE_WINMD_SUPPORT
            if (resourceLoad)
            {
                // Load from Unity Resources via awkward UWP streams and initialize model
                using (var modelStream = new InMemoryRandomAccessStream())
                {
                    var dataWriter    = new DataWriter(modelStream);
                    var modelResource = Resources.Load(ModelFileName) as TextAsset;
                    dataWriter.WriteBytes(modelResource.bytes);
                    await dataWriter.StoreAsync();

                    var randomAccessStream = RandomAccessStreamReference.CreateFromStream(modelStream);

                    _model = await LearningModel.LoadFromStreamAsync(randomAccessStream);

                    var deviceKind = shouldUseGpu ? LearningModelDeviceKind.DirectXHighPerformance : LearningModelDeviceKind.Cpu;
                    _session = new LearningModelSession(_model, new LearningModelDevice(deviceKind));
                }
            }
            else
            {
                try
                {
                    var modelFile = await StorageFile.GetFileFromApplicationUriAsync(
                        new Uri($"ms-appx:///Data/StreamingAssets/SqueezeNet.onnx"));

                    _model = await LearningModel.LoadFromStorageFileAsync(modelFile);

                    var deviceKind = shouldUseGpu ? LearningModelDeviceKind.DirectXHighPerformance : LearningModelDeviceKind.Cpu;
                    _session = new LearningModelSession(_model, new LearningModelDevice(deviceKind));
                }
                catch (Exception e)
                {
                    var exceptionStr = e.ToString();
                    //StatusBlock.text = exceptionStr;
                }
            }

            // Get model input and output descriptions
            var inputImageDescription =
                _model.InputFeatures.FirstOrDefault(feature => feature.Kind == LearningModelFeatureKind.Image)
                as ImageFeatureDescriptor;
            // Check if input is passed as image if not try to interpret it as generic tensor
            if (inputImageDescription != null)
            {
                InputWidth  = inputImageDescription.Width;
                InputHeight = inputImageDescription.Height;
            }
            else
            {
                var inputTensorDescription =
                    _model.InputFeatures.FirstOrDefault(feature => feature.Kind == LearningModelFeatureKind.Tensor)
                    as TensorFeatureDescriptor;
                InputWidth  = (uint)inputTensorDescription.Shape[3];
                InputHeight = (uint)inputTensorDescription.Shape[2];
            }

            _outputDescription =
                _model.OutputFeatures.FirstOrDefault(feature => feature.Kind == LearningModelFeatureKind.Tensor)
                as TensorFeatureDescriptor;
#endif
        }
        catch
        {
#if ENABLE_WINMD_SUPPORT
            _model = null;
#endif
            throw;
        }
    }
Пример #7
0
 public void UnitTrainEmoTest()
 {
     Assert.IsNotNull(LearningModel.Train(FalseTrain()));
 }
Пример #8
0
        private void Accept_Click(object sender, RoutedEventArgs e)
        {
            if ((UseInternalDataChbx.IsChecked.HasValue && UseInternalDataChbx.IsChecked.Value) ||
                (!String.IsNullOrEmpty(HALVfileNameTextBox.Text) &&
                 !String.IsNullOrEmpty(HAHVfileNameTextBox.Text) &&
                 !String.IsNullOrEmpty(LALVfileNameTextBox.Text) &&
                 !String.IsNullOrEmpty(LAHVfileNameTextBox.Text)))
            {
                try
                {
                    Console.WriteLine("empezando");
                    var dict = new Dictionary <TagType, List <List <double[]> > >();

                    Console.WriteLine("------------------------------------------------------------");
                    Console.WriteLine("A procesar HALV, faltan 4");
                    if (UseInternalDataChbx.IsChecked.HasValue && UseInternalDataChbx.IsChecked.Value)
                    {
                        //dict.Add(TagType.HALV, ReadFromData(Data.HALV.data));
                    }
                    else if (System.IO.Path.GetExtension(HALVfileNameTextBox.Text).Equals(".tsv"))
                    {
                        var halvFile   = new StreamReader(HALVfileNameTextBox.Text);
                        var halvString = halvFile.ReadToEnd();
                        dict.Add(TagType.HALV, ReadTsv(halvString));
                    }
                    else if (System.IO.Path.GetExtension(HALVfileNameTextBox.Text).Equals(".db") ||
                             System.IO.Path.GetExtension(HALVfileNameTextBox.Text).Equals(".sqlite") ||
                             System.IO.Path.GetExtension(HALVfileNameTextBox.Text).Equals(".sqlite3"))
                    {
                        dict.Add(TagType.HALV, ReadSqlite(HALVfileNameTextBox.Text));
                    }


                    Console.WriteLine("------------------------------------------------------------");
                    Console.WriteLine("A procesar HAHV, faltan 3");
                    if (UseInternalDataChbx.IsChecked.HasValue && UseInternalDataChbx.IsChecked.Value)
                    {
                        //dict.Add(TagType.HAHV, ReadFromData(Data.HAHV.data));
                    }
                    else if (System.IO.Path.GetExtension(HAHVfileNameTextBox.Text).Equals(".tsv"))
                    {
                        var hahvFile   = new StreamReader(HAHVfileNameTextBox.Text);
                        var hahvString = hahvFile.ReadToEnd();
                        dict.Add(TagType.HAHV, ReadTsv(hahvString));
                    }
                    else if (System.IO.Path.GetExtension(HAHVfileNameTextBox.Text).Equals(".db") ||
                             System.IO.Path.GetExtension(HALVfileNameTextBox.Text).Equals(".sqlite") ||
                             System.IO.Path.GetExtension(HALVfileNameTextBox.Text).Equals(".sqlite3"))
                    {
                        dict.Add(TagType.HAHV, ReadSqlite(HAHVfileNameTextBox.Text));
                    }

                    Console.WriteLine("------------------------------------------------------------");
                    Console.WriteLine("A procesar LALV, faltan 2");
                    if (UseInternalDataChbx.IsChecked.HasValue && UseInternalDataChbx.IsChecked.Value)
                    {
                        //dict.Add(TagType.LALV, ReadFromData(Data.LALV.data));
                    }
                    else if (System.IO.Path.GetExtension(LALVfileNameTextBox.Text).Equals(".tsv"))
                    {
                        var lalvFile   = new StreamReader(LALVfileNameTextBox.Text);
                        var lalvString = lalvFile.ReadToEnd();
                        dict.Add(TagType.LALV, ReadTsv(lalvString));
                    }
                    else if (System.IO.Path.GetExtension(LALVfileNameTextBox.Text).Equals(".db") ||
                             System.IO.Path.GetExtension(HALVfileNameTextBox.Text).Equals(".sqlite") ||
                             System.IO.Path.GetExtension(HALVfileNameTextBox.Text).Equals(".sqlite3"))
                    {
                        dict.Add(TagType.LALV, ReadSqlite(LALVfileNameTextBox.Text));
                    }

                    Console.WriteLine("------------------------------------------------------------");
                    Console.WriteLine("A procesar LAHV, falta 1");
                    if (UseInternalDataChbx.IsChecked.HasValue && UseInternalDataChbx.IsChecked.Value)
                    {
                        //dict.Add(TagType.LAHV, ReadFromData(Data.LAHV.data));
                    }
                    else if (System.IO.Path.GetExtension(LAHVfileNameTextBox.Text).Equals(".tsv"))
                    {
                        var lahvFile   = new StreamReader(LAHVfileNameTextBox.Text);
                        var lahvString = lahvFile.ReadToEnd();
                        dict.Add(TagType.LAHV, ReadTsv(lahvString));
                    }
                    else if (System.IO.Path.GetExtension(LAHVfileNameTextBox.Text).Equals(".db") ||
                             System.IO.Path.GetExtension(HALVfileNameTextBox.Text).Equals(".sqlite") ||
                             System.IO.Path.GetExtension(HALVfileNameTextBox.Text).Equals(".sqlite3"))
                    {
                        dict.Add(TagType.LAHV, ReadSqlite(LAHVfileNameTextBox.Text));
                    }


                    Console.WriteLine("procesados, ahora a entrenar");
                    LearningModel.Train(dict);

                    //TODO: terminó bien
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"error: {ex}");
                }
            }
        }
        // This method is executed by the ThreadPoolTimer, it performs the evaluation on a copy of the VideoFrame
        private async void EvaluateVideoFrame(ThreadPoolTimer timer)
        {
            if (semaphore == null)
            {
                return;
            }

            if (!modelCreated)
            {
                Debug.WriteLine($"EvaluateVideoFrame Skipped - LearningModel Not Ready.");
                return;
            }

            // If a lock is being held, or WinML isn't fully initialized, return
            if (!semaphore.Wait(0))
            {
                Debug.WriteLine($"EvaluateVideoFrame Skipped - Waiting Semaphore Access");
                return;
            }

            if (session == null)
            {
                try
                {
                    Debug.WriteLine($"Attempting to create LearningModelSession using DeviceKind: {detectedDeviceKind}");

                    session = new LearningModelSession(model, new LearningModelDevice(detectedDeviceKind));

                    Debug.WriteLine($"LearningModelSession successfully created.");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Error Creating Session: {ex.Message}");
                    model = null;
                    return;
                }
            }

            Debug.WriteLine($"*************** Evaluating Video Frame [START] ***************");

            try
            {
                using (videoFrameToProcess)
                {
                    // ************ WinML Evaluate Frame ************ //

                    Debug.WriteLine($"VideoFrame RelativeTime: {videoFrameToProcess.RelativeTime?.Seconds}s");

                    // Create a binding object from the session
                    binding = new LearningModelBinding(session);

                    // Create an image tensor from a video frame
                    var image = ImageFeatureValue.CreateFromVideoFrame(videoFrameToProcess);

                    // The YOLO model's input name is "image" and output name is "grid"
                    var inputName  = "image";
                    var outputName = "grid";

                    // Bind the image to the input
                    binding.Bind(inputName, image);

                    // Process the frame with the model
                    var results = await session.EvaluateAsync(binding, $"YoloRun {++runCount}");

                    Debug.WriteLine($"Evaluation Result Success? {results.Succeeded} ");

                    if (!results.Succeeded)
                    {
                        return;
                    }

                    Debug.WriteLine($" **** {results.Outputs.Count} Outputs Available ***** ");

                    foreach (var output in results.Outputs)
                    {
                        Debug.WriteLine($" - {output.Key}");
                    }

                    // Retrieve the results of evaluation
                    var resultTensor = results.Outputs[outputName] as TensorFloat;

                    Debug.WriteLine($"Result Feature Kind: {resultTensor?.Kind.ToString()} ");

                    var resultVector = resultTensor?.GetAsVectorView();

                    // Remove overlapping and low confidence bounding boxes
                    filteredBoxes = parser.NonMaxSuppress(parser.ParseOutputs(resultVector?.ToArray()), 5, .5F);

                    Debug.WriteLine(filteredBoxes.Count <= 0 ? $"No Valid Bounding Boxes" : $"Valid Bounding Boxes: {filteredBoxes.Count}");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error: EvaluateFrameException: {ex}");
            }
            finally
            {
                semaphore?.Release();

                Debug.WriteLine($"*************** Evaluating Video Frame [END] ***************");
            }
        }
 public LearningOutcomeController(LearningModel context)
 {
     _context = context;
 }
Пример #11
0
        private void btnOgren_Click(object sender, EventArgs e)
        {
            try
            {
                GuvenlikOzellikleri go = GuvenlikOzellikleri.YOK;
                IcDonanim           id = IcDonanim.YOK;

                if (cbAbs.Checked)
                {
                    go = go | GuvenlikOzellikleri.Seviye1;
                }
                else if (cbAsr.Checked)
                {
                    go = go | GuvenlikOzellikleri.Seviye2;
                }
                else if (cbEsp.Checked)
                {
                    go = go | GuvenlikOzellikleri.Seviye3;
                }
                else if (cbKumasKoltuk.Checked)
                {
                    id = id | IcDonanim.Seviye1;
                }
                else if (cbKlima.Checked)
                {
                    id = id | IcDonanim.Seviye2;
                }
                else if (cbDeriKoltuk.Checked)
                {
                    id = id | IcDonanim.Seviye3;
                }
                else if (cbYolBilgsayarı.Checked)
                {
                    id = id | IcDonanim.Seviye4;
                }

                Otomobiller.Add(new Otomobil(int.Parse(txtFiyat.Text), int.Parse(txtYıl.Text), int.Parse(txtKm.Text), cbOtomatik.Checked ? Vites.Otomatik : Vites.Manuel, cbDizel.Checked ? Yakit.Dizel : Yakit.Benzin, int.Parse(txtMotorHacmi.Text), int.Parse(txtMotorGucu.Text), cbGaranti.Checked, cbTakas.Checked, cbSıfır.Checked ? Durum.Sıfır : Durum.IkinciEl, go, id, int.Parse(txtBoyalıSayısı.Text), int.Parse(txtDegisenSayısı.Text), cbAlınır.Checked));

                if (Otomobiller.Count < 2)
                {
                    MessageBox.Show("Öğrenme Yapılabilmesi için en az 2 kayıt olması gerek");
                    lblDurum.ForeColor = Color.Green;
                    lblDurum.Text      = "Kayıt eklendi.";
                    return;
                }
                var d = Descriptor.Create <Otomobil>();
                var g = new DecisionTreeGenerator(d);
                g.SetHint(true);
                Model = Learner.Learn(Otomobiller, 0.80, 1000, g);

                lblDurum.ForeColor = Color.Green;
                lblDurum.Text      = "Öğrenme Yapıldı : Doğruluk:" + Model.Accuracy;
                btnOgren.Enabled   = false;
                linkLabel1.Visible = true;
            }
            catch (Exception)
            {
                lblDurum.ForeColor = Color.DarkRed;
                lblDurum.Text      = "Otomobil eklenemedi.";
                linkLabel1.Visible = false;
            }
        }
        /// <summary>
        /// Load the labels and model and initialize WinML
        /// </summary>
        /// <returns></returns>
        private async Task LoadModelAsync(string modelFileName)
        {
            Debug.WriteLine("LoadModelAsync");
            _evaluationLock.Wait();
            {
                m_binding       = null;
                m_model         = null;
                m_session       = null;
                _isReadyForEval = false;

                try
                {
                    // Start stopwatch
                    _perfStopwatch.Restart();

                    // Load Model
                    StorageFile modelFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Assets/{modelFileName}.onnx"));

                    m_model = await LearningModel.LoadFromStorageFileAsync(modelFile);

                    // Stop stopwatch
                    _perfStopwatch.Stop();

                    // Setting preferred inference device given user's intent
                    m_inferenceDeviceSelected = _useGPU ? LearningModelDeviceKind.DirectXHighPerformance : LearningModelDeviceKind.Cpu;
                    m_session = new LearningModelSession(m_model, new LearningModelDevice(m_inferenceDeviceSelected));

                    // Debugging logic to see the input and output of ther model and retrieve dimensions of input/output variables
                    // ### DEBUG ###
                    foreach (var inputF in m_model.InputFeatures)
                    {
                        Debug.WriteLine($"input | kind:{inputF.Kind}, name:{inputF.Name}, type:{inputF.GetType()}");
                        int i = 0;
                        ImageFeatureDescriptor  imgDesc = inputF as ImageFeatureDescriptor;
                        TensorFeatureDescriptor tfDesc  = inputF as TensorFeatureDescriptor;
                        m_inWidth  = (uint)(imgDesc == null ? tfDesc.Shape[3] : imgDesc.Width);
                        m_inHeight = (uint)(imgDesc == null ? tfDesc.Shape[2] : imgDesc.Height);
                        m_inName   = inputF.Name;

                        Debug.WriteLine($"N: {(imgDesc == null ? tfDesc.Shape[0] : 1)}, " +
                                        $"Channel: {(imgDesc == null ? tfDesc.Shape[1].ToString() : imgDesc.BitmapPixelFormat.ToString())}, " +
                                        $"Height:{(imgDesc == null ? tfDesc.Shape[2] : imgDesc.Height)}, " +
                                        $"Width: {(imgDesc == null ? tfDesc.Shape[3] : imgDesc.Width)}");
                    }
                    foreach (var outputF in m_model.OutputFeatures)
                    {
                        Debug.WriteLine($"output | kind:{outputF.Kind}, name:{outputF.Name}, type:{outputF.GetType()}");
                        int i = 0;
                        ImageFeatureDescriptor  imgDesc = outputF as ImageFeatureDescriptor;
                        TensorFeatureDescriptor tfDesc  = outputF as TensorFeatureDescriptor;
                        m_outWidth  = (uint)(imgDesc == null ? tfDesc.Shape[3] : imgDesc.Width);
                        m_outHeight = (uint)(imgDesc == null ? tfDesc.Shape[2] : imgDesc.Height);
                        m_outName   = outputF.Name;

                        Debug.WriteLine($"N: {(imgDesc == null ? tfDesc.Shape[0] : 1)}, " +
                                        $"Channel: {(imgDesc == null ? tfDesc.Shape[1].ToString() : imgDesc.BitmapPixelFormat.ToString())}, " +
                                        $"Height:{(imgDesc == null ? tfDesc.Shape[2] : imgDesc.Height)}, " +
                                        $"Width: {(imgDesc == null ? tfDesc.Shape[3] : imgDesc.Width)}");
                    }
                    // ### END OF DEBUG ###

                    // Create output frame
                    _outputFrame?.Dispose();
                    _outputFrame = new VideoFrame(BitmapPixelFormat.Bgra8, (int)m_outWidth, (int)m_outHeight);

                    Debug.WriteLine($"Elapsed time: {_perfStopwatch.ElapsedMilliseconds} ms");

                    _isReadyForEval = true;
                }
                catch (Exception ex)
                {
                    NotifyUser($"error: {ex.Message}", NotifyType.ErrorMessage);
                    Debug.WriteLine($"error: {ex.Message}");
                }
            }
            _evaluationLock.Release();
        }
Пример #13
0
 public HomeController(LearningModel context, RoleManager <IdentityRole> rolecontext, UserManager <IdentityUser> usercontext)
 {
     _context     = context;
     _rolecontext = rolecontext;
     _usercontext = usercontext;
 }