示例#1
0
        public TemporaryWorkspace(SolutionInfo solutionInfo)
            : base(RoslynServices.HostServices, workspaceKind: TemporaryWorkspace.WorkspaceKind_TemporaryWorkspace)
        {
            Options = Options.WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0);

            this.OnSolutionAdded(solutionInfo);
        }
示例#2
0
    public static SolutionInfo GetSolutionInfo(int universityId)
    {
        var now = DateTime.Now;
        if ((now - lastInfoCacheTime).TotalMinutes > 15) {
            solutionInfoCache.Clear();
            lastInfoCacheTime = now;
        }

        if (solutionInfoCache.ContainsKey(universityId))
            return solutionInfoCache[universityId];

        var reader = File.OpenText(HttpContext.Current.Server.MapPath("Universities/List"));
        var start = universityId + ";";
        while (!reader.EndOfStream) {
            var line = reader.ReadLine();
            if (line.StartsWith(start)) {
                var items = line.Split(';');
                var info = new SolutionInfo() {
                    Name = items[1],
                    BaseUrl = items[3],
                    AttachedValues = items[9] != "" ? Json.Parse<string[]>(items[9]) : new string[0]
                };
                solutionInfoCache[universityId] = info;
                reader.Close();
                reader.Dispose();
                return info;
            }
        }
        reader.Close();
        reader.Dispose();
        return null;
    }
示例#3
0
        /// <summary>
        /// Adds an entire solution to the workspace, replacing any existing solution.
        /// </summary>
        public Solution AddSolution(SolutionInfo solutionInfo)
        {
            if (solutionInfo == null)
            {
                throw new ArgumentNullException(nameof(solutionInfo));
            }

            lock (_gate)
            {
                this.OnSolutionAdded(solutionInfo);
                this.UpdateReferencesAfterAdd();

                return this.CurrentSolution;
            }
        }
示例#4
0
        /// <summary>
        /// Computes model by solving optimization problem
        /// </summary>
        /// <returns>Model</returns>
        public override Model <SparseVec> ComputeModel()
        {
            Stopwatch timer = Stopwatch.StartNew();

            int problemSize = problem.ElementsCount;
            //float[] alphaResult = new float[problem.ElementsCount];

            SolutionInfo si = new SolutionInfo();

            Solve(problem.Y, si);

            timer.Stop();
            Model <SparseVec> model = new Model <SparseVec>();

            model.NumberOfClasses = 2;
            model.Alpha           = alpha;//alphaResult;
            model.Bias            = si.rho;
            model.Iter            = si.iter;
            model.Obj             = si.obj;
            model.ModelTime       = timer.Elapsed;
            model.ModelTimeMs     = timer.ElapsedMilliseconds;

            //------------------
            List <SparseVec> supportElements = new List <SparseVec>(alpha.Length);
            List <int>       suporrtIndexes  = new List <int>(alpha.Length);
            List <float>     supportLabels   = new List <float>(alpha.Length);

            for (int j = 0; j < alpha.Length; j++)
            {
                if (Math.Abs(alpha[j]) > 0)
                {
                    supportElements.Add(problem.Elements[j]);
                    suporrtIndexes.Add(j);
                    supportLabels.Add(problem.Y[j]);
                }
            }
            model.SupportElements        = supportElements.ToArray();
            model.SupportElementsIndexes = suporrtIndexes.ToArray();
            model.Y = supportLabels.ToArray();



            return(model);
        }
            internal Task <(MonoDevelop.Projects.Solution, SolutionInfo)> CreateSolutionInfoFromCache(MonoDevelop.Projects.Solution sol, CancellationToken ct)
            {
                return(Task.Run(delegate {
                    return CreateSolutionInfoFromCacheInternal(sol, ct);
                }));

                async Task <(MonoDevelop.Projects.Solution, SolutionInfo)> CreateSolutionInfoFromCacheInternal(MonoDevelop.Projects.Solution solution, CancellationToken token)
                {
                    projections.ClearOldProjectionList();
                    solutionData = new SolutionData();

                    workspaceCache.Load(solution);

                    var projectInfos = await CreateProjectInfosFromCache(solution.GetAllProjects(), token).ConfigureAwait(false);

                    if (projectInfos == null)
                    {
                        return(solution, null);
                    }

                    if (token.IsCancellationRequested)
                    {
                        return(solution, null);
                    }

                    var solutionId   = GetSolutionId(solution);
                    var solutionInfo = SolutionInfo.Create(solutionId, VersionStamp.Create(), solution.FileName, projectInfos);

                    lock (addLock) {
                        if (!added)
                        {
                            added = true;
                            OnSolutionOpened(workspace, solutionInfo);
                        }
                    }

                    // Clear modified projects during load. The projects will be loaded later.
                    lock (workspace.projectModifyLock) {
                        workspace.modifiedProjects.RemoveAll(p => p.ParentSolution == solution);
                    }

                    return(solution, solutionInfo);
                }
            }
            internal Task <(MonoDevelop.Projects.Solution, SolutionInfo)> CreateSolutionInfo(MonoDevelop.Projects.Solution sol, CancellationToken ct)
            {
                return(Task.Run(delegate {
                    return CreateSolutionInfoInternal(sol, ct);
                }));

                async Task <(MonoDevelop.Projects.Solution, SolutionInfo)> CreateSolutionInfoInternal(MonoDevelop.Projects.Solution solution, CancellationToken token)
                {
                    using (var timer = Counters.AnalysisTimer.BeginTiming()) {
                        projections.ClearOldProjectionList();

                        solutionData = new SolutionData();

                        var projectInfos = await CreateProjectInfos(solution.GetAllProjects(), token).ConfigureAwait(false);

                        if (IsModifiedWhileLoading(solution))
                        {
                            return(await CreateSolutionInfoInternal(solution, token).ConfigureAwait(false));
                        }

                        if (token.IsCancellationRequested)
                        {
                            return(solution, null);
                        }

                        var solutionId   = GetSolutionId(solution);
                        var solutionInfo = SolutionInfo.Create(solutionId, VersionStamp.Create(), solution.FileName, projectInfos);

                        lock (addLock) {
                            if (!added)
                            {
                                added = true;
                                OnSolutionOpened(workspace, solutionInfo);
                            }
                        }
                        // Check for modified projects here after the solution has been added to the workspace
                        // in case a NuGet package restore finished after the IsModifiedWhileLoading check. This
                        // ensures the type system does not have missing references that may have been added by
                        // the restore.
                        ReloadModifiedProjects();
                        return(solution, solutionInfo);
                    }
                }
            }
示例#7
0
        public Document CreateDocument(string text)
        {
            var workspace = new AdhocWorkspace();
            var solution  = workspace.AddSolution(SolutionInfo.Create(
                                                      SolutionId.CreateNewId(),
                                                      VersionStamp.Default
                                                      ));
            var projectId = ProjectId.CreateNewId();
            var project   = solution.AddProject(ProjectInfo.Create(
                                                    projectId,
                                                    VersionStamp.Default,
                                                    "TestSuite",
                                                    "TestSuite",
                                                    LanguageNames.CSharp
                                                    )).GetProject(projectId);
            var document = project.AddDocument("Test.cs", text);

            return(document);
        }
示例#8
0
        private double GeneralSolutionScore(ExamDetailSubmitInfo detail)
        {
            double score = 0;

            foreach (int solutionId in detail.solutionId)
            {
                QuestionInfo question = _questionApp.Load(detail.questionId);
                SolutionInfo solution = _questionApp.QuerySolution(p => p.QuestionId.Equals(detail.questionId) && p.SolutionId.Equals(solutionId));
                if (solution.IsCorrect)
                {
                    score += solution.Score;
                }
                else
                {
                    score -= solution.Score;
                }
            }
            return(score);
        }
示例#9
0
        public async Task LoadFileOrProjectAsync(MainWindow mainWindow1, string filename)
        {
            if (filename != null && filename.EndsWith(".csproj"))
            {
                await LoadProjectAsync(mainWindow1, filename);

                return;
            }
            if (filename != null && filename.EndsWith(".sln"))
            {
                await LoadSolutionAsync(mainWindow1, filename);

                return;
            }

            var w = mainWindow1._workspace = new AdhocWorkspace(mainWindow1._host);

            w.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create()));
            var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(),
                                                 "Code Project", "code", LanguageNames.CSharp);
            var w2 = w.CurrentSolution.AddProject(projectInfo);

            w.TryApplyChanges(w2);

            DocumentInfo documentInfo;

            if (filename != null)
            {
                documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(projectInfo.Id), "Default",
                                                   null, SourceCodeKind.Regular, new FileTextLoader(filename, Encoding.UTF8), filename);
            }
            else
            {
                documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(projectInfo.Id), "Default",
                                                   null, SourceCodeKind.Regular);
            }

            w2 = w.CurrentSolution.AddDocument(documentInfo);
            w.TryApplyChanges(w2);

            mainWindow1.Project  = w.CurrentSolution.GetProject(projectInfo.Id);
            mainWindow1.Document = w.CurrentSolution.GetDocument(documentInfo.Id);
        }
        private void Given_a_solution_with_n_projects()
        {
            _workspace = new AdhocWorkspace();
            var si = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default);

            _workspace.AddSolution(si);
            _sln = _workspace.CurrentSolution;
            // TODO: Generate random data.
            _projs = new[] {
                ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "ProjectName", "ProjectName", "C#"),
                ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "ProjectName2", "ProjectName2", "C#")
            };
            foreach (var proj in _projs)
            {
                _workspace.AddProject(proj);
                _sln = _sln.AddProject(proj);
            }
            _workspace.TryApplyChanges(_sln);
        }
