public double GetRandom() { int block = SafeRandom.NextInt(0, numberOfBlocks - 1); if (block == 0) { return(TailFallback()); } double xRand = SafeRandom.NextDouble(); double yRand = SafeRandom.NextDouble(); int flip = SafeRandom.NextInt(0, 2); double xVal = xRand * x[block]; if (xVal < x[block + 1]) { if (flip == 1) { xVal = -xVal; } return(xVal); } double yVal = y[block] + (yRand * (y[block + 1] - y[block])); if (yVal < pFunc(xVal)) { if (flip == 1) { xVal = -xVal; } return(xVal); } return(GetRandom()); }
private static void BuyItem(Player player, ref MsgItem packet) { if (Collections.Items.TryGetValue(packet.Param, out var item)) { if (GameWorld.Find(packet.UnqiueId, out Npc shop)) { if (shop.Inventory == null) { Output.WriteLine($"Shop {shop.UniqueId} null."); return; } //if (!shop.Inventory.HasItem(item.ItemId)) //{ // Output.WriteLine($"Item {item.ItemId} not found in Shop {shop.UniqueId}"); // return; //} if (player.Money >= item.PriceBaseline) { if (player.Inventory.Count < 40) { var cloned = CloneChamber.Clone(item); cloned.UniqueId = SafeRandom.Next(1000, 100000); player.Inventory.Items.AddOrUpdate(cloned.UniqueId, cloned); player.Money -= cloned.PriceBaseline; player.Send(new MsgItemInformation(cloned, MsgItemPosition.Inventory)); } } } } }
private async Task RunAsync() { var random = new SafeRandom(); TimeSpan?overrideDelay = random.NextTimeSpan(InitialReadRetryPeriod); while (await listRefreshTimer.NextTick(overrideDelay)) { try { overrideDelay = null; switch (Status) { case GrainServiceStatus.Booting: await DoInitialReadAndUpdateReminders(); break; case GrainServiceStatus.Started: await ReadAndUpdateReminders(); break; default: listRefreshTimer.Dispose(); return; } } catch (Exception exception) { this.logger.LogWarning(exception, "Exception while reading reminders: {Exception}", exception); overrideDelay = random.NextTimeSpan(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(20)); } } }
public FakeRandom(params double[] values) { _values = values; _oldRandom = SafeRandom.TestGenerator?.Value; SafeRandom.SetTestGenerator(this); }
internal PersistentStreamPullingAgent( GrainId id, string strProviderName, IStreamProviderRuntime runtime, IStreamPubSub streamPubSub, QueueId queueId, PersistentStreamProviderConfig config) : base(id, runtime.ExecutingSiloAddress, true) { if (runtime == null) { throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: runtime reference should not be null"); } if (strProviderName == null) { throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: strProviderName should not be null"); } QueueId = queueId; streamProviderName = strProviderName; pubSub = streamPubSub; pubSubCache = new Dictionary <StreamId, StreamConsumerCollection>(); safeRandom = new SafeRandom(); this.config = config; numMessages = 0; logger = runtime.GetLogger(((ISystemTargetBase)this).GrainId + "-" + streamProviderName); logger.Info(ErrorCode.PersistentStreamPullingAgent_01, "Created {0} {1} for Stream Provider {2} on silo {3} for Queue {4}.", GetType().Name, ((ISystemTargetBase)this).GrainId.ToDetailedString(), streamProviderName, Silo, QueueId.ToStringWithHashCode()); numReadMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_READ_MESSAGES, StatisticUniquePostfix)); numSentMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_SENT_MESSAGES, StatisticUniquePostfix)); // TODO: move queue cache size statistics tracking into queue cache implementation once Telemetry APIs and LogStatistics have been reconciled. //IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_QUEUE_CACHE_SIZE, statUniquePostfix), () => queueCache != null ? queueCache.Size : 0); }
private static (ulong MagicMultiplier, ulong[] MovesMasks) FindMagicMultiplier(Dictionary <ulong, ulong> occupancyToMovesMask, int shift, ulong?knownMagicMultiplier) { var indexBits = 64 - shift; var indexLength = (int)Math.Pow(2d, indexBits); var movesMasks = new ulong[indexLength]; var occupancies = new List <ulong>(occupancyToMovesMask.Keys); NextMagicMultiplier: var magicMultiplier = knownMagicMultiplier ?? SafeRandom.NextULong(); // Clear moves masks. for (var maskIndex = 0; maskIndex < movesMasks.Length; maskIndex++) { movesMasks[maskIndex] = 0; } for (var occupancyIndex = 0; occupancyIndex < occupancies.Count; occupancyIndex++) { var occupancy = occupancies[occupancyIndex]; var magicIndex = GetMagicIndex(occupancy, magicMultiplier, shift); var movesMask = movesMasks[magicIndex]; if (movesMask == 0) { movesMasks[magicIndex] = occupancyToMovesMask[occupancy]; // Moves mask not yet added to unique moves array. } else if (movesMask != occupancyToMovesMask[occupancy]) { goto NextMagicMultiplier; // Moves mask already added to unique moves array but mask is incorrect. } } // Found magic multiplier that maps to correct moves index for all occupancies. return(magicMultiplier, movesMasks); }
private void AddSalesOrderLine(UserContext userContext, ClientLogicalForm newSalesOrderPage, int index) { var repeater = newSalesOrderPage.Repeater(); var rowCount = repeater.Offset + repeater.DefaultViewport.Count; if (index >= rowCount) { // scroll to the next viewport userContext.InvokeInteraction(new ScrollRepeaterInteraction(repeater, 1)); } var rowIndex = (int)(index - repeater.Offset); var itemsLine = repeater.DefaultViewport[rowIndex]; // Activate Type field itemsLine.Control("Type").Activate(); // set Type = Item TestScenario.SaveValueWithDelay(itemsLine.Control("Type"), "Item"); // Set Item No. from random lookup var itemNoControl = itemsLine.Control("No."); var itemNo = TestScenario.SelectRandomRecordFromLookup(TestContext, userContext, itemNoControl, "No."); TestScenario.SaveValueWithDelay(itemNoControl, itemNo); var qtyToOrder = SafeRandom.GetRandomNext(1, 10).ToString(CultureInfo.InvariantCulture); TestScenario.SaveValueAndIgnoreWarning(TestContext, userContext, itemsLine.Control("Quantity"), qtyToOrder); TestScenario.SaveValueAndIgnoreWarning(TestContext, userContext, itemsLine.Control("Qty. to Ship"), qtyToOrder, "OK"); // Look at the line for 1 seconds. DelayTiming.SleepDelay(DelayTiming.ThinkDelay); }
private void PromoteToStarted() { if (StoppedCancellationTokenSource.IsCancellationRequested) { return; } // Logger.Info(ErrorCode.RS_ServiceStarted, "Reminder system target started OK on: {0} x{1,8:X8}, with range {2}", this.Silo, this.Silo.GetConsistentHashCode(), this.myRange); var random = new SafeRandom(); var dueTime = random.NextTimeSpan(Constants.RefreshReminderList); if (listRefreshTimer != null) { listRefreshTimer.Dispose(); } listRefreshTimer = GrainTimer.FromTaskCallback( this.RuntimeClient.Scheduler, _ => ReadAndUpdateReminders(), null, dueTime, Constants.RefreshReminderList, name: "ReminderService.ReminderListRefresher"); listRefreshTimer.Start(); Status = GrainServiceStatus.Started; startedTask.TrySetResult(true); }
/// <summary> /// Attempt to retrieve reminders, that are my responsibility, from the global reminder table when starting this silo (reminder service instance) /// </summary> /// <returns></returns> public async Task Start() { myRange = ring.GetMyRange(); logger.Info(ErrorCode.RS_ServiceStarting, "Starting reminder system target on: {0} x{1,8:X8}, with range {2}", Silo, Silo.GetConsistentHashCode(), myRange); await reminderTable.Init(config, logger).WithTimeout(initTimeout); await ReadAndUpdateReminders(); logger.Info(ErrorCode.RS_ServiceStarted, "Reminder system target started OK on: {0} x{1,8:X8}, with range {2}", Silo, Silo.GetConsistentHashCode(), myRange); status = ReminderServiceStatus.Started; startedTask.TrySetResult(true); var random = new SafeRandom(); var dueTime = random.NextTimeSpan(Constants.RefreshReminderList); listRefresher = GrainTimer.FromTaskCallback( _ => ReadAndUpdateReminders(), null, dueTime, Constants.RefreshReminderList, name: "ReminderService.ReminderListRefresher"); listRefresher.Start(); ring.SubscribeToRangeChangeEvents(this); }
protected async Task RemindersRange(int iterations = 1000) { await Task.WhenAll(Enumerable.Range(1, iterations).Select(async i => { GrainReference grainRef = MakeTestGrainReference(); await RetryHelper.RetryOnExceptionAsync <Task>(10, RetryOperation.Sigmoid, async() => { await remindersTable.UpsertRow(CreateReminder(grainRef, i.ToString())); return(Task.CompletedTask); }); })); var rows = await remindersTable.ReadRows(0, uint.MaxValue); Assert.Equal(rows.Reminders.Count, iterations); rows = await remindersTable.ReadRows(0, 0); Assert.Equal(rows.Reminders.Count, iterations); var remindersHashes = rows.Reminders.Select(r => r.GrainRef.GetUniformHashCode()).ToArray(); SafeRandom random = new SafeRandom(); await Task.WhenAll(Enumerable.Range(0, iterations).Select(i => TestRemindersHashInterval(remindersTable, (uint)random.Next(), (uint)random.Next(), remindersHashes))); }
private void AddSalesOrderLine(UserContext userContext, ClientLogicalForm newSalesOrderPage, int line) { // Get Line var itemsLine = newSalesOrderPage.Repeater().DefaultViewport[line]; // Activate Type field itemsLine.Control("Type").Activate(); // set Type = Item TestScenario.SaveValueWithDelay(itemsLine.Control("Type"), "Item"); // Set Item No. var itemNo = TestScenario.SelectRandomRecordFromListPage(TestContext, ItemListPageId, userContext, "No."); TestScenario.SaveValueWithDelay(itemsLine.Control("No."), itemNo); string qtyToOrder = SafeRandom.GetRandomNext(1, 10).ToString(CultureInfo.InvariantCulture); TestScenario.SaveValueAndIgnoreWarning(TestContext, userContext, itemsLine.Control("Quantity"), qtyToOrder); TestScenario.SaveValueAndIgnoreWarning(TestContext, userContext, itemsLine.Control("Qty. to Ship"), qtyToOrder, "OK"); // Look at the line for 1 seconds. DelayTiming.SleepDelay(DelayTiming.ThinkDelay); }
public ExponentialBackoffRejectedExecutionHandler(int retries, TimeSpan minDelay, TimeSpan maxDelay, TimeSpan step) { if (retries <= 0) { ThrowHelper.ThrowArgumentException_Positive(retries, ExceptionArgument.retries); } if (minDelay <= TimeSpan.Zero) { ThrowHelper.ArgumentOutOfRangeException_Positive(minDelay, ExceptionArgument.minDelay); } if (maxDelay <= TimeSpan.Zero) { ThrowHelper.ArgumentOutOfRangeException_Positive(maxDelay, ExceptionArgument.maxDelay); } if (step <= TimeSpan.Zero) { ThrowHelper.ArgumentOutOfRangeException_Positive(step, ExceptionArgument.step); } if (minDelay >= maxDelay) { ThrowHelper.ArgumentOutOfRangeException_Invalid_minValue(minDelay); } _retries = retries; _minDelay = minDelay; _maxDelay = maxDelay; _step = step; _random = new SafeRandom(); }
internal PersistentStreamPullingAgent( GrainId id, string strProviderName, IStreamProviderRuntime runtime, QueueId queueId, TimeSpan queueGetPeriod, TimeSpan initQueueTimeout) : base(id, runtime.ExecutingSiloAddress, true) { if (runtime == null) { throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: runtime reference should not be null"); } QueueId = queueId; streamProviderName = strProviderName; providerRuntime = runtime; pubSub = runtime.PubSub(StreamPubSubType.GrainBased); pubSubCache = new Dictionary <StreamId, StreamConsumerCollection>(); safeRandom = new SafeRandom(); this.queueGetPeriod = queueGetPeriod; this.initQueueTimeout = initQueueTimeout; numMessages = 0; logger = providerRuntime.GetLogger(this.GrainId.ToString() + "-" + streamProviderName); logger.Info((int)ErrorCode.PersistentStreamPullingAgent_01, "Created {0} {1} for Stream Provider {2} on silo {3} for Queue {4}.", this.GetType().Name, this.GrainId.ToDetailedString(), streamProviderName, base.Silo, QueueId.ToStringWithHashCode()); numReadMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_READ_MESSAGES, strProviderName)); numSentMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_SENT_MESSAGES, strProviderName)); }
public static void Drop(YiObj attacker, Monster mob) { var rand = SafeRandom.Next(1, 1000); Item created = default(Item); switch (mob.Id) { case 3131: case 3135: created = ItemFactory.Create(ItemNames.ExpPotion); break; //exp potion from titan and gano default: { if (!GenerateDrop(attacker, mob, rand, ref created)) //YOU FORGOT TO ADD THE ! SO NOTHING WAS DROPPING { return; } break; } } if (created.Valid()) { FloorItemSystem.Drop(attacker, mob, created); } if (YiCore.Success(5)) //5% chance to drop more than one item. { Drop(attacker, mob); } }
public ExponentialBackoff(TimeSpan minDelay, TimeSpan maxDelay, TimeSpan step) { if (minDelay <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException("minDelay", minDelay, "ExponentialBackoff min delay must be a positive number."); } if (maxDelay <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException("maxDelay", maxDelay, "ExponentialBackoff max delay must be a positive number."); } if (step <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException("step", step, "ExponentialBackoff step must be a positive number."); } if (minDelay >= maxDelay) { throw new ArgumentOutOfRangeException("minDelay", minDelay, "ExponentialBackoff min delay must be greater than max delay."); } this.minDelay = minDelay; this.maxDelay = maxDelay; this.step = step; this.backoffFactor = 1; this.random = new SafeRandom(); }
/// <summary> /// Attempt to retrieve reminders, that are my responsibility, from the global reminder table when starting this silo (reminder service instance) /// </summary> /// <returns></returns> public async Task Start() { myRange = ring.GetMyRange(); logger.Info(ErrorCode.RS_ServiceStarting, "Starting reminder system target on: {0} x{1,8:X8}, with range {2}", Silo, Silo.GetConsistentHashCode(), myRange); // in case reminderTable is as grain, poke the grain to activate it, before slamming it with multipel parallel requests, which may create duplicate activations. await reminderTable.Init(); await ReadAndUpdateReminders(); logger.Info(ErrorCode.RS_ServiceStarted, "Reminder system target started OK on: {0} x{1,8:X8}, with range {2}", Silo, Silo.GetConsistentHashCode(), myRange); status = ReminderServiceStatus.Started; startedTask.TrySetResult(true); var random = new SafeRandom(); var dueTime = random.NextTimeSpan(Constants.RefreshReminderList); listRefresher = GrainTimer.FromTaskCallback( _ => ReadAndUpdateReminders(), null, dueTime, Constants.RefreshReminderList, name: "ReminderService.ReminderListRefresher"); listRefresher.Start(); ring.SubscribeToRangeChangeEvents(this); }
public ConstantProtection(ModuleDefMD module) { RP = Obfuscation.ObfuscationProcess.RP; _module = module; random = new SafeRandom(); InitializeCollatz(); }
public MultiClusterOracle( ILocalSiloDetails siloDetails, MultiClusterGossipChannelFactory channelFactory, ISiloStatusOracle siloStatusOracle, MembershipTableManager tableManager, IInternalGrainFactory grainFactory, ILoggerFactory loggerFactory, IOptions <MultiClusterOptions> multiClusterOptions) : base(Constants.MultiClusterOracleId, siloDetails.SiloAddress, loggerFactory) { this.loggerFactory = loggerFactory; this.channelFactory = channelFactory; this.siloStatusOracle = siloStatusOracle; this.tableManager = tableManager; this.grainFactory = grainFactory; logger = loggerFactory.CreateLogger <MultiClusterOracle>(); localData = new MultiClusterOracleData(logger, grainFactory); clusterId = siloDetails.ClusterId; var multiClusterOptionsSnapshot = multiClusterOptions.Value; defaultMultiCluster = multiClusterOptionsSnapshot.DefaultMultiCluster?.ToList(); this.multiClusterActive = multiClusterOptionsSnapshot.HasMultiClusterNetwork; this.maxMultiClusterGateways = multiClusterOptionsSnapshot.MaxMultiClusterGateways; random = new SafeRandom(); // to avoid convoying, each silo varies these period intervals a little backgroundGossipInterval = RandomizeTimespanSlightly(multiClusterOptionsSnapshot.BackgroundGossipInterval); resendActiveStatusAfter = RandomizeTimespanSlightly(ResendActiveStatusAfter); }
internal PersistentStreamPullingAgent( GrainId id, string strProviderName, IStreamProviderRuntime runtime, IStreamPubSub streamPubSub, QueueId queueId, PersistentStreamProviderConfig config) : base(id, runtime.ExecutingSiloAddress, true) { if (runtime == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: runtime reference should not be null"); if (strProviderName == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: strProviderName should not be null"); QueueId = queueId; streamProviderName = strProviderName; providerRuntime = runtime; pubSub = streamPubSub; pubSubCache = new Dictionary<StreamId, StreamConsumerCollection>(); safeRandom = new SafeRandom(); this.config = config; numMessages = 0; logger = providerRuntime.GetLogger(GrainId + "-" + streamProviderName); logger.Info((int)ErrorCode.PersistentStreamPullingAgent_01, "Created {0} {1} for Stream Provider {2} on silo {3} for Queue {4}.", GetType().Name, GrainId.ToDetailedString(), streamProviderName, Silo, QueueId.ToStringWithHashCode()); string statUniquePostfix = strProviderName + "." + QueueId; numReadMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_READ_MESSAGES, statUniquePostfix)); numSentMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_SENT_MESSAGES, statUniquePostfix)); IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_PUBSUB_CACHE_SIZE, statUniquePostfix), () => pubSubCache.Count); IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_QUEUE_CACHE_SIZE, statUniquePostfix), () => queueCache !=null ? queueCache.Size : 0); }
private void AddPurchaseInvoiceLine( UserContext userContext, ClientLogicalForm purchaseInvoicePage, int index) { using (new TestTransaction(TestContext, "AddPurchaseInvoiceLine")) { var repeater = purchaseInvoicePage.Repeater(); var rowCount = repeater.Offset + repeater.DefaultViewport.Count; if (index >= rowCount) { // scroll to the next viewport userContext.InvokeInteraction( new ScrollRepeaterInteraction(repeater, 1)); } var rowIndex = (int)(index - repeater.Offset); var itemsLine = repeater.DefaultViewport[rowIndex]; // select random Item No. from lookup var itemNoControl = itemsLine.Control("Item No."); var itemNo = TestScenario.SelectRandomRecordFromLookup( TestContext, userContext, itemNoControl, "No."); TestScenario.SaveValueWithDelay(itemNoControl, itemNo); var qtyToOrder = SafeRandom.GetRandomNext(1, 10); TestScenario.SaveValueWithDelay(itemsLine.Control("Quantity"), qtyToOrder); } }
public SingleStreamTestRunner(string streamProvider, int testNum = 0, bool fullTest = true) { this.streamProviderName = streamProvider; this.logger = TraceLogger.GetLogger("SingleStreamTestRunner", TraceLogger.LoggerType.Application); this.testNumber = testNum; this.runFullTest = fullTest; this.random = TestConstants.random; }
public QuasarClient(HostsManager hostsManager) : base() { this._hosts = hostsManager; this._random = new SafeRandom(); base.ClientState += OnClientState; base.ClientRead += OnClientRead; base.ClientFail += OnClientFail; }
public async Task InterleavingConsistencyTest(int numItems) { TimeSpan delay = TimeSpan.FromMilliseconds(1); SafeRandom random = new SafeRandom(); List <Task> getFileMetadataPromises = new List <Task>(numItems * 2); Dictionary <int, string> fileMetadatas = new Dictionary <int, string>(numItems * 2); for (int i = 0; i < numItems; i++) { int capture = i; Func <Task> func = ( async() => { await Task.Delay(random.NextTimeSpan(delay)); int fileMetadata = capture; if ((fileMetadata % 2) == 0) { fileMetadatas.Add(fileMetadata, fileMetadata.ToString()); } }); getFileMetadataPromises.Add(func()); } await Task.WhenAll(getFileMetadataPromises.ToArray()); List <Task> tagPromises = new List <Task>(fileMetadatas.Count); foreach (KeyValuePair <int, string> keyValuePair in fileMetadatas) { int fileId = keyValuePair.Key; Func <Task> func = (async() => { await Task.Delay(random.NextTimeSpan(delay)); string fileMetadata = fileMetadatas[fileId]; }); tagPromises.Add(func()); } await Task.WhenAll(tagPromises); // sort the fileMetadatas according to fileIds. List <string> results = new List <string>(fileMetadatas.Count); for (int i = 0; i < numItems; i++) { string metadata; if (fileMetadatas.TryGetValue(i, out metadata)) { results.Add(metadata); } } if (numItems != results.Count) { //throw new OrleansException(String.Format("numItems != results.Count, {0} != {1}", numItems, results.Count)); } }
internal SingleStreamTestRunner(IInternalClusterClient client, string streamProvider, int testNum = 0, bool fullTest = true) { this.client = client; this.streamProviderName = streamProvider; this.logger = TestingUtils.CreateDefaultLoggerFactory($"{this.GetType().Name}.log").CreateLogger <SingleStreamTestRunner>(); this.testNumber = testNum; this.runFullTest = fullTest; this.random = TestConstants.random; }
/// <summary> /// Randomizes the order of the source sequence in a new sequence. /// </summary> /// <param name="randomProvider">the random provider used to shuffle. if null, a new instance of <see cref="SafeRandom"/> is used</param> /// <exception cref="ArgumentNullException"/> public static IEnumerable Shuffle(this IEnumerable source, Random randomProvider) { Error.ThrowIfNull(source, nameof(source)); if (randomProvider is null) { randomProvider = new SafeRandom(); } return(source.OrderBy(_ => randomProvider.Next())); }
public QuasarClient(HostsManager hostsManager, X509Certificate2 serverCertificate) : base(serverCertificate) { this._hosts = hostsManager; this._random = new SafeRandom(); base.ClientState += OnClientState; base.ClientRead += OnClientRead; base.ClientFail += OnClientFail; }
internal SingleStreamTestRunner(IInternalGrainFactory grainFactory, string streamProvider, int testNum = 0, bool fullTest = true) { this.grainFactory = grainFactory; this.streamProviderName = streamProvider; this.logger = LogManager.GetLogger("SingleStreamTestRunner", LoggerType.Application); this.testNumber = testNum; this.runFullTest = fullTest; this.random = TestConstants.random; }
internal SingleStreamTestRunner(IInternalClusterClient client, string streamProvider, int testNum = 0, bool fullTest = true) { this.client = client; this.streamProviderName = streamProvider; this.logger = LogManager.GetLogger("SingleStreamTestRunner", LoggerType.Application); this.testNumber = testNum; this.runFullTest = fullTest; this.random = TestConstants.random; }
private static int GetGemBlessWorth(int itemId)//FOR ENCHANTMENT { var high = 1; var low = 0; if (itemId % 10 == 1) // refined { high = 59; low = 1; } else { switch (itemId) { /* unique ---------------------------------------------------unique-----------------------------*/ case 700012: high = 159; low = 100; break; // dragon case 700002: case 700062: case 700052: high = 109; low = 60; break; // phoenix, moon, violet case 700032: high = 129; low = 80; break; // rainbow case 700072: case 700042: case 700022: high = 89; low = 40; break; // tortoise, kylin, fury /* super -------------------------------------------------------super---------------------------*/ case 700013: high = 255; low = 200; break; // dragon case 700003: case 700073: case 700033: high = 229; low = 170; break; // phoenix, tortoise, rainbow case 700063: case 700053: high = 199; low = 140; break; // moon, violet case 700023: high = 149; low = 90; break; // fury case 700043: high = 119; low = 70; break; // kylin } } return(SafeRandom.Next(low, high)); }
private void InitializeRandomVelocities() { for (var index = 0; index < Parameters.Count; index++) { var parameter = Parameters[index]; var maxVelocity = _maxInitialVelocityFraction * (parameter.MaxValue - parameter.MinValue); // Permit positive or negative velocity. _velocities[index] = (SafeRandom.NextDouble() * maxVelocity * 2) - maxVelocity; } }
static GrainInfo() { rand = new SafeRandom(); }
public void RandomNotEqualTest() { SafeRandom rnd = new SafeRandom(); for (int loop = 0; loop < 1000000; loop++) { byte[] a = new byte[rnd.Next(1, 100)]; rnd.NextBytes(a); byte[] b = DeepCopy(a); b[rnd.Next(0, b.Length)]++; // Increment at a random index bool actual = ByteArrayEqualityComparer.AreEqual(a, b); Assert.IsFalse(actual); } }
public void RandomEqualTest() { SafeRandom rnd = new SafeRandom(); for (int loop = 0; loop < 100000; loop++) { byte[] a = new byte[rnd.Next(1, 100)]; rnd.NextBytes(a); byte[] b = DeepCopy(a); bool actual = ByteArrayEqualityComparer.AreEqual(a, b); Assert.IsTrue(actual); } }
SafeRandom rand; // The class used for generating the numbers #endregion Fields #region Constructors // Constructor. public Die() { // Initialise the SafeRandom class for die rolls // Don't worry about the seed as it'll use TickCount.Now for that rand = new SafeRandom(); }