protected internal override Results Match(string userAgent)
        {
            bool isMobile = false;

            // Use RIS to find a match first.
            Results results = base.Match(userAgent);

            // If no match with RIS then try edit distance.
            if (results == null || results.Count == 0)
                results = Matcher.Match(userAgent, this);

            // If a match other than edit distance was used then we'll have more confidence
            // and return the mobile version of the device.
            if (results.GetType() == typeof (Results))
                isMobile = true;

            Results newResults = new Results();

            // Look at the results for one that matches our isMobile setting based on the
            // matcher used.
            foreach (Result result in results)
            {
                if (result.Device.IsMobileDevice == isMobile)
                    newResults.Add(result.Device);
            }

            // Return the new results if any values are available.
            return newResults;
        }
Exemple #2
0
 public Results Join(Guid partyId, int userId, out IPlayer player)
 {
     player = null;
     var results = new Results();
     IParty party = this.GetAllJoinable(userId).Where(p => p.Id == partyId).FirstOrDefault();
     if (party != null)
     {
         var players = party.Players.Where(p => p.UserId == userId);
         if (players.Count() == 1)
         {
             player = players.ElementAt(0);
             results.Add(ResultCode.Undefined, @"\Games\mv\map.html?partyId=" + partyId);
         }
     }
     else
     {
         results.Add(ResultCode.PartyNotFound);
     }
     return results;
 }
Exemple #3
0
 public static Results GetLatestAlertResults(String ipHost, Namespace nameSpace)
 {
     if (!latest_results.ContainsKey(nameSpace))
         latest_results[nameSpace] = new Dictionary<String, ResultsCounter>();
     if (!latest_results[nameSpace].ContainsKey(ipHost))
         latest_results[nameSpace].Add(ipHost, new ResultsCounter());
     Results results = new Results();
     foreach (IResult result in latest_results[nameSpace][ipHost].Results.ToEnumerable())
     {
         if(!result.Ok)
             results.Add(result);
     }
     return results;
 }
        public bool Login(string userName, string password, bool rememberMe, out Results results)
        {
            bool ok = WebSecurity.Login(userName, password, persistCookie: rememberMe);
            results = new Results();
            if (ok)
            {
                var user = base.Resolve<IUserRepository>().GetUserByUserName(userName);
                if (user != null)
                    CreateAuthTicket(userName, Guid.Empty, string.Empty, rememberMe, HttpContext.Current.Response, user.Nick, Guid.Empty);
            }

            if (!ok) results.Add(ResultCode.LoginError);
            return ok;
        }
 public void Update(GameResult result)
 {
     Results.Add(result);
 }
        public override void ExecuteInternal()
        {
            if (!roots.Any())
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    foreach (var driveInfo in DriveInfo.GetDrives())
                    {
                        if (driveInfo.IsReady && driveInfo.DriveType == DriveType.Fixed)
                        {
                            roots.Add(driveInfo.Name);
                        }
                    }
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    roots.Add("/");
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    roots.Add("/");
                }
            }

            Action <string> IterateOn = Path =>
            {
                Log.Verbose("Started parsing {0}", Path);
                FileSystemObject obj = FilePathToFileSystemObject(Path, downloadCloud, INCLUDE_CONTENT_HASH);
                if (obj != null)
                {
                    Results.Add(obj);

                    // TODO: Also try parse .DER as a key
                    if (Path.EndsWith(".cer", StringComparison.CurrentCulture) ||
                        Path.EndsWith(".der", StringComparison.CurrentCulture) ||
                        Path.EndsWith(".p7b", StringComparison.CurrentCulture) ||
                        Path.EndsWith(".pfx", StringComparison.CurrentCulture))
                    {
                        try
                        {
                            using var certificate = new X509Certificate2(Path);

                            var certObj = new CertificateObject(
                                StoreLocation: StoreLocation.LocalMachine.ToString(),
                                StoreName: StoreName.Root.ToString(),
                                Certificate: new SerializableCertificate(certificate));

                            Results.Add(certObj);
                        }
                        catch (Exception e)
                        {
                            Log.Verbose($"Could not parse certificate from file: {Path}, {e.GetType().ToString()}");
                        }
                    }
                }
                Log.Verbose("Finished parsing {0}", Path);
            };

            foreach (var root in roots)
            {
                Log.Information("{0} root {1}", Strings.Get("Scanning"), root);
                var filePathEnumerable = DirectoryWalker.WalkDirectory(root);

                if (parallel)
                {
                    filePathEnumerable.AsParallel().ForAll(filePath =>
                    {
                        IterateOn(filePath);
                    });
                }
                else
                {
                    foreach (var filePath in filePathEnumerable)
                    {
                        IterateOn(filePath);
                    }
                }
            }
        }