示例#11
0
文件: IO.cs 项目: lbm7926/Imp
    public static SolutionInfo Load(string path)
    {
        SolutionInfo result;

        try
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            using (Stream stream = new FileStream(path, FileMode.Open))
            {
                SolutionInfo solutionInfo = binaryFormatter.Deserialize(stream) as SolutionInfo;
                result = solutionInfo;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return(result);
    }
            //[Fact]
            //public void WhenCalculatingEventCouplingsThenIncludesEventDependencies()
            //{
            //    var testee = CreateTestee();

            //    var couplings = testee.Calculate(this.GetEvent("EventA")).ToList();

            //    Assert.true(couplings, Has.Some.Matches<ITypeCoupling>(x => x.Namespace == "System" && x.TypeName == "EventHandler" && x.Assembly == "mscorlib"));
            //}

            private Solution CreateSolution(params string[] code)
            {
                using (var workspace = new AdhocWorkspace())
                {
                    workspace.AddSolution(
                        SolutionInfo.Create(
                            SolutionId.CreateNewId("Semantic"),
                            VersionStamp.Default));
                    var x         = 1;
                    var projectId = ProjectId.CreateNewId("testcode");
                    var solution  = workspace.CurrentSolution.AddProject(projectId, "testcode", "testcode.dll", LanguageNames.CSharp)
                                    .AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(object).Assembly.Location));
                    solution = code.Aggregate(
                        solution,
                        (sol, c) => sol.AddDocument(DocumentId.CreateNewId(projectId), $"TestClass{x++}.cs", c));

                    return(solution);
                }
            }
示例#13
0
        public async Task <BufferedCommandResult> RunAsync(SolutionInfo solutionInfo)
        {
            string runCommand = CppCommands.Run(solutionInfo);
            string command    = DockerCommands.Exec(this, runCommand);

            Console.WriteLine(command);

            using var cts = new CancellationTokenSource();
            cts.CancelAfter(TimeSpan.FromSeconds(ContainerConfiguration.ProcessTimeoutSeconds));

            BufferedCommandResult result = await Cli.Wrap(ContainerConfiguration.DefaultShell)
                                           .WithArguments(command)
                                           .WithValidation(CommandResultValidation.None)
                                           .ExecuteBufferedAsync(cts.Token); // cts

            // throws OperationCanceledException

            return(result);
        }
示例#14
0
        private string GetSolutionInfo(SolutionInfo type)
        {
            string solutionFolder, solutionName, optFile;

            _solution.GetSolutionInfo(out solutionFolder, out solutionName, out optFile);

            switch (type)
            {
            case SolutionInfo.Folder:
                return(solutionFolder);

            case SolutionInfo.Name:
                return(solutionName);

            case SolutionInfo.UserOptionFile:
                return(optFile);
            }
            return(string.Empty);
        }
示例#15
0
        public async Task RunClangTidyAsync(int aCommandId, CommandUILocation commandUILocation)
        {
            await PrepareCommmandAsync(commandUILocation);

            await Task.Run(() =>
            {
                try
                {
                    using (var silentFileController = new SilentFileChangerController())
                    {
                        using (var fileChangerWatcher = new FileChangerWatcher())
                        {
                            SettingsProvider settingsProvider = new SettingsProvider();
                            TidySettingsModel tidySettings    = settingsProvider.GetTidySettingsModel();

                            if (CommandIds.kTidyFixId == aCommandId || tidySettings.TidyOnSave)
                            {
                                fileChangerWatcher.OnChanged += FileOpener.Open;

                                var dte2 = VsServiceProvider.GetService(typeof(DTE)) as DTE2;
                                string solutionFolderPath = SolutionInfo.IsOpenFolderModeActive() ?
                                                            dte2.Solution.FullName : dte2.Solution.FullName
                                                            .Substring(0, dte2.Solution.FullName.LastIndexOf('\\'));

                                fileChangerWatcher.Run(solutionFolderPath);

                                FilePathCollector fileCollector = new FilePathCollector();
                                var filesPath = fileCollector.Collect(mItemsCollector.Items).ToList();

                                silentFileController.SilentFiles(filesPath);
                                silentFileController.SilentFiles(dte2.Documents);
                            }
                            RunScript(aCommandId);
                        }
                    }
                }
                catch (Exception exception)
                {
                    VsShellUtilities.ShowMessageBox(AsyncPackage, exception.Message, "Error",
                                                    OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                }
            });
        }
示例#16
0
        public async Task UpdaterService()
        {
            var exportProvider = ExportProviderCache
                                 .GetOrCreateExportProviderFactory(ServiceTestExportProvider.CreateAssemblyCatalog()
                                                                   .WithParts(typeof(InProcRemoteHostClientProvider.Factory), typeof(CSharpOptionsSerializationService)))
                                 .CreateExportProvider();

            using var workspace = new AdhocWorkspace(TestHostServices.CreateHostServices(exportProvider));

            var options = workspace.CurrentSolution.Options
                          .WithChangedOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1)
                          .WithChangedOption(RemoteTestHostOptions.RemoteHostTest, true);

            workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options));

            var listenerProvider = exportProvider.GetExportedValue <AsynchronousOperationListenerProvider>();

            var checksumUpdater = new SolutionChecksumUpdater(workspace, listenerProvider, CancellationToken.None);
            var service         = workspace.Services.GetRequiredService <IRemoteHostClientProvider>();

            // make sure client is ready
            using var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None);

            // add solution, change document
            workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));
            var project  = workspace.AddProject("proj", LanguageNames.CSharp);
            var document = workspace.AddDocument(project.Id, "doc.cs", SourceText.From("code"));

            workspace.ApplyTextChanges(document.Id, new[] { new TextChange(new TextSpan(0, 1), "abc") }, CancellationToken.None);

            // wait for listener
            var workspaceListener = listenerProvider.GetWaiter(FeatureAttribute.Workspace);
            await workspaceListener.ExpeditedWaitAsync();

            var listener = listenerProvider.GetWaiter(FeatureAttribute.SolutionChecksumUpdater);
            await listener.ExpeditedWaitAsync();

            // checksum should already exist
            Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out _));

            checksumUpdater.Shutdown();
        }
示例#17
0
        internal static async Task <IReadOnlyList <Diagnostic> > RunGenerator(
            string code, bool compile = false, LanguageVersion langVersion = LanguageVersion.Preview, MetadataReference[]?additionalRefs = null, bool allowUnsafe = false, CancellationToken cancellationToken = default)
        {
            var proj = new AdhocWorkspace()
                       .AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create()))
                       .AddProject("RegexGeneratorTest", "RegexGeneratorTest.dll", "C#")
                       .WithMetadataReferences(additionalRefs is not null ? References.Concat(additionalRefs) : References)
                       .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: allowUnsafe)
                                               .WithNullableContextOptions(NullableContextOptions.Enable))
                       .WithParseOptions(new CSharpParseOptions(langVersion))
                       .AddDocument("RegexGenerator.g.cs", SourceText.From(code, Encoding.UTF8)).Project;

            Assert.True(proj.Solution.Workspace.TryApplyChanges(proj.Solution));

            Compilation?comp = await proj !.GetCompilationAsync(CancellationToken.None).ConfigureAwait(false);

            Debug.Assert(comp is not null);

            var generator = new RegexGenerator();
            CSharpGeneratorDriver    cgd = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(langVersion));
            GeneratorDriver          gd  = cgd.RunGenerators(comp !, cancellationToken);
            GeneratorDriverRunResult generatorResults = gd.GetRunResult();

            if (!compile)
            {
                return(generatorResults.Diagnostics);
            }

            comp = comp.AddSyntaxTrees(generatorResults.GeneratedTrees.ToArray());
            EmitResult results = comp.Emit(Stream.Null, cancellationToken: cancellationToken);
            ImmutableArray <Diagnostic> generatorDiagnostics = generatorResults.Diagnostics.RemoveAll(d => d.Severity <= DiagnosticSeverity.Hidden);
            ImmutableArray <Diagnostic> resultsDiagnostics   = results.Diagnostics.RemoveAll(d => d.Severity <= DiagnosticSeverity.Hidden);

            if (!results.Success || resultsDiagnostics.Length != 0 || generatorDiagnostics.Length != 0)
            {
                throw new ArgumentException(
                          string.Join(Environment.NewLine, resultsDiagnostics.Concat(generatorDiagnostics)) + Environment.NewLine +
                          string.Join(Environment.NewLine, generatorResults.GeneratedTrees.Select(t => t.ToString())));
            }

            return(generatorResults.Diagnostics.Concat(results.Diagnostics).Where(d => d.Severity != DiagnosticSeverity.Hidden).ToArray());
        }
