/// <summary> /// Generates random CharacterId /// </summary> /// <param name="counter">Counter of number of tries to generate a random character Id.</param> /// <returns>CharacterId</returns> public static long generateCharacterId(int counter = 0) { long Result = StaticRandom.NextLong(); if (Database.Characters.Get(Result) != null) { if (counter < 100) { counter++; generateCharacterId(counter); } else { throw new ArgumentException($"CharacterHelper::generateCharacterId - Can not generate random character Id after {counter} tries"); } } return(Result); }
public static double NextGaussian(double mu = 0, double sigma = 1) { double x, u, v, s; if (isStored) { isStored = !isStored; return(prevGauss * sigma + mu); } do { u = 2 * StaticRandom.NextDouble() - 1; v = 2 * StaticRandom.NextDouble() - 1; s = u * u + v * v; } while (s >= 1 || s == 0); x = Math.Sqrt(-2 * Math.Log(s) / s); prevGauss = x * u; isStored = !isStored; return(x * v * sigma + mu); }
private static int GetRandomInventoryCount(int current, int averageIfNone) { double retVal; if (current == 0) { retVal = StaticRandom.NextPercent(averageIfNone, 2.5); } else { retVal = current * StaticRandom.NextPercent(1, .5); } if (retVal == 0) { retVal = 1; } return(Convert.ToInt32(Math.Round(retVal))); }
public void Revalidate() { int childCount = this.rectTransform.childCount; if (this.deck.Count < childCount) { // There are currently more children than there should be, so remove // children from the top of the stack until we're back to the right // number. int removeCount = childCount - this.deck.Count; for (int i = 0; i < removeCount; ++i) { int back = this.rectTransform.childCount - 1; GameObject child = this.rectTransform.GetChild(back).gameObject; child.transform.SetParent(null); GameObject.Destroy(child); } } else if (this.deck.Count > childCount) { // There are currently not enough children, so add card backs until we // get to the right number. int addCount = this.deck.Count - childCount; for (int i = 0; i < addCount; ++i) { GameObject card = GameObject.Instantiate(cardBackPrefab, this.rectTransform); RectTransform cardTransform = card.GetComponent <RectTransform>(); cardTransform.pivot = new Vector2(0.5f, 0.5f); cardTransform.anchorMin = new Vector2(0.5f, 0.5f); cardTransform.anchorMax = new Vector2(0.5f, 0.5f); // Rotate the card a littel bit to make it sloppy. cardTransform.Rotate(0f, 0f, StaticRandom.Range(-3f, 3f)); // Shift the card slightly for the same reason. cardTransform.anchoredPosition = StaticRandom.Range( new Vector2(-3f, -3f), new Vector2(-3f, -3f) ) / this.rectTransform.localScale; } } this.invalidated = false; }
private Unit divide(Unit p0, Unit p1, out Unit streetWidth) { if (p0 > p1) { Do.Swap(ref p0, ref p1); } var d = p1 - p0; var sw = d.NumericValue.Sqrted() * 0.3f; streetWidth = Math.Floor(sw).Clamped(1.5f, 5).U(); var ret = p0 + d * StaticRandom.Float(0.3f, 0.7f); var offset = streetWidth + minBlockSize * 0.5f; var ret2 = ret.NumericValue.Clamped((p0 + offset).NumericValue, (p1 - offset).NumericValue).U(); return(ret2); }
public static void SetupMps(int n) { List <BigZp> inputs = new List <BigZp>(); for (int i = 0; i < n; i++) { inputs.Add(new BigZp(prime, StaticRandom.Next(prime))); } /* * Console.WriteLine("Inputs: " + string.Join(" ", inputs)); * var sorted = inputs.Select(zp => zp.Value).ToList(); * sorted.Sort(); * * Console.WriteLine("Expected Output: " + string.Join(" ", sorted)); */ for (int i = 0; i < n; i++) { NetSimulator.RegisterParty(new MpsParty(n, inputs[i])); } }
public void MultipleCompetitorsWithLanguagesAreCachedAndApiCalledOnceForEachDelayed() { const string callType = "GetCompetitorAsync"; const int cidCount = 100; Assert.IsNotNull(_memoryCache); Assert.IsTrue(!_memoryCache.Any()); Assert.AreEqual(0, _dataRouterManager.GetCallCount(callType), $"{callType} should be called 0 times."); _dataRouterManager.AddDelay(TimeSpan.FromSeconds(10), true, 10); for (var i = 0; i < 1000; i++) { Debug.Print($"{DateTime.Now} - {i}"); var cid = i < cidCount ? i + 1 : StaticRandom.I(cidCount); var competitor = _profileCache.GetCompetitorProfileAsync(CreateCompetitorUrn(cid), TestData.Cultures).Result; Assert.IsNotNull(competitor); } Assert.AreEqual(cidCount, _memoryCache.Count(s => s.Key.Contains(":competitor:"))); Assert.AreEqual(TestData.Cultures.Count * cidCount, _dataRouterManager.GetCallCount(callType), $"{callType} should be called exactly {TestData.Cultures.Count * cidCount} times."); }
List <GroupClientData> GenerateGroups(ref int nextContainerID) { var groups = new List <GroupClientData>(); for (int i = 1; i < StaticRandom.Next(2) + 2; i++) { var group = new GroupClientData() { ContainerID = nextContainerID--, Name = $"Group {i}", Settings = new GroupSettings() { Color = StaticRandom.Next(Int32.MaxValue) }, }; groups.Add(group); } return(groups); }
/// <summary> /// called by timeout /// </summary> public async Task FillPendingRoomWithBots(Room room) { room.RoomBots = new(); var botsCount = room.Capacity - room.RoomUsers.Count; var botIds = new List <string> { "999", "9999", "99999" }; for (int i = 0; i < botsCount; i++) { var botId = botIds.Cut(StaticRandom.GetRandom(botIds.Count)); room.RoomBots.Add(new RoomBot { Id = botId, Room = room }); } room.RoomActors.AddRange(room.RoomBots); await PrepareRoom(room); }
private void Broadcast(NetworkContextImpl senderContext, byte[] buffer, int offset, int length) { byte[] payload = new byte[length]; Buffer.BlockCopy(buffer, offset, payload, 0, length); if (StaticRandom.NextDouble() > Math.Sqrt(1 - dropRate)) { return; } foreach (var context in contexts) { if (StaticRandom.NextDouble() > Math.Sqrt(1 - dropRate)) { return; } if (context != senderContext) { context.HandleDataArrived(payload); } } }
public async Task SportEventCacheSemiSequentialTest() { var stopWatch = Stopwatch.StartNew(); Assert.AreEqual(0, _memoryCache.Count()); var i = 1000; var culture = TestData.Cultures4[StaticRandom.I(4)]; while (i > 0) { var matchId = URN.Parse($"sr:match:1{StaticRandom.I100}"); i--; var ci = await GetMatchCacheItemAsync(matchId, culture, stopWatch, i).ConfigureAwait(false); Assert.IsNotNull(ci); Assert.AreEqual(matchId, ci.Id); } Assert.IsTrue(_memoryCache.Count() > 50); Assert.IsTrue(_memoryCache.Count() < 100); }
private RuleInfo GenerateRule(int siteId) { var random = StaticRandom.NextDouble(); RuleTypeEnum ruleType = random < 0.166 ? RuleTypeEnum.Attribute : random < 0.333 ? RuleTypeEnum.Macro : RuleTypeEnum.Activity; switch (ruleType) { case RuleTypeEnum.Activity: return(GenerateActivityRule(siteId)); case RuleTypeEnum.Attribute: return(GenerateAttributeRule(siteId)); case RuleTypeEnum.Macro: return(GenerateMacroRule(siteId)); } return(null); }
/// <summary> /// This method removes how many it's told, or figures out how many to remove /// </summary> private static void RemoveRandomItems <T>(IList <T> list, int?removeCount = null) { if (list.Count == 0) { return; } Random rand = StaticRandom.GetRandomForThread(); if (removeCount == null) { double percent = rand.NextDouble(.33, 1); removeCount = Convert.ToInt32(list.Count * percent); } for (int cntr = 0; cntr < removeCount.Value; cntr++) { list.RemoveAt(rand.Next(list.Count)); } }
private Tuple <int, Tuple <ColorHSV, FlagColorCategory>[]> GetRandomFlagColors_Group(List <Tuple <ColorHSV, FlagColorCategory> > existing) { int groupIndex = -1; Tuple <ColorHSV, FlagColorCategory>[] existingOfGroup = null; Random rand = StaticRandom.GetRandomForThread(); while (true) { // Pick a random group double percent = rand.NextDouble(); for (int cntr = 0; cntr < this.MaxPerFlag.Length; cntr++) { if (percent >= this.MaxPerFlag[cntr].Item3 && percent < this.MaxPerFlag[cntr].Item4) { groupIndex = cntr; break; } } if (groupIndex < 0) { throw new ApplicationException("Couldn't find a category group"); } // See if there are open slots in this group existingOfGroup = existing. Where(o => this.MaxPerFlag[groupIndex].Item1.Contains(o.Item2)). ToArray(); if (existingOfGroup.Length < this.MaxPerFlag[groupIndex].Item2) { break; } } return(Tuple.Create(groupIndex, existingOfGroup)); }
public SwarmBay(EditorOptions options, ItemOptions itemOptions, ShipPartDNA dna, Map map, World world, int material_SwarmBot, IContainer plasma, SwarmObjectiveStrokes strokes) : base(options, dna, itemOptions.SwarmBay_Damage.HitpointMin, itemOptions.SwarmBay_Damage.HitpointSlope, itemOptions.SwarmBay_Damage.Damage) { _itemOptions = itemOptions; _map = map; _world = world; _material_SwarmBot = material_SwarmBot; _plasma = plasma; _strokes = strokes; this.Design = new SwarmBayDesign(options, true); this.Design.SetDNA(dna); double volume, radius; GetMass(out _mass, out volume, out radius, out _scaleActual, dna, itemOptions); //this.Radius = radius; _timeBetweenBots = StaticRandom.NextPercent(itemOptions.SwarmBay_BirthRate, .1); int maxCount = (itemOptions.SwarmBay_MaxCount * Math1D.Avg(dna.Scale.X, dna.Scale.Y, dna.Scale.Z)).ToInt_Round(); if (maxCount < 0) { maxCount = 1; } _maxBots = maxCount; _plasmaTankThreshold = itemOptions.SwarmBay_Birth_TankThresholdPercent; _birthCost = itemOptions.SwarmBay_BirthCost; _birthRadius = itemOptions.SwarmBay_BirthSize / 2d; if (_map != null) { _map.ItemRemoved += Map_ItemRemoved; } this.Destroyed += SwarmBay_Destroyed; }
public async Task Start(CommandContext ctx) { if (ctx.Channel.IsPrivate) { await ctx.TriggerTypingAsync(); var interactivity = ctx.Client.GetInteractivityModule(); var text = StaticRandom.NextString(StaticRandom.Next(6, 8), "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789"); var fontIndex = StaticRandom.Next(-1, Fonts.Count); using (var font = fontIndex == -1 ? null : new MemoryStream(Fonts[fontIndex])) { var asciiText = new AsciiArt(text, font == null ? null : new FIGletFont(font)); await ctx.RespondAsync($"```{asciiText}```"); } var response = await interactivity.WaitForMessageAsync(message => message.Author.Id == ctx.User.Id && message.Channel.IsPrivate, TimeSpan.FromSeconds(1.0)); await ctx.TriggerTypingAsync(); if (response == null) { await(await ctx.RespondAsync("Too late!")).CreateReactionAsync(DiscordEmoji.FromUnicode("⌛")); return; } if (text.Equals(response.Message.Content, StringComparison.Ordinal)) { await response.Message.CreateReactionAsync(DiscordEmoji.FromUnicode("🎉")); await ctx.RespondAsync("You did it! The flag is Pycon_{{45c11_M45t3r}}."); } else { await(await ctx.RespondAsync("You lost!")).CreateReactionAsync(DiscordEmoji.FromUnicode("😏")); } } }
static void Main(string[] args) { Console.WriteLine("Started."); StaticRandom.Init(seed); int quorumSize = 20; int degree = quorumSize / 3; var secret = new Zp(Prime, 3); var shareMatrix = ZpMatrix.GetIdentityMatrix(quorumSize, Prime); // create the initial shares var initalShares = ShamirSharing.Share(secret, quorumSize, degree); for (var i = 0; i < quorumSize; i++) { IList <Zp> reshares = QuorumSharing.CreateReshares(initalShares[i], quorumSize, degree); for (var j = 0; j < quorumSize; j++) { shareMatrix.SetMatrixCell(j, i, reshares[j]); } } // combine the reshares List <Zp> finalShares = new List <Zp>(); for (var i = 0; i < quorumSize; i++) { Zp finalShare = QuorumSharing.CombineReshares(shareMatrix.GetMatrixRow(i), quorumSize, Prime); finalShares.Add(finalShare); } // combine the shares Zp final = ShamirSharing.Recombine(finalShares, degree, Prime); Console.WriteLine(final.Value); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); }
private void CreateBox(Vector3 pos) { ///Create a Simple Model SimpleModel model = new SimpleModel(GraphicFactory, "..\\Content\\Model\\cubo"); model.SetTexture(GraphicFactory.CreateTexture2DColor(1, 1, StaticRandom.RandomColor()), TextureType.DIFFUSE); ///Create a Physic Object IPhysicObject pobj = new BoxObject(pos, 1, 1, 1, 10, new Vector3(2), Matrix.Identity, MaterialDescription.DefaultBepuMaterial()); pobj.isMotionLess = true; ///Create a shader IShader nd = new DeferredNormalShader(); ///Create a Material IMaterial material = new DeferredMaterial(nd); ///Create a an Object that englobs everything and add it to the world IObject obj = new IObject(material, model, pobj); this.World.AddObject(obj); objects.Add(obj); }
//randomizes values - only run for the initial generation public void randomizeValues() { //nodesize, constructprobability, buildingcount nodeSize.min = Random.Range(10, 20); nodeSize.max = Random.Range(nodeSize.min, 40); constructIntervals = new int[Random.Range(1, 100)]; for (int i = 0; i < constructIntervals.Length; i++) { constructIntervals[i] = Random.Range(0, 10); } this.position = new Vector2(((float)StaticRandom.Sample() * (Terrain.activeTerrain.terrainData.size.x - (gen.Dimension.x / 2))) + (gen.Dimension.x / 2), ((float)StaticRandom.Sample() * (Terrain.activeTerrain.terrainData.size.z - (gen.Dimension.y / 2))) + (gen.Dimension.x / 2)); //randomizes building count according to initial desired count +- 5 (atleast have 1 building) buildingCount = Random.Range(buildingCount - 5, buildingCount + 5); if (buildingCount < 1) { buildingCount = 1; } }
private void Reset1_Click(object sender, RoutedEventArgs e) { try { ResetField(); for (int x = 1; x < _field.Size - 1; x++) // if I go to the edges, they just get blanked out { for (int y = 1; y < _field.Size - 1; y++) { _field.SetInk(_field.Get1DIndex(x, y, 1 + StaticRandom.Next(_field.Size - 2)), 1); } } //_field.Update(); //DrawField(_bitmap, _field); } catch (Exception ex) { MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error); } }
private void MoveFrontOfInitial() { // Figure out how many to move int moveCount = _initialBuffer.Count - _keepInInitialCountOnOverflow; Random rand = StaticRandom.GetRandomForThread(); //NOTE: Going backward to the longterm first. That way there's a chance tentative won't need to be populated for (int cntr = moveCount - 1; cntr >= 0; cntr--) { if (_initialBuffer[cntr].Percent == null) { TransferToLongterm(_initialBuffer[cntr], rand); } else { TransferToTentative(_initialBuffer[cntr]); } _initialBuffer.RemoveAt(cntr); } }
public IState Play() { double successProb = (2.25 * attacker.LPS + 5 + 2.25 * 10) / 100.0; if (!counter) { successProb += 2.25 * (10 - defender.DEF) / 100; } if (StaticRandom.RandDouble() > successProb) { /***Cross is blocked***/ switch (StaticRandom.Rand(3)) { case 0: if (left) { return(new ThrowInState(attTeam, defTeam, 'l')); } else { return(new ThrowInState(attTeam, defTeam, 'r')); } case 1: return(new ClearenceState(defTeam, attTeam)); case 2: return(new CornerState(attTeam, defTeam)); default: return(null); } } else { /***Not blocked - cross***/ return(new LowCrossState(attTeam, defTeam, attacker)); } }
private void TestPositive() { double min = 15; double max = 18; while (min > 0) { double result = StaticRandom.Rand(min, max); if (result < min || result > max || result < 0) { Console.WriteLine("Min: " + min.ToString()); Console.WriteLine("Max: " + max.ToString()); Console.WriteLine("Result: " + result.ToString()); Assert.Fail("Invalid result: "); } min -= .05; max -= .05; } }
public IState Play() { double y = attacker.FIN - defender.DEF + 7; double shotProb = (-0.0125 * y * y + 3 * y + 50) / 100; if (counter) { shotProb = 1.5 * shotProb / (shotProb + 0.5); } if (StaticRandom.RandDouble() > shotProb) /***Shot is blocked***/ { switch (StaticRandom.Rand(3)) { case 0: return(new CornerState(attTeam, defTeam)); case 1: return(new ClearenceState(defTeam, attTeam)); case 2: return(new OutboxReboundState(attTeam, defTeam)); default: return(null); } } else /***Not blocked - shot***/ if (StaticRandom.RandDouble() < 0.16) { return(new FreeKickState(attTeam, defTeam)); } else { return(new ShotState(attTeam, defTeam, attacker, "outbox")); } }
public IState Play() { double defProb; double y = attacker.FIN - defender.DEF + 7; defProb = (-0.0125 * y * y + 3 * y + 50) / 100; if (StaticRandom.RandDouble() > defProb) /***Shot is blocked***/ { switch (StaticRandom.Rand(4)) { case 0: return(new CornerState(attTeam, defTeam)); case 1: return(new ClearenceState(defTeam, attTeam)); case 2: return(new OutboxReboundState(attTeam, defTeam)); case 3: return(new InboxReboundState(attTeam, defTeam)); default: return(null); } } else /***Not blocked - penalty/shot***/ if (StaticRandom.RandDouble() < 0.05) { return(new PenaltyState(attTeam, defTeam)); } else { return(new ShotState(attTeam, defTeam, attacker, "inbox", assist)); } }
public void MoveShip(IntPtr webBrowserFlash) { if (browserMin.X > browserMax.X) { var bm = browserMin.X; browserMin.X = browserMax.X; browserMax.X = bm; } if (browserMin.Y > browserMax.Y) { var bm = browserMin.Y; browserMin.Y = browserMax.Y; browserMax.Y = bm; } var randomPoint = new Point { X = StaticRandom.Next(browserMin.X, browserMax.X), Y = StaticRandom.Next(browserMin.Y, browserMax.Y) }; Mouse.DoMouseLeftClick(webBrowserFlash, randomPoint); }
private static T GetRandomItemChance <T>(T[] items) where T : IItemChance { double randValue = StaticRandom.NextDouble(); double sum = 0; foreach (T item in items) { sum += item.ProbabilityPercent; if (sum > randValue) { return(item); } } if (sum.IsNearValue(1)) { return(items[items.Length - 1]); } throw new ApplicationException("Couldn't pick a random item. The percents don't add to one: " + sum.ToString()); }
private void CreateInternalModel(String fileName) { if (!modelLoaded.ContainsKey(fileName)) { ContentBuilder.Clear(); String iname = "Model" + StaticRandom.Random(); ContentBuilder.Add(fileName, iname, null, "ModelProcessor"); String buildError = ContentBuilder.Build(); if (string.IsNullOrEmpty(buildError)) { if (!Directory.Exists(Directory.GetCurrentDirectory() + "/Content/Loaded")) { Directory.CreateDirectory(Directory.GetCurrentDirectory() + "/Content/Loaded"); } MakeCopy(ContentBuilder.OutputDirectory, Directory.GetCurrentDirectory() + "/Content/Loaded/"); modelLoaded.Add(fileName, iname); } else { throw new Exception(buildError); } } }
public IState Play() { double shotProb = 1.0; double crossProb = 1.0; crossProb += (attTeam.All() .Select(x => x.HEA) .OrderByDescending(y => y) .Take(6) .Average() - 14) / 10.0; crossProb += shotProb; double p = StaticRandom.RandDouble(0, crossProb); if (p < shotProb) { return(new FreeKickShotState(attTeam, defTeam, attacker)); } else { return(new FreeKickCrossState(attTeam, defTeam, attacker)); } }
public IState Play() { double shortThrow = 1.0; double longThrow = 0.3 + (attacker.SP - 12) / 12.0; double p = StaticRandom.RandDouble(0, longThrow); if (p < shortThrow) { if (left) { return(new AttackSideState(attTeam, defTeam, 'l')); } else { return(new AttackSideState(attTeam, defTeam, 'r')); } } else { return(new BoxCrossState(attTeam, defTeam, attacker)); } }