Exemplo n.º 1
0
        public override CoolQRouteMessage OnMessageReceived(CoolQScopeEventArgs scope)
        {
            var                  routeMsg    = scope.RouteMessage;
            BllUserRole          bllUserRole = new BllUserRole();
            List <TableUserRole> userInfo    = bllUserRole.GetUserRoleByQq(long.Parse(routeMsg.UserId));

            if (userInfo.Count == 0)
            {
                return(routeMsg.ToSource(DefaultReply.IdNotBound, true));
            }

            var id = userInfo[0].UserId;

            var client      = new OldSiteApiClient();
            var beatmapSets = client.GetBeatmapSetsByCreator(new UserId(id))
                              .Where(k => k.Beatmaps.FirstOrDefault()?.LastUpdate.AddDays(28) < DateTimeOffset.Now)
                              .ToArray();

            if (beatmapSets.Length == 0)
            {
                return(routeMsg.ToSource("你没有Graveyard Beatmaps!", true));
            }

            var beatmapSet = beatmapSets[StaticRandom.Next(beatmapSets.Length)];
            var cqMusic    = new CustomMusic(
                $"https://osu.ppy.sh/s/{beatmapSet.Id}",
                $"https://b.ppy.sh/preview/{beatmapSet.Id}.mp3",
                beatmapSet.Title,
                $"{beatmapSet.Artist}\r\n({beatmapSet.FavouriteCount} fav)",
                $"https://b.ppy.sh/thumb/{beatmapSet.Id}l.jpg");

            return(routeMsg
                   .ToSource(cqMusic.ToString())
                   .ForceToSend());
        }
Exemplo n.º 2
0
        // OnConnectedAsync and regular hub method calls should have the same connection selection for the same client connection
        // This test verifies this by sending messages from both and verifying the message order.
        public async Task OutgoingMessagesMultipleContexts()
        {
            var builder = WebHost.CreateDefaultBuilder()
                          .ConfigureServices((IServiceCollection services) => { })
                          .ConfigureLogging(logging => logging.AddXunit(_output))
                          .UseStartup <IntegrationTestStartup <MockServiceMessageOrderTestParams, MultipleContextsHub> >();

            using var server = new AspNetTestServer(builder);
            var mockSvc = (server.Host.Services.GetRequiredService <ServiceHubDispatcher <MultipleContextsHub> >() as MockServiceHubDispatcher <MultipleContextsHub>).MockService;
            await mockSvc.AllConnectionsEstablished();

            List <MockServiceSideConnection> allSvcConns = mockSvc.ServiceSideConnections;

            mockSvc.CurrentInvocationBinder = new TestHubBroadcastNCallsInvocationBinder();
            var priList = allSvcConns.Where(i => i.Endpoint.EndpointType == EndpointType.Primary).ToList();

            await using var primarySvc0 = priList[StaticRandom.Next(priList.Count)];
            var client0 = await primarySvc0.ConnectClientAsync();

            int       epCount = allSvcConns.Distinct(new MockServiceSideConnectionEndpointComparer()).Count();
            const int MsgNum  = 10;
            await client0.SendMessage("BroadcastNumCallsMultipleContexts", new object[] { MsgNum });

            var counts = await DrainBroadcastMessages(epCount, MsgNum, mockSvc);

            Assert.Equal(counts.Count(), MockServiceMessageOrderTestParams.ServiceEndpoints.Count());
            foreach (var conn in counts)
            {
                Assert.Equal(MsgNum, conn.Value);
            }
        }
 static void Main(string[] args)
 {
     for (int i = 0; i < 100; i++)
     {
         Console.WriteLine(StaticRandom.Next());
     }
 }