示例#18
0
        private void BuildThread(Settings settings)
        {
            _output.Clear();
            _output.Activate();
            _output.WriteLine("RudeBuild building...");
            _output.WriteLine();

            _stopwatch.Reset();
            _stopwatch.Start();

            int exitCode = -1;

            try
            {
                var          solutionReaderWriter = new SolutionReaderWriter(settings);
                SolutionInfo solutionInfo         = solutionReaderWriter.ReadWrite(settings.BuildOptions.Solution.FullName);
                settings.SolutionSettings = SolutionSettings.Load(settings, solutionInfo);
                var projectReaderWriter = new ProjectReaderWriter(settings);
                projectReaderWriter.ReadWrite(solutionInfo);
                settings.SolutionSettings.UpdateAndSave(settings, solutionInfo);

                exitCode = _processLauncher.Run(solutionInfo);
            }
            catch (System.Exception ex)
            {
                _output.WriteLine("Build failed. An error occurred while building:");
                _output.WriteLine(ex.Message);
            }

            _stopwatch.Stop();
            TimeSpan ts            = _stopwatch.Elapsed;
            string   buildTimeText = string.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

            _output.WriteLine("Build time: " + buildTimeText);

            lock (_lock)
            {
                _lastBuildWasSuccessful = !_isBeingStopped && exitCode == 0;
                _buildThread            = null;
                _processLauncher        = null;
            }
        }
示例#19
0
        public async Task <SolutionInfo> CreateSolutionInfoAsync(Checksum solutionChecksum)
        {
            var solutionChecksumObject = await _assetService.GetAssetAsync <SolutionStateChecksums>(solutionChecksum, _cancellationToken).ConfigureAwait(false);

            var solutionInfo = await _assetService.GetAssetAsync <SolutionInfo.SolutionAttributes>(solutionChecksumObject.Info, _cancellationToken).ConfigureAwait(false);

            var projects = new List <ProjectInfo>();

            foreach (var projectChecksum in solutionChecksumObject.Projects)
            {
                var projectInfo = await CreateProjectInfoAsync(projectChecksum).ConfigureAwait(false);

                if (projectInfo != null)
                {
                    projects.Add(projectInfo);
                }
            }

            return(SolutionInfo.Create(solutionInfo.Id, solutionInfo.Version, solutionInfo.FilePath, projects));
        }
示例#20
0
        /// <summary>
        /// Parse a <see cref="SolutionInfo"/> from <paramref name="sln"/>.
        /// </summary>
        /// <param name="sln">The solution file.</param>
        /// <returns>A <see cref="SolutionInfo"/>.</returns>
        public static SolutionInfo ParseInfo(FileInfo sln)
        {
            var contents = File.ReadAllText(sln.FullName);
            var builder  = ImmutableDictionary.CreateBuilder <ProjectId, FileInfo>();

            foreach (Match match in Regex.Matches(contents, @"Project\(""[^ ""]+""\) = ""(?<name>\w+(\.\w+)*)\"", ?""(?<path>\w+(\.\w+)*(\\\w+(\.\w+)*)*.csproj)", RegexOptions.ExplicitCapture))
            {
                //// ReSharper disable once AssignNullToNotNullAttribute
                var projectFile = new FileInfo(Path.Combine(sln.DirectoryName, match.Groups["path"].Value));
                builder.Add(ProjectId.CreateNewId(projectFile.FullName), projectFile);
            }

            ImmutableDictionary <ProjectId, FileInfo> idFileMap = builder.ToImmutable();

            return(SolutionInfo.Create(
                       SolutionId.CreateNewId(sln.FullName),
                       VersionStamp.Create(sln.LastWriteTimeUtc),
                       sln.FullName,
                       idFileMap.Keys.Select(x => ProjectFile.ParseInfo(x, idFileMap))));
        }
        /// <summary>
        /// Processes the build dependencies defined in template
        /// </summary>
        /// <param name="templateInfo">Information about the template used</param>
        /// <param name="solutionInfo">Information about current solution</param>
        private void ProcessBuildDependencies(TemplateInfo templateInfo, SolutionInfo solutionInfo)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var solutionBuild = solutionInfo.Solution.SolutionBuild;

            foreach (var buildDependency in templateInfo.BuildDependencies)
            {
                if (!string.IsNullOrEmpty(buildDependency.ProjectName) && !string.IsNullOrEmpty(buildDependency.DependsOnProjectName))
                {
                    ProcessBuildDependency(solutionInfo, buildDependency, solutionBuild);
                }
                else
                {
                    Package.Output($"  WARN: Dependency {buildDependency} is missing data ");
                    Package.ErrorListAddWarning($"Dependency {buildDependency} is missing data");
                }
            }

            Package.Output($"Processed build dependencies");
        }
示例#22
0
    public bool IsSolvable()
    {
        SudokuData cloneData = GetClone();

        cloneData.Update();

        while (cloneData.HasEmptySlot())
        {
            SolutionInfo solution = SudokuUtility.FindSolution(cloneData);
            if (solution == null)
            {
                return(false);
            }

            cloneData.SetSlotValueAndReason(solution.SlotData.SlotIndex, solution.Value, FillReason.None);
            cloneData.Update();
        }

        return(true);
    }
        public SolutionHierarchy(CommandManager commandManager, SolutionInfo solutionInfo, Settings settings)
        {
            _solutionInfo = solutionInfo;
            _settings     = settings;

            _icons[IconType.Project] = null;
            _icons[IconType.Folder]  = null;
            _icons[IconType.CppFile] = null;

            TopLevelItems = new List <Item>();

            try
            {
                ProcessSolution(commandManager);
            }
            catch
            {
                TopLevelItems.Clear();
            }
        }
示例#24
0
        public override IEnumerable <ITask> Create(SolutionInfo solutionInfo)
        {
            var result = new List <ITask>();

            if (solutionInfo.BuildSolution)
            {
                result.Add(new MsBuildTask(
                               taskType: MsBuildTask.MsBuildTaskType.Solution,
                               sourceFiles: new List <FilePath> {
                    (FilePath)solutionInfo.SolutionPath
                },
                               projectName: solutionInfo.Name
                               ));
            }
            else
            {
                result.Add(new RestoreNugetTask(solutionInfo.Name));
            }
            return(result);
        }
示例#25
0
        async Task <SolutionInfo> CreateSolutionInfo(MonoDevelop.Projects.Solution solution, CancellationToken token)
        {
            var projects   = new ConcurrentBag <ProjectInfo> ();
            var mdProjects = solution.GetAllProjects();

            projectionList.Clear();
            solutionData = new SolutionData();

            List <Task> allTasks = new List <Task> ();

            foreach (var proj in mdProjects)
            {
                if (token.IsCancellationRequested)
                {
                    return(null);
                }
                var tp = LoadProject(proj, token).ContinueWith(t => {
                    if (!t.IsCanceled)
                    {
                        projects.Add(t.Result);
                    }
                });
                allTasks.Add(tp);
            }
            await Task.WhenAll(allTasks.ToArray());

            if (token.IsCancellationRequested)
            {
                return(null);
            }
            var solutionInfo = SolutionInfo.Create(GetSolutionId(solution), VersionStamp.Create(), solution.FileName, projects);

            lock (addLock) {
                if (!added)
                {
                    added = true;
                    OnSolutionAdded(solutionInfo);
                }
            }
            return(solutionInfo);
        }
示例#26
0
        public async Task UpdateLastUser(string username, LoginType logintype = LoginType.SSO)
        {
            List <SolutionInfo> solutions = Utils.Solutions;
            SolutionInfo        current   = App.Settings.CurrentSolution;

            current.LastUser  = username;
            current.LoginType = logintype;

            foreach (SolutionInfo sol in solutions)
            {
                if (sol.SolutionName == current.SolutionName && sol.RootUrl == current.RootUrl)
                {
                    sol.LastUser  = username;
                    sol.LoginType = logintype;
                    break;
                }
            }
            await Store.SetJSONAsync(AppConst.SOLUTION_OBJ, current);

            await Store.SetJSONAsync(AppConst.MYSOLUTIONS, solutions);
        }
示例#27
0
        public void SolutionAdded_Simple()
        {
            using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
            {
                var solutionId = SolutionId.CreateNewId();
                var projectId  = ProjectId.CreateNewId();

                var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
                                                       projects: new[]
                {
                    ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
                                       documents: new[]
                    {
                        DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1")
                    })
                });

                var worker = ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo));
                Assert.Equal(1, worker.SyntaxDocumentIds.Count);
            }
        }
        private void CreateQuestion(CreateQuestionInfo questionInfo)
        {
            QuestionInfo saveInfo = new QuestionInfo();

            saveInfo.Name              = questionInfo.Name;
            saveInfo.QuestionType      = (QuestionType)questionInfo.QuestionTypeInt;
            saveInfo.QuestionScore     = questionInfo.QuestionScore;
            saveInfo.QuestionGroupName = questionInfo.QuestionGroupName;
            List <SolutionInfo> solutions = new List <SolutionInfo>();

            for (int i = 0; i < questionInfo.SolutionNames.Count(); i++)
            {
                SolutionInfo solution = new SolutionInfo();
                solution.Name      = questionInfo.SolutionNames.ElementAt(i);
                solution.Score     = questionInfo.SolutionScore.ElementAt(i);
                solution.IsCorrect = solution.Score > 0;
                solutions.Add(solution);
            }
            saveInfo.Solutions = solutions;
            _questionApp.Save(saveInfo);
        }
        private void RegisterFileSystemWatcher()
        {
            var solutionInfo = new SolutionInfo(GetDte());

            var bariDir = solutionInfo.BariWorkingDirectory;

            if (bariDir == null)
            {
                return;
            }

            var srcDir = Path.Combine(bariDir, "src");

            if (!Directory.Exists(srcDir))
            {
                return;
            }

            solutionWatcher          = new SolutionWatcher(srcDir);
            solutionWatcher.Changed += SolutionWatcherOnChanged;
        }
        /// <summary>
        ///  Processes single build dependency defined in template
        /// </summary>
        /// <param name="solutionInfo">Information about current solution</param>
        /// <param name="buildDependency">Build dependency definition</param>
        /// <param name="solutionBuild">Visual Studio build wrapper for current solution</param>
        private void ProcessBuildDependency(SolutionInfo solutionInfo, BuildDependency buildDependency, SolutionBuild solutionBuild)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            Package.Output($"  Processing build dependency {buildDependency}...");

            //get applicable projects (the projects the dependency is to be se on)
            var applicableProjects = GetBuildDependencyApplicableProjects(solutionInfo, buildDependency);

            if (applicableProjects.Count > 0)
            {
                var applicableProjectsStr = string.Join(", ", applicableProjects.Select(p =>
                {
                    ThreadHelper.ThrowIfNotOnUIThread();
                    return(p.Name);
                }));
                Package.Output($"    Applicable projects: {applicableProjectsStr}");

                //find required project (the project that the applicable project depends on)
                var dependsOn        = buildDependency.DependsOnProjectName.Trim();
                var dependsOnProject = solutionInfo.ExistingProjects.FirstOrDefault(p =>
                {
                    ThreadHelper.ThrowIfNotOnUIThread();
                    return(p.Name == dependsOn);
                });
                if (dependsOnProject != null)
                {
                    SetBuildDependency(solutionBuild, applicableProjects, dependsOnProject);
                }
                else
                {
                    Package.Output($"    Required project (depends on) not found");
                }
            }
            else
            {
                Package.Output($"    No applicable projects found");
            }

            Package.Output($"  Processed build dependency {buildDependency}");
        }
        /// <summary>
        /// Gets the lists of projects the <paramref name="buildDependency"/> should be applied to
        /// </summary>
        /// <param name="solutionInfo">Information about current solution</param>
        /// <param name="buildDependency">Build dependency definition</param>
        /// <returns></returns>
        private static List <Project> GetBuildDependencyApplicableProjects(SolutionInfo solutionInfo, BuildDependency buildDependency)
        {
            //  * means all projects
            //  *-project1,project2 means all projects but the ones defines in list split by ","
            //  other strings represent the project names split by ","
            var projectsRaw = buildDependency.ProjectName.Trim();
            var allProjects = projectsRaw == "*" || projectsRaw.StartsWith("*-");

            if (projectsRaw == "*")
            {
                projectsRaw = "";
            }
            if (projectsRaw.StartsWith("*-"))
            {
                projectsRaw = projectsRaw.Substring(2);
            }
            var projects = projectsRaw.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            var applicableProjects = new List <Project>();

            foreach (var project in solutionInfo.ExistingProjects.Where(p =>
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                return(!SolutionInfo.IsProjectSolutionItems(p) &&
                       p.Name != "Miscellaneous Files" && p.Kind != Constants.vsProjectItemsKindMisc);
            }))
            {
                var isInList = projects.Any(p =>
                {
                    ThreadHelper.ThrowIfNotOnUIThread();
                    return(p == project.Name);
                });
                if (allProjects && !isInList || !allProjects && isInList)
                {
                    applicableProjects.Add(project);
                }
            }

            return(applicableProjects);
        }
