double.ToString(System.IFormatProvider)

Here are the examples of the csharp api double.ToString(System.IFormatProvider) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

840 Examples 7

19 Source : ExcelVmlDrawingPictureCollection.cs
with Apache License 2.0
from Appdynamics

private XmlNode AddImage(string id, Uri targeUri, string Name, double width, double height)
        {
            var node = VmlDrawingXml.CreateElement("v", "shape", ExcelPackage.schemaMicrosoftVml);
            VmlDrawingXml.DoreplacedentElement.AppendChild(node);
            node.SetAttribute("id", id);
            node.SetAttribute("o:type", "#_x0000_t75");
            node.SetAttribute("style", string.Format("position:absolute;margin-left:0;margin-top:0;width:{0}pt;height:{1}pt;z-index:1", width.ToString(CultureInfo.InvariantCulture), height.ToString(CultureInfo.InvariantCulture)));
            //node.SetAttribute("fillcolor", "#ffffe1");
            //node.SetAttribute("insetmode", ExcelPackage.schemaMicrosoftOffice, "auto");

            node.InnerXml = string.Format("<v:imagedata o:relid=\"\" o:replacedle=\"{0}\"/><o:lock v:ext=\"edit\" rotation=\"t\"/>",  Name);
            return node;
        }

19 Source : ExcelGradientFillXml.cs
with Apache License 2.0
from Appdynamics

internal override XmlNode CreateXmlNode(XmlNode topNode)
        {
            TopNode = topNode;
            CreateNode("d:gradientFill");
            if(Type==ExcelFillGradientType.Path) SetXmlNodeString(_typePath, "path");
            if(!double.IsNaN(Degree)) SetXmlNodeString(_degreePath, Degree.ToString(CultureInfo.InvariantCulture));
            if (GradientColor1!=null)
            {
                /*** Gradient color node 1***/
                var node = TopNode.SelectSingleNode("d:gradientFill", NameSpaceManager);
                var stopNode = node.OwnerDoreplacedent.CreateElement("stop", ExcelPackage.schemaMain);
                stopNode.SetAttribute("position", "0");
                node.AppendChild(stopNode);
                var colorNode = node.OwnerDoreplacedent.CreateElement("color", ExcelPackage.schemaMain);
                stopNode.AppendChild(colorNode);
                GradientColor1.CreateXmlNode(colorNode);

                /*** Gradient color node 2***/
                stopNode = node.OwnerDoreplacedent.CreateElement("stop", ExcelPackage.schemaMain);
                stopNode.SetAttribute("position", "1");
                node.AppendChild(stopNode);
                colorNode = node.OwnerDoreplacedent.CreateElement("color", ExcelPackage.schemaMain);
                stopNode.AppendChild(colorNode);

                GradientColor2.CreateXmlNode(colorNode);
            }
            if (!double.IsNaN(Top)) SetXmlNodeString(_topPath, Top.ToString("F5",CultureInfo.InvariantCulture));
            if (!double.IsNaN(Bottom)) SetXmlNodeString(_bottomPath, Bottom.ToString("F5", CultureInfo.InvariantCulture));
            if (!double.IsNaN(Left)) SetXmlNodeString(_leftPath, Left.ToString("F5", CultureInfo.InvariantCulture));
            if (!double.IsNaN(Right)) SetXmlNodeString(_rightPath, Right.ToString("F5", CultureInfo.InvariantCulture));

            return topNode;
        }

19 Source : ExcelPivotTableField.cs
with Apache License 2.0
from Appdynamics

internal ExcelPivotTableFieldNumericGroup SetNumericGroup(double start, double end, double interval)
        {
            ExcelPivotTableFieldNumericGroup group;
            group = new ExcelPivotTableFieldNumericGroup(NameSpaceManager, _cacheFieldHelper.TopNode);
            _cacheFieldHelper.SetXmlNodeBool("d:sharedItems/@containsNumber", true);
            _cacheFieldHelper.SetXmlNodeBool("d:sharedItems/@containsInteger", true);
            _cacheFieldHelper.SetXmlNodeBool("d:sharedItems/@containsSemiMixedTypes", false);
            _cacheFieldHelper.SetXmlNodeBool("d:sharedItems/@containsString", false);

            group.TopNode.InnerXml += string.Format("<fieldGroup base=\"{0}\"><rangePr autoStart=\"0\" autoEnd=\"0\" startNum=\"{1}\" endNum=\"{2}\" groupInterval=\"{3}\"/><groupItems /></fieldGroup>", BaseIndex, start.ToString(CultureInfo.InvariantCulture), end.ToString(CultureInfo.InvariantCulture), interval.ToString(CultureInfo.InvariantCulture));
            int items = AddNumericGroupItems(group, start, end, interval);
            AddFieldItems(items);

            _grouping = group;
            return group;
        }

19 Source : ExcelPivotTableField.cs
with Apache License 2.0
from Appdynamics

private int AddNumericGroupItems(ExcelPivotTableFieldNumericGroup group, double start, double end, double interval)
        {
            if (interval < 0)
            {
                throw (new Exception("The interval must be a positiv"));
            }
            if (start > end)
            {
                throw(new Exception("Then End number must be larger than the Start number"));
            }

            XmlElement groupItems = group.TopNode.SelectSingleNode("d:fieldGroup/d:groupItems", group.NameSpaceManager) as XmlElement;
            int items = 2;
            //First date
            double index=start;
            double nextIndex=start+interval;
            AddGroupItem(groupItems, "<" + start.ToString(CultureInfo.InvariantCulture));

            while (index < end)
            {
                AddGroupItem(groupItems, string.Format("{0}-{1}", index.ToString(CultureInfo.InvariantCulture), nextIndex.ToString(CultureInfo.InvariantCulture)));
                index=nextIndex;
                nextIndex+=interval;
                items++;
            }
            AddGroupItem(groupItems, ">" + nextIndex.ToString(CultureInfo.InvariantCulture));
            return items;
        }

19 Source : ExcelWorkbook.cs
with Apache License 2.0
from Appdynamics

private void SetNameElement(ExcelNamedRange name, XmlElement elem)
		{
			if (name.IsName)
			{
				if (string.IsNullOrEmpty(name.NameFormula))
				{
					if ((TypeCompat.IsPrimitive(name.NameValue) || name.NameValue is double || name.NameValue is decimal))
					{
						elem.InnerText = Convert.ToDouble(name.NameValue, CultureInfo.InvariantCulture).ToString("R15", CultureInfo.InvariantCulture); 
					}
					else if (name.NameValue is DateTime)
					{
						elem.InnerText = ((DateTime)name.NameValue).ToOADate().ToString(CultureInfo.InvariantCulture);
					}
					else
					{
						elem.InnerText = "\"" + name.NameValue.ToString() + "\"";
					}                                
				}
				else
				{
					elem.InnerText = name.NameFormula;
				}
			}
			else
			{
                elem.InnerText = name.FullAddressAbsolute;
			}
		}

19 Source : ExcelWorksheet.cs
with Apache License 2.0
from Appdynamics

private string GetValueForXml(object v)
        {
            string s;
            try
            {
                if (v is DateTime)
                {
                    double sdv = ((DateTime)v).ToOADate();

                    if (Workbook.Date1904)
                    {
                        sdv -= ExcelWorkbook.date1904Offset;
                    }

                    s = sdv.ToString(CultureInfo.InvariantCulture);
                }
                else if (v is TimeSpan)
                {
                    s = DateTime.FromOADate(0).Add(((TimeSpan)v)).ToOADate().ToString(CultureInfo.InvariantCulture);
                }
                else if(TypeCompat.IsPrimitive(v) || v is double || v is decimal)
                {
                    if (v is double && double.IsNaN((double)v))
                    {
                        s = "";
                    }
                    else if (v is double && double.IsInfinity((double)v))
                    {
                        s = "#NUM!";
                    }
                    else
                    {
                        s = Convert.ToDouble(v, CultureInfo.InvariantCulture).ToString("R15", CultureInfo.InvariantCulture);
                    }
                }
                else
                {
                    s = v.ToString();
                }
            }

            catch
            {
                s = "0";
            }
            return s;
        }

19 Source : OfficeProperties.cs
with Apache License 2.0
from Appdynamics

public void SetCustomPropertyValue(string propertyName, object value)
        {
            XmlNode allProps = CustomPropertiesXml.SelectSingleNode(@"ctp:Properties", NameSpaceManager);

            var prop = string.Format("ctp:Properties/ctp:property[@name='{0}']", propertyName);
            XmlElement node = CustomPropertiesXml.SelectSingleNode(prop, NameSpaceManager) as XmlElement;
            if (node == null)
            {
                int pid;
                var MaxNode = CustomPropertiesXml.SelectSingleNode("ctp:Properties/ctp:property[not(@pid <= preceding-sibling::ctp:property/@pid) and not(@pid <= following-sibling::ctp:property/@pid)]", NameSpaceManager);
                if (MaxNode == null)
                {
                    pid = 2;
                }
                else
                {
                    if (!int.TryParse(MaxNode.Attributes["pid"].Value, out pid))
                    {
                        pid = 2;
                    }
                    pid++;
                }
                node = CustomPropertiesXml.CreateElement("property", ExcelPackage.schemaCustom);
                node.SetAttribute("fmtid", "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}");
                node.SetAttribute("pid", pid.ToString());  // custom property pid
                node.SetAttribute("name", propertyName);

                allProps.AppendChild(node);
            }
            else
            {
                while (node.ChildNodes.Count > 0) node.RemoveChild(node.ChildNodes[0]);
            }
            XmlElement valueElem;
            if (value is bool)
            {
                valueElem = CustomPropertiesXml.CreateElement("vt", "bool", ExcelPackage.schemaVt);
                valueElem.InnerText = value.ToString().ToLower(CultureInfo.InvariantCulture);
            }
            else if (value is DateTime)
            {
                valueElem = CustomPropertiesXml.CreateElement("vt", "filetime", ExcelPackage.schemaVt);
                valueElem.InnerText = ((DateTime)value).AddHours(-1).ToString("yyyy-MM-ddTHH:mm:ssZ");
            }
            else if (value is short || value is int)
            {
                valueElem = CustomPropertiesXml.CreateElement("vt", "i4", ExcelPackage.schemaVt);
                valueElem.InnerText = value.ToString();
            }
            else if (value is double || value is decimal || value is float || value is long)
            {
                valueElem = CustomPropertiesXml.CreateElement("vt", "r8", ExcelPackage.schemaVt);
                if (value is double)
                {
                    valueElem.InnerText = ((double)value).ToString(CultureInfo.InvariantCulture);
                }
                else if (value is float)
                {
                    valueElem.InnerText = ((float)value).ToString(CultureInfo.InvariantCulture);
                }
                else if (value is decimal)
                {
                    valueElem.InnerText = ((decimal)value).ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    valueElem.InnerText = value.ToString();
                }
            }
            else
            {
                valueElem = CustomPropertiesXml.CreateElement("vt", "lpwstr", ExcelPackage.schemaVt);
                valueElem.InnerText = value.ToString();
            }
            node.AppendChild(valueElem);
        }

19 Source : WorkSheet.cs
with Apache License 2.0
from Appdynamics