Exemplo n.º 4
0
        //TODO: Take in previous hue's and have a slight chance of 120 or 90 degree offset instead of always 0 and 180
        private static double GetRandomHue(double hue)
        {
            // Randomly choose a new hue that is similar to the one passed in
            double retVal = hue + StaticRandom.NextPow(3d, 18d, true);

            if (retVal < 0d)
            {
                retVal += 360d;
            }
            else if (retVal > 360d)
            {
                retVal -= 360d;
            }

            // Maybe rotate 180 degrees
            if (StaticRandom.Next(2) == 0)
            {
                retVal += 180d;

                if (retVal < 0d)
                {
                    retVal += 360d;
                }
                else if (retVal > 360d)
                {
                    retVal -= 360d;
                }
            }

            return(retVal);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Randomly select from the available endpoints
        /// </summary>
        /// <param name="owinContext">The incoming owin http context</param>
        /// <param name="endpoints"></param>
        /// <returns></returns>
        public ServiceEndpoint GetNegotiateEndpoint(IOwinContext owinContext, IEnumerable <ServiceEndpoint> endpoints)
        {
            // get primary endpoints snapshot
            var availableEndpoints = GetNegotiateEndpoints(endpoints);

            return(availableEndpoints[StaticRandom.Next(availableEndpoints.Length)]);
        }
Exemplo n.º 6
0
        private void AddEgg_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_bots.Count == 0)
                {
                    MessageBox.Show("Add a bot first", this.Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                Swimbot bot = _bots[StaticRandom.Next(_bots.Count)];

                Point3D position = bot.PositionWorld + Math3D.GetRandomVector_Spherical_Shell(bot.Radius * 1.5d);

                // The radius should be 20% the size of the adult ship
                ShipDNA dna    = bot.GetNewDNA();
                double  radius = dna.PartsByLayer.SelectMany(o => o.Value).
                                 Max(o => o.Position.ToVector().Length + Math1D.Max(o.Scale.X, o.Scale.Y, o.Scale.Z))
                                 * .2d;

                Egg <ShipDNA> egg = new Egg <ShipDNA>(position, radius, _world, _material_Egg, _itemOptions, dna);

                egg.PhysicsBody.AngularVelocity = bot.PhysicsBody.AngularVelocity;
                egg.PhysicsBody.Velocity        = bot.PhysicsBody.Velocity;

                egg.PhysicsBody.ApplyForceAndTorque += new EventHandler <BodyApplyForceAndTorqueArgs>(Egg_ApplyForceAndTorque);

                _map.AddItem(egg);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 7
0
        public override CoolQRouteMessage OnMessageReceived(CoolQScopeEventArgs scope)
        {
            var routeMsg = scope.RouteMessage;

            if (routeMsg.MessageType == MessageType.Private)
            {
                return(null);
            }
            string groupId = routeMsg.GroupId ?? routeMsg.DiscussId;

            if (!GroupDic.ContainsKey(groupId))
            {
                GroupDic.GetOrAdd(groupId, new GroupSettings
                {
                    GroupId = groupId,
                });

                GroupDic[groupId].Task = Task.Run(DecreaseQueue);
                //GroupDic[groupId].Thread.Start();
            }

            if (GroupDic[groupId].IntQueue >= MaxNum && !GroupDic[groupId].Locked)
            {
                GroupDic[groupId].Locked = true;
                Logger.Debug(groupId + " locked");
                Logger.Success(groupId + "的" + routeMsg.UserId + "触发了复读");
                Thread.Sleep(StaticRandom.Next(1000, 8000));
                return(routeMsg.ToSource(routeMsg.RawMessage));
            }

            GroupDic[groupId].IntQueue++;
            //Logger.Debug(groupId + " incresed to " + GroupDic[groupId].IntQueue);
            return(null);

            Task DecreaseQueue()
            {
                while (true)
                {
                    Thread.Sleep(StaticRandom.Next(1000, 10000));
                    if (GroupDic[groupId].IntQueue <= 0)
                    {
                        if (GroupDic[groupId].Locked)
                        {
                            GroupDic[groupId].Locked = false;
                            Logger.Debug(groupId + " unlocked");
                        }

                        continue;
                    }

                    if (StaticRandom.NextDouble() < 0.02)
                    {
                        Thread.Sleep(StaticRandom.Next(30000, 45000));
                    }

                    GroupDic[groupId].IntQueue--;
                    //Logger.Debug(groupId + " decresed to " + GroupDic[groupId].IntQueue);
                }
            }
        }
Exemplo n.º 8
0
        protected void ProcessFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return;
            }
            var charCounter = new Dictionary <char, int>();

            using (var sr = new StreamReader(filePath))
            {
                do
                {
                    var character = (char)sr.Read();
                    if (!charCounter.TryGetValue(character, out int currentValue))
                    {
                        currentValue = 0;
                    }
                    charCounter[character] = currentValue + 1;
                } while (!sr.EndOfStream);
                var fileName       = Path.GetFileNameWithoutExtension(filePath);
                var outputFilePath = Path.Combine(_outputDirectory, $"{fileName}.json");
                File.WriteAllText(outputFilePath, JsonSerializer.Serialize(
                                      charCounter.OrderBy(x => x.Key)
                                      .ToDictionary(k => k.Key.ToString(), v => v.Value)));
                Thread.Sleep(StaticRandom.Next(0, _maxSleep));
            }
        }