示例#32
0
        private static void IndexSolution(SolutionInfo solutionInfo, HashSet<string> assemblyList)
        {
            using (Disposable.Timing("Generating projects for " + Path.GetFileName(solutionInfo.SlnPath)))
            {
                bool needToCallAgain = false;

                // we need to call several times because it only processes projects one batch at a time
                // to avoid OutOfMemory on really large solutions
                do
                {
                    GC.Collect();
                    var solutionGenerator = new SolutionGenerator(
                        solutionInfo.SlnPath,
                        Paths.SolutionDestinationFolder,
                        solutionInfo.UrlRoot,
                        solutionInfo.MSBuildProperties != null ? solutionInfo.MSBuildProperties.ToImmutableDictionary() : null,
                        new Federation(Federation.FederatedIndexUrls));
                    needToCallAgain = solutionGenerator.Generate(assemblyList, mergedSolutionExplorerRoot);
                    solutionGenerator.GenerateResultsHtml(assemblyList);
                } while (needToCallAgain);
            }
        }
示例#33
0
        public async Task SolutionAdded_Simple()
        {
            using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler))
            {
                var solutionId = SolutionId.CreateNewId();
                var projectId  = ProjectId.CreateNewId();

                var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
                                                       projects: new[]
                {
                    ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
                                       documents: new[]
                    {
                        DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1")
                    })
                });

                var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo));

                Assert.Equal(1, worker.SyntaxDocumentIds.Count);
            }
        }
示例#34
0
        internal async Task <Compilation> CreateCompilationAsync(IEnumerable <string> paths, IEnumerable <string> preprocessors = null, Regex filter = null, string[] filters = null)
        {
            Console.WriteLine("Creating workspace...");

            var ws           = new AdhocWorkspace();
            var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default);

            ws.AddSolution(solutionInfo);
            var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "CSharpExample", "CSharpExample", "C#");

            ws.AddProject(projectInfo);
            foreach (var path in paths)
            {
                if (path.StartsWith("http://") || path.StartsWith("https://"))
                {
                    await DownloadDocumentsAsync(path, ws, projectInfo.Id, filter, filters).ConfigureAwait(false);
                }
                else if (path.EndsWith(".zip"))
                {
                    LoadCompressedDocuments(path, ws, projectInfo.Id, filter, filters);
                }
                else
                {
                    LoadFolderDocuments(path, ws, projectInfo.Id, filter, filters);
                }
            }
            Console.WriteLine("Compiling...");
            string mscorlib = @"c:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll";
            var    project  = ws.CurrentSolution.Projects.Single();

            if (File.Exists(mscorlib))
            {
                project = project.WithParseOptions(new Microsoft.CodeAnalysis.CSharp.CSharpParseOptions(Microsoft.CodeAnalysis.CSharp.LanguageVersion.Latest, DocumentationMode.Parse, SourceCodeKind.Regular, preprocessors));
                var metaref = MetadataReference.CreateFromFile(mscorlib);
                project = project.AddMetadataReference(metaref);
            }

            return(await project.GetCompilationAsync().ConfigureAwait(false));
        }
示例#35
0
        /// <summary>
        /// Checks the output produced when the converted solution
        /// was run by cygwin.
        /// </summary>
        private static TestResults checkResults(SolutionInfo solutionInfo)
        {
            TestResults results = new TestResults();
            results.Result = TestResults.PassFail.PASSED;

            // The solution folder should contain a file called testExpectedResults.txt.
            // This contains lines like:
            // [output-file-name] = [expected-output]
            // (There may be multiple lines so that we can test multiple configurations
            // of the solutions.)

            // We read each line from the expected-results file...
            string expectedResultsFilename = String.Format("{0}/testExpectedResults.txt", solutionInfo.Folder);
            string[] lines = File.ReadAllLines(expectedResultsFilename);
            foreach (string line in lines)
            {
                // We get the filename and expected result from the line...
                List<string> tokens = Utils.split(line, '=');
                if (tokens.Count != 2)
                {
                    throw new Exception(String.Format("Lines should be in the format [output-file-name] = [expected-output]. File={0}", expectedResultsFilename) );
                }
                string file = solutionInfo.Folder + "/" + tokens[0].Trim();
                string expectedResult = tokens[1].Trim();

                // We read the data from the output file, and compare it
                // with the expected results...
                string actualResult = File.ReadAllText(file);
                if (actualResult != expectedResult)
                {
                    results.Result = TestResults.PassFail.FAILED;
                    results.Description += String.Format("Expected '{0}', got '{1}'.", expectedResult, actualResult);
                }
            }

            return results;
        }