public void ReadWorkSheet()
        {
            FileStream instream = new FileStream(_worksheetPath + @"Worksheet.xlsx", FileMode.Open, FileAccess.ReadWrite);
            using (ExcelPackage pck = new ExcelPackage(instream))
            {
                var ws = pck.Workbook.Worksheets["Perf"];
                replacedert.AreEqual(ws.Cells["H6"].Formula, "B5+B6");

                ws = pck.Workbook.Worksheets["Comment"];
                var comment = ws.Cells["B2"].Comment;

                replacedert.AreNotEqual(comment, null);
                replacedert.AreEqual(comment.Author, "Jan Källman");
                ws = pck.Workbook.Worksheets["Hidden"];
                replacedert.AreEqual<eWorkSheetHidden>(ws.Hidden, eWorkSheetHidden.Hidden);

                ws = pck.Workbook.Worksheets["VeryHidden"];
                replacedert.AreEqual<eWorkSheetHidden>(ws.Hidden, eWorkSheetHidden.VeryHidden);

                ws = pck.Workbook.Worksheets["RichText"];
                replacedert.AreEqual("Room 02 & 03", ws.Cells["G1"].RichText.Text);

                ws = pck.Workbook.Worksheets["HeaderImage"];
                //replacedert.AreEqual(ws.HeaderFooter.Pictures.Count, 3);

                ws = pck.Workbook.Worksheets["newsheet"];
                replacedert.AreEqual(ws.Cells["F2"].Style.Font.UnderLine, true);
                replacedert.AreEqual(ws.Cells["F2"].Style.Font.UnderLineType, ExcelUnderLineType.Double);
                replacedert.AreEqual(ws.Cells["F3"].Style.Font.UnderLineType, ExcelUnderLineType.SingleAccounting);
                replacedert.AreEqual(ws.Cells["F5"].Style.Font.UnderLineType, ExcelUnderLineType.None);
                replacedert.AreEqual(ws.Cells["F5"].Style.Font.UnderLine, false);

                replacedert.AreEqual(ws.Cells["T20"].GetValue<string>(), 0.396180555555556d.ToString(CultureInfo.CurrentCulture));
                replacedert.AreEqual(ws.Cells["T20"].GetValue<int>(), 0);
                replacedert.AreEqual(ws.Cells["T20"].GetValue<int?>(), 0);
                replacedert.AreEqual(ws.Cells["T20"].GetValue<double>(), 0.396180555555556d);
                replacedert.AreEqual(ws.Cells["T20"].GetValue<double?>(), 0.396180555555556d);
                replacedert.AreEqual(ws.Cells["T20"].GetValue<decimal>(), 0.396180555555556m);
                replacedert.AreEqual(ws.Cells["T20"].GetValue<decimal?>(), 0.396180555555556m);
                replacedert.AreEqual(ws.Cells["T20"].GetValue<bool>(), true);
                replacedert.AreEqual(ws.Cells["T20"].GetValue<bool?>(), true);
                replacedert.AreEqual(ws.Cells["T20"].GetValue<DateTime>(), new DateTime(1899, 12, 30, 9, 30, 30));
                replacedert.AreEqual(ws.Cells["T20"].GetValue<DateTime?>(), new DateTime(1899, 12, 30, 9, 30, 30));
                replacedert.AreEqual(ws.Cells["T20"].GetValue<TimeSpan>(), new TimeSpan(693593, 9, 30, 30));
                replacedert.AreEqual(ws.Cells["T20"].GetValue<TimeSpan?>(), new TimeSpan(693593, 9, 30, 30));
                replacedert.AreEqual(ws.Cells["T20"].Text, "09:30:30");

                replacedert.AreEqual(ws.Cells["T24"].GetValue<string>(), 1.39618055555556d.ToString(CultureInfo.CurrentCulture));
                replacedert.AreEqual(ws.Cells["T24"].GetValue<int>(), 1);
                replacedert.AreEqual(ws.Cells["T24"].GetValue<int?>(), 1);
                replacedert.AreEqual(ws.Cells["T24"].GetValue<double>(), 1.39618055555556d);
                replacedert.AreEqual(ws.Cells["T24"].GetValue<double?>(), 1.39618055555556d);
                replacedert.AreEqual(ws.Cells["T24"].GetValue<decimal>(), 1.39618055555556m);
                replacedert.AreEqual(ws.Cells["T24"].GetValue<decimal?>(), 1.39618055555556m);
                replacedert.AreEqual(ws.Cells["T24"].GetValue<bool>(), true);
                replacedert.AreEqual(ws.Cells["T24"].GetValue<bool?>(), true);
                replacedert.AreEqual(ws.Cells["T24"].GetValue<DateTime>(), new DateTime(1899, 12, 31, 9, 30, 30));
                replacedert.AreEqual(ws.Cells["T24"].GetValue<DateTime?>(), new DateTime(1899, 12, 31, 9, 30, 30));
                replacedert.AreEqual(ws.Cells["T24"].GetValue<TimeSpan>(), new TimeSpan(693593, 33, 30, 30));
                replacedert.AreEqual(ws.Cells["T24"].GetValue<TimeSpan?>(), new TimeSpan(693593, 33, 30, 30));
                replacedert.AreEqual(ws.Cells["T24"].Text, "09:30:30");

                replacedert.AreEqual(ws.Cells["U20"].GetValue<string>(), "40179");
                replacedert.AreEqual(ws.Cells["U20"].GetValue<int>(), 40179);
                replacedert.AreEqual(ws.Cells["U20"].GetValue<int?>(), 40179);
                replacedert.AreEqual(ws.Cells["U20"].GetValue<double>(), 40179d);
                replacedert.AreEqual(ws.Cells["U20"].GetValue<double?>(), 40179d);
                replacedert.AreEqual(ws.Cells["U20"].GetValue<decimal>(), 40179m);
                replacedert.AreEqual(ws.Cells["U20"].GetValue<decimal?>(), 40179m);
                replacedert.AreEqual(ws.Cells["U20"].GetValue<bool>(), true);
                replacedert.AreEqual(ws.Cells["U20"].GetValue<bool?>(), true);
                replacedert.AreEqual(ws.Cells["U20"].GetValue<DateTime>(), new DateTime(2010, 1, 1));
                replacedert.AreEqual(ws.Cells["U20"].GetValue<DateTime?>(), new DateTime(2010, 1, 1));
                replacedert.AreEqual(ws.Cells["U20"].Text, "2010-01-01");

                replacedert.AreEqual(ws.Cells["V20"].GetValue<string>(), "102");
                replacedert.AreEqual(ws.Cells["V20"].GetValue<int>(), 102);
                replacedert.AreEqual(ws.Cells["V20"].GetValue<int?>(), 102);
                replacedert.AreEqual(ws.Cells["V20"].GetValue<double>(), 102d);
                replacedert.AreEqual(ws.Cells["V20"].GetValue<double?>(), 102d);
                replacedert.AreEqual(ws.Cells["V20"].GetValue<decimal>(), 102m);
                replacedert.AreEqual(ws.Cells["V20"].GetValue<decimal?>(), 102m);
                replacedert.AreEqual(ws.Cells["V20"].GetValue<bool>(), true);
                replacedert.AreEqual(ws.Cells["V20"].GetValue<bool?>(), true);
                replacedert.AreEqual(ws.Cells["V20"].GetValue<DateTime>(), new DateTime(1900, 4, 11));
                replacedert.AreEqual(ws.Cells["V20"].GetValue<DateTime?>(), new DateTime(1900, 4, 11));
                replacedert.AreEqual(ws.Cells["V20"].Text,
                    $"$102{CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator}00");

                replacedert.AreEqual(ws.Cells["W20"].GetValue<string>(), null);
                replacedert.AreEqual(ws.Cells["W20"].GetValue<int>(), 0);
                replacedert.AreEqual(ws.Cells["W20"].GetValue<int?>(), null);
                replacedert.AreEqual(ws.Cells["W20"].GetValue<double>(), 0d);
                replacedert.AreEqual(ws.Cells["W20"].GetValue<double?>(), null);
                replacedert.AreEqual(ws.Cells["W20"].GetValue<decimal>(), 0m);
                replacedert.AreEqual(ws.Cells["W20"].GetValue<decimal?>(), null);
                replacedert.AreEqual(ws.Cells["W20"].GetValue<bool>(), false);
                replacedert.AreEqual(ws.Cells["W20"].GetValue<bool?>(), null);
                replacedert.AreEqual(ws.Cells["W20"].GetValue<DateTime>(), DateTime.MinValue);
                replacedert.AreEqual(ws.Cells["W20"].GetValue<DateTime?>(), null);
                replacedert.AreEqual(ws.Cells["W20"].GetValue<TimeSpan>(), TimeSpan.Zero);
                replacedert.AreEqual(ws.Cells["W20"].GetValue<TimeSpan?>(), null);
                replacedert.AreEqual(ws.Cells["W20"].Text, string.Empty);

                replacedert.AreEqual(ws.Cells["Y20"].GetValue<string>(), "True");
                replacedert.AreEqual(ws.Cells["Y20"].GetValue<int>(), 1);
                replacedert.AreEqual(ws.Cells["Y20"].GetValue<int?>(), 1);
                replacedert.AreEqual(ws.Cells["Y20"].GetValue<double>(), 1d);
                replacedert.AreEqual(ws.Cells["Y20"].GetValue<double?>(), 1d);
                replacedert.AreEqual(ws.Cells["Y20"].GetValue<decimal>(), 1m);
                replacedert.AreEqual(ws.Cells["Y20"].GetValue<decimal?>(), 1m);
                replacedert.AreEqual(ws.Cells["Y20"].GetValue<bool>(), true);
                replacedert.AreEqual(ws.Cells["Y20"].GetValue<bool?>(), true);

                replacedert.IsInstanceOfType(GetValueException<DateTime>(ws.Cells["Y20"]), typeof(InvalidCastException));
                replacedert.IsInstanceOfType(GetValueException<DateTime?>(ws.Cells["Y20"]), typeof(InvalidCastException));
                replacedert.IsInstanceOfType(GetValueException<TimeSpan>(ws.Cells["Y20"]), typeof(InvalidCastException));
                replacedert.IsInstanceOfType(GetValueException<TimeSpan?>(ws.Cells["Y20"]), typeof(InvalidCastException));

                replacedert.AreEqual(ws.Cells["Z20"].GetValue<string>(), "Text2");
                replacedert.IsInstanceOfType(GetValueException<int>(         ws.Cells["Z20"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<int?>(        ws.Cells["Z20"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<double>(      ws.Cells["Z20"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<double?>(     ws.Cells["Z20"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<decimal>(     ws.Cells["Z20"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<decimal?>(    ws.Cells["Z20"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<bool>(        ws.Cells["Z20"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<bool?>(       ws.Cells["Z20"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<DateTime>(    ws.Cells["Z20"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<DateTime?>(   ws.Cells["Z20"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<TimeSpan>(    ws.Cells["Z20"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<TimeSpan?>(   ws.Cells["Z20"]), typeof(FormatException));
                replacedert.AreEqual(ws.Cells["Z20"].Text, "Text2");

                // even though value is set as integer, it is stored/exposed by EPPlust as double; feature?
                //replacedert.IsInstanceOfType(ws.Cells["X19"].Value, typeof(int));
                replacedert.AreEqual(ws.Cells["X19"].GetValue<string>(), "210");
                replacedert.AreEqual(ws.Cells["X19"].GetValue<int>(), 210);
                replacedert.AreEqual(ws.Cells["X19"].GetValue<int?>(), 210);
                replacedert.AreEqual(ws.Cells["X19"].GetValue<double>(), 210d);
                replacedert.AreEqual(ws.Cells["X19"].GetValue<double?>(), 210d);
                replacedert.AreEqual(ws.Cells["X19"].GetValue<decimal>(), 210m);
                replacedert.AreEqual(ws.Cells["X19"].GetValue<decimal?>(), 210m);
                replacedert.AreEqual(ws.Cells["X19"].GetValue<bool>(), true);
                replacedert.AreEqual(ws.Cells["X19"].GetValue<bool?>(), true);
                // double is converted to DateTime and TimeSpan, but value is meaningless
                replacedert.IsNull(GetValueException<DateTime>(    ws.Cells["X19"]));
                replacedert.IsNull(GetValueException<DateTime?>(   ws.Cells["X19"]));
                replacedert.IsNull(GetValueException<TimeSpan>(    ws.Cells["X19"]));
                replacedert.IsNull(GetValueException<TimeSpan?>(   ws.Cells["X19"]));
                replacedert.AreEqual(ws.Cells["X19"].Text, "210");

                replacedert.IsInstanceOfType(ws.Cells["AA19"].Value, typeof(string));
                replacedert.AreEqual(ws.Cells["AA19"].GetValue<string>(), "210");
                replacedert.AreEqual(ws.Cells["AA19"].GetValue<int>(), 210);
                replacedert.AreEqual(ws.Cells["AA19"].GetValue<int?>(), 210);
                replacedert.AreEqual(ws.Cells["AA19"].GetValue<double>(), 210d);
                replacedert.AreEqual(ws.Cells["AA19"].GetValue<double?>(), 210d);
                replacedert.AreEqual(ws.Cells["AA19"].GetValue<decimal>(), 210m);
                replacedert.AreEqual(ws.Cells["AA19"].GetValue<decimal?>(), 210m);
                replacedert.IsInstanceOfType(GetValueException<bool>(        ws.Cells["AA19"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<bool?>(       ws.Cells["AA19"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<DateTime>(    ws.Cells["AA19"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<DateTime?>(   ws.Cells["AA19"]), typeof(FormatException));
                replacedert.AreEqual(TimeSpan.FromDays(210), ws.Cells["AA19"].GetValue<TimeSpan>());
                replacedert.AreEqual(TimeSpan.FromDays(210), ws.Cells["AA19"].GetValue<TimeSpan?>());
                replacedert.AreEqual(ws.Cells["AA19"].Text, "210");

                // blank string produces null for nullable primitive types and conversion to non-nullable types throws FormatException
                replacedert.IsInstanceOfType(ws.Cells["AA18"].Value, typeof(string));
                replacedert.IsInstanceOfType(GetValueException<int>(         ws.Cells["AA18"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<double>(      ws.Cells["AA18"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<decimal>(     ws.Cells["AA18"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<bool>(        ws.Cells["AA18"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<DateTime>(    ws.Cells["AA18"]), typeof(FormatException));
                replacedert.IsInstanceOfType(GetValueException<TimeSpan>(    ws.Cells["AA18"]), typeof(FormatException));

                replacedert.IsNull(GetValueException<int?>(        ws.Cells["AA18"]));
                replacedert.IsNull(GetValueException<double?>(     ws.Cells["AA18"]));
                replacedert.IsNull(GetValueException<decimal?>(    ws.Cells["AA18"]));
                replacedert.IsNull(GetValueException<bool?>(       ws.Cells["AA18"]));
                replacedert.IsNull(GetValueException<DateTime?>(   ws.Cells["AA18"]));
                replacedert.IsNull(GetValueException<TimeSpan?>(   ws.Cells["AA18"]));
                replacedert.AreEqual(ws.Cells["AA18"].Text, " ");
            }
            instream.Close();
        }

19 Source : AsciiFormatter.cs
with Apache License 2.0
from AppMetrics

private static void WriteSimpleValue(StreamWriter writer, string family, double value, IEnumerable<LabelPair> labels, string namePostfix = null)
        {
            writer.Write(family);
            if (namePostfix != null)
            {
                writer.Write(namePostfix);
            }

            bool any = false;
            foreach (var l in labels)
            {
                writer.Write(any ? ',' : '{');

                writer.Write(l.name);
                writer.Write("=\"");
                writer.Write(l.value);
                writer.Write('"');

                any = true;
            }

            if (any)
            {
                writer.Write('}');
            }

            writer.Write(' ');
            writer.WriteLine(value.ToString(CultureInfo.InvariantCulture));
        }

19 Source : LineProtocolSyntax.cs
with Apache License 2.0
from AppMetrics

private static string FormatTimespan(object ts) { return ((TimeSpan)ts).TotalMilliseconds.ToString(CultureInfo.InvariantCulture); }

19 Source : AsciiFormatter.cs
with Apache License 2.0
from AppMetrics

private static string SimpleValue(string family, double value, IEnumerable<LabelPair> labels, string namePostfix = null)
        {
            return string.Format("{0} {1}", WithLabels(family + (namePostfix ?? string.Empty), labels), value.ToString(CultureInfo.InvariantCulture));
        }

19 Source : TransferFunction.cs
with MIT License
from ar1st0crat

public void ToCsv(Stream stream, char delimiter = ',')
        {
            using (var writer = new StreamWriter(stream))
            {
                var content = string.Join(delimiter.ToString(), Numerator.Select(k => k.ToString(CultureInfo.InvariantCulture)));
                writer.WriteLine(content);

                content = string.Join(delimiter.ToString(), Denominator.Select(k => k.ToString(CultureInfo.InvariantCulture)));
                writer.WriteLine(content);
            }
        }

19 Source : MetricLogEntry.cs
with MIT License
from arcus-azure

public override string ToString()
        {
            string contextFormatted = $"{{{String.Join("; ", Context.Select(item => $"[{item.Key}, {item.Value}]"))}}}";
            return $"{MetricName}: {MetricValue.ToString(CultureInfo.InvariantCulture)} at {Timestamp} (Context: {contextFormatted})";
        }

19 Source : Copy_selected_node.cs
with GNU Affero General Public License v3.0
from arklumpus

public static async void PerformAction(int actionIndex, TreeNode selection, MainWindow window, InstanceStateData stateData)
        {
            if (actionIndex <= 0)
            {
                string text = NWKA.WriteTree(selection, true);
                if (!text.EndsWith(";"))
                {
                    text += ";";
                }
                _ = Avalonia.Application.Current.Clipboard.SetTextAsync(text);
            }
            else if (actionIndex == 1)
            {
                List<TreeNode> selectedTips = window.SelectedNode.GetLeaves();

                ChildWindow attributeSelectionWindow = new ChildWindow() { FontFamily = window.FontFamily, FontSize = window.FontSize, Icon = window.Icon, Width = 350, Height = 190, replacedle = "Select attribute...", WindowStartupLocation = WindowStartupLocation.CenterOwner, Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(231, 231, 231)), CanMaximizeMinimize = false };

                Grid grd = new Grid() { Margin = new Avalonia.Thickness(10) };
                attributeSelectionWindow.Content = grd;
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                grd.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                {
					Grid header = new Grid();
					header.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
					header.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
					
					header.Children.Add(new DPIAwareBox(GetIcon) { Width = 32, Height = 32, Margin = new Avalonia.Thickness(0, 0, 10, 0) });
					
                    TextBlock blk = new TextBlock() { Text = "Copy attribute at tips", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Avalonia.Thickness(0, 0, 0, 10), FontSize = 16, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(0, 114, 178)) };
                    Grid.SetColumn(blk, 1);
					header.Children.Add(blk);
					
					Grid.SetColumnSpan(header, 2);
                    grd.Children.Add(header);
                }

                {
                    TextBlock blk = new TextBlock() { Text = selectedTips.Count + " tips selected.", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, Margin = new Avalonia.Thickness(0, 5, 0, 10), FontSize = 13, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(102, 102, 102)) };
                    Grid.SetColumnSpan(blk, 2);
                    Grid.SetRow(blk, 1);
                    grd.Children.Add(blk);
                }

                {
                    TextBlock blk = new TextBlock() { Text = "Select attribute to copy:", FontSize = 14, Margin = new Avalonia.Thickness(0, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    Grid.SetRow(blk, 2);
                    grd.Children.Add(blk);
                }

                Grid buttonGrid = new Grid();
                Grid.SetColumnSpan(buttonGrid, 2);

                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                Button okButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = new TextBlock() { Text = "OK", FontSize = 14, Foreground = Avalonia.Media.Brushes.Black } };
                okButton.Clreplacedes.Add("SideBarButton");
                Grid.SetColumn(okButton, 1);
                buttonGrid.Children.Add(okButton);

                Button cancelButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = new TextBlock() { Text = "Cancel", FontSize = 14, Foreground = Avalonia.Media.Brushes.Black }, Foreground = Avalonia.Media.Brushes.Black };
                cancelButton.Clreplacedes.Add("SideBarButton");
                Grid.SetColumn(cancelButton, 3);
                buttonGrid.Children.Add(cancelButton);

                Grid.SetRow(buttonGrid, 4);
                grd.Children.Add(buttonGrid);

                bool result = false;

                okButton.Click += (s, e) =>
                {
                    result = true;
                    attributeSelectionWindow.Close();
                };

                cancelButton.Click += (s, e) =>
                {
                    attributeSelectionWindow.Close();
                };

                HashSet<string> attributes = new HashSet<string>();

                foreach (TreeNode node in selectedTips)
                {
                    foreach (KeyValuePair<string, object> attribute in node.Attributes)
                    {
                        attributes.Add(attribute.Key);
                    }
                }

                List<string> attributesList = attributes.ToList();

                ComboBox attributeBox = new ComboBox() { Items = attributesList, SelectedIndex = Math.Max(attributesList.IndexOf("Name"), 0), Margin = new Avalonia.Thickness(5, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, MinWidth = 150, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Stretch };
                Grid.SetRow(attributeBox, 2);
                Grid.SetColumn(attributeBox, 1);
                grd.Children.Add(attributeBox);


                await attributeSelectionWindow.ShowDialog2(window);

                if (result)
                {
                    string attributeName = attributesList[attributeBox.SelectedIndex];

                    List<string> attributeValues = new List<string>();

                    if (attributeName != null)
                    {
                        foreach (TreeNode node in selectedTips)
                        {
                            if (node.Attributes.TryGetValue(attributeName, out object attributeValue))
                            {
                                if (attributeValue is string attributeString)
                                {
                                    attributeValues.Add(attributeString);
                                }
                                else if (attributeValue is double attributeDouble)
                                {
                                    attributeValues.Add(attributeDouble.ToString(System.Globalization.CultureInfo.InvariantCulture));
                                }
                            }
                        }
                    }

                    if (attributeValues.Count > 0)
                    {
                        _ = Avalonia.Application.Current.Clipboard.SetTextAsync(attributeValues.Aggregate((a, b) => a + "\n" + b));
                    }
                }
            }
            else if (actionIndex == 2)
            {
                List<TreeNode> selectedTips = window.SelectedNode.GetChildrenRecursive();

                ChildWindow attributeSelectionWindow = new ChildWindow() { FontFamily = window.FontFamily, FontSize = window.FontSize, Icon = window.Icon, Width = 350, Height = 190, replacedle = "Select attribute...", WindowStartupLocation = WindowStartupLocation.CenterOwner, Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(231, 231, 231)), CanMaximizeMinimize = false };

                Grid grd = new Grid() { Margin = new Avalonia.Thickness(10) };
                attributeSelectionWindow.Content = grd;
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                grd.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                {
					Grid header = new Grid();
					header.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
					header.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
					
					header.Children.Add(new DPIAwareBox(GetIcon) { Width = 32, Height = 32, Margin = new Avalonia.Thickness(0, 0, 10, 0) });
					
                    TextBlock blk = new TextBlock() { Text = "Copy attribute at nodes", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Avalonia.Thickness(0, 0, 0, 10), FontSize = 16, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(0, 114, 178)) };
                    Grid.SetColumn(blk, 1);
					header.Children.Add(blk);
					
					Grid.SetColumnSpan(header, 2);
                    grd.Children.Add(header);
                }

                {
                    TextBlock blk = new TextBlock() { Text = selectedTips.Count + " nodes selected.", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, Margin = new Avalonia.Thickness(0, 5, 0, 10), FontSize = 13, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(102, 102, 102)) };
                    Grid.SetColumnSpan(blk, 2);
                    Grid.SetRow(blk, 1);
                    grd.Children.Add(blk);
                }

                {
                    TextBlock blk = new TextBlock() { Text = "Select attribute to copy:", FontSize = 14, Margin = new Avalonia.Thickness(0, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    Grid.SetRow(blk, 2);
                    grd.Children.Add(blk);
                }

                Grid buttonGrid = new Grid();
                Grid.SetColumnSpan(buttonGrid, 2);

                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                Button okButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = new TextBlock() { Text = "OK", FontSize = 14, Foreground = Avalonia.Media.Brushes.Black } };
                okButton.Clreplacedes.Add("SideBarButton");
                Grid.SetColumn(okButton, 1);
                buttonGrid.Children.Add(okButton);

                Button cancelButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = new TextBlock() { Text = "Cancel", FontSize = 14, Foreground = Avalonia.Media.Brushes.Black }, Foreground = Avalonia.Media.Brushes.Black };
                cancelButton.Clreplacedes.Add("SideBarButton");
                Grid.SetColumn(cancelButton, 3);
                buttonGrid.Children.Add(cancelButton);

                Grid.SetRow(buttonGrid, 4);
                grd.Children.Add(buttonGrid);

                bool result = false;

                okButton.Click += (s, e) =>
                {
                    result = true;
                    attributeSelectionWindow.Close();
                };

                cancelButton.Click += (s, e) =>
                {
                    attributeSelectionWindow.Close();
                };

                HashSet<string> attributes = new HashSet<string>();

                foreach (TreeNode node in selectedTips)
                {
                    foreach (KeyValuePair<string, object> attribute in node.Attributes)
                    {
                        attributes.Add(attribute.Key);
                    }
                }

                List<string> attributesList = attributes.ToList();

                ComboBox attributeBox = new ComboBox() { Items = attributesList, SelectedIndex = Math.Max(attributesList.IndexOf("Name"), 0), Margin = new Avalonia.Thickness(5, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, MinWidth = 150, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Stretch };
                Grid.SetRow(attributeBox, 2);
                Grid.SetColumn(attributeBox, 1);
                grd.Children.Add(attributeBox);


                await attributeSelectionWindow.ShowDialog2(window);

                if (result)
                {
                    string attributeName = attributesList[attributeBox.SelectedIndex];

                    List<string> attributeValues = new List<string>();

                    if (attributeName != null)
                    {
                        foreach (TreeNode node in selectedTips)
                        {
                            if (node.Attributes.TryGetValue(attributeName, out object attributeValue))
                            {
                                if (attributeValue is string attributeString)
                                {
                                    attributeValues.Add(attributeString);
                                }
                                else if (attributeValue is double attributeDouble)
                                {
                                    attributeValues.Add(attributeDouble.ToString(System.Globalization.CultureInfo.InvariantCulture));
                                }
                            }
                        }
                    }

                    if (attributeValues.Count > 0)
                    {
                        _ = Avalonia.Application.Current.Clipboard.SetTextAsync(attributeValues.Aggregate((a, b) => a + "\n" + b));
                    }
                }
            }
        }

19 Source : Lasso_selection.cs
with GNU Affero General Public License v3.0
from arklumpus

public static void PerformAction(int actionIndex, MainWindow window, InstanceStateData stateData)
        {
            if (window.TransformedTree == null || window.PlottingActions.Count == 0 || (stateData.Tags.TryGetValue("a04dcde8-75e2-43b5-a45b-e78ec8fd1ab6", out object lreplacedoTag) && (bool)lreplacedoTag))
            {
                return;
            }
            stateData.Tags["a04dcde8-75e2-43b5-a45b-e78ec8fd1ab6"] = true;

            Avalonia.Controls.PanAndZoom.ZoomBorder zom = window.FindControl<Avalonia.Controls.PanAndZoom.ZoomBorder>("PlotContainer");

            Grid lreplacedoGrid = new Grid() { ClipToBounds = true };

            lreplacedoGrid.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
            lreplacedoGrid.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));

            lreplacedoGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
            lreplacedoGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
            lreplacedoGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
            lreplacedoGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

            StackPanel pnl = new StackPanel() { Orientation = Avalonia.Layout.Orientation.Horizontal, Margin = new Avalonia.Thickness(0, 5, 0, 0) };
            pnl.Children.Add(new TextBlock() { Text = "Lreplacedo selection currently active", VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 13 });
            HelpButton help = new HelpButton() { Margin = new Avalonia.Thickness(10, 0, 0, 0) };
            AvaloniaBugFixes.SetToolTip(help, HelpText);
            help.PointerPressed += async (s, e) =>
            {
                HelpWindow helpWindow = new HelpWindow(Modules.LoadedModulesMetadata[Id].BuildReadmeMarkdown(), Id);
                await helpWindow.ShowDialog2(window);
            };
            pnl.Children.Add(help);
            Grid.SetColumn(pnl, 1);
            lreplacedoGrid.Children.Add(pnl);

            Button closeButton = new Button() { Margin = new Avalonia.Thickness(5, 5, 10, 0), Width = 32, Height = 32, Background = Avalonia.Media.Brushes.Transparent, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Top, Content = new Avalonia.Controls.Shapes.Path() { Width = 10, Height = 10, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Data = Avalonia.Media.Geometry.Parse("M0,0 L10,10 M10,0 L0,10"), StrokeThickness = 2 } };
            closeButton.Clreplacedes.Add("SideBarButton");
            Grid.SetColumn(closeButton, 2);
            lreplacedoGrid.Children.Add(closeButton);

            Canvas separator = new Canvas() { Height = 1, Margin = new Avalonia.Thickness(5, 5, 5, 1), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Bottom };
            separator.Clreplacedes.Add("RibbonSeparator");
            Grid.SetColumnSpan(separator, 4);
            Grid.SetRow(separator, 1);
            lreplacedoGrid.Children.Add(separator);

            lreplacedoGrid.MaxHeight = 0;

            Avalonia.Animation.Transitions openCloseTransitions = new Avalonia.Animation.Transitions();
            openCloseTransitions.Add(new Avalonia.Animation.DoubleTransition() { Property = Avalonia.Controls.Shapes.Path.MaxHeightProperty, Duration = TimeSpan.FromMilliseconds(150) });

            lreplacedoGrid.Transitions = openCloseTransitions;
            window.FindControl<StackPanel>("UpperBarContainer").Children.Add(lreplacedoGrid);
            window.SetSelection(null);
            lreplacedoGrid.MaxHeight = 80;

            Canvas can = new Canvas() { Width = window.FindControl<Canvas>("ContainerCanvas").Width, Height = window.FindControl<Canvas>("ContainerCanvas").Height };

            Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () =>
            {
                await System.Threading.Tasks.Task.Delay(150);
                lreplacedoGrid.Transitions = null;
                lreplacedoGrid.MaxHeight = double.PositiveInfinity;
            });

            closeButton.Click += async (s, e) =>
            {
                lreplacedoGrid.MaxHeight = lreplacedoGrid.Bounds.Height;
                lreplacedoGrid.Transitions = openCloseTransitions;
                lreplacedoGrid.MaxHeight = 0;

                await System.Threading.Tasks.Task.Delay(150);
                window.FindControl<StackPanel>("UpperBarContainer").Children.Remove(lreplacedoGrid);

                window.FindControl<Canvas>("ContainerCanvas").Children.Remove(can);

                stateData.Tags["a04dcde8-75e2-43b5-a45b-e78ec8fd1ab6"] = false;
            };

            window.SetSelection(null);

            can.Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(255, 255, 255), 0);

            window.FindControl<Canvas>("ContainerCanvas").Children.Add(can);

            List<Point> selectionPoints = new List<Point>();

            bool globalIsClosed = false;
            Avalonia.Controls.Shapes.Path globalPath = null;

            void pointerPressed(object sender, Avalonia.Input.PointerPressedEventArgs e)
            {
                Avalonia.Point pt = e.GetCurrentPoint(can).Position;

                bool isClosed = selectionPoints.Count > 0 && ((pt.X == selectionPoints[^1].X && pt.Y == selectionPoints[^1].Y) || Math.Sqrt((pt.X - selectionPoints[0].X) * (pt.X - selectionPoints[0].X) + (pt.Y - selectionPoints[0].Y) * (pt.Y - selectionPoints[0].Y)) * zom.ZoomX <= 25);


                if (!isClosed)
                {
                    selectionPoints.Add(new Point(pt.X, pt.Y));
                }

                Page pg = new Page(can.Width, can.Height);

                if (selectionPoints.Count > 1)
                {
                    GraphicsPath pth = new GraphicsPath();

                    for (int i = 0; i < selectionPoints.Count; i++)
                    {
                        if (i == 0)
                        {
                            pth.MoveTo(selectionPoints[i]);
                        }
                        else
                        {
                            pth.LineTo(selectionPoints[i]);
                        }
                    }

                    if (isClosed)
                    {
                        pth.Close();
                    }

                    pg.Graphics.StrokePath(pth, window.SelectionColour, lineWidth: 5 / zom.ZoomX, lineCap: LineCaps.Round, lineJoin: LineJoins.Round, tag: "selectionOutline");
                }
                else if (selectionPoints.Count == 1)
                {
                    pg.Graphics.StrokePath(new GraphicsPath().MoveTo(selectionPoints[0]).LineTo(selectionPoints[0]), window.SelectionColour, lineWidth: 5 / zom.ZoomX, lineCap: LineCaps.Round, lineJoin: LineJoins.Round, tag: "selectionOutline");
                }



                can.Children.Clear();
                can.Children.Add(pg.PaintToCanvas(new Dictionary<string, Delegate>()
                {
                    {
                        "selectionOutline",
                        new Action<Avalonia.Controls.Shapes.Path>((Avalonia.Controls.Shapes.Path path) =>
                        {
                            void zoomHandler(object sender, Avalonia.AvaloniaPropertyChangedEventArgs e)
                            {
                                if (e.Property == Avalonia.Controls.PanAndZoom.ZoomBorder.ZoomXProperty)
                                {
                                    path.StrokeThickness = 5 / zom.ZoomX;
                                }
                            };

                            if (isClosed)
                            {
                                globalIsClosed = isClosed;
                                globalPath = path;
                            }

                            zom.PropertyChanged += zoomHandler;

                            can.DetachedFromLogicalTree += (s, e) =>
                            {
                                zom.PropertyChanged -= zoomHandler;
                            };
                        })
                    }
                }));
            };



            void pointerReleased(object sender, Avalonia.Input.PointerReleasedEventArgs e)
            {
                bool isClosed = globalIsClosed;
                Avalonia.Controls.Shapes.Path path = globalPath;

                if (isClosed)
                {
                    SkiaSharp.SKColor selectionChildColor = window.SelectionChildSKColor;
                    List<string> tipsInside = new List<string>();
                    List<TreeNode> nodesInside = new List<TreeNode>();
                    int tipCount = 0;

                    foreach (KeyValuePair<string, Point> kvp in window.Coordinates)
                    {
                        if (path.RenderedGeometry.FillContains(new Avalonia.Point(kvp.Value.X - window.PlotOrigin.X + 10, kvp.Value.Y - window.PlotOrigin.Y + 10)))
                        {
                            TreeNode node = window.TransformedTree.GetNodeFromId(kvp.Key);
                            if (node != null)
                            {
                                nodesInside.Add(node);

                                if (node.Children.Count == 0)
                                {
                                    tipCount++;
                                }
                            }
                        }
                    }

                    Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () =>
                    {
                        foreach (TreeNode node in nodesInside)
                        {
                            foreach ((double, SKRenderAction) pth in MainWindow.FindPaths(window.FullSelectionCanvas, node.Id))
                            {
                                window.ChangeActionColour(pth.Item2, selectionChildColor);
                            }
                        }

                        (int nodeIndex, string attributeName) = await ShowAttributeSelectionWindow(nodesInside, tipCount, window, window.TransformedTree);

                        if (attributeName != null)
                        {
                            foreach (TreeNode node in nodesInside)
                            {
                                if (nodeIndex == 2 || (nodeIndex == 1 && node.Children.Count == 0) || (nodeIndex == 0 && node.Children.Count > 0))
                                {
                                    if (node.Attributes.TryGetValue(attributeName, out object attributeValue))
                                    {
                                        if (attributeValue is string attributeString)
                                        {
                                            tipsInside.Add(attributeString);
                                        }
                                        else if (attributeValue is double attributeDouble)
                                        {
                                            tipsInside.Add(attributeDouble.ToString(System.Globalization.CultureInfo.InvariantCulture));
                                        }
                                    }
                                }
                            }
                        }

                        if (tipsInside.Count > 0)
                        {
                            await Avalonia.Application.Current.Clipboard.SetTextAsync(tipsInside.Aggregate((a, b) => a + "\n" + b));
                        }

                        lreplacedoGrid.MaxHeight = lreplacedoGrid.Bounds.Height;
                        lreplacedoGrid.Transitions = openCloseTransitions;
                        lreplacedoGrid.MaxHeight = 0;

                        window.HasPointerDoneSomething = true;
                        e.Handled = true;

                        path.Transitions = new Avalonia.Animation.Transitions();
                        path.Transitions.Add(new Avalonia.Animation.DoubleTransition() { Property = Avalonia.Controls.Shapes.Path.OpacityProperty, Duration = TimeSpan.FromMilliseconds(500) });
                        path.Opacity = 0;

                        await Task.Delay(550);
                        window.FindControl<StackPanel>("UpperBarContainer").Children.Remove(lreplacedoGrid);

                        window.FindControl<Canvas>("ContainerCanvas").Children.Remove(can);

                        stateData.Tags["a04dcde8-75e2-43b5-a45b-e78ec8fd1ab6"] = false;

                        can.PointerPressed -= pointerPressed;
                        can.PointerReleased -= pointerReleased;
                    });
                }
            }

            can.PointerPressed += pointerPressed;
            can.PointerReleased += pointerReleased;
        }

19 Source : Set_up_stochastic_mapping_attachment.cs
with GNU Affero General Public License v3.0
from arklumpus

public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
        {
            Attachment attachment = (Attachment)parameterValues["Attachment:"];

            if (attachment == null)
            {
                return;
            }

            attachment.Stream.Seek(attachment.StreamStart, SeekOrigin.Begin);

            TreeCollection trees = new TreeCollection(OpenFile(attachment.Stream, progressAction));

            InstanceStateData stateData = (InstanceStateData)parameterValues["StateData"];

            bool isClockLike = (bool)parameterValues["Treat trees as clock-like"];

            double resolution = (double)parameterValues["Resolution:"];
            int resolutionType = (int)parameterValues["Resolution unit:"];

            double actualResolution = resolution;

            switch (resolutionType)
            {
                case 0:
                    break;
                case 1:
                    actualResolution = resolution * tree.LongestDownstreamLength();
                    break;
                case 2:
                    break;
            }

            Dictionary<string, TreeNode> nodeCorresps = new Dictionary<string, TreeNode>();

            foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
            {
                nodeCorresps[node.GetLeafNames().OrderBy(a => a).Aggregate((a, b) => a + "," + b)] = node;
            }

            Dictionary<string, List<(double left, double right, SimmapBranchState[] states)>> branchStates = new Dictionary<string, List<(double, double, SimmapBranchState[])>>(nodeCorresps.Count);

            foreach (KeyValuePair<string, TreeNode> kvp in nodeCorresps)
            {
                branchStates.Add(kvp.Value.Id, new List<(double start, double end, SimmapBranchState[] states)>());
            }

            HashSet<string>[] states = null;

            int sampleIndex = 0;

            foreach (TreeNode sample in trees)
            {
                foreach (TreeNode node in sample.GetChildrenRecursiveLazy())
                {
                    SimmapBranchState[] nodeStates = null;

                    if (node.Attributes.TryGetValue("States", out object statesObj) && statesObj is string statesString)
                    {
                        try
                        {
                            nodeStates = System.Text.Json.JsonSerializer.Deserialize<SimmapBranchState[]>(statesString);
                        }
                        catch { }
                    }

                    if (nodeStates != null)
                    {
                        string leafString = node.GetLeafNames().OrderBy(a => a).Aggregate((a, b) => a + "," + b);

                        if (nodeCorresps.TryGetValue(leafString, out TreeNode corresp))
                        {
                            if (states == null)
                            {
                                states = new HashSet<string>[nodeStates[0].States.Length];
                                for (int i = 0; i < states.Length; i++)
                                {
                                    states[i] = new HashSet<string>();
                                }
                            }

                            for (int i = 0; i < nodeStates.Length; i++)
                            {
                                for (int j = 0; j < nodeStates[i].States.Length; j++)
                                {
                                    states[j].Add(nodeStates[i].States[j]);
                                }
                            }

                            double left;
                            double right;

                            if (!isClockLike)
                            {
                                right = node.UpstreamLength();
                                left = right - node.Length;
                            }
                            else
                            {
                                right = node.LongestDownstreamLength();
                                left = right + node.Length;
                            }

                            branchStates[corresp.Id].Add((left, right, nodeStates));
                        }
                    }
                }

                sampleIndex++;

                progressAction(0.5 + (double)sampleIndex / trees.Count * 0.25);
            }

            List<List<string>> allPossibleStates = GetAllPossibleStates(states);

            Dictionary<string, (double samplePosPerc, double[] stateProbs)[]> preparedStates = new Dictionary<string, (double, double[])[]>();

            Dictionary<string, double[]> conditionedPosteriors = new Dictionary<string, double[]>();
            Dictionary<string, double[]> meanPosteriors = new Dictionary<string, double[]>();

            int nodeIndex = 0;

            List<(string, List<int>)> NaNSamples = new List<(string, List<int>)>();
            List<string> missingConditionedPosteriors = new List<string>();

            foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
            {
                if (!double.IsNaN(node.Length) && node.Length > 0)
                {
                    double left;
                    double right;

                    if (!isClockLike)
                    {
                        right = node.UpstreamLength();
                        left = right - node.Length;
                    }
                    else
                    {
                        right = node.LongestDownstreamLength();
                        left = right + node.Length;
                    }

                    if (resolutionType == 2)
                    {
                        actualResolution = resolution * node.Length;
                    }

                    List<(double left, double right, SimmapBranchState[] states)> observedStates = branchStates[node.Id];

                    double[] meanPosterior = new double[allPossibleStates.Count];

                    for (int i = 0; i < observedStates.Count; i++)
                    {
                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            if (allPossibleStates[j].SequenceEqual(observedStates[i].states[0].States))
                            {
                                meanPosterior[j]++;
                                break;
                            }
                        }
                    }

                    if (observedStates.Count > 0)
                    {
                        for (int i = 0; i < meanPosterior.Length; i++)
                        {
                            meanPosterior[i] /= observedStates.Count;
                        }
                    }

                    {
                        string state = "{";

                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + meanPosterior[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                            if (j < allPossibleStates.Count - 1)
                            {
                                state += ",";
                            }
                        }

                        state += "}";

                        meanPosteriors[node.Id] = meanPosterior;
                        node.Attributes["MeanPosteriors"] = state;
                    }


                    List<(double samplePosPerc, double[] stateProbs)> preparedBranchStates = new List<(double samplePosPerc, double[] stateProbs)>();
                    List<int> NaNs = new List<int>();

                    for (int i = 0; i < Math.Ceiling(Math.Abs(right - left) / actualResolution) + 1; i++)
                    {
                        double samplingTime;
                        if (!isClockLike)
                        {
                            samplingTime = Math.Min(left + actualResolution * i, right);
                        }
                        else
                        {
                            samplingTime = Math.Max(left - actualResolution * i, right);
                        }

                        double perc = (samplingTime - left) / (right - left);



                        int[] counts = new int[allPossibleStates.Count];

                        for (int j = 0; j < observedStates.Count; j++)
                        {
                            string[] sample = SampleBranch(samplingTime, observedStates[j].left, observedStates[j].right, observedStates[j].states);

                            if (sample != null)
                            {
                                for (int k = 0; k < allPossibleStates.Count; k++)
                                {
                                    if (sample.SequenceEqual(allPossibleStates[k]))
                                    {
                                        counts[k]++;
                                        break;
                                    }
                                }
                            }
                        }

                        double total = counts.Sum();

                        double[] probs = new double[counts.Length];


                        if (total > 0)
                        {
                            for (int j = 0; j < probs.Length; j++)
                            {
                                probs[j] = counts[j] / total;
                            }
                        }
                        else
                        {
                            NaNs.Add(i);
                        }

                        preparedBranchStates.Add((perc, probs));

                        if (samplingTime == right)
                        {
                            if (total > 0)
                            {
                                string state = "{";

                                for (int j = 0; j < allPossibleStates.Count; j++)
                                {
                                    state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + probs[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                                    if (j < allPossibleStates.Count - 1)
                                    {
                                        state += ",";
                                    }
                                }

                                state += "}";

                                node.Attributes["ConditionedPosteriors"] = state;
                                conditionedPosteriors[node.Id] = probs;
                            }
                            else
                            {
                                missingConditionedPosteriors.Add(node.Id);
                            }

                            break;
                        }
                    }

                    if (NaNs.Count > 0)
                    {
                        NaNs.Sort();
                        NaNSamples.Add((node.Id, NaNs));
                    }

                    preparedStates[node.Id] = preparedBranchStates.ToArray();
                }
                else if (node.Parent == null && node.Children.Count > 0)
                {
                    List<(double left, double right, SimmapBranchState[] states)> observedStates = branchStates[node.Children[0].Id];

                    double[] meanPosterior = new double[allPossibleStates.Count];

                    for (int i = 0; i < observedStates.Count; i++)
                    {
                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            if (allPossibleStates[j].SequenceEqual(observedStates[i].states[observedStates[i].states.Length - 1].States))
                            {
                                meanPosterior[j]++;
                                break;
                            }
                        }
                    }

                    if (observedStates.Count > 0)
                    {
                        for (int i = 0; i < meanPosterior.Length; i++)
                        {
                            meanPosterior[i] /= observedStates.Count;
                        }
                    }

                    {
                        string state = "{";

                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + meanPosterior[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                            if (j < allPossibleStates.Count - 1)
                            {
                                state += ",";
                            }
                        }

                        state += "}";

                        node.Attributes["MeanPosteriors"] = state;
                        node.Attributes["ConditionedPosteriors"] = state;

                        conditionedPosteriors[node.Id] = meanPosterior;
                    }
                }

                nodeIndex++;
                progressAction(0.75 + (double)nodeIndex / nodeCorresps.Count * 0.25);
            }

            for (int i = 0; i < NaNSamples.Count; i++)
            {
                (double samplePosPerc, double[] stateProbs)[] samples = preparedStates[NaNSamples[i].Item1];
                TreeNode node = tree.GetNodeFromId(NaNSamples[i].Item1);

                if (NaNSamples[i].Item2.Count == samples.Length)
                {
                    if (missingConditionedPosteriors.Contains(node.Id))
                    {
                        conditionedPosteriors[node.Id] = meanPosteriors[node.Id];
                    }

                    for (int j = 0; j < samples.Length; j++)
                    {
                        samples[j] = (samples[j].samplePosPerc, conditionedPosteriors[node.Id]);
                    }
                }
                else
                {
                    List<int> missingSamplesStart = new List<int>();
                    List<int> missingSamplesEnd = new List<int>();

                    for (int j = 0; j < NaNSamples[i].Item2.Count; j++)
                    {
                        if (NaNSamples[i].Item2[j] == j)
                        {
                            missingSamplesStart.Add(NaNSamples[i].Item2[j]);
                        }

                        if (NaNSamples[i].Item2[NaNSamples[i].Item2.Count - 1 - j] == samples.Length - 1 - j)
                        {
                            missingSamplesEnd.Add(NaNSamples[i].Item2[NaNSamples[i].Item2.Count - 1 - j]);
                        }
                    }

                    if (missingSamplesStart.Count > 0)
                    {
                        double[] left = null;
                        double[] right = null;

                        // Parent
                        if (!missingConditionedPosteriors.Contains(node.Parent.Id))
                        {
                            left = conditionedPosteriors[node.Parent.Id];
                        }
                        else
                        {
                            (double samplePosPerc, double[] stateProbs)[] parentSamples = preparedStates[node.Parent.Id];

                            for (int j = parentSamples.Length - 1; j >= 0; j--)
                            {
                                if (parentSamples[j].stateProbs.Sum() > 0)
                                {
                                    left = parentSamples[j].stateProbs;
                                    break;
                                }
                            }
                        }

                        // First sample
                        for (int j = 0; j < samples.Length; j++)
                        {
                            if (samples[j].stateProbs.Sum() > 0)
                            {
                                right = samples[j].stateProbs;
                                break;
                            }
                        }

                        if (left != null && right != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                double[] average = new double[left.Length];

                                for (int k = 0; k < left.Length; k++)
                                {
                                    average[k] = left[k] * (1 - (double)(j + 1) / (missingSamplesStart.Count + 1)) + right[k] * (double)(j + 1) / (missingSamplesStart.Count + 1);
                                }

                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, average);
                            }
                        }
                        else if (right != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, right);
                            }
                        }
                        else if (left != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, left);
                            }
                        }
                    }


                    if (missingSamplesEnd.Count > 0)
                    {
                        double[] left = null;
                        List<double[]> right = new List<double[]>();

                        // Children
                        for (int k = 0; k < node.Children.Count; k++)
                        {
                            if (!missingConditionedPosteriors.Contains(node.Children[k].Id))
                            {
                                right.Add(conditionedPosteriors[node.Children[k].Id]);
                            }
                            else
                            {
                                (double samplePosPerc, double[] stateProbs)[] childSamples = preparedStates[node.Children[k].Id];

                                for (int j = 0; j < childSamples.Length; j++)
                                {
                                    if (childSamples[j].stateProbs.Sum() > 0)
                                    {
                                        right.Add(childSamples[j].stateProbs);
                                        break;
                                    }
                                }
                            }
                        }

                        // Last sample
                        for (int j = samples.Length - 1; j >= 0; j--)
                        {
                            if (samples[j].stateProbs.Sum() > 0)
                            {
                                left = samples[j].stateProbs;
                                break;
                            }
                        }

                        if (left != null && right.Count > 0)
                        {
                            double[] rightAverage = new double[right[0].Length];

                            for (int j = 0; j < right.Count; j++)
                            {
                                for (int k = 0; k < rightAverage.Length; k++)
                                {
                                    rightAverage[k] += right[j][k];
                                }
                            }

                            for (int k = 0; k < rightAverage.Length; k++)
                            {
                                rightAverage[k] /= right.Count;
                            }

                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                double[] average = new double[left.Length];

                                for (int k = 0; k < left.Length; k++)
                                {
                                    average[k] = rightAverage[k] * (1 - (double)(j + 1) / (missingSamplesEnd.Count + 1)) + left[k] * (double)(j + 1) / (missingSamplesEnd.Count + 1);
                                }

                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, average);
                            }
                        }
                        else if (right.Count > 0)
                        {
                            double[] rightAverage = new double[right[0].Length];

                            for (int j = 0; j < right.Count; j++)
                            {
                                for (int k = 0; k < rightAverage.Length; k++)
                                {
                                    rightAverage[k] += right[j][k];
                                }
                            }

                            for (int k = 0; k < rightAverage.Length; k++)
                            {
                                rightAverage[k] /= right.Count;
                            }

                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, rightAverage);
                            }
                        }
                        else if (left != null)
                        {
                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, left);
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < missingConditionedPosteriors.Count; i++)
            {
                double[] probs = preparedStates[missingConditionedPosteriors[i]].Last().stateProbs;

                string state = "{";

                for (int j = 0; j < allPossibleStates.Count; j++)
                {
                    state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + probs[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                    if (j < allPossibleStates.Count - 1)
                    {
                        state += ",";
                    }
                }

                state += "}";

                tree.GetNodeFromId(missingConditionedPosteriors[i]).Attributes["ConditionedPosteriors"] = state;
                conditionedPosteriors[missingConditionedPosteriors[i]] = probs;
            }

            stateData.Tags["32858c9d-0247-497f-aeee-03f7bfe24158"] = preparedStates;
            stateData.Tags["32858c9d-0247-497f-aeee-03f7bfe24158/states"] = (from el in states select el.ToArray()).ToArray();
            tree.Attributes["32858c9d-0247-497f-aeee-03f7bfe24158"] = "Stochastic map";
        }

19 Source : Parse_node_states.cs
with GNU Affero General Public License v3.0
from arklumpus

private static void BuildPreviewTable(NumericUpDown rowCountNud, List<object[]> attributes, int matchColumn, string[] attributeNames, ScrollViewer scroller)
        {
            int previewRows = Math.Min((int)rowCountNud.Value, attributes.Count);

            Grid previewGrid = new Grid();
            previewGrid.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));

            int columnCount = (from el in attributes select el.Length).Max();

            for (int i = 0; i < columnCount; i++)
            {
                previewGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star) { MinWidth = 150 });
            }

            if (matchColumn == 1 && attributeNames.Length < columnCount)
            {
                {
                    TextBlock blk = new TextBlock()
                    {
                        FontWeight = Avalonia.Media.FontWeight.Bold,
                        FontStyle = Avalonia.Media.FontStyle.Italic,
                        Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(128, 128, 128)),
                        Text = "[match column]",
                        Margin = new Thickness(5),
                        TextWrapping = Avalonia.Media.TextWrapping.Wrap,
                        VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center
                    };
                    previewGrid.Children.Add(blk);
                }

                for (int i = 0; i < attributeNames.Length; i++)
                {
                    TextBlock blk = new TextBlock() { FontWeight = Avalonia.Media.FontWeight.Bold, Text = attributeNames[i], Margin = new Thickness(5), TextWrapping = Avalonia.Media.TextWrapping.Wrap, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    Grid.SetColumn(blk, i + 1);
                    previewGrid.Children.Add(blk);
                }
            }
            else
            {
                for (int i = 0; i < Math.Min(attributeNames.Length, columnCount); i++)
                {
                    TextBlock blk;

                    if (i != matchColumn - 1)
                    {
                        blk = new TextBlock() { FontWeight = Avalonia.Media.FontWeight.Bold, Text = attributeNames[i], Margin = new Thickness(5), TextWrapping = Avalonia.Media.TextWrapping.Wrap, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    }
                    else
                    {
                        blk = new TextBlock() { FontWeight = Avalonia.Media.FontWeight.Bold, FontStyle = Avalonia.Media.FontStyle.Italic, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(128, 128, 128)), Text = attributeNames[i] + " [match column]", Margin = new Thickness(5), TextWrapping = Avalonia.Media.TextWrapping.Wrap, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    }

                    Grid.SetColumn(blk, i);
                    previewGrid.Children.Add(blk);
                }
            }

            previewGrid.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Pixel));

            {
                Canvas canvas = new Canvas() { Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(0, 0, 0)), Height = 1 };
                Grid.SetRow(canvas, 1);
                Grid.SetColumnSpan(canvas, columnCount);
                previewGrid.Children.Add(canvas);
            }

            for (int i = 0; i < previewRows; i++)
            {
                previewGrid.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));


                {
                    Canvas canvas = new Canvas() { Background = Avalonia.Media.Brushes.Transparent, ZIndex = -100 };
                    Grid.SetRow(canvas, i + 2);
                    Grid.SetColumnSpan(canvas, columnCount);

                    canvas.PointerEnter += (s, e) =>
                    {
                        canvas.Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(220, 220, 220));
                    };

                    canvas.PointerLeave += (s, e) =>
                    {
                        canvas.Background = Avalonia.Media.Brushes.Transparent;
                    };

                    previewGrid.Children.Add(canvas);
                }

                for (int j = 0; j < attributes[i].Length; j++)
                {
                    string stringValue;
                    bool isString;

                    if (attributes[i][j] is string strVal)
                    {
                        stringValue = strVal;
                        isString = true;
                    }
                    else if (attributes[i][j] is double dblVal)
                    {
                        stringValue = dblVal.ToString(System.Globalization.CultureInfo.InvariantCulture);
                        isString = false;
                    }
                    else
                    {
                        continue;
                    }

                    TextBlock blk;

                    if (j != matchColumn - 1)
                    {
                        blk = new TextBlock() { Text = stringValue, Margin = new Thickness(5), TextWrapping = Avalonia.Media.TextWrapping.Wrap, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, IreplacedTestVisible = false };

                        if (isString)
                        {
                            blk.Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(0, 78, 138));
                        }
                        else
                        {
                            blk.Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(166, 55, 0));
                        }
                    }
                    else
                    {
                        blk = new TextBlock() { FontStyle = Avalonia.Media.FontStyle.Italic, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(128, 128, 128)), Text = stringValue, Margin = new Thickness(5), TextWrapping = Avalonia.Media.TextWrapping.Wrap, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, IreplacedTestVisible = false };
                    }

                    if (j >= attributeNames.Length + 1 || (matchColumn != 1 && j >= attributeNames.Length))
                    {
                        blk.FontStyle = Avalonia.Media.FontStyle.Italic;
                        blk.Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(128, 128, 128));
                    }

                    Grid.SetColumn(blk, j);
                    Grid.SetRow(blk, i + 2);
                    previewGrid.Children.Add(blk);
                }
            }

            scroller.Content = previewGrid;
        }

19 Source : Set_up_stochastic_mapping.cs
with GNU Affero General Public License v3.0
from arklumpus

public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
        {
            TreeCollection trees = (TreeCollection)parameterValues["Trees"];
            InstanceStateData stateData = (InstanceStateData)parameterValues["StateData"];

            bool isClockLike = (bool)parameterValues["Treat trees as clock-like"];

            double resolution = (double)parameterValues["Resolution:"];
            int resolutionType = (int)parameterValues["Resolution unit:"];

            double actualResolution = resolution;

            switch (resolutionType)
            {
                case 0:
                    break;
                case 1:
                    actualResolution = resolution * tree.LongestDownstreamLength();
                    break;
                case 2:
                    break;
            }

            Dictionary<string, TreeNode> nodeCorresps = new Dictionary<string, TreeNode>();

            foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
            {
                nodeCorresps[node.GetLeafNames().OrderBy(a => a).Aggregate((a, b) => a + "," + b)] = node;
            }

            Dictionary<string, List<(double left, double right, SimmapBranchState[] states)>> branchStates = new Dictionary<string, List<(double, double, SimmapBranchState[])>>(nodeCorresps.Count);

            foreach (KeyValuePair<string, TreeNode> kvp in nodeCorresps)
            {
                branchStates.Add(kvp.Value.Id, new List<(double start, double end, SimmapBranchState[] states)>());
            }

            HashSet<string>[] states = null;

            int sampleIndex = 0;

            foreach (TreeNode sample in trees)
            {
                foreach (TreeNode node in sample.GetChildrenRecursiveLazy())
                {
                    SimmapBranchState[] nodeStates = null;

                    if (node.Attributes.TryGetValue("States", out object statesObj) && statesObj is string statesString)
                    {
                        try
                        {
                            nodeStates = System.Text.Json.JsonSerializer.Deserialize<SimmapBranchState[]>(statesString);
                        }
                        catch { }
                    }

                    if (nodeStates != null)
                    {
                        string leafString = node.GetLeafNames().OrderBy(a => a).Aggregate((a, b) => a + "," + b);

                        if (nodeCorresps.TryGetValue(leafString, out TreeNode corresp))
                        {
                            if (states == null)
                            {
                                states = new HashSet<string>[nodeStates[0].States.Length];
                                for (int i = 0; i < states.Length; i++)
                                {
                                    states[i] = new HashSet<string>();
                                }
                            }

                            for (int i = 0; i < nodeStates.Length; i++)
                            {
                                for (int j = 0; j < nodeStates[i].States.Length; j++)
                                {
                                    states[j].Add(nodeStates[i].States[j]);
                                }
                            }

                            double left;
                            double right;

                            if (!isClockLike)
                            {
                                right = node.UpstreamLength();
                                left = right - node.Length;
                            }
                            else
                            {
                                right = node.LongestDownstreamLength();
                                left = right + node.Length;
                            }

                            branchStates[corresp.Id].Add((left, right, nodeStates));
                        }
                    }
                }

                sampleIndex++;
                progressAction((double)sampleIndex / trees.Count * 0.5);
            }

            List<List<string>> allPossibleStates = GetAllPossibleStates(states);

            Dictionary<string, (double samplePosPerc, double[] stateProbs)[]> preparedStates = new Dictionary<string, (double, double[])[]>();

            Dictionary<string, double[]> conditionedPosteriors = new Dictionary<string, double[]>();
            Dictionary<string, double[]> meanPosteriors = new Dictionary<string, double[]>();

            int nodeIndex = 0;

            List<(string, List<int>)> NaNSamples = new List<(string, List<int>)>();
            List<string> missingConditionedPosteriors = new List<string>();

            foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
            {
                if (!double.IsNaN(node.Length) && node.Length > 0)
                {
                    double left;
                    double right;

                    if (!isClockLike)
                    {
                        right = node.UpstreamLength();
                        left = right - node.Length;
                    }
                    else
                    {
                        right = node.LongestDownstreamLength();
                        left = right + node.Length;
                    }

                    if (resolutionType == 2)
                    {
                        actualResolution = resolution * node.Length;
                    }

                    List<(double left, double right, SimmapBranchState[] states)> observedStates = branchStates[node.Id];

                    double[] meanPosterior = new double[allPossibleStates.Count];

                    for (int i = 0; i < observedStates.Count; i++)
                    {
                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            if (allPossibleStates[j].SequenceEqual(observedStates[i].states[0].States))
                            {
                                meanPosterior[j]++;
                                break;
                            }
                        }
                    }

                    if (observedStates.Count > 0)
                    {
                        for (int i = 0; i < meanPosterior.Length; i++)
                        {
                            meanPosterior[i] /= observedStates.Count;
                        }
                    }

                    {
                        string state = "{";

                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + meanPosterior[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                            if (j < allPossibleStates.Count - 1)
                            {
                                state += ",";
                            }
                        }

                        state += "}";

                        meanPosteriors[node.Id] = meanPosterior;
                        node.Attributes["MeanPosteriors"] = state;
                    }


                    List<(double samplePosPerc, double[] stateProbs)> preparedBranchStates = new List<(double samplePosPerc, double[] stateProbs)>();
                    List<int> NaNs = new List<int>();

                    for (int i = 0; i < Math.Ceiling(Math.Abs(right - left) / actualResolution) + 1; i++)
                    {
                        double samplingTime;
                        if (!isClockLike)
                        {
                            samplingTime = Math.Min(left + actualResolution * i, right);
                        }
                        else
                        {
                            samplingTime = Math.Max(left - actualResolution * i, right);
                        }

                        double perc = (samplingTime - left) / (right - left);



                        int[] counts = new int[allPossibleStates.Count];

                        for (int j = 0; j < observedStates.Count; j++)
                        {
                            string[] sample = SampleBranch(samplingTime, observedStates[j].left, observedStates[j].right, observedStates[j].states);

                            if (sample != null)
                            {
                                for (int k = 0; k < allPossibleStates.Count; k++)
                                {
                                    if (sample.SequenceEqual(allPossibleStates[k]))
                                    {
                                        counts[k]++;
                                        break;
                                    }
                                }
                            }
                        }

                        double total = counts.Sum();

                        double[] probs = new double[counts.Length];

                        if (total > 0)
                        {
                            for (int j = 0; j < probs.Length; j++)
                            {
                                probs[j] = counts[j] / total;
                            }
                        }
                        else
                        {
                            NaNs.Add(i);
                        }

                        preparedBranchStates.Add((perc, probs));

                        if (samplingTime == right)
                        {
                            if (total > 0)
                            {
                                string state = "{";

                                for (int j = 0; j < allPossibleStates.Count; j++)
                                {
                                    state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + probs[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                                    if (j < allPossibleStates.Count - 1)
                                    {
                                        state += ",";
                                    }
                                }

                                state += "}";

                                node.Attributes["ConditionedPosteriors"] = state;
                                conditionedPosteriors[node.Id] = probs;
                            }
                            else
                            {
                                missingConditionedPosteriors.Add(node.Id);
                            }

                            break;
                        }
                    }

                    if (NaNs.Count > 0)
                    {
                        NaNs.Sort();
                        NaNSamples.Add((node.Id, NaNs));
                    }

                    preparedStates[node.Id] = preparedBranchStates.ToArray();
                }
                else if (node.Parent == null && node.Children.Count > 0)
                {
                    List<(double left, double right, SimmapBranchState[] states)> observedStates = branchStates[node.Children[0].Id];

                    double[] meanPosterior = new double[allPossibleStates.Count];

                    for (int i = 0; i < observedStates.Count; i++)
                    {
                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            if (allPossibleStates[j].SequenceEqual(observedStates[i].states[observedStates[i].states.Length - 1].States))
                            {
                                meanPosterior[j]++;
                                break;
                            }
                        }
                    }

                    if (observedStates.Count > 0)
                    {
                        for (int i = 0; i < meanPosterior.Length; i++)
                        {
                            meanPosterior[i] /= observedStates.Count;
                        }
                    }

                    {
                        string state = "{";

                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + meanPosterior[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                            if (j < allPossibleStates.Count - 1)
                            {
                                state += ",";
                            }
                        }

                        state += "}";

                        node.Attributes["MeanPosteriors"] = state;
                        node.Attributes["ConditionedPosteriors"] = state;

                        conditionedPosteriors[node.Id] = meanPosterior;
                    }
                }

                nodeIndex++;
                progressAction(0.5 + (double)nodeIndex / nodeCorresps.Count * 0.5);
            }

            for (int i = 0; i < NaNSamples.Count; i++)
            {
                (double samplePosPerc, double[] stateProbs)[] samples = preparedStates[NaNSamples[i].Item1];
                TreeNode node = tree.GetNodeFromId(NaNSamples[i].Item1);

                if (NaNSamples[i].Item2.Count == samples.Length)
                {
                    if (missingConditionedPosteriors.Contains(node.Id))
                    {
                        conditionedPosteriors[node.Id] = meanPosteriors[node.Id];
                    }

                    for (int j = 0; j < samples.Length; j++)
                    {
                        samples[j] = (samples[j].samplePosPerc, conditionedPosteriors[node.Id]);
                    }
                }
                else
                {
                    List<int> missingSamplesStart = new List<int>();
                    List<int> missingSamplesEnd = new List<int>();

                    for (int j = 0; j < NaNSamples[i].Item2.Count; j++)
                    {
                        if (NaNSamples[i].Item2[j] == j)
                        {
                            missingSamplesStart.Add(NaNSamples[i].Item2[j]);
                        }

                        if (NaNSamples[i].Item2[NaNSamples[i].Item2.Count - 1 - j] == samples.Length - 1 - j)
                        {
                            missingSamplesEnd.Add(NaNSamples[i].Item2[NaNSamples[i].Item2.Count - 1 - j]);
                        }
                    }

                    if (missingSamplesStart.Count > 0)
                    {
                        double[] left = null;
                        double[] right = null;

                        // Parent
                        if (!missingConditionedPosteriors.Contains(node.Parent.Id))
                        {
                            left = conditionedPosteriors[node.Parent.Id];
                        }
                        else
                        {
                            (double samplePosPerc, double[] stateProbs)[] parentSamples = preparedStates[node.Parent.Id];

                            for (int j = parentSamples.Length - 1; j >= 0; j--)
                            {
                                if (parentSamples[j].stateProbs.Sum() > 0)
                                {
                                    left = parentSamples[j].stateProbs;
                                    break;
                                }
                            }
                        }

                        // First sample
                        for (int j = 0; j < samples.Length; j++)
                        {
                            if (samples[j].stateProbs.Sum() > 0)
                            {
                                right = samples[j].stateProbs;
                                break;
                            }
                        }

                        if (left != null && right != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                double[] average = new double[left.Length];

                                for (int k = 0; k < left.Length; k++)
                                {
                                    average[k] = left[k] * (1 - (double)(j + 1) / (missingSamplesStart.Count + 1)) + right[k] * (double)(j + 1) / (missingSamplesStart.Count + 1);
                                }

                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, average);
                            }
                        }
                        else if (right != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, right);
                            }
                        }
                        else if (left != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, left);
                            }
                        }
                    }


                    if (missingSamplesEnd.Count > 0)
                    {
                        double[] left = null;
                        List<double[]> right = new List<double[]>();

                        // Children
                        for (int k = 0; k < node.Children.Count; k++)
                        {
                            if (!missingConditionedPosteriors.Contains(node.Children[k].Id))
                            {
                                right.Add(conditionedPosteriors[node.Children[k].Id]);
                            }
                            else
                            {
                                (double samplePosPerc, double[] stateProbs)[] childSamples = preparedStates[node.Children[k].Id];

                                for (int j = 0; j < childSamples.Length; j++)
                                {
                                    if (childSamples[j].stateProbs.Sum() > 0)
                                    {
                                        right.Add(childSamples[j].stateProbs);
                                        break;
                                    }
                                }
                            }
                        }

                        // Last sample
                        for (int j = samples.Length - 1; j >= 0; j--)
                        {
                            if (samples[j].stateProbs.Sum() > 0)
                            {
                                left = samples[j].stateProbs;
                                break;
                            }
                        }

                        if (left != null && right.Count > 0)
                        {
                            double[] rightAverage = new double[right[0].Length];

                            for (int j = 0; j < right.Count; j++)
                            {
                                for (int k = 0; k < rightAverage.Length; k++)
                                {
                                    rightAverage[k] += right[j][k];
                                }
                            }

                            for (int k = 0; k < rightAverage.Length; k++)
                            {
                                rightAverage[k] /= right.Count;
                            }

                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                double[] average = new double[left.Length];

                                for (int k = 0; k < left.Length; k++)
                                {
                                    average[k] = rightAverage[k] * (1 - (double)(j + 1) / (missingSamplesEnd.Count + 1)) + left[k] * (double)(j + 1) / (missingSamplesEnd.Count + 1);
                                }

                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, average);
                            }
                        }
                        else if (right.Count > 0)
                        {
                            double[] rightAverage = new double[right[0].Length];

                            for (int j = 0; j < right.Count; j++)
                            {
                                for (int k = 0; k < rightAverage.Length; k++)
                                {
                                    rightAverage[k] += right[j][k];
                                }
                            }

                            for (int k = 0; k < rightAverage.Length; k++)
                            {
                                rightAverage[k] /= right.Count;
                            }

                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, rightAverage);
                            }
                        }
                        else if (left != null)
                        {
                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, left);
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < missingConditionedPosteriors.Count; i++)
            {
                double[] probs = preparedStates[missingConditionedPosteriors[i]].Last().stateProbs;

                string state = "{";

                for (int j = 0; j < allPossibleStates.Count; j++)
                {
                    state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + probs[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                    if (j < allPossibleStates.Count - 1)
                    {
                        state += ",";
                    }
                }

                state += "}";

                tree.GetNodeFromId(missingConditionedPosteriors[i]).Attributes["ConditionedPosteriors"] = state;
                conditionedPosteriors[missingConditionedPosteriors[i]] = probs;
            }

            stateData.Tags["32858c9d-0247-497f-aeee-03f7bfe24158"] = preparedStates;
            stateData.Tags["32858c9d-0247-497f-aeee-03f7bfe24158/states"] = (from el in states select el.ToArray()).ToArray();
            tree.Attributes["32858c9d-0247-497f-aeee-03f7bfe24158"] = "Stochastic map";
        }