Exemplo n.º 9
0
            public Trunk(double _x, double _y, double _thickness, double _height)
            {
                int    n     = StaticRandom.Next(1, 2);
                double new_x = _x;
                double new_y = _y;

                listTrunk1 = new List <Shape>();
                for (int i = 0; i < n; i++)
                {
                    Polygon pol = new Polygon();
                    pol.Stroke   = Brushes.Black;
                    pol.Fill     = Brushes.Black;
                    pol.FillRule = FillRule.Nonzero;
                    pol.Points.Add(new Point(new_x, new_y));
                    pol.Points.Add(new Point(new_x + (1 - thick_coef) * _thickness / 2, new_y - _height));
                    pol.Points.Add(new Point(new_x + (1 + thick_coef) * _thickness / 2, new_y - _height));
                    pol.Points.Add(new Point(new_x + _thickness, new_y));
                    listTrunk1.Add(pol);
                    _height    = _height * height_coef;
                    new_x     += (1 - thick_coef) * _thickness / 2;
                    _thickness = _thickness * thick_coef;
                    new_y     -= _height;
                }
                startOfTrees1 = new TreeViaPath();
                startOfTrees1.MakeATree(new_x, new_y, _thickness, _height, 0, 0, true);
            }
Exemplo n.º 10
0
        /// <summary>
        /// Get random city scenario for civilization
        /// </summary>
        /// <param name="civId">The civilization Id.</param>
        /// <returns>Path to city scenario</returns>
        public static string GetRandomCityScenario(Civilizations civId)
        {
            switch (civId)
            {
            case Civilizations.Greek:

                return($"Capitals/CAPITAL_C01_0{StaticRandom.Next(1, 6)}");

            case Civilizations.Egypt:

                return($"Capitals/CAPITAL_C02_0{StaticRandom.Next(1, 6)}");


            case Civilizations.Celt:

                return($"Capitals/CAPITAL_C03_0{StaticRandom.Next(1, 6)}");

            case Civilizations.Persia:

                return($"Capitals/CAPITAL_C04_0{StaticRandom.Next(1, 3)}");

            case Civilizations.Babylonian:

                return($"Capitals/CAPITAL_C06_0{StaticRandom.Next(1, 3)}");


            case Civilizations.Norse:

                return($"Capitals/CAPITAL_C07_0{StaticRandom.Next(1, 3)}");

            default:

                throw new ArgumentOutOfRangeException($"CharacterHelper::getRandomCityScenario - Unknown CivId. CivId: {civId}");
            }
        }
Exemplo n.º 11
0
        public static void TestShamir(int n, BigInteger prime, int seed)
        {
            var PolyDegree = (int)Math.Ceiling(n / 3.0);
            var i1         = new BigZp(prime, StaticRandom.Next(1000000000));
            var i2         = new BigZp(prime, StaticRandom.Next(1000000000));
            var i3         = new BigZp(prime, StaticRandom.Next(1000000000));
            var i4         = new BigZp(prime, StaticRandom.Next(1000000000));
            var a          = i1 + i2 + i3 + i4;

            var shares1 = BigShamirSharing.Share(i1, n, PolyDegree - 1);
            var shares2 = BigShamirSharing.Share(i2, n, PolyDegree - 1);
            var shares3 = BigShamirSharing.Share(i3, n, PolyDegree - 1);
            var shares4 = BigShamirSharing.Share(i4, n, PolyDegree - 1);

            var rs = new List <BigZp>(n);

            for (int i = 0; i < n; i++)
            {
                rs.Add(new BigZp(prime));
                rs[i] += shares1[i];
                rs[i] += shares2[i];
                rs[i] += shares3[i];
                rs[i] += shares4[i];
            }

            var t = BigShamirSharing.Recombine(rs, PolyDegree - 1, prime);
        }
Exemplo n.º 12
0
    // Start is called before the first frame update
    void Start()
    {
        base.Start();
        trialsLeft = TOTAL_TRIALS;

        //Find child components
        leftLight        = transform.Find("LeftLight").gameObject;
        rightLight       = transform.Find("RightLight").gameObject;
        leftLightSource  = transform.Find("LeftLightSource").gameObject;
        rightLightSource = transform.Find("RightLightSource").gameObject;
        operationPrompt  = transform.Find("Prompt").gameObject;
        toggleLight      = transform.Find("OutputLight").gameObject;
        submitButton     = transform.Find("Submit").gameObject;
        moduleBase       = transform.Find("Base").gameObject;
        rounds           = new GameObject[TOTAL_TRIALS];
        for (int i = 0; i < TOTAL_TRIALS; ++i)
        {
            rounds[i] = transform.Find("RoundCounter").Find("Round" + (i + 1)).gameObject;
        }

        //Randomize the toggle light
        toggleState = StaticRandom.Next() < 0.5;
        SetObjectColor(toggleLight, "_EmissionColor", toggleState ? trueColor : falseColor);
        SetObjectColor(toggleLight, "_Color", toggleState ? trueColor : falseColor);

        GenerateTrial();
    }
