// POST: api/Vote
        public HttpResponseMessage Post(string username, int vote)
        {
            IEnumerable <string> headerValues = Request.Headers.GetValues("Authorization");
            string accessToken = (string)headerValues.FirstOrDefault();
            string userId      = GraphProvider.getUserId(accessToken);

            if (userId == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            string user = UserDataProvider.getUsername(Int64.Parse(userId));

            if (user == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            if (!(vote == 1 || vote == 0 || vote == -1))
            {
                return(Request.CreateResponse(HttpStatusCode.MethodNotAllowed));
            }
            if (UserStatsProvider.castVote(username, user, vote))
            {
                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError));
            }
        }
Example #2
0
            public void UnlinkedPathQuery_Should_ReturnNoPaths()
            {
                var service = new PathFinderService(GraphProvider.GetGraph());
                var paths   = service.FindAllPaths("e", "h");

                paths.Count.ShouldBe(0);
            }
        public async Task GenerateHistogramAsync(DivisionWithCategory?divisionWithCategory, Tier?tier, string imageName, string locCode)
        {
            using (Context.Channel.EnterTypingState())
            {
                if (imageName != null && !ScoreRetrievalService.Metadata.SupportsInexpensiveDetailQueries)
                {
                    throw new InvalidOperationException("Per-image histograms are not supported on online score providers. Use the `datasource` command to select an offline score provider.");
                }

                CompleteScoreboardSummary scoreboard = await ScoreRetrievalService.GetScoreboardAsync(new ScoreboardFilterInfo(divisionWithCategory?.Division, tier)).ConfigureAwait(false);

                decimal[] data = await scoreboard.TeamList
                                 .Conditionally(locCode != null, tle => tle.Where(t => t.Location == locCode))
                                 .Conditionally(divisionWithCategory?.Category != null, tle => tle.Where(t => t.Category == divisionWithCategory.Value.Category))
                                 .TernaryAsync(imageName == null,
                                               x => x.Select(datum => (decimal)datum.TotalScore).ToAsyncEnumerable(),
                                               x => x.Select(t => ScoreRetrievalService.GetDetailsAsync(t.TeamId))
                                               .ToTaskResultEnumerable()
                                               .Select(t => t.Images.SingleOrDefault(i => i.ImageName == imageName))
                                               .Where(i => i != null)
                                               .Select(i => (decimal)i.Score))
                                 .ToArrayAsync().ConfigureAwait(false);

                Array.Sort(data);

                Models.User userSettings = await Preferences.Database.FindOneAsync <Models.User>(u => u.Id == Context.User.Id).ConfigureAwait(false);

                ColorPresets.HistogramColorPreset histogramColorScheme = (userSettings?.DiscordTheme ?? "dark") == "light" ? ColorPresets.DiscordLight : ColorPresets.DiscordDark;

                using (var memStr = new System.IO.MemoryStream())
                {
                    await GraphProvider.WriteHistogramPngAsync(data, "Score", "Frequency", datum => datum.ToString("0.0#"), histogramColorScheme, memStr).ConfigureAwait(false);

                    memStr.Position = 0;

                    var histogramEmbed = new EmbedBuilder()
                                         .WithTitle("CyberPatriot Score Analysis")
                                         .WithDescription(Utilities.JoinNonNullNonEmpty(" | ",
                                                                                        imageName.AppendPrependIfNonEmpty("`"),
                                                                                        divisionWithCategory?.Division.ToStringCamelCaseToSpace(),
                                                                                        tier,
                                                                                        divisionWithCategory?.Category?.ToCanonicalName(),
                                                                                        LocationResolutionService.GetFullNameOrNull(locCode))
                                                          .CoalesceBlank("All Teams"))
                                         .AddInlineField("Teams", data.Length)
                                         .AddInlineField("Mean", $"{data.Average():0.##}")
                                         .AddInlineField("Standard Deviation", $"{data.StandardDeviation():0.##}")
                                         .AddInlineField("First Quartile", $"{data.Take(data.Length / 2).ToArray().Median():0.##}")
                                         .AddInlineField("Median", $"{data.Median():0.##}")
                                         .AddInlineField("Third Quartile", $"{data.Skip(data.Length / 2).ToArray().Median():0.##}")
                                         .AddInlineField("Min Score", $"{data.Min()}")
                                         .AddInlineField("Max Score", $"{data.Max()}")
                                         .WithTimestamp(scoreboard.SnapshotTimestamp)
                                         .WithFooter(ScoreRetrievalService.Metadata.StaticSummaryLine)
                                         .WithImageUrl("attachment://histogram.png"); // Discord API requirement to use the uploaded histogram

                    await Context.Channel.SendFileAsync(memStr, "histogram.png", embed : histogramEmbed.Build()).ConfigureAwait(false);
                }
            }
        }
Example #4
0
            public void ComplexPath_Should_ReturnCorrectPaths()
            {
                var service = new PathFinderService(GraphProvider.GetGraph());
                var paths   = service.FindAllPaths("g", "e");

                paths.Count.ShouldBe(3);
            }
Example #5
0
            public void TwoNodeQuery_Should_ReturnCorrectPaths()
            {
                var service = new PathFinderService(GraphProvider.GetGraph());
                var paths   = service.FindAllPaths("a", "b");

                paths.Count.ShouldBe(1);
            }