19 Source : SelectionLogic.cs
with GNU Affero General Public License v3.0
from arklumpus

private async void CopySelectionButtonClicked(object sender, Avalonia.Interactivity.RoutedEventArgs e)
        {
            if (this.SelectedNode != null)
            {
                List<TreeNode> selectedTips = this.SelectedNode.GetLeaves();

                Window attributeSelectionWindow = new Window() { FontFamily = this.FontFamily, FontSize = this.FontSize, Icon = this.Icon, Width = 300, Height = 180, replacedle = "Select attribute...", WindowStartupLocation = WindowStartupLocation.CenterOwner }; ;

                Grid grd = new Grid() { Margin = new Avalonia.Thickness(10) };
                attributeSelectionWindow.Content = grd;

                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                grd.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                grd.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));

                {
                    TextBlock blk = new TextBlock() { Text = selectedTips.Count + " tips selected.", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                    grd.Children.Add(blk);
                }

                {
                    TextBlock blk = new TextBlock() { Text = "Select attribute to copy:", FontWeight = Avalonia.Media.FontWeight.Bold, FontSize = 15, Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                    Grid.SetRow(blk, 1);
                    grd.Children.Add(blk);
                }

                Grid buttonGrid = new Grid();

                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                buttonGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                Button okButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = "OK" };
                Grid.SetColumn(okButton, 1);
                buttonGrid.Children.Add(okButton);

                Button cancelButton = new Button() { HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Width = 100, Content = "Cancel" };
                Grid.SetColumn(cancelButton, 3);
                buttonGrid.Children.Add(cancelButton);

                Grid.SetRow(buttonGrid, 5);
                grd.Children.Add(buttonGrid);

                bool result = false;

                okButton.Click += (s, e) =>
                {
                    result = true;
                    attributeSelectionWindow.Close();
                };

                cancelButton.Click += (s, e) =>
                {
                    attributeSelectionWindow.Close();
                };

                HashSet<string> attributes = new HashSet<string>();

                foreach (TreeNode node in selectedTips)
                {
                    foreach (KeyValuePair<string, object> attribute in node.Attributes)
                    {
                        attributes.Add(attribute.Key);
                    }
                }

                List<string> attributesList = attributes.ToList();

                ComboBox attributeBox = new ComboBox() { Items = attributesList, SelectedIndex = Math.Max(attributesList.IndexOf("Name"), 0), Margin = new Avalonia.Thickness(0, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center };
                Grid.SetRow(attributeBox, 3);
                grd.Children.Add(attributeBox);


                await attributeSelectionWindow.ShowDialog2(this);

                if (result)
                {
                    string attributeName = attributesList[attributeBox.SelectedIndex];

                    List<string> attributeValues = new List<string>();

                    if (attributeName != null)
                    {
                        foreach (TreeNode node in selectedTips)
                        {
                            if (node.Attributes.TryGetValue(attributeName, out object attributeValue))
                            {
                                if (attributeValue is string attributeString)
                                {
                                    attributeValues.Add(attributeString);
                                }
                                else if (attributeValue is double attributeDouble)
                                {
                                    attributeValues.Add(attributeDouble.ToString(System.Globalization.CultureInfo.InvariantCulture));
                                }
                            }
                        }
                    }

                    if (attributeValues.Count > 0)
                    {
                        _ = Avalonia.Application.Current.Clipboard.SetTextAsync(attributeValues.Aggregate((a, b) => a + "\n" + b));
                    }
                }
            }
        }