Exemplo n.º 13
0
        static void Main()
        {
            DirectoryInfo directory = new DirectoryInfo(@"c:\CSharpInDepthLogs");

            if (directory.Exists)
            {
                directory.Delete(true);
            }
            directory.Create();

            DateTime today = DateTime.UtcNow.Date;

            DateTime start = DateTime.Now;

            foreach (DateTime date in new DateTimeRange(today.AddDays(-FilesToGenerate),
                                                        today.AddDays(-1)))
            {
                using (TextWriter writer = new StreamWriter(Path.Combine(directory.FullName, date.ToString("yyyyMMdd'.log'"))))
                {
                    for (int i = 0; i < EntriesPerFile; i++)
                    {
                        LogEntry entry = new LogEntry
                        {
                            Timestamp = date + TimeSpan.FromTicks(TicksPerEntry * i),
                            Type      = (EntryType)StaticRandom.Next(NumberOfEntryTypes),
                            Message   = GenerateRandomMessage()
                        };
                        entry.WriteTo(writer);
                    }
                }
            }
            DateTime end = DateTime.Now;

            Console.WriteLine(end - start);
        }
Exemplo n.º 14
0
        public PersonalDataStructure GeneratePersonalData(UserGenderEnum?gender = null)
        {
            int contactNumber = StaticRandom.Next();

            string name;
            string lastName = "Doe " + contactNumber;

            gender = gender ?? (UserGenderEnum)(contactNumber % 3);
            if (gender.Value == UserGenderEnum.Male)
            {
                name = "John";
            }
            else if (gender.Value == UserGenderEnum.Female)
            {
                name = "Jolene";
            }
            else
            {
                name = "Dog";
            }


            return(new PersonalDataStructure()
            {
                Gender = gender.Value,
                FirstName = name,
                LastName = lastName,
                Address = name + " street",
                City = name + " city",
                MobilePhone = contactNumber.ToString(),
                HomePhone = (contactNumber * 2).ToString(),
                ZIP = (contactNumber * 3).ToString(),
            });
        }
Exemplo n.º 15
0
        protected override object GenerateBodyRequest()
        {
            var plan = new PlanClientData();

            plan.Windows = GenerateWindows();
            var minContainerID = plan.Windows.Min(x => x.WindowID) - 1;

            plan.MainContainer = GenerateMainContainer(ref minContainerID);

            var walls           = plan.MainContainer.Floors.SelectMany(f => f.Rooms.SelectMany(r => r.Walls)).ToList();
            var windowsIDsStack = new Stack <int>(plan.Windows.Select(x => x.WindowID));

            while (windowsIDsStack.Count > 0)
            {
                foreach (var wall in walls)
                {
                    if (StaticRandom.Next(3) != 0)
                    {
                        continue;
                    }

                    if (wall.WindowIDs == null)
                    {
                        wall.WindowIDs = new List <int>();
                    }

                    wall.WindowIDs.Add(windowsIDsStack.Pop());
                    if (windowsIDsStack.Count == 0)
                    {
                        break;
                    }
                }
            }

            var rooms = plan.MainContainer.Floors.SelectMany(f => f.Rooms).ToList();

            foreach (var room in rooms)
            {
                var roomWindowIDs = room.Walls.Where(w => w.WindowIDs != null).SelectMany(w => w.WindowIDs);
                foreach (var group in room.Groups)
                {
                    foreach (var windowID in roomWindowIDs)
                    {
                        if (StaticRandom.Next(3) != 0)
                        {
                            continue;
                        }

                        if (group.WindowIDs == null)
                        {
                            group.WindowIDs = new List <int>();
                        }

                        group.WindowIDs.Add(windowID);
                    }
                }
            }

            return(plan);
        }
Exemplo n.º 16
0
 private PerfMonValue MakeFakeValue(DateTime date)
 {
     return(new PerfMonValue()
     {
         Time = TimeUtil.GetTimeInMsSinceEpoch(date), Value = StaticRandom.Next(0, 100)
     });
 }
