float.Parse(string)

Here are the examples of the csharp api float.Parse(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1033 Examples 7

19 Source : DialogueManagerController.cs
with MIT License
from 0xbustos

public int changeSpeed( int i )
        {
            i++;
            string speed = string.Empty;
            while (this.sentence[i] != ']')
            {
                speed += this.sentence[i];
                i++;
            }
            this.currentSpeed = float.Parse( speed );
            return i;
        }

19 Source : BeatmapConverter.cs
with MIT License
from 39M

static void Convert()
    {
        Debug.Log(string.Format("Source path: {0}", beatmapPath));

        // 每个目录代表一首歌,里面按字典序放置至多三个谱面,依次为 Easy, Normal, Hard
        string[] sourceDirectories = Directory.GetDirectories(beatmapPath);
        foreach (string directoryPath in sourceDirectories)
        {
            Music music = new Music();

            // 遍历单个目录下的所有 osu 文件,对每个文件创建一个 Beatmap 对象,加到 Music 对象里面
            string[] sourceFiles = Directory.GetFiles(directoryPath, "*.osu");
            int count = 0;
            foreach (string filepath in sourceFiles)
            {
                string[] lines = File.ReadAllLines(filepath);

                Beatmap beatmap = new Beatmap();
                music.beatmapList.Add(beatmap);

                #region Set Difficulty
                beatmap.difficultyName = difficultyNames[Mathf.Min(count, difficultyNames.Length - 1)];
                beatmap.difficultyDisplayColor = new SimpleColor(difficultyColors[Mathf.Min(count, difficultyNames.Length - 1)]);
                count++;
                #endregion

                #region Processing file line by line
                bool startProcessNotes = false;
                foreach (string line in lines)
                {
                    if (line.StartsWith("[HitObjects]"))
                    {
                        startProcessNotes = true;
                        continue;
                    }

                    if (!startProcessNotes)
                    {
                        // 处理谱面信息

                        int lastIndex = line.LastIndexOf(':');
                        if (lastIndex < 0)
                        {
                            // 如果不是有效信息行则跳过
                            continue;
                        }

                        string value = line.Substring(lastIndex + 1).Trim();

                        if (line.StartsWith("replacedle"))
                        {
                            music.replacedle = value;
                        }
                        else if (line.StartsWith("Artist"))
                        {
                            music.artist = value;
                        }
                        else if (line.StartsWith("AudioFilename"))
                        {
                            value = value.Remove(value.LastIndexOf('.'));
                            music.audioFilename = value;
                            music.bannerFilename = value;
                            music.soundEffectFilename = value;
                        }
                        else if (line.StartsWith("PreviewTime"))
                        {
                            music.previewTime = float.Parse(value) / 1000;
                        }
                        else if (line.StartsWith("Creator"))
                        {
                            beatmap.creator = value;
                        }
                        else if (line.StartsWith("Version"))
                        {
                            beatmap.version = value;
                        }
                    }
                    else
                    {
                        // 开始处理 HitObject

                        string[] noteInfo = line.Split(',');
                        int type = int.Parse(noteInfo[3]);

                        if ((type & 0x01) != 0)
                        {
                            // Circle
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Circle 相关的处理
                            });
                        }
                        else if ((type & 0x02) != 0)
                        {
                            // Slider
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Slider 相关的处理
                            });
                        }
                        else if ((type & 0x08) != 0)
                        {
                            // Spinner
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Spinner 相关的处理
                            });

                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[5]) / 1000,
                                // 其他 Spinner 相关的处理
                            });
                        }
                    }
                }
                #endregion
            }

            string targetPath = directoryPath + ".json";
            if (File.Exists(targetPath))
            {
                File.Delete(targetPath);
            }
            File.WriteAllText(targetPath, music.ToJson());

            Debug.Log(string.Format("Converted osu! beatmap\n[{0}]\nto json file\n[{1}]", directoryPath, targetPath));
        }

        Debug.Log(string.Format("All done, converted {0} files.", sourceDirectories.Length));
    }

19 Source : LUTPanelOptions.cs
with MIT License
from a1xd

private static (Vec2<float>[], int length) UserTextToPoints(string userText)
        {
            if (string.IsNullOrWhiteSpace(userText))
            {
                throw new ApplicationException("Text must be entered in text box to fill Look Up Table.");
            }

            Vec2<float>[] points = new Vec2<float>[AccelArgs.MaxLutPoints];

            var userTextSplit = userText.Trim().Trim(';').Split(';');
            int index = 0;
            float lastX = 0;

            int pointsCount = userTextSplit.Count();

            if (pointsCount < 2)
            {
                throw new ApplicationException("At least 2 points required");
            }

            if (pointsCount > AccelArgs.MaxLutPoints)
            {
                throw new ApplicationException($"Number of points exceeds max ({AccelArgs.MaxLutPoints})");
            }

            foreach(var pointEntry in userTextSplit)
            {
                var pointSplit = pointEntry.Trim().Split(',');

                if (pointSplit.Length != 2)
                {
                    throw new ApplicationException($"Point at index {index} is malformed. Expected format: x,y; Given: {pointEntry.Trim()}");
                }

                float x;
                float y;

                try
                {
                    x = float.Parse(pointSplit[0]);
                }
                catch (Exception ex)
                {
                    throw new ApplicationException($"X-value for point at index {index} is malformed. Expected: float. Given: {pointSplit[0]}", ex);
                }

                if (x <= 0)
                {
                    throw new ApplicationException($"X-value for point at index {index} is less than or equal to 0. Point (0,0) is implied and should not be specified in points text.");
                }

                if (x <= lastX)
                {
                    throw new ApplicationException($"X-value for point at index {index} is less than or equal to previous x-value. Value: {x} Previous: {lastX}");
                }

                lastX = x;

                try
                {
                    y = float.Parse(pointSplit[1]);
                }
                catch (Exception ex)
                {
                    throw new ApplicationException($"Y-value for point at index {index} is malformed. Expected: float. Given: {pointSplit[1]}", ex);
                }

                if (y <= 0)
                {
                    throw new ApplicationException($"Y-value for point at index {index} is less than or equal to 0. Value: {y}");
                }

                points[index] = new Vec2<float> { x = x, y = y };

                index++;
            }

            return (points, userTextSplit.Length);
        }

19 Source : SQLWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator

protected static float? TrimNegativeZero(float? input, int places = 6)
        {
            if (input == null)
                return null;

            var str = input.Value.ToString($"0.{new string('#', places)}");

            if (str == $"-0.{new string('#', places)}" || str == "-0")
                str = str.Substring(1, str.Length - 1);

            var ret = float.Parse(str);

            return ret;
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public void LightningStrike(Farmer who, MeleeWeapon weapon, Dictionary<string, string> parameters)
        {
            int minDamage = weapon.minDamage;
            int maxDamage = weapon.maxDamage;
            if (parameters.ContainsKey("damageMult"))
            {
                minDamage = (int)Math.Round(weapon.minDamage * float.Parse(parameters["damageMult"]));
                maxDamage = (int)Math.Round(weapon.maxDamage * float.Parse(parameters["damageMult"]));
            }
            else if (parameters.ContainsKey("minDamage") && parameters.ContainsKey("maxDamage"))
            {
                minDamage = int.Parse(parameters["minDamage"]);
                maxDamage = int.Parse(parameters["maxDamage"]);
            }

            int radius = int.Parse(parameters["radius"]);

            Vector2 playerLocation = who.position;
            GameLocation currentLocation = who.currentLocation;
            Farm.LightningStrikeEvent lightningEvent = new Farm.LightningStrikeEvent();
            lightningEvent.bigFlash = true;
            lightningEvent.createBolt = true;

            Vector2 offset = Vector2.Zero;
            if (parameters.ContainsKey("offsetX") && parameters.ContainsKey("offsetY"))
            {
                float x = float.Parse(parameters["offsetX"]);
                float y = float.Parse(parameters["offsetY"]);
                offset = TranslateVector(new Vector2(x, y), who.FacingDirection);
            }
            lightningEvent.boltPosition = playerLocation + new Vector2(32f, 32f) + offset;
            Game1.flashAlpha = (float)(0.5 + Game1.random.NextDouble());
            
            if(parameters.ContainsKey("sound"))
                Game1.playSound(parameters["sound"]);
            
            Utility.drawLightningBolt(lightningEvent.boltPosition, currentLocation);

            currentLocation.damageMonster(new Rectangle((int)Math.Round(playerLocation.X - radius), (int)Math.Round(playerLocation.Y - radius), radius * 2, radius * 2), minDamage, maxDamage, false, who);
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public void Explosion(Farmer user, MeleeWeapon weapon, Dictionary<string, string> parameters)
        {
            Vector2 tileLocation = user.getTileLocation();
            if(parameters.ContainsKey("tileOffsetX") && parameters.ContainsKey("tileOffsetY")) 
                tileLocation += TranslateVector(new Vector2(float.Parse(parameters["tileOffsetX"]), float.Parse(parameters["tileOffsetY"])), user.facingDirection);
            int radius = int.Parse(parameters["radius"]);
            
            int damage;
            if (parameters.ContainsKey("damageMult"))
            {
                damage = (int)Math.Round(Game1.random.Next(weapon.minDamage, weapon.maxDamage + 1) * float.Parse(parameters["damageMult"]));
            }
            else if (parameters.ContainsKey("minDamage") && parameters.ContainsKey("maxDamage"))
            {
                damage = Game1.random.Next(int.Parse(parameters["minDamage"]), int.Parse(parameters["maxDamage"]) + 1);

            }
            else
                damage = Game1.random.Next(weapon.minDamage, weapon.maxDamage + 1);

            user.currentLocation.explode(tileLocation, radius, user, false, damage);
        }

19 Source : NumericValidator.cs
with MIT License
from afucher

public bool Validate(string value)
        {
            try
            {
                float.Parse(value);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

19 Source : PercentageValidator.cs
with MIT License
from afucher

public bool Validate(string value)
        {
            try
            {
                if (value.EndsWith("%"))
                {
                    value = value.Remove(value.Length - 1);
                }
                var number = float.Parse(value);
                return number >= 0 && number <= 100;
            }
            catch (Exception)
            {
                return false;
            }
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

void ReadSettings()
        {
            currentlyReading = true;
            StreamReader sr = null;
            string checkVer = c_toolVer;

            try
            {
                using (sr = new StreamReader(settingsFile))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        try
                        {
                            int equalsign = line.IndexOf('=');
                            if (equalsign > 0)
                            {
                                string varName = line.Substring(0, equalsign);
                                string varValue = line.Substring(equalsign + 1);

                                if (varName == "ToolVersion" || varName == "GameVersion")
                                {
                                    checkVer = varValue;
                                }
                                else if (varName == "GameMode")
                                {
                                    rbSingleplayer.Checked = (varValue == "sp");
                                }
                                else if (varName == "Beep")
                                {
                                    chkBeep.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "FoV")
                                {
                                    SetFoV(float.Parse(varValue));
                                }
                                else if (varName == "FoVOffset" || varName == "RelativeFoVOffset")
                                {
                                    dword_ptr tmp = dword_ptr.Parse(varValue, NumberStyles.AllowHexSpecifier);
                                    if (tmp > (dword_ptr)gameMode.GetValue("c_baseAddr"))
                                        pFoV = (varName == "RelativeFoVOffset" ? (dword_ptr)gameMode.GetValue("c_baseAddr") : 0) + tmp;
                                }
                                else if (varName == "UpdateNotify")
                                {
                                    chkUpdate.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "DisableHotkeys")
                                {
                                    chkHotkeys.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "HotkeyIncrease")
                                {
                                    catchKeys[0] = (Keys)int.Parse(varValue);
                                    btnKeyZoomOut.Text = VirtualKeyName(catchKeys[0]);
                                }
                                else if (varName == "HotkeyDecrease")
                                {
                                    catchKeys[1] = (Keys)int.Parse(varValue);
                                    btnKeyZoomIn.Text = VirtualKeyName(catchKeys[1]);
                                }
                                else if (varName == "HotkeyReset")
                                {
                                    catchKeys[2] = (Keys)int.Parse(varValue);
                                    btnKeyReset.Text = VirtualKeyName(catchKeys[2]);
                                }
                            }
                        }
                        catch { }
                    }
                }
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }

            if (checkVer != c_toolVer)
                pFoV = (dword_ptr)gameMode.GetValue("c_pFoV");

            UpdateCheck();

            currentlyReading = false;
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

private void StringRead(string buffer, ref bool[] read, ref string checkVer)
        {
            if (!String.IsNullOrEmpty(buffer.Trim()))
            {
                if (buffer.StartsWith("ToolVersion=") || buffer.StartsWith("GameVersion="))
                {
                    checkVer = buffer.Substring(12);
                    read[0] = true;
                    //if (toolVer != c_toolVer) Checksum(settingsFile);
                }
                else if (buffer.StartsWith("Beep="))
                {
                    chkBeep.Checked = (buffer.Substring(5).ToLower() == "false") ? false : true;
                    read[1] = true;
                }
                else if (buffer.StartsWith("FoV="))
                {
                    SetFoV(float.Parse(buffer.Substring(4)));
                    read[2] = true;
                }
                else if (buffer.StartsWith("RelativeFoVOffset="))
                {
                    //MessageBox.Show((pFoV).ToString());

                    uint tmp = uint.Parse(buffer.Substring(18), NumberStyles.AllowHexSpecifier);
                    if (tmp > c_baseAddr && tmp < 0x40000000)
                        //MessageBox.Show(Increment(c_pFoV, -0x250000).ToString("x8"));
                        pFoV = c_baseAddr + tmp;
                    read[3] = true;

                    //MessageBox.Show((pFoV).ToString());
                }
                else if (buffer.StartsWith("FoVOffset="))
                {
                    uint tmp = uint.Parse(buffer.Substring(0), NumberStyles.AllowHexSpecifier);
                    if (tmp > c_baseAddr && tmp < 0x40000000)
                        pFoV = tmp;
                    read[3] = true;
                }
                else if (buffer.StartsWith("UpdatePopup=") || buffer.StartsWith("UpdateCheck="))
                {
                    chkUpdate.Checked = (buffer.Substring(12).ToLower() == "false") ? false : true;
                    read[4] = true;
                }
                else if (buffer.StartsWith("DisableHotkeys="))
                {
                    chkHotkeys.Checked = (buffer.Substring(15).ToLower() == "false") ? false : true;
                    read[5] = true;
                }
                else if (buffer.StartsWith("HotkeyIncrease="))
                {
                    catchKeys[0] = (Keys)int.Parse(buffer.Substring(15));
                    btnKeyZoomOut.Text = VirtualKeyName(catchKeys[0]);
                    read[6] = true;
                }
                else if (buffer.StartsWith("HotkeyDecrease="))
                {
                    catchKeys[1] = (Keys)int.Parse(buffer.Substring(15));
                    btnKeyZoomIn.Text = VirtualKeyName(catchKeys[1]);
                    read[7] = true;
                }
                else if (buffer.StartsWith("HotkeyReset="))
                {
                    catchKeys[2] = (Keys)int.Parse(buffer.Substring(12));
                    btnKeyReset.Text = VirtualKeyName(catchKeys[2]);
                    read[8] = true;
                }
                else throw new Exception("Invalid setting: " + buffer);
            }
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

void ReadSettings()
        {
            currentlyReading = true;
            StreamReader sr = null;
            string checkVer = c_toolVer;

            try
            {
                using (sr = new StreamReader(settingsFile))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        try
                        {
                            int equalsign = line.IndexOf('=');
                            if (equalsign > 0)
                            {
                                string varName = line.Substring(0, equalsign);
                                string varValue = line.Substring(equalsign + 1);

                                if (varName == "ToolVersion" || varName == "GameVersion")
                                {
                                    checkVer = varValue;
                                }
                                else if (varName == "GameMode")
                                {
                                    rbSingleplayer.Checked = (varValue == "sp");
                                }
                                else if (varName == "Beep")
                                {
                                    chkBeep.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "FoV")
                                {
                                    SetFoV(float.Parse(varValue));
                                }
                                else if (varName == "FoVOffset" || varName == "RelativeFoVOffset")
                                {
                                    int tmp = int.Parse(varValue, NumberStyles.AllowHexSpecifier);
                                    if (tmp > (int)gameMode.GetValue("c_baseAddr") && tmp < 0x40000000)
                                        pFoV = (varName == "RelativeFoVOffset" ? (int)gameMode.GetValue("c_baseAddr") : 0) + tmp;
                                }
                                else if (varName == "UpdatePopup" || varName == "UpdateCheck")
                                {
                                    chkUpdate.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "DisableHotkeys")
                                {
                                    chkHotkeys.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "HotkeyIncrease")
                                {
                                    catchKeys[0] = (Keys)int.Parse(varValue);
                                    btnKeyZoomOut.Text = VirtualKeyName(catchKeys[0]);
                                }
                                else if (varName == "HotkeyDecrease")
                                {
                                    catchKeys[1] = (Keys)int.Parse(varValue);
                                    btnKeyZoomIn.Text = VirtualKeyName(catchKeys[1]);
                                }
                                else if (varName == "HotkeyReset")
                                {
                                    catchKeys[2] = (Keys)int.Parse(varValue);
                                    btnKeyReset.Text = VirtualKeyName(catchKeys[2]);
                                }
                            }
                        }
                        catch { }
                    }
                }
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }

            if (checkVer != c_toolVer)
                pFoV = (int)gameMode.GetValue("c_pFoV");

            if (!requestSent)
            {
                try
                {
                    request = (HttpWebRequest)WebRequest.Create(c_checkURL);
                    request.BeginGetResponse(new AsyncCallback(UpdateResponse), null);
                    requestSent = true;
                }
                catch { }
            }

            currentlyReading = false;
        }

19 Source : Float32Data.cs
with GNU Affero General Public License v3.0
from aianlinb

public override void FromString(string value) {
			Value = float.Parse(value.TrimEnd('F'));
		}

19 Source : DefaultParamValueProcessors.cs
with MIT License
from aillieo

public float Load(string serializedValue)
        {
            return float.Parse(serializedValue);
        }

19 Source : Util.cs
with MIT License
from ajayyy

public static Vector3 Vector3FromString( string szString )
		{
			string[] szParseString = szString.Substring( 1, szString.Length - 1 ).Split( ',' );

			float x = float.Parse( szParseString[0] );
			float y = float.Parse( szParseString[1] );
			float z = float.Parse( szParseString[2] );

			Vector3 vReturn = new Vector3( x, y, z );

			return vReturn;
		}

19 Source : Util.cs
with MIT License
from ajayyy

public static Vector2 Vector2FromString( string szString )
		{
			string[] szParseString = szString.Substring( 1, szString.Length - 1 ).Split( ',' );

			float x = float.Parse( szParseString[0] );
			float y = float.Parse( szParseString[1] );

			Vector3 vReturn = new Vector2( x, y );

			return vReturn;
		}

19 Source : SteamVR_ExternalCamera.cs
with MIT License
from ajayyy

public void ReadConfig()
	{
		try
		{
			var mCam = new HmdMatrix34_t();
			var readCamMatrix = false;

			object c = config; // box
			var lines = System.IO.File.ReadAllLines(configPath);
			foreach (var line in lines)
			{
				var split = line.Split('=');
				if (split.Length == 2)
				{
					var key = split[0];
					if (key == "m")
					{
						var values = split[1].Split(',');
						if (values.Length == 12)
						{
							mCam.m0 = float.Parse(values[0]);
							mCam.m1 = float.Parse(values[1]);
							mCam.m2 = float.Parse(values[2]);
							mCam.m3 = float.Parse(values[3]);
							mCam.m4 = float.Parse(values[4]);
							mCam.m5 = float.Parse(values[5]);
							mCam.m6 = float.Parse(values[6]);
							mCam.m7 = float.Parse(values[7]);
							mCam.m8 = float.Parse(values[8]);
							mCam.m9 = float.Parse(values[9]);
							mCam.m10 = float.Parse(values[10]);
							mCam.m11 = float.Parse(values[11]);
							readCamMatrix = true;
						}
					}
#if !UNITY_METRO
					else if (key == "disableStandardreplacedets")
					{
						var field = c.GetType().GetField(key);
						if (field != null)
							field.SetValue(c, bool.Parse(split[1]));
					}
					else
					{
						var field = c.GetType().GetField(key);
						if (field != null)
							field.SetValue(c, float.Parse(split[1]));
					}
#endif
				}
			}
			config = (Config)c; //unbox

			// Convert calibrated camera matrix settings.
			if (readCamMatrix)
			{
				var t = new SteamVR_Utils.RigidTransform(mCam);
				config.x = t.pos.x;
				config.y = t.pos.y;
				config.z = t.pos.z;
				var angles = t.rot.eulerAngles;
				config.rx = angles.x;
				config.ry = angles.y;
				config.rz = angles.z;
			}
		}
		catch { }

		// Clear target so AttachToCamera gets called to pick up any changes.
		target = null;
#if !UNITY_METRO
		// Listen for changes.
		if (watcher == null)
		{
			var fi = new System.IO.FileInfo(configPath);
			watcher = new System.IO.FileSystemWatcher(fi.DirectoryName, fi.Name);
			watcher.NotifyFilter = System.IO.NotifyFilters.LastWrite;
			watcher.Changed += new System.IO.FileSystemEventHandler(OnChanged);
			watcher.EnableRaisingEvents = true;
		}
	}

19 Source : SteamVR_PlayArea.cs
with MIT License
from ajayyy

public static bool GetBounds( Size size, ref HmdQuad_t pRect )
	{
		if (size == Size.Calibrated)
		{
			var initOpenVR = (!SteamVR.active && !SteamVR.usingNativeSupport);
			if (initOpenVR)
			{
				var error = EVRInitError.None;
				OpenVR.Init(ref error, EVRApplicationType.VRApplication_Utility);
			}

			var chaperone = OpenVR.Chaperone;
			bool success = (chaperone != null) && chaperone.GetPlayAreaRect(ref pRect);
			if (!success)
				Debug.LogWarning("Failed to get Calibrated Play Area bounds!  Make sure you have tracking first, and that your space is calibrated.");

			if (initOpenVR)
				OpenVR.Shutdown();

			return success;
		}
		else
		{
			try
			{
				var str = size.ToString().Substring(1);
				var arr = str.Split(new char[] {'x'}, 2);

				// convert to half size in meters (from cm)
				var x = float.Parse(arr[0]) / 200;
				var z = float.Parse(arr[1]) / 200;

				pRect.vCorners0.v0 =  x;
				pRect.vCorners0.v1 =  0;
				pRect.vCorners0.v2 = -z;

				pRect.vCorners1.v0 = -x;
				pRect.vCorners1.v1 =  0;
				pRect.vCorners1.v2 = -z;

				pRect.vCorners2.v0 = -x;
				pRect.vCorners2.v1 =  0;
				pRect.vCorners2.v2 =  z;

				pRect.vCorners3.v0 =  x;
				pRect.vCorners3.v1 =  0;
				pRect.vCorners3.v2 =  z;

				return true;
			}
			catch {}
		}

		return false;
	}

19 Source : MagicPathParser.cs
with GNU General Public License v3.0
from AlanMorel

public static CoordF ParseCoordWithDuplicateDot(string input)
    {
        float[] floatArray = new float[input.Length];

        for (int i = 0; i < input.Split(",").Length; i++)
        {
            floatArray[i] = float.Parse(Regex.Match(input.Split(",")[i], "[+-]?([0-9]*[.])?[0-9]+").Value);
        }

        return CoordF.From(floatArray[0], floatArray[1], floatArray[2]);
    }

19 Source : Coord.cs
with GNU General Public License v3.0
from AlanMorel

public static CoordF Parse(string value)
    {
        string[] coord = value.Split(", ");
        return From(
            float.Parse(coord[0]),
            float.Parse(coord[1]),
            float.Parse(coord[2])
        );
    }

19 Source : Coord.cs
with GNU General Public License v3.0
from AlanMorel

public static CoordS Parse(string value)
    {
        string[] coord = value.Split(", ");
        return From(
            (short) float.Parse(coord[0]),
            (short) float.Parse(coord[1]),
            (short) float.Parse(coord[2])
        );
    }

19 Source : PacketStructureResolver.cs
with GNU General Public License v3.0
from AlanMorel

public static PacketStructureResolver Parse(string input)
    {
        string[] args = input.Split(" ", StringSplitOptions.RemoveEmptyEntries);

        // Parse opCode: 81 0081 0x81 0x0081
        ushort opCode;
        string firstArg = args[0];
        if (firstArg.ToLower().StartsWith("0x"))
        {
            opCode = Convert.ToUInt16(firstArg, 16);
        }
        else
        {
            if (firstArg.Length == 2)
            {
                opCode = firstArg.ToByte();
            }
            else if (firstArg.Length == 4)
            {
                // Reverse bytes
                byte[] bytes = firstArg.ToByteArray();
                Array.Reverse(bytes);

                opCode = BitConverter.ToUInt16(bytes);
            }
            else
            {
                Logger.Info("Invalid opcode.");
                return null;
            }
        }

        PacketStructureResolver resolver = new(opCode);
        DirectoryInfo dir = Directory.CreateDirectory($"{Paths.SOLUTION_DIR}/MapleServer2/PacketStructures");

        string filePath = $"{dir.FullName}/{resolver.OpCode:X4} - {resolver.PacketName}.txt";
        if (!File.Exists(filePath))
        {
            StreamWriter writer = File.CreateText(filePath);
            writer.WriteLine("# Generated by MapleServer2 PacketStructureResolver");
            IEnumerable<char> enumerable = opCode.ToString("D4").Reverse();
            writer.WriteLine($"PacketWriter pWriter = PacketWriter.Of(SendOp.{resolver.PacketName});");
            writer.Close();
            return resolver;
        }

        string[] fileLines = File.ReadAllLines(filePath);
        foreach (string line in fileLines)
        {
            if (string.IsNullOrEmpty(line) || line.StartsWith("#") || line.StartsWith("PacketWriter"))
            {
                continue;
            }

            string[] packetLine = line.Split("(");
            string type = packetLine[0][13..];
            string valuereplacedtring = packetLine[1].Split(")")[0];
            valuereplacedtring = string.IsNullOrEmpty(valuereplacedtring) ? "0" : valuereplacedtring;
            try
            {
                switch (type)
                {
                    case "Byte":
                        resolver.Packet.WriteByte(byte.Parse(valuereplacedtring));
                        break;
                    case "Short":
                        resolver.Packet.WriteShort(short.Parse(valuereplacedtring));
                        break;
                    case "Int":
                        resolver.Packet.WriteInt(int.Parse(valuereplacedtring));
                        break;
                    case "Long":
                        resolver.Packet.WriteLong(long.Parse(valuereplacedtring));
                        break;
                    case "Float":
                        resolver.Packet.WriteFloat(float.Parse(valuereplacedtring));
                        break;
                    case "UnicodeString":
                        resolver.Packet.WriteUnicodeString(valuereplacedtring.Replace("\"", ""));
                        break;
                    case "String":
                        resolver.Packet.WriteString(valuereplacedtring.Replace("\"", ""));
                        break;
                    default:
                        Logger.Info($"Unknown type: {type}");
                        break;
                }
            }
            catch
            {
                Logger.Info($"Couldn't parse value on function: {line}");
                return null;
            }
        }
        return resolver;
    }

19 Source : MixtureNodeView.cs
with MIT License
from alelievr

protected bool MaterialPropertiesGUI(Material material, bool fromInspector, bool autoLabelWidth = true)
		{
			if (material == null || material.shader == null)
				return false;

			if (autoLabelWidth)
			{
				EditorGUIUtility.wideMode = false;
				EditorGUIUtility.labelWidth = nodeTarget.nodeWidth / 3.0f;
			}

			MaterialProperty[] properties = MaterialEditor.GetMaterialProperties(new []{material});
			var portViews = GetPortViewsFromFieldName(nameof(ShaderNode.materialInputs));

			MaterialEditor  editor;
			if (!materialEditors.TryGetValue(material, out editor))
			{
				foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
				{
					var editorType = replacedembly.GetType("UnityEditor.MaterialEditor");
					if (editorType != null)
					{
						editor = materialEditors[material] = Editor.CreateEditor(material, editorType) as MaterialEditor;
						MixturePropertyDrawer.RegisterEditor(editor, this, owner.graph);
						break ;
					}
				}

			}

			bool propertiesChanged = CheckPropertyChanged(material, properties);

			foreach (var property in properties)
			{
				if ((property.flags & (MaterialProperty.PropFlags.HideInInspector | MaterialProperty.PropFlags.PerRendererData)) != 0)
					continue;

				int idx = material.shader.FindPropertyIndex(property.name);
				var propertyAttributes = material.shader.GetPropertyAttributes(idx);
				if (!fromInspector && propertyAttributes.Contains("ShowInInspector"))
					continue;

				// Retrieve the port view from the property name
				var portView = portViews?.FirstOrDefault(p => p.portData.identifier == property.name);
				if (portView != null && portView.connected)
					continue;
				
				// We only display textures that are excluded from the filteredOutProperties (i.e they are not exposed as ports)
				if (property.type == MaterialProperty.PropType.Texture && nodeTarget is ShaderNode sn)
				{
					if (!sn.GetFilterOutProperties().Contains(property.name))
						continue;
				}

				// TODO: cache to improve the performance of the UI
				var visibleIfAtribute = propertyAttributes.FirstOrDefault(s => s.Contains("VisibleIf"));
				if (!string.IsNullOrEmpty(visibleIfAtribute))
				{
					var match = visibleIfRegex.Match(visibleIfAtribute);
					if (match.Success)
					{
						string propertyName = match.Groups[1].Value;
						string[] accpectedValues = match.Groups[2].Value.Split(',');

						if (material.HasProperty(propertyName))
						{
							float f = material.GetFloat(propertyName);

							bool show = false;
							foreach (var value in accpectedValues)
							{
								float f2 = float.Parse(value);

								if (f == f2)
									show = true;
							}

							if (!show)
								continue;
						}
						else
							continue;
					}
				}

				// Hide all the properties that are not supported in the current dimension
				var currentDimension = nodeTarget.settings.GetResolvedTextureDimension(owner.graph);
				string displayName = property.displayName;

				bool is2D = displayName.Contains(MixtureUtils.texture2DPrefix);
				bool is3D = displayName.Contains(MixtureUtils.texture3DPrefix);
				bool isCube = displayName.Contains(MixtureUtils.textureCubePrefix);

				if (is2D || is3D || isCube)
				{
					if (currentDimension == TextureDimension.Tex2D && !is2D)
						continue;
					if (currentDimension == TextureDimension.Tex3D && !is3D)
						continue;
					if (currentDimension == TextureDimension.Cube && !isCube)
						continue;
					displayName = Regex.Replace(displayName, @"_2D|_3D|_Cube", "", RegexOptions.IgnoreCase);
				}

				// In ShaderGraph we can put [Inspector] in the name of the property to show it only in the inspector and not in the node
				if (property.displayName.ToLower().Contains("[inspector]"))
				{
					if (fromInspector)
						displayName = Regex.Replace(property.displayName, @"\[inspector\]\s*", "", RegexOptions.IgnoreCase);
					else
						continue;
				}

				float h = editor.GetPropertyHeight(property, displayName);

				// We always display textures on a single line without scale or offset because they are not supported
				if (property.type == MaterialProperty.PropType.Texture)
					h = EditorGUIUtility.singleLineHeight;

				Rect r = EditorGUILayout.GetControlRect(true, h);
				if (property.name.Contains("Vector2"))
					property.vectorValue = (Vector4)EditorGUI.Vector2Field(r, displayName, (Vector2)property.vectorValue);
				else if (property.name.Contains("Vector3"))
					property.vectorValue = (Vector4)EditorGUI.Vector3Field(r, displayName, (Vector3)property.vectorValue);
				else if (property.type == MaterialProperty.PropType.Range)
				{
					if (material.shader.GetPropertyAttributes(idx).Any(a => a.Contains("IntRange")))
						property.floatValue = EditorGUI.IntSlider(r, displayName, (int)property.floatValue, (int)property.rangeLimits.x, (int)property.rangeLimits.y);
					else
						property.floatValue = EditorGUI.Slider(r, displayName, property.floatValue, property.rangeLimits.x, property.rangeLimits.y);
				}
				else if (property.type == MaterialProperty.PropType.Texture)
					property.textureValue = (Texture)EditorGUI.ObjectField(r, displayName, property.textureValue, typeof(Texture), false);
				else
					editor.ShaderProperty(r, property, displayName);
			}

			return propertiesChanged;
		}

19 Source : TFHCFlipBookUVAnimation.cs
with MIT License
from alexismorin

public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
		{
			// OPTIMIZATION NOTES
			//
			//  round( fmod( x, y ) ) can be replaced with a faster
			//  floor( frac( x / y ) * y + 0.5 ) => div can be muls with 1/y, almost always static/constant
			//
			if( m_outputPorts[ 0 ].IsLocalValue( dataCollector.PortCategory ) )
				return GetOutputVectorItem( 0, outputId, m_outputPorts[ 0 ].LocalValue( dataCollector.PortCategory ) );

			string uv = m_inputPorts[ 0 ].GeneratePortInstructions( ref dataCollector );
			string columns = m_inputPorts[ 1 ].GeneratePortInstructions( ref dataCollector );

			if ( !m_inputPorts[ 1 ].IsConnected )
				columns = ( float.Parse( columns ) == 0f ? "1" : columns );

			string rows = m_inputPorts[ 2 ].GeneratePortInstructions( ref dataCollector );
			if ( !m_inputPorts[ 2 ].IsConnected )
				rows = ( float.Parse( rows ) == 0f ? "1" : rows );

			string speed = m_inputPorts[ 3 ].GeneratePortInstructions( ref dataCollector );
			string startframe = m_inputPorts[ 4 ].GeneratePortInstructions( ref dataCollector );
            string timer = m_inputPorts[ 5 ].IsConnected ? m_inputPorts[ 5 ].GeneratePortInstructions( ref dataCollector ) : "_Time[ 1 ]";

			string vcomment1 = "// *** BEGIN Flipbook UV Animation vars ***";
			string vcomment2 = "// Total tiles of Flipbook Texture";
			string vtotaltiles = "float fbtotaltiles" + OutputId + " = " + columns + " * " + rows + ";";
			string vcomment3 = "// Offsets for cols and rows of Flipbook Texture";
			string vcolsoffset = "float fbcolsoffset" + OutputId + " = 1.0f / " + columns + ";";
			string vrowssoffset = "float fbrowsoffset" + OutputId + " = 1.0f / " + rows + ";";
			string vcomment4 = "// Speed of animation";

            string vspeed = string.Format(  "float fbspeed{0} = {1} * {2};", OutputId,timer,speed);
			string vcomment5 = "// UV Tiling (col and row offset)";
			string vtiling = "float2 fbtiling" + OutputId + " = float2(fbcolsoffset" + OutputId + ", fbrowsoffset" + OutputId + ");";
			string vcomment6 = "// UV Offset - calculate current tile linear index, and convert it to (X * coloffset, Y * rowoffset)";
			string vcomment7 = "// Calculate current tile linear index";
			//float fbcurrenttileindex1 = round( fmod( fbspeed1 + _Float0, fbtotaltiles1 ) );
			string vcurrenttileindex = "float fbcurrenttileindex" + OutputId + " = round( fmod( fbspeed" + OutputId + " + " + startframe + ", fbtotaltiles" + OutputId + ") );";
			string  vcurrenttileindex1 = "fbcurrenttileindex" + OutputId + " += ( fbcurrenttileindex" + OutputId + " < 0) ? fbtotaltiles" + OutputId + " : 0;";
			//fbcurrenttileindex1 += ( fbcurrenttileindex1 < 0 ) ? fbtotaltiles1 : 0;
			//string vcurrenttileindex = "int fbcurrenttileindex" + m_uniqueId + " = (int)fmod( fbspeed" + m_uniqueId + ", fbtotaltiles" + m_uniqueId + ") + " + startframe + ";";
			string vcomment8 = "// Obtain Offset X coordinate from current tile linear index";

			//float fblinearindextox1 = round( fmod( fbcurrenttileindex1, 5.0 ) );
			//string voffsetx1 = "int fblinearindextox" + m_uniqueId + " = fbcurrenttileindex" + m_uniqueId + " % (int)" + columns + ";";
			string voffsetx1 = "float fblinearindextox" + OutputId + " = round ( fmod ( fbcurrenttileindex" + OutputId + ", " + columns + " ) );";
			string vcomment9 = String.Empty;
			string voffsetx2 = String.Empty;
			if ( m_negativeSpeedBehavior != 0 )
			{
				vcomment9 = "// Reverse X animation if speed is negative";
				voffsetx2 = "fblinearindextox" + OutputId + " = (" + speed + " > 0 ? fblinearindextox" + OutputId + " : (int)" + columns + " - fblinearindextox" + OutputId + ");";
			}
			string vcomment10 = "// Multiply Offset X by coloffset";
			string voffsetx3 = "float fboffsetx" + OutputId + " = fblinearindextox" + OutputId + " * fbcolsoffset" + OutputId + ";";
			string vcomment11 = "// Obtain Offset Y coordinate from current tile linear index";
			//float fblinearindextoy1 = round( fmod( ( fbcurrenttileindex1 - fblinearindextox1 ) / 5.0, 5.0 ) );
			string voffsety1 = "float fblinearindextoy" + OutputId + " = round( fmod( ( fbcurrenttileindex" + OutputId + " - fblinearindextox" + OutputId + " ) / " + columns + ", " + rows + " ) );";
			//string voffsety1 = "int fblinearindextoy" + m_uniqueId + " = (int)( ( fbcurrenttileindex" + m_uniqueId + " - fblinearindextox" + m_uniqueId + " ) / " + columns + " ) % (int)" + rows + ";";
			//string vcomment10 = "// Reverse Y to get from Top to Bottom";
			//string voffsety2 = "fblinearindextoy" + m_uniqueId + " = (int)" + rows + " - fblinearindextoy" + m_uniqueId + ";";
			string vcomment12 = String.Empty;
			string voffsety2 = String.Empty;
			if ( m_negativeSpeedBehavior == 0 )
			{
				if ( m_selectedTextureVerticalDirection == 0 )
				{
					vcomment12 = "// Reverse Y to get tiles from Top to Bottom";
					voffsety2 = "fblinearindextoy" + OutputId + " = (int)(" + rows + "-1) - fblinearindextoy" + OutputId + ";";
				}
			}
			else
			{
				string reverseanimationoperator = String.Empty;
				if ( m_selectedTextureVerticalDirection == 0 )
				{
					vcomment12 = "// Reverse Y to get tiles from Top to Bottom and Reverse Y animation if speed is negative";
					reverseanimationoperator = " < ";
				}
				else
				{
					vcomment12 = "// Reverse Y animation if speed is negative";
					reverseanimationoperator = " > ";
				}
				voffsety2 = "fblinearindextoy" + OutputId + " = (" + speed + reverseanimationoperator + " 0 ? fblinearindextoy" + OutputId + " : (int)" + rows + " - fblinearindextoy" + OutputId + ");";
			}
			string vcomment13 = "// Multiply Offset Y by rowoffset";
			string voffsety3 = "float fboffsety" + OutputId + " = fblinearindextoy" + OutputId + " * fbrowsoffset" + OutputId + ";";
			string vcomment14 = "// UV Offset";
			string voffset = "float2 fboffset" + OutputId + " = float2(fboffsetx" + OutputId + ", fboffsety" + OutputId + ");";
			//string voffset = "float2 fboffset" + m_uniqueId + " = float2( ( ( (int)fmod( fbspeed" + m_uniqueId + " , fbtotaltiles" +  m_uniqueId + ") % (int)" + columns + " ) * fbcolsoffset" + m_OutputId + " ) , ( ( (int)" + rows + " - ( (int)( ( (int)fmod( fbspeed" + m_uniqueId + " , fbtotaltiles" + m_uniqueId + " ) - ( (int)fmod( fbspeed" + m_uniqueId + " , fbtotaltiles" + m_uniqueId + " ) % (int)" + columns + " ) ) / " + columns + " ) % (int)" + rows + " ) ) * fbrowsoffset" + m_uniqueId + " ) );";
			string vcomment15 = "// Flipbook UV";
			string vfbuv = "half2 fbuv" + OutputId + " = " + uv + " * fbtiling" + OutputId + " + fboffset" + OutputId + ";";
			string vcomment16 = "// *** END Flipbook UV Animation vars ***";
			string result = "fbuv" + OutputId;

			dataCollector.AddLocalVariable( UniqueId, vcomment1 );
			dataCollector.AddLocalVariable( UniqueId, vcomment2 );
			dataCollector.AddLocalVariable( UniqueId, vtotaltiles );
			dataCollector.AddLocalVariable( UniqueId, vcomment3 );
			dataCollector.AddLocalVariable( UniqueId, vcolsoffset );
			dataCollector.AddLocalVariable( UniqueId, vrowssoffset );
			dataCollector.AddLocalVariable( UniqueId, vcomment4 );
			dataCollector.AddLocalVariable( UniqueId, vspeed );
			dataCollector.AddLocalVariable( UniqueId, vcomment5 );
			dataCollector.AddLocalVariable( UniqueId, vtiling );
			dataCollector.AddLocalVariable( UniqueId, vcomment6 );
			dataCollector.AddLocalVariable( UniqueId, vcomment7 );
			dataCollector.AddLocalVariable( UniqueId, vcurrenttileindex );
			dataCollector.AddLocalVariable( UniqueId, vcurrenttileindex1 );
			dataCollector.AddLocalVariable( UniqueId, vcomment8 );
			dataCollector.AddLocalVariable( UniqueId, voffsetx1 );
			if ( m_negativeSpeedBehavior != 0 )
			{
				dataCollector.AddLocalVariable( UniqueId, vcomment9 );
				dataCollector.AddLocalVariable( UniqueId, voffsetx2 );
			}
			dataCollector.AddLocalVariable( UniqueId, vcomment10 );
			dataCollector.AddLocalVariable( UniqueId, voffsetx3 );
			dataCollector.AddLocalVariable( UniqueId, vcomment11 );
			dataCollector.AddLocalVariable( UniqueId, voffsety1 );
			if ( m_selectedTextureVerticalDirection == 0 || m_negativeSpeedBehavior != 0 )
			{
				dataCollector.AddLocalVariable( UniqueId, vcomment12 );
				dataCollector.AddLocalVariable( UniqueId, voffsety2 );
			}
			dataCollector.AddLocalVariable( UniqueId, vcomment13 );
			dataCollector.AddLocalVariable( UniqueId, voffsety3 );
			dataCollector.AddLocalVariable( UniqueId, vcomment14 );
			dataCollector.AddLocalVariable( UniqueId, voffset );
			dataCollector.AddLocalVariable( UniqueId, vcomment15 );
			dataCollector.AddLocalVariable( UniqueId, vfbuv );
			dataCollector.AddLocalVariable( UniqueId, vcomment16 );

			m_outputPorts[ 0 ].SetLocalValue( result, dataCollector.PortCategory );

			return GetOutputVectorItem( 0, outputId, result );

		}

19 Source : TFHCFlipBookUVAnimation.cs
with GNU General Public License v3.0
from alexismorin

public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
		{
			// OPTIMIZATION NOTES
			//
			//  round( fmod( x, y ) ) can be replaced with a faster
			//  floor( frac( x / y ) * y + 0.5 ) => div can be muls with 1/y, almost always static/constant
			//

			string uv = m_inputPorts[ 0 ].GeneratePortInstructions( ref dataCollector );
			string columns = m_inputPorts[ 1 ].GeneratePortInstructions( ref dataCollector );
			if ( !m_inputPorts[ 1 ].IsConnected )
				columns = ( float.Parse( columns ) == 0f ? "1" : columns );

			string rows = m_inputPorts[ 2 ].GeneratePortInstructions( ref dataCollector );
			if ( !m_inputPorts[ 2 ].IsConnected )
				rows = ( float.Parse( rows ) == 0f ? "1" : rows );


			string speed = m_inputPorts[ 3 ].GeneratePortInstructions( ref dataCollector );
			string startframe = m_inputPorts[ 4 ].GeneratePortInstructions( ref dataCollector );

			string vcomment1 = "// *** BEGIN Flipbook UV Animation vars ***";
			string vcomment2 = "// Total tiles of Flipbook Texture";
			string vtotaltiles = "float fbtotaltiles" + OutputId + " = " + columns + " * " + rows + ";";
			string vcomment3 = "// Offsets for cols and rows of Flipbook Texture";
			string vcolsoffset = "float fbcolsoffset" + OutputId + " = 1.0f / " + columns + ";";
			string vrowssoffset = "float fbrowsoffset" + OutputId + " = 1.0f / " + rows + ";";
			string vcomment4 = "// Speed of animation";
            string timer = m_inputPorts[ 5 ].IsConnected ? m_inputPorts[ 5 ].GeneratePortInstructions( ref dataCollector ) : "_Time[ 1 ]";

            string vspeed = string.Format(  "float fbspeed{0} = {1} * {2};", OutputId,timer,speed);
			string vcomment5 = "// UV Tiling (col and row offset)";
			string vtiling = "float2 fbtiling" + OutputId + " = float2(fbcolsoffset" + OutputId + ", fbrowsoffset" + OutputId + ");";
			string vcomment6 = "// UV Offset - calculate current tile linear index, and convert it to (X * coloffset, Y * rowoffset)";
			string vcomment7 = "// Calculate current tile linear index";
			//float fbcurrenttileindex1 = round( fmod( fbspeed1 + _Float0, fbtotaltiles1 ) );
			string vcurrenttileindex = "float fbcurrenttileindex" + OutputId + " = round( fmod( fbspeed" + OutputId + " + " + startframe + ", fbtotaltiles" + OutputId + ") );";
			string  vcurrenttileindex1 = "fbcurrenttileindex" + OutputId + " += ( fbcurrenttileindex" + OutputId + " < 0) ? fbtotaltiles" + OutputId + " : 0;";
			//fbcurrenttileindex1 += ( fbcurrenttileindex1 < 0 ) ? fbtotaltiles1 : 0;
			//string vcurrenttileindex = "int fbcurrenttileindex" + m_uniqueId + " = (int)fmod( fbspeed" + m_uniqueId + ", fbtotaltiles" + m_uniqueId + ") + " + startframe + ";";
			string vcomment8 = "// Obtain Offset X coordinate from current tile linear index";

			//float fblinearindextox1 = round( fmod( fbcurrenttileindex1, 5.0 ) );
			//string voffsetx1 = "int fblinearindextox" + m_uniqueId + " = fbcurrenttileindex" + m_uniqueId + " % (int)" + columns + ";";
			string voffsetx1 = "float fblinearindextox" + OutputId + " = round ( fmod ( fbcurrenttileindex" + OutputId + ", " + columns + " ) );";
			string vcomment9 = String.Empty;
			string voffsetx2 = String.Empty;
			if ( m_negativeSpeedBehavior != 0 )
			{
				vcomment9 = "// Reverse X animation if speed is negative";
				voffsetx2 = "fblinearindextox" + OutputId + " = (" + speed + " > 0 ? fblinearindextox" + OutputId + " : (int)" + columns + " - fblinearindextox" + OutputId + ");";
			}
			string vcomment10 = "// Multiply Offset X by coloffset";
			string voffsetx3 = "float fboffsetx" + OutputId + " = fblinearindextox" + OutputId + " * fbcolsoffset" + OutputId + ";";
			string vcomment11 = "// Obtain Offset Y coordinate from current tile linear index";
			//float fblinearindextoy1 = round( fmod( ( fbcurrenttileindex1 - fblinearindextox1 ) / 5.0, 5.0 ) );
			string voffsety1 = "float fblinearindextoy" + OutputId + " = round( fmod( ( fbcurrenttileindex" + OutputId + " - fblinearindextox" + OutputId + " ) / " + columns + ", " + rows + " ) );";
			//string voffsety1 = "int fblinearindextoy" + m_uniqueId + " = (int)( ( fbcurrenttileindex" + m_uniqueId + " - fblinearindextox" + m_uniqueId + " ) / " + columns + " ) % (int)" + rows + ";";
			//string vcomment10 = "// Reverse Y to get from Top to Bottom";
			//string voffsety2 = "fblinearindextoy" + m_uniqueId + " = (int)" + rows + " - fblinearindextoy" + m_uniqueId + ";";
			string vcomment12 = String.Empty;
			string voffsety2 = String.Empty;
			if ( m_negativeSpeedBehavior == 0 )
			{
				if ( m_selectedTextureVerticalDirection == 0 )
				{
					vcomment12 = "// Reverse Y to get tiles from Top to Bottom";
					voffsety2 = "fblinearindextoy" + OutputId + " = (int)(" + rows + "-1) - fblinearindextoy" + OutputId + ";";
				}
			}
			else
			{
				string reverseanimationoperator = String.Empty;
				if ( m_selectedTextureVerticalDirection == 0 )
				{
					vcomment12 = "// Reverse Y to get tiles from Top to Bottom and Reverse Y animation if speed is negative";
					reverseanimationoperator = " < ";
				}
				else
				{
					vcomment12 = "// Reverse Y animation if speed is negative";
					reverseanimationoperator = " > ";
				}
				voffsety2 = "fblinearindextoy" + OutputId + " = (" + speed + reverseanimationoperator + " 0 ? fblinearindextoy" + OutputId + " : (int)" + rows + " - fblinearindextoy" + OutputId + ");";
			}
			string vcomment13 = "// Multiply Offset Y by rowoffset";
			string voffsety3 = "float fboffsety" + OutputId + " = fblinearindextoy" + OutputId + " * fbrowsoffset" + OutputId + ";";
			string vcomment14 = "// UV Offset";
			string voffset = "float2 fboffset" + OutputId + " = float2(fboffsetx" + OutputId + ", fboffsety" + OutputId + ");";
			//string voffset = "float2 fboffset" + m_uniqueId + " = float2( ( ( (int)fmod( fbspeed" + m_uniqueId + " , fbtotaltiles" +  m_uniqueId + ") % (int)" + columns + " ) * fbcolsoffset" + m_OutputId + " ) , ( ( (int)" + rows + " - ( (int)( ( (int)fmod( fbspeed" + m_uniqueId + " , fbtotaltiles" + m_uniqueId + " ) - ( (int)fmod( fbspeed" + m_uniqueId + " , fbtotaltiles" + m_uniqueId + " ) % (int)" + columns + " ) ) / " + columns + " ) % (int)" + rows + " ) ) * fbrowsoffset" + m_uniqueId + " ) );";
			string vcomment15 = "// Flipbook UV";
			string vfbuv = "half2 fbuv" + OutputId + " = " + uv + " * fbtiling" + OutputId + " + fboffset" + OutputId + ";";
			string vcomment16 = "// *** END Flipbook UV Animation vars ***";
			string result = "fbuv" + OutputId;

			dataCollector.AddToLocalVariables( UniqueId, vcomment1 );
			dataCollector.AddToLocalVariables( UniqueId, vcomment2 );
			dataCollector.AddToLocalVariables( UniqueId, vtotaltiles );
			dataCollector.AddToLocalVariables( UniqueId, vcomment3 );
			dataCollector.AddToLocalVariables( UniqueId, vcolsoffset );
			dataCollector.AddToLocalVariables( UniqueId, vrowssoffset );
			dataCollector.AddToLocalVariables( UniqueId, vcomment4 );
			dataCollector.AddToLocalVariables( UniqueId, vspeed );
			dataCollector.AddToLocalVariables( UniqueId, vcomment5 );
			dataCollector.AddToLocalVariables( UniqueId, vtiling );
			dataCollector.AddToLocalVariables( UniqueId, vcomment6 );
			dataCollector.AddToLocalVariables( UniqueId, vcomment7 );
			dataCollector.AddToLocalVariables( UniqueId, vcurrenttileindex );
			dataCollector.AddToLocalVariables( UniqueId, vcurrenttileindex1 );
			dataCollector.AddToLocalVariables( UniqueId, vcomment8 );
			dataCollector.AddToLocalVariables( UniqueId, voffsetx1 );
			if ( m_negativeSpeedBehavior != 0 )
			{
				dataCollector.AddToLocalVariables( UniqueId, vcomment9 );
				dataCollector.AddToLocalVariables( UniqueId, voffsetx2 );
			}
			dataCollector.AddToLocalVariables( UniqueId, vcomment10 );
			dataCollector.AddToLocalVariables( UniqueId, voffsetx3 );
			dataCollector.AddToLocalVariables( UniqueId, vcomment11 );
			dataCollector.AddToLocalVariables( UniqueId, voffsety1 );
			if ( m_selectedTextureVerticalDirection == 0 || m_negativeSpeedBehavior != 0 )
			{
				dataCollector.AddToLocalVariables( UniqueId, vcomment12 );
				dataCollector.AddToLocalVariables( UniqueId, voffsety2 );
			}
			dataCollector.AddToLocalVariables( UniqueId, vcomment13 );
			dataCollector.AddToLocalVariables( UniqueId, voffsety3 );
			dataCollector.AddToLocalVariables( UniqueId, vcomment14 );
			dataCollector.AddToLocalVariables( UniqueId, voffset );
			dataCollector.AddToLocalVariables( UniqueId, vcomment15 );
			dataCollector.AddToLocalVariables( UniqueId, vfbuv );
			dataCollector.AddToLocalVariables( UniqueId, vcomment16 );

			return GetOutputVectorItem( 0, outputId, result );

		}

19 Source : Extensions.cs
with Apache License 2.0
from Algoryx

public static Vector3 ParseVector3( this string[] strs, int startIndex )
    {
      if ( startIndex + 2 >= strs.Length )
        throw new IndexOutOfRangeException( $"Unable to parse Vector3: End index {startIndex + 2} >= length " +
                                            $"of string array with {strs.Length} elements." );
      return new Vector3( float.Parse( strs[ startIndex + 0 ] ),
                          float.Parse( strs[ startIndex + 1 ] ),
                          float.Parse( strs[ startIndex + 2 ] ) );
    }

19 Source : StanfordNLPClassifier.cs
with MIT License
from allisterb

public override StageResult Train(Dictionary<string, object> options = null)
        {
            ClreplacedifierPropsFile = CreatePropsFile(ClreplacedifierProperties);
            if (!ClreplacedifierPropsFile.Exists)
            {
                Error("Could not find clreplacedifier props file {0}.", ClreplacedifierPropsFile.FullName);
            }
            else
            {
                Debug("Using clreplacedifier props file {0}.", ClreplacedifierPropsFile.FullName);
            }

            javaCommand = new JavaCommand(JavaHome, ClreplacedPath, "edu.stanford.nlp.clreplacedify.ColumnDataClreplacedifier", "-mx16000m", 
                "-trainFile", TrainingFile.FullName, "-testFile", TestFile.FullName, "-prop", ClreplacedifierPropsFile.FullName);
            PrintCommand(javaCommand);
            Task c = javaCommand.Run();
            if (!CheckCommandStartedAndReport(javaCommand))
            {
                return StageResult.FAILED;
            }
 
            ClreplacedifierOutput = new List<string>();

            foreach (string s in javaCommand.GetOutputAndErrorLines())
            {
                if (!BuiltClreplacedifier && s.StartsWith("Built this clreplacedifier"))
                {
                    BuiltClreplacedifier = true;
                    
                    Match m = builtClreplacedifierRegex.Match(s);
                    if (m.Success)
                    {
                        ClreplacedifierType = m.Groups[1].Value;
                        NumberofFeatures = Int32.Parse(m.Groups[2].Value);
                        NumberofClreplacedes = Int32.Parse(m.Groups[3].Value);
                        NumberofParameters = Int32.Parse(m.Groups[4].Value);
                        Info("Built clreplacedifier {0} with {1} features, {2} clreplacedes and {3} parameters.", ClreplacedifierType, NumberofFeatures, NumberofClreplacedes, NumberofParameters);
                    }
                }
                else if (ClreplacedifierType.IsEmpty() && s.StartsWith("QNMinimizer called on double function"))
                {
                    ClreplacedifierType = "BinaryLogisticClreplacedifier";
                    Match m = binaryClreplacediferQNN.Match(s);
                    if (m.Success)
                    {
                        NumberofFeatures = Int32.Parse(m.Groups[1].Value);
                        Info("Built clreplacedifier {0} with {1} features.", ClreplacedifierType, NumberofFeatures);
                    }
                    else
                    {
                        Error("Could not parse BinaryLogisticClreplacedifier output: {0}.", s);
                    }
                }

            
                else if (!ReadTrainingDataset && s.StartsWith("Reading dataset from {0} ... done".F(TrainingFile.FullName)))
                {
                    ReadTrainingDataset = true;
                    Match m = readDataSetRegex.Match(s);
                    if (m.Success)
                    {
                        TrainingDataSereplacedems = Int32.Parse(m.Groups[3].Value);
                        Info("{0} items in training dataset read in {1} s.", TrainingDataSereplacedems, m.Groups[2].Value);
                    }
                    else
                    {
                        Error("Could not parse clreplacedifier output line: {0}.", s);
                        return StageResult.FAILED;
                    }
                }

                else if (!ReadTestDataset && s.StartsWith("Reading dataset from {0} ... done".F(TestFile.FullName)))
                {
                    ReadTestDataset = true;
                    Match m = readDataSetRegex.Match(s);
                    if (m.Success)
                    {
                        TestDataSereplacedems = Int32.Parse(m.Groups[3].Value);
                        Info("{0} items in test dataset read in {1} s.", TestDataSereplacedems, m.Groups[2].Value);
                    }
                    else
                    {
                        Error("Could not parse clreplacedifier output line: {0}.", s);
                        return StageResult.FAILED;
                    }
                }

                else if (!KFoldCrossValidation && s.StartsWith("### Fold"))
                {
                    KFoldCrossValidation = true;
                    Match m = kFold.Match(s);
                    if (m.Success)
                    {
                        if (!KFoldIndex.HasValue)
                        {
                            MicroAveragedF1Folds = new float[10];
                            MacroAveragedF1Folds = new float[10];
                        }
                        KFoldIndex = Int32.Parse(m.Groups[1].Value);
                    }
                }

                else if (KFoldCrossValidation && s.StartsWith("### Fold"))
                {
                    Match m = kFold.Match(s);
                    if (m.Success)
                    {
                        KFoldIndex = Int32.Parse(m.Groups[1].Value);
                    }
                    else
                    {
                        Error("Could not parse k-fold output line: {0}.", s);
                        return StageResult.FAILED;
                    }
                }

                else if (!KFoldCrossValidation && !MicroAveragedF1.HasValue && s.StartsWith("Accuracy/micro-averaged F1"))
                {
                    Match m = f1MicroRegex.Match(s);
                    if (m.Success)
                    {
                        MicroAveragedF1 = Single.Parse(m.Groups[1].Value);
                        Info("Micro-averaged F1 = {0}.", MicroAveragedF1);
                    }
                    else
                    {
                        Error("Could not parse micro-averaged F1 statistic {0}.", s);
                    }
                }

                else if (KFoldCrossValidation && ReadTestDataset && !MicroAveragedF1.HasValue && s.StartsWith("Accuracy/micro-averaged F1"))
                {
                    Match m = f1MicroRegex.Match(s);
                    if (m.Success)
                    {
                        MicroAveragedF1 = Single.Parse(m.Groups[1].Value);
                        Info("Micro-averaged F1 = {0}.", MicroAveragedF1);
                    }
                    else
                    {
                        Error("Could not parse micro-averaged F1 statistic {0}.", s);
                    }
                }

                else if (KFoldCrossValidation && s.StartsWith("Accuracy/micro-averaged F1"))
                {
                    Match m = f1MicroRegex.Match(s);
                    if (m.Success)
                    {
                        MicroAveragedF1Folds[KFoldIndex.Value] = Single.Parse(m.Groups[1].Value);
                        Info("Fold {0} Micro-averaged F1 = {1}.", KFoldIndex.Value, MicroAveragedF1Folds[KFoldIndex.Value]);
                    }
                    else
                    {
                        Error("Could not parse micro-averaged F1 statistic {0}.", s);
                    }
                }

                else if (!KFoldCrossValidation && !MacroAveragedF1.HasValue && s.StartsWith("Macro-averaged F1"))
                {
                    Match m = f1MacroRegex.Match(s);
                    if (m.Success)
                    {
                        MacroAveragedF1 = Single.Parse(m.Groups[1].Value);
                        Info("Macro-averaged F1 = {0}.", MacroAveragedF1);
                    }
                    else
                    {
                        Error("Could not parse macro-averaged F1 statistic {0}.", s);
                    }
                }

                else if (KFoldCrossValidation && ReadTestDataset && !MacroAveragedF1.HasValue && s.StartsWith("Macro-averaged F1"))
                {
                    Match m = f1MacroRegex.Match(s);
                    if (m.Success)
                    {
                        MacroAveragedF1Folds[KFoldIndex.Value] = Single.Parse(m.Groups[1].Value);
                        Info("Macro-averaged F1 = {0}.\n", MacroAveragedF1Folds[KFoldIndex.Value]);
                    }
                    else
                    {
                        Error("Could not parse macro-averaged F1 statistic {0}.", s);
                    }
                }

                else if (KFoldCrossValidation && s.StartsWith("Macro-averaged F1"))
                {
                    Match m = f1MacroRegex.Match(s);
                    if (m.Success)
                    {
                        MacroAveragedF1Folds[KFoldIndex.Value] = Single.Parse(m.Groups[1].Value);
                        Info("Fold {0} Macro-averaged F1 = {1}.\n", KFoldIndex.Value, MacroAveragedF1Folds[KFoldIndex.Value]);
                    }
                    else
                    {
                        Error("Could not parse macro-averaged F1 statistic {0}.", s);
                    }
                }

                else if (Features == null && s.StartsWith("Built this clreplacedifier: 1"))
                {
                    Features = new Dictionary<string, float>();
                    string f = s.Remove(0,"Built this clreplacedifier: ".Length);
                    foreach (string l in f.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                    {
                        string[] ls = l.Split('=');
                        Features.Add(ls[0].Trim(), Single.Parse(ls[1].Trim()));
                    }
                    Info("Using {0} features.", Features.Count);
          
                }
                else if (s.StartsWith("Cls"))
                {
                    Match m = clreplacedStatisticRegex.Match(s);
                    if (m.Success)
                    {
                        ClreplacedStatistic cs = new ClreplacedStatistic()
                        {
                            Name = m.Groups[1].Value,
                            TruePositives = Int32.Parse(m.Groups[2].Value),
                            FalsePositives = Int32.Parse(m.Groups[3].Value),
                            TrueNegatives = Int32.Parse(m.Groups[4].Value),
                            Accuracy = Single.Parse(m.Groups[5].Value),
                            Precision = Single.Parse(m.Groups[6].Value),
                            Recall = Single.Parse(m.Groups[7].Value),
                            F1 = Single.Parse(m.Groups[8].Value)
                        };
                        _ClreplacedStatistics.Add(cs);
                        Info(s);
                    }
                    else
                    {
                        L.Error("Could not parse clreplaced statistic: {0}.", s);
                    }
                }

                else if (resultRegex.IsMatch(s))
                {
                    Match m = resultRegex.Match(s);
                    ClreplacedifierResult cr = new ClreplacedifierResult()
                    {
                        GoldAnswer = m.Groups[1].Value,
                        ClreplacedifierAnswer = m.Groups[2].Value,
                        P_GoldAnswer = Single.Parse(m.Groups[3].Value),
                        P_ClAnswer = Single.Parse(m.Groups[4].Value)

                    };
                    _Results.Add(cr);
                }
                ClreplacedifierOutput.Add(s);
                Debug(s);
            }

            c.Wait();
            if (!CheckCommandSuccessAndReport(javaCommand))
            {
                return StageResult.FAILED;
            }
            
            if (!KFoldCrossValidation)
            {
                Info("Got {0} clreplaced statistics.", _ClreplacedStatistics.Count);
                Info("Got {0} results.", _Results.Count);
            }
            return StageResult.SUCCESS;
        }

19 Source : Tools.cs
with MIT License
from AmigoCap

public static float InterpretExponent(string word) {
            int pos = word.IndexOf("E");
            if (pos == -1) {
                pos = word.IndexOf("e");
            }
            if (pos != -1) {
                return float.Parse(word.Substring(0, pos - 1).Replace('.', ',')) * Mathf.Pow(10, float.Parse(word.Substring(pos + 1)));
            }
            else
                return float.Parse(word.Replace('.', ','));
        }

19 Source : Program.cs
with MIT License
from anastasios-stamoulis

float[][] load_data(List<string> all_lines) {
      var float_data = new float[all_lines.Count][];
      for (int i = 0; i < all_lines.Count; i++) {
        var current_line = all_lines[i];
        float_data[i] = current_line.Split(',').Skip(1).Select((x) => float.Parse(x)).ToArray();
      }
      return float_data;
    }

19 Source : Program.cs
with MIT License
from anastasios-stamoulis

Dictionary<string, float[]> preprocess_embeddings() {
      var glove_dir = "C:\\Users\\anastasios\\Downloads\\glove.6B";
      var embeddings_index = new Dictionary<string, float[]>();
      var glove_path = System.IO.Path.Combine(glove_dir, "glove.6B.100d.txt");
      Console.WriteLine($"Processing {glove_path}");
      foreach(var line in System.IO.File.ReadLines(glove_path, Encoding.UTF8)) {
        var values = line.Split(' ');
        var word = values[0];
        var coefs = values.Skip(1).Select(v => Single.Parse(v)).ToArray();
        System.Diagnostics.Debug.replacedert(coefs.Length == Constants.embedding_dim);
        embeddings_index[word] = coefs;        
      }
      Console.WriteLine($"Found {embeddings_index.Keys.Count:n0} word vectors.");
      return embeddings_index;
    }

19 Source : SteamVR_ExternalCamera.cs
with GNU General Public License v2.0
from andrewjc

public void ReadConfig()
	{
		try
		{
			var mCam = new HmdMatrix34_t();
			var readCamMatrix = false;

			object c = config; // box
			var lines = System.IO.File.ReadAllLines(configPath);
			foreach (var line in lines)
			{
				var split = line.Split('=');
				if (split.Length == 2)
				{
					var key = split[0];
					if (key == "m")
					{
						var values = split[1].Split(',');
						if (values.Length == 12)
						{
							mCam.m0 = float.Parse(values[0]);
							mCam.m1 = float.Parse(values[1]);
							mCam.m2 = float.Parse(values[2]);
							mCam.m3 = float.Parse(values[3]);
							mCam.m4 = float.Parse(values[4]);
							mCam.m5 = float.Parse(values[5]);
							mCam.m6 = float.Parse(values[6]);
							mCam.m7 = float.Parse(values[7]);
							mCam.m8 = float.Parse(values[8]);
							mCam.m9 = float.Parse(values[9]);
							mCam.m10 = float.Parse(values[10]);
							mCam.m11 = float.Parse(values[11]);
							readCamMatrix = true;
						}
					}
					else if (key == "disableStandardreplacedets")
					{
						var field = c.GetType().GetField(key);
						if (field != null)
							field.SetValue(c, bool.Parse(split[1]));
					}
					else
					{
						var field = c.GetType().GetField(key);
						if (field != null)
							field.SetValue(c, float.Parse(split[1]));
					}
				}
			}
			config = (Config)c; //unbox

			// Convert calibrated camera matrix settings.
			if (readCamMatrix)
			{
				var t = new SteamVR_Utils.RigidTransform(mCam);
				config.x = t.pos.x;
				config.y = t.pos.y;
				config.z = t.pos.z;
				var angles = t.rot.eulerAngles;
				config.rx = angles.x;
				config.ry = angles.y;
				config.rz = angles.z;
			}
		}
		catch { }
	}

19 Source : SteamVR_PlayArea.cs
with GNU General Public License v2.0
from andrewjc

public static bool GetBounds( Size size, ref HmdQuad_t pRect )
	{
		if (size == Size.Calibrated)
		{
			var initOpenVR = (!SteamVR.active && !SteamVR.usingNativeSupport);
			if (initOpenVR)
			{
				var error = EVRInitError.None;
				OpenVR.Init(ref error, EVRApplicationType.VRApplication_Other);
			}

			var chaperone = OpenVR.Chaperone;
			bool success = (chaperone != null) && chaperone.GetPlayAreaRect(ref pRect);
			if (!success)
				Debug.LogWarning("Failed to get Calibrated Play Area bounds!  Make sure you have tracking first, and that your space is calibrated.");

			if (initOpenVR)
				OpenVR.Shutdown();

			return success;
		}
		else
		{
			try
			{
				var str = size.ToString().Substring(1);
				var arr = str.Split(new char[] {'x'}, 2);

				// convert to half size in meters (from cm)
				var x = float.Parse(arr[0]) / 200;
				var z = float.Parse(arr[1]) / 200;

				pRect.vCorners0.v0 =  x;
				pRect.vCorners0.v1 =  0;
				pRect.vCorners0.v2 =  z;

				pRect.vCorners1.v0 =  x;
				pRect.vCorners1.v1 =  0;
				pRect.vCorners1.v2 = -z;

				pRect.vCorners2.v0 = -x;
				pRect.vCorners2.v1 =  0;
				pRect.vCorners2.v2 = -z;

				pRect.vCorners3.v0 = -x;
				pRect.vCorners3.v1 =  0;
				pRect.vCorners3.v2 =  z;

				return true;
			}
			catch {}
		}

		return false;
	}

19 Source : TripleObject.cs
with MIT License
from angshuman

public JValue ToTypedJSON()
        {
            switch (TokenType) {
                case JTokenType.String:
                case JTokenType.Date:
                case JTokenType.TimeSpan:
                case JTokenType.Guid:
                case JTokenType.Uri:
                    return new JValue(Value);
                case JTokenType.Integer:
                    return new JValue(int.Parse(Value));
                case JTokenType.Boolean:
                    return new JValue(bool.Parse(Value));
                case JTokenType.Float:
                    return new JValue(float.Parse(Value));
                default:
                    throw new InvalidOperationException($"{TokenType} not support as object");
            }
        }

19 Source : EgsDoseLoader.cs
with Apache License 2.0
from anmcgrath

public EgsDoseObject Load(string fileName)
        {
            EgsDoseObject dose = new EgsDoseObject();
            GridBasedVoxelDataStructure grid = new GridBasedVoxelDataStructure();
            dose.Name = Path.GetFileName(fileName);
            string text = File.ReadAllText(fileName);
            string[] numbers = text.Split(new char[] { '\n', ' ', '\t', '\r' }, StringSplitOptions.RemoveEmptyEntries);
            int SizeX = Int32.Parse(numbers[0]);
            int SizeY = Int32.Parse(numbers[1]);
            int SizeZ = Int32.Parse(numbers[2]);
            grid.XCoords = new double[SizeX];
            grid.YCoords = new double[SizeY];
            grid.ZCoords = new double[SizeZ];
            grid.Data = new float[SizeX, SizeY, SizeZ];

            int offset = 3;

            for (int i = 0; i < SizeX; i++)
            {
                grid.XCoords[i] = 10 * (Double.Parse(numbers[offset + i]) + Double.Parse(numbers[offset + i + 1])) / 2;
            }
            offset += SizeX + 1;
            for (int i = 0; i < SizeY; i++)
            {
                grid.YCoords[i] = 10 * (Double.Parse(numbers[offset + i]) + Double.Parse(numbers[offset + i + 1])) / 2;
            }
            offset += SizeY + 1;
            for (int i = 0; i < SizeZ; i++)
            {
                grid.ZCoords[i] = 10 * (Double.Parse(numbers[offset + i]) + Double.Parse(numbers[offset + i + 1])) / 2;
            }
            offset += SizeZ + 1;

            for (int i = 0; i < SizeX * SizeY * SizeZ; i++)
            {
                int indexX = i % SizeX;
                int indexZ = (int)(i / (SizeX * SizeY));
                int indexY = (int)(i / SizeX) - indexZ * (SizeY);
                grid.Data[indexX, indexY, indexZ] = float.Parse(numbers[offset + i]);
            }

            foreach(Voxel voxel in grid.Voxels)
            {
                if (voxel.Value > grid.GlobalMax.Value)
                    grid.GlobalMax = voxel;
            }
            return dose;
        }

19 Source : FontSerializationHelper.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public static Font FromString(
            string value)
        {
            var f = FontInfo.DefaultFont.ToFontForWindowsForm();

            if (string.IsNullOrEmpty(value))
            {
                return f;
            }

            try
            {
                var parts = value.Split(FontSerializationDelimiter);

                if (parts.Length >= 6)
                {
                    f = new Font(
                        parts[0],
                        float.Parse(parts[1]),
                        (FontStyle)Enum.Parse(typeof(FontStyle), parts[2]),
                        (GraphicsUnit)Enum.Parse(typeof(GraphicsUnit), parts[3]),
                        byte.Parse(parts[4]),
                        bool.Parse(parts[5]));
                }
            }
            catch (Exception)
            {
                f = FontInfo.DefaultFont.ToFontForWindowsForm();
            }

            return f;
        }

19 Source : StatisticsDatabase.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public async Task CreateHistogramAsync(
            string rankingFileName)
        {
            if (!File.Exists(rankingFileName))
            {
                return;
            }

            using (var cn = this.OpenRankingDatabaseConnection(rankingFileName))
            {
                using (var tran = cn.BeginTransaction())
                {
                    using (var cm = cn.CreateCommand())
                    {
                        cm.Transaction = tran;

                        var q = new StringBuilder();
                        q.AppendLine("DELETE FROM histograms;");
                        cm.CommandText = q.ToString();
                        await cm.ExecuteNonQueryAsync();
                    }

                    tran.Commit();
                }

                using (var db = new DataContext(cn))
                using (var tran = cn.BeginTransaction())
                {
                    db.Transaction = tran;
                    var rankings = db.GetTable<RankingModel>().ToArray();

                    var averages =
                        from x in rankings
                        group x by
                        x.CharacterHash
                        into g
                        select new
                        {
                            SpecName = g.First().Spec,
                            DPSAverage = g.Average(z => z.Total),
                            Rank = ((int)(g.Average(z => z.Total)) / 100) * 100,
                        };

                    var histograms =
                        from x in averages
                        group x by new
                        {
                            x.SpecName,
                            x.Rank
                        }
                        into g
                        select new
                        {
                            g.Key.SpecName,
                            g.Key.Rank,
                            RankFrom = g.Key.Rank,
                            Frequency = (double)g.Count(),
                        };

                    var id = 1;
                    var specs =
                        from x in histograms
                        orderby
                        x.SpecName,
                        x.Rank
                        group x by
                        x.SpecName;

                    var enreplacedies = new List<HistogramModel>(histograms.Count());

                    foreach (var spec in specs)
                    {
                        var totalCount = spec.Sum(x => x.Frequency);
                        var count = 0d;
                        var rankMin = spec.Min(x => x.Rank);
                        var rankMax = spec.Max(x => x.Rank);

                        for (int i = rankMin; i <= rankMax; i += 100)
                        {
                            var entry = spec.FirstOrDefault(x => x.Rank == i);
                            var f = entry?.Frequency ?? 0;

                            var hist = new HistogramModel()
                            {
                                ID = id++,
                                SpecName = spec.Key,
                                Rank = i,
                                RankFrom = i,
                                Frequency = f,
                                FrequencyPercent = round(f / totalCount * 100d),
                                RankPercentile = round(count / totalCount * 100d),
                            };

                            enreplacedies.Add(hist);
                            count += f;
                        }
                    }

                    var table = db.GetTable<HistogramModel>();
                    table.InsertAllOnSubmit<HistogramModel>(enreplacedies);
                    db.SubmitChanges();

                    // ランキングテーブルを消去する
                    using (var cm = cn.CreateCommand())
                    {
                        cm.Transaction = tran;

                        var q = new StringBuilder();
                        q.AppendLine("DELETE FROM rankings;");
                        cm.CommandText = q.ToString();
                        await cm.ExecuteNonQueryAsync();
                    }

                    tran.Commit();
                }

                // DBを最適化する
                using (var cm = cn.CreateCommand())
                {
                    var q = new StringBuilder();
                    q.AppendLine("VACUUM;");
                    q.AppendLine("PRAGMA Optimize;");
                    cm.CommandText = q.ToString();
                    await cm.ExecuteNonQueryAsync();
                }
            }

            double round(double value)
            {
                return float.Parse(value.ToString("N3"));
            }
        }

19 Source : Item.cs
with Apache License 2.0
from anpShawn

public static void CreateItems()
    {
        items = new Dictionary<string, Item>();

        //use this line to load from a json file
        //ItemMap map = Utils.LoadJsonFromPath<ItemMap>("data/item_data");

        /*
         *      {"id":"3:wooden_sword",                                              "type":"WEAPON",         "stats" : ["atk=2", "crit_chance=1","crit_bonus=10"],                                                           "spawn_rate":"15",        "min_spawn_lvl":"5",          "max_spawn_lvl":"0",          "area":"CAVERNS",                                         "attached_skill_ids":"",                                                                        "season":"ALL",                  "slots": [],                           "flags":"",                                               "explicit_rarity":"",                   "explicit_value":0},
                {"id":"4:buckler",                                                   "type":"SHIELD",         "stats" : ["hp=2"],                                                                                             "spawn_rate":"15",        "min_spawn_lvl":"5",          "max_spawn_lvl":"0",          "area":"CAVERNS",                                         "attached_skill_ids":"",                                                                        "season":"ALL",                  "slots": [],                           "flags":"",                                               "explicit_rarity":"",                   "explicit_value":0},
                {"id":"5:leather_armor",                                             "type":"ARMOR",          "stats" : ["hp=1"],                                                                                             "spawn_rate":"20",        "min_spawn_lvl":"5",          "max_spawn_lvl":"0",          "area":"CAVERNS",                                         "attached_skill_ids":"",                                                                        "season":"ALL",                  "slots": [],                           "flags":"",                                               "explicit_rarity":"",                   "explicit_value":0},
         * 
         */

        //instead, create the data manually
        var woodenSwordData = new ItemRow()  { id = "3:" + ItemId.WOODEN_SWORD,    type="WEAPON",   stats = new string[] { "atk=2", "crit_chance=1","crit_bonus=10"},   spawn_rate=15,   min_spawn_lvl=5,  max_spawn_lvl=0, area="CAVERNS", attached_skill_ids="", slots = new string[] { }, flags=""  };
        var woodenShieldData = new ItemRow() { id = "4:" + ItemId.BUCKLER,         type="SHIELD",   stats = new string[] { "hp=2"},                                     spawn_rate=15,   min_spawn_lvl=5,  max_spawn_lvl=0, area="CAVERNS", attached_skill_ids="", slots = new string[] { }, flags=""  };
        var leatherArmorData = new ItemRow() { id = "5:" + ItemId.LEATHER_ARMOR,   type="ARMOR",    stats = new string[] { "hp=1"},                                     spawn_rate=20,   min_spawn_lvl=5,  max_spawn_lvl=0, area="CAVERNS", attached_skill_ids="", slots = new string[] { }, flags=""  };
        var peltData = new ItemRow()         { id = "6:" + ItemId.PELT,            type="RESOURCE", stats = new string[] { },                                           spawn_rate=0,    min_spawn_lvl=0,  max_spawn_lvl=0, area="CAVERNS", attached_skill_ids="", slots = new string[] { }, flags=""  };

        ItemMap map = new ItemMap();
        map.items = new ItemRow[] { woodenSwordData, woodenShieldData, leatherArmorData, peltData };

        ItemRow row;
        Item tempItem;
        string[] idPieces;
        string id;

        for (int i = 0; i < map.items.Length; i++)
        {
            row = map.items[i];

            //item ids are provied in a number:name format. the name is only present in the data file for readability, so we need to discard it
            idPieces = row.id.Split(':');
            id = idPieces[0];

            if (!ItemId.IsValid(id)) throw new Exception("Item id '" + row.id + "' does not exist");

            tempItem = new Item();
            tempItem.Init();

            tempItem.SetId(id);
            tempItem.DeriveBaseAndStorageId();
            ItemType parsedType = (ItemType)Enum.Parse(typeof(ItemType), row.type);
            tempItem.SetType(parsedType);

            Stats.ParseArrayIntoStatObject(row.stats, tempItem.baseStats);

            AdventureArea parsedAreas = Utils.ParseStringToFlagEnum<AdventureArea>(row.area, '|');
            tempItem.SetSpawnInfo(row.spawn_rate, row.min_spawn_lvl, row.max_spawn_lvl, parsedAreas);

            if(string.IsNullOrEmpty(row.explicit_rarity))
                tempItem.DeriveRarity();
            else
            {
                tempItem._rarity = (Rarity)Enum.Parse(typeof(Rarity), row.explicit_rarity);
            }

            char[] separators = new char[',']; //must define a separator array so that we can preplaced in the stringsplit option param
            tempItem.attachedSkillIds = row.attached_skill_ids.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            string curId;
            for(int j=0; j<tempItem.attachedSkillIds.Length; j++)
            {
                curId = tempItem.attachedSkillIds[j];
                if (!SkillId.IsValid(curId))
                    throw new Exception(curId + " is not a valid skill id to attach to an item");
            }

            int numSlots = row.slots.Length;
            tempItem.slotPositions = new Vector2[numSlots];
            string[] coords;
            for (int j = 0; j < numSlots; j++)
            {
                coords = row.slots[j].Split(',');
                tempItem.slotPositions[j] = new Vector2(float.Parse(coords[0]), float.Parse(coords[1]));
            }

            tempItem.flags = Utils.ParseStringToFlagEnum<ItemFlags>(row.flags, ',');

            if (row.explicit_value == 0)
                tempItem.CalculateValue();
            else tempItem.value = row.explicit_value;
           

            items.Add(tempItem.id, tempItem);
        }

        //record the number of un-leveled items
        numBasicItemsInGame = items.Count;

        //create leveled items
        itemLevelBoosts = new Stats();
        itemLevelBoosts.Set(Stat.hp, 3);
        itemLevelBoosts.Set(Stat.mp, 4);
        itemLevelBoosts.Set(Stat.atk, 2);
        itemLevelBoosts.Set(Stat.crit_chance, 1);
        itemLevelBoosts.Set(Stat.crit_bonus, 1);
        itemLevelBoosts.Set(Stat.dmg_reduction, 1);
        itemLevelBoosts.Set(Stat.evade, 1);
        itemLevelBoosts.Set(Stat.gold_find, 3);
        itemLevelBoosts.Set(Stat.item_find, 2);
        itemLevelBoosts.Set(Stat.magic_boost, 2);
        itemLevelBoosts.Set(Stat.phys_boost, 2);
        itemLevelBoosts.Set(Stat.hp_boost, 1);
        itemLevelBoosts.Set(Stat.mp_boost, 1);
        itemLevelBoosts.Set(Stat.atk_boost, 1);
        itemLevelBoosts.Set(Stat.dmg_reflection, 2);
        itemLevelBoosts.Set(Stat.mastery_xp_boost, 2);

        itemTypesThatLevelUp = ItemType.WEAPON | ItemType.ARMOR | ItemType.SHIELD;
        List<Item> existingItems = items.Values.ToList();
        Item newItem;
        int spawnRange = 100;

        for (int i = 0; i < existingItems.Count; i++)
        {
            tempItem = existingItems[i];

            if(tempItem.IsTypeThatLevelsUp())
            {
                //TODO manually exclude some stuff from leveling up
                if (tempItem.id == ItemId.APHOTIC_BLADE || tempItem.id == ItemId.MOP || tempItem.id == ItemId.IRON_SKILLET)
                    continue;

                //force all items to have a max spawn level of min + 100
                tempItem._spawnMaxLevel = tempItem.spawnMinLevel + spawnRange;

                //right now just levels 2 to the "max"
                for(int j=2; j<=GameContext.MAX_ITEM_LEVEL_WITHOUT_ENHANCING; j++)
                {
                    newItem = tempItem.GetCopy();
                    newItem.BoosreplacedemToLevel(j);
                    items.Add(newItem.id, newItem);

                    //once item is level 5 or higher it can ALWAYS spawn, otherwise limit it
                    if (j > 4)
                        newItem._spawnMaxLevel = 0;
                    else
                        newItem._spawnMaxLevel = newItem.spawnMinLevel + spawnRange;

                }
            }
        }

        //copy ALL items into a parallel list for convenience
        itemCollectionList = items.Values.ToList();

        //create specialized lists
        foodItemIds = new List<string>() { ItemId.APPLE, ItemId.BACON, ItemId.CARROT, ItemId.CARAMEL, ItemId.EGGPLANT, ItemId.MUSHROOM, ItemId.RADISH };



        //build this dict to make status effect prevention checks much faster
        statusEffectToPreventionFlagMap = new Dictionary<StatusEffectType, ItemFlags>();
        statusEffectToPreventionFlagMap[StatusEffectType.BURN] = ItemFlags.PREVENTS_BURN;
        statusEffectToPreventionFlagMap[StatusEffectType.STONE] = ItemFlags.PREVENTS_STONE;
        statusEffectToPreventionFlagMap[StatusEffectType.SPEED_DOWN] = ItemFlags.PREVENTS_SPEED_DOWN;
        statusEffectToPreventionFlagMap[StatusEffectType.SLEEP] = ItemFlags.PREVENTS_SLEEP;
    }

19 Source : Product.cs
with MIT License
from ansel86castro

public static List<Product> GetProducts()
		{
			List<Product> products = new List<Product>();

			var brands = Enumerable.Range(1, 5).Select(i => new Brand { Id = i, Name = $"Brand {i}" }).ToList();
			var catalogs = Enumerable.Range(1, 3).Select(i => new Models.Catalog { Id = i, Name = $"Catalog {i}" });

			var rand = new Random();
			foreach (var catalog in catalogs)
			{
				products.AddRange(Enumerable.Range(1, 10)
					 .Select(i => new Product
					 {
						 Brand = brands[i % 5],
						 Catalog = catalog,
						 AvalaibleStock = rand.Next(1000),
						 CreateDate = DateTime.Now,
						 Name = $"Product {catalog.Id}-{i}",
						 Price = i % 2 == 0 ? i : float.Parse($"{rand.Next(100, 500)}.{rand.Next(0, 100)}"),
						 RestockThreshold = 5,
						 Description = $"Description for Product {catalog.Id}{i}",
						 BrandId = brands[i % 5].Id,
						 CatalogId = catalog.Id
					 }));

			}

			return products;
		}

19 Source : StringConverter.cs
with MIT License
from ansel86castro

public static object GetValue(Type type, string value)
        {
            if (string.IsNullOrEmpty(value))
                return null;
            if (type == typeof(float))
                return float.Parse(value);
            else if (type == typeof(int))
                return int.Parse(value);
            else if (type == typeof(bool))
                return bool.Parse(value);
            else if (type == typeof(short))
                return short.Parse(value);
            else if (type == typeof(double))
                return double.Parse(value);
            else if (type == typeof(byte))
                return byte.Parse(value);
            else if (type == typeof(string))
                return value;
            else if (type == typeof(Vector3))
            {
                //var match = Regex.Match(value, @"(?<X>\d+(\.\d+)?)\s?,\s?(?<Y>\d+(\.\d+)?)\s?,\s?(?<Z>\d+(\.\d+)?)");
                var match = Regex.Match(value, @"\((?<X>-?\d+(\.\d+)?)\s?,\s?(?<Y>-?\d+(\.\d+)?)\s?,\s?(?<Z>-?\d+(\.\d+)?)\)");
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                return new Vector3(float.Parse(match.Groups["X"].Value), float.Parse(match.Groups["Y"].Value), float.Parse(match.Groups["Z"].Value));
            }
            else if (type == typeof(Vector2))
            {
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");                
                var match = Regex.Match(value, @"\((?<X>-?\d+(\.\d+)?)\s?,\s?(?<Y>-?\d+(\.\d+)?)\)");
                return new Vector2(float.Parse(match.Groups["X"].Value), float.Parse(match.Groups["Y"].Value));
            }
            else if (type == typeof(Vector4))
            {
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                var match = Regex.Match(value, @"\((?<X>-?\d+(\.\d+)?)\s?,\s?(?<Y>-?\d+(\.\d+)?)\s?,\s?(?<Z>-?\d+(\.\d+)?)\s?,\s?(?<W>-?\d+(\.\d+)?)\)");
                return new Vector4(float.Parse(match.Groups["X"].Value), float.Parse(match.Groups["Y"].Value), float.Parse(match.Groups["Z"].Value), float.Parse(match.Groups["W"].Value));
            }
            else if (type == typeof(Euler))
            {
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                var match = Regex.Match(value, @"<(?<X>-?\d+(\.\d+)?)\s?,\s?(?<Y>-?\d+(\.\d+)?)\s?,\s?(?<Z>-?\d+(\.\d+)?)>");
                return new Euler(ToRadians(float.Parse(match.Groups["X"].Value)), ToRadians(float.Parse(match.Groups["Y"].Value)), ToRadians(float.Parse(match.Groups["Z"].Value)));
            }
            else if (type == typeof(SizeF))
            {
                var match = Regex.Match(value, @"<(?<W>-?\d+(\.\d+)?)\s?x\s?(?<H>-?\d+(\.\d+)?)>F");
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                return new SizeF(float.Parse(match.Groups["W"].Value), float.Parse(match.Groups["H"].Value));
            }
            else if (type == typeof(Size))
            {
                var match = Regex.Match(value, @"<(?<W>-?\d+(\.\d+)?)\s?x\s?(?<H>-?\d+(\.\d+)?)>");
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                return new SizeF(float.Parse(match.Groups["W"].Value), float.Parse(match.Groups["H"].Value));
            }
            else if (type == typeof(Spherical))
            {
                var match = Regex.Match(value, @"<(?<THETA>-?\d+(\.\d+)?)\s?,\s?(?<PITCH>-?\d+(\.\d+)?)>");
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                return new SizeF(float.Parse(match.Groups["THETA"].Value), float.Parse(match.Groups["PITCH"].Value));
            }        
            else if (type == typeof(Plane))
            {
                //var match = Regex.Matches(value, @"(-?\d+(\.\d+)?)");
                var match = Regex.Match(value, @"< \((?<X>-?\d+(\.\d+)?)\s?,\s?(?<Y>-?\d+(\.\d+)?)\s?,\s?(?<Z>-?\d+(\.\d+)?)\) \s?,\s? (?<D>-?\d+(\.\d+)?)>", RegexOptions.IgnorePatternWhitespace);
                return new Plane(float.Parse(match.Groups["X"].Value), float.Parse(match.Groups["Y"].Value), float.Parse(match.Groups["Z"].Value), float.Parse(match.Groups["D"].Value));
            }          
            else if (type == typeof(Spherical))
            {
                var match = Regex.Match(value, @"\((?<Theta>-?\d+(\.\d+)?)\s?,\s?(?<Phi>-?\d+(\.\d+)?)\)");
                return new Spherical(ToRadians(float.Parse(match.Groups["Theta"].Value)), ToRadians(float.Parse(match.Groups["Phi"].Value)));
            }
            throw new ArgumentException("Unable to Converto to " + type + " from " + value);
        }

19 Source : ColladaLoader.Utilities.cs
with MIT License
from ansel86castro

internal Vector4 ParseVector4(string text, bool invert = true)
        {
            var values = Split(text);// _numericExp.Matches(text);

            if (_zUp && invert)
            {
                return new Vector4(float.Parse(values[0]),
                   float.Parse(values[2]),
                   float.Parse(values[1]),
                   float.Parse(values[3]));
            }
            else
            {
                return new Vector4(float.Parse(values[0]),
                    float.Parse(values[1]),
                    float.Parse(values[2]),
                    float.Parse(values[3]));
            }
        }

19 Source : ColladaLoader.Utilities.cs
with MIT License
from ansel86castro

internal Vector3 ParseVector3(string text, bool invert = true)
        {
            var m = Split(text); //_numericExp.Matches(text);   

            if (_zUp && invert)
            {
                return new Vector3(float.Parse(m[0]),
                   float.Parse(m[2]),
                   float.Parse(m[1]));
            }
            else return new Vector3(float.Parse(m[0]),
                   float.Parse(m[1]),
                   float.Parse(m[2]));
        }

19 Source : ColladaLoader.Utilities.cs
with MIT License
from ansel86castro

internal Vector2 ParseVector2(string text)
        {
            var m = Split(text);//_numericExp.Matches(text);    
            return new Vector2(float.Parse(m[0]), float.Parse(m[1]));
        }

19 Source : ColladaLoader.Utilities.cs
with MIT License
from ansel86castro

internal float[] ParseFloatArray(string text)
        {
            var m = Split(text);// _numericExp.Matches(text);                             
            float[] floatValues = new float[m.Length];

            for (int i = 0; i < floatValues.Length; i++)
            {
                floatValues[i] = float.Parse(m[i]);
            }

            return floatValues;
        }

19 Source : SerializationBinaryTest.cs
with MIT License
from ansel86castro

private List<Product> GetProducts()
        {
            List<Product> products = new List<Product>();

            var brands = Enumerable.Range(1, 5).Select(i => new Brand { Id = i, Name = $"Brand {i}" }).ToList();
            var catalogs = Enumerable.Range(1, 3).Select(i => new Models.Catalog { Id = i, Name = $"Catalog {i}" });

            var rand = new Random();
            foreach (var catalog in catalogs)
            {
                products.AddRange(Enumerable.Range(1, 10)
                     .Select(i => new Product
                     {
                         Brand = brands[i % 5],
                         Catalog = catalog,
                         AvalaibleStock = rand.Next(1000),
                         CreateDate = DateTime.Now,
                         Name = $"Product {catalog.Id}-{i}",
                         Price = i % 2 == 0 ? i : float.Parse($"{rand.Next(100, 500)}.{rand.Next(0, 100)}"),
                         RestockThreshold = 5,
                         Description = $"Description for Product {catalog.Id}{i}",
                         BrandId = brands[i % 5].Id,
                         CatalogId = catalog.Id
                     }));

            }

            return products;
        }

19 Source : ConditionalUtils.cs
with GNU Lesser General Public License v3.0
from antonmihaylov

internal static bool EvaluateConditionalVariableWithParameters(string varIdentifier,
            IVariableSource variableSource,
            List<string> otherParameters)
        {
            var value = EvaluateVariable(varIdentifier, variableSource, out var variableValue);
            
            //If no special parameters are found simply return the found value
            if (otherParameters.Count <= 0) return value;
            
            //Process the extra parameters
            string lastOperator = null;
            
            foreach (var otherParameter in otherParameters)
            {
                switch (otherParameter)
                {
                    case OrTagIdentifier:
                    case AndTagIdentifier:
                    case EqualTagIdentifier:
                    case GreaterTagIdentifier:
                    case LessTagIdentifier:
                        lastOperator = otherParameter;
                        break;
                    case NotTagIdentifier:
                        value = !value;
                        lastOperator = null;
                        break;
                    default:
                    {
                        if (lastOperator != null)
                        {
                            object nextValue;
                                nextValue = variableSource.GetVariable(otherParameter) ?? otherParameter;

                                var nextValueEvaluated = EvaluateVariableValue(nextValue);

                            switch (lastOperator)
                            {
                                case OrTagIdentifier:
                                    value = value || nextValueEvaluated;
                                    break;
                                case AndTagIdentifier:
                                    value = value && nextValueEvaluated;
                                    break;
                                case EqualTagIdentifier:
                                    value = variableValue?.ToString() == nextValue.ToString();
                                    break;
                                case GreaterTagIdentifier:
                                    try
                                    {
                                        value = float.Parse(variableValue?.ToString()) > float.Parse(nextValue.ToString());
                                    }
                                    catch
                                    {
                                        try
                                        {
                                            value = int.Parse(variableValue?.ToString()) > int.Parse(nextValue.ToString());
                                        }
                                        catch
                                        {
                                            // ignored
                                        }
                                    }

                                    break;
                                case LessTagIdentifier:
                                    try
                                    {
                                        value = float.Parse(variableValue?.ToString()) < float.Parse(nextValue.ToString());
                                    }
                                    catch
                                    {
                                        try
                                        {
                                            value = int.Parse(variableValue?.ToString()) < int.Parse(nextValue.ToString());
                                        }
                                        catch
                                        {
                                            // ignored
                                        }
                                    }

                                    break;
                            }

                            lastOperator = null;
                        }

                        break;
                    }
                }
            }

            return value;
        }

19 Source : NmsStreamMessageTest.cs
with Apache License 2.0
from apache

[Test, Description("Set a string, then retrieve it as all of the legal type combinations to verify it is parsed correctly")]
        public void TestWriteStringReadLegal()
        {
            NmsStreamMessage streamMessage = factory.CreateStreamMessage();

            string integralValue = Convert.ToString(byte.MaxValue);
            streamMessage.WriteString(integralValue);
            streamMessage.Reset();

            replacedertGetStreamEntryEquals<string>(streamMessage, true, integralValue);
            replacedertGetStreamEntryEquals<bool>(streamMessage, true, false);
            replacedertGetStreamEntryEquals<byte>(streamMessage, true, byte.MaxValue);

            streamMessage.ClearBody();
            integralValue = Convert.ToString(short.MaxValue);
            streamMessage.WriteString(integralValue);
            streamMessage.Reset();

            replacedertGetStreamEntryEquals<short>(streamMessage, true, short.MaxValue);

            streamMessage.ClearBody();
            integralValue = Convert.ToString(int.MaxValue);
            streamMessage.WriteString(integralValue);
            streamMessage.Reset();

            replacedertGetStreamEntryEquals<int>(streamMessage, true, int.MaxValue);

            streamMessage.ClearBody();
            integralValue = Convert.ToString(long.MaxValue);
            streamMessage.WriteString(integralValue);
            streamMessage.Reset();

            replacedertGetStreamEntryEquals<long>(streamMessage, true, long.MaxValue);

            streamMessage.ClearBody();
            string fpValue = Convert.ToString(float.MaxValue, CultureInfo.InvariantCulture);
            streamMessage.WriteString(fpValue);
            streamMessage.Reset();

            replacedertGetStreamEntryEquals<float>(streamMessage, true, float.Parse(fpValue));

            // TODO: make following preplaced
            //replacedertGetStreamEntryEquals<double>(streamMessage, true, double.Parse(fpValue));
        }

19 Source : MtlParser.cs
with MIT License
from arcplus

public ICollection<Material> GetMats()
        {
            var mats = new List<Material>();
            var matStrs = new List<List<string>>();
            while(!_reader.EndOfStream)
            {
                var line = _reader.ReadLine().Trim();
                if (line.StartsWith("newmtl"))
                {
                    matStrs.Add(new List<string> { line });
                }
                else if (matStrs.Count > 0)
                {
                    matStrs[matStrs.Count - 1].Add(line);
                }
            }
            foreach(var matS in matStrs)
            {
                var m = new Material();
                foreach(var line in matS)
                {
                    if (line.StartsWith("newmtl"))
                    {
                        var matName = line.Substring("newmtl".Length).Trim();
                        m.Name = matName;
                    }
                    else if (line.StartsWith("Ka"))
                    {
                        var ka = line.Substring("Ka".Length).Trim();
                        var r = GetReflectivity(ka);
                        if (r != null)
                        {
                            m.Ambient = r;
                        }
                    }
                    else if (line.StartsWith("Kd"))
                    {
                        var kd = line.Substring("Kd".Length).Trim();
                        var r = GetReflectivity(kd);
                        if (r != null)
                        {
                            m.Diffuse = r;
                        }
                    }
                    else if (line.StartsWith("Ks"))
                    {
                        var ks = line.Substring("Ks".Length).Trim();
                        var r = GetReflectivity(ks);
                        if (r != null)
                        {
                            m.Specular = r;
                        }
                    }
                    else if (line.StartsWith("Ke"))
                    {
                        var ks = line.Substring("Ke".Length).Trim();
                        var r = GetReflectivity(ks);
                        if (r != null)
                        {
                            m.Emissive = r;
                        }
                    }
                    else if (line.StartsWith("d"))
                    {
                        var d = line.Substring("d".Length).Trim();
                        m.Dissolve = GetDissolve(d);
                    }
                    else if (line.StartsWith("Tr"))
                    {
                        var tr = line.Substring("Tr".Length).Trim();
                        m.Transparency = GetTransparency(tr);
                    }
                    else if (line.StartsWith("Ns"))
                    {
                        var ns = line.Substring("Ns".Length).Trim();
                        if (ns.Contains("."))
                        {
                            var d = float.Parse(ns);
                            m.SpecularExponent = (int)Math.Round(d);
                        }
                        else
                        {
                            m.SpecularExponent = int.Parse(ns);
                        }                           
                    }
                    else if (line.StartsWith("map_Ka"))
                    {
                        var ma = line.Substring("map_Ka".Length).Trim();
                        if (File.Exists(Path.Combine(_parentFolder, ma)))
                        {
                            m.AmbientTextureFile = ma;
                        }
                    }
                    else if (line.StartsWith("map_Kd"))
                    {
                        var md = line.Substring("map_Kd".Length).Trim();
                        if (File.Exists(Path.Combine(_parentFolder, md)))
                        {
                            m.DiffuseTextureFile = md;
                        }
                    }
                }
                mats.Add(m);
            }
            return mats;
        }

19 Source : GUIUtils.cs
with GNU General Public License v3.0
from ArduinoIoTDev

public static float[] GetFloatArray(string str)
        {
            if (string.IsNullOrEmpty(str))
                return null;

            string[] arr = GetStringArray(str);

            if (arr != null)
            {
                float[] vars = new float[arr.Length];

                for (int i = 0; i < arr.Length; i++)
                {
                    vars[i] = float.Parse(arr[i]);
                }

                return vars;
            }
            else
                return null;
        }

19 Source : MeshVisualizer.cs
with GNU General Public License v3.0
from artembakhanov

public void ReadFle()
    {
        string filePath = "C:/Users/artem/Unity Projects/ARTest 3/startpoints11.txt";
        if (!File.Exists(filePath)) return;

        string[] lines = File.ReadAllLines(filePath);

        foreach (var line in lines)
        {
            float x = float.Parse(line.Split(' ')[0]);
            float y = float.Parse(line.Split(' ')[1]);
            float z = float.Parse(line.Split(' ')[2]);
            pointStorage.voxelSet.AddPoint(1, new Vector3(x, y, z), Random.Range(0.1f, 1), Vector3.forward, false);

            var obj = Instantiate(test);
            obj.tag = "Voxel";
            obj.transform.position = new Vector3(x, y, z);
            obj.transform.localScale = new Vector3(0.01f, 0.01f, 0.01f);
            obj.GetComponent<MeshRenderer>().material = test1;
        }
        pointStorage.voxelSet.Update();


        //VoxelSet_NewActivePointsEvent(null);
    }

19 Source : PointCloudVisual.cs
with GNU General Public License v3.0
from artembakhanov

public void ReadFle()
    {
        string filePath = "D:\\Unity Projects\\ARTest 3\\startpoints9.txt";
        if (!File.Exists(filePath)) return;

        string[] lines = File.ReadAllLines(filePath);

        foreach (var line in lines)
        {
            float x = float.Parse(line.Split(' ')[0]);
            float y = float.Parse(line.Split(' ')[1]);
            float z = float.Parse(line.Split(' ')[2]);
            VoxelSet.AddPoint(new Point(1, new Vector3(x, y, z), 1), false);
        }
        cloudSystem.SetParticles(VoxelSet.GetParticles().ToArray());
        Mesh();
    }

19 Source : Check.cs
with MIT License
from arttonoyan

public static float replacedingle(object obj)
        {
            if (obj == null || obj == DBNull.Value)
                return 0;

            return float.Parse(obj.ToString());
        }

See More Examples