19 Source : PriceExtensions.cs
with MIT License
from armutcom

public static string ToPrice(this double price)
        {
            return price.ToString(PriceCulture);
        }

19 Source : Telescope Base Class.cs
with GNU General Public License v3.0
from ASCOMInitiative

public void SlewToAltAz(double Azimuth, double Alreplacedude)
        {
            RemoteClientDriver.SetClientTimeout(client, longServerResponseTimeout);
            Dictionary<string, string> Parameters = new Dictionary<string, string>
            {
                { SharedConstants.AZ_PARAMETER_NAME, Azimuth.ToString(CultureInfo.InvariantCulture) },
                { SharedConstants.ALT_PARAMETER_NAME, Alreplacedude.ToString(CultureInfo.InvariantCulture) }
            };
            RemoteClientDriver.SendToRemoteDriver<NoReturnValue>(clientNumber, client, URIBase, TL, "SlewToAltAz", Parameters, Method.PUT);
        }

19 Source : Telescope Base Class.cs
with GNU General Public License v3.0
from ASCOMInitiative

public void SlewToCoordinates(double RightAscension, double Declination)
        {
            RemoteClientDriver.SetClientTimeout(client, longServerResponseTimeout);
            Dictionary<string, string> Parameters = new Dictionary<string, string>
            {
                { SharedConstants.RA_PARAMETER_NAME, RightAscension.ToString(CultureInfo.InvariantCulture) },
                { SharedConstants.DEC_PARAMETER_NAME, Declination.ToString(CultureInfo.InvariantCulture) }
            };
            RemoteClientDriver.SendToRemoteDriver<NoReturnValue>(clientNumber, client, URIBase, TL, "SlewToCoordinates", Parameters, Method.PUT);
        }