Example #6
0
            public void MultiplePathQuery_Should_ReturnCorrectPaths()
            {
                var service = new PathFinderService(GraphProvider.GetGraph());
                var paths   = service.FindAllPaths("a", "c");

                paths.Count.ShouldBe(2);
            }
        // POST: api/User
        public HttpResponseMessage Post(string username)
        {
            IEnumerable <string> headerValues = Request.Headers.GetValues("Authorization");
            string accessToken = (string)headerValues.FirstOrDefault();
            string userId      = GraphProvider.getUserId(accessToken);

            if (userId == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            UserDataProvider.userOperationResult result = UserDataProvider.registerUser(Int64.Parse(userId), username);
            switch (result)
            {
            case UserDataProvider.userOperationResult.UserRegistrationSuccess:
                return(Request.CreateResponse(HttpStatusCode.Created));

            case UserDataProvider.userOperationResult.UsernameIsTaken:
                return(Request.CreateResponse(HttpStatusCode.Conflict));

            case UserDataProvider.userOperationResult.UserRegistrationFailed:
                return(Request.CreateResponse(HttpStatusCode.InternalServerError));

            case UserDataProvider.userOperationResult.UserAlreadyRegistered:
                return(Request.CreateResponse(HttpStatusCode.MethodNotAllowed));

            default:
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
        }
Example #8
0
        private static void HandleTrustExistanceSpecialCase(PackStatus packStatus, AdditionalChecks additionalChecks, AmountOfStockSubmited amountOfStockSubmited, NumberOfChecks numberOfChecks)
        {
            var chain1 = GraphProvider.GetQSimpleQSepAndHierSubQTableRuleChain(null, null,
                                                                               () => packStatus,
                                                                               () => true,
                                                                               () => amountOfStockSubmited,
                                                                               () => numberOfChecks,
                                                                               () => additionalChecks,
                                                                               () => false
                                                                               );

            Assert.That(RuleChainFulfilledResoveHelper.RuleChainIsFulfilled(chain1), Is.EqualTo(true));


            var chain2 = GraphProvider.GetQSimpleQSepAndHierSubQTableRuleChain(null, null,
                                                                               () => packStatus,
                                                                               () => false,
                                                                               () => amountOfStockSubmited,
                                                                               () => numberOfChecks,
                                                                               () => additionalChecks,
                                                                               () => false
                                                                               );

            Assert.That(RuleChainFulfilledResoveHelper.RuleChainIsFulfilled(chain2), Is.EqualTo(false));
        }
Example #9
0
 /// <summary>
 /// Returns an enumerator that iterates through the collection of results.
 /// </summary>
 /// <returns>
 /// An System.Collections.IEnumerator object that can be used to iterate through the collection.
 /// </returns>
 IEnumerator IEnumerable.GetEnumerator()
 {
     foreach (var graph in GraphProvider.Execute(GraphExpression))
     {
         yield return(TypifyGraph(graph, TypeGraph));
     }
 }
        public void Load_ThrowsIfXmlIsWrong_Test()
        {
            // Arrange
            var provider = new GraphProvider();

            // Assert
            Assert.Throws<SourceIsNotValidException>(() => provider.Load<Graph<Node>>(@"xml\wrong.xml"));
        }
        public void Load_ThrowsIfFileNotExists_Test()
        {
            // Arrange
            var provider = new GraphProvider();

            // Assert
            var ex = Assert.Throws<SourceIsNotExistsException>(() => provider.Load<Graph<Node>>(@"xml\not_exists.xml"));
            Assert.AreEqual(ex.Message, "Source is not exists on path: [xml\\not_exists.xml]");
        }
Example #12
0
        public override void Execute(MethodDef context)
        {
            var graphProvider = GraphProvider.Create(context);

            // TODO: automatically update theme?
            var font   = fontService.GetSettings("text").Active;
            var newTab = documentTabService.OpenEmptyTab();

            newTab.Show(new ControlFlowGraphTabContent(graphProvider, themeService.Theme, font), null, null);
        }
Example #13
0
 private static void FindWay(string path)
 {
     var graph = new GraphProvider().Load<DijkstraGraph>(path);
     graph.Validate();
     graph.Markup();
     var way = new Dijkstra.Dijkstra()
                           .Compute(graph)
                           .GetShortestWay(graph);
     PrintResults(way);
 }
        public void Load_Test()
        {
            // Arrange
            var provider = new GraphProvider();

            // Act
            var graph = provider.Load<Graph<Node>>(@"xml\simple-valid.xml");

            // Assert
            Assert.AreEqual(graph.Nodes.Count(), 5);
        }
        public void Validate_Failure_Test(string xml)
        {
            // Arrange
            var graph = new GraphProvider().Load<DijkstraGraph>(xml);
            graph.Validate();
            graph.Markup();
            var dijkstra = new ShortestWay.Dijkstra.Dijkstra();

            // Assert
            dijkstra.Compute(graph).GetShortestWay(graph);
        }
        public void InitBulletin()
        {
            Page1 = new Page(1);
            Page2 = new Page(2);
            Page3 = new Page(3);


            var questions = new List <Question>();

            QSimple1 = TestBulletinModel.GetFreshQSimple(Page1);
            QSimple2 = TestBulletinModel.GetFreshQSimple(Page1);
            QSimple3 = TestBulletinModel.GetFreshQSimple(Page1);
            questions.Add(QSimple1);
            questions.Add(QSimple2);
            questions.Add(QSimple3);


            QCumulative1 = TestBulletinModel.GetFreshQCumulative(Page2);
            QCumulative2 = TestBulletinModel.GetFreshQCumulative(Page2);
            questions.Add(QCumulative1);
            questions.Add(QCumulative2);

            QSeparate1 = TestBulletinModel.GetFreshQSeparate(Page3);
            QSeparate2 = TestBulletinModel.GetFreshQSeparate(Page3);
            questions.Add(QSeparate1);
            questions.Add(QSeparate2);

            const bool packetIsRegistered = true;

            Signature1 = new Signature(Fields.CheckBoxDocField(true, Page1), 1, 1, new List <Question> {
                QSimple1, QSimple2, QSimple3, QSeparate1
            });
            Signature2 = new Signature(Fields.CheckBoxDocField(true, Page2), 2, 2, new List <Question> {
                QSeparate2, QCumulative1
            });
            Signature3 = new Signature(Fields.CheckBoxDocField(true, Page3), 3, 3, new List <Question> {
                QCumulative2
            });

            var signatures = new List <Signature> {
                Signature1, Signature2, Signature3
            };

            Bulletin = TestBulletinModel.Create(questions, signatures, AllowedVotesAmount, PackStatus, TrustExists, packetIsRegistered);

            var graph = GraphProvider.BuildGraph(Bulletin);

            new GraphWalker().WalkThrough(graph, Bulletin);
        }
Example #17
0
        public GraphViewEditor(GraphViewWindow window)
        {
            _window         = window;
            _graphProvider  = ScriptableObject.CreateInstance <GraphProvider>();
            _objectProvider = ScriptableObject.CreateInstance <ObjectProvider>();

            this.AddStyleSheet(Stylesheet);
            AddToClassList(UssClassName);

            CreateToolbar();

            // this has to be here because Unity doesn't allow EditorPrefs access in a static constructor
            Graph.IsDebugBreakEnabled   = _breakpointsEnabled.Value;
            Graph.IsDebugLoggingEnabled = _loggingEnabled.Value;
        }
Example #18
0
        private IEnumerable <IGraph> GetGraphsFor(GraphItemInComboBox item, GraphProvider graphProvider)
        {
            foreach (var listOfSensors in (from movement in baseSetOfMovements.Movements select movement.Sensors))
            {
                foreach (var sensor in listOfSensors)
                {
                    if (sensor.SensorInfo == item.Sensor.SensorInfo)
                    {
                        yield return(graphProvider(sensor));

                        break;
                    }
                }
            }
        }
Example #19
0
        private void CreateNewGraph()
        {
            graph_area.Children.Clear();
            graph_provider = new GraphProvider();
            graph_area.AsyncAlgorithmCompute  = true;
            graph_area.RelayoutFinished      += OnRelayoutFinished;
            graph_area.UseNativeObjectArrange = true;
            graph_area.Graph = graph_provider.Graph;
            SetGraphLayoutParameters();
            graph_area.GenerateGraph(graph_provider.Graph);
            graph_area.RelayoutGraph(true);

            root_control = graph_area.VertexList.Values.First();
            graph_provider.root_vertex = (FileBrowser)graph_area.VertexList.Keys.First();
            centre_on_me = root_control;
        }
Example #20
0
        public void ClassQuery()
        {
            var graphSource   = new GraphSource("http://localhost:7200/repositories/Pets");
            var graphProvider = new GraphProvider <SparqlBgpEvaluator>(graphSource);

            var classGraph = (new LabelledTreeNode <object, Term>(new Variable())).AddChild(new Rdfs("subClassOf"), new Variable());
            var query      = new QueryableGraph(graphProvider, new GraphExpression(classGraph));

            int count = 0;

            foreach (var item in query)
            {
                count++;
            }
            Assert.Equal(291, count);
        }
        public HttpResponseMessage Get()
        {
            IEnumerable <string> headerValues = Request.Headers.GetValues("Authorization");
            string accessToken = (string)headerValues.FirstOrDefault();
            string userId      = GraphProvider.getUserId(accessToken);

            if (userId == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            string user = UserDataProvider.getUsername(Int64.Parse(userId));

            if (user == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            return(Request.CreateResponse(HttpStatusCode.OK, UserStatsProvider.getUserRating(user)));
        }
        // POST api/values
        public HttpResponseMessage Post(double lat, double lng)
        {
            IEnumerable <string> headerValues = Request.Headers.GetValues("Authorization");
            string accessToken = (string)headerValues.FirstOrDefault();
            string userId      = GraphProvider.getUserId(accessToken);

            if (userId == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            string username = UserDataProvider.getUsername(Int64.Parse(userId));

            if (username == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            Random rnd       = new Random();
            string body      = Request.Content.ReadAsStringAsync().Result;
            string converted = body.Replace('-', '+');

            converted = converted.Replace('_', '/');
            //double lat, double lng, string user,
            int id;

            try
            {
                byte[]       imgByteArr = Convert.FromBase64String(converted);
                MemoryStream ms         = new MemoryStream(imgByteArr);
                BlobProvider provider   = new BlobProvider();
                //1 to max int32
                id = rnd.Next(1, 2147483647);
                provider.save(ms, id);
            }
            catch (Exception e)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            ImageData d = new ImageData(id, DateTime.Now, lat, lng, username);

            ImageDataProvider.InsertImage(d);
            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Example #23
0
        private void button1_Click(object sender, EventArgs e)
        {
            var txt = System.IO.File.ReadAllText("\\WorkingCurrent\\gv\\Network.gv");

            using (GraphResult g = GraphProvider.Generate(txt, "dot", "bmp"))
            {
                if (g != null)
                {
                    using (var bitmap = new Bitmap(g.Image.Width, g.Image.Height))
                    {
                        using (var gx = Graphics.FromImage(bitmap))
                        {
                            gx.DrawImage(g.Image, 0, 0);
                        }
                        bitmap.Save("\\WorkingCurrent\\gv\\test.jpg");
                    }
                }
            }
        }
        public void SimpleSample_Test()
        {
            // Arrange
            var graph = new GraphProvider().Load<DijkstraGraph>(@"xml\simple-valid.xml");
            graph.Validate();
            graph.Markup();
            var dijkstra = new ShortestWay.Dijkstra.Dijkstra();

            // Act
            var way = dijkstra.Compute(graph)
                              .GetShortestWay(graph);

            // Assert
            Assert.AreEqual(way[0].Id, 1);
            Assert.AreEqual(way[1].Id, 3);
            Assert.AreEqual(way[2].Id, 5);

            Assert.AreEqual(way.Count, 3);
            Assert.AreEqual((way[2] as DijkstraNode).TotalWeigth, 20);
        }
        public void AcceptanceSample_Test()
        {
            // Arrange
            var graph = new GraphProvider().Load<DijkstraGraph>(@"xml\shortestway-sample.xml");
            graph.Validate();
            graph.Markup();
            var dijkstra = new ShortestWay.Dijkstra.Dijkstra();

            // Act
            var way = dijkstra.Compute(graph)
                              .GetShortestWay(graph);

            // Assert
            Assert.AreEqual(way[0].Id, 1);
            Assert.AreEqual(way[1].Id, 6);
            Assert.AreEqual(way[2].Id, 8);
            Assert.AreEqual(way[3].Id, 9);
            Assert.AreEqual(way[4].Id, 10);

            Assert.AreEqual(way.Count, 5);
            Assert.AreEqual((way[4] as DijkstraNode).TotalWeigth, 22);
        }
Example #26
0
        public void MatrixTest(Status status,
                               AdditionalChecks additionalChecks,
                               AmountOfStockSubmited amountOfStockSubmited,
                               NumberOfChecks numberOfChecks,
                               bool expected)
        {
            var packStatus = GetPackStatusFor(status);

            // Специальный случай для голосования по доверенности
            if (packStatus == PackStatus.Simple &&
                additionalChecks == AdditionalChecks.HasTrust &&
                amountOfStockSubmited == AmountOfStockSubmited.LessOrEqualThanThereIsOnPack &&
                numberOfChecks == NumberOfChecks.Single)
            {
                HandleTrustExistanceSpecialCase(packStatus, additionalChecks, amountOfStockSubmited, numberOfChecks);
                return;
            }
            var chain1 = GraphProvider.GetQSimpleQSepAndHierSubQTableRuleChain(null, null,
                                                                               () => packStatus,
                                                                               () => true,
                                                                               () => amountOfStockSubmited,
                                                                               () => numberOfChecks,
                                                                               () => additionalChecks,
                                                                               () => false);
            var chain2 = GraphProvider.GetQSimpleQSepAndHierSubQTableRuleChain(null, null,
                                                                               () => packStatus,
                                                                               () => false,
                                                                               () => amountOfStockSubmited,
                                                                               () => numberOfChecks,
                                                                               () => additionalChecks,
                                                                               () => false);



            Assert.That(RuleChainFulfilledResoveHelper.RuleChainIsFulfilled(chain1), Is.EqualTo(expected));
            Assert.That(RuleChainFulfilledResoveHelper.RuleChainIsFulfilled(chain2), Is.EqualTo(expected));
        }
Example #27
0
        public void LeftJoinTest()
        {
            var graphSource   = new GraphSource("http://localhost:7200/repositories/Pets");
            var graphProvider = new GraphProvider <SparqlBgpEvaluator>(graphSource);

            var propertyGraph = (new LabelledTreeNode <object, Term>(new Variable()))
                                .AddChild(new Rdf("type"), new Rdf("Property"));
            var propertyQuery = new QueryableGraph(graphProvider, new GraphExpression(propertyGraph));

            var classGraph = (new LabelledTreeNode <object, Term>(new Variable()))
                             .AddChild(new Rdfs("subClassOf"), new Variable());
            var classQuery = new QueryableGraph(graphProvider, new GraphExpression(classGraph));

            var query = propertyQuery.Expand(new Rdfs("range"), classQuery);

            int count = 0;

            foreach (var item in query)
            {
                count++;
                Debug.WriteLine(item);
            }
            Assert.Equal(79, count);
        }
        public void Test()
        {
            var graph = GraphProvider.BuildGraph(Bulletin);

            var rootRule = (PacketMustBeRegisteredRule)graph;

            Assert.That(rootRule.DependantRule != null);
            Assert.That(rootRule._packetIsRegistered.Value, Is.EqualTo(true));

            var signaturesParallelRule = (ParallelRule)rootRule.DependantRule;


            Assert.That(signaturesParallelRule.ParallelRules.Count, Is.EqualTo(3));
            Assert.That(signaturesParallelRule.ParallelRules.Select(x => ((SignatureMustBePresentRule)x).Signature)
                        .SequenceEqual(new List <Signature> {
                Signature1, Signature2, Signature3
            }));

            Assert.That(signaturesParallelRule.DependantRule == null);

            var ruleAfterSignatureRule1 = (ParallelRule)signaturesParallelRule.ParallelRules[0].DependantRule;
            var ruleAfterSignatureRule2 = (ParallelRule)signaturesParallelRule.ParallelRules[1].DependantRule;
            var ruleAfterSignatureRule3 = (ParallelRule)signaturesParallelRule.ParallelRules[2].DependantRule;

            Assert.That(ruleAfterSignatureRule1.ParallelRules.Count, Is.EqualTo(2));
            Assert.That(ruleAfterSignatureRule2.ParallelRules.Count, Is.EqualTo(2));
            Assert.That(ruleAfterSignatureRule3.ParallelRules.Count, Is.EqualTo(2));

            var rulesAfterEverySignatureRule = signaturesParallelRule.ParallelRules.Select(x => (ParallelRule)x.DependantRule).ToList();

            Assert.That(rulesAfterEverySignatureRule.All(r => r.ParallelRules.Count == 2));

            var ownersCountWarningRules = rulesAfterEverySignatureRule.Select(x => x.ParallelRules[0]).ToList();

            Assert.That(ownersCountWarningRules.Select(x => ((OwnersCountSignatureWarningRule)x).Signature)
                        .SequenceEqual(new List <Signature> {
                Signature1, Signature2, Signature3
            }));
            Assert.That(ownersCountWarningRules.All(x => x.DependantRule == null));


            var signature1QuestionRules = (ParallelRule)rulesAfterEverySignatureRule[0].ParallelRules[1];
            var signature2QuestionRules = (ParallelRule)rulesAfterEverySignatureRule[1].ParallelRules[1];
            var signature3QuestionRules = (ParallelRule)rulesAfterEverySignatureRule[2].ParallelRules[1];

            Assert.That(signature1QuestionRules.ParallelRules.Count, Is.EqualTo(4));
            Assert.That(signature2QuestionRules.ParallelRules.Count, Is.EqualTo(2));
            Assert.That(signature3QuestionRules.ParallelRules.Count, Is.EqualTo(1));


            //////////////QSIMPLE/////////////////

            var qSimple1TopRule = (PointShouldHaveAtLeastOneSelectionRule)signature1QuestionRules.ParallelRules[0];
            var qSimple2TopRule = (PointShouldHaveAtLeastOneSelectionRule)signature1QuestionRules.ParallelRules[1];
            var qSimple3TopRule = (PointShouldHaveAtLeastOneSelectionRule)signature1QuestionRules.ParallelRules[2];

            Assert.That(qSimple1TopRule.Point, Is.EqualTo(QSimple1.Point));
            Assert.That(qSimple2TopRule.Point, Is.EqualTo(QSimple2.Point));
            Assert.That(qSimple3TopRule.Point, Is.EqualTo(QSimple3.Point));



            var qsimple1BelowRule = (InCaseOfSimplePackPointWithNoAdditionalMarksAlwaysPassesRule)qSimple1TopRule.DependantRule;
            var qsimple2BelowRule = (InCaseOfSimplePackPointWithNoAdditionalMarksAlwaysPassesRule)qSimple2TopRule.DependantRule;
            var qsimple3BelowRule = (InCaseOfSimplePackPointWithNoAdditionalMarksAlwaysPassesRule)qSimple3TopRule.DependantRule;

            Assert.That(qsimple1BelowRule.Point, Is.EqualTo(QSimple1.Point));
            Assert.That(qsimple1BelowRule.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));

            Assert.That(qsimple2BelowRule.Point, Is.EqualTo(QSimple2.Point));
            Assert.That(qsimple2BelowRule.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));

            Assert.That(qsimple3BelowRule.Point, Is.EqualTo(QSimple3.Point));
            Assert.That(qsimple3BelowRule.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));



            var qsimple1BelowRule2 = (MultivariantVotingPointRule)qsimple1BelowRule.DependantRule;
            var qsimple2BelowRule2 = (MultivariantVotingPointRule)qsimple2BelowRule.DependantRule;
            var qsimple3BelowRule2 = (MultivariantVotingPointRule)qsimple3BelowRule.DependantRule;

            Assert.That(qsimple1BelowRule2.Point, Is.EqualTo(QSimple1.Point));
            Assert.That(qsimple1BelowRule2.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));

            Assert.That(qsimple2BelowRule2.Point, Is.EqualTo(QSimple2.Point));
            Assert.That(qsimple2BelowRule2.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));

            Assert.That(qsimple3BelowRule2.Point, Is.EqualTo(QSimple3.Point));
            Assert.That(qsimple3BelowRule2.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));



            var qsimple1BelowRule3 = (QSimpleQSepAndHierSubQTableRule)qsimple1BelowRule2.DependantRule;
            var qsimple2BelowRule3 = (QSimpleQSepAndHierSubQTableRule)qsimple2BelowRule2.DependantRule;
            var qsimple3BelowRule3 = (QSimpleQSepAndHierSubQTableRule)qsimple3BelowRule2.DependantRule;

            Assert.That(qsimple1BelowRule3.Point, Is.EqualTo(QSimple1.Point));
            Assert.That(qsimple1BelowRule3.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));

            Assert.That(qsimple2BelowRule3.Point, Is.EqualTo(QSimple2.Point));
            Assert.That(qsimple2BelowRule3.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));

            Assert.That(qsimple3BelowRule3.Point, Is.EqualTo(QSimple3.Point));
            Assert.That(qsimple3BelowRule3.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));


            var qsimple1BelowRule4 = (QSimpleQSepAndHierSubQFractionDistributionRule)qsimple1BelowRule3.DependantRule;
            var qsimple2BelowRule4 = (QSimpleQSepAndHierSubQFractionDistributionRule)qsimple2BelowRule3.DependantRule;
            var qsimple3BelowRule4 = (QSimpleQSepAndHierSubQFractionDistributionRule)qsimple3BelowRule3.DependantRule;

            Assert.That(qsimple1BelowRule4.Point, Is.EqualTo(QSimple1.Point));
            Assert.That(qsimple2BelowRule4.Point, Is.EqualTo(QSimple2.Point));
            Assert.That(qsimple3BelowRule4.Point, Is.EqualTo(QSimple3.Point));


            var qsimple1BelowRule5 = (AdrMustHaveExactVotesSpreadedForQSimple)qsimple1BelowRule4.DependantRule;
            var qsimple2BelowRule5 = (AdrMustHaveExactVotesSpreadedForQSimple)qsimple2BelowRule4.DependantRule;
            var qsimple3BelowRule5 = (AdrMustHaveExactVotesSpreadedForQSimple)qsimple3BelowRule4.DependantRule;

            Assert.That(qsimple1BelowRule5.Point, Is.EqualTo(QSimple1.Point));

            Assert.That(qsimple2BelowRule5.Point, Is.EqualTo(QSimple2.Point));

            Assert.That(qsimple3BelowRule5.Point, Is.EqualTo(QSimple3.Point));

            var qsimple1BelowRule6 = (QSimpleQSepAndHierSubQWarningRule)qsimple1BelowRule5.DependantRule;
            var qsimple2BelowRule6 = (QSimpleQSepAndHierSubQWarningRule)qsimple2BelowRule5.DependantRule;
            var qsimple3BelowRule6 = (QSimpleQSepAndHierSubQWarningRule)qsimple3BelowRule5.DependantRule;

            Assert.That(qsimple1BelowRule6.Point, Is.EqualTo(QSimple1.Point));
            Assert.That(qsimple1BelowRule6.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));

            Assert.That(qsimple2BelowRule6.Point, Is.EqualTo(QSimple2.Point));
            Assert.That(qsimple2BelowRule6.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));

            Assert.That(qsimple3BelowRule6.Point, Is.EqualTo(QSimple3.Point));
            Assert.That(qsimple3BelowRule6.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));


            var qsimple1BelowRule7 = (QSimplePrivilegeDividendsNoAbsWarningRule)qsimple1BelowRule6.DependantRule;
            var qsimple2BelowRule7 = (QSimplePrivilegeDividendsNoAbsWarningRule)qsimple2BelowRule6.DependantRule;
            var qsimple3BelowRule7 = (QSimplePrivilegeDividendsNoAbsWarningRule)qsimple3BelowRule6.DependantRule;

            Assert.That(qsimple1BelowRule7.Question, Is.EqualTo(QSimple1));
            Assert.That(qsimple1BelowRule7.DependantRule, Is.Null);

            Assert.That(qsimple2BelowRule7.Question, Is.EqualTo(QSimple2));
            Assert.That(qsimple2BelowRule7.DependantRule, Is.Null);

            Assert.That(qsimple3BelowRule7.Question, Is.EqualTo(QSimple3));
            Assert.That(qsimple3BelowRule7.DependantRule, Is.Null);
            //////////////QSEPARATE/////////////////

            var qSeparate1ParallelRule = (ParallelRule)signature1QuestionRules.ParallelRules[3];
            var qSeparate2ParallelRule = (ParallelRule)signature2QuestionRules.ParallelRules[0];

            Assert.That(qSeparate1ParallelRule.ParallelRules.Count, Is.EqualTo(10));
            Assert.That(qSeparate1ParallelRule.ParallelRules.All(r => r is PointShouldHaveAtLeastOneSelectionRule));
            Assert.That(qSeparate1ParallelRule.ParallelRules.Select(x => x.DependantRule).All(r => r is InCaseOfSimplePackPointWithNoAdditionalMarksAlwaysPassesRule));
            Assert.That(qSeparate1ParallelRule.ParallelRules.Select(x => x.DependantRule).All(r => r.DependantRule is MultivariantVotingPointRule));
            Assert.That(qSeparate1ParallelRule.ParallelRules.Select(x => x.DependantRule).All(r => r.DependantRule.DependantRule is QSimpleQSepAndHierSubQTableRule));
            Assert.That(qSeparate1ParallelRule.ParallelRules.Select(x => x.DependantRule).All(r => r.DependantRule.DependantRule.DependantRule is QSimpleQSepAndHierSubQFractionDistributionRule));
            Assert.That(qSeparate1ParallelRule.ParallelRules.Select(x => x.DependantRule).All(r => r.DependantRule.DependantRule.DependantRule.DependantRule is QSimpleQSepAndHierSubQWarningRule));
            Assert.That(qSeparate1ParallelRule.ParallelRules.Select(x => x.DependantRule).All(r => r.DependantRule.DependantRule.DependantRule.DependantRule.DependantRule == null));

            Assert.That(qSeparate2ParallelRule.ParallelRules.Count, Is.EqualTo(10));
            Assert.That(qSeparate2ParallelRule.ParallelRules.All(r => r is PointShouldHaveAtLeastOneSelectionRule));
            Assert.That(qSeparate2ParallelRule.ParallelRules.Select(x => x.DependantRule).All(r => r is InCaseOfSimplePackPointWithNoAdditionalMarksAlwaysPassesRule));
            Assert.That(qSeparate2ParallelRule.ParallelRules.Select(x => x.DependantRule).All(r => r.DependantRule is MultivariantVotingPointRule));
            Assert.That(qSeparate2ParallelRule.ParallelRules.Select(x => x.DependantRule).All(r => r.DependantRule.DependantRule is QSimpleQSepAndHierSubQTableRule));
            Assert.That(qSeparate2ParallelRule.ParallelRules.Select(x => x.DependantRule).All(r => r.DependantRule.DependantRule.DependantRule is QSimpleQSepAndHierSubQFractionDistributionRule));
            Assert.That(qSeparate2ParallelRule.ParallelRules.Select(x => x.DependantRule).All(r => r.DependantRule.DependantRule.DependantRule.DependantRule is QSimpleQSepAndHierSubQWarningRule));
            Assert.That(qSeparate2ParallelRule.ParallelRules.Select(x => x.DependantRule).All(r => r.DependantRule.DependantRule.DependantRule.DependantRule.DependantRule == null));


            var qSeparate1NumberOfPlacesRule = (QSeparateYesChecksShouldNotExceedPlacesCountRule)qSeparate1ParallelRule.DependantRule;
            var qSeparate2NumberOfPlacesRule = (QSeparateYesChecksShouldNotExceedPlacesCountRule)qSeparate2ParallelRule.DependantRule;

            Assert.That(qSeparate1NumberOfPlacesRule.Question, Is.EqualTo(QSeparate1));
            Assert.That(qSeparate2NumberOfPlacesRule.Question, Is.EqualTo(QSeparate2));
            Assert.That(qSeparate1NumberOfPlacesRule.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));
            Assert.That(qSeparate2NumberOfPlacesRule.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));



            var qSeparate1AdrRule = (AdrMustHaveExactOrLessVotesSpreadedForQSep)qSeparate1NumberOfPlacesRule.DependantRule;
            var qSeparate2AdrRule = (AdrMustHaveExactOrLessVotesSpreadedForQSep)qSeparate2NumberOfPlacesRule.DependantRule;

            Assert.That(qSeparate1AdrRule.QSeparate, Is.EqualTo(QSeparate1));
            Assert.That(qSeparate2AdrRule.QSeparate, Is.EqualTo(QSeparate2));

            Assert.That(qSeparate1AdrRule.DependantRule, Is.EqualTo(null));
            Assert.That(qSeparate2AdrRule.DependantRule, Is.EqualTo(null));


            //////////////QCUMULATIVE/////////////////

            var qCumulative1TopRule = (QCumulativeMustHaveAtLeastOneSelectionRule)signature2QuestionRules.ParallelRules[1];
            var qCumulative2TopRule = (QCumulativeMustHaveAtLeastOneSelectionRule)signature3QuestionRules.ParallelRules[0];

            Assert.That(qCumulative1TopRule.Question, Is.EqualTo(QCumulative1));

            Assert.That(qCumulative2TopRule.Question, Is.EqualTo(QCumulative2));

            ///

            var qCumulative1BelowRule = (InCaseOfSimplePackQCumulativeWithNoAdditionalMarksAlwaysPassesRule)qCumulative1TopRule.DependantRule;
            var qCumulative2BelowRule = (InCaseOfSimplePackQCumulativeWithNoAdditionalMarksAlwaysPassesRule)qCumulative2TopRule.DependantRule;

            Assert.That(qCumulative1BelowRule.Question, Is.EqualTo(QCumulative1));
            Assert.That(qCumulative1BelowRule.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));

            Assert.That(qCumulative2BelowRule.Question, Is.EqualTo(QCumulative2));
            Assert.That(qCumulative2BelowRule.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));

            ///

            var qCumulative1BelowRule2 = (MultivariantVotingQCumulativeRule)qCumulative1BelowRule.DependantRule;
            var qCumulative2BelowRule2 = (MultivariantVotingQCumulativeRule)qCumulative2BelowRule.DependantRule;

            Assert.That(qCumulative1BelowRule2.Question, Is.EqualTo(QCumulative1));
            Assert.That(qCumulative1BelowRule2.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));

            Assert.That(qCumulative2BelowRule2.Question, Is.EqualTo(QCumulative2));
            Assert.That(qCumulative2BelowRule2.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));

            ///

            var qCumulative1BelowRule3 = (QCumulativeTableRule)qCumulative1BelowRule2.DependantRule;
            var qCumulative2BelowRule3 = (QCumulativeTableRule)qCumulative2BelowRule2.DependantRule;

            Assert.That(qCumulative1BelowRule3.Question, Is.EqualTo(QCumulative1));
            Assert.That(qCumulative1BelowRule3.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));


            Assert.That(qCumulative2BelowRule3.Question, Is.EqualTo(QCumulative2));
            Assert.That(qCumulative2BelowRule3.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));

            ///

            var qCumulative1BelowRule4 = (QCumulativeFractionDistributionRule)qCumulative1BelowRule3.DependantRule;
            var qCumulative2BelowRule4 = (QCumulativeFractionDistributionRule)qCumulative2BelowRule3.DependantRule;

            Assert.That(qCumulative1BelowRule4.Question, Is.EqualTo(QCumulative1));
            Assert.That(qCumulative2BelowRule4.Question, Is.EqualTo(QCumulative2));

            ///

            var qCumulative1BelowRule5 = (AdrMustHaveExactVotesSpreadedWithMinimalSpredForQCum)qCumulative1BelowRule4.DependantRule;
            var qCumulative2BelowRule5 = (AdrMustHaveExactVotesSpreadedWithMinimalSpredForQCum)qCumulative2BelowRule4.DependantRule;

            Assert.That(qCumulative1BelowRule5.QCumulative, Is.EqualTo(QCumulative1));
            Assert.That(qCumulative2BelowRule5.QCumulative, Is.EqualTo(QCumulative2));

            ///

            var qCumulative1BelowRule6 = (QCumulativeWarningRule)qCumulative1BelowRule5.DependantRule;
            var qCumulative2BelowRule6 = (QCumulativeWarningRule)qCumulative2BelowRule5.DependantRule;

            Assert.That(qCumulative1BelowRule6.Question, Is.EqualTo(QCumulative1));
            Assert.That(qCumulative1BelowRule6.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));
            Assert.That(qCumulative1BelowRule6.DependantRule, Is.Null);


            Assert.That(qCumulative2BelowRule6.Question, Is.EqualTo(QCumulative2));
            Assert.That(qCumulative2BelowRule6.AdditionalMarks, Is.EqualTo(Bulletin.AdditionalMarks));
            Assert.That(qCumulative2BelowRule6.DependantRule, Is.Null);
        }