示例#36
0
        private void RemoveProjectFromSolution(string slnFile, string destFile)
        {
            if (slnFile == null) throw new ArgumentNullException("slnFile");
            if (destFile == null) throw new ArgumentNullException("destFile");
            if (!File.Exists(slnFile)) throw new ArgumentException(
                string.Format("Can not found file \"{0}\".", slnFile));
            if (!ForceOverwrite && File.Exists(destFile))
                throw new ArgumentException(string.Format
                    ("Destination file \"{0}\" already exists, "
                    + "You can use ForceOverwrite to force overwrite file.", destFile));

            var sln = new SolutionInfo(slnFile);
            foreach (var e in ProjectNamePatterns)
            {
                var pattern = e;
                sln.RemoveProjects(p => new Regex(pattern).IsMatch(p.ProjectName));
            }
            foreach (var e in ItemPatterns)
            {
                var pattern = e;
                sln.RemoveSolutionItems(m => new Regex(pattern).IsMatch(m));
            }
            File.WriteAllText(destFile, sln.ToString(), new UTF8Encoding(true, true));
        }
        protected override EstimationResult BuildEstimate(Scalar spotPrice, CurveMarketData interestDataSet, CallPriceMarketData callDataSet, EquityCalibrationData equityCalData, SolutionInfo solution)
        {
            string[] names = new string[] { "S0", "kappa", "theta", "sigma",
                                            "rho", "V0", "r", "q" };
            Vector param = new Vector(8);
            param[0] = spotPrice.Value;
            param[Range.New(1, 5)] = solution.x[Range.New(0, 4)];
            param[6] = equityCalData.zrFunc.Evaluate(TheoreticalModelsSettings.ConstantDYRFMaturity);
            if (impliedDividends)
                param[7] = solution.x[Range.End];// equityCalData.dyFunc.Evaluate(TheoreticalModelsSettings.ConstantDYRFMaturity);
            else
                param[7] = DY(equityCalData);

            var result = new EstimationResult(names, param);
            result.Fit = HestonCallOptimizationProblem.avgPricingError;
            Console.WriteLine(result);
            return result;
        }
示例#38
0
 internal override void Solve(int l, Kernel Q, double[] b, sbyte[] y, double[] alpha, double Cp, double Cn,
                              double eps, SolutionInfo si, int shrinking)
 {
     this.si = si;
     base.Solve(l, Q, b, y, alpha, Cp, Cn, eps, si, shrinking);
 }
示例#39
0
文件: Solver.cs 项目: wendelad/RecSys
 public override sealed void Solve(int l, IQMatrix Q, double[] p, sbyte[] y,
        double[] alpha, double Cp, double Cn, double eps,
        SolutionInfo si, bool shrinking)
 {
     this.si = si;
     base.Solve(l, Q, p, y, alpha, Cp, Cn, eps, si, shrinking);
 }
示例#40
0
        internal virtual void Solve(int l1, SvmMatrix q1, double[] p1, short[] y1, double[] alpha1, double cp1, double cn1,
			double eps1, SolutionInfo si, bool shrinking)
        {
            l = l1;
            q = q1;
            qd = q1.GetQd();
            p = (double[]) p1.Clone();
            y = (short[]) y1.Clone();
            alpha = (double[]) alpha1.Clone();
            cp = cp1;
            cn = cn1;
            eps = eps1;
            unshrink = false;
            // initialize alpha_status
                {
                    alphaStatus = new byte[l1];
                    for (int i = 0; i < l1; i++){
                        UpdateAlphaStatus(i);
                    }
                }
            // initialize active set (for shrinking)
                {
                    activeSet = new int[l1];
                    for (int i = 0; i < l1; i++){
                        activeSet[i] = i;
                    }
                    activeSize = l1;
                }
            // initialize gradient
                {
                    g = new double[l1];
                    gBar = new double[l1];
                    int i;
                    for (i = 0; i < l1; i++){
                        g[i] = p[i];
                        gBar[i] = 0;
                    }
                    for (i = 0; i < l1; i++){
                        if (!IsLowerBound(i)){
                            float[] qI = q1.GetQ(i, l1);
                            double alphaI = alpha[i];
                            int j;
                            for (j = 0; j < l1; j++){
                                g[j] += alphaI*qI[j];
                            }
                            if (IsUpperBound(i)){
                                for (j = 0; j < l1; j++){
                                    gBar[j] += GetC(i)*qI[j];
                                }
                            }
                        }
                    }
                }
            // optimization step
            int iter = 0;
            int maxIter = Math.Max(10000000, l1 > int.MaxValue/100 ? int.MaxValue : 100*l1);
            int counter = Math.Min(l1, 1000) + 1;
            int[] workingSet = new int[2];
            while (iter < maxIter){
                // show progress and do shrinking
                if (--counter == 0){
                    counter = Math.Min(l1, 1000);
                    if (shrinking){
                        DoShrinking();
                    }
                    SvmMain.Info(".");
                }
                if (SelectWorkingSet(workingSet) != 0){
                    // reconstruct the whole gradient
                    ReconstructGradient();
                    // reset active set size and check
                    activeSize = l1;
                    SvmMain.Info("*");
                    if (SelectWorkingSet(workingSet) != 0){
                        break;
                    }
                    counter = 1; // do shrinking next iteration
                }
                int i = workingSet[0];
                int j = workingSet[1];
                ++iter;
                // update alpha[i] and alpha[j], handle bounds carefully
                float[] qI = q1.GetQ(i, activeSize);
                float[] qJ = q1.GetQ(j, activeSize);
                double cI = GetC(i);
                double cJ = GetC(j);
                double oldAlphaI = alpha[i];
                double oldAlphaJ = alpha[j];
                if (y[i] != y[j]){
                    double quadCoef = qd[i] + qd[j] + 2*qI[j];
                    if (quadCoef <= 0){
                        quadCoef = 1e-12;
                    }
                    double delta = (-g[i] - g[j])/quadCoef;
                    double diff = alpha[i] - alpha[j];
                    alpha[i] += delta;
                    alpha[j] += delta;
                    if (diff > 0){
                        if (alpha[j] < 0){
                            alpha[j] = 0;
                            alpha[i] = diff;
                        }
                    } else{
                        if (alpha[i] < 0){
                            alpha[i] = 0;
                            alpha[j] = -diff;
                        }
                    }
                    if (diff > cI - cJ){
                        if (alpha[i] > cI){
                            alpha[i] = cI;
                            alpha[j] = cI - diff;
                        }
                    } else{
                        if (alpha[j] > cJ){
                            alpha[j] = cJ;
                            alpha[i] = cJ + diff;
                        }
                    }
                } else{
                    double quadCoef = qd[i] + qd[j] - 2*qI[j];
                    if (quadCoef <= 0){
                        quadCoef = 1e-12;
                    }
                    double delta = (g[i] - g[j])/quadCoef;
                    double sum = alpha[i] + alpha[j];
                    alpha[i] -= delta;
                    alpha[j] += delta;
                    if (sum > cI){
                        if (alpha[i] > cI){
                            alpha[i] = cI;
                            alpha[j] = sum - cI;
                        }
                    } else{
                        if (alpha[j] < 0){
                            alpha[j] = 0;
                            alpha[i] = sum;
                        }
                    }
                    if (sum > cJ){
                        if (alpha[j] > cJ){
                            alpha[j] = cJ;
                            alpha[i] = sum - cJ;
                        }
                    } else{
                        if (alpha[i] < 0){
                            alpha[i] = 0;
                            alpha[j] = sum;
                        }
                    }
                }
                // update G
                double deltaAlphaI = alpha[i] - oldAlphaI;
                double deltaAlphaJ = alpha[j] - oldAlphaJ;
                for (int k = 0; k < activeSize; k++){
                    g[k] += qI[k]*deltaAlphaI + qJ[k]*deltaAlphaJ;
                }
                // update alpha_status and G_bar
                {
                    bool ui = IsUpperBound(i);
                    bool uj = IsUpperBound(j);
                    UpdateAlphaStatus(i);
                    UpdateAlphaStatus(j);
                    int k;
                    if (ui != IsUpperBound(i)){
                        qI = q1.GetQ(i, l1);
                        if (ui){
                            for (k = 0; k < l1; k++){
                                gBar[k] -= cI*qI[k];
                            }
                        } else{
                            for (k = 0; k < l1; k++){
                                gBar[k] += cI*qI[k];
                            }
                        }
                    }
                    if (uj != IsUpperBound(j)){
                        qJ = q1.GetQ(j, l1);
                        if (uj){
                            for (k = 0; k < l1; k++){
                                gBar[k] -= cJ*qJ[k];
                            }
                        } else{
                            for (k = 0; k < l1; k++){
                                gBar[k] += cJ*qJ[k];
                            }
                        }
                    }
                }
            }
            if (iter >= maxIter){
                if (activeSize < l1){
                    // reconstruct the whole gradient to calculate objective value
                    ReconstructGradient();
                    activeSize = l1;
                    SvmMain.Info("*");
                }
                SvmMain.Info("\nWARNING: reaching max number of iterations");
            }
            // calculate rho
            si.rho = CalculateRho();
            // calculate objective value
                {
                    double v = 0;
                    int i;
                    for (i = 0; i < l1; i++){
                        v += alpha[i]*(g[i] + p[i]);
                    }
                    si.obj = v/2;
                }
            // put back the solution
                {
                    for (int i = 0; i < l1; i++){
                        alpha1[activeSet[i]] = alpha[i];
                    }
                }
            si.upperBoundP = cp1;
            si.upperBoundN = cn1;
            SvmMain.Info("\noptimization finished, #iter = " + iter + "\n");
        }