19 Source : Telescope Base Class.cs
with GNU General Public License v3.0
from ASCOMInitiative

public void SlewToAltAzAsync(double Azimuth, double Alreplacedude)
        {
            RemoteClientDriver.SetClientTimeout(client, longServerResponseTimeout);
            Dictionary<string, string> Parameters = new Dictionary<string, string>
            {
                { SharedConstants.AZ_PARAMETER_NAME, Azimuth.ToString(CultureInfo.InvariantCulture) },
                { SharedConstants.ALT_PARAMETER_NAME, Alreplacedude.ToString(CultureInfo.InvariantCulture) }
            };
            RemoteClientDriver.SendToRemoteDriver<NoReturnValue>(clientNumber, client, URIBase, TL, "SlewToAltAzAsync", Parameters, Method.PUT);
        }

19 Source : Camera Base Class.cs
with GNU General Public License v3.0
from ASCOMInitiative

public void StartExposure(double Duration, bool Light)
        {
            Dictionary<string, string> Parameters = new Dictionary<string, string>
            {
                { SharedConstants.DURATION_PARAMETER_NAME, Duration.ToString(CultureInfo.InvariantCulture) },
                { SharedConstants.LIGHT_PARAMETER_NAME, Light.ToString() }
            };
            RemoteClientDriver.SendToRemoteDriver<NoReturnValue>(clientNumber, client, URIBase, TL, "StartExposure", Parameters, Method.PUT);
        }