Exemplo n.º 17
0
        public FluidPainter2D()
        {
            InitializeComponent();

            this.Background = SystemColors.ControlBrush;

            //NOTE: RandColorType.Any is calculated on the fly isntead of preloaded
            _randColors = new SortedList <RandColorType, Color[]>();
            _randColors.Add(RandColorType.Black_Green, new Color[] { Colors.Black, Colors.Black, Colors.Black, Colors.Chartreuse });
            _randColors.Add(RandColorType.Black_Orange, new Color[] { Colors.Black, Colors.Black, Colors.Black, UtilityWPF.ColorFromHex("F76700") });
            _randColors.Add(RandColorType.Black_Purple, new Color[] { Colors.Black, Colors.Black, Colors.Black, UtilityWPF.ColorFromHex("811CD6") });
            _randColors.Add(RandColorType.Red_Tan_Green, new string[] { "65BA99", "59A386", "F1DDBB", "D6C4A6", "E74C3C", "C74134" }.Select(o => UtilityWPF.ColorFromHex(o)).ToArray());
            _randColors.Add(RandColorType.Tans, new string[] { "736753", "594832", "D9CFC7", "BFB6AE", "A68D77" }.Select(o => UtilityWPF.ColorFromHex(o)).ToArray());
            _randColors.Add(RandColorType.Skittles, new string[] { "AC1014", "E87011", "FDD526", "73C509", "0980BA", "65286B" }.Select(o => UtilityWPF.ColorFromHex(o)).ToArray());
            _randColors.Add(RandColorType.Unispew, new string[] { "FF009C", "FFA11F", "9BFF00", "00FFFD", "8E47FF" }.Select(o => UtilityWPF.ColorFromHex(o)).ToArray());
            _randColors.Add(RandColorType.Camo, new string[] { "244034", "5E744A", "9EA755", "0D0A00", "745515" }.Select(o => UtilityWPF.ColorFromHex(o)).ToArray());
            _randColors.Add(RandColorType.Cold_Beach, new string[] { "CCC8B1", "858068", "FFFCF6", "B7ECFF", "B1CCCC" }.Select(o => UtilityWPF.ColorFromHex(o)).ToArray());
            _randColors.Add(RandColorType.Mono_Cyan, UtilityCore.Iterate(new string[] { "037B8E" }, Enumerable.Range(0, 10).Select(o => new string[] { "99A3A4", "B8BCBB", "535855", "79756A" }).SelectMany(o => o)).Select(o => UtilityWPF.ColorFromHex(o)).ToArray());

            foreach (string colorType in Enum.GetNames(typeof(RandColorType)))
            {
                cboBrushColorType.Items.Add(colorType.Replace('_', ' '));
                cboRandColorType.Items.Add(colorType.Replace('_', ' '));
            }
            cboBrushColorType.SelectedIndex = StaticRandom.Next(cboBrushColorType.Items.Count);
            cboRandColorType.SelectedIndex  = StaticRandom.Next(cboRandColorType.Items.Count);
        }
Exemplo n.º 18
0
        private static int[] PruneAutosavesSprtGetDeletes(List <int>[] deletableSets, int numToDelete)
        {
            if (deletableSets.Sum(o => o.Count) == numToDelete)
            {
                // Everything in deletable sets needs to be deleted, so just return them all instead of taking the expense of load balancing
                return(deletableSets.SelectMany(o => o).ToArray());
            }

            List <int> retVal = new List <int>();

            for (int cntr = 0; cntr < numToDelete; cntr++)
            {
                // Get the largest sets
                int          maxSize = deletableSets.Max(o => o.Count);
                List <int>[] largest = deletableSets.Where(o => o.Count == maxSize).ToArray();

                // Pick a random set, and a random index within that set
                int setIndex   = StaticRandom.Next(largest.Length);
                int innerIndex = StaticRandom.Next(largest[setIndex].Count);

                // Store the value pointed to
                retVal.Add(largest[setIndex][innerIndex]);

                // Now remove this from the set
                largest[setIndex].RemoveAt(innerIndex);
            }

            return(retVal.ToArray());
        }
Exemplo n.º 19
0
        public ProducerResponse Process(IMessage message, bool addressed)
        {
            var match = Regex.Match(message.Text, @"^([a-z]\w*)\s+([a-z]\w*)\s+([a-z]\w*)$",
                                    RegexOptions.IgnoreCase);

            if (match.Success)
            {
                var words = new[] { match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value };

                var expandedAcronym        = String.Join(" ", words);
                var tlaChance              = int.Parse(Config.Get("PercentChanceOfNewTLA", "5"));
                var shouldCreateNewAcronym = StaticRandom.Next(0, 100) < tlaChance;

                if (shouldCreateNewAcronym)
                {
                    var acronym = new String(words.Select(s => s.First()).ToArray()).ToUpperInvariant();
                    if (!tlaDataStore.Put(acronym, expandedAcronym))
                    {
                        return(null);
                    }

                    // grab a random band name reply factoid and :shipit:
                    var bandNameFactoidStr = factoidDataStore.GetRandomValue("band name reply")?.Value ?? DefaultBandNameReply;
                    var bandNameFactoid    =
                        FactoidUtilities.GetVerbAndResponseFromPartialFactoid(bandNameFactoidStr);

                    // GHETTO ALERT
                    var coercedResponse = Regex.Replace(bandNameFactoid.Response, @"\$(?:band|tla)", expandedAcronym, RegexOptions.IgnoreCase);
                    return(new ProducerResponse(variableHandler.Substitute(coercedResponse, message), false));
                }
            }

            return(null);
        }
