//copied from HeuristicLab.Problems.Instances.DataAnalysis.ValueGenerator which is not public /// <summary> /// Generates uniformly distributed values between start and end (inclusive!) /// </summary> /// <param name="n">Number of values to generate.</param> /// <param name="start">The lower value (inclusive)</param> /// <param name="end">The upper value (inclusive)</param> /// <returns>An enumerable including n values in [start, end]</returns> public static IEnumerable <double> GenerateUniformDistributedValues(int n, double start, double end, FastRandom rand) { for (int i = 0; i < n; i++) { // we need to return a random value including end. // so we cannot use rand.NextDouble() as it returns a value strictly smaller than 1. double r = rand.NextUInt() / (double)uint.MaxValue; // r \in [0,1] yield return(r * (end - start) + start); } }
public PathGenerator(uint seed, GetHeight getHeight) { m_getHeight = getHeight; var fastRandom = new FastRandom(seed); m_cellNoise = new CellNoise2D(fastRandom.NextUInt()); m_sources = new Dictionary<uint, PathGraphNode>(); m_sinks = new Dictionary<uint, PathGraphNode>(); m_general = new Dictionary<uint, PathGraphNode>(); m_paths = new List<PathNodeList>(); }
private string GenerateKey1And2(FastRandom random) { // Changed random.Next(1, 13) to random.Next(2, 13) else max would be too large var spaces = random.Next(2, 13); var max = random.NextUInt() / spaces; var number = random.Next(0, (int)max + 1); var product = number * spaces; var key = product.ToString(); var amountOfCharacters = random.Next(1, 13); var amountFirstSeries = amountOfCharacters / 2; var amountSecondSeries = amountOfCharacters - amountFirstSeries; var firstSeries = new List <string>(); for (var i = 0; i < amountFirstSeries; i++) { // First unicode series var unicodeChar = Convert.ToString(random.Next(21, 48)); firstSeries.Add(unicodeChar); } var secondSeries = new List <string>(); for (var i = 0; i < amountSecondSeries; i++) { // Second unicode series var unicodeChar = Convert.ToString(random.Next(58, 126)); secondSeries.Add(unicodeChar); } firstSeries.ForEach(unicodeCharacter => key = InsertAtRandomLocation(key, unicodeCharacter, random)); secondSeries.ForEach(unicodeCharacter => key = InsertAtRandomLocation(key, unicodeCharacter, random)); // Insert random spaces for (var i = 0; i < spaces; i++) { var location = random.Next(1, key.Length - 1); key = key.Insert(location, SpaceCharacter); } return(key); }
/// <summary> /// Get the next sample value from the gaussian distribution. /// </summary> public double NextSample() { for (; ;) { // Select box at random. byte u = _rng.NextByte(); int i = u & 0x7F; double sign = ((u & 0x80) == 0) ? -1.0 : 1.0; // Generate uniform random value with range [0,0xffffffff]. uint u2 = _rng.NextUInt(); // Special case for the base segment. if (0 == i) { if (u2 < _xComp[0]) { // Generated x is within R0. return(u2 * __UIntToU * _A_Div_Y0 * sign); } // Generated x is in the tail of the distribution. return(SampleTail() * sign); } // All other segments. if (u2 < _xComp[i]) { // Generated x is within the rectangle. return(u2 * __UIntToU * _x[i] * sign); } // Generated x is outside of the rectangle. // Generate a random y coordinate and test if our (x,y) is within the distribution curve. // This execution path is relatively slow/expensive (makes a call to Math.Exp()) but relatively rarely executed, // although more often than the 'tail' path (above). double x = u2 * __UIntToU * _x[i]; if (_y[i - 1] + ((_y[i] - _y[i - 1]) * _rng.NextDouble()) < GaussianPdfDenorm(x)) { return(x * sign); } } }
public static uint UInt() { return(random.NextUInt()); }
private static async Task QueryJavaServerAsync(string hostname, ushort port, PingServerDelegate pingCallback, ServerStatusDelegate statusCallBack) { IPEndPoint endPoint = null; var sw = Stopwatch.StartNew(); string jsonResponse = null; try { var result = await ResolveHostnameAsync(hostname); if (!result.Success) { statusCallBack?.Invoke(new ServerQueryResponse(false, "multiplayer.status.cannot_resolve", new ServerQueryStatus() { Delay = sw.ElapsedMilliseconds, Success = false, EndPoint = null, Address = hostname, Port = port })); return; } bool waitingOnPing = true; using (TcpClient client = new TcpClient()) { await client.ConnectAsync(result.Result, port); endPoint = client.Client.RemoteEndPoint as IPEndPoint; if (client.Connected) { //conn = new NetConnection(Direction.ClientBound, client.Client); //conn.LogExceptions = false; using (var conn = new NetConnection(Direction.ClientBound, client.Client) { LogExceptions = true }) { long pingId = Rnd.NextUInt(); EventWaitHandle ar = new EventWaitHandle(false, EventResetMode.AutoReset); conn.OnPacketReceived += (sender, args) => { if (args.Packet is ResponsePacket responsePacket) { jsonResponse = responsePacket.ResponseMsg; ar.Set(); } else if (args.Packet is PingPacket pong) { if (pong.Payload == pingId) { waitingOnPing = false; pingCallback?.Invoke(new ServerPingResponse(true, sw.ElapsedMilliseconds)); } else { waitingOnPing = false; pingCallback?.Invoke(new ServerPingResponse(true, sw.ElapsedMilliseconds)); } } }; bool connectionClosed = false; conn.OnConnectionClosed += (sender, args) => { connectionClosed = true; ar.Set(); }; conn.Initialize(); conn.SendPacket(new HandshakePacket() { NextState = ConnectionState.Status, ServerAddress = hostname, ServerPort = port, ProtocolVersion = JavaProtocol.ProtocolVersion }); conn.ConnectionState = ConnectionState.Status; conn.SendPacket(new RequestPacket()); if (await WaitHandleHelpers.FromWaitHandle(ar, TimeSpan.FromMilliseconds(10000)) && !connectionClosed && jsonResponse != null) { long timeElapsed = sw.ElapsedMilliseconds; // Log.Debug($"Server json: " + jsonResponse); var query = ServerQuery.FromJson(jsonResponse); if (pingCallback != null) { conn.SendPacket(new PingPacket() { Payload = pingId, }); sw.Restart(); } var r = new ServerQueryStatus() { Delay = timeElapsed, Success = true, WaitingOnPing = pingCallback != null && !waitingOnPing, EndPoint = endPoint, Address = hostname, Port = port, Query = query }; statusCallBack?.Invoke(new ServerQueryResponse(true, r)); } else { statusCallBack?.Invoke(new ServerQueryResponse(false, "multiplayer.status.cannot_connect", new ServerQueryStatus() { EndPoint = endPoint, Delay = sw.ElapsedMilliseconds, Success = false, /* Motd = motd.MOTD, * ProtocolVersion = motd.ProtocolVersion, * MaxNumberOfPlayers = motd.MaxPlayers, * Version = motd.ClientVersion, * NumberOfPlayers = motd.Players,*/ Address = hostname, Port = port, WaitingOnPing = false })); } } } } } catch (Exception ex) { if (sw.IsRunning) { sw.Stop(); } Log.Error($"Could not get server query result! Exception: {ex.ToString()}"); string msg = ex.Message; if (ex is SocketException) { msg = $"multiplayer.status.cannot_connect"; } statusCallBack?.Invoke(new ServerQueryResponse(false, msg, new ServerQueryStatus() { Delay = sw.ElapsedMilliseconds, Success = false, EndPoint = endPoint, Address = hostname, Port = port })); } finally { //conn?.Stop(); //conn?.Dispose(); //conn?.Dispose(); // client?.Close(); } }
private static async Task QueryJavaServerAsync(ServerConnectionDetails connectionDetails, PingServerDelegate pingCallback, ServerStatusDelegate statusCallBack) { CancellationTokenSource cts = new CancellationTokenSource(10000); using TcpClient client = new TcpClient(); IPEndPoint endPoint = null; var sw = Stopwatch.StartNew(); string jsonResponse = null; try { bool waitingOnPing = true; await client.ConnectAsync(connectionDetails.EndPoint.Address, connectionDetails.EndPoint.Port); endPoint = client.Client.RemoteEndPoint as IPEndPoint; if (client.Connected) { //conn = new NetConnection(Direction.ClientBound, client.Client); //conn.LogExceptions = false; using (var conn = new NetConnection(PacketDirection.ClientBound, client.Client) { LogExceptions = true }) { long pingId = Rnd.NextUInt(); long pingResult = 0; EventWaitHandle ar = new EventWaitHandle(false, EventResetMode.AutoReset); conn.OnPacketReceived += (sender, args) => { if (args.Packet is ResponsePacket responsePacket) { jsonResponse = responsePacket.ResponseMsg; if (pingCallback != null) { conn.SendPacket(new PingPacket() { Payload = pingId, }); sw.Restart(); } ar.Set(); } else if (args.Packet is PingPacket pong) { pingResult = sw.ElapsedMilliseconds; if (pong.Payload == pingId) { waitingOnPing = false; pingCallback?.Invoke(new ServerPingResponse(true, sw.ElapsedMilliseconds)); } else { waitingOnPing = false; pingCallback?.Invoke(new ServerPingResponse(true, sw.ElapsedMilliseconds)); } ar.Set(); } }; bool connectionClosed = false; conn.OnConnectionClosed += (sender, args) => { if (!cts.IsCancellationRequested) { cts.Cancel(); } connectionClosed = true; ar.Set(); }; conn.Initialize(); conn.SendPacket(new HandshakePacket() { NextState = ConnectionState.Status, ServerAddress = connectionDetails.Hostname, ServerPort = (ushort)connectionDetails.EndPoint.Port, ProtocolVersion = JavaProtocol.ProtocolVersion }); conn.ConnectionState = ConnectionState.Status; conn.SendPacket(new RequestPacket()); if (await WaitHandleHelpers.FromWaitHandle(ar, TimeSpan.FromMilliseconds(10000), cts.Token) && !connectionClosed && jsonResponse != null) { long timeElapsed = sw.ElapsedMilliseconds; // Log.Debug($"Server json: " + jsonResponse); var query = ServerQuery.FromJson(jsonResponse); if (query.Version.Protocol == JavaProtocol.ProtocolVersion) { query.Version.Compatibility = CompatibilityResult.Compatible; } else if (query.Version.Protocol < JavaProtocol.ProtocolVersion) { query.Version.Compatibility = CompatibilityResult.OutdatedServer; } else if (query.Version.Protocol > JavaProtocol.ProtocolVersion) { query.Version.Compatibility = CompatibilityResult.OutdatedClient; } var r = new ServerQueryStatus() { Delay = timeElapsed, Success = true, WaitingOnPing = pingCallback != null && waitingOnPing, EndPoint = endPoint, Address = connectionDetails.Hostname, Port = (ushort)connectionDetails.EndPoint.Port, Query = query }; statusCallBack?.Invoke(new ServerQueryResponse(true, r)); if (waitingOnPing && pingCallback != null) { await WaitHandleHelpers.FromWaitHandle(ar, TimeSpan.FromSeconds(1000)); } } else { statusCallBack?.Invoke(new ServerQueryResponse(false, "multiplayer.status.cannot_connect", new ServerQueryStatus() { EndPoint = endPoint, Delay = sw.ElapsedMilliseconds, Success = false, /* Motd = motd.MOTD, * ProtocolVersion = motd.ProtocolVersion, * MaxNumberOfPlayers = motd.MaxPlayers, * Version = motd.ClientVersion, * NumberOfPlayers = motd.Players,*/ Address = connectionDetails.Hostname, Port = (ushort)connectionDetails.EndPoint.Port, WaitingOnPing = false })); } } } } catch (Exception ex) { cts.Cancel(); if (sw.IsRunning) { sw.Stop(); } // client?.Dispose(); string msg = ex.Message; if (ex is SocketException) { msg = $"multiplayer.status.cannot_connect"; } else { Log.Error(ex, $"Could not get server query result!"); } statusCallBack?.Invoke(new ServerQueryResponse(false, msg, new ServerQueryStatus() { Delay = sw.ElapsedMilliseconds, Success = false, EndPoint = endPoint, Address = connectionDetails.Hostname, Port = (ushort)connectionDetails.EndPoint.Port })); } finally { //conn?.Stop(); //conn?.Dispose(); //conn?.Dispose(); // client?.Close(); } }
public GlobalGenerator(uint seed) { _random = new FastRandom(seed); _sysRand = new System.Random((int)seed); _heightMap0 = new SimplexNoise2D(_random.NextUInt()); }