19 Source : Dome Base Class.cs
with GNU General Public License v3.0
from ASCOMInitiative

public void SlewToAlreplacedude(double Alreplacedude)
        {
            Dictionary<string, string> Parameters = new Dictionary<string, string>
            {
                { SharedConstants.ALT_PARAMETER_NAME, Alreplacedude.ToString(CultureInfo.InvariantCulture) }
            };
            RemoteClientDriver.SendToRemoteDriver<NoReturnValue>(clientNumber, client, URIBase, TL, "SlewToAlreplacedude", Parameters, Method.PUT);
        }

19 Source : Dome Base Class.cs
with GNU General Public License v3.0
from ASCOMInitiative

public void SlewToAzimuth(double Azimuth)
        {
            Dictionary<string, string> Parameters = new Dictionary<string, string>
            {
                { SharedConstants.AZ_PARAMETER_NAME, Azimuth.ToString(CultureInfo.InvariantCulture) }
            };
            RemoteClientDriver.SendToRemoteDriver<NoReturnValue>(clientNumber, client, URIBase, TL, "SlewToAzimuth", Parameters, Method.PUT);
        }

19 Source : Dome Base Class.cs
with GNU General Public License v3.0
from ASCOMInitiative

public void SyncToAzimuth(double Azimuth)
        {
            Dictionary<string, string> Parameters = new Dictionary<string, string>
            {
                { SharedConstants.AZ_PARAMETER_NAME, Azimuth.ToString(CultureInfo.InvariantCulture) }
            };
            RemoteClientDriver.SendToRemoteDriver<NoReturnValue>(clientNumber, client, URIBase, TL, "SyncToAzimuth", Parameters, Method.PUT);
        }