示例#41
0
        protected virtual EstimationResult BuildEstimate(Scalar spotPrice, CurveMarketData interestDataSet, CallPriceMarketData callDataSet, EquityCalibrationData equityCalData, SolutionInfo solution)
        {
            string[] names = new string[] { "S0", "kappa", "theta", "sigma", "rho", "V0" };
            Vector param = new Vector(6);
            param[0] = spotPrice.Value;
            param[Range.New(1, 5)] = solution.x;
            var result = new EstimationResult(names, param);

            // In the following the two function describing the ZR and dividend yields are created
            //Matrix zerorate = new Matrix(interestDataSet.Durations.Length, 2);
            //zerorate[Range.All, 0] = interestDataSet.Durations;
            //zerorate[Range.All, 1] = interestDataSet.Values;

            //Matrix dividendYield = new Matrix(equityCalData.MaturityDY.Length, 2);
            //dividendYield[Range.All, 0] = equityCalData.MaturityDY;
            //dividendYield[Range.All, 1] = equityCalData.DividendYield;

            Matrix zerorate = new Matrix((equityCalData.zrFunc as PFunction).Expr);
            //Matrix dividendYield = new Matrix((equityCalData.dyFunc as PFunction).Expr);
            Matrix dividendYield = ToMatrix(IstantaneousDividendYield(equityCalData));
            result.Objects = new object[2];
            result.Objects[0] = zerorate;
            result.Objects[1] = dividendYield;
            result.Fit = solution.obj;
            Console.WriteLine(result);
            return result;
        }
示例#42
0
文件: Solver.cs 项目: wendelad/RecSys
        public virtual void Solve(int l, IQMatrix Q, double[] p_, sbyte[] y_, double[] alpha_, double Cp, double Cn, double eps, SolutionInfo si, bool shrinking)
        {
            this.l = l;
            this.Q = Q;
            QD = Q.GetQD();
            p = (double[])p_.Clone();
            y = (sbyte[])y_.Clone();
            alpha = (double[])alpha_.Clone();
            this.Cp = Cp;
            this.Cn = Cn;
            this.EPS = eps;
            this.unshrink = false;

            // initialize alpha_status
            {
                alpha_status = new byte[l];
                for (int i = 0; i < l; i++)
                    update_alpha_status(i);
            }

            // initialize active set (for shrinking)
            {
                active_set = new int[l];
                for (int i = 0; i < l; i++)
                    active_set[i] = i;
                active_size = l;
            }

            // initialize gradient
            {
                G = new double[l];
                G_bar = new double[l];
                int i;
                for (i = 0; i < l; i++)
                {
                    G[i] = p[i];
                    G_bar[i] = 0;
                }
                for (i = 0; i < l; i++)
                    if (!is_lower_bound(i))
                    {
                        float[] Q_i = Q.GetQ(i, l);
                        double alpha_i = alpha[i];
                        int j;
                        for (j = 0; j < l; j++)
                            G[j] += alpha_i * Q_i[j];
                        if (is_upper_bound(i))
                            for (j = 0; j < l; j++)
                                G_bar[j] += get_C(i) * Q_i[j];
                    }
            }

            // optimization step

            int iter = 0;
            int counter = Math.Min(l, 1000) + 1;
            int[] working_set = new int[2];

            while (true)
            {
                // show progress and do shrinking

                if (--counter == 0)
                {
                    counter = Math.Min(l, 1000);
                    if (shrinking) do_shrinking();
                    Procedures.info(".");
                }

                if (select_working_set(working_set) != 0)
                {
                    // reconstruct the whole gradient
                    reconstruct_gradient();
                    // reset active set size and check
                    active_size = l;
                    Procedures.info("*");
                    if (select_working_set(working_set) != 0)
                        break;
                    else
                        counter = 1;	// do shrinking next iteration
                }

                int i = working_set[0];
                int j = working_set[1];

                ++iter;

                // update alpha[i] and alpha[j], handle bounds carefully

                float[] Q_i = Q.GetQ(i, active_size);
                float[] Q_j = Q.GetQ(j, active_size);

                double C_i = get_C(i);
                double C_j = get_C(j);

                double old_alpha_i = alpha[i];
                double old_alpha_j = alpha[j];

                if (y[i] != y[j])
                {
                    double quad_coef = Q_i[i] + Q_j[j] + 2 * Q_i[j];
                    if (quad_coef <= 0)
                        quad_coef = 1e-12;
                    double delta = (-G[i] - G[j]) / quad_coef;
                    double diff = alpha[i] - alpha[j];
                    alpha[i] += delta;
                    alpha[j] += delta;

                    if (diff > 0)
                    {
                        if (alpha[j] < 0)
                        {
                            alpha[j] = 0;
                            alpha[i] = diff;
                        }
                    }
                    else
                    {
                        if (alpha[i] < 0)
                        {
                            alpha[i] = 0;
                            alpha[j] = -diff;
                        }
                    }
                    if (diff > C_i - C_j)
                    {
                        if (alpha[i] > C_i)
                        {
                            alpha[i] = C_i;
                            alpha[j] = C_i - diff;
                        }
                    }
                    else
                    {
                        if (alpha[j] > C_j)
                        {
                            alpha[j] = C_j;
                            alpha[i] = C_j + diff;
                        }
                    }
                }
                else
                {
                    double quad_coef = Q_i[i] + Q_j[j] - 2 * Q_i[j];
                    if (quad_coef <= 0)
                        quad_coef = 1e-12;
                    double delta = (G[i] - G[j]) / quad_coef;
                    double sum = alpha[i] + alpha[j];
                    alpha[i] -= delta;
                    alpha[j] += delta;

                    if (sum > C_i)
                    {
                        if (alpha[i] > C_i)
                        {
                            alpha[i] = C_i;
                            alpha[j] = sum - C_i;
                        }
                    }
                    else
                    {
                        if (alpha[j] < 0)
                        {
                            alpha[j] = 0;
                            alpha[i] = sum;
                        }
                    }
                    if (sum > C_j)
                    {
                        if (alpha[j] > C_j)
                        {
                            alpha[j] = C_j;
                            alpha[i] = sum - C_j;
                        }
                    }
                    else
                    {
                        if (alpha[i] < 0)
                        {
                            alpha[i] = 0;
                            alpha[j] = sum;
                        }
                    }
                }

                // update G

                double delta_alpha_i = alpha[i] - old_alpha_i;
                double delta_alpha_j = alpha[j] - old_alpha_j;

                for (int k = 0; k < active_size; k++)
                {
                    G[k] += Q_i[k] * delta_alpha_i + Q_j[k] * delta_alpha_j;
                }

                // update alpha_status and G_bar

                {
                    bool ui = is_upper_bound(i);
                    bool uj = is_upper_bound(j);
                    update_alpha_status(i);
                    update_alpha_status(j);
                    int k;
                    if (ui != is_upper_bound(i))
                    {
                        Q_i = Q.GetQ(i, l);
                        if (ui)
                            for (k = 0; k < l; k++)
                                G_bar[k] -= C_i * Q_i[k];
                        else
                            for (k = 0; k < l; k++)
                                G_bar[k] += C_i * Q_i[k];
                    }

                    if (uj != is_upper_bound(j))
                    {
                        Q_j = Q.GetQ(j, l);
                        if (uj)
                            for (k = 0; k < l; k++)
                                G_bar[k] -= C_j * Q_j[k];
                        else
                            for (k = 0; k < l; k++)
                                G_bar[k] += C_j * Q_j[k];
                    }
                }

            }

            // calculate rho

            si.rho = calculate_rho();

            // calculate objective value
            {
                double v = 0;
                int i;
                for (i = 0; i < l; i++)
                    v += alpha[i] * (G[i] + p[i]);

                si.obj = v / 2;
            }

            // put back the solution
            {
                for (int i = 0; i < l; i++)
                    alpha_[active_set[i]] = alpha[i];
            }

            si.upper_bound_p = Cp;
            si.upper_bound_n = Cn;

            Procedures.info("\noptimization finished, #iter = " + iter + "\n");
        }