Exemplo n.º 20
0
        public static FieldData GenerateFieldData(LevelDescriptor descriptor)
        {
            CellData[,] cells = new CellData[descriptor.Width, descriptor.Height];

            for (int x = 0; x < cells.GetLength(0); x++)
            {
                for (int y = 0; y < cells.GetLength(1); y++)
                {
                    cells[x, y] = new CellData(x, y);
                }
            }


            CellData sourceCell = cells[StaticRandom.Next(descriptor.Width), StaticRandom.Next(descriptor.Height)];

            GenerateWires(cells, sourceCell, descriptor.Difficult);

            for (int x = 0; x < cells.GetLength(0); x++)
            {
                for (int y = 0; y < cells.GetLength(1); y++)
                {
                    FinalizeCell(cells[x, y], sourceCell);
                }
            }

            return(new FieldData()
            {
                CellsData = cells
            });
        }
Exemplo n.º 21
0
        // verifies that outgoing messages from a hub call:
        // - use the same primary service connection the hub call was made from
        // - pick and stick to the same secondary connection(s)
        public async Task OutgoingMessagesUseSameServiceConnection()
        {
            var builder = WebHost.CreateDefaultBuilder()
                          .ConfigureServices((IServiceCollection services) => {})
                          .ConfigureLogging(logging => logging.AddXunit(_output))
                          .UseStartup <IntegrationTestStartup <MockServiceMessageOrderTestParams, UseSameServiceConnectionHub> >();

            using var server = new AspNetTestServer(builder);
            var mockSvc = (server.Host.Services.GetRequiredService <ServiceHubDispatcher <UseSameServiceConnectionHub> >()
                           as MockServiceHubDispatcher <UseSameServiceConnectionHub>).MockService;
            await mockSvc.AllConnectionsEstablished();

            List <MockServiceSideConnection> allSvcConns = mockSvc.ServiceSideConnections;

            // A few extra checks (just for this initial test to verify more invariants)
            // Each ServiceEndpoint will have ConnectionCount connections
            Assert.Equal(
                MockServiceMessageOrderTestParams.ConnectionCount * MockServiceMessageOrderTestParams.ServiceEndpoints.Length,
                allSvcConns.Count);
            int endpointCount = allSvcConns.Distinct(new MockServiceSideConnectionEndpointComparer()).Count();

            Assert.Equal(MockServiceMessageOrderTestParams.ServiceEndpoints.Length, endpointCount);

            // specify invocation binder before making calls
            mockSvc.CurrentInvocationBinder = new TestHubBroadcastNCallsInvocationBinder();

            // pick a random primary svc connection to make a client connection
            var priList = allSvcConns.Where(i => i.Endpoint.EndpointType == EndpointType.Primary).ToList();

            await using var primarySvc0 = priList[StaticRandom.Next(priList.Count)];
            var client0 = await primarySvc0.ConnectClientAsync();

            const int MsgNum = 10;
            await client0.SendMessage("BroadcastNumCalls", new object[] { MsgNum });

            var counts = await DrainBroadcastMessages(endpointCount, MsgNum, mockSvc);

            // Did we got the expected number of calls and all of them stick to exactly one primary?
            var primary = counts.Where(c => c.Key.Endpoint.EndpointType == EndpointType.Primary);

            Assert.Single(primary);

            // the primary is the one we used to send client message
            Assert.Equal(primarySvc0, primary.FirstOrDefault().Key);

            // the primary received MsgNum messages
            Assert.Equal(MsgNum, primary.FirstOrDefault().Value);

            // for every secondary that received the messages verify that
            // - their number equals to the number of seconary endpoints
            // - each received N messages
            var secondary          = counts.Where(c => c.Key.Endpoint.EndpointType == EndpointType.Secondary);
            var secondaryEndpoints = MockServiceMessageOrderTestParams.ServiceEndpoints.Where(ep => ep.EndpointType == EndpointType.Secondary);

            Assert.Equal(secondaryEndpoints.Count(), secondary.Count());
            foreach (var conn in secondary)
            {
                Assert.Equal(MsgNum, conn.Value);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// This returns a candidate that still needs to be spawned and scored
        /// </summary>
        public Tuple <long, ShipDNA> GetCandidate(string shipName)
        {
            // Find the finalists that still need more spawned
            TrackingCandidate[] finalists = _finalists.Where(o => o.DNA.ShipName == shipName && o.NumStarted < this.FinalistCount).ToArray();

            TrackingCandidate finalist = null;

            if (finalists.Length > 0)
            {
                // Pick a random one
                finalist = finalists[StaticRandom.Next(finalists.Length)];
            }
            else
            {
                // See if there are any candidates waiting to go in the finalist list
                ShipDNA dna = this.Candidates.Pop(shipName);
                if (dna == null)
                {
                    return(null);
                }

                finalist = new TrackingCandidate(dna);
                _finalists.Add(finalist);
            }

            // Exit Function
            return(Tuple.Create(finalist.Token, finalist.DNA));
        }
Exemplo n.º 23
0
        /// <summary>
        /// Sample using a random walk with teleport technique.
        /// </summary>
        /// <typeparam name="TNode"></typeparam>
        /// <typeparam name="TLabel"></typeparam>
        /// <param name="graph"></param>
        /// <param name="n">Upper bound on the number of nodes to sample.</param>
        /// <param name="p">Probability to teleport to a random node after visiting a node.</param>
        /// <returns></returns>
        public static HashSet <TNode> RandomWalkTeleport <TNode, TLabel>(this MultiDirectedGraph <TNode, TLabel> graph, int n, double p)
        {
            var V     = new HashSet <TNode>();
            var nodes = graph.Nodes.ToArray();

            n = Math.Min(n, graph.NumNodes);

            // Initial teleport
            var v = nodes[StaticRandom.Next(nodes.Length)];

            while (n > 0)
            {
                if (!V.Contains(v))
                {
                    V.Add(v);
                    n -= 1;
                }

                double t            = StaticRandom.NextDouble();
                var    outNeighbors = graph.Out(v).Select(eo => graph.Target(eo)).ToArray();

                if (t < p || outNeighbors.Length <= 0)
                {
                    // Teleport
                    v = nodes[StaticRandom.Next(nodes.Length)];
                }
                else
                {
                    v = outNeighbors[StaticRandom.Next(outNeighbors.Length)];
                }
            }

            return(V);
        }
Exemplo n.º 24
0
        public async Task Call_NegotiateAsync_After_WithEndpoints(ServiceTransportType serviceTransportType)
        {
            var serviceManager = new ServiceManagerBuilder()
                                 .WithOptions(o =>
            {
                o.ServiceTransportType = serviceTransportType;
                o.ServiceEndpoints     = ServiceEndpoints;
            })
                                 .BuildServiceManager();
            var hubContext = await serviceManager.CreateHubContextAsync(Hub, default);

            for (var i = 0; i < 5; i++)
            {
                var randomEndpoint      = ServiceEndpoints[StaticRandom.Next(0, Count)];
                var negotiationResponse = await(hubContext as IInternalServiceHubContext)
                                          .WithEndpoints(new ServiceEndpoint[] { randomEndpoint })
                                          .NegotiateAsync();

                Assert.Equal(ClientEndpointUtils.GetExpectedClientEndpoint(Hub, null, randomEndpoint.Endpoint), negotiationResponse.Url);
                var tokenString   = negotiationResponse.AccessToken;
                var token         = JwtTokenHelper.JwtHandler.ReadJwtToken(tokenString);
                var expectedToken = JwtTokenHelper.GenerateJwtBearer(
                    ClientEndpointUtils.GetExpectedClientEndpoint(Hub, null, randomEndpoint.Endpoint),
                    ClaimsUtility.BuildJwtClaims(null, null, null), token.ValidTo, token.ValidFrom, token.ValidFrom, randomEndpoint.AccessKey);
                Assert.Equal(expectedToken, tokenString);
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// This returns a random winner for the type requested (could return null)
        /// WARNING: Don't modify the returned dna directly, make a copy first
        /// </summary>
        public ShipDNA GetWinner(string name)
        {
            var current = _current;             // store local because it's volatile

            if (current == null)
            {
                return(null);
            }

            // Find the set for the name requested
            WinningSet set = current.Item2.Where(o => o.ShipName == name).FirstOrDefault();

            if (set == null)
            {
                return(null);
            }

            // Get all the beans across all the lineages
            var beans = set.BeansByLineage.SelectMany(o => o.Item2).ToArray();

            // Pick a random one
            int index = StaticRandom.Next(beans.Length);

            if (beans[index].Ship == null)
            {
                return(beans[index].DNA);
            }
            else
            {
                return(beans[index].Ship.GetNewDNA());
            }
        }
Exemplo n.º 26
0
        private static string GetRandomAlbum(IReadOnlyList <string> albumName)
        {
            string choice = albumName[StaticRandom.Next(0, albumName.Count)];
            string dir    = Path.Combine(_imagePath, choice);

            return(dir);
        }
Exemplo n.º 27
0
        private void Reset2a_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ResetField();

                int depth = 2 + StaticRandom.Next(_field.Size - 4);

                for (int x = 0; x < _field.Size; x++)
                {
                    for (int y = 0; y < _field.Size; y++)
                    {
                        for (int z = depth - 2; z <= depth + 2; z++)
                        {
                            _field.SetInk(_field.Get1DIndex(x, y, z), .75);
                        }
                    }
                }

                //_field.Update();
                //DrawField(_bitmap, _field);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Reserves a region of memory within the virtual address space of a specified process.
        /// </summary>
        /// <param name="processHandle">The handle to a process.</param>
        /// <param name="allocAddress">The rough address of where the allocation should take place.</param>
        /// <param name="size">The size of the region of memory to allocate, in bytes.</param>
        /// <param name="protectionFlags">The memory protection for the region of pages to be allocated.</param>
        /// <param name="allocationFlags">The type of memory allocation.</param>
        /// <returns>The base address of the allocated region</returns>
        public static IntPtr Allocate(
            IntPtr processHandle,
            IntPtr allocAddress,
            Int32 size,
            MemoryProtectionFlags protectionFlags = MemoryProtectionFlags.ExecuteReadWrite,
            MemoryAllocationFlags allocationFlags = MemoryAllocationFlags.Commit | MemoryAllocationFlags.Reserve)
        {
            if (allocAddress != IntPtr.Zero)
            {
                /* A specific address has been given. We will modify it to support the following constraints:
                 *  - Aligned by 0x10000 / 65536
                 *  - Pointing to an unallocated region of memory
                 *  - Within +/- 2GB (using 1GB for safety) of address space of the originally specified address, such as to always be in range of a far jump instruction
                 * Note: A retry count has been put in place because VirtualAllocEx with an allocAddress specified may be invalid by the time we request the allocation.
                 */

                IntPtr result     = IntPtr.Zero;
                Int32  retryCount = 0;

                // Request all chunks of unallocated memory. These will be very large in a 64-bit process.
                IEnumerable <MemoryBasicInformation64> freeMemory = Memory.QueryUnallocatedMemory(
                    processHandle,
                    allocAddress.Subtract(Int32.MaxValue >> 1, wrapAround: false),
                    allocAddress.Add(Int32.MaxValue >> 1, wrapAround: false));

                // Convert to normalized regions
                IEnumerable <NormalizedRegion> regions = freeMemory.Select(x => new NormalizedRegion(x.BaseAddress, x.RegionSize.ToInt32()));

                // Chunk the large regions into smaller regions based on the allocation size (minimum size is the alloc alignment to prevent creating too many chunks)
                List <NormalizedRegion> subRegions = new List <NormalizedRegion>();
                foreach (NormalizedRegion region in regions)
                {
                    region.BaseAddress = region.BaseAddress.Subtract(region.BaseAddress.Mod(Memory.AllocAlignment), wrapAround: false);
                    IEnumerable <NormalizedRegion> chunkedRegions = region.ChunkNormalizedRegion(Math.Max(size, Memory.AllocAlignment)).Take(128).Where(x => x.RegionSize >= size);
                    subRegions.AddRange(chunkedRegions);
                }

                do
                {
                    // Sample a random chunk and attempt to allocate the memory
                    result = subRegions.ElementAt(StaticRandom.Next(0, subRegions.Count())).BaseAddress;
                    result = NativeMethods.VirtualAllocEx(processHandle, result, size, allocationFlags, protectionFlags);

                    if (result != IntPtr.Zero || retryCount >= Memory.AllocateRetryCount)
                    {
                        break;
                    }

                    retryCount++;
                }while (result == IntPtr.Zero);

                return(result);
            }
            else
            {
                // Allocate a memory page
                return(NativeMethods.VirtualAllocEx(processHandle, allocAddress, size, allocationFlags, protectionFlags));
            }
        }
Exemplo n.º 29
0
        public DataStoreValue GetRandomValue(string key)
        {
            var values = data[key].ToList();

            return(values.Count == 0
                       ? null
                    : new DataStoreValue(-1, key, values.ElementAt(StaticRandom.Next(0, values.Count))));
        }
Exemplo n.º 30
0
        private static string GetRandomPhoto(string dir)
        {
            string[] innerContent = ConcurrentFile.ReadAllLines(Path.Combine(dir, ".content"));
            string   innerChoice  = innerContent[StaticRandom.Next(0, innerContent.Length)];
            string   file         = Path.Combine(dir, innerChoice);

            return(file);
        }