19 Source : Telescope Base Class.cs
with GNU General Public License v3.0
from ASCOMInitiative

public PierSide DestinationSideOfPier(double RightAscension, double Declination)
        {
            RemoteClientDriver.SetClientTimeout(client, standardServerResponseTimeout);
            Dictionary<string, string> Parameters = new Dictionary<string, string>
            {
                { SharedConstants.RA_PARAMETER_NAME, RightAscension.ToString(CultureInfo.InvariantCulture) },
                { SharedConstants.DEC_PARAMETER_NAME, Declination.ToString(CultureInfo.InvariantCulture) }
            };
            return RemoteClientDriver.SendToRemoteDriver<PierSide>(clientNumber, client, URIBase, TL, "DestinationSideOfPier", Parameters, Method.GET);
        }

19 Source : Telescope Base Class.cs
with GNU General Public License v3.0
from ASCOMInitiative

public void MoveAxis(TelescopeAxes Axis, double Rate)
        {
            RemoteClientDriver.SetClientTimeout(client, longServerResponseTimeout);
            Dictionary<string, string> Parameters = new Dictionary<string, string>
            {
                { SharedConstants.AXIS_PARAMETER_NAME, ((int)Axis).ToString(CultureInfo.InvariantCulture) },
                { SharedConstants.RATE_PARAMETER_NAME, Rate.ToString(CultureInfo.InvariantCulture) }
            };
            RemoteClientDriver.SendToRemoteDriver<NoReturnValue>(clientNumber, client, URIBase, TL, "MoveAxis", Parameters, Method.PUT);
        }

19 Source : Telescope Base Class.cs
with GNU General Public License v3.0
from ASCOMInitiative

public void SlewToCoordinatesAsync(double RightAscension, double Declination)
        {
            RemoteClientDriver.SetClientTimeout(client, longServerResponseTimeout);
            Dictionary<string, string> Parameters = new Dictionary<string, string>
            {
                { SharedConstants.RA_PARAMETER_NAME, RightAscension.ToString(CultureInfo.InvariantCulture) },
                { SharedConstants.DEC_PARAMETER_NAME, Declination.ToString(CultureInfo.InvariantCulture) }
            };
            RemoteClientDriver.SendToRemoteDriver<NoReturnValue>(clientNumber, client, URIBase, TL, "SlewToCoordinatesAsync", Parameters, Method.PUT);
        }

19 Source : Telescope Base Class.cs
with GNU General Public License v3.0
from ASCOMInitiative

public void SyncToAltAz(double Azimuth, double Alreplacedude)
        {
            RemoteClientDriver.SetClientTimeout(client, standardServerResponseTimeout);
            Dictionary<string, string> Parameters = new Dictionary<string, string>
            {
                { SharedConstants.AZ_PARAMETER_NAME, Azimuth.ToString(CultureInfo.InvariantCulture) },
                { SharedConstants.ALT_PARAMETER_NAME, Alreplacedude.ToString(CultureInfo.InvariantCulture) }
            };
            RemoteClientDriver.SendToRemoteDriver<NoReturnValue>(clientNumber, client, URIBase, TL, "SyncToAltAz", Parameters, Method.PUT);
        }

19 Source : Telescope Base Class.cs
with GNU General Public License v3.0
from ASCOMInitiative

public void SyncToCoordinates(double RightAscension, double Declination)
        {
            RemoteClientDriver.SetClientTimeout(client, standardServerResponseTimeout);
            Dictionary<string, string> Parameters = new Dictionary<string, string>
            {
                { SharedConstants.RA_PARAMETER_NAME, RightAscension.ToString(CultureInfo.InvariantCulture) },
                { SharedConstants.DEC_PARAMETER_NAME, Declination.ToString(CultureInfo.InvariantCulture) }
            };
            RemoteClientDriver.SendToRemoteDriver<NoReturnValue>(clientNumber, client, URIBase, TL, "SyncToCoordinates", Parameters, Method.PUT);
        }

19 Source : AddressesViewModel.cs
with GNU General Public License v3.0
from atomex-me

private void DesignerMode()
        {
            _currency = DesignTime.Currencies.First();

            Addresses = new ObservableCollection<AddressInfo>(new List<AddressInfo>
            {
                new AddressInfo
                {
                    Address = "mzztP8VVJYxV93EUiiYrJUbL55MLx7KLoM",
                    Path    = "m/44'/0'/0'/0/0",
                    Balance = 4.0000000.ToString(CultureInfo.InvariantCulture),
                },
                new AddressInfo
                {
                    Address = "mzztP8VVJYxV93EUiiYrJUbL55MLx7KLoM",
                    Path    = "m/44'/0'/0'/0/0",
                    Balance = 100.ToString(CultureInfo.InvariantCulture),
                },
                new AddressInfo
                {
                    Address = "mzztP8VVJYxV93EUiiYrJUbL55MLx7KLoM",
                    Path    = "m/44'/0'/0'/0/0",
                    Balance = 16.0000001.ToString(CultureInfo.InvariantCulture),
                }
            });
        }

19 Source : UpdateHandler.cs
with GNU General Public License v3.0
from AutoDarkMode

private static void DownloadProgress(object sender, (float, long, long) progress)
        {
            int percent = (int)progress.Item1;
            long totalBytes = progress.Item2;
            long receivedBytes = progress.Item3;

            if (percent > Progress)
            {
                if (percent % 10 == 0)
                {
                    string mbReceived = (receivedBytes / 1000000).ToString();
                    string mbTotal = (totalBytes / 1000000).ToString();
                    nfi.NumberDecimalSeparator = ".";
                    Progress = percent;
                    string progressString = (Progress / 100d).ToString(nfi);
                    Logger.Info($"downloaded {mbReceived} of {mbTotal} MB. {Progress} % complete");
                    try
                    {
                        ToastHandler.UpdateProgressToast(progressString, $"{mbReceived} / {mbTotal} MB");
                    }
                    catch (Exception ex)
                    {
                        Logger.Warn(ex, "toast updater died, please tell the devs to add the toast updater to the ActionQueue:");
                    }
                }
            }
        }

19 Source : Degree.cs
with MIT License
from Autodesk

public string ToString(IFormatProvider fp)
        {
            return Value.ToString(fp);
        }

19 Source : Degree.Test.cs
with MIT License
from Autodesk

[Test]
        public void ToStringTest()
        {
            Degree angle = new Degree(1.23);

            replacedert.AreEqual(angle.ToString(), 1.23.ToString());

            replacedert.AreEqual(angle.ToString("N3"), 1.23.ToString("N3"));

            System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("de-DE");
            replacedert.AreEqual(angle.ToString(culture), 1.23.ToString(culture));

            replacedert.AreEqual(angle.ToString("N3", culture), 1.23.ToString("N3", culture));
        }

19 Source : Radian.Test.cs
with MIT License
from Autodesk

[Test]
        public void ToStringTest()
        {
            Radian angle = new Radian(1.23);

            replacedert.AreEqual(angle.ToString(), 1.23.ToString());

            replacedert.AreEqual(angle.ToString("N3"), 1.23.ToString("N3"));

            System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("de-DE");
            replacedert.AreEqual(angle.ToString(culture), 1.23.ToString(culture));

            replacedert.AreEqual(angle.ToString("N3", culture), 1.23.ToString("N3", culture));
        }

19 Source : Extensions.cs
with The Unlicense
from BAndysc

internal static string ToSql(this object? o)
        {
            if (o is null)
                return "NULL";
            if (o is string s)
                return s.ToSqlEscapeString();
            if (o is float f)
                return f.ToString(CultureInfo.InvariantCulture);
            if (o is double d)
                return d.ToString(CultureInfo.InvariantCulture);
            if (o is bool b)
                return b ? "1" : "0";
            return o.ToString() ?? "[INVALID TYPE]";
        }

19 Source : NFlagsGenericConfigurationTest.cs
with MIT License
from bartoszgolek

[Fact]
        public void RegisterCommand_ShouldPreplacedArgumentsToValuesToExecute_EvenIfConfigurationValuesAreSet()
        {
            var testEnvironment = new TestGenericConfig()
                .SetConfigValue("NFLAG_TEST_OPTION1", 3)
                .SetConfigValue("NFLAG_TEST_OPTION2", "xyz")
                .SetConfigValue("NFLAG_TEST_PARAMETER1", 2.53)
                .SetConfigValue("NFLAG_TEST_PARAMETER2", 5);

            CommandArgs a = null;
            Cli
                .Configure(c => c
                    .SetDialect(Dialect.Gnu)
                    .SetConfiguration(testEnvironment)
                )
                .Root(c => c
                    .RegisterCommand("sub", "sub command ", rc => rc
                        .RegisterOption<int>(b => b.Name("option1").Description("option desc").DefaultValue(1).ConfigPath("NFLAG_TEST_OPTION1"))
                        .RegisterOption<string>(b => b.Name("option2").Abr("o2").Description("option2 desc").DefaultValue("asd").ConfigPath("NFLAG_TEST_OPTION2"))
                        .RegisterParameter<double>(b => b.Name("parameter1").Description("parameter desc").DefaultValue(1.1).ConfigPath("NFLAG_TEST_PARAMETER1"))
                        .RegisterParameter<int>(b => b.Name("parameter2").Description("parameter2 desc").DefaultValue(1).ConfigPath("NFLAG_TEST_PARAMETER2"))
                        .SetExecute((args, output) =>
                        {
                            a = args;
                        }))
                    .SetExecute((type, output) => { })
                )
                .Run(new[]
                {
                    "sub",
                    "--option1",
                    "30",
                    "-o2",
                    "cxyz",
                    20.53.ToString(CultureInfo.CurrentCulture),
                    "50"
                });

            replacedert.Equal(30, a.GetOption<int>("option1"));
            replacedert.Equal("cxyz", a.GetOption<string>("option2"));
            replacedert.Equal(20.53, a.GetParameter<double>("parameter1"));
            replacedert.Equal(50, a.GetParameter<int>("parameter2"));
        }

19 Source : NFlagsRegisterWithConfigValues.cs
with MIT License
from bartoszgolek

[Fact]
        public void RegisterCommand_ShouldPreplacedArgumentsToValuesToExecute_EvenIfConfigurationValuesAreSet()
        {
            var testEnvironment = new TestConfig()
                .SetConfigValue("NFLAG_TEST_OPTION1", "3")
                .SetConfigValue("NFLAG_TEST_OPTION2", "xyz")
                .SetConfigValue("NFLAG_TEST_PARAMETER1", 2.53.ToString(CultureInfo.CurrentCulture))
                .SetConfigValue("NFLAG_TEST_PARAMETER2", "5");

            CommandArgs a = null;
            Cli
                .Configure(c => c
                    .SetDialect(Dialect.Gnu)
                    .SetConfiguration(testEnvironment)
                )
                .Root(c => c
                    .RegisterCommand("sub", "sub command ", rc => rc
                        .RegisterOption<int>(b => b.Name("option1").Description("option desc").DefaultValue(1).ConfigPath("NFLAG_TEST_OPTION1"))
                        .RegisterOption<string>(b => b.Name("option2").Abr("o2").Description("option2 desc").DefaultValue("asd").ConfigPath("NFLAG_TEST_OPTION2"))
                        .RegisterParameter<double>(b => b.Name("parameter1").Description("parameter desc").DefaultValue(1.1).ConfigPath("NFLAG_TEST_PARAMETER1"))
                        .RegisterParameter<int>(b => b.Name("parameter2").Description("parameter2 desc").DefaultValue(1).ConfigPath("NFLAG_TEST_PARAMETER2"))
                        .SetExecute((args, output) =>
                        {
                            a = args;
                        }))
                    .SetExecute((type, output) => { })
                )
                .Run(new[]
                {
                    "sub",
                    "--option1",
                    "30",
                    "-o2",
                    "cxyz",
                    20.53.ToString(CultureInfo.CurrentCulture),
                    "50"
                });

            replacedert.Equal(30, a.GetOption<int>("option1"));
            replacedert.Equal("cxyz", a.GetOption<string>("option2"));
            replacedert.Equal(20.53, a.GetParameter<double>("parameter1"));
            replacedert.Equal(50, a.GetParameter<int>("parameter2"));
        }