Exemple #7
0
        public override void Parse()
        {
            string linkText = string.Empty;
            string linkURL  = string.Empty;

            try
            {
                byte[] fileByteArray = Utility.GetFileByteArray(FileUrl);

                if (fileByteArray != null)
                {
                    using (MemoryStream fileStream = new MemoryStream(fileByteArray, false))
                    {
                        Mail_Message mime = Mail_Message.ParseFromStream(fileStream);
                        HtmlDocument doc  = new HtmlDocument();
                        string       html = string.IsNullOrEmpty(mime.BodyHtmlText) ? mime.BodyText : mime.BodyHtmlText;
                        if (!string.IsNullOrEmpty(html))
                        {
                            doc.LoadHtml(html);
                            foreach (HtmlNode link in doc.DocumentNode.SelectNodesOrEmpty("//a[@href]"))
                            {
                                if (link.Attributes["href"].Value.StartsWith("#", StringComparison.InvariantCultureIgnoreCase) == false &&
                                    link.Attributes["href"].Value.StartsWith("javascript:", StringComparison.InvariantCultureIgnoreCase) == false &&
                                    link.Attributes["href"].Value.StartsWith("mailto:", StringComparison.InvariantCultureIgnoreCase) == false)
                                {
                                    linkURL = link.Attributes["href"].Value;
                                    if (link.FirstChild == link.LastChild)
                                    {
                                        linkText = link.InnerText;
                                    }
                                    else
                                    {
                                        linkText = link.LastChild.InnerText;
                                    }

                                    linkText = new string(linkText.ToCharArray()).Replace("\r\n", " ");

                                    FileLink objLink = new FileLink()
                                    {
                                        ParentFileUrl = FileUrl,
                                        LinkText      = linkText,
                                        LinkAddress   = linkURL
                                    };

                                    Results.Add(objLink);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FileLink objLink = new FileLink()
                {
                    ParentFileUrl = FileUrl,
                    LinkText      = "Error occurred when parsing this file.",
                    LinkAddress   = ex.Message,
                    hasError      = true
                };

                Results.Add(objLink);
            }
        }
Exemple #8
0
 public Result AddResult(Result arg)
 {
     arg.C_RowId = ++_rowCounter;
     Results.Add(arg);
     return(arg);
 }
Exemple #9
0
        void ExecuteConvert(object sender, EventArgs e)
        {
            var result = _model.SecretLogic();

            Results.Add(result);
        }
 public GyroTemperatureCalibrator(IRUSDevice device) : base(device)
 {
     Results.Add(_measureResult);
 }
            /// <summary>
            /// Adds the result of a test method into the log.
            /// </summary>
            /// <param name="test">The test metadata.</param>
            /// <param name="storage">The storage value.</param>
            /// <param name="codeBase">The code base value.</param>
            /// <param name="adapterTypeName">The adapter type name.</param>
            /// <param name="className">The class name.</param>
            /// <param name="testListName">The test list name.</param>
            /// <param name="computerName">The computer name.</param>
            /// <param name="startTime">The start time.</param>
            /// <param name="endTime">The end time.</param>
            /// <param name="outcome">The outcome.</param>
            public void AddTestMethodResult(
                ITestMethod test,
                string storage,
                string codeBase,
                string adapterTypeName,
                string className,
                string testListName,
                string computerName,
                DateTime startTime,
                DateTime endTime,
                TestOutcome outcome)
            {
                if (test == null)
                {
                    throw new ArgumentNullException("test");
                }

                // Friendly name of the test
                string name = test.Name;

                // Generate GUIDs.
                string testId      = Guid.NewGuid().ToString();
                string executionId = Guid.NewGuid().ToString();
                string testListId  = GetTestListGuid(testListName);

                // UnitTest element.
                SimpleXElement unitTest = CreateElement("UnitTest");

                unitTest.SetAttributeValue("name", name);
                unitTest.SetAttributeValue("storage", storage);
                unitTest.SetAttributeValue("id", testId);

                SimpleXElement owners      = CreateElement("Owners");
                SimpleXElement owner       = CreateElement("Owner");
                string         ownerString = test.Owner ?? string.Empty;

                owner.SetAttributeValue("name", ownerString);
                owners.Add(owner);
                unitTest.Add(owners);

                if (!string.IsNullOrEmpty(test.Description))
                {
                    SimpleXElement description = CreateElement("Description");
                    description.SetValue(test.Description);
                    unitTest.Add(description);
                }

                SimpleXElement execution = CreateElement("Execution");

                execution.SetAttributeValue("id", executionId);
                unitTest.Add(execution);

                // TestMethod element.
                SimpleXElement testMethod = CreateElement("TestMethod");

                testMethod.SetAttributeValue("codeBase", codeBase);
                testMethod.SetAttributeValue("adapterTypeName", adapterTypeName);
                testMethod.SetAttributeValue("className", className);
                testMethod.SetAttributeValue("name", name);
                unitTest.Add(testMethod);

                TestDefinitions.Add(unitTest);

                // TestEntry element.
                SimpleXElement testEntry = CreateElement("TestEntry");

                testEntry.SetAttributeValue("testId", testId);
                testEntry.SetAttributeValue("executionId", executionId);
                testEntry.SetAttributeValue("testListId", testListId);
                TestEntries.Add(testEntry);

                // UnitTestResult element.
                SimpleXElement unitTestResult = CreateElement("UnitTestResult");

                unitTestResult.SetAttributeValue("executionId", executionId);
                unitTestResult.SetAttributeValue("testId", testId);
                unitTestResult.SetAttributeValue("testName", name);
                unitTestResult.SetAttributeValue("computerName", computerName);

                TimeSpan duration = endTime.Subtract(startTime);

                unitTestResult.SetAttributeValue("duration", duration.ToString());

                unitTestResult.SetAttributeValue("startTime", ToDateString(startTime));
                unitTestResult.SetAttributeValue("endTime", ToDateString(endTime));
                unitTestResult.SetAttributeValue("testType", UnitTestTestTypeId);
                unitTestResult.SetAttributeValue("outcome", outcome.ToString());
                unitTestResult.SetAttributeValue("testListId", testListId.ToString());

                // Add any pending items
                foreach (SimpleXElement pending in _pendingElements)
                {
                    unitTestResult.Add(pending);
                }
                _pendingElements.Clear();

                Results.Add(unitTestResult);
            }
Exemple #12
0
 private static void SecondPass(VersionHandler handler, int[] maxCharacters, List<DeviceResult> initialResults, Results results)
 {
     int lowestScore = int.MaxValue;
     foreach (DeviceResult current in initialResults)
     {
         // Calculate the score for this device.
         int deviceScore = 0;
         for (int segment = 0; segment < handler.VersionRegexes.Length; segment++)
         {
             deviceScore += (maxCharacters[segment] - current.Scores[segment].CharactersMatched + 1)*
                            (current.Scores[segment].Difference + maxCharacters[segment] -
                             current.Scores[segment].CharactersMatched);
         }
         // If the score is lower than the lowest so far then reset the list
         // of best matching devices.
         if (deviceScore < lowestScore)
         {
             results.Clear();
             lowestScore = deviceScore;
         }
         // If the device score is the same as the lowest score so far then add this
         // device to the list.
         if (deviceScore == lowestScore)
         {
             results.Add(current.Device);
         }
     }
 }
Exemple #13
0
        protected override void Run()
        {
            var solution = CreateZeroRSolution(Problem.ProblemData);

            Results.Add(new Result("ZeroR solution", "The simplest possible classifier, ZeroR always predicts the majority class.", solution));
        }
Exemple #14
0
 public Row(string owner)
 {
     Results.Add(owner, new MatchResult('X', 0));
 }
Exemple #15
0
        private async Task AllCompanyScoresYieldResults(IEnumerable <ScoringParam> sps)
        {
            foreach (ScoringParam sp in sps)
            {
                // 2. There are companies with non-zero values
                string scoreTable;
                switch (sp.ScoringType)
                {
                case CompanyScoringType.CompanyTextBagOfWords:
                case CompanyScoringType.PatentClassProfile:
                case CompanyScoringType.TopicScore:
                    scoreTable = "company_score_real";
                    break;

                case CompanyScoringType.IndustryAttribute:
                    scoreTable = "company_score_str";
                    break;

                case CompanyScoringType.OrbisTemporalAttribute:
                    scoreTable = (sp.ScoreDataType == "real" ? "company_time_score_real" : scoreTable = "company_time_score_int");
                    break;

                case CompanyScoringType.ManualScore:
                    scoreTable = (sp.ScoreDataType == "real" ? "company_score_real" : (sp.ScoreDataType == "nvarchar" ? scoreTable = "company_score_str" : scoreTable = "company_score_int"));
                    break;

                case CompanyScoringType.OrbisAttribute:
                    scoreTable = "unknown";
                    break;

                default:
                    scoreTable = "unknown";
                    break;
                }

                using (var cmd = Db.CreateCommand())
                {
                    if (scoreTable == "unknown")
                    {
                        cmd.CommandText = @"select
                                                count(distinct isnull(csr.company_id,isnull(csi.company_id,isnull(css.company_id,isnull(csrt.company_id,csit.company_id))))) as NumberOfScoredCompanies
                                            from
                                                (select @p1 as score_name) s LEFT OUTER JOIN
                                                company_score_real csr ON csr.score_name=s.score_name LEFT OUTER JOIN
                                                company_score_int csi ON csi.score_name=s.score_name LEFT OUTER JOIN
                                                company_score_str css ON css.score_name=s.score_name LEFT OUTER JOIN
                                                company_time_score_real csrt ON csrt.score_name=s.score_name LEFT OUTER JOIN
                                                company_time_score_int csit ON csit.score_name=s.score_name";
                    }
                    else
                    {
                        cmd.CommandText = @"select
                                                count(distinct company_id) as NumberOfScoredCompanies
                                            from
                                                " + scoreTable + @"
                                            where
                                                score_name=@p1";
                    }

                    cmd.Parameters.AddWithValue("@p1", sp.ScoringLabel);

                    using (var reader = await cmd.ExecuteReaderAsync())
                    {
                        while (await reader.ReadAsync() && !Program.StopNow)
                        {
                            int nc = (int)reader["NumberOfScoredCompanies"];
                            Results.Add(new TestResult
                            {
                                Message = String.Format("Encountered {1} score-values for [{0}].", sp.ScoringLabel, nc),
                                Name    = "ScoresHaveValues",
                                Success = (nc > 0),
                            });
                        }
                    }
                }
            }
        }
Exemple #16
0
        public void SendMails()
        {
            try
            {
                logger.Debug("Summarized mails...");
                foreach (var mailcache in MailCaches)
                {
                    var summarizedMail = GetMailFromSummarizedMailList(mailcache.Settings);
                    if (summarizedMail == null)
                    {
                        logger.Debug("Create new mail for summarized mail list...");
                        var mailTo   = mailcache.Settings?.To?.Replace(";", ",")?.TrimEnd(',') ?? "No mail recipient was specified.";
                        var mailFrom = mailcache.Settings?.MailServer?.From ?? "No sender was specified.";
                        summarizedMail = new MailMessage(mailFrom, mailTo)
                        {
                            BodyEncoding    = Encoding.UTF8,
                            SubjectEncoding = Encoding.UTF8,
                            Subject         = mailcache.Settings?.Subject?.Trim() ?? "No subject was specified.",
                        };

                        var ccAddresses = mailcache.Settings?.Cc?.Replace(";", ",")?.TrimEnd(',');
                        if (!String.IsNullOrEmpty(ccAddresses))
                        {
                            summarizedMail.CC.Add(ccAddresses);
                        }

                        var bccAddresses = mailcache.Settings?.Bcc?.Replace(";", ",")?.TrimEnd(',');
                        if (!String.IsNullOrEmpty(bccAddresses))
                        {
                            summarizedMail.Bcc.Add(bccAddresses);
                        }

                        var msgBody = mailcache.Settings?.Message?.Trim() ?? String.Empty;
                        switch (mailcache.Settings?.MailType ?? EMailType.TEXT)
                        {
                        case EMailType.TEXT:
                            msgBody = msgBody.Replace("{n}", Environment.NewLine);
                            break;

                        case EMailType.HTML:
                            summarizedMail.IsBodyHtml = true;
                            break;

                        case EMailType.MARKDOWN:
                            summarizedMail.IsBodyHtml = true;
                            msgBody = Markdown.ToHtml(msgBody);
                            break;

                        default:
                            throw new Exception($"Unknown mail type {mailcache.Settings?.MailType}.");
                        }
                        msgBody = msgBody.Trim();
                        logger.Debug($"Set mail body '{msgBody}'...");
                        summarizedMail.Body = msgBody;
                        if (mailcache.Settings.SendAttachment)
                        {
                            logger.Debug($"Attachment report files...");
                            AddReportstoMail(summarizedMail, mailcache.Report);
                        }
                        else
                        {
                            logger.Debug($"Use no mail attachment...");
                        }
                        SummarizedMails.Add(summarizedMail);
                    }
                    else
                    {
                        logger.Debug("Duplicate Mail settings was found in summarized mail list...");
                        if (mailcache.Settings.SendAttachment)
                        {
                            logger.Debug($"Attachment report files...");
                            AddReportstoMail(summarizedMail, mailcache.Report);
                        }
                        else
                        {
                            logger.Debug($"Use no mail attachment...");
                        }
                    }
                }

                var mailServers = MailCaches.Select(c => c.Settings).Select(s => s.MailServer).GroupBy(s => s.Host).Select(s => s.First()).ToList();
                logger.Debug($"Send {SummarizedMails.Count} Mails over {MailCaches.Count} mail servers...");
                foreach (var mailServer in mailServers)
                {
                    var mailResult = new MailResult();

                    try
                    {
                        foreach (var summarizedMail in SummarizedMails)
                        {
                            using var client = new SmtpClient(mailServer.Host, mailServer.Port);
                            var priateKeyPath = HelperUtilities.GetFullPathFromApp(mailServer.PrivateKey);
                            if (!File.Exists(priateKeyPath))
                            {
                                logger.Debug("No private key path found...");
                            }

                            if (!String.IsNullOrEmpty(mailServer.Username) && !String.IsNullOrEmpty(mailServer.Password))
                            {
                                logger.Debug($"Set mail server credential for user '{mailServer.Username}'...");
                                var password = mailServer.Password;
                                if (mailServer.UseBase64Password && File.Exists(priateKeyPath))
                                {
                                    logger.Debug($"Use private key path {priateKeyPath}...");
                                    var textCrypter = new TextCrypter(priateKeyPath);
                                    password = textCrypter.DecryptText(password);
                                }
                                client.Credentials = new NetworkCredential(mailServer.Username, password);
                            }
                            else
                            {
                                logger.Debug($"No mail server credential found...");
                            }

                            if (mailServer.UseSsl)
                            {
                                logger.Debug($"Use SSL for mail sending...");
                                client.EnableSsl = true;
                            }

                            if (mailServer.UseCertificate && File.Exists(priateKeyPath))
                            {
                                var certifcateFolder = Path.GetDirectoryName(priateKeyPath);
                                logger.Info($"Search for email certificates with name 'mailcert.*' in folder '{certifcateFolder}'...");
                                var certFiles = Directory.GetFiles(certifcateFolder, "mailcert.*", SearchOption.TopDirectoryOnly);
                                foreach (var certFile in certFiles)
                                {
                                    logger.Debug($"Load certificate '{certFile}'.");
                                    var x509File = new X509Certificate2(certFile);
                                    logger.Debug($"Add certificate '{certFile}'.");
                                    client.ClientCertificates.Add(x509File);
                                }
                            }

                            if (summarizedMail.To.Count > 0)
                            {
                                var delay = 0;
                                if (mailServer.SendDelay > 0)
                                {
                                    delay = mailServer.SendDelay * 1000;
                                    logger.Debug($"Wait {delay} milliseconds for the mail to be sent...");
                                }

                                Task.Delay(delay).ContinueWith(r =>
                                {
                                    logger.Debug("Send mail package...");
                                    client.Send(summarizedMail);

                                    mailResult.Message     = "The mail was sent successfully.";
                                    mailResult.Success     = true;
                                    mailResult.TaskName    = JobResult.TaskName;
                                    mailResult.ReportState = GetFormatedState();
                                }).Wait();
                            }
                            else
                            {
                                mailResult.Message = "Mail without mail Address could not be sent.";
                                logger.Error(mailResult.Message);
                                mailResult.Success     = false;
                                mailResult.TaskName    = JobResult.TaskName;
                                mailResult.ReportState = "ERROR";
                                JobResult.Exception    = ReportException.GetException(mailResult.Message);
                                JobResult.Status       = TaskStatusInfo.ERROR;
                            }

                            client.Dispose();
                            Results.Add(mailResult);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex, $"The delivery via 'Mail' failed with server '{mailServer.Host}'.");
                        JobResult.Exception    = ReportException.GetException(ex);
                        JobResult.Status       = TaskStatusInfo.ERROR;
                        mailResult.Success     = false;
                        mailResult.ReportState = "ERROR";
                        mailResult.TaskName    = JobResult.TaskName;
                        mailResult.Message     = JobResult?.Exception?.FullMessage ?? null;
                        Results.Add(mailResult);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "The delivery via 'Mail' failed.");
                JobResult.Exception = ReportException.GetException(ex);
                JobResult.Status    = TaskStatusInfo.ERROR;
                var errorResult = new MailResult()
                {
                    Success     = false,
                    ReportState = "ERROR",
                    TaskName    = JobResult?.TaskName ?? "Unknown Task",
                    Message     = JobResult?.Exception?.FullMessage ?? null
                };
                Results.Add(errorResult);
            }
        }
        public static void benchmarkGraph(Graph graph, int avg_iterations, bool usebrute)
        {
            Results results = new Results();

            Console.WriteLine("Benchmarking graph with {0} vertices and {1} edges.", graph.VerticesCount, graph.EdgesCount);

            for (int i = 0; i < avg_iterations; i++)
            {
                Result res = new Result();
                res.vertices = graph.VerticesCount;
                res.edges    = graph.EdgesCount;

                int[]     result;
                long      elapsedMs;
                Stopwatch watch;

                Console.WriteLine("Starting iteration " + i);

                if (usebrute)
                {
                    watch  = System.Diagnostics.Stopwatch.StartNew();
                    result = BruteForce.Solve(ref graph);
                    watch.Stop();
                    elapsedMs = watch.ElapsedMilliseconds;
                    bool tmp = graph.IsColoringValid();
                    res.bruteChromaticNum = graph.ChromaticNumber();
                    res.bruteTimeMs       = elapsedMs;
                    res.bruteValid        = graph.IsColoringValid();
                }

                watch  = System.Diagnostics.Stopwatch.StartNew();
                result = SmallestLast.Solve(ref graph);
                watch.Stop();
                elapsedMs = watch.ElapsedMilliseconds;
                res.smallestlastChromaticNum = graph.ChromaticNumber();
                res.smallestlastTimeMs       = elapsedMs;
                res.smallestlastValid        = graph.IsColoringValid();

                watch  = System.Diagnostics.Stopwatch.StartNew();
                result = DSatur.Solve(ref graph);
                watch.Stop();
                elapsedMs = watch.ElapsedMilliseconds;
                res.dsaturChromaticNum = graph.ChromaticNumber();
                res.dsaturTimeMs       = elapsedMs;
                res.dsaturValid        = graph.IsColoringValid();

                watch  = System.Diagnostics.Stopwatch.StartNew();
                result = BFSColoring.Solve(ref graph);
                watch.Stop();
                elapsedMs           = watch.ElapsedMilliseconds;
                res.bfsChromaticNum = graph.ChromaticNumber();
                res.bfsTimeMs       = elapsedMs;
                res.bfsValid        = graph.IsColoringValid();

                results.Add(res);

                //Console.WriteLine(String.Format("{0};{1};{2};{3};{4};{5};{6};{7};",
                //   res.bruteTimeMs, res.bruteChromaticNum,
                //   res.smallestlastTimeMs, res.smallestlastChromaticNum,
                //   res.bfsTimeMs, res.bfsChromaticNum,
                //   res.dsaturTimeMs, res.dsaturChromaticNum));
            }
            Console.WriteLine("Brute ms;XBrute;BFS ms;Xbfs;DS ms;Xds;SL ms;Xsl");
            Console.WriteLine(String.Format("{0};{1};{2};{3};{4};{5};{6};{7};"
                                            , results.AvgBruteMs(), results.AvgBruteChromaticNum()
                                            , results.AvgBFSMs(), results.AvgBFSChromaticNum()
                                            , results.AvgDSMs(), results.AvgDSChromaticNum()
                                            , results.AvgSLMs(), results.AvgSLChromaticNum()));

            Console.WriteLine("Benchmark done. Press key to exit...");
            Console.ReadKey();
        }
Exemple #18
0
        public IResults Geocode(string _address)
        {
            Results results = new Results();
            Uri uriRequest = new Uri(c_strRequestUri + "\"" + _address + "\"");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriRequest);

            WebProxy proxy = null;

            IWebProxy proxySystem = HttpWebRequest.GetSystemWebProxy();
            Uri uriProxy = proxySystem.GetProxy(uriRequest);

            if (uriProxy != uriRequest)
            {
                proxy = new WebProxy(uriProxy);
                proxy.UseDefaultCredentials = true;
                request.Proxy = proxy;
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            String content = new StreamReader(response.GetResponseStream()).ReadToEnd();

            Regex reg = new Regex(
                "\"Name\":\"(?<name>.*?)\".*?,\"BestLocation\":{.*?\"Latitude\":(?<lat>.*?),\"Longitude\":(?<lon>.*?)}}.*?\"Locality\":\"(?<locality>.*?)\",.*?\"AdminDistrict\":\"(?<state>.*?)\",\"PostalCode\":\"(?<code>.*?)\",\"CountryRegion\":\"(?<country>.*?)\""
                , RegexOptions.IgnoreCase);

            foreach (Match match in reg.Matches(content)) //mResult.Result("${result}"
            {
                Result r = new Result();

                r.Address = match.Result("${name}");
                r.Country = match.Result("${country}");
                r.City = match.Result("${locality}");
                r.State = match.Result("${state}");
                r.Zip = match.Result("${code}");
                try {
                    r.Latitude = Double.Parse(match.Result("${lat}"));
                    r.Longitude = Double.Parse(match.Result("${lon}"));
                }
                catch (ArgumentNullException) { }
                catch (FormatException) { }
                catch (OverflowException) { }

                results.Add(r);
            }

            /*
            Regex regex = new Regex(@"AddLocation\(.*?\)", RegexOptions.IgnoreCase);
            MatchCollection matchCollection = regex.Matches(content);

            foreach (Match match in matchCollection)
            {
                Double dLongitude;
                Double dLatitude;

                String m = match.Value.Remove(0, 12); m = m.Remove(m.Length - 1);
                if (!m.StartsWith("'")) continue;
                Int32 a = m.IndexOf("'", 1); if (a == -1) continue;
                String address = HttpUtility.HtmlDecode(m.Substring(1, a - 1));
                m = m.Substring(a + 1);
                String[] marr = m.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                try
                {
                    dLongitude = Convert.ToDouble(marr[1].Trim(), CultureInfo.InvariantCulture);
                    dLatitude = Convert.ToDouble(marr[0].Trim(), CultureInfo.InvariantCulture);
                }
                catch (InvalidCastException) { continue; }

                results.Add(new Result(address, dLongitude, dLatitude));
            }

            regex = new Regex(@"new Array\('.*?',.*?\)", RegexOptions.IgnoreCase);
            matchCollection = regex.Matches(content);

            foreach (Match match in matchCollection)
            {
                Double dLongitude;
                Double dLatitude;

                String m = match.Value.Remove(0, 10); m = m.Remove(m.Length - 1);
                if (!m.StartsWith("'")) continue;
                Int32 a = m.IndexOf("'", 1); if (a == -1) continue;
                String address = HttpUtility.HtmlDecode(m.Substring(1, a - 1));
                m = m.Substring(a + 1);
                String[] marr = m.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                try
                {
                    dLongitude = (Convert.ToDouble(marr[1].Trim(), CultureInfo.InvariantCulture) + Convert.ToDouble(marr[3].Trim(), CultureInfo.InvariantCulture)) / 2;
                    dLatitude = (Convert.ToDouble(marr[0].Trim(), CultureInfo.InvariantCulture) + Convert.ToDouble(marr[2].Trim(), CultureInfo.InvariantCulture)) / 2;
                }
                catch (InvalidCastException) { continue; }

                results.Add(new Result(address, dLongitude, dLatitude));
            }

            if (results.Count == 0)
            {
                regex = new Regex(@"SetViewport\(.*?\)", RegexOptions.IgnoreCase);
                Match match = regex.Match(content);
                if (match.Success)
                {
                    Double dLongitude;
                    Double dLatitude;

                    String m = match.Value.Remove(0, 12); m = m.Remove(m.Length - 1);
                    String[] marr = m.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    try
                    {
                        dLongitude = (Convert.ToDouble(marr[1].Trim(), CultureInfo.InvariantCulture) + Convert.ToDouble(marr[3].Trim(), CultureInfo.InvariantCulture)) / 2;
                        dLatitude = (Convert.ToDouble(marr[0].Trim(), CultureInfo.InvariantCulture) + Convert.ToDouble(marr[2].Trim(), CultureInfo.InvariantCulture)) / 2;
                        results.Add(new Result("", dLongitude, dLatitude));
                    }
                    catch (InvalidCastException) { }
                }
            }
            */

            return results;
        }
Exemple #19
0
        private async void OnStopped(Results results)
        {
            string reason = results.TryFindString("reason");

            if (reason.StartsWith("exited"))
            {
                string threadGroupId = results.TryFindString("id");
                if (!String.IsNullOrEmpty(threadGroupId))
                {
                    lock (_debuggeePids)
                    {
                        _debuggeePids.Remove(threadGroupId);
                    }
                }

                if (IsLocalGdbAttach())
                {
                    CmdExitAsync();
                }

                this.ProcessState = ProcessState.Exited;
                if (ProcessExitEvent != null)
                {
                    ProcessExitEvent(this, new ResultEventArgs(results));
                }
                return;
            }

            //if this is an exception reported from LLDB, it will not currently contain a frame object in the MI
            //if we don't have a frame, check if this is an excpetion and retrieve the frame
            if (!results.Contains("frame") &&
                string.Compare(reason, "exception-received", StringComparison.OrdinalIgnoreCase) == 0
                )
            {
                //get the info for the current frame
                Results frameResult = await MICommandFactory.StackInfoFrame();

                //add the frame to the stopping results
                results.Add("frame", frameResult.Find("frame"));
            }

            bool fIsAsyncBreak = MICommandFactory.IsAsyncBreakSignal(results);
            if (await DoInternalBreakActions(fIsAsyncBreak))
            {
                return;
            }

            this.ProcessState = ProcessState.Stopped;
            FlushBreakStateData();

            if (!results.Contains("frame"))
            {
                if (ModuleLoadEvent != null)
                {
                    ModuleLoadEvent(this, new ResultEventArgs(results));
                }
            }
            else if (BreakModeEvent != null)
            {
                if (fIsAsyncBreak) { _requestingRealAsyncBreak = false; }
                BreakModeEvent(this, new ResultEventArgs(results));
            }
        }
Exemple #20
0
        public override void Search()
        {
            Results.Clear();

            byte[]        text = (byte[])Params["text"];
            ProcessHandle phandle;
            int           count = 0;

            bool opt_priv = (bool)Params["private"];
            bool opt_img  = (bool)Params["image"];
            bool opt_map  = (bool)Params["mapped"];

            bool nooverlap = (bool)Params["nooverlap"];

            if (text.Length == 0)
            {
                CallSearchFinished();
                return;
            }

            try
            {
                phandle = new ProcessHandle(PID, ProcessAccess.QueryInformation | Program.MinProcessReadMemoryRights);
            }
            catch
            {
                CallSearchError("Could not open process: " + Win32.GetLastErrorMessage());
                return;
            }

            phandle.EnumMemory(info =>
            {
                // skip unreadable areas
                if (info.Protect == MemoryProtection.AccessDenied)
                {
                    return(true);
                }
                if (info.State != MemoryState.Commit)
                {
                    return(true);
                }

                if ((!opt_priv) && (info.Type == MemoryType.Private))
                {
                    return(true);
                }

                if ((!opt_img) && (info.Type == MemoryType.Image))
                {
                    return(true);
                }

                if ((!opt_map) && (info.Type == MemoryType.Mapped))
                {
                    return(true);
                }

                byte[] data   = new byte[info.RegionSize.ToInt32()];
                int bytesRead = 0;

                CallSearchProgressChanged(
                    String.Format("Searching 0x{0} ({1} found)...", info.BaseAddress.ToString("x"), count));

                try
                {
                    bytesRead = phandle.ReadMemory(info.BaseAddress, data, data.Length);

                    if (bytesRead == 0)
                    {
                        return(true);
                    }
                }
                catch
                {
                    return(true);
                }

                for (int i = 0; i < bytesRead; i++)
                {
                    bool good = true;

                    for (int j = 0; j < text.Length; j++)
                    {
                        if (i + j > bytesRead - 1)
                        {
                            continue;
                        }

                        if (data[i + j] != text[j])
                        {
                            good = false;
                            break;
                        }
                    }

                    if (good)
                    {
                        Results.Add(new string[]
                        {
                            Utils.FormatAddress(info.BaseAddress),
                            String.Format("0x{0:x}", i), text.Length.ToString(), ""
                        });

                        count++;

                        if (nooverlap)
                        {
                            i += text.Length - 1;
                        }
                    }
                }

                return(true);
            });

            phandle.Dispose();

            CallSearchFinished();
        }
Exemple #21
0
        protected override void Run(CancellationToken cancellationToken)
        {
            var solution = CreateOneRSolution(Problem.ProblemData, MinBucketSizeParameter.Value.Value);

            Results.Add(new Result("OneR solution", "The 1R classifier.", solution));
        }
Exemple #22
0
        public void Insert(string search, Item item, ref MergeResult result, int pos = 0)
        {
            TraversalOption nextStep = new TraversalOption(Label, search, pos);

            switch (nextStep.option)
            {
            case TraversalOptions.Found:
                if (!Items.Any(item1 => item1.ComparePath(item)))
                {
                    Items.Add(item);
                    Results.Add(item);
                    result.ToBeMergedInto = Results;
                    result.NeedsMerge     = true;
                }
                break;

            case TraversalOptions.MoveNext:
                if (NextNode == null)
                {
                    NextNode = new SearchNode {
                        Label = search.Substring(pos)
                    };
                    NextNode.Items.Add(item);
                    NextNode.Results.Add(item);
                    result.ToBeMergedInto = NextNode.Results;
                    result.NeedsMerge     = true;
                }
                else
                {
                    NextNode.Insert(search, item, ref result, pos);
                }
                break;

            case TraversalOptions.MoveDown:
                if (ChildNode == null)
                {
                    ChildNode = new SearchNode()
                    {
                        Label = search.Substring(pos + nextStep.commonPrefixLength),
                        Items = new List <Item>(),
                    };
                    ChildNode.Items.Add(item);
                    ChildNode.Results.Add(item);
                    result.ToBeMergedInto = ChildNode.Results;
                    result.NeedsMerge     = true;
                    if (result.NeedsMerge)
                    {
                        result.NeedsMerge     = Results.MergeIntoList(result.ToBeMergedInto) > 0;
                        result.ToBeMergedInto = Results;
                    }
                }
                else
                {
                    ChildNode.Insert(search, item, ref result, pos + nextStep.commonPrefixLength);
                    if (result.NeedsMerge)
                    {
                        result.NeedsMerge     = Results.MergeIntoList(result.ToBeMergedInto) > 0;
                        result.ToBeMergedInto = Results;
                    }
                }
                break;

            case TraversalOptions.Split:
                SearchNode newNode = new SearchNode
                {
                    Label     = Label.Substring(nextStep.commonPrefixLength),
                    Items     = Items,
                    Results   = Results,
                    ChildNode = ChildNode
                };

                Items     = new List <Item>();
                Results   = new MergedResultList(newNode.ResultItems);
                Label     = Label.Substring(0, nextStep.commonPrefixLength);
                ChildNode = newNode;
                if (search.Length == nextStep.commonPrefixLength + pos)
                {
                    Items.Add(item);
                    Results.Add(item);
                }
                else
                {
                    SearchNode toInsert = new SearchNode
                    {
                        Label = search.Substring(nextStep.commonPrefixLength + pos),
                        Items = new List <Item> {
                            item
                        },
                        Results = new MergedResultList(new List <Item> {
                            item
                        })
                    };
                    Results.MergeIntoList(toInsert.Results);
                    newNode.NextNode = toInsert;
                }

                result.ToBeMergedInto = Results;
                result.NeedsMerge     = true;
                break;
            }
        }
Exemple #23
0
            private CharacterGroupListItemViewModel?GenerateFrom(CharacterGroup characterGroup, int deepLevel, IList <CharacterGroup> pathToTop)
            {
                if (!characterGroup.IsVisible(CurrentUserId))
                {
                    return(null);
                }
                var prevCopy = Results.FirstOrDefault(cg => cg.FirstCopy && cg.CharacterGroupId == characterGroup.CharacterGroupId);

                var vm = new CharacterGroupListItemViewModel
                {
                    CharacterGroupId    = characterGroup.CharacterGroupId,
                    DeepLevel           = deepLevel,
                    Name                = characterGroup.CharacterGroupName,
                    FirstCopy           = prevCopy == null,
                    AvaiableDirectSlots = characterGroup.HaveDirectSlots ? characterGroup.AvaiableDirectSlots : 0,
                    IsAcceptingClaims   = characterGroup.IsAcceptingClaims(),
                    ActiveCharacters    =
                        prevCopy?.ActiveCharacters ??
                        GenerateCharacters(characterGroup)
                        .ToList(),
                    Description       = characterGroup.Description.ToHtmlString(),
                    ActiveClaimsCount = characterGroup.Claims.Count(c => c.ClaimStatus.IsActive()),
                    Path        = pathToTop.Select(cg => Results.First(item => item.CharacterGroupId == cg.CharacterGroupId)),
                    IsPublic    = characterGroup.IsPublic,
                    IsSpecial   = characterGroup.IsSpecial,
                    IsRootGroup = characterGroup.IsRoot,
                    ProjectId   = characterGroup.ProjectId,
                    RootGroupId = Root.CharacterGroupId,
                };

                if (Root == characterGroup)
                {
                    vm.First = true;
                    vm.Last  = true;
                }

                if (vm.IsSpecial)
                {
                    var variant = characterGroup.GetBoundFieldDropdownValueOrDefault();

                    if (variant != null)
                    {
                        vm.BoundExpression = $"{variant.ProjectField.FieldName} = {variant.Label}";
                    }
                }

                Results.Add(vm);

                if (prevCopy != null)
                {
                    vm.ChildGroups = prevCopy.ChildGroups;
                    return(vm);
                }

                var childGroups     = characterGroup.GetOrderedChildGroups().OrderBy(g => g.IsSpecial).Where(g => g.IsActive && g.IsVisible(CurrentUserId)).ToList();
                var pathForChildren = pathToTop.Union(new[] { characterGroup }).ToList();

                vm.ChildGroups = childGroups.Select(childGroup => GenerateFrom(childGroup, deepLevel + 1, pathForChildren)).ToList().MarkFirstAndLast();

                return(vm);
            }
Exemple #24
0
 internal void Add(PartialResult partialResult)
 {
     Results.Add(partialResult);
 }
        protected override void Run(CancellationToken cancellationToken)
        {
            IRegressionProblemData problemData            = Problem.ProblemData;
            IEnumerable <string>   selectedInputVariables = problemData.AllowedInputVariables;
            int nSv;
            ISupportVectorMachineModel model;

            Run(problemData, selectedInputVariables, SvmType.Value, KernelType.Value, Cost.Value, Nu.Value, Gamma.Value, Epsilon.Value, Degree.Value, out model, out nSv);

            if (CreateSolution)
            {
                var solution = new SupportVectorRegressionSolution((SupportVectorMachineModel)model, (IRegressionProblemData)problemData.Clone());
                Results.Add(new Result("Support vector regression solution", "The support vector regression solution.", solution));
            }

            Results.Add(new Result("Number of support vectors", "The number of support vectors of the SVR solution.", new IntValue(nSv)));


            {
                // calculate regression model metrics
                var ds         = problemData.Dataset;
                var trainRows  = problemData.TrainingIndices;
                var testRows   = problemData.TestIndices;
                var yTrain     = ds.GetDoubleValues(problemData.TargetVariable, trainRows);
                var yTest      = ds.GetDoubleValues(problemData.TargetVariable, testRows);
                var yPredTrain = model.GetEstimatedValues(ds, trainRows).ToArray();
                var yPredTest  = model.GetEstimatedValues(ds, testRows).ToArray();

                OnlineCalculatorError error;
                var trainMse = OnlineMeanSquaredErrorCalculator.Calculate(yPredTrain, yTrain, out error);
                if (error != OnlineCalculatorError.None)
                {
                    trainMse = double.MaxValue;
                }
                var testMse = OnlineMeanSquaredErrorCalculator.Calculate(yPredTest, yTest, out error);
                if (error != OnlineCalculatorError.None)
                {
                    testMse = double.MaxValue;
                }

                Results.Add(new Result("Mean squared error (training)", "The mean of squared errors of the SVR solution on the training partition.", new DoubleValue(trainMse)));
                Results.Add(new Result("Mean squared error (test)", "The mean of squared errors of the SVR solution on the test partition.", new DoubleValue(testMse)));


                var trainMae = OnlineMeanAbsoluteErrorCalculator.Calculate(yPredTrain, yTrain, out error);
                if (error != OnlineCalculatorError.None)
                {
                    trainMae = double.MaxValue;
                }
                var testMae = OnlineMeanAbsoluteErrorCalculator.Calculate(yPredTest, yTest, out error);
                if (error != OnlineCalculatorError.None)
                {
                    testMae = double.MaxValue;
                }

                Results.Add(new Result("Mean absolute error (training)", "The mean of absolute errors of the SVR solution on the training partition.", new DoubleValue(trainMae)));
                Results.Add(new Result("Mean absolute error (test)", "The mean of absolute errors of the SVR solution on the test partition.", new DoubleValue(testMae)));


                var trainRelErr = OnlineMeanAbsolutePercentageErrorCalculator.Calculate(yPredTrain, yTrain, out error);
                if (error != OnlineCalculatorError.None)
                {
                    trainRelErr = double.MaxValue;
                }
                var testRelErr = OnlineMeanAbsolutePercentageErrorCalculator.Calculate(yPredTest, yTest, out error);
                if (error != OnlineCalculatorError.None)
                {
                    testRelErr = double.MaxValue;
                }

                Results.Add(new Result("Average relative error (training)", "The mean of relative errors of the SVR solution on the training partition.", new DoubleValue(trainRelErr)));
                Results.Add(new Result("Average relative error (test)", "The mean of relative errors of the SVR solution on the test partition.", new DoubleValue(testRelErr)));
            }
        }
Exemple #26
0
        public void ProcessTemplate()
        {
            // Initialize the template
            TemplateContext.Iterators.Clear();
            TemplateClass.TemplateSetup();

            foreach (
                var item in
                TemplateClass.GetType()
                .GetCustomAttributes(typeof(TemplateAttribute), true)
                .OfType <TemplateAttribute>().OrderBy(p => p.Priority))
            {
                item.Modify(TemplateClass, null, TemplateContext);
            }

            var initializeMethods = TemplateClass.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public).Where(p => p.IsDefined(typeof(TemplateSetup), true)).ToArray();

            foreach (var item in initializeMethods)
            {
                item.Invoke(TemplateClass, null);
            }

            InvertApplication.SignalEvent <ICodeTemplateEvents>(_ => _.TemplateGenerating(TemplateClass, TemplateContext));


            foreach (var templateProperty in TemplateProperties)
            {
                if (FilterToMembers != null && !FilterToMembers.Contains(templateProperty.Key.Name))
                {
                    continue;
                }
                foreach (var item in TemplateContext.RenderTemplateProperty(TemplateClass, templateProperty))
                {
                    Results.Add(new TemplateMemberResult(this, templateProperty.Key, templateProperty.Value, item, Decleration));
                }
            }

            foreach (var templateMethod in TemplateMethods)
            {
                if (FilterToMembers != null && !FilterToMembers.Contains(templateMethod.Key.Name))
                {
                    continue;
                }
                foreach (var item in TemplateContext.RenderTemplateMethod(TemplateClass, templateMethod))
                {
                    Results.Add(new TemplateMemberResult(this, templateMethod.Key, templateMethod.Value, item, Decleration));
                }
            }

            foreach (var templateConstructor in TemplateConstructors)
            {
                if (FilterToMembers != null && !FilterToMembers.Contains(templateConstructor.Key.Name))
                {
                    continue;
                }
                foreach (var item in TemplateContext.RenderTemplateConstructor(TemplateClass, templateConstructor))
                {
                    Results.Add(new TemplateMemberResult(this, templateConstructor.Key, templateConstructor.Value, item, Decleration));
                }
            }
            var postMethods = TemplateClass.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public).Where(p => p.IsDefined(typeof(TemplateComplete), true)).ToArray();

            foreach (var item in postMethods)
            {
                item.Invoke(TemplateClass, null);
            }

            var list = new List <CodeNamespaceImport>();

            foreach (var item in TemplateContext.Namespace.Imports)
            {
                list.Add((CodeNamespaceImport)item);
            }
            TemplateContext.Namespace.Imports.Clear();
            foreach (var item in list.OrderBy(p => p.Namespace))
            {
                TemplateContext.Namespace.Imports.Add(item);
            }
        }
Exemple #27
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// \fn public override void ReceiveHandling(BaseMessage message)
        ///
        /// \brief Receive handling.
        ///
        /// \par Description.
        /// -#  This method is activated when a new message arrived to the process
        /// -#  The method processing is done according to their arrival order
        /// -#  If you want to change the order of processing use the ArrangeMessageQ
        ///
        /// \par Algorithm.
        ///
        /// \par Usage Notes.
        /// Usually the algorithm of this method is:
        /// -#  if message type is ... perform ...
        /// -#  if message type is ... perform ...
        ///
        /// \author Ilan Hindy
        /// \date 26/01/2017
        ///
        /// \param message The message.
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        //public override void ReceiveHandling(BaseMessage message)
        //{
        //ChandyLamport_NewStyleChannel channel = (ChandyLamport_NewStyleChannel)ChannelFrom(message);
        //ChandyLamport_NewStyleMessage msg = message as ChandyLamport_NewStyleMessage;
        //switch ((msg.MessageType)
        //{
        //    case BaseMessage:

        //        // If the process performed snapshot but still did not get marker from all
        //        // it's neighbors :
        //        // Save the message - It will be sent as message in the channels
        //        if (Recordered && !channel.Recorderd)
        //        {
        //            channel.State.Add(msg.Name);
        //        }
        //        break;
        //    case (int)Marker:

        //        // If the process received a marker:
        //        // Add the weight in the marker
        //        // Perform TakeSnapshot (If first Marker in round - Send Marker to all the neighbors)
        //        Weight += msg.MarkerWeight;
        //        TakeSnapshot();

        //        // Check if the round ended (Received Marker from all it's neighbors)
        //        // Perform EndSnapshot (Send Report, reset variables)
        //        channel.or[c.ork.Recorderd] = true;
        //        if (InChannels.All(cnl => cnl.or[c.ork.Recorderd]))
        //        {
        //            EndSnapshot();
        //        }

        //        // Change the text on the process because the weight changed
        //        pp[bp.ppk.Text] = GetProcessDefaultName() + "\n" + or[p.ork.Weight];
        //        break;
        //    case m.MessageTypes.Report:

        //        // If received a Report Message
        //        // If this is not the first report from the source processor in this round
        //        // (or the previouse round because a report can come befor or after
        //        // the marker throw the message
        //        if (message[bm.pak.Round] < or[bp.ork.Round] - 1 ||
        //            ((AttributeList)or[p.ork.ReceivedMessageFrom]).Any((a => a.Value == (int)message[m.report.Id])))
        //        {
        //            break;
        //        }
        //        else
        //        {
        //            or[p.ork.ReceivedMessageFrom].Add(message[m.report.Id]);
        //        }

        //        // If the process is the initiator
        //        // Add the message to the results
        //        // Add the weight to the process weight
        //        // Check condition for end round (weight == 1)
        //        // Check condition for end running (round = max rounds)
        //        if (ea[bp.eak.Initiator])
        //        {
        //            or[p.ork.Results].Add(message[m.report.Snapshot]);
        //            or[p.ork.Weight] += message[m.report.ReportWeight];
        //            pp[bp.ppk.Text] = GetProcessDefaultName() + "\n" + or[p.ork.Weight];
        //            if (or[p.ork.Weight] == 1)
        //            {
        //                PrintResults();

        //                if (or[bp.ork.Round] < pa[p.pak.MaxRounds])
        //                {
        //                    TakeSnapshot();
        //                }
        //                else
        //                {
        //                    Terminate();
        //                }
        //            }
        //        }

        //        // If the process is not the initiator
        //        // Propagate the message to all the neighbors
        //        else
        //        {
        //            SendToNeighbours(message, SelectingMethod.Exclude, new List<int> { (int)message[m.report.Id] });
        //        }
        //        break;
        //}


        public override void ReceiveHandling(BaseMessage message)
        {
            ChandyLamport_NewStyleChannel channel = (ChandyLamport_NewStyleChannel)ChannelFrom(message);
            ChandyLamport_NewStyleMessage msg     = message as ChandyLamport_NewStyleMessage;

            switch (msg.MessageType)
            {
            case BaseMessage:

                // If the process performed snapshot but still did not get marker from all
                // it's neighbors :
                // Save the message - It will be sent as message in the channels
                if (Recorderd && !channel.Recorderd)
                {
                    channel.State.Add(msg.Name);
                }
                break;

            case Marker:

                // If the process received a marker:
                // Add the weight in the marker
                // Perform TakeSnapshot (If first Marker in round - Send Marker to all the neighbors)
                Weight += msg.MarkerWeight;
                TakeSnapshot();

                // Check if the round ended (Received Marker from all it's neighbors)
                // Perform EndSnapshot (Send Report, reset variables)
                channel.or[c.ork.Recorderd] = true;
                if (InChannels.All(cnl => ((ChandyLamport_NewStyleChannel)cnl).Recorderd))
                {
                    EndSnapshot();
                }

                // Change the text on the process because the weight changed
                Text = GetProcessDefaultName() + "\n" + Weight;
                break;

            case Report:

                // If received a Report Message
                // If this is not the first report from the source processor in this round
                // (or the previouse round because a report can come befor or after
                // the marker throw the message
                if (msg.Round < Round - 1 ||
                    (ReceivedMessageFrom.Any(a => a.Value == msg.Id)))
                {
                    break;
                }
                else
                {
                    ReceivedMessageFrom.Add(msg.Id);
                }

                // If the process is the initiator
                // Add the message to the results
                // Add the weight to the process weight
                // Check condition for end round (weight == 1)
                // Check condition for end running (round = max rounds)
                if (Initiator)
                {
                    Results.Add(msg.Snapshot);
                    Weight += msg.ReportWeight;
                    Text    = GetProcessDefaultName() + "\n" + Weight;
                    if (Weight == 1)
                    {
                        PrintResults();

                        if (Round < MaxRounds)
                        {
                            TakeSnapshot();
                        }
                        else
                        {
                            Terminate();
                        }
                    }
                }

                // If the process is not the initiator
                // Propagate the message to all the neighbors
                else
                {
                    SendToNeighbours(msg, SelectingMethod.Exclude, new List <int> {
                        msg.Id
                    });
                }
                break;
            }
        }
        public void Start()
        {
            float  percent = 0, cpercent = 0.0f;
            double scalex, scaley;
            int    c, crot = 0;
            //Shape temp;
            Matrix points;
            Matrix ctrans, m, m2, r;
            SPoint center;

            foreach (Shape s in b)
            {
                points = a.ShapePoints;
                ctrans = Matrix.Indentity(3);
                //temp = a;
                scalex    = a.ShapeBitmap.Width < s.ShapeBitmap.Width ? Math.Round(s.Center.X / a.Center.X) : 1 / Math.Round(a.Center.X / s.Center.X);
                scaley    = a.ShapeBitmap.Height < s.ShapeBitmap.Height ? Math.Round(s.Center.X / a.Center.X) : 1 / Math.Round(a.Center.X / s.Center.X);
                ctrans   *= Matrix.Scale(scalex, scaley);
                center    = a.Center;
                center.X *= (float)scalex;
                center.Y *= (float)scaley;
                points   *= ctrans;

                /*crot = 0;-----------------BROKEN ROTATION STUFF
                 * for (int i = 0; i < 8; i++)
                 * {
                 *  //points = a.ShapePoints;
                 *
                 *  m = Matrix.Translation(-center.X, -center.Y);
                 *  r = Matrix.Rotation(Math.PI/4);
                 *  m2 = Matrix.Translation(center.X, center.Y);
                 *  ctrans *= (m * r * m2);
                 *
                 *  temp.ShapePoints *= ctrans;
                 *
                 *  temp.ResetPoints();
                 *
                 *  //points *= ctrans;
                 *
                 *  c = Hit(s, temp.ShapePoints);
                 *  percent = ((float)c / (float)temp.ShapePoints.Count()) * 100.0f;
                 *
                 *  if (percent > cpercent)
                 *  {
                 *      cpercent = percent;
                 *      crot = i;
                 *      if (percent == 100.0f)
                 *      {
                 *          break;
                 *      }
                 *
                 *  }
                 * }
                 * crot *= 45;*/
                c       = Hit(s, points);
                percent = ((float)c / (float)a.ShapePoints.Count()) * 100.0f;
                Percent.Add(percent);
                Results.Add(s.Name);
                Scale.Add(scalex.ToString("0.0") + "," + scaley.ToString("0.0"));
                //Rotation.Add(crot.ToString());
            }
        }
Exemple #29
0
        public void Traverse(TSqlFragment node)
        {
            if (nestingLevel++ == 1)
            {
                Results.Add(new ParseResults());
            }
            ;
            Debug.Assert(nestingLevel < 10, "Maximum recursion level exceeded.");
            switch (node)
            {
            case InsertStatement insSt:
                Result.SetStatementType(StatementType.Insert);
                Traverse(insSt.InsertSpecification);
                break;

            case InsertSpecification ins:
                Result.SetTargetTableFromTableRef(ins.Target);
                if (ins.InsertSource is SelectInsertSource)
                {
                    Traverse(((SelectInsertSource)ins.InsertSource).Select);
                }
                break;

            case DeleteStatement delSt:
                Result.SetStatementType(StatementType.Delete);
                Traverse(delSt.DeleteSpecification);
                break;

            case UpdateStatement updSt:
                Result.SetStatementType(StatementType.Update);
                Traverse(updSt.UpdateSpecification);
                break;

            case UpdateSpecification us:
                Result.SetTargetTableFromTableRef(us.Target);
                if (us.FromClause != null)
                {
                    Traverse(((FromClause)us.FromClause).TableReferences[0]);
                }
                if (us.Target.IsNull() &&
                    Result.Alias.BinarySearch(Result.TargetTable) > 0
                    )
                {
                    Result.SetTargetTableFromAlias();
                    Result.SetFeature(Features.UpdateTargetPointsToAlias);
                }
                if (us.WhereClause != null)
                {
                    Result.SetFeature(Features.HasWhereClause);
                }
                break;

            case SelectStatement selSt:
                Result.SetStatementType(StatementType.Select);
                Result.SetTargetTableFromSchema(selSt.Into);
                Traverse(((QuerySpecification)(selSt.QueryExpression)));
                break;

            case CreateTableStatement createTableSt:
                Result.SetStatementType(StatementType.CreateTable);
                Result.SetFeature(Features.IsDDL);
                break;

            case AlterTableStatement alterTableSt:
                Result.SetStatementType(StatementType.AlterTable);
                Result.SetFeature(Features.IsDDL);
                break;

            case TruncateTableStatement truncateTableSt:
                Result.SetStatementType(StatementType.TruncateTable);
                Result.SetFeature(Features.IsDDL);
                break;

            case DeclareVariableStatement declareVariableSt:
                Result.SetStatementType(StatementType.DeclareVariable);
                break;

            case SetVariableStatement setVariableSt:
                Result.SetStatementType(StatementType.SetVariable);
                break;

            case QuerySpecification qs:
                if (qs.WhereClause != null)
                {
                    Result.SetFeature(Features.HasWhereClause);
                }
                Traverse(qs.FromClause.TableReferences[0]);
                break;

            case UnqualifiedJoin uj:
                Traverse(uj.FirstTableReference);
                Traverse(uj.SecondTableReference);
                break;

            case QualifiedJoin qj:
                Traverse(qj.FirstTableReference);
                Traverse(qj.SecondTableReference);
                break;

            case BinaryQueryExpression bqs:
                Traverse(bqs.FirstQueryExpression);
                Traverse(bqs.SecondQueryExpression);
                break;

            case NamedTableReference tr:
                Result.SourceTables.Add(tr.SchemaObject.FullyQualifiedName());
                Result.Alias.Add(string.Format("[{0}]", tr.Alias != null ? tr.Alias.Value : ""));
                break;

            default:
                Debug.Assert(false, "This node type is not implemented yet!!!");
                break;
            }
            --nestingLevel;
        }
Exemple #30
0
        private async void OnStopped(Results results)
        {
            string reason = results.TryFindString("reason");

            if (reason.StartsWith("exited") || reason.StartsWith("disconnected"))
            {
                if (this.ProcessState != ProcessState.Exited)
                {
                    this.ProcessState = ProcessState.Exited;
                    if (ProcessExitEvent != null)
                    {
                        ProcessExitEvent(this, new ResultEventArgs(results));
                    }
                }
                return;
            }

            //if this is an exception reported from LLDB, it will not currently contain a frame object in the MI
            //if we don't have a frame, check if this is an exception and retrieve the frame
            if (!results.Contains("frame") &&
                (string.Compare(reason, "exception-received", StringComparison.OrdinalIgnoreCase) == 0 ||
                string.Compare(reason, "signal-received", StringComparison.OrdinalIgnoreCase) == 0)
                )
            {
                //get the info for the current frame
                Results frameResult = await MICommandFactory.StackInfoFrame();

                //add the frame to the stopping results
                results = results.Add("frame", frameResult.Find("frame"));
            }

            bool fIsAsyncBreak = MICommandFactory.IsAsyncBreakSignal(results);
            if (await DoInternalBreakActions(fIsAsyncBreak))
            {
                return;
            }

            this.ProcessState = ProcessState.Stopped;
            FlushBreakStateData();

            if (!results.Contains("frame"))
            {
                if (ModuleLoadEvent != null)
                {
                    ModuleLoadEvent(this, new ResultEventArgs(results));
                }
            }
            else if (BreakModeEvent != null)
            {
                BreakRequest request = _requestingRealAsyncBreak;
                _requestingRealAsyncBreak = BreakRequest.None;
                BreakModeEvent(this, new StoppingEventArgs(results, request));
            }
        }
        public void CopyFile(Report report, FileSettings settings, Connection socketConnection)
        {
            var reportName = report?.Name ?? null;

            try
            {
                if (String.IsNullOrEmpty(reportName))
                {
                    throw new Exception("The report filename is empty.");
                }

                var target = settings?.Target?.Trim() ?? null;
                if (target == null)
                {
                    var message = $"No target file path for report '{reportName}' found.";
                    logger.Error(message);
                    JobResult.Exception = ReportException.GetException(message);
                    JobResult.Status    = TaskStatusInfo.ERROR;
                    Results.Add(new FileResult()
                    {
                        Success     = false,
                        ReportState = "ERROR",
                        TaskName    = JobResult.TaskName,
                        Message     = message,
                        ReportName  = reportName
                    });
                    return;
                }

                if (!target.ToLowerInvariant().StartsWith("lib://") && socketConnection != null)
                {
                    var message = $"Target value '{target}' is not a 'lib://' connection.";
                    logger.Error(message);
                    JobResult.Exception = ReportException.GetException(message);
                    JobResult.Status    = TaskStatusInfo.ERROR;
                    Results.Add(new FileResult()
                    {
                        Success     = false,
                        ReportState = "ERROR",
                        Message     = message,
                        TaskName    = JobResult.TaskName,
                        ReportName  = reportName
                    });
                    return;
                }

                var targetPath = String.Empty;
                if (PathCache.ContainsKey(target))
                {
                    targetPath = PathCache[target];
                }
                else
                {
                    targetPath = ResolveLibPath(target, socketConnection);
                    PathCache.Add(target, targetPath);
                }

                logger.Info($"Use the following resolved path '{targetPath}'...");

                var fileCount = 0;
                foreach (var reportPath in report.Paths)
                {
                    var targetFile = Path.Combine(targetPath, $"{NormalizeReportName(reportName)}{Path.GetExtension(reportPath)}");
                    if (report.Paths.Count > 1)
                    {
                        fileCount++;
                        targetFile = Path.Combine(targetPath, $"{NormalizeReportName(reportName)}_{fileCount}{Path.GetExtension(reportPath)}");
                    }

                    var fileData = report.Data.FirstOrDefault(f => f.Filename == Path.GetFileName(reportPath));
                    logger.Info($"Copy with distibute mode '{settings.Mode}'...");
                    switch (settings.Mode)
                    {
                    case DistributeMode.OVERRIDE:
                        Directory.CreateDirectory(targetPath);
                        File.WriteAllBytes(targetFile, fileData.DownloadData);
                        break;

                    case DistributeMode.DELETEALLFIRST:
                        if (File.Exists(targetFile))
                        {
                            File.Delete(targetFile);
                        }
                        Directory.CreateDirectory(targetPath);
                        File.WriteAllBytes(targetFile, fileData.DownloadData);
                        break;

                    case DistributeMode.CREATEONLY:
                        if (File.Exists(targetFile))
                        {
                            throw new Exception($"The file '{targetFile}' does not exist.");
                        }
                        File.WriteAllBytes(targetFile, fileData.DownloadData);
                        break;

                    default:
                        throw new Exception($"Unkown distribute mode {settings.Mode}");
                    }
                    logger.Info($"The file '{targetFile}' was copied...");
                    Results.Add(new FileResult()
                    {
                        Success     = true,
                        ReportState = GetFormatedState(),
                        TaskName    = JobResult.TaskName,
                        ReportName  = reportName,
                        Message     = "Report was successful created.",
                        CopyPath    = targetFile
                    });
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "The delivery process for 'files' failed.");
                JobResult.Exception = ReportException.GetException(ex);
                JobResult.Status    = TaskStatusInfo.ERROR;
                Results.Add(new FileResult()
                {
                    Success     = false,
                    ReportState = "ERROR",
                    TaskName    = JobResult.TaskName,
                    Message     = ex.Message,
                    ReportName  = reportName
                });
            }
            finally
            {
                PathCache.Clear();
                if (socketConnection != null)
                {
                    socketConnection.IsFree = true;
                }
            }
        }
Exemple #32
0
 /// <summary>
 /// Callback for task threads
 /// </summary>
 public void ReceiveResult(byte[] binData, object taskInfo)
 {
     Results.Add(new TaskResult(binData, (TaskInfo)taskInfo));
 }
Exemple #33
0
 /// <summary>
 /// Add a Error severity result to the Results list.
 /// </summary>
 /// <param name="description">Human-readable description of
 /// why the rule failed.</param>
 public void AddErrorResult(string description)
 {
     Results.Add(new RuleResult(Rule.RuleName, Rule.PrimaryProperty, description));
 }
Exemple #34
0
 protected override void Initialize(CancellationToken cancellationToken)
 {
     Results.Add(new Result(BestQualityResultName, new DoubleValue(double.NaN)));
     Results.Add(new Result(IterationsResultName, new IntValue(0)));
     base.Initialize(cancellationToken);
 }
Exemple #35
0
 static int Main(string[] args)
 {
   if (args.Length > 2) { System.Diagnostics.Debugger.Launch(); }
   if (args.Length < 1)
   {
     Console.WriteLine("Usage: parseStats logfile");
     return -1;
   }
   if (args[0].StartsWith(@"*\"))
   {
     var components = args[0].Split('\\');
     var results = new Results();
     // first dir is key
     Contract.Assume(components.Count() > 0, "Follows from the fact that Split return a non-empty array");
     foreach (var file in Directory.EnumerateFiles(".", components.Last(), SearchOption.AllDirectories)) {
       var fileComps = file.Split('\\');
       if (Matches(components, fileComps))
       {
         var lr = RunOneLog(file);
         var stats = Sum(lr);
         results.Add(fileComps[1], stats);
       }
     }
     PrintStats(results, args.Length > 1);
   }
   else
   {
     var lr = RunOneLog(args[0]);
     PrintStats(lr, args.Length > 1);
   }
   return 0;
 }
Exemple #36
0
 public override void AddResult(Document result)
 {
     Results.Add(result);
 }
Exemple #37
0
        protected override void Add(TypeDeclarationSyntax type, AttributeSyntax att)
        {
            var r = new ClassWithAttributeResult(type as ClassDeclarationSyntax, att);

            Results.Add(r);
        }
Exemple #38
0
 private static List<Result> GetProjectResults(Results all, string projectName)
 {
   Contract.Ensures(Contract.Result<List<Result>>() != null);
   List<Result> list;
   if (!all.TryGetValue(projectName, out list))
   {
     list = new List<Result>();
     all.Add(projectName, list);
   }
   else
   {
     Contract.Assume(list != null);
   }
   return list;
 }
Exemple #39
0
        private void DoSearch()
        {
            var criteria = new SearchCriteria();

            ((RangeFilterFieldViewModel)NumConditions).Parse(out criteria.NumConditions, out criteria.NumConditionsComparison);
            ((RangeFilterFieldViewModel)NumAltGroups).Parse(out criteria.NumAltGroups, out criteria.NumAltGroupsComparison);

            criteria.Flag       = (RequirementType)Flag.SelectedId;
            criteria.SourceType = (FieldType)SourceType.SelectedId;
            ((RangeFilterFieldViewModel)SourceValue).Parse(out criteria.SourceValue, out criteria.SourceValueComparison);
            criteria.Comparison = (RequirementOperator)Comparison.SelectedId;
            criteria.TargetType = (FieldType)TargetType.SelectedId;
            ((RangeFilterFieldViewModel)TargetValue).Parse(out criteria.TargetValue, out criteria.TargetValueComparison);
            ((RangeFilterFieldViewModel)HitCount).Parse(out criteria.HitCount, out criteria.HitCountComparison);

            var directory = _settings.DumpDirectory;

            var filesToRead = 0;

            if (IsCoreAchievementsScanned || IsNonCoreAchievementsScanned)
            {
                filesToRead += Snapshot.AchievementGameCount;
            }
            if (IsLeaderboardCancelScanned || IsLeaderboardStartScanned || IsLeaderboardSubmitScanned)
            {
                filesToRead += Snapshot.LeaderboardGameCount;
            }
            if (IsRichPresenceScanned)
            {
                filesToRead += Snapshot.RichPresenceCount;
            }

            Progress.Reset(filesToRead);
            Progress.IsEnabled = true;

            var results = new List <Result>();

            if (IsCoreAchievementsScanned || IsNonCoreAchievementsScanned)
            {
                Progress.Label = "Processing Achievements...";

                foreach (var gameId in Snapshot.GamesWithAchievements)
                {
                    Progress.Current++;
                    if (!Progress.IsEnabled)
                    {
                        break;
                    }

                    var file      = Path.Combine(directory, gameId + ".json");
                    var contents  = File.ReadAllText(file);
                    var json      = new Jamiras.IO.Serialization.JsonObject(contents);
                    var patchData = json.GetField("PatchData");

                    var achievements = patchData.ObjectValue.GetField("Achievements").ObjectArrayValue;
                    if (achievements == null)
                    {
                        continue;
                    }

                    var gameName = patchData.ObjectValue.GetField("Title").StringValue;

                    foreach (var achievement in achievements)
                    {
                        var flags = achievement.GetField("Flags").IntegerValue;
                        if (!IsCoreAchievementsScanned)
                        {
                            if (flags == 3)
                            {
                                continue;
                            }
                        }
                        else if (!IsNonCoreAchievementsScanned)
                        {
                            if (flags != 3)
                            {
                                continue;
                            }
                        }

                        var memAddr = achievement.GetField("MemAddr").StringValue;
                        if (Matches(memAddr, criteria))
                        {
                            results.Add(new Result
                            {
                                GameId        = gameId,
                                GameName      = gameName,
                                AchievementId = achievement.GetField("ID").IntegerValue.GetValueOrDefault(),
                                ItemName      = achievement.GetField("Title").StringValue,
                                Details       = memAddr,
                                IsUnofficial  = flags == 5
                            });
                        }
                    }
                }
            }

            if (IsLeaderboardStartScanned || IsLeaderboardSubmitScanned || IsLeaderboardCancelScanned)
            {
                Progress.Label = "Processing Leaderboards...";

                foreach (var gameId in Snapshot.GamesWithLeaderboards)
                {
                    Progress.Current++;
                    if (!Progress.IsEnabled)
                    {
                        break;
                    }

                    var file      = Path.Combine(directory, gameId + ".json");
                    var contents  = File.ReadAllText(file);
                    var json      = new Jamiras.IO.Serialization.JsonObject(contents);
                    var patchData = json.GetField("PatchData");

                    var leaderboards = patchData.ObjectValue.GetField("Leaderboards").ObjectArrayValue;
                    if (leaderboards == null)
                    {
                        continue;
                    }

                    var gameName = patchData.ObjectValue.GetField("Title").StringValue;

                    foreach (var leaderboard in leaderboards)
                    {
                        var details = String.Empty;

                        var token   = Token.Empty;
                        var memAddr = leaderboard.GetField("Mem").StringValue;
                        foreach (var part in Tokenizer.Split(memAddr, ':'))
                        {
                            if (part == "STA" && IsLeaderboardStartScanned)
                            {
                                token = part;
                                continue;
                            }
                            if (part == "CAN" && IsLeaderboardCancelScanned)
                            {
                                token = part;
                                continue;
                            }
                            if (part == "SUB" && IsLeaderboardSubmitScanned)
                            {
                                token = part;
                                continue;
                            }
                            if (token.IsEmpty)
                            {
                                continue;
                            }

                            if (Matches(part.ToString(), criteria))
                            {
                                if (details.Length > 0)
                                {
                                    details += ", ";
                                }
                                details += token.ToString();
                                details += ':';
                                details += part.ToString();
                            }

                            token = Token.Empty;
                        }

                        if (details.Length > 0)
                        {
                            results.Add(new Result
                            {
                                GameId        = gameId,
                                GameName      = gameName,
                                LeaderboardId = leaderboard.GetField("ID").IntegerValue.GetValueOrDefault(),
                                ItemName      = "Leaderboard: " + leaderboard.GetField("Title").StringValue,
                                Details       = details,
                            });
                        }
                    }
                }
            }

            if (IsRichPresenceScanned)
            {
                Progress.Label = "Processing Rich Presence...";

                foreach (var gameId in Snapshot.GamesWithRichPresence)
                {
                    Progress.Current++;
                    if (!Progress.IsEnabled)
                    {
                        break;
                    }

                    var file      = Path.Combine(directory, gameId + ".json");
                    var contents  = File.ReadAllText(file);
                    var json      = new Jamiras.IO.Serialization.JsonObject(contents);
                    var patchData = json.GetField("PatchData");

                    var richPresence = patchData.ObjectValue.GetField("RichPresencePatch").StringValue;
                    if (richPresence != null)
                    {
                        int index = richPresence.IndexOf("Display:");
                        if (index != -1)
                        {
                            var details = String.Empty;

                            foreach (var line in richPresence.Substring(index).Split('\n'))
                            {
                                if (line.Trim().Length == 0)
                                {
                                    break;
                                }

                                if (line.StartsWith("?"))
                                {
                                    index = line.IndexOf('?', 1);
                                    if (index != -1)
                                    {
                                        var memAddr = line.Substring(1, index - 1);
                                        if (Matches(memAddr, criteria))
                                        {
                                            if (details.Length > 0)
                                            {
                                                details += ", ";
                                            }
                                            details += '?';
                                            details += memAddr;
                                            details += '?';
                                        }
                                    }
                                }
                            }

                            if (details.Length > 0)
                            {
                                results.Add(new Result
                                {
                                    GameId   = gameId,
                                    GameName = patchData.ObjectValue.GetField("Title").StringValue,
                                    ItemName = "Rich Presence",
                                    Details  = details,
                                });
                            }
                        }
                    }
                }
            }

            if (Progress.IsEnabled)
            {
                results.Sort((l, r) =>
                {
                    var diff = String.Compare(l.GameName, r.GameName);
                    if (diff == 0)
                    {
                        diff = String.Compare(l.ItemName, r.ItemName);
                    }

                    return(diff);
                });

                _backgroundWorkerService.InvokeOnUiThread(() =>
                {
                    Results.Clear();
                    foreach (var result in results)
                    {
                        Results.Add(result);
                    }
                });

                Progress.IsEnabled = false;
                Progress.Label     = String.Empty;
            }
        }
        /// <summary>
        ///     Renders the rules.
        /// </summary>
        /// <returns> </returns>
        public IValidationContext RenderRules()
        {
            results = new Results();
            if (rules == null || rules.Count < 1)
            {
                return this;
            }
            else
            {
                //sort rules based on priority;
                rules.Sort();
            }

            foreach (RulePolicy rule in rules)
            {
                if (!exitRuleRendering)
                {
                    rule.OnRuleRendered += OnRuleRenderedHandler;
                    results.Add(rule.Execute());
                }
                else
                {
                    break;
                }
            }

            ProcessResults();
            return this;
        }
Exemple #41
0
        public override void Write(HttpRequestData result)
        {
            // don't log request detail data for non errors over a certain no of requests
            if (!result.IsError && RequestsProcessed > 30000)
            {
                // always clear response
                result.ResponseContent = null;

                // detail data only if we explicitly requested
                if (_stressTester.Options.CaptureMinimalResponseData)
                {
                    result.Headers         = null;
                    result.ResponseHeaders = null;
                    result.FullRequest     = null;
                    result.RequestContent  = null;
                }
            }

            bool writeOut     = false;
            var  savedResults = Results;
            int  savedCount   = 0;

            lock (InsertLock)
            {
                Results.Add(result);
                RequestsProcessed++;
                if (result.IsError)
                {
                    RequestsFailed++;
                }

                if (Results.Count >= MaxCollectionItems)
                {
                    FileCount++;
                    savedCount = FileCount;
                    writeOut   = true;

                    Results = null;
                    Results = new List <HttpRequestData>();
                }
            }

            if (writeOut)
            {
                //Console.WriteLine();
                ThreadPool.QueueUserWorkItem((parm) =>
                {
                    //Console.WriteLine("QUWI Thread: " + Thread.CurrentThread.ManagedThreadId);
                    FileWriteParms parms = (FileWriteParms)parm;

                    var file = Path.Combine(TempFolderName, BaseFilename + parms.FileCount + ".json");
                    JsonSerializationUtils.SerializeToFile(parms.Requests, file, false);

                    //SerializationUtils.SerializeObject(parms.Requests, file, true);

                    //if (ResultsList == null)
                    //    ResultsList = new List<List<HttpRequestData>>();

                    //ResultsList.Add(parms.Requests);
                    ////ResultsList.Add(null);
                    //ResultsList[ResultsList.Count-1] = parms.Requests;

                    //var r = parms.Requests;
                    //Console.WriteLine("Queued Item " + parms.FileCount  + " " + r.Count);

                    //IFormatter formatter = new BinaryFormatter();
                    //Stream stream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None);
                    //formatter.Serialize(stream, parms.Requests);
                    //stream.Close();
                }, new FileWriteParms {
                    FileCount = savedCount, Requests = savedResults
                });

                //Console.WriteLine("Queue Use Worker Item time: " + swatch.ElapsedTicks.ToString("N0") + " " + Thread.CurrentThread.ManagedThreadId);
            }
        }