示例#43
0
文件: Form1.cs 项目: uvbs/Holodeck
        /// <summary>
        /// LoadDetailsFromConfigFile:
        /// Loads details from the config file. It populates the global variable cfProducts with
        /// product names. If the productName parameter is not empty and contains a valid product
        /// name, then the productDetails parameter is populated with the build information for
        /// the specified product.
        /// </summary>
        /// <param name="configFileName">[required, in] The path and filename of the config file</param>
        /// <param name="productName">[optional, in] The name of the product to be loaded</param>
        /// <param name="productDetails">[optional, out] Required only if productName is specified</param>
        /// <returns>A boolean value indicating if product names were successfully added to the
        /// cfProducts variable</returns>
        private bool LoadDetailsFromConfigFile(string configFileName, string productName, out ProductDetails productDetails)
        {
            productDetails = null;

            //Local variables
            bool hasMoreProducts = true;

            //Erase any previously loaded information
            cfProducts = null;

            XmlTextReader xmlReader = null;
            XmlValidatingReader validator = null;
            System.Xml.XPath.XPathDocument doc;
            System.Xml.XPath.XPathNavigator nav;

            try
            {
                xmlReader = new XmlTextReader(configFileName);
                validator = new XmlValidatingReader(xmlReader);
                validator.ValidationType = ValidationType.DTD;
                //Any errors will cause an XmlException to be thrown
                while (validator.Read())
                {
                }

                doc = new System.Xml.XPath.XPathDocument(configFileName);
                nav = doc.CreateNavigator();
            }

            catch (Exception)
            {
                if (xmlReader != null)
                    xmlReader.Close();
                if (validator != null)
                    validator.Close();
                return false;
            }

            #region Load PRODUCT names (and product details if specified) from the XML configuration file
            //Move to the SIBuilder Tag
            nav.MoveToFirstChild();
            if (!nav.HasChildren)
            {
                //MessageBox.Show ("The configuration file does not contain any products that can be built", errorDialogCaption);
                xmlReader.Close();
                validator.Close();
                return false;
            }

            this.cfProducts = new ArrayList();
            //Move to the first PRODUCT in the configuration file
            nav.MoveToFirstChild ();
            hasMoreProducts = true;

            while (hasMoreProducts)
            {
                this.cfProducts.Add (nav.GetAttribute ("Name", ""));

                //Check if the Name attribute was returned; if not declare config file corrupt
                if (this.cfProducts[this.cfProducts.Count - 1].ToString() == String.Empty)
                {
                    this.cfProducts = null;
                    xmlReader.Close();
                    validator.Close();
                    return false;
                }

                #region Load details of this product if requested by the user
                //Check if the user wants details about the current PRODUCT
                if ((productName != "") && (cfProducts[cfProducts.Count -1].ToString() == productName))
                {
                    productDetails = new ProductDetails();
                    //Add the product name
                    productDetails.Name = productName;
                    //Get the Versioning information
                    productDetails.MajorVersion = nav.GetAttribute ("MajorVersion", "");
                    productDetails.MinorVersion = nav.GetAttribute ("MinorVersion", "");
                    productDetails.BuildNumber = nav.GetAttribute ("BuildNumber", "");
                    //Get the other product details
                    if (nav.HasChildren)
                    {
                        nav.MoveToFirstChild();
                        bool moreProductDetails = true;
                        bool moreChildren = true;

                        while (moreProductDetails)
                        {
                            switch (nav.Name.ToUpper())
                            {
                                case "SOURCECONTROL":
                                    //Move into the children of the SOURCECONTROL node
                                    moreChildren= nav.MoveToFirstChild();
                                    if (!moreChildren)
                                        break;
                                    while (moreChildren)
                                    {
                                        if (productDetails.SourceControlInfo== null)
                                            productDetails.SourceControlInfo = new ArrayList();

                                        SourceControlInfo scInfo = new SourceControlInfo();
                                        scInfo.Executable = nav.Value;
                                        scInfo.Arguments = nav.GetAttribute ("Args", "");
                                        productDetails.SourceControlInfo.Add (scInfo);
                                        moreChildren = nav.MoveToNext();
                                    }
                                    //Move back to the SOURCECONTROL node
                                    nav.MoveToParent();
                                    break;
                                case "PATHS":
                                    //Move into the children of the PATHS node
                                    moreChildren = nav.MoveToFirstChild();
                                    if (!moreChildren)
                                        break;
                                    while (moreChildren)
                                    {
                                        switch (nav.Name.ToUpper())
                                        {
                                            case "BUILDS_LOCATION":
                                                productDetails.BuildsLocation = nav.Value;
                                                break;
                                            case "LOGS_LOCATION":
                                                productDetails.LogsLocation = nav.Value;
                                                break;
                                            case "DEVENV_FILE":
                                                productDetails.DevenvFile = nav.Value;
                                                break;
                                            case "INSTALLSHIELD_SCRIPT":
                                                productDetails.InstallShieldScript = nav.Value;
                                                break;
                                            case "INSTALLSHIELD_OUTPUT":
                                                productDetails.InstallShieldOutput = nav.Value;
                                                break;
                                            default:
                                                break;
                                        }
                                        moreChildren = nav.MoveToNext();
                                    }
                                    //Move back to the PATHS node
                                    nav.MoveToParent();
                                    break;

                                case "BUILDMAIL":
                                    //Move to the children of the BUILDMAIL node
                                    moreChildren = nav.MoveToFirstChild();
                                    if (!moreChildren)
                                        break;
                                    while (moreChildren)
                                    {
                                        switch (nav.Name.ToUpper())
                                        {
                                            case "RECIPIENTS":
                                                productDetails.MailRecipients = nav.Value;
                                                break;
                                            case "MAILSENDER":
                                                productDetails.MailSenderAddress = nav.GetAttribute ("Address", "");
                                                productDetails.MailServerAddress = nav.GetAttribute ("SmtpServer", "");
                                                break;
                                            default:
                                                break;
                                        }
                                        moreChildren = nav.MoveToNext();
                                    }
                                    //Move back to the BUILDMAIL node
                                    nav.MoveToParent();
                                    break;

                                case "BUILD_SOLUTIONS":
                                    //Move to the children of the BUILD_SOLUTIONS node
                                    moreChildren = nav.MoveToFirstChild();
                                    if (!moreChildren)
                                        break;
                                    while (moreChildren)
                                    {
                                        switch (nav.Name.ToUpper())
                                        {
                                            case "SOLUTION":
                                                if (productDetails.SolutionInfo == null)
                                                    productDetails.SolutionInfo = new ArrayList();

                                                SolutionInfo solInfo = new SolutionInfo();
                                                solInfo.SolutionPath = nav.Value;
                                                solInfo.ProjectName = nav.GetAttribute ("Project", "");
                                                solInfo.BuildConfig = nav.GetAttribute ("BuildConfig", "");
                                                productDetails.SolutionInfo.Add (solInfo);

                                                break;
                                            default:
                                                break;
                                        }
                                        moreChildren = nav.MoveToNext();
                                    }
                                    //Move back to the BUILD_SOLUTIONS node
                                    nav.MoveToParent();
                                    break;
                                default:
                                    break;
                            }
                            moreProductDetails = nav.MoveToNext();
                        }

                    }
                }
                #endregion

                hasMoreProducts = nav.MoveToNext();
            }
            #endregion

            xmlReader.Close();
            validator.Close();
            return true;
        }
示例#44
0
        /// <summary>
        /// Finds all solutions to convert in sub-folders and shows them
        /// in a list box.
        /// </summary>
        private void findSolutions()
        {
            // We get the collection of solutions and loop through them...
            string[] solutionFiles = Directory.GetFiles(".", "*.sln", SearchOption.AllDirectories);
            foreach (string solutionFile in solutionFiles)
            {
                // We store info for each solution...
                SolutionInfo solutionInfo = new SolutionInfo();
                solutionInfo.RelativePath = solutionFile;
                solutionInfo.FullPath = Path.GetFullPath(solutionFile);
                solutionInfo.SolutionName = Path.GetFileName(solutionFile);
                solutionInfo.Name = Path.GetFileNameWithoutExtension(solutionFile);
                solutionInfo.Folder = Path.GetDirectoryName(solutionFile);
                
                // We work out the folder to use when launching cygwin...
                string cygwinFolder = Path.GetDirectoryName(solutionInfo.FullPath);
                cygwinFolder = cygwinFolder.Replace("\\", "/");
                cygwinFolder = cygwinFolder.Replace(":", "");
                cygwinFolder = "/cygdrive/" + cygwinFolder;
                solutionInfo.CygwinFolder = cygwinFolder;

                // And show it in the list view...
                ctrlSolutions.Items.Add(solutionInfo, true);
            }
        }
示例#45
0
 internal override void Solve(int l1, SvmMatrix q1, double[] p1, short[] y1, double[] alpha1, double cp1,
                              double cn1, double eps1, SolutionInfo si1, bool shrinking)
 {
     si = si1;
     base.Solve(l1, q1, p1, y1, alpha1, cp1, cn1, eps1, si1, shrinking);
 }
示例#46
0
        internal virtual void Solve(int l, Kernel Q, double[] b_, sbyte[] y_, double[] alpha_, double Cp, double Cn,
                                    double eps, SolutionInfo si, int shrinking)
        {
            this.l = l;
            this.Q = Q;
            b = new double[b_.Length];
            b_.CopyTo(b, 0);
            y = new sbyte[y_.Length];
            y_.CopyTo(y, 0);
            alpha = new double[alpha_.Length];
            alpha_.CopyTo(alpha, 0);
            this.Cp = Cp;
            this.Cn = Cn;
            this.eps = eps;
            unshrinked = false;

            // initialize alpha_status
            {
                alpha_status = new sbyte[l];
                for (int i = 0; i < l; i++)
                    update_alpha_status(i);
            }

            // initialize active set (for shrinking)
            {
                active_set = new int[l];
                for (int i = 0; i < l; i++)
                    active_set[i] = i;
                active_size = l;
            }

            // initialize gradient
            {
                G = new double[l];
                G_bar = new double[l];
                int i;
                for (i = 0; i < l; i++)
                {
                    G[i] = b[i];
                    G_bar[i] = 0;
                }
                for (i = 0; i < l; i++)
                    if (!is_lower_bound(i))
                    {
                        float[] Q_i = Q.get_Q(i, l);
                        double alpha_i = alpha[i];
                        int j;
                        for (j = 0; j < l; j++)
                            G[j] += alpha_i*Q_i[j];
                        if (is_upper_bound(i))
                            for (j = 0; j < l; j++)
                                G_bar[j] += get_C(i)*Q_i[j];
                    }
            }

            // optimization step

            int iter = 0;
            int counter = Math.Min(l, 1000) + 1;
            var working_set = new int[2];

            while (true)
            {
                // show progress and do shrinking

                if (--counter == 0)
                {
                    counter = Math.Min(l, 1000);
                    if (shrinking != 0)
                        do_shrinking();
                    Console.Error.Write(".");
                }

                if (select_working_set(working_set) != 0)
                {
                    // reconstruct the whole gradient
                    reconstruct_gradient();
                    // reset active set size and check
                    active_size = l;
                    Console.Error.Write("*");
                    if (select_working_set(working_set) != 0)
                        break;
                    else
                        counter = 1; // do shrinking next iteration
                }

                int i = working_set[0];
                int j = working_set[1];

                ++iter;

                // update alpha[i] and alpha[j], handle bounds carefully

                float[] Q_i = Q.get_Q(i, active_size);
                float[] Q_j = Q.get_Q(j, active_size);

                double C_i = get_C(i);
                double C_j = get_C(j);

                double old_alpha_i = alpha[i];
                double old_alpha_j = alpha[j];

                if (y[i] != y[j])
                {
                    double delta = (- G[i] - G[j])/Math.Max(Q_i[i] + Q_j[j] + 2*Q_i[j], 0);
                    double diff = alpha[i] - alpha[j];
                    alpha[i] += delta;
                    alpha[j] += delta;

                    if (diff > 0)
                    {
                        if (alpha[j] < 0)
                        {
                            alpha[j] = 0;
                            alpha[i] = diff;
                        }
                    }
                    else
                    {
                        if (alpha[i] < 0)
                        {
                            alpha[i] = 0;
                            alpha[j] = - diff;
                        }
                    }
                    if (diff > C_i - C_j)
                    {
                        if (alpha[i] > C_i)
                        {
                            alpha[i] = C_i;
                            alpha[j] = C_i - diff;
                        }
                    }
                    else
                    {
                        if (alpha[j] > C_j)
                        {
                            alpha[j] = C_j;
                            alpha[i] = C_j + diff;
                        }
                    }
                }
                else
                {
                    double delta = (G[i] - G[j])/Math.Max(Q_i[i] + Q_j[j] - 2*Q_i[j], 0);
                    double sum = alpha[i] + alpha[j];
                    alpha[i] -= delta;
                    alpha[j] += delta;
                    if (sum > C_i)
                    {
                        if (alpha[i] > C_i)
                        {
                            alpha[i] = C_i;
                            alpha[j] = sum - C_i;
                        }
                    }
                    else
                    {
                        if (alpha[j] < 0)
                        {
                            alpha[j] = 0;
                            alpha[i] = sum;
                        }
                    }
                    if (sum > C_j)
                    {
                        if (alpha[j] > C_j)
                        {
                            alpha[j] = C_j;
                            alpha[i] = sum - C_j;
                        }
                    }
                    else
                    {
                        if (alpha[i] < 0)
                        {
                            alpha[i] = 0;
                            alpha[j] = sum;
                        }
                    }
                }

                // update G

                double delta_alpha_i = alpha[i] - old_alpha_i;
                double delta_alpha_j = alpha[j] - old_alpha_j;

                for (int k = 0; k < active_size; k++)
                {
                    G[k] += Q_i[k]*delta_alpha_i + Q_j[k]*delta_alpha_j;
                }

                // update alpha_status and G_bar

                {
                    bool ui = is_upper_bound(i);
                    bool uj = is_upper_bound(j);
                    update_alpha_status(i);
                    update_alpha_status(j);
                    int k;
                    if (ui != is_upper_bound(i))
                    {
                        Q_i = Q.get_Q(i, l);
                        if (ui)
                            for (k = 0; k < l; k++)
                                G_bar[k] -= C_i*Q_i[k];
                        else
                            for (k = 0; k < l; k++)
                                G_bar[k] += C_i*Q_i[k];
                    }

                    if (uj != is_upper_bound(j))
                    {
                        Q_j = Q.get_Q(j, l);
                        if (uj)
                            for (k = 0; k < l; k++)
                                G_bar[k] -= C_j*Q_j[k];
                        else
                            for (k = 0; k < l; k++)
                                G_bar[k] += C_j*Q_j[k];
                    }
                }
            }

            // calculate rho

            si.rho = calculate_rho();

            // calculate objective value
            {
                double v = 0;
                int i;
                for (i = 0; i < l; i++)
                    v += alpha[i]*(G[i] + b[i]);

                si.obj = v/2;
            }

            // put back the solution
            {
                for (int i = 0; i < l; i++)
                    alpha_[active_set[i]] = alpha[i];
            }

            si.upper_bound_p = Cp;
            si.upper_bound_n = Cn;

            Console.Out.Write("\noptimization finished, #iter = " + iter + "\n");
        }
示例#47
0
 /// <summary>
 /// Runs a bash script file with cygwin to build and run the solution.
 /// </summary>
 private static void cygwinBuildAndRun(SolutionInfo solutionInfo)
 {
     Process cygwinProcess = new Process();
     cygwinProcess.StartInfo.FileName = "c:/cygwin/bin/bash.exe";
     cygwinProcess.StartInfo.Arguments = String.Format("-li '{0}/testMakeAndTest.sh'", solutionInfo.CygwinFolder);
     cygwinProcess.StartInfo.WorkingDirectory = solutionInfo.Folder;
     cygwinProcess.StartInfo.UseShellExecute = false;
     cygwinProcess.Start();
     cygwinProcess.WaitForExit();
 }
示例#48
0
 /// <summary>
 /// Runs MakeItSo to convert the solution to a makefile.
 /// </summary>
 private static void runMakeItSo(SolutionInfo solutionInfo)
 {
     Process makeItSoProcess = new Process();
     makeItSoProcess.StartInfo.FileName = "MakeItSo.exe";
     makeItSoProcess.StartInfo.Arguments = String.Format("-file={0} -cygwin=true", Utils.quote(solutionInfo.SolutionName));
     makeItSoProcess.StartInfo.WorkingDirectory = solutionInfo.Folder;
     makeItSoProcess.StartInfo.UseShellExecute = false;
     makeItSoProcess.Start();
     makeItSoProcess.WaitForExit();
 }
示例#49
0
 public override void Solve(int l, QMatrix Q, double[] p, short[] y,
      double[] alpha, double Cp, double Cn, double eps,
      SolutionInfo si, int shrinking) {
   this.si = si;
   base.Solve(l, Q, p, y, alpha, Cp, Cn, eps, si, shrinking);
 }