19 Source : NFlagsRegisterWithBuilder.cs
with MIT License
from bartoszgolek

[Fact]
        public void RegisterCommandT_ShouldPreplacedValuesToExecute()
        {
            CommandArgs a = null;
            Cli
                .Configure(c => c
                    .SetDialect(Dialect.Gnu)
                )
                .Root(c => c
                    .RegisterCommand("sub", "sub command ", rc => rc
                        .RegisterOption<int>(b => b.Name("option1").Description("option desc").DefaultValue(1))
                        .RegisterOption<string>(b => b.Name("option2").Abr("o2").Description("option2 desc").DefaultValue("asd"))
                        .RegisterFlag(b => b.Name("flag1").Description("flag desc").DefaultValue(true))
                        .RegisterFlag(b => b.Name("flag2").Abr("f2").Description("flag2 desc"))
                        .RegisterParameter<double>(b => b.Name("parameter1").Description("parameter desc").DefaultValue(1.1))
                        .RegisterParameter<int>(b => b.Name("parameter2").Description("parameter2 desc").DefaultValue(1))
                        .RegisterParameterSeries<int>(b => b.Name("parameterSeries").Description("parameter series desc"))
                        .SetExecute((args, output) =>
                        {
                            a = args;
                        }))
                    .SetExecute((type, output) => { })
                )
                .Run(new[]
                {
                    "sub",
                    "--flag1",
                    "-f2",
                    "--option1",
                    "3",
                    "-o2",
                    "xyz",
                    2.53.ToString(CultureInfo.CurrentCulture),
                    "5",
                    "6",
                    "7"
                });

            replacedert.Equal(3, a.GetOption<int>("option1"));
            replacedert.Equal("xyz", a.GetOption<string>("option2"));
            replacedert.False(a.GetFlag("flag1"));
            replacedert.True(a.GetFlag("flag2"));
            replacedert.Equal(2.53, a.GetParameter<double>("parameter1"));
            replacedert.Equal(5, a.GetParameter<int>("parameter2"));
            replacedert.Equal(new[] {6, 7}, a.GetParameterSeries<int>().ToArray());
        }

19 Source : NFlagsRegisterWithEnvironmentVariables.cs
with MIT License
from bartoszgolek

[Fact]
        public void RegisterCommand_ShouldPreplacedArgumentsToValuesToExecute_EvenIfEnvironmentVariablesAreSet()
        {
            var testEnvironment = new TestEnvironment()
                .SetEnvironmentVariable("NFLAG_TEST_OPTION1", "3")
                .SetEnvironmentVariable("NFLAG_TEST_OPTION2", "xyz")
                .SetEnvironmentVariable("NFLAG_TEST_PARAMETER1", 2.53.ToString(CultureInfo.CurrentCulture))
                .SetEnvironmentVariable("NFLAG_TEST_PARAMETER2", "5");

            CommandArgs a = null;
            Cli
                .Configure(c => c
                    .SetDialect(Dialect.Gnu)
                    .SetEnvironment(testEnvironment)
                )
                .Root(c => c
                    .RegisterCommand("sub", "sub command ", rc => rc
                        .RegisterOption<int>(b => b.Name("option1").Description("option desc").DefaultValue(1).EnvironmentVariable("NFLAG_TEST_OPTION1"))
                        .RegisterOption<string>(b => b.Name("option2").Abr("o2").Description("option2 desc").DefaultValue("asd").EnvironmentVariable("NFLAG_TEST_OPTION2"))
                        .RegisterParameter<double>(b => b.Name("parameter1").Description("parameter desc").DefaultValue(1.1).EnvironmentVariable("NFLAG_TEST_PARAMETER1"))
                        .RegisterParameter<int>(b => b.Name("parameter2").Description("parameter2 desc").DefaultValue(1).EnvironmentVariable("NFLAG_TEST_PARAMETER2"))
                        .SetExecute((args, output) =>
                        {
                            a = args;
                        }))
                    .SetExecute((type, output) => { })
                )
                .Run(new[]
                {
                    "sub",
                    "--option1",
                    "30",
                    "-o2",
                    "cxyz",
                    20.53.ToString(CultureInfo.CurrentCulture),
                    "50"
                });

            replacedert.Equal(30, a.GetOption<int>("option1"));
            replacedert.Equal("cxyz", a.GetOption<string>("option2"));
            replacedert.Equal(20.53, a.GetParameter<double>("parameter1"));
            replacedert.Equal(50, a.GetParameter<int>("parameter2"));
        }

19 Source : NFlagsRegisterCommandGenericTest.cs
with MIT License
from bartoszgolek

[Fact]
        public void RegisterCommandT_ShouldPreplacedValuesToExecute()
        {
            ArgumentsType a = null;
            Cli
                .Configure(c => c
                    .SetDialect(Dialect.Gnu)
                )
                .Root<ArgumentsType>(c => c
                    .RegisterCommand<ArgumentsType>("sub", "sub command ", rc => rc
                        .SetExecute((args, output) =>
                        {
                            a = args;
                        }))
                    .SetExecute((type, output) => { })
                )
                .Run(new[]
                {
                    "sub",
                    "--flag1",
                    "-f2",
                    "--option1",
                    "3",
                    "-o2",
                    "xyz",
                    2.53.ToString(CultureInfo.CurrentCulture),
                    "5",
                    "6",
                    "7"
                });

            replacedert.Equal(3, a.Option1);
            replacedert.Equal("xyz", a.Option2);
            replacedert.False(a.Flag1);
            replacedert.True(a.Flag2);
            replacedert.Equal(2.53, a.Parameter1);
            replacedert.Equal(5, a.Parameter2);
            replacedert.Equal(new[] {6, 7}, a.ParameterSeries);
        }

19 Source : NFlagsRootGenericTest.cs
with MIT License
from bartoszgolek

[Fact]
        public void RegisterCommandT_ShouldPreplacedValuesToExecute()
        {
            ArgumentsType a = null;
            Cli
                .Configure(c => c
                    .SetDialect(Dialect.Gnu)
                )
                .Root<ArgumentsType>(c => c
                    .SetExecute((args, output) =>
                    {
                        a = args;
                    })
                )
                .Run(new[]
                {
                    "--flag1",
                    "-f2",
                    "--option1",
                    "3",
                    "-o2",
                    "xyz",
                    2.53.ToString(CultureInfo.CurrentCulture),
                    "5",
                    "6",
                    "7"
                });

            replacedert.Equal(3, a.Option1);
            replacedert.Equal("xyz", a.Option2);
            replacedert.False(a.Flag1);
            replacedert.True(a.Flag2);
            replacedert.Equal(2.53, a.Parameter1);
            replacedert.Equal(5, a.Parameter2);
            replacedert.Equal(new[] {6, 7}, a.ParameterSeries);
        }

19 Source : NFlagsRegisterWithConfigValues.cs
with MIT License
from bartoszgolek

[Fact]
        public void RegisterCommand_ShouldPreplacedConfigurationValuesToValuesToExecute()
        {
            var testConfig = new TestConfig()
                .SetConfigValue("NFLAG_TEST_FLAG1", "false")
                .SetConfigValue("NFLAG_TEST_FLAG2", "true")
                .SetConfigValue("NFLAG_TEST_OPTION1", "3")
                .SetConfigValue("NFLAG_TEST_OPTION2", "xyz")
                .SetConfigValue("NFLAG_TEST_PARAMETER1", 2.53.ToString(CultureInfo.CurrentCulture))
                .SetConfigValue("NFLAG_TEST_PARAMETER2", "5");

            CommandArgs a = null;
            Cli
                .Configure(c => c
                    .SetDialect(Dialect.Gnu)
                    .SetConfiguration(testConfig)
                )
                .Root(c => c
                    .RegisterCommand("sub", "sub command ", rc => rc
                        .RegisterOption<int>(b => b.Name("option1").Description("option desc").DefaultValue(1).ConfigPath("NFLAG_TEST_OPTION1"))
                        .RegisterOption<string>(b => b.Name("option2").Abr("o2").Description("option2 desc").DefaultValue("asd").ConfigPath("NFLAG_TEST_OPTION2"))
                        .RegisterFlag(b => b.Name("flag1").Description("flag desc").DefaultValue(true).ConfigPath("NFLAG_TEST_FLAG1"))
                        .RegisterFlag(b => b.Name("flag2").Abr("f2").Description("flag2 desc").ConfigPath("NFLAG_TEST_FLAG2"))
                        .RegisterParameter<double>(b => b.Name("parameter1").Description("parameter desc").DefaultValue(1.1).ConfigPath("NFLAG_TEST_PARAMETER1"))
                        .RegisterParameter<int>(b => b.Name("parameter2").Description("parameter2 desc").DefaultValue(1).ConfigPath("NFLAG_TEST_PARAMETER2"))
                        .SetExecute((args, output) =>
                        {
                            a = args;
                        }))
                    .SetExecute((type, output) => { })
                )
                .Run(new[] { "sub" });

            replacedert.Equal(3, a.GetOption<int>("option1"));
            replacedert.Equal("xyz", a.GetOption<string>("option2"));
            replacedert.False(a.GetFlag("flag1"));
            replacedert.True(a.GetFlag("flag2"));
            replacedert.Equal(2.53, a.GetParameter<double>("parameter1"));
            replacedert.Equal(5, a.GetParameter<int>("parameter2"));
        }

19 Source : NFlagsRegisterWithEnvironmentVariables.cs
with MIT License
from bartoszgolek

[Fact]
        public void RegisterCommand_ShouldPreplacedEnvironmentVariablesToValuesToExecute()
        {
            var testEnvironment = new TestEnvironment()
                .SetEnvironmentVariable("NFLAG_TEST_FLAG1", "false")
                .SetEnvironmentVariable("NFLAG_TEST_FLAG2", "true")
                .SetEnvironmentVariable("NFLAG_TEST_OPTION1", "3")
                .SetEnvironmentVariable("NFLAG_TEST_OPTION2", "xyz")
                .SetEnvironmentVariable("NFLAG_TEST_PARAMETER1", 2.53.ToString(CultureInfo.CurrentCulture))
                .SetEnvironmentVariable("NFLAG_TEST_PARAMETER2", "5");

            CommandArgs a = null;
            Cli
                .Configure(c => c
                    .SetDialect(Dialect.Gnu)
                    .SetEnvironment(testEnvironment)
                )
                .Root(c => c
                    .RegisterCommand("sub", "sub command ", rc => rc
                        .RegisterOption<int>(b => b.Name("option1").Description("option desc").DefaultValue(1).EnvironmentVariable("NFLAG_TEST_OPTION1"))
                        .RegisterOption<string>(b => b.Name("option2").Abr("o2").Description("option2 desc").DefaultValue("asd").EnvironmentVariable("NFLAG_TEST_OPTION2"))
                        .RegisterFlag(b => b.Name("flag1").Description("flag desc").DefaultValue(true).EnvironmentVariable("NFLAG_TEST_FLAG1"))
                        .RegisterFlag(b => b.Name("flag2").Abr("f2").Description("flag2 desc").EnvironmentVariable("NFLAG_TEST_FLAG2"))
                        .RegisterParameter<double>(b => b.Name("parameter1").Description("parameter desc").DefaultValue(1.1).EnvironmentVariable("NFLAG_TEST_PARAMETER1"))
                        .RegisterParameter<int>(b => b.Name("parameter2").Description("parameter2 desc").DefaultValue(1).EnvironmentVariable("NFLAG_TEST_PARAMETER2"))
                        .SetExecute((args, output) =>
                        {
                            a = args;
                        }))
                    .SetExecute((type, output) => { })
                )
                .Run(new[] { "sub" });

            replacedert.Equal(3, a.GetOption<int>("option1"));
            replacedert.Equal("xyz", a.GetOption<string>("option2"));
            replacedert.False(a.GetFlag("flag1"));
            replacedert.True(a.GetFlag("flag2"));
            replacedert.Equal(2.53, a.GetParameter<double>("parameter1"));
            replacedert.Equal(5, a.GetParameter<int>("parameter2"));
        }

19 Source : NumericUpDown.cs
with Apache License 2.0
from beckzhu

private string FormattedValue(double? newValue, string format, CultureInfo culture)
        {
            format = format.Replace("{}", string.Empty);
            if (!string.IsNullOrWhiteSpace(format))
            {
                var match = RegexStringFormatHexadecimal.Match(format);
                if (match.Success)
                {
                    if (match.Groups["simpleHEX"].Success)
                    {
                        // HEX DOES SUPPORT INT ONLY.
                        return ((int)newValue.Value).ToString(match.Groups["simpleHEX"].Value, culture);
                    }
                    if (match.Groups["complexHEX"].Success)
                    {
                        return string.Format(culture, match.Groups["complexHEX"].Value, (int)newValue.Value);
                    }
                }
                else
                {
                    if (!format.Contains("{"))
                    {
                        // then we may have a StringFormat of e.g. "N0"
                        return newValue.Value.ToString(format, culture);
                    }
                    return string.Format(culture, format, newValue.Value);
                }
            }

            return newValue.Value.ToString(culture);
        }

19 Source : InfoModule.cs
with GNU Affero General Public License v3.0
from berichan

private static string GetHeapSize() => Math.Round(GC.GetTotalMemory(true) / (1024.0 * 1024.0), 2).ToString(CultureInfo.CurrentCulture);

19 Source : NumberExtensions.cs
with MIT License
from Blazor-Diagrams

public static string ToInvariantString(this double n) => n.ToString(CultureInfo.InvariantCulture);

19 Source : Slider.cs
with MIT License
from bonsai-rx

private void UpdateValue(double value)
        {
            if (decimalPlaces.HasValue) value = Math.Round(value, decimalPlaces.Value);
            value = Math.Max(minimum, Math.Min(value, maximum));
            if (Converter != null) valueLabel.Text = Converter.ConvertToInvariantString(value);
            else valueLabel.Text = value.ToString(CultureInfo.InvariantCulture);
            this.value = value;
        }

See More Examples