Example #29
0
        // [Command(HistogramCommandName), Alias("scoregraph", "scorestats", "statistics"), Summary("Generates a histogram of the given tier's scores for the given image within the given state on the current CyberPatriot leaderboard.")]
        // [Priority(-1)]
        // public Task HistogramCommandAsync([OverrideTypeReader(typeof(LocationTypeReader))] string location, Division div, Tier tier, string imageName) => GenerateHistogramAsync(new ScoreboardFilterInfo(div, tier), imageName, location);


        public async Task GenerateHistogramAsync(ScoreboardFilterInfo filter, string imageName, string locCode)
        {
            using (Context.Channel.EnterTypingState())
            {
                var descBuilder = new System.Text.StringBuilder();
                if (filter.Division.HasValue)
                {
                    descBuilder.Append(' ').Append(filter.Division.Value.ToStringCamelCaseToSpace());
                }
                if (filter.Tier.HasValue)
                {
                    descBuilder.Append(' ').Append(filter.Tier.Value);
                }
                if (imageName != null)
                {
                    throw new NotSupportedException("Per-image histograms are not yet supported.");

                    // unreachable code - not implemented on the data-aggregation/filter side, but this code Should Work:tm: for constructing the title
#pragma warning disable 0162
                    if (descBuilder.Length > 0)
                    {
                        descBuilder.Append(": ");
                    }
                    descBuilder.Append(imageName);
#pragma warning restore 0162
                }

                CompleteScoreboardSummary scoreboard = await ScoreRetrievalService.GetScoreboardAsync(filter).ConfigureAwait(false);

                decimal[] data = scoreboard.TeamList
                                 .Conditionally(locCode != null, tle => tle.Where(t => t.Location == locCode))
                                 // nasty hack
                                 .Select(datum => decimal.TryParse(ScoreRetrievalService.Metadata.FormattingOptions.FormatScore(datum.TotalScore), out decimal d) ? d : datum.TotalScore)
                                 .OrderBy(d => d).ToArray();
                using (var memStr = new System.IO.MemoryStream())
                {
                    await GraphProvider.WriteHistogramPngAsync(data, "Score", "Frequency", datum => datum.ToString("0.0#"), BitmapProvider.Color.Parse("#32363B"), BitmapProvider.Color.Parse("#7289DA"), BitmapProvider.Color.White, BitmapProvider.Color.Gray, memStr).ConfigureAwait(false);

                    memStr.Position = 0;

                    // This shouldn't be necessary, Discord's API supports embedding attached images
                    // BUT discord.net does not, see #796
                    var httpClient       = new System.Net.Http.HttpClient();
                    var imagePostMessage = new System.Net.Http.StreamContent(memStr);
                    imagePostMessage.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
                    Task <System.Net.Http.HttpResponseMessage> uploadUrlResponseTask = httpClient.PutAsync("https://transfer.sh/histogram.png", imagePostMessage);

                    var histogramEmbed = new EmbedBuilder()
                                         .WithTitle("CyberPatriot Score Analysis")
                                         .WithDescription(Utilities.JoinNonNullNonEmpty(" | ", filter.Division?.ToStringCamelCaseToSpace(), filter.Tier, locCode).CoalesceBlank("All Teams"))
                                         .AddInlineField("Teams", data.Length)
                                         .AddInlineField("Mean", $"{data.Average():0.##}")
                                         .AddInlineField("Standard Deviation", $"{data.StandardDeviation():0.##}")
                                         .AddInlineField("First Quartile", $"{data.Take(data.Length / 2).ToArray().Median():0.##}")
                                         .AddInlineField("Median", $"{data.Median():0.##}")
                                         .AddInlineField("Third Quartile", $"{data.Skip(data.Length / 2).ToArray().Median():0.##}")
                                         .AddInlineField("Min Score", $"{data.Min()}")
                                         .AddInlineField("Max Score", $"{data.Max()}")
                                         .WithImageUrl(await(await uploadUrlResponseTask.ConfigureAwait(false)).Content.ReadAsStringAsync().ConfigureAwait(false))
                                         .WithTimestamp(scoreboard.SnapshotTimestamp)
                                         .WithFooter(ScoreRetrievalService.Metadata.StaticSummaryLine);

                    await Context.Channel.SendMessageAsync("", embed : histogramEmbed).ConfigureAwait(false);
                }
            }
        }
Example #30
0
 /// <summary>
 /// Constructor
 /// </summary>
 public GraphContext()
 {
     GraphProvider = new GraphProvider <SparqlBgpEvaluator>(Configuration.Instance.QueryEndpoint);
     GraphWriter   = new GraphWriter(Configuration.Instance.UpdateEndpoint);
 }
Example #31
0
 public Validator(BulletinScreenModelBase bulletin)
 {
     Bulletin       = bulletin;
     _graphRootNode = GraphProvider.BuildGraph(bulletin);
 }
Example #32
0
 public static string FromEnum(GraphProvider provider)
 {
     return(provider.ToString());
 }
Example #33
0
        public IGraphColoringResponse ColorGraph(IGraphColoringRequest graphColoringRequest)
        {
            try
            {
                Graph graph = graphColoringRequest.Graph;
                GraphProvider.SetGraph(graph);

                Console.WriteLine(graph.PrintGraphInOriginalForm());

                CPChromosome                 chromosome  = new CPChromosome(graphColoringRequest.StartValues.Length, graphColoringRequest.StartValues, graphColoringRequest.Population);
                Population                   population  = new Population(graphColoringRequest.PopulationSize, graphColoringRequest.PopulationSize, chromosome);
                CPFitness                    fitness     = new CPFitness();
                EliteSelection               selection   = new EliteSelection();
                OnePointCrossover            crossover   = new OnePointCrossover();
                CPMutation                   mutation    = new CPMutation();
                FitnessStagnationTermination termination = new FitnessStagnationTermination(50);
                GeneticAlgorithm             ga          = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
                {
                    Termination = termination, MutationProbability = 0.1f
                };
                int          latestFitness  = int.MinValue;
                int          bestFitness    = 0;
                CPChromosome bestChromosome = null;
                ga.GenerationRan += (sender, e) =>
                {
                    bestChromosome = ga.BestChromosome as CPChromosome;
                    bestFitness    = (int)-bestChromosome.Fitness.Value;

                    if (bestFitness == latestFitness)
                    {
                        return;
                    }
                    latestFitness = bestFitness;
                    bestChromosome.GetValues();
                    Console.WriteLine("Current Generation Result : {0}", bestFitness);
                };
                ga.TerminationReached += (sender, e) => { Console.WriteLine("This is the end of generations"); };
                ga.Start();

                Console.WriteLine("End");

                if (bestFitness > graph.Vertexes.Count)
                {
                    return(new GraphColoringResponse());
                }

                int[] resultGenType = bestChromosome.GetValues();

                IDictionary <int, int> coloredVertex = new Dictionary <int, int>(graph.Vertexes.Count);

                foreach (int vertex in graph.Vertexes)
                {
                    coloredVertex.Add(vertex, resultGenType[vertex - 1]);
                }
                GraphWithColoredVertexes coloredGraph = new GraphWithColoredVertexes(graph, coloredVertex);

                return(new GraphColoringResponse(coloredGraph));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(new GraphColoringResponse());
            }
        }
 public OnePointCrossoverStrategyTests()
 {
     Strategy = new OnePointCrossoverStrategy(GraphProvider.ProvideValid());
 }
Example #35
0
        private void CreateNewGraph()
        {
            graph_area.Children.Clear();
            graph_provider = new GraphProvider();
            graph_area.AsyncAlgorithmCompute = true;
            graph_area.RelayoutFinished += OnRelayoutFinished;
            graph_area.UseNativeObjectArrange = true;
            graph_area.Graph = graph_provider.Graph;
            SetGraphLayoutParameters();
            graph_area.GenerateGraph(graph_provider.Graph);
            graph_area.RelayoutGraph(true);

            root_control = graph_area.VertexList.Values.First();
            graph_provider.root_vertex = (FileBrowser)graph_area.VertexList.Keys.First();
            centre_on_me = root